-
Notifications
You must be signed in to change notification settings - Fork 98
/
onnx_operator.py
1344 lines (1236 loc) · 50.5 KB
/
onnx_operator.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
# SPDX-License-Identifier: Apache-2.0
import warnings
from logging import getLogger
import numpy as np
from onnx import GraphProto
from onnx.helper import make_graph, make_model
from onnx.numpy_helper import from_array
from scipy.sparse import coo_matrix
from ..proto import TensorProto
from ..common.data_types import _guess_type_proto_str, _guess_type_proto_str_inv
from ..common._topology import (
Variable,
VariableStr,
Scope,
_update_domain_version,
Operator,
_get_main_opset_version,
OPSET_TO_IR_VERSION,
)
from ..common._container import ModelComponentContainer
from ..common import utils
from ..common.data_types import guess_proto_type, _guess_numpy_type
from ..common._registration import _converter_pool, _shape_calculator_pool
from .._supported_operators import sklearn_operator_name_map
from ..proto import get_latest_tested_opset_version, onnx_proto
from ..helpers.onnx_helper import infer_outputs
from .graph_state import GraphState, GraphStateVar
from .type_helper import _guess_type
logger = getLogger("skl2onnx")
class OnnxOperatorItem:
"""
Accessor to one of the output returned by a *OnnxOperator*.
:param onx_op: OnnxOperator
:param index: integer
"""
def __init__(self, onx_op, index, op_version=None):
if not isinstance(index, int):
raise TypeError("index must be an integer.")
self.onx_op = onx_op
self.index = index
self.op_version = op_version
def __str__(self):
"""
usual
"""
return "%s[%d]" % (str(self.onx_op), self.index)
def get_latest_tested_opset_version(self):
"""
Returns ``get_latest_tested_opset_version()``
of the wrapped *OnnxOperator* instance.
"""
return self.onx_op.get_latest_tested_opset_version()
def add_to(self, scope, container, operator=None, run_converters=False):
"""
Adds outputs to the container if not already added,
registered the outputs if the node is not final.
:param scope: scope
:param container: container
:param operator: overwrite inputs
:param run_converters: must be True if called from method `to_onnx`
"""
self.onx_op.add_to(
scope, container, operator=operator, run_converters=run_converters
)
def get_output_name(self, i=0):
"""
Returns the output.
"""
if i != 0:
raise IndexError("Can only return the first item.")
return self.onx_op.get_output_name(self.index)
def get_output(self, i=0):
"""
Returns the output.
"""
if i != 0:
raise IndexError("Can only return the first item.")
return self.onx_op.get_output(self.index)
@property
def outputs(self):
"""
Returns the outputs of the node.
"""
if self.onx_op is None:
raise RuntimeError(
"self.onx_op cannot be None, type(self)={}".format(type(self))
)
if self.index is None:
raise RuntimeError(
"self.index cannot be None, type(self)={}".format(type(self))
)
outputs = self.onx_op.outputs
if outputs is None:
raise RuntimeError(
"self.onx_op.outputs cannot be None, "
"type(self)={}, type(self.onx_op)={}, "
"type(self.onx_op.state)={}".format(
type(self), type(self.onx_op), type(self.onx_op.state)
)
)
return outputs[self.index : self.index + 1]
def get_output_type_inference(self, input_shapes=None):
"""
Returns the inferred shape.
"""
if self.onx_op is None:
raise RuntimeError(
"self.onx_op cannot be None, type(self)={}".format(type(self))
)
if self.index is None:
raise RuntimeError(
"self.index cannot be None, type(self)={}".format(type(self))
)
outputs = self.onx_op.get_output_type_inference(input_shapes)
if outputs is None:
raise RuntimeError(
"self.onx_op.outputs cannot be None, "
"type(self)={}, type(self.onx_op)={}, "
"type(self.onx_op.state)={}".format(
type(self), type(self.onx_op), type(self.onx_op.state)
)
)
return outputs[self.index : self.index + 1]
class OnnxOperator:
"""
Ancestor to every *ONNX* operator exposed in
:mod:`onnx_ops` and :mod:`onnx_ops_ml`. These files
are automatically generated by unit test
*test_onnx_operators_parse_spec*
Every instance is supposed to be included in
a graph as a node.
:param inputs: list of inputs expected by the operator
:param op_version: to select a specific version of the operator
:param output_names: used defined names for the outputs
:param domain: to overwrite the default domain
:param global_context: operator *If* executes one subgraph
whose nodes may use one existing output in the current
context. If not used in the main graph, these operators
are not linked to the output and cannot be retrieved.
*global_context* is a dictionary mapped the subgraph input
names to these operators.
:param clear_subgraph_inputs: clears subgraphs outputs.
Operator *If* does take subgraphs as attribute,
there are subgraphs with no inputs and
global variable as hidden inputs.
:param kwargs: additional parameters of the operator
.. versionchanged:: 1.10.1
Parameter *global_context*, *clear_subgraph_inputs*
were added.
"""
class OnnxOperatorVariable(GraphStateVar):
def __init__(self, index, name=None):
self.index = index
self.name = name
def as_variable(self, scope):
name = "ov%s" % self.name
if hasattr(self, "variable_") and self.variable_.onnx_name == name:
return self.variable_
var = Variable(name, name, scope=scope, type=None)
if scope is not None:
scope.register_variable(var)
self.variable_ = var
return var
def __repr__(self):
return "OnnxOperatorVariable('%s')" % self.name
def __iter__(self):
yield self.name
yield None
class UnscopedVariable(GraphStateVar):
def __init__(self, name):
self.name = name
def as_variable(self, scope):
name = self.name
if hasattr(self, "variable_") and self.variable_.onnx_name == name:
return self.variable_
if scope is not None:
if name in scope.variables:
var = scope.variables[name]
else:
onnx_name = scope.get_unique_variable_name(name)
var = Variable(name, onnx_name, scope=scope, type=None)
scope.register_variable(var)
self.variable_ = var
else:
var = Variable(name, name, scope=scope, type=None)
return var
def __eq__(self, name):
if isinstance(name, str):
return name == self.name
elif isinstance(name, OnnxOperator.UnscopedVariable):
return self.name == name.name
else:
raise TypeError("Unsupported type for comparison {}".format(type(name)))
def __repr__(self):
return "UnscopedVariable('%s')" % self.name
def __iter__(self):
yield self.name
yield None
class ConstantVariable(GraphStateVar):
def __init__(self, value):
self.value = value
def as_variable(self, scope):
ha = utils.hash_array(self.value)
name = "CST%s" % ha
if hasattr(self, "variable_") and self.variable_.onnx_name == name:
return self.variable_
if scope is not None:
var = scope.declare_local_variable(name, type=_guess_type(self.value))
else:
var = Variable(name, name, scope=scope, type=_guess_type(self.value))
self.variable_ = var
return var
@property
def ConstantValue(self):
return self.value
def __str__(self):
return "Cst({})".format(self.value)
def __iter__(self):
yield "id%d" % id(self)
yield _guess_type(self.value)
def find_schema(self, op_version):
"""
Checks if there is an existing schema for a
specific version.
:param op_version: requested version
:return: schema
"""
if not hasattr(self.__class__, "past_version"):
raise RuntimeError(
"Missing attribute 'past_version', there is "
"no other available schema."
)
found = None
for v in self.past_version.values():
if v.since_version > op_version:
continue
if found is None or v.since_version > found.since_version:
found = v
if found is None:
raise RuntimeError(
"Operator '{}': requested version {} < "
"{} schema version.".format(
self.__class__.__name__, op_version, self.since_version
)
)
return found
def __init__(
self,
*inputs,
op_version=None,
output_names=None,
domain=None,
global_context=None,
clear_subgraph_inputs=False,
**kwargs
):
if output_names is None and self.__class__.__name__.startswith("OnnxScan"):
raise NotImplementedError(
"The class cannot infer the number of variables "
"for node '{}' yet. output_names must be specified"
".".format(self.__class__.__name__)
)
if isinstance(output_names, (str, Variable)):
output_names = [output_names]
if isinstance(output_names[0], str):
output_names[0] = VariableStr(output_names[0])
elif isinstance(output_names, Operator):
if len(output_names.outputs) == 0:
raise ValueError(
"output_names cannot be empty (operator %r)." "" % output_names
)
output_names = output_names.outputs.copy()
elif isinstance(output_names, Operator.OperatorList):
if len(output_names) == 0:
raise ValueError(
"output_names cannot be empty (operator %r)."
"" % self.__class__.__name__
)
output_names = output_names.copy()
elif isinstance(output_names, list):
if len(output_names) == 0:
raise ValueError(
"output_names cannot be empty (operator %r)."
"" % self.__class__.__name__
)
output_names = output_names.copy()
for i in range(len(output_names)):
if isinstance(output_names[i], str):
output_names[i] = VariableStr(output_names[i])
elif output_names is not None:
raise TypeError(
"output_names must be a string or a list not %r."
"" % type(output_names)
)
if op_version is None:
if domain == "":
self.op_version = get_latest_tested_opset_version()
else:
self.op_version = None
else:
self.op_version = op_version
self.since_version = self.__class__.since_version
if self.op_version is not None and self.op_version < self.since_version:
schema = self.find_schema(self.op_version)
self.since_version = schema.since_version
self.expected_inputs = schema.expected_inputs.copy()
self.expected_outputs = schema.expected_outputs.copy()
self.input_range = schema.input_range
self.output_range = schema.output_range
else:
self.expected_inputs = (
None
if self.__class__.expected_inputs is None
else self.__class__.expected_inputs.copy()
)
self.expected_outputs = (
None
if self.__class__.expected_outputs is None
else self.__class__.expected_outputs.copy()
)
self.input_range = self.__class__.input_range
self.output_range = self.__class__.output_range
if self.__class__.__name__ not in {"OnnxScan", "OnnxLoop", "OnnxIf"}:
# TODO: the minimum opset depends on embedded graph
# by default, it takes the given op_version but the
# optimal value could be lower.
self.op_version = self.since_version
if self.op_version is None:
self.op_version = self.since_version
if self.op_version is not None and self.op_version < self.since_version:
raise RuntimeError(
"Operator '{}': requested version {} < "
"{} schema version.".format(
self.__class__.__name__, self.op_version, self.since_version
)
)
self.state = None
self.domain = domain
self.kwargs = kwargs
self.onnx_prefix_name = None
# check inputs
if len(inputs) == 0:
if self.input_range[0] == self.input_range[1]:
self.inputs = [
OnnxOperator.UnscopedVariable(_[0]) for _ in self.expected_inputs
]
else:
# The number of inputs may vary.
self.inputs = None
else:
self.inputs = []
for inp in inputs:
if isinstance(inp, str):
self.inputs.append(OnnxOperator.UnscopedVariable(inp))
elif isinstance(
inp, (OnnxOperator, Variable, OnnxOperatorItem, OnnxSubEstimator)
):
self.inputs.append(inp)
elif isinstance(inp, tuple) and len(inp) == 2:
self.inputs.append(inp)
elif isinstance(inp, (np.ndarray, coo_matrix)):
self.inputs.append(OnnxOperator.ConstantVariable(inp))
elif isinstance(inp, TensorProto):
self.inputs.append(OnnxOperator.ConstantVariable(inp))
elif isinstance(
inp,
(OnnxOperator.OnnxOperatorVariable, OnnxOperator.ConstantVariable),
):
self.inputs.append(inp)
elif isinstance(
inp, (np.int64, np.float32, np.float64, np.bool_, np.int8, np.uint8)
):
self.inputs.append(OnnxOperator.ConstantVariable(inp))
elif isinstance(inp, (float,)):
self.inputs.append(np.float64(inp))
elif isinstance(inp, (int,)):
self.inputs.append(np.int64(inp))
else:
raise TypeError(
"Unable to interpret the input name for type {} in "
"operator '{}' (value={}).".format(
type(inp), self.__class__.__name__, inp
)
)
if self.inputs is not None:
if (
len(self.inputs) < self.input_range[0]
or len(self.inputs) > self.input_range[1]
):
raise RuntimeError(
"Operator '{}' expects a number of inputs "
"in [{}, {}] not {} (expected opset={}, "
"class opset={})".format(
self.operator_name,
*self.input_range,
len(self.inputs),
op_version,
self.op_version
)
)
# global context
if global_context is None:
self.global_context = None
else:
if not isinstance(global_context, dict):
raise TypeError(
"global_context must be a dictionary not %r."
"" % type(global_context)
)
for k, v in global_context.items():
if not isinstance(v, (OnnxOperator, OnnxOperatorItem)):
raise TypeError(
"Value %r in must be an OnnxOperator or an "
"OnnxOperatorItem not %r." % (k, type(v))
)
self.global_context = global_context
# check output
self.output_names = output_names
self.output_variables = None
if self.output_names is not None:
if len(self.output_names) == 0:
raise ValueError(
"output_names can be None but cannot be empty for "
"operator %r." % self
)
if self.output_variables is None:
self.output_variables = [None for o in self.output_names]
for i in range(len(self.output_names)):
name = self.output_names[i]
if isinstance(name, Variable):
self.output_variables[i] = name
else:
raise TypeError(
"output_names must be a list of strings "
"and element %r is %r (%r)" % (i, type(name), name)
)
if all(map(lambda x: x is None, self.output_variables)):
self.output_variables = None
if self.output_names is not None and (
self.expected_outputs is None
or len(self.output_names) > len(self.expected_outputs)
):
if self.expected_outputs is None:
self.expected_outputs = []
for i in range(len(self.expected_outputs), len(self.output_names)):
self.expected_outputs.append((self.output_names[i], None))
if self.expected_inputs is None or len(self.inputs) > len(self.expected_inputs):
if self.expected_inputs is None:
self.expected_inputs = []
for i in range(len(self.expected_inputs), len(self.inputs)):
inp = self.inputs[i]
if isinstance(inp, GraphStateVar):
inp = tuple(inp)
elif isinstance(inp, str):
inp = (inp, None)
elif hasattr(inp, "add_to"):
# OnnxOperator
existing = set(_[0] for _ in self.expected_inputs)
i = 10
name = "input%d" % (10 + i)
while name in existing:
i += 1
name = "input%d" % (10 + i)
inp = (name, None)
self.expected_inputs.append(inp)
self.output_names_ = None
self._post_process_attributes(clear_subgraph_inputs=clear_subgraph_inputs)
logger.debug(
"[Ops] +%s-%d (%s) id=%d",
self.__class__.__name__,
self.op_version,
self.domain,
id(self),
)
def _post_process_attributes(self, clear_subgraph_inputs=False):
"""
Walks through attributes and replaces them by ONNX
values.
"""
# Looks into attributes if there is any tuple
# (GraphProto, OnnxOperator). In that case, the function
# replaces the tuple by the graph proto and keeps
# in attributes graph_algebra the OnnxOperator
# which is the source of it.
updates = {}
graph_algebra = {}
for k, v in self.kwargs.items():
if isinstance(v, tuple) and isinstance(v[0], GraphProto):
updates[k] = v[0]
graph_algebra[k] = v[1]
if len(graph_algebra) > 0:
self.kwargs.update(updates)
self.graph_algebra = graph_algebra
if clear_subgraph_inputs:
for k, v in self.kwargs.items():
if isinstance(v, GraphProto):
del v.input[:]
if self.__class__.__name__ == "OnnxConstantOfShape":
if "value" in self.kwargs:
value = self.kwargs["value"]
if isinstance(value, TensorProto):
return
if isinstance(value, np.ndarray):
if value.shape == (1,):
val = value[0]
elif len(value.shape) == 0:
val = value
else:
raise RuntimeError(
"Unexpected shape %r for value, it must be "
"an array of one element." % value.shape
)
self.kwargs["value"] = from_array(
np.array([val], dtype=value.dtype)
)
return
raise TypeError(
"Unexpected type %r for value. It should be an array "
"of one element." % type(value)
)
return
if self.__class__.__name__ == "OnnxCast":
if "to" in self.kwargs:
value = self.kwargs["to"]
if isinstance(value, int):
return
to = guess_proto_type(_guess_numpy_type(value, None))
self.kwargs["to"] = to
return
def __str__(self):
"""
usual
"""
return "{}({} in) -> {}".format(
self.__class__.__name__,
len(self.inputs) if self.inputs is not None else 0,
(
[str(o) for o in self.output_names]
if self.output_names is not None
else "?"
),
)
def set_onnx_name_prefix(self, onnx_prefix_name):
"""
Provides a name to define a prefix in the onnx graph
to avoid to get unreadable node names. The method
does not overwrite an existing name, it propagates
the prefix to inputs and stops the propagation
if the prefix is already defined.
"""
if self.onnx_prefix_name is None:
self.onnx_prefix_name = onnx_prefix_name
for inp in self.inputs:
if hasattr(inp, "onnx_prefix_name"):
inp.set_onnx_name_prefix(onnx_prefix_name)
return self
@property
def onnx_prefix(self):
if self.onnx_prefix_name is None:
name = self.__class__.__name__
if name.startswith("Onnx"):
name = name[4:]
return name[:2]
return self.onnx_prefix_name
def __getitem__(self, index):
"""
Returns an accessor to one of the output
of this node.
"""
return OnnxOperatorItem(self, index, self.op_version)
def get_output_name(self, i, scope=None):
"Returns name of output *i*."
if self.state is not None:
return self.state.computed_outputs_[i][0]
if self.output_names_ is not None:
return self.output_names_[i]
self._set_output_names_(getattr(self, "scope", None) or scope, None)
return self.output_names_[i]
def get_output(self, i, scope=None):
"Returns name of output *i*."
if self.state is not None:
return self.state.computed_outputs_[i]
if self.output_names_ is not None:
res = self.output_names_[i]
if not isinstance(res, (tuple, Variable)):
raise RuntimeError(
"Unable to retrieve output %r from %r." "" % (i, self)
)
return res
def _set_output_names_(self, scope, operator):
"Called by add_to."
if operator is not None:
self.operator_ = operator
if self.output_names_ is not None:
raise RuntimeError("output_names_ is already set.")
elif self.output_variables is not None:
outputs = [o.onnx_name for o in self.output_variables]
self.output_names_ = outputs
elif self.output_names:
if not isinstance(self.output_names, (list, tuple)):
louts = [self.output_names]
else:
louts = self.output_names
if operator is not None and len(louts) != len(operator.outputs):
raise RuntimeError(
"Output mismatch for '{}'\n{}\n{}".format(
type(operator.raw_operator), louts, operator.outputs
)
)
outputs = []
for iname, name in enumerate(louts):
if name is None:
raise AssertionError(
"Issue for operator '{}'.".format(type(operator.raw_operator))
)
if name.startswith("u(") and name[-1] == ")":
name = scope.get_unique_variable_name(name[2:-1])
elif operator is not None:
oout = operator.outputs[iname]
name = oout.onnx_name
outputs.append(name)
self.output_names_ = outputs
elif self.expected_outputs is None:
raise AttributeError(
"expected_outputs is None for operator=%r, output_names=%r, "
"output_variables=%r, operator=%r"
% (self, self.output_names, self.output_variables, operator)
)
else:
if scope is None:
raise RuntimeError("scope must not be None.")
outputs = []
for name in self.expected_outputs:
name = scope.get_unique_variable_name(self.onnx_prefix + "_" + name[0])
outputs.append(name)
self.output_names_ = outputs
return outputs
def _add_to_inputs(self, operator):
inputs = []
for input in self.inputs:
if isinstance(input, OnnxOperator.OnnxOperatorVariable):
if operator is None:
raise RuntimeError(
"A placeholder cannot be replaced "
"as an operator is not specified."
)
if len(operator.inputs) == 0:
raise RuntimeError("No input variable in {}.".format(operator))
# The inputs must be looked into the graph.
for i in operator.inputs:
if i.onnx_name == input.name:
inputs.append(i)
break
else:
vars = ", ".join(
map(lambda o: "'%s'" % o.onnx_name, operator.inputs)
)
raise RuntimeError(
"Unable to find variable " "{} in {}.".format(input, vars)
)
else:
inputs.append(input)
return inputs
def add_to(self, scope, container, operator=None, run_converters=False):
"""
Adds outputs to the container if not already added,
registered the outputs if the node is not final.
:param scope: scope
:param container: container
:param operator: overwrite inputs
:param run_converters: False by default, must be True if
called from method `to_onnx`
At this stage, inputs types are not necessarily known.
"""
if self.state is None:
if self.is_deprecated:
raise RuntimeError(
"Node '{}' is deprecated. This API cannot deprecated "
"nodes.".format(self.__class__.__name__)
)
if self.op_version is not None and self.op_version < self.since_version:
raise RuntimeError(
"Incompatible versions for node '{}' op_version {} "
"< since_version {}.".format(
self.__class__.__name__, self.op_version, self.since_version
)
)
if self.kwargs.get("op_version", "") is None:
kwargs = self.kwargs.copy()
del kwargs["op_version"]
else:
kwargs = self.kwargs
self._set_output_names_(scope, operator)
domain = self.domain
if domain is None:
domain = self.__class__.domain
inputs = self._add_to_inputs(operator)
logger.debug("[Ops.add_to] state id=%d", id(self))
self.state = GraphState(
inputs,
self.output_names_,
self.operator_name,
scope,
container,
None,
op_version=self.op_version,
op_domain=domain,
onnx_prefix_name=self.onnx_prefix,
expected_inputs=self.expected_inputs,
expected_outputs=self.expected_outputs,
input_range=self.input_range,
output_range=self.output_range,
operator=operator,
run_converters=run_converters,
**kwargs
)
self.state.run()
self._verify_add_to_()
def _verify_add_to_(self):
if self.state is None:
raise RuntimeError(
"Graph was not produced for operator '{}': {}."
"".format(self.__class__.__name__, self)
)
for i in self.inputs:
if hasattr(i, "_verify_add_to_"):
i._verify_add_to_()
@property
def outputs(self):
"""
Returns the outputs of the node.
"""
if self.state is None:
raise RuntimeError("Method add_to was not called.")
return self.state.outputs
def get_output_type_inference(self, input_shapes=None):
"""
Returns the expected output types in a list.
"""
if self.state is not None and self.state.computed_outputs_ is not None:
return self.state.computed_outputs_
expected_inputs = (
self.state.computed_inputs_
if self.expected_inputs is None
else self.expected_inputs
)
if expected_inputs is None:
raise RuntimeError(
"Attribute 'expected_inputs' is empty for %r, "
"input_shapes=%r." % (self, input_shapes)
)
expected_outputs = (
self.state.computed_outputs_
if self.expected_outputs is None
else self.expected_outputs
)
if expected_outputs is None:
raise RuntimeError(
"Attribute 'expected_outputs' is empty for %r, "
"input_shapes=%r." % (self, input_shapes)
)
# Shape inference only work on a full graph.
if input_shapes is None:
input_shapes = self.inputs
given = {}
for i, inp in enumerate(input_shapes):
if isinstance(inp, tuple):
given[i] = inp[1]
elif isinstance(inp, GraphStateVar):
dt = inp.as_variable(scope=None)
if dt.type is None:
continue
given[i] = dt.type
rev = {}
for i, (name, v) in enumerate(expected_inputs):
if v in rev:
rev[v].append(i)
else:
rev[v] = [i]
res = []
for name, ct in expected_outputs:
if isinstance(ct, str) and ct[0] in ("T", "V", "I"):
if ct[0] not in rev or all(map(lambda k: k not in given, rev[ct])):
raise NotImplementedError(
"Unable to guess output type for (%r, %r) - "
"given=%r - rev=%r input_shapes=%r expected_inputs"
"=%r."
% (name, ct, given, rev, input_shapes, self.expected_inputs)
)
found = False
for ind in rev[ct]:
if ind in given:
res.append((name, given[ind]))
found = True
break
if not found:
raise NotImplementedError(
"Unable to guess output type for (%r, %r) - "
"given=%r - rev=%r input_shapes=%r expected_inputs"
"=%r."
% (name, ct, given, rev, input_shapes, self.expected_inputs)
)
continue
if isinstance(ct, str):
try:
dt = _guess_type_proto_str(ct, None)
except NotImplementedError as e:
raise NotImplementedError(
"Unable to guess output type for (%r, %r) - "
"given=%r - rev=%r." % (name, ct, given, rev)
) from e
res.append((name, dt))
continue
try:
dt = _guess_type_proto_str(_guess_type_proto_str_inv(ct), None)
except NotImplementedError as e:
raise NotImplementedError(
"Unable to guess output type for (%r, %r) - given=%r - "
"rev=%r." % (name, ct, given, rev)
) from e
res.append((name, dt))
return res
def _clean_attributes(self, *args, recursive=True):
"""
Removes attributes in this node and its parents.
"""
for arg in args:
if arg in ("state", "output_names_"):
setattr(self, arg, None)
elif hasattr(self, arg):
delattr(self, arg)
if recursive:
for obj in self.inputs:
if isinstance(obj, OnnxOperator):
obj._clean_attributes(*args, recursive=True)
def to_onnx(
self,
inputs=None,
outputs=None,
other_outputs=None,
target_opset=None,
domain=None,
verbose=0,
):
"""
Converts this operator into an ONNX graph.
:param inputs: specific inputs (as a dictionary) or
default inputs if not specified
:param outputs: specific outputs
:param other_outputs: additional outputs to consider
as graph outputs but not outputs of this particular
node
:param target_opset: dictionary with target opset per domain,
None for the default one
:param domain: domain of the operator
:param verbose: prints information
"""
if isinstance(target_opset, dict):
dom = self.domain or ""
target_opset = target_opset.get(dom, None)
elif isinstance(target_opset, int):
if self.domain not in ("", None):
# The target_opset is for the domain ''
# We ignore it.
target_opset = None
elif target_opset is not None:
raise TypeError(
"target_opset must be a dictionary {domain: "
"target_opset} not %r for operator %r."
% (target_opset, self.__class__.__name__)
)
if self.domain in ("", None) and target_opset == 1:
raise RuntimeError("target_opset cannot be 1.")
if (
self.op_version is not None
and target_opset is not None
and self.op_version > target_opset
):
raise RuntimeError(
"target_opset={} is lower than the version={} requested "
"for this node '{}'.".format(
target_opset, self.op_version, self.__class__.__name__
)
)
if self.state is not None:
# The conversion already happened and needs to be cleaned.
self._clean_attributes("output_names_", "state")
if inputs is None:
raise NotImplementedError("inputs must be specified.")
if isinstance(inputs, dict):
inputs = [(k, v) for k, v in inputs.items()]
new_inputs = []
for obj in inputs:
if isinstance(obj, Variable):
new_inputs.append((obj.onnx_name, obj.type))
elif isinstance(obj, tuple) and len(obj) == 2:
ty = _guess_type(obj[1])
new_inputs.append((obj[0], ty))
else:
raise TypeError(
"Inputs must be Variable or "
"tuple(name, type) not {}."
"".format(type(obj))
)
inputs = new_inputs
for name, typ in inputs:
if typ is None:
raise RuntimeError(
"Type input '{}' for operator '{}' "
"is unknown. You should specify "
"input types.".format(name, self.__class__.__name__)
)
registered_models = dict(
conv=_converter_pool,
shape=_shape_calculator_pool,
aliases=sklearn_operator_name_map,
)
target_opset = self.get_latest_tested_opset_version(target_opset)
container = ModelComponentContainer(
target_opset, registered_models=registered_models
)