-
Notifications
You must be signed in to change notification settings - Fork 427
/
graph.py
1385 lines (1169 loc) · 52.3 KB
/
graph.py
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
"""
tf2onnx.graph - class to manage graph manipulation on top of onnx
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import collections
import copy
import logging
import six
import numpy as np
from onnx import helper, numpy_helper, shape_inference, OperatorSetIdProto, AttributeProto, TensorProto
from tf2onnx import utils, __version__
from tf2onnx.utils import make_name, port_name, find_opset
from tf2onnx import optimizer
from tf2onnx.schemas import get_schema, infer_onnx_shape_dtype
from tf2onnx import constants
logger = logging.getLogger(__name__)
# todo(pengwa): remove protected-access later
# pylint: disable=broad-except,protected-access
class Node(object):
"""A Node - wrapper around onnx nodes that we use for graph manipulations."""
def __init__(self, node, graph, skip_conversion=False):
"""Create Node.
Args:
node: Onnx node in NodeProto
graph: Graph() we are part of
"""
self._op = node
self.graph = graph
self._input = list(node.input)
self._output = list(node.output)
self._attr = {}
graph.set_node_by_name(self)
# dict to original attributes
for a in node.attribute:
self._attr[a.name] = a
self._skip_conversion = skip_conversion
@property
def input(self):
return self._input
@property
def output(self):
return copy.deepcopy(self._output)
@output.setter
def output(self, val):
"""Set op output. Output should be updated explicitly,
changing it would require output mapping changed.
"""
self._graph_check()
for o in self._output:
del self.graph._output_to_node_name[o]
self._output = val
for o in self._output:
utils.make_sure(o not in self.graph._output_to_node_name, "output %s already in output mapping", o)
self.graph._output_to_node_name[o] = self.name
@property
def inputs(self):
"""Input node objects."""
self._graph_check()
val = [self.graph.get_node_by_output(n) for n in self._input]
return val
@property
def attr(self):
return self._attr
@property
def attr_onnx(self):
"""Return onnx valid attributes"""
schema = get_schema(self.type, self.graph.opset, self.domain)
if schema is None and not (self.is_const() or self.is_graph_input()):
logger.debug("Node %s uses non-stardard onnx op <%s, %s>, skip attribute check",
self.name, self.domain, self.type)
onnx_attrs = {}
for a in self._attr.values():
if schema is None or schema.has_attribute(a.name):
onnx_attrs[a.name] = a
return onnx_attrs
@property
def name(self):
return self._op.name
@property
def op(self):
"""TODO: have a better interface for this."""
return self._op
@property
def type(self):
"""Return Op type."""
return self._op.op_type
@type.setter
def type(self, val):
"""Set Op type."""
self._op.op_type = val
@property
def domain(self):
"""Return Op type."""
return self._op.domain
@domain.setter
def domain(self, val):
"""Set Op type."""
self._op.domain = val
@property
def data_format(self):
"""Return data_format."""
return self.get_attr_str("data_format")
@data_format.setter
def data_format(self, val):
"""Set data_format."""
self.set_attr("data_format", val)
def is_nhwc(self):
"""Return True if node is in NHWC format."""
return self.data_format == "NHWC"
def is_const(self):
"""Return True if node is a constant."""
return self.type in ["Const", "ConstV2"]
def is_graph_input(self):
return self.type in ["Placeholder", "PlaceholderWithDefault", "PlaceholderV2"]
def is_graph_input_default_const(self):
return self.is_const() and any(
out.is_graph_input() for out in self.graph.find_output_consumers(self.output[0])
)
def __str__(self):
return str(self._op)
def __repr__(self):
return "<onnx op type='%s' name=%s>" % (self.type, self._op.name)
@property
def summary(self):
"""Return node summary information."""
lines = []
lines.append("OP={}".format(self.type))
lines.append("Name={}".format(self.name))
g = self.graph
if self.input:
lines.append("Inputs:")
for name in self.input:
node = g.get_node_by_output(name)
op = node.type if node else "N/A"
lines.append("\t{}={}, {}, {}".format(name, op, g.get_shape(name), g.get_dtype(name)))
if self.output:
for name in self.output:
lines.append("Outpus:")
lines.append("\t{}={}, {}".format(name, g.get_shape(name), g.get_dtype(name)))
return '\n'.join(lines)
def get_attr(self, name, default=None):
"""Get raw attribute value."""
attr = self.attr.get(name, default)
return attr
def get_attr_value(self, name, default=None):
attr = self.get_attr(name)
if attr:
return helper.get_attribute_value(attr)
return default
def get_attr_int(self, name):
"""Get attribute value as int."""
attr_int = self.get_attr_value(name)
utils.make_sure(
attr_int is not None and isinstance(attr_int, int),
"attribute %s is None", name
)
return attr_int
def get_attr_str(self, name, encoding="utf-8"):
"""Get attribute value as string."""
attr_str = self.get_attr_value(name)
utils.make_sure(
attr_str is not None and isinstance(attr_str, bytes),
"attribute %s is None", name
)
return attr_str.decode(encoding)
def set_attr(self, name, value):
self.attr[name] = helper.make_attribute(name, value)
def set_attr_onnx(self, value):
self.attr[value.name] = value
@property
def skip_conversion(self):
return self._skip_conversion
@skip_conversion.setter
def skip_conversion(self, val):
self._skip_conversion = val
# If some Node is created as onnx_node, then we don't need convert it
def need_skip(self):
return self._skip_conversion
@property
def output_shapes(self):
"""Get output shapes."""
self._graph_check()
val = [self.graph.get_shape(n) for n in self._output]
return val
@property
def output_dtypes(self):
"""Get output dtypes."""
self._graph_check()
val = [self.graph.get_dtype(n) for n in self._output]
return val
def get_tensor_value(self, as_list=True):
"""Get value for onnx tensor.
Args:
as_list: whether return numpy ndarray in list.
Returns:
If as_list=True, return the array as a (possibly nested) list.
Otherwise, return data of type np.ndarray.
If a tensor is a scalar having value 1,
when as_list=False, return np.array(1), type is <class 'numpy.ndarray'>
when as_list=True, return 1, type is <class 'int'>.
"""
if not self.is_const():
raise ValueError("get tensor value: {} must be Const".format(self.name))
t = self.get_attr("value")
if t:
t = numpy_helper.to_array(helper.get_attribute_value(t))
if as_list is True:
t = t.tolist() # t might be scalar after tolist()
return t
def scalar_to_dim1(self):
"""Get value for onnx tensor."""
if not self.is_const():
raise ValueError("get tensor value: {} must be Const".format(self.name))
t = self.get_attr("value")
if t:
t = helper.get_attribute_value(t)
if not t.dims:
t.dims.extend([1])
return t.dims
def set_tensor_value(self, new_val):
"""Set new value for existing onnx tensor.
Args:
new_val: value of type numpy ndarray
"""
if not self.is_const():
raise ValueError("set tensor value: {} must be Const".format(self.name))
t = self.get_attr("value")
if not t:
raise ValueError("set tensor value: {} is None".format(self.name))
t = helper.get_attribute_value(t)
onnx_tensor = numpy_helper.from_array(new_val, t.name)
del t
self.set_attr("value", onnx_tensor)
# track shapes in _output_shapes
self._graph_check()
self.graph.set_shape(onnx_tensor.name, onnx_tensor.dims)
def get_body_graphs(self):
self._graph_check()
return self.graph.contained_graphs.get(self.name, None)
def set_body_graph_as_attr(self, attr_name, graph):
self._graph_check()
if self.name not in self.graph.contained_graphs:
self.graph.contained_graphs[self.name] = {}
self.graph.contained_graphs[self.name].update({attr_name: graph})
graph.parent_graph = self.graph
def update_proto(self):
"""Update protobuf from internal structure."""
nodes = list(self._op.input)
for node in nodes:
self._op.input.remove(node)
self._op.input.extend(self.input)
nodes = list(self._op.output)
for node in nodes:
self._op.output.remove(node)
self._op.output.extend(self.output)
# update attributes to proto
del self._op.attribute[:]
# check attribute of type GraphProto
attr_graphs = self.get_body_graphs()
if attr_graphs:
for attr_name, sub_graph in attr_graphs.items():
graph_proto = sub_graph.make_graph("graph for " + self.name + " " + attr_name)
self.set_attr(attr_name, graph_proto)
attr = list(self.attr_onnx.values())
if attr:
self._op.attribute.extend(attr)
def get_implicit_inputs(self, recursive=True):
"""Get implicit inputs if the node has attributes being GraphProto."""
output_available_in_cur_graph = set()
all_node_inputs = set()
graphs = []
body_graphs = self.get_body_graphs()
if body_graphs:
graphs.extend(body_graphs.values())
while graphs:
graph = graphs.pop()
for n in graph.get_nodes():
output_available_in_cur_graph |= set(n.output)
for i in n.input:
all_node_inputs.add(i)
if recursive:
b_graphs = n.get_body_graphs()
if b_graphs:
graphs.extend(b_graphs.values())
outer_scope_node_input_ids = all_node_inputs - output_available_in_cur_graph
return list(outer_scope_node_input_ids)
def _graph_check(self):
utils.make_sure(self.graph is not None, "Node %s not belonging any graph",
self.name)
class Graph(object):
""""Class that provides graph manipulation and matching."""
def __init__(self, nodes, output_shapes=None, dtypes=None, target=None, opset=None, extra_opset=None,
output_names=None):
"""Create Graph.
Args:
nodes: list of Node()
output_shapes: dict of tensorflow output shapes
dtypes: dict of tensorflow dtype
"""
if target is None:
target = []
self._nodes = []
self._nodes_by_name = {}
self._output_to_node_name = {}
self.shapes = {}
self._target = set(target)
self._dtypes = dtypes
self._output_shapes = output_shapes
self._opset = find_opset(opset)
if extra_opset is not None:
utils.make_sure(isinstance(extra_opset, list), "invalid extra_opset")
self._extra_opset = extra_opset
self._order_sensitive_inputs = []
self.outputs = output_names if output_names is not None else []
self.parent_graph = None
self.contained_graphs = {} # {node_name: {node_attribute_name: Graph}}
ops = [Node(node, self) for node in nodes]
self.reset_nodes(ops)
# add identity node after each output, in case it is renamed during conversion.
for o in self.outputs:
n = self.get_node_by_output_in_current_graph(o)
new_output_name = port_name(n.name + "_" + utils.make_name("raw_output_"))
n_shapes = n.output_shapes
n_dtypes = n.output_dtypes
body_graphs = n.graph.contained_graphs.pop(n.name, None)
self.remove_node(n.name)
new_outputs = [output if output != o else new_output_name for output in n.output]
# domain should be passed to new node
new_node = self.make_node(n.type, n.input, outputs=new_outputs, attr=n.attr, name=n.name,
skip_conversion=n._skip_conversion, dtypes=n_dtypes, shapes=n_shapes,
domain=n.domain)
if body_graphs:
for attr_name, body_graph in body_graphs.items():
body_graph.parent_graph = self
new_node.set_body_graph_as_attr(attr_name, body_graph)
self.replace_all_inputs(self.get_nodes(), o, new_output_name)
self.make_node("Identity", [new_output_name], outputs=[o], op_name_scope=n.name + "_" + "graph_outputs")
self.copy_shape(new_output_name, o)
self.copy_dtype(new_output_name, o)
def create_new_graph_with_same_config(self):
"""Create a clean graph inheriting current graph's configuration."""
return Graph([], output_shapes={}, dtypes={}, target=self._target, opset=self._opset,
extra_opset=self.extra_opset, output_names=[])
@property
def opset(self):
return self._opset
@property
def extra_opset(self):
return self._extra_opset
def is_target(self, *names):
"""Return True if target platform contains any name."""
return any(name in self._target for name in names)
def make_const(self, name, np_val, skip_conversion=False, raw=True):
"""Make a new constant in the graph.
Args:
name: const node name, must be unique.
np_val: value of type numpy ndarray.
skip_conversion: bool, indicate whether this created node would be mapped during conversion.
raw: whether to store data at field of raw_data or the specific field according to its dtype
"""
if raw:
onnx_tensor = numpy_helper.from_array(np_val, name)
else:
onnx_tensor = helper.make_tensor(name, utils.map_numpy_to_onnx_dtype(np_val.dtype),
np_val.shape, np_val, raw=False)
dtype = onnx_tensor.data_type
node = self.make_node("Const", [], outputs=[name], name=name, attr={"value": onnx_tensor},
skip_conversion=skip_conversion, dtypes=[dtype], infer_shape_dtype=False)
self.set_shape(name, np_val.shape)
self.set_dtype(name, utils.map_numpy_to_onnx_dtype(np_val.dtype))
return node
def make_node(self, op_type, inputs, attr=None, output_count=1, outputs=None, skip_conversion=True,
op_name_scope=None, name=None, shapes=None, dtypes=None, domain=constants.ONNX_DOMAIN,
infer_shape_dtype=True):
"""Make a new onnx node in the graph"""
if attr is None:
attr = {}
if shapes is None:
shapes = []
if dtypes is None:
dtypes = []
if name is None:
name = utils.make_name(op_type)
if op_name_scope:
name = "_".join([op_name_scope, name])
logger.debug("Making node: Name=%s, OP=%s", name, op_type)
if outputs is None:
outputs = [name + ":" + str(i) for i in range(output_count)]
output_count = len(outputs)
raw_attr = {}
onnx_attrs = []
for a, v in attr.items():
if isinstance(v, AttributeProto):
onnx_attrs.append(v)
else:
raw_attr[a] = v
n = self.get_node_by_name(name)
utils.make_sure(n is None, "name %s already exists in node: \n%s", name, n)
for o in outputs:
n = self.get_node_by_output_in_current_graph(o)
utils.make_sure(n is None, "output tensor named %s already exists in node: \n%s", o, n)
onnx_node = helper.make_node(op_type, inputs, outputs, name=name, domain=domain, **raw_attr)
if op_type in ["If", "Loop", "Scan"]:
# we force the op containing inner graphs not skipped during conversion.
skip_conversion = False
node = Node(onnx_node, self, skip_conversion=skip_conversion)
if onnx_attrs:
_ = [node.set_attr_onnx(a) for a in onnx_attrs]
if shapes:
utils.make_sure(len(shapes) == output_count,
"output shape count %s not equal to output count %s", len(shapes), output_count)
for i in range(output_count):
self.set_shape(node.output[i], shapes[i])
if dtypes:
utils.make_sure(len(dtypes) == output_count,
"output dtypes count %s not equal to output count %s", len(dtypes), output_count)
for i in range(output_count):
self.set_dtype(node.output[i], dtypes[i])
if (not shapes or not dtypes) and infer_shape_dtype:
self.update_node_shape_dtype(node, override=False)
logger.debug("Made node: %s\n%s", node.name, node.summary)
self._nodes.append(node)
return node
def remove_node(self, node_name):
"""Remove node in current graph."""
utils.make_sure(node_name in self._nodes_by_name, "node %s not in current graph, cannot remove", node_name)
node = self.get_node_by_name(node_name)
del self._nodes_by_name[node_name]
if node_name in self.contained_graphs:
del self.contained_graphs[node_name]
if node in self._order_sensitive_inputs:
self._order_sensitive_inputs.remove(node)
for op_output in node.output:
del self._output_to_node_name[op_output]
if op_output in self._output_shapes:
del self._output_shapes[op_output]
if op_output in self._dtypes:
del self._dtypes[op_output]
self._nodes.remove(node)
node.graph = None
def reset_nodes(self, ops):
"""Reset the graph with node list."""
remained_dtypes = {}
remained_shapes = {}
remained_sub_graphs = {}
for op in ops:
for op_output in op.output:
# this check should be removed once we make sure all output tensors have dtype/shape.
if op_output in self._dtypes:
remained_dtypes[op_output] = self._dtypes[op_output]
if op_output in self._output_shapes:
remained_shapes[op_output] = self._output_shapes[op_output]
if op.name in self.contained_graphs:
remained_sub_graphs[op.name] = self.contained_graphs[op.name]
self._nodes = ops
self.contained_graphs = remained_sub_graphs
self._nodes_by_name = {op.name: op for op in ops}
self._output_to_node_name = {}
for op in ops:
for op_output in op.output:
self._output_to_node_name[op_output] = op.name
for n in self._order_sensitive_inputs:
if n not in ops:
self._order_sensitive_inputs.remove(n)
for o in self.outputs:
if o not in self._output_to_node_name:
raise ValueError("graph output " + o + " not exist")
self._dtypes = remained_dtypes
self._output_shapes = remained_shapes
def is_empty_input(self, name):
# in ONNX, operation may have optional input and an empty string may be used
# in the place of an actual argument's name to indicate a missing argument
return name == utils.ONNX_EMPTY_INPUT
def check_integrity(self):
"""
Check graph integrity. Every node's input needs to associate with a node.
Return broken outputs.
"""
broken_outputs = set()
for node in self.get_nodes():
for inp in node.input:
if self.get_node_by_output(inp) is None and not self.is_empty_input(inp):
broken_outputs.add(inp)
return list(broken_outputs)
def update_node_shape_dtype(self, node, override=False):
"""Try the best to infer shapes and dtypes for outputs of the node,
by default, we respect TF shapes and dtypes.
"""
if node.is_const() or node.is_graph_input():
return
# NOTE: only support onnx node for now
if not utils.is_onnx_domain(node.domain):
return
logger.debug("Infer shape and dtype for [%s]", node.name)
# NOTE: shape inference for some ops need the input values of the op, e.g., Reshape
# op needs the "Shape" value to infer output shape.
initializers = []
for i, inp in enumerate(node.inputs):
if inp is None:
if not self.is_empty_input(node.input[i]):
if logger.isEnabledFor(logging.INFO):
logger.warning(
"[%s] infer a inexistent node: [%s], please check the code",
node.name, node.input[i]
)
continue
if inp.is_const():
t = inp.get_attr("value")
tensor = helper.get_attribute_value(t)
tensor.name = inp.output[0]
initializers.append(tensor)
input_shapes = [self.get_shape(i) for i in node.input]
input_dtypes = [self.get_dtype(i) for i in node.input]
shapes, dtypes = infer_onnx_shape_dtype(node, self._opset, input_shapes, input_dtypes, initializers)
if not shapes or not dtypes:
return
for output, shape, dtype in zip(node.output, shapes, dtypes):
if dtype == TensorProto.UNDEFINED:
logger.debug("Inferred dtype for [%s, type: %s] is UNDEFINED, SKIP", node.name, node.type)
else:
existing_dtype = self.get_dtype(output)
if existing_dtype is not None and existing_dtype != dtype:
if override:
logger.warning("Override dtype of %s from %s to %s", output, existing_dtype, dtype)
else:
dtype = existing_dtype
self.set_dtype(output, dtype)
logger.debug("Set dtype of [%s] to %s", output, dtype)
if shape is None:
logger.debug("Inferred shape for [%s, type: %s] is None, SKIP", node.name, node.type)
else:
existing_shape = self.get_shape(output)
if existing_shape is not None and not utils.are_shapes_equal(existing_shape, shape):
if override:
logger.warning("Override shape of %s from %s to %s", output, existing_shape, shape)
else:
shape = existing_shape
self.set_shape(output, shape)
logger.debug("Set shape of [%s] to %s", output, shape)
def update_proto(self):
"""Update the onnx protobuf from out internal Node structure."""
for node in self._nodes:
node.update_proto()
def get_nodes(self):
"""Get node list."""
return self._nodes
def get_node_by_output(self, output, search_in_parent_graphs=True):
"""Get node by node output id recursively going through nested graphs.
Args:
search_in_parent_graphs: search in all parent graphs
"""
ret = None
g = self
while not ret and g:
ret = g.get_node_by_output_in_current_graph(output)
if ret:
return ret
if not search_in_parent_graphs:
break
g = g.parent_graph
return ret
def get_node_by_output_in_current_graph(self, output):
"""Get node by node output id."""
name = self._output_to_node_name.get(output)
ret = None
if name:
ret = self._nodes_by_name.get(name)
return ret
def get_node_by_name(self, name):
"""Get node by name."""
ret = self._nodes_by_name.get(name)
return ret
def set_node_by_name(self, node):
"""Set node by name."""
self._nodes_by_name[node.name] = node
for op_output in node.output:
self._output_to_node_name[op_output] = node.name
def add_graph_input(self, name, dtype=None, shape=None):
"""Add placeholder node as graph's input. Order matters only for subgraph.
Placeholders in original graph are assumed for main graph, order not matters.
"""
if dtype is None:
dtype = self.get_dtype(name)
if shape is None:
shape = self.get_shape(name)
new_node = self.make_node("Placeholder", [], outputs=[name], dtypes=[dtype], shapes=[shape])
self._order_sensitive_inputs.append(new_node)
def add_graph_input_with_default(self, name, default_const, dtype=None, shape=None):
"""Add placeholderwithdefault."""
if dtype is None:
dtype = self.get_dtype(name)
if shape is None:
shape = self.get_shape(name)
default_const_name = port_name(make_name("{}_default".format(name)))
default_const.output = [default_const_name]
new_node = self.make_node("PlaceholderWithDefault", [default_const_name], outputs=[name],
dtypes=[dtype], shapes=[shape])
self._order_sensitive_inputs.append(new_node)
def add_graph_output(self, name, dtype=None, shape=None):
"""Add node output as graph's output."""
utils.make_sure(name in self._output_to_node_name, "output %s not exist in the graph", name)
if dtype is None:
dtype = self.get_dtype(name)
if shape is None:
shape = self.get_shape(name)
if name not in self.outputs:
utils.make_sure(shape is not None, "shape for output %s should not be None", name)
utils.make_sure(dtype is not None, "dtype for output %s should not be None", name)
self.outputs.append(name)
self.set_shape(name, shape)
self.set_dtype(name, dtype)
else:
raise ValueError("graph output " + name + " already exists")
def get_dtype(self, name):
"""Get dtype for node."""
node = self.get_node_by_output(name, search_in_parent_graphs=True)
return node.graph._dtypes.get(name) if node else None
def set_dtype(self, name, dtype):
"""Set dtype for node."""
node = self.get_node_by_output(name, search_in_parent_graphs=True)
node.graph._dtypes[name] = dtype
def copy_dtype(self, src_name, dst_name):
"""Copy dtype from another node."""
dtype = self.get_dtype(src_name)
self.set_dtype(dst_name, dtype)
def get_shape(self, name):
"""Get shape for node."""
utils.make_sure(isinstance(name, six.text_type), "get_shape name is invalid type: %s", name)
node = self.get_node_by_output(name, search_in_parent_graphs=True)
shape = node.graph._output_shapes.get(name) if node else None
if shape:
for i, v in enumerate(shape):
if v is None:
# pylint: disable=unsupported-assignment-operation
shape[i] = -1
# hack to allow utils.ONNX_UNKNOWN_DIMENSION to override batchsize if needed.
# default is -1.
if shape[0] == -1:
# pylint: disable=unsupported-assignment-operation
shape[0] = utils.ONNX_UNKNOWN_DIMENSION
return shape
return shape
def set_shape(self, name, val):
"""Set new shape of node."""
if isinstance(val, np.ndarray):
val = val.tolist()
if isinstance(val, tuple):
val = list(val)
node = self.get_node_by_output(name, search_in_parent_graphs=True)
utils.make_sure(node is not None, "cannot find node by output id %s", name)
node.graph._output_shapes[name] = val
def copy_shape(self, input_name, output_name):
"""Copy shape from another node."""
shape = self.get_shape(input_name)
# assert shape is not None
if shape is not None:
self.set_shape(output_name, shape)
def topological_sort(self, ops):
"""Topological sort of graph."""
# sort by name, the result will be reversed alphabeta
ops.sort(key=lambda op: op.name)
def _push_stack(stack, node, in_stack):
stack.append(node)
if node in in_stack:
raise ValueError('Graph has cycles.')
in_stack[node] = True
def _get_unvisited_child(g, node, not_visited):
for child in g[node]:
if child in not_visited:
return child
return -1
n = len(ops)
g = [[] for _ in range(n)]
op_name_to_index = {}
for i, op in enumerate(ops):
op_name_to_index[op.name] = i
for i, op in enumerate(ops):
all_input = set(op.input)
implicit_inputs = op.get_implicit_inputs()
all_input |= set(implicit_inputs)
# remove those empty inputs
all_input = list(filter(lambda a: a != '', all_input))
for inp in sorted(all_input):
j = self.get_node_by_output(inp)
utils.make_sure(j is not None, "Cannot find node with output {}".format(inp))
if self.parent_graph and j.name not in op_name_to_index:
# there might be some outer-scoped inputs for an inner Graph.
pass
else:
g[op_name_to_index[j.name]].append(i)
# label for each op. highest = sink nodes.
label = [-1 for _ in range(n)]
stack = []
in_stack = dict()
not_visited = dict.fromkeys(range(n))
label_counter = n - 1
while not_visited:
node = list(not_visited.keys())[0]
_push_stack(stack, node, in_stack)
while stack:
node = _get_unvisited_child(g, stack[-1], not_visited)
if node != -1:
_push_stack(stack, node, in_stack)
else:
node = stack.pop()
in_stack.pop(node)
not_visited.pop(node)
label[node] = label_counter
label_counter -= 1
ret = [x for _, x in sorted(zip(label, ops))]
self.reset_nodes(ret)
def make_graph(self, doc, graph_name="tf2onnx"):
"""
Create GraphProto for onnx from internal graph.
Args:
optimize: optimize graph via onnx
doc: text for doc string of the graph
"""
self.delete_unused_nodes(self.outputs)
self.topological_sort(self.get_nodes())
self.update_proto()
# TODO: we'd want to do something like this so that transpose optimizer is active
# for all (unit) tests
# if optimize:
# from tf2onnx.optimizer.transpose_optimizer import TransposeOptimizer
# optimizer = TransposeOptimizer(self, False)
# optimizer.optimize()
ops = []
order_non_sensitive_placeholders = []
order_sensitive_placeholders = self._order_sensitive_inputs
const_ops = []
for op in self.get_nodes():
if op.is_const():
const_ops.append(op)
continue
if op.is_graph_input():
if op not in self._order_sensitive_inputs:
order_non_sensitive_placeholders.append(op)
continue
ops.append(op)
placeholder_ops = order_sensitive_placeholders + order_non_sensitive_placeholders
# create initializers for placeholder with default nodes
initializers = []
placeholder_default_const_ops = []
for op in placeholder_ops:
if op.type == "PlaceholderWithDefault":
utils.make_sure(op.inputs[0] is not None, "Cannot find node with output {}".format(op.input[0]))
utils.make_sure(op.inputs[0].is_const(),
"non-const default value for PlaceholderWithDefault is not supported.")
# copy the tensor value, set its name to current node's output, add as initializer
value = op.inputs[0].get_tensor_value(as_list=False)
tensor = numpy_helper.from_array(value, op.output[0])
initializers.append(tensor)
placeholder_default_const_ops.append(op.inputs[0])
# create initializers for constant nodes
const_ops = [op for op in const_ops if op not in placeholder_default_const_ops]
for op in const_ops:
# not to use numpy_helper.from_array to create a new tensor
# because sometimes onnx will have a bug that only check the tensor data in specific field
# such as at upsample it only checks the float_data field.
t = op.get_attr("value")
tensor = helper.get_attribute_value(t)
tensor.name = op.output[0]
initializers.append(tensor)
# create input_tensor_values
input_ids = [op.output[0] for op in placeholder_ops]
# onnx with IR version below 4 requires initializer should be in inputs.
# here we check opset version rather than IR version for the reason:
# https://github.com/onnx/tensorflow-onnx/pull/557
# opset 9 come with IR 4.
if self.opset < 9:
input_ids += [op.output[0] for op in const_ops]
input_tensor_values = self.make_onnx_graph_io(input_ids)
# create output_tensor_values
output_tensor_values = self.make_onnx_graph_io(self.outputs)
# create graph proto
graph = helper.make_graph([op.op for op in ops],
graph_name,
input_tensor_values,
output_tensor_values,
initializer=initializers,
doc_string=doc)
return graph
def make_model(self, graph_doc, optimize=False, graph_name="tf2onnx", **kwargs):
"""
Create final ModelProto for onnx from internal graph.
Args:
optimize: optimize graph via onnx
doc: text for doc string of the model
"""
graph = self.make_graph(graph_doc, graph_name)
if "producer_name" not in kwargs:
kwargs = {"producer_name": "tf2onnx",
"producer_version": __version__}
if "opset_imports" not in kwargs:
opsets = []
imp = OperatorSetIdProto()
imp.version = self._opset
opsets.append(imp)
if self.extra_opset is not None:
opsets.extend(self.extra_opset)
kwargs["opset_imports"] = opsets
model_proto = helper.make_model(graph, **kwargs)
# optimize the model proto.
# TODO: this is disabled by default because of bugs in fuse_consecutive_transposes
if optimize:
model_proto = optimizer.optimize(model_proto)
return model_proto
def make_onnx_graph_io(self, ids):
"""Create tensor_value_info for passed input/output ids."""
tensor_value_infos = []
for name in ids:
dtype = self.get_dtype(name)
shape = self.get_shape(name)
utils.make_sure(dtype is not None, "missing output dtype for " + name)
utils.make_sure(shape is not None, "missing output shape for " + name)
v = utils.make_onnx_inputs_outputs(name, dtype, shape)
tensor_value_infos.append(v)
return tensor_value_infos
def dump_graph(self):
"""Dump graph with shapes (helpful for debugging)."""
for node in self.get_nodes():
input_names = ["{}{}".format(n, self.get_shape(n)) for n in node.input]
logger.debug("%s %s %s %s",
node.type,
self.get_shape(node.output[0]),
node.name,
", ".join(input_names))
def follow_inputs(self, node, num, space=""):
"""Follow inputs for (helpful for debugging)."""
val = []