-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathsonnx.py
executable file
·2229 lines (2057 loc) · 73.4 KB
/
sonnx.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
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
#
from __future__ import division
import numpy as np
import onnx
import onnx.utils
from onnx.backend.base import Backend, BackendRep
from onnx import (checker, helper, numpy_helper, GraphProto, NodeProto,
TensorProto, OperatorSetIdProto, optimizer, mapping,
shape_inference)
import warnings
from . import device
from . import autograd
from . import layer
from . import tensor
from . import model
from . import utils
from . import singa_wrap as singa
import collections
OrderedDict = collections.OrderedDict
namedtuple = collections.namedtuple
# singa only supports float32 and int32
NP_TYPE_TO_SINGA_SUPPORT_TYPE = {
np.dtype('float32'): np.dtype('float32'),
np.dtype('uint8'): None,
np.dtype('int8'): np.dtype('int32'),
np.dtype('uint16'): None,
np.dtype('int16'): np.dtype('int32'),
np.dtype('int32'): np.dtype('int32'),
np.dtype('int64'): np.dtype('int32'),
np.dtype('bool'): np.dtype('float32'),
np.dtype('float16'): np.dtype('float32'),
np.dtype('float64'): np.dtype('float32'),
np.dtype('complex64'): None,
np.dtype('complex128'): None,
np.dtype('uint32'): None,
np.dtype('uint64'): None,
np.dtype(np.object): None
}
def onnx_type_to_singa_type(onnx_type):
np_type = mapping.TENSOR_TYPE_TO_NP_TYPE[onnx_type]
return NP_TYPE_TO_SINGA_SUPPORT_TYPE[np_type]
gpu_dev = None
if singa.USE_CUDA:
gpu_dev = device.create_cuda_gpu()
cpu_dev = device.get_default_device()
class SingaFrontend(object):
"""
This class provides mthods to convert model from singa to onnx.
"""
# This number indicates the target onnx operator set version
_target_opset_version = 11
# beceuase singa's operators are different from onnx.
# we define a dict for the name projection
# "singa op name": "onnx op name"
_rename_operators = {
'_Conv2d': 'Conv',
'ReLU': 'Relu',
'MaxPool2d': 'MaxPool',
'AvgPool2d': 'AveragePool',
'SoftMax': 'Softmax',
'Sigmoid': 'Sigmoid',
'Add': 'Add',
'Matmul': 'MatMul',
'_BatchNorm2d': 'BatchNormalization',
'Concat': 'Concat',
'Flatten': 'Flatten',
'AddBias': 'Add',
'Gemm': 'Gemm',
'Reshape': 'Reshape',
'Sum': 'Sum',
'cos': 'Cos',
'cosh': 'Cosh',
'sin': 'Sin',
'sinh': 'Sinh',
'tan': 'Tan',
'tanh': 'Tanh',
'acos': 'Acos',
'acosh': 'Acosh',
'asin': 'Asin',
'asinh': 'Asinh',
'atan': 'Atan',
'atanh': 'Atanh',
'SeLU': 'Selu',
'Elu': 'Elu',
'Equal': 'equal',
'Less': 'Less',
'Sign': 'Sign',
'Div': 'Div',
'Sub': 'Sub',
'Sqrt': 'Sqrt',
'Log': 'Log',
'Greater': 'Greater',
'HardSigmoid': 'HardSigmoid',
'Identity': 'Identity',
'SoftPlus': 'Softplus',
'SoftSign': 'Softsign',
'Mean': 'Mean',
'Pow': 'Pow',
'Clip': 'Clip',
'PRelu': 'PRelu',
'Mul': 'Mul',
'Transpose': 'Transpose',
'Max': 'Max',
'Min': 'Min',
'Shape': 'Shape',
'And': 'And',
'Or': 'Or',
'Xor': 'Xor',
'Not': 'Not',
'Negative': 'Neg',
'Reciprocal': 'Reciprocal',
'ConstantOfShape': 'ConstantOfShape',
'Dropout': 'Dropout',
'ReduceSum': 'ReduceSum',
'ReduceMean': 'ReduceMean',
'LeakyRelu': 'LeakyRelu',
'GlobalAveragePool': 'GlobalAveragePool',
'Squeeze': 'Squeeze',
'Unsqueeze': 'Unsqueeze',
'Slice': 'Slice',
'Ceil': 'Ceil',
'Split': 'Split',
'Gather': 'Gather',
'Tile': 'Tile',
'NonZero': 'NonZero',
'Cast': 'Cast',
'OneHot': 'OneHot',
}
# this dict indicates the operators that need extra handle
# each indicates a function name
_special_operators = {
'_Conv2d': '_create_conv_pool',
'_Pooling2d': '_create_conv_pool',
'_BatchNorm2d': '_create_batchnorm',
'Concat': '_create_concat',
'Flatten': '_create_flatten',
'Gemm': '_create_gemm',
'Reshape': '_create_reshape',
'SoftMax': '_create_softmax',
'SeLU': '_create_selu',
'Elu': '_create_elu',
'HardSigmoid': '_create_hardsigmoid',
'Clip': '_create_clip',
'Transpose': '_create_transpose',
'ConstantOfShape': '_create_constantOfShape',
'Dropout': '_create_dropout',
'ReduceSum': '_create_reduceOp',
'ReduceMean': '_create_reduceOp',
'Squeeze': '_create_squeeze',
'Unsqueeze': '_create_squeeze',
'Slice': '_create_slice',
'Split': '_create_split',
'Gather': '_create_gather',
'Tile': '_create_tile',
'Cast': '_create_cast',
'OneHot': '_create_onehot',
}
# operators with bool output
_bool_operators = {
'Equal': TensorProto.BOOL,
'Greater': TensorProto.BOOL,
'Less': TensorProto.BOOL,
'And': TensorProto.BOOL,
'Not': TensorProto.BOOL,
'Or': TensorProto.BOOL,
'Xor': TensorProto.BOOL,
'Shape': TensorProto.INT64,
'NonZero': TensorProto.INT64,
}
# some ops(such as batchnorm) has inputs we cannot handle directly,
# so we record these items firstly so that we can handle then
# at other place.
_unhandled_operators = {
"_BatchNorm2d": "_special_handle_batchnorm",
"Reshape": "_special_handle_reshape",
"Clip": "_special_handle_clip",
"Slice": "_special_handle_slice",
"Gather": "_special_handle_gather",
"Tile": "_special_handle_tile",
"OneHot": "_special_handle_onehot",
}
@classmethod
def _create_onehot(cls, op, op_t):
"""
get a onnx node from singa onthot
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
# axis, indices, depth, values
node.attribute.extend([
helper.make_attribute('axis', op.axis),
])
for attr in ['depth', 'values']:
node.input.append(op.name + ":" + attr)
return node
@classmethod
def _create_cast(cls, op, op_t):
"""
get a onnx node from singa cast
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
map_dict = {
tensor.float32: TensorProto.FLOAT, # FLOAT to float32
tensor.int32: TensorProto.INT32, # INT32 to int32
}
node.attribute.extend([
helper.make_attribute('to', map_dict[op.to]),
])
return node
@classmethod
def _create_tile(cls, op, op_t):
"""
get a onnx node from singa tile
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
node.input.append(op.name + ":repeats")
return node
@classmethod
def _create_gather(cls, op, op_t):
"""
get a onnx node from singa gather
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
node.attribute.extend([
helper.make_attribute('axis', op.axis),
])
node.input.append(op.name + ":indices")
return node
@classmethod
def _create_split(cls, op, op_t):
"""
get a onnx node from singa split
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
node.attribute.extend([
helper.make_attribute('axis', op.axis),
helper.make_attribute('split', op.parts),
])
return node
@classmethod
def _create_slice(cls, op, op_t):
"""
get a onnx node from singa slice
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
for attr in ['starts', 'ends', 'axes', 'steps']:
node.input.append(op.name + ":" + attr)
return node
@classmethod
def _create_squeeze(cls, op, op_t):
"""
get a onnx node from singa squeeze and unsqueeze
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
node.attribute.extend([
helper.make_attribute('axes', list(op.axis)),
])
return node
@classmethod
def _create_reduceOp(cls, op, op_t):
"""
get a onnx node from singa ReduceSum, ReduceMean, ReduceMax, ReduceMin, etc.
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
node.attribute.extend([
helper.make_attribute('axes', list(op.axes)),
helper.make_attribute('keepdims', op.keepdims),
])
return node
@classmethod
def _create_dropout(cls, op, op_t):
"""
get a onnx node from singa Dropout operator
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
node.attribute.extend([
helper.make_attribute('ratio', op.ratio),
])
return node
@classmethod
def _create_constantOfShape(cls, op, op_t):
"""
get a onnx node from singa ConstantOfShape operator
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
tensor_type = TensorProto.FLOAT if isinstance(
op.value, float) else TensorProto.INT32
tensor_value = helper.make_tensor("value", tensor_type, [1], [op.value])
node.attribute.extend([
helper.make_attribute('value', tensor_value),
])
return node
@classmethod
def _create_transpose(cls, op, op_t):
"""
get a onnx node from singa Transpose operator
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
node.attribute.extend([
helper.make_attribute('perm', op.perm),
])
return node
@classmethod
def _create_clip(cls, op, op_t):
"""
get a onnx node from singa clip operator
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
if op.min is not None:
node.input.append(op.name + ":min")
else:
node.input.append("")
if op.max is not None:
node.input.append(op.name + ":max")
else:
node.input.append("")
return node
@classmethod
def _create_hardsigmoid(cls, op, op_t):
"""
get a onnx node from singa HardSigmoid operator
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
node.attribute.extend([
helper.make_attribute('alpha', op.alpha),
helper.make_attribute('beta', op.gamma),
])
return node
@classmethod
def _create_elu(cls, op, op_t):
"""
get a onnx node from singa elu operator
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
node.attribute.extend([
helper.make_attribute('alpha', op.alpha),
])
return node
@classmethod
def _create_selu(cls, op, op_t):
"""
get a onnx node from singa SeLU operator
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
node.attribute.extend([
helper.make_attribute('alpha', op.alpha),
helper.make_attribute('gamma', op.gamma),
])
return node
@classmethod
def _create_reshape(cls, op, op_t):
"""
get a onnx node from singa Concat operator
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
# make the shape node
# because the reshape in singa does not provide its shape as input tensor
shape_node_name = op.name + ":shape"
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
node.input.extend([shape_node_name])
return node
@classmethod
def _create_concat(cls, op, op_t):
"""
get a onnx node from singa Concat operator
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
node.attribute.extend([
helper.make_attribute('axis', op.axis),
])
return node
@classmethod
def _create_softmax(cls, op, op_t):
"""
get a onnx node from singa Concat operator
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
node.attribute.extend([
helper.make_attribute('axis', op.axis),
])
return node
@classmethod
def _create_flatten(cls, op, op_t):
"""
get a onnx node from singa flatten operator
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
node.attribute.extend([
helper.make_attribute('axis', op.axis),
])
return node
@classmethod
def _create_gemm(cls, op, op_t):
"""
get a onnx node from singa gemm operator
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
node.attribute.extend([
helper.make_attribute('alpha', float(op.alpha)),
helper.make_attribute('beta', float(op.beta)),
helper.make_attribute('transA', op.transA),
helper.make_attribute('transB', op.transB),
])
return node
@classmethod
def _create_batchnorm(cls, op, op_t):
"""
get a onnx node from singa _BatchNorm2d operator
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
# first, we init batchnorm node
epsilon = 1e-5 # the epsilon value used in singa
bn_node = cls._common_singa_tensor_to_onnx_node(op, op_t)
bn_node.attribute.extend([
helper.make_attribute('momentum', op.handle.factor),
helper.make_attribute('epsilon', epsilon),
])
# then we add nodes of scal, bias, mean, var
nodes = []
running_values = {"mean": op.running_mean, "var": op.running_var}
for tmp_name, running_value in running_values.items():
node_name = op.name + ":" + tmp_name
bn_node.input.append(node_name)
nodes.append(bn_node)
return nodes
@classmethod
def _create_conv_pool(cls, op, op_t):
"""
get a onnx node from singa _Conv2d and _Pooling2d operator
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
node = cls._common_singa_tensor_to_onnx_node(op, op_t)
k = [op.handle.kernel_h, op.handle.kernel_w]
s = [op.handle.stride_h, op.handle.stride_w]
oddp = op.odd_padding
p = [
op.handle.pad_h + oddp[0],
op.handle.pad_w + oddp[1],
op.handle.pad_w + oddp[2],
op.handle.pad_h + oddp[3],
]
node.attribute.extend([
helper.make_attribute('kernel_shape', k),
helper.make_attribute('pads', p),
helper.make_attribute('strides', s),
])
if cls._get_singa_op_type(op) == '_Conv2d':
node.op_type = cls._rename_operators.get('_Conv2d')
node.attribute.extend([
helper.make_attribute('group', op.handle.group),
helper.make_attribute('auto_pad', 'NOTSET'),
])
elif op.handle.is_max_pooling:
node.op_type = cls._rename_operators.get('MaxPool2d')
else:
node.op_type = cls._rename_operators.get('AvgPool2d')
return node
@classmethod
def _get_singa_op_inputs_outputs(cls, op):
"""
get inputs and outputs from a given operator
Args:
op: a given operator
Returns:
inputs and outputs of the op
"""
outputs = [op.output_name(idx) for _, idx in op.y_id2idx.items()]
inputs = [
srcop.output_name(srcop.y_id2idx[yid])
for (srcop, yid, _, _) in op.src
]
return inputs, outputs
@classmethod
def _get_singa_op_type(cls, op):
"""
get the operator type from a given operator
Args:
op: a given operator
Returns:
operator type
"""
return type(op).__name__
@classmethod
def _special_handle_batchnorm(cls, op, X, W):
"""
hanlde the special operators
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
onnx tensor list
"""
# for singa, x, scale, bias is input
# and mean and var is attribute
# so we add the mean and var to W
tensor_list = []
append_inputs = {"mean": op.running_mean, "var": op.running_var}
for tmp_name, append_input in append_inputs.items():
node_name = op.name + ":" + tmp_name
append_input = tensor.to_numpy(tensor.from_raw_tensor(append_input))
tensor_list.append(numpy_helper.from_array(append_input, node_name))
return tensor_list
@classmethod
def _special_handle_reshape(cls, op, X, W):
"""
hanlde the special operators
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
onnx tensor list
"""
node_name = op.name + ":shape"
return [
numpy_helper.from_array(np.array(op.shape, dtype=np.int64),
node_name)
]
@classmethod
def _special_handle_clip(cls, op, X, W):
"""
hanlde the special operators
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
onnx tensor list
"""
tensor_list = []
# clip add min and max
append_inputs = {"min": op.min, "max": op.max}
for tmp_name, append_input in append_inputs.items():
node_name = op.name + ":" + tmp_name
tensor_list.append(
helper.make_tensor(node_name, TensorProto.FLOAT, [],
[append_input]))
return tensor_list
@classmethod
def _special_handle_slice(cls, op, X, W):
"""
hanlde the special operators
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
onnx tensor list
"""
tensor_list = []
# slice add starts, ends, axes, steps
append_inputs = {
"starts": op.starts,
"ends": op.ends,
"axes": op.axes,
"steps": op.steps,
}
for tmp_name, append_input in append_inputs.items():
node_name = op.name + ":" + tmp_name
tensor_list.append(
numpy_helper.from_array(np.array(append_input), node_name))
return tensor_list
@classmethod
def _special_handle_gather(cls, op, X, W):
"""
hanlde the special operators
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
onnx tensor list
"""
tensor_list = []
append_inputs = {
"indices": op.indices,
}
for tmp_name, append_input in append_inputs.items():
node_name = op.name + ":" + tmp_name
tensor_list.append(
numpy_helper.from_array(np.array(append_input), node_name))
return tensor_list
@classmethod
def _special_handle_tile(cls, op, X, W):
"""
hanlde the special operators
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
onnx tensor list
"""
tensor_list = []
append_inputs = {
"repeats": op.repeats,
}
for tmp_name, append_input in append_inputs.items():
node_name = op.name + ":" + tmp_name
tensor_list.append(
numpy_helper.from_array(np.array(append_input), node_name))
return tensor_list
@classmethod
def _special_handle_onehot(cls, op, X, W):
"""
hanlde the special operators
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
onnx tensor list
"""
tensor_list = []
append_inputs = {
"depth": op.depth,
"values": op.values,
}
for tmp_name, append_input in append_inputs.items():
node_name = op.name + ":" + tmp_name
tensor_list.append(
numpy_helper.from_array(np.array(append_input), node_name))
return tensor_list
@classmethod
def handle_special_ops(cls, op, X, W):
"""
hanlde the special operators,
because the inputs of batchnorm and reshape are differnet with onnx
we need to add these inputs into onnx model mannully
Args:
op: a given operator
Args:
X: onnx input list
Args:
X: onnx weight list
Returns: the onnx node
"""
optype = cls._get_singa_op_type(op)
translator = getattr(cls, cls._unhandled_operators[optype])
tensor_list = translator(op, X, W)
for tensor in tensor_list:
X.append(
helper.make_tensor_value_info(tensor.name, tensor.data_type,
tensor.dims))
W.append(tensor)
# return X, W
@classmethod
def _common_singa_tensor_to_onnx_node(cls, op, op_t):
"""
get a onnx node from singa operator, prepare its type, inputs and outputs
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns: the onnx node
"""
node_def = NodeProto()
node_def.name = op.name
optype = cls._get_singa_op_type(op)
node_def.op_type = cls._rename_operators.get(optype, optype)
inputs, outputs = cls._get_singa_op_inputs_outputs(op)
node_def.input.extend(inputs)
node_def.output.extend(outputs)
return node_def
@classmethod
def singa_op_to_onnx_node(cls, op, op_t):
"""
get a onnx node from singa operator
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
the onnx node
"""
optype = cls._get_singa_op_type(op)
# wether the operator needs special handler
if optype in cls._special_operators:
translator = getattr(cls, cls._special_operators[optype])
else:
translator = cls._common_singa_tensor_to_onnx_node
nodes = translator(op, op_t)
if not isinstance(nodes, collections.Iterable):
nodes = [nodes]
nodes = [node for node in nodes if node is not None]
return nodes
@classmethod
def singa_to_onnx_graph(cls, inputs, y, model_name="sonnx"):
"""
get onnx model from singa computational graph
Args:
inputs: a list of input tensors (each is initialized with a name)
Args:
y: a list of tensors, usually the outputs of the graph
Returns:
the onnx model
"""
assert len(
y
) == 1, "Not support multiple output now." # assume there is only one output
y = y[0]
graph_def = GraphProto()
graph_def.name = model_name
topol, ws, ins = utils.post_order_recursive(y.creator, y)
# prepare the input
X = []
for op_name, op_t in ins.items():
op_t = inputs.pop(0)
dtype = TensorProto.INT32 if op_t.dtype == tensor.int32 else TensorProto.FLOAT
X.append(helper.make_tensor_value_info(op_name, dtype, op_t.shape))
# prepare the output
y_optype = cls._get_singa_op_type(y.creator)
if y_optype in cls._bool_operators:
y_dtype = cls._bool_operators[y_optype]
elif y.dtype == tensor.int32:
y_dtype = TensorProto.INT32
else:
y_dtype = TensorProto.FLOAT
Y = [helper.make_tensor_value_info(y.name, y_dtype, y.shape)]
# prepare the weight
W = []
for op_name, op_t in ws.items():
dtype = TensorProto.INT32 if op_t.dtype == tensor.int32 else TensorProto.FLOAT
wt = tensor.to_numpy(op_t)
wt = numpy_helper.from_array(wt)
wt.name = op_name
W.append(wt)
X.append(helper.make_tensor_value_info(op_name, dtype, op_t.shape))
# iterate the node graph
for op_name, op in topol.items():
optype = cls._get_singa_op_type(op)
if optype in cls._unhandled_operators:
cls.handle_special_ops(op, X, W)
graph_def.node.extend(cls.singa_op_to_onnx_node(op, op_t))
graph_def.input.extend(X)
graph_def.output.extend(Y)
graph_def.initializer.extend(W)
return graph_def
@classmethod
def singa_to_onnx_model(cls, inputs, y, model_name="sonnx"):
"""
get onnx model from singa computational graph
Args:
inputs: a list of input tensors (each is initialized with a name)
Args:
y: a list of tensors, usually the outputs of the graph
Returns:
the onnx model
"""
opset_id = OperatorSetIdProto()
opset_id.version = cls._target_opset_version
model = helper.make_model(cls.singa_to_onnx_graph(inputs,
y,
model_name="sonnx"),
producer_name='sonnx',
opset_imports=[opset_id])
model = optimizer.optimize(model)
checker.check_model(model)
return model
class OnnxNode(object):
"""
Reimplementation of NodeProto from ONNX, but in a form
more convenient to work with from Python.
"""
def __init__(self, node):
self.name = str(node.name).replace(".", "_")
self.op_type = str(node.op_type)
self.attrs = OnnxAttributes.from_onnx(node.attribute)
# inputs as attributes in singa