Repository navigation
Expand file tree
/
Copy pathfunction_utils.cc
More file actions
368 lines (331 loc) · 12 KB
/
Copy pathfunction_utils.cc
File metadata and controls
368 lines (331 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/common_runtime/function_utils.h"
#include "tensorflow/core/common_runtime/function_body.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/op_def.pb.h"
#include "tensorflow/core/framework/versions.pb.h"
#include "tensorflow/core/graph/algorithm.h"
#include "tensorflow/core/graph/control_flow.h"
#include "tensorflow/core/graph/graph.h"
namespace tensorflow {
static constexpr const char* const kNodeLabel = "Func";
// Represents the index-th output of a node.
struct Endpoint {
Node* node;
int index;
// Returns the string name represents this endpoint.
string name() const {
if (index == 0) {
return node->name();
} else {
return strings::StrCat(node->name(), ":", index);
}
}
DataType dtype() const { return node->output_type(index); }
};
// The following Add* routines are used to add a few graph nodes while
// functions are transformed.
static Node* AddNoOp(StringPiece name, Graph* g) {
NodeDef ndef;
ndef.set_name(g->NewName(absl::StrCat(kNodeLabel, "/", name)));
ndef.set_op("NoOp");
Status s;
Node* ret = g->AddNode(ndef, &s);
TF_CHECK_OK(s);
return ret;
}
static Node* AddIdentity(StringPiece name, Graph* g, Endpoint input) {
DCHECK_LT(0, input.dtype());
NodeDef ndef;
ndef.set_name(g->NewName(absl::StrCat(kNodeLabel, "/", name)));
ndef.set_op("Identity");
ndef.add_input(input.name());
AddNodeAttr("T", BaseType(input.dtype()), &ndef);
Status s;
Node* ret = g->AddNode(ndef, &s);
TF_CHECK_OK(s);
g->AddEdge(input.node, input.index, ret, 0);
return ret;
}
void DumpGraph(StringPiece label, const Graph* g) {
// TODO(zhifengc): Change Graph to record #nodes.
VLOG(2) << "Graph " << label << " #nodes " << g->num_nodes() << " #edges "
<< g->num_edges();
if (VLOG_IS_ON(5)) {
for (const auto& line : str_util::Split(DebugString(g), '\n')) {
VLOG(5) << "|| " << line;
}
}
}
bool RemoveDeadNodes(Graph* g) {
VLOG(2) << "Removing dead nodes";
std::unordered_set<const Node*> nodes;
for (auto n : g->nodes()) {
if (n->IsSource() || n->IsSink() || n->IsControlFlow() ||
n->op_def().is_stateful()) {
nodes.insert(n);
}
}
return PruneForReverseReachability(g, std::move(nodes));
}
namespace {
// If 'edges' contains only 1 non-control edge, returns it. Otherwise,
// returns a nullptr.
const Edge* GetTheOnlyDataEdge(const EdgeSet& edges) {
const Edge* ret = nullptr;
for (const Edge* e : edges) {
if (e->IsControlEdge() || ret) {
// Don't touch it if there is a control edge.
return nullptr;
}
if (IsRefType(e->src()->output_type(e->src_output()))) {
// Don't touch it if the identity node is effectively de-reffing
// a ref.
return nullptr;
}
if (IsRecv(e->src()) || IsSwitch(e->src())) {
// Don't touch it if the identity is introduced for control flow.
// Recv disables all its successors if it receives a dead signal.
// When Recv has an outgoing control edge, the current executor
// would not disable the destination. The current solution (see
// graph_partition.cc) is to add an identity after Recv and change
// the control edge to be from this identity node. So the identity
// can't be removed.
return nullptr;
}
ret = e;
}
return ret;
}
} // end namespace
bool RemoveIdentityNodes(Graph* g) {
VLOG(2) << "Removing identity nodes";
bool removed_any = false;
gtl::InlinedVector<Node*, 8> matches;
for (Node* n : g->nodes()) {
if (!n->IsIdentity()) continue;
if (!GetTheOnlyDataEdge(n->in_edges())) continue;
// Some identity nodes are used as sink nodes to give names to output
// tensors. These nodes are not going to be executed unless they are in the
// fetch set. But if they are in the fetch set we don't want to remove them.
if (n->out_edges().empty()) continue;
matches.push_back(n);
}
if (!matches.empty()) {
for (Node* n : matches) {
const Edge* in = GetTheOnlyDataEdge(n->in_edges());
for (const Edge* out : n->out_edges()) {
if (out->IsControlEdge()) {
g->AddControlEdge(in->src(), out->dst());
} else {
g->AddEdge(in->src(), in->src_output(), out->dst(), out->dst_input());
}
}
VLOG(2) << "Remove Identity: " << n->DebugString();
g->RemoveNode(n);
removed_any = true;
}
}
return removed_any;
}
bool RemoveListArrayConverter(Graph* g) {
VLOG(2) << "Removing list array converter";
gtl::InlinedVector<Node*, 8> matches;
for (Node* n : g->nodes()) {
if ((n->type_string() == "_ListToArray") ||
(n->type_string() == "_ArrayToList")) {
matches.push_back(n);
}
}
bool removed_any = false;
if (!matches.empty()) {
for (Node* n : matches) {
if (n->num_inputs() != n->num_outputs()) {
continue; // Not expected. Skip.
}
gtl::InlinedVector<Node*, 8> identity_nodes(n->num_inputs(), nullptr);
const auto no_op = [&](StringPiece name) -> Node* {
return AddNoOp(absl::StrCat(n->name(), "/", name), g);
};
const auto identity = [&](StringPiece name, Endpoint input) -> Node* {
Node* node = AddIdentity(absl::StrCat(n->name(), "/", name), g, input);
node->set_requested_device(input.node->def().device());
return node;
};
// Process input edges first.
Node* input_control_node = nullptr;
for (const Edge* e : n->in_edges()) {
if (e->IsControlEdge()) {
if (input_control_node == nullptr) {
// If node "n" has any control dependencies, adds a no-op
// node (input_control_node) which the additional Identity
// nodes depends on and the input_control_node depends on
// the node "n"s control dependencies.
input_control_node = no_op("input_control_node");
}
g->AddControlEdge(e->src(), input_control_node);
} else {
const int index = e->dst_input();
Node** id_node = &identity_nodes[index];
if (*id_node != nullptr) {
LOG(ERROR)
<< "RemoveListArrayConverter unexpected duplicated input: "
<< e->dst_input();
return removed_any;
}
*id_node = identity("input", {e->src(), e->src_output()});
}
}
// If node "n" has any control dependencies, the added identity
// nodes should have control dependencies on input_control_node.
if (input_control_node != nullptr) {
for (Node* id : identity_nodes) {
g->AddControlEdge(input_control_node, id);
}
}
Node* output_control_node = nullptr;
for (const Edge* e : n->out_edges()) {
if (e->IsControlEdge()) {
if (output_control_node == nullptr) {
// If node "n" is control-depended upon by other nodes,
// adds a no-op node (output_control_node) which those
// nodes will depend on and output_control_node depends on
// all Identity nodes.
output_control_node = no_op("output_control_node");
}
g->AddControlEdge(output_control_node, e->dst());
} else {
Node* id_node = identity_nodes[e->src_output()];
if (id_node == nullptr) {
LOG(ERROR) << "RemoveListArrayConverter unexpected missing input: "
<< e->src_output();
return removed_any;
}
CHECK(id_node);
g->AddEdge(id_node, 0, e->dst(), e->dst_input());
}
}
// If any nodes have control dependencies on node "n", those
// nodes should have control dependencies on
// output_control_node.
if (output_control_node != nullptr) {
for (Node* id : identity_nodes) {
g->AddControlEdge(id, output_control_node);
}
}
g->RemoveNode(n);
removed_any = true;
}
}
return removed_any;
}
Status NameAndAttrsFromFunctionCall(const NodeDef& call_def,
NameAttrList* function) {
if (call_def.op() == "PartitionedCall" ||
call_def.op() == "StatefulPartitionedCall") {
TF_RETURN_IF_ERROR(GetNodeAttr(call_def, "f", function));
} else {
function->set_name(call_def.op());
*function->mutable_attr() = call_def.attr();
}
return Status::OK();
}
Status InstantiateFunctionCall(const NodeDef& call_def,
FunctionLibraryRuntime* flr,
FunctionLibraryRuntime::Handle* handle) {
NameAttrList function;
TF_RETURN_IF_ERROR(NameAndAttrsFromFunctionCall(call_def, &function));
return flr->Instantiate(function.name(), AttrSlice(&function.attr()), handle);
}
bool IsFunctionCall(const FunctionLibraryDefinition& lib_def,
const Node& node) {
return node.IsFunctionCall();
}
string NewName(const Node* n, bool pretty) {
if (pretty) {
return strings::StrCat(n->type_string(), n->id());
} else {
return strings::StrCat("n", n->id());
}
}
// TODO(zhifengc): Maybe this should be the default Graph::AsGraphDef.
// and stash the original NodeDef name as an attr for documentation
// purpose.
void ToGraphDef(const Graph* g, GraphDef* gdef, bool pretty) {
// We visit nodes in forward topological sort order, which is a
// possible execution order of the graph.
gtl::InlinedVector<const Edge*, 4> inputs;
gdef->Clear();
*gdef->mutable_versions() = g->versions();
std::vector<Node*> start_nodes;
for (Node* n : g->nodes()) {
if (n->out_edges().empty()) {
start_nodes.push_back(n);
}
}
ReverseDFSFrom(*g, start_nodes, nullptr, [gdef, pretty, &inputs](Node* n) {
if (!n->IsOp()) return;
NodeDef* ndef = gdef->add_node();
ndef->set_name(NewName(n, pretty));
ndef->set_op(n->type_string());
for (const auto& attr : n->attrs()) {
(*ndef->mutable_attr())[attr.first] = attr.second;
}
if (!n->assigned_device_name().empty()) {
ndef->set_device(n->assigned_device_name());
} else {
ndef->set_device(n->requested_device());
}
inputs.clear();
inputs.resize(n->num_inputs());
for (const Edge* e : n->in_edges()) {
if (e->IsControlEdge()) {
inputs.push_back(e);
} else {
if (inputs[e->dst_input()] == nullptr) {
inputs[e->dst_input()] = e;
} else {
LOG(WARNING) << "Malformed graph node. multiple input edges: "
<< n->DebugString();
}
}
}
// node->name() is merely NodeDef::name, which are not guaranteed
// to be unique and stable after optimization rewrites. Therefore,
// we use "n<node id>" instead.
for (const Edge* e : inputs) {
if (e == nullptr) {
ndef->add_input("unknown");
continue;
}
const string srcname = NewName(e->src(), pretty);
if (!e->src()->IsOp()) {
} else if (e->IsControlEdge()) {
ndef->add_input(strings::StrCat("^", srcname));
} else if (e->src_output() == 0) {
ndef->add_input(srcname);
} else {
ndef->add_input(strings::StrCat(srcname, ":", e->src_output()));
}
}
});
}
string DebugString(const Graph* g) {
GraphDef gdef;
ToGraphDef(g, &gdef);
return DebugString(gdef);
}
} // end namespace tensorflow