This repository has been archived by the owner on Feb 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 80
/
_operators.py
1993 lines (1763 loc) · 82.5 KB
/
_operators.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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import copy
from typing import Sequence, Callable, List, Tuple, Optional, Text, Any
from coremltools.models.neural_network import NeuralNetworkBuilder #type: ignore
from ._graph import Node, Graph
from coremltools.proto import NeuralNetwork_pb2 #type: ignore
from ._error_utils import ErrorHandling
INT_MAX = 2**30
'''
General common functions
'''
def _compare(a, b, encoding="utf8"): #type: (Text, Text, Text) -> bool
if isinstance(a, bytes):
a = a.decode(encoding)
if isinstance(b, bytes):
b = b.decode(encoding)
return a == b
def _is_input_shape_mapping_defined(node, graph): # type: (Node, Graph) -> Bool
if node.inputs[0] in graph.onnx_coreml_shape_mapping:
return True
else:
return False
def _update_shape_mapping_unchanged(node, graph, err): # type: (Node, Graph, ErrorHandling) -> None
if _is_input_shape_mapping_defined(node, graph):
graph.onnx_coreml_shape_mapping[node.outputs[0]] = graph.onnx_coreml_shape_mapping[node.inputs[0]]
def _convert_broadcast_op(builder, node, graph, err, mode): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling, Text) -> None
if node.op_type == 'Max' or node.op_type == 'Min' or node.op_type == 'Mean':
if len(node.inputs) == 1:
inputs = [node.inputs[0], node.inputs[0]]
else:
inputs = node.inputs
else:
inputs = node.inputs
if node.op_type == 'Sub':
builder.add_elementwise(
name=node.name + '_neg',
input_names=[inputs[1]],
output_name=inputs[1] + '_neg',
mode='MULTIPLY',
alpha=-1.0
)
builder.add_elementwise(
name=node.name,
input_names=[inputs[0], inputs[1] + '_neg'],
output_name=node.outputs[0],
mode=mode
)
else:
builder.add_elementwise(
name=node.name,
input_names=inputs,
output_name=node.outputs[0],
mode=mode
)
if _is_input_shape_mapping_defined(node, graph):
ranks = [len(graph.onnx_coreml_shape_mapping[input_]) for input_ in node.inputs]
max_id = np.argmax(np.array(ranks))
graph.onnx_coreml_shape_mapping[node.outputs[0]] = graph.onnx_coreml_shape_mapping[node.inputs[max_id]]
def _get_coreml_target_shape(target_shape, builder, node, graph, err):
# type: (Tuple[int, ...], NeuralNetworkBuilder, node, Graph, ErrorHandling) -> Optional[Tuple[int, ...]]
if len(target_shape) == 1: # (D,)
coreml_shape = (1, target_shape[0], 1, 1) # type: Optional[Tuple[int, ...]]
if _is_input_shape_mapping_defined(node, graph):
graph.onnx_coreml_shape_mapping[node.outputs[0]] = [2]
elif len(target_shape) == 2: # (S,D)
coreml_shape = target_shape + (1, 1)
if _is_input_shape_mapping_defined(node, graph):
graph.onnx_coreml_shape_mapping[node.outputs[0]] = [0,2]
elif len(target_shape) == 3: # (C,H,W)
coreml_shape = (
1, target_shape[0], target_shape[1], target_shape[2]
)
if _is_input_shape_mapping_defined(node, graph):
graph.onnx_coreml_shape_mapping[node.outputs[0]] = [2,3,4]
elif len(target_shape) == 4:
coreml_shape = target_shape
if _is_input_shape_mapping_defined(node, graph):
mapp = graph.onnx_coreml_shape_mapping[node.inputs[0]]
if mapp[0] == 1 and coreml_shape[0] == 1:
graph.onnx_coreml_shape_mapping[node.outputs[0]] = [1,2,3,4]
else:
graph.onnx_coreml_shape_mapping[node.outputs[0]] = [0,2,3,4]
elif len(target_shape) > 4:
#return err.unsupported_op_configuration(builder, node, graph, "Supports tensors not more than 4d") # type: ignore
diff = len(target_shape) - 4
if all([d == 1 for d in target_shape[:diff]]):
coreml_shape = target_shape[diff:]
else:
err.unsupported_op_configuration(builder, node, graph, "Tensors more than rank 4 are not supported") # type: ignore
if _is_input_shape_mapping_defined(node, graph):
if target_shape[0] == 1 and len(target_shape) == 5:
graph.onnx_coreml_shape_mapping[node.outputs[0]] = [1,0,2,3,4]
else:
return err.unsupported_op_configuration(builder, node, graph, "Supports tensors not more than 4d") # type: ignore
else:
coreml_shape = None
return coreml_shape
def _get_coreml_axis(axes, builder, node, graph, err): # type: (List[int], NeuralNetworkBuilder, node, Graph, ErrorHandling) -> Text
coreml_axis = ""
if node.inputs[0] not in graph.shape_dict:
return err.unsupported_op_configuration(builder, node, graph, "Failed to translate axis")
input_shape = graph.shape_dict[node.inputs[0]]
if len(input_shape) == 1: coreml_axis = 'C'
elif len(input_shape) == 2:
if len(axes) == 1 and axes[0] == 1: coreml_axis = 'C'
elif len(input_shape) == 3:
for ind in [['C','H','W'][i] for i in axes]: coreml_axis += ind
elif len(input_shape) == 4:
for ind in [['B','C','H','W'][i] for i in axes]: coreml_axis += ind
return coreml_axis
def _add_transpose_before_after(layer_func, # function for layer conversion
input_names, # List[str]
output_names, # List[str]
transpose_dims, # List[int]
**kwargs): # type: ignore
for i, input_ in enumerate(input_names):
kwargs['builder'].add_permute(name=kwargs['node'].name + '_input_transpose' + str(i),
dim=transpose_dims,
input_name=input_,
output_name=kwargs['node'].name + '_' + input_ + '_transpose')
new_input_names = [kwargs['node'].name + '_' + input_ + '_transpose' for input_ in input_names]
new_output_names = [output_ + '_transpose' for output_ in output_names]
layer_func(new_input_names, new_output_names, **kwargs)
for i, output_ in enumerate(output_names):
kwargs['builder'].add_permute(name=kwargs['node'].name + '_output_transpose' + str(i),
dim=transpose_dims,
input_name=output_ + '_transpose',
output_name=output_)
def _add_inner_product(input_names, output_names, **kwargs):
node = kwargs['node']
builder = kwargs['builder']
builder.add_inner_product(
name=node.name,
W=kwargs['W'],
b=kwargs['b'],
input_channels=kwargs['W'].shape[1],
output_channels=kwargs['W'].shape[0],
has_bias=kwargs['b'] is not None,
input_name=input_names[0],
output_name=output_names[0]
)
def _add_conv_like_op(add_func, get_params_func, params_dict,
builder, node, graph, err):
if node.inputs[0] in graph.onnx_coreml_shape_mapping:
mapp = graph.onnx_coreml_shape_mapping[node.inputs[0]]
r = len(mapp)
if not (r == 3 or r == 4):
return err.unsupported_op_configuration(builder, node, graph, "more than 4 axes not supported")
if r == 4:
if not (mapp == [1, 2, 3, 4] or mapp == [0, 2, 3, 4]):
return err.unsupported_op_configuration(builder, node, graph,
"error in axes alignment between onnx and coreml")
get_params_func(builder, node, graph, err, params_dict)
add_func(node.inputs, node.outputs, params_dict=params_dict, node=node, builder=builder, graph=graph, err=err)
if r == 3:
if mapp == [1, 2, 3]: # [B,C,H]
# spatial dimension: height
get_params_func(builder, node, graph, err, params_dict, axis='height')
add_func(node.inputs, node.outputs, params_dict=params_dict, node=node, builder=builder, graph=graph, err=err)
elif mapp == [1, 2, 4]: # [B,C,W]
# spatial dimension: width
get_params_func(builder, node, graph, err, params_dict, axis='width')
add_func(node.inputs, node.outputs, params_dict=params_dict, node=node, builder=builder, graph=graph, err=err)
elif mapp == [2, 3, 4]: # [C,H,W] in CoreML, but it represents [B,C,D] in ONNX.
# spatial dimension: sequence
get_params_func(builder, node, graph, err, params_dict, axis='width')
node.inputs = [node.inputs[0]]
_add_transpose_before_after(add_func,
node.inputs,
node.outputs,
[0, 2, 1, 3], # swap C & H
builder=builder, node=node, params_dict=params_dict, graph=graph, err=err)
elif mapp == [1, 2, 0]: # [B,C,S]
# spatial dimension: sequence
get_params_func(builder, node, graph, err, params_dict, axis='width')
node.inputs = [node.inputs[0]]
_add_transpose_before_after(add_func,
node.inputs,
node.outputs,
[3, 1, 2, 0],
builder=builder, node=node, params_dict=params_dict, graph=graph, err=err)
else:
return err.unsupported_op_configuration(builder, node, graph,
"error in axes alignment between onnx and coreml")
else:
get_params_func(builder, node, graph, err, params_dict)
add_func(node.inputs, node.outputs, params_dict=params_dict, builder=builder, node=node, graph=graph, err=err)
def _is_no_op(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> Bool
if node.inputs[0] in graph.shape_dict and node.outputs[0] in graph.shape_dict:
if graph.shape_dict[node.inputs[0]] == graph.shape_dict[node.outputs[0]]:
builder.add_activation(
name=node.name,
non_linearity='LINEAR',
input_name=node.inputs[0],
output_name=node.outputs[0],
params=[1.0, 0.0]
)
_update_shape_mapping_unchanged(node, graph, err)
return True
return False
'''
Layer conversion functions
'''
def _convert_abs(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None
builder.add_unary(
name=node.name,
input_name=node.inputs[0],
output_name=node.outputs[0],
mode='abs'
)
_update_shape_mapping_unchanged(node, graph, err)
def _convert_add(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None
# check if its equivalent to a bias layer
if len(node.inputs) > 1:
if node.inputs[1] in node.input_tensors:
second_input = np.squeeze(node.input_tensors[node.inputs[1]])
if len(second_input.shape) == 1:
builder.add_bias(name=node.name,
b=second_input,
input_name=node.inputs[0],
output_name=node.outputs[0],
shape_bias=[second_input.shape[0]])
return
'''
Supported shapes by CoreML 2.0 for broadcasting (-1 means it can be 1 or greater than 1):
(i.e. all of the outputs must have one of these shapes for broadcasting support)
- (S=-1,B=-1,1,1,1)
- (S=-1,B=-1,C,1,1)
- (S=-1,B=-1,1,H,W)
- (S=-1,B=-1,C,H,W)
Unsupported:
- (S=-1,B=-1,1,1,W)
- (S=-1,B=-1,1,H,1)
- (S=-1,B=-1,C,1,W)
- (S=-1,B=-1,C,H,1)
'''
_convert_broadcast_op(builder, node, graph, err, "ADD")
def _convert_sub(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None
_convert_broadcast_op(builder, node, graph, err, "ADD")
def _get_conv_params(builder, node, graph, err, params_dict, axis=None):
if 'dilations' not in node.attrs:
params_dict['dilations'] = [1, 1]
else:
if axis == 'height':
params_dict['dilations'] = node.attrs['dilations']
params_dict['dilations'].append(1)
elif axis == 'width':
params_dict['dilations'] = node.attrs['dilations']
params_dict['dilations'].insert(0, 1)
else:
params_dict['dilations'] = node.attrs['dilations']
if 'pads' not in node.attrs:
params_dict['pads'] = [0, 0, 0, 0]
else:
pads = node.attrs['pads']
if axis == 'height':
pads = [pads[0], 0, pads[1], 0]
elif axis == 'width':
pads = [0, pads[0], 0, pads[1]]
params_dict['pads'] = pads
if params_dict['is_deconv']:
params_dict['crops'] = copy.copy(params_dict['pads'])
params_dict['pads'] = [0, 0, 0, 0]
if sum(params_dict['crops']) == 0:
params_dict['is_post_crop'] = False
else:
params_dict['is_post_crop'] = True
if "kernel_shape" in node.attrs:
params_dict['kernel_shape'] = node.attrs["kernel_shape"]
else:
# w_shape is ONNX format shape
w_shape = params_dict["w_shape"]
if len(w_shape) == 4:
params_dict['kernel_shape'] = [w_shape[-2], w_shape[-1]]
else:
params_dict['kernel_shape'] = [w_shape[-1]]
params_dict['strides'] = node.attrs.get("strides", [1, 1] if axis is None else [1])
if axis == 'height':
if params_dict['W'] is not None:
params_dict['W'] = np.expand_dims(params_dict['W'], axis=-1)
params_dict['kernel_shape'].append(1)
params_dict['strides'].append(1)
elif axis == 'width':
if params_dict['W'] is not None:
params_dict['W'] = np.expand_dims(params_dict['W'], axis=-2)
params_dict['strides'].insert(0,1)
params_dict['kernel_shape'].insert(0,1)
params_dict['out_shape'] = None
params_dict['padding_type'] = 'valid'
params_dict['same_padding_asymmetry_mode'] = 'BOTTOM_RIGHT_HEAVY'
if params_dict['W'] is not None:
if not params_dict['is_deconv']:
params_dict['W'] = params_dict['W'].transpose((2, 3, 1, 0)) # type: ignore
else:
params_dict['W'] = params_dict['W'].transpose((2, 3, 0, 1)) # type: ignore
if "auto_pad" in node.attrs and \
not _compare(node.attrs["auto_pad"], 'VALID'):
params_dict['padding_type'] = 'same'
if _compare(node.attrs["auto_pad"], 'SAME_LOWER'):
params_dict['same_padding_asymmetry_mode'] = 'TOP_LEFT_HEAVY'
if params_dict['is_deconv']:
if 'output_shape' in node.attrs:
if axis == 'height':
params_dict['out_shape'] = (node.attrs['output_shape'][-1], 1) # (Hout, wout)
elif axis == 'width':
params_dict['out_shape'] = (1, node.attrs['output_shape'][-1]) # (Hout, wout)
else:
params_dict['out_shape'] = (node.attrs['output_shape'][-2], node.attrs['output_shape'][-1]) # (Hout, wout)
elif 'output_padding' in node.attrs:
post_pads = node.attrs['output_padding']
if sum(post_pads) != 0:
t = l = b = r = 0
if len(post_pads) == 1:
if axis == 'height':
b = post_pads[0]
elif axis == 'width':
r = post_pads[0]
else:
err.unsupported_op_configuration(builder, node, graph,
"length 1 output padding attribute only supported for 1D conv")
elif len(post_pads) == 2:
if axis == 'height':
b, r = post_pads
elif axis == 'width':
r, b = post_pads
else:
b, r = post_pads
elif len(post_pads) == 4:
b, r, t, l = post_pads
else:
return err.unsupported_op_configuration(builder, node, graph,
"Supports only length 1 or 2 or 4 output padding attribute")
def _update_crop_pad(idx, v):
if params_dict['crops'][idx] >= v:
params_dict['crops'][idx] -= v
else:
params_dict['pads'][idx] = v - params_dict['crops'][idx]
_update_crop_pad(0, t)
_update_crop_pad(1, l)
_update_crop_pad(2, b)
_update_crop_pad(3, r)
params_dict['is_post_crop'] = True if sum(params_dict['crops']) > 0 else False
params_dict['is_pre_pad'] = True if sum(params_dict['pads']) > 0 else False
def _add_conv(input_names, output_names, **kwargs):
params_dict = kwargs['params_dict']
node = kwargs['node']
builder = kwargs['builder']
graph = kwargs['graph']
err = kwargs['err']
W_shape = params_dict['w_shape']
output_name = output_names[0]
pre_padding_input_name = input_names[0]
if params_dict.get('is_post_crop', False):
output_name += '_conv_tranpose_post_crop'
if params_dict.get('is_pre_pad', False):
input_names[0] += '_conv_tranpose_pre_pad'
if params_dict['W'] is None and len(node.inputs) == 1:
return err.unsupported_op_configuration(builder, node, graph, "Kernel weight missing")
if params_dict['is_deconv']:
oc = W_shape[1] * params_dict['groups']
kc = W_shape[0]
else:
oc = W_shape[0]
kc = W_shape[1]
if params_dict.get('is_pre_pad', False):
builder.add_padding(
name=node.name + '_pre_pad', # type: ignore
left=params_dict['pads'][1],
right=params_dict['pads'][3],
top=params_dict['pads'][0],
bottom=params_dict['pads'][2],
input_name=pre_padding_input_name,
output_name=input_names[0],
value=0
)
builder.add_convolution(
name=node.name,
kernel_channels=kc,
output_channels=oc,
height=params_dict['kernel_shape'][0],
width=params_dict['kernel_shape'][1],
stride_height=params_dict['strides'][0],
stride_width=params_dict['strides'][1],
border_mode=params_dict['padding_type'],
same_padding_asymmetry_mode=params_dict['same_padding_asymmetry_mode'],
groups=params_dict['groups'],
W=params_dict['W'],
b=params_dict['bias'],
has_bias=params_dict['bias'] is not None,
is_deconv=params_dict['is_deconv'],
output_shape=params_dict['out_shape'],
input_name=input_names[0] if params_dict['W'] is not None else [input_names[0], input_names[1]],
output_name=output_name,
dilation_factors=params_dict['dilations'],
padding_top=params_dict['pads'][0],
padding_bottom=params_dict['pads'][2],
padding_left=params_dict['pads'][1],
padding_right=params_dict['pads'][3]
)
if params_dict.get('is_post_crop', False):
builder.add_crop(
name=node.name + '_post_crop', # type: ignore
left=params_dict['crops'][1],
right=params_dict['crops'][3],
top=params_dict['crops'][0],
bottom=params_dict['crops'][2],
input_names=[output_name],
output_name=output_names[0],
offset = [0,0]
)
def _convert_conv(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None
params_dict = dict()
#get weights for convolution
weight_name = node.inputs[1]
W = None
if weight_name in node.input_tensors:
W = node.input_tensors[weight_name]
params_dict['w_shape'] = W.shape
else:
err.missing_initializer(node,
"Weight tensor: {} not found in the graph initializer".format(weight_name,))
params_dict['W'] = W
params_dict['is_deconv'] = False
if node.op_type.endswith("Transpose"):
params_dict['is_deconv'] = True
bias = None
if len(node.inputs) > 2:
bias = node.input_tensors[node.inputs[2]]
params_dict['bias'] = bias
params_dict['groups'] = node.attrs.get("group", 1)
_add_conv_like_op(_add_conv, _get_conv_params, params_dict,
builder, node, graph, err)
# update map
_update_shape_mapping_unchanged(node, graph, err)
def _convert_relu(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None
builder.add_activation(
name=node.name,
non_linearity='RELU',
input_name=node.inputs[0],
output_name=node.outputs[0]
)
_update_shape_mapping_unchanged(node, graph, err)
def _convert_thresholdedrelu(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None
alpha = node.attrs.get('alpha', 1.0)
builder.add_activation(
name=node.name,
non_linearity='THRESHOLDEDRELU',
input_name=node.inputs[0],
output_name=node.outputs[0],
params = alpha
)
_update_shape_mapping_unchanged(node, graph, err)
def _convert_reshape(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None
shape = tuple(node.attrs.get('shape', ())) # type: (Tuple[int, ...])
if len(shape) == 0:
shape_name = node.inputs[1]
if shape_name in node.input_tensors:
shape = tuple(node.input_tensors[shape_name].astype(int)) #type: ignore
else:
err.missing_initializer(node,
"CoreML only supports Reshape layer when the target shape is static and known apriori")
# check if all entries in shape are 1/-1
is_flatten = True
for s in shape:
if abs(s) != 1:
is_flatten = False
break
if is_flatten:
builder.add_flatten(
name=node.name,
input_name=node.inputs[0],
output_name=node.outputs[0],
mode=0
)
if _is_input_shape_mapping_defined(node, graph):
mapp = graph.onnx_coreml_shape_mapping[node.inputs[0]]
if len(shape) == 4:
mapp_out = [mapp[0],2,3,4]
elif len(shape) == 3:
mapp_out = [2,3,4]
elif len(shape) == 2:
mapp_out = [mapp[0], 2]
elif len(shape) == 1:
mapp_out = [2]
else:
return err.unsupported_op_configuration(builder, node, graph,
"Supports only less than equal to 4d tensors")
graph.onnx_coreml_shape_mapping[node.outputs[0]] = mapp_out
return
new_shape = _get_coreml_target_shape(shape, builder, node, graph, err)
if new_shape is None:
return err.unsupported_op_configuration(builder, node, graph, "Unsupported shape for reshape")
builder.add_reshape(
name=node.name,
target_shape=new_shape,
mode=0,
input_name=node.inputs[0],
output_name=node.outputs[0]
)
def _convert_transpose(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None
if _is_input_shape_mapping_defined(node, graph):
mapp = graph.onnx_coreml_shape_mapping[node.inputs[0]]
r = len(mapp)
default_perm = list(range(r))
default_perm.reverse()
perm = node.attrs.get("perm", default_perm)
coreml_perm = []
for p in perm:
coreml_perm.append(mapp[p])
if 1 in mapp:
batch_index = mapp.index(1)
batch_index_new = coreml_perm.index(1)
if batch_index != batch_index_new:
return err.unsupported_op_configuration(builder, node, graph, "cannot transpose batch dimension")
perm_translated = []
for c in coreml_perm:
if c == 0:
perm_translated.append(c)
elif c == 1:
continue
else:
perm_translated.append(c-1)
perm_final = [-1,-1,-1,-1] # has to be of length 4 corresponding to [S,C,H,W]
for i in range(4):
if i not in perm_translated:
perm_final[i] = i
if perm_final.count(-1) != len(perm_translated):
return err.unsupported_op_configuration(builder, node, graph, "unable to translate transpose op to CoreML")
ctr = 0
for i, v in enumerate(perm_final):
if v == -1:
perm_final[i] = perm_translated[ctr]
ctr += 1
perm = tuple(perm_final)
else:
perm = node.attrs.get("perm", [0, 3, 2, 1])
if len(perm) > 4:
diff = len(perm) - 4
if all([perm[i] == i for i in range(diff)]):
perm = [p - diff for p in perm[diff:]]
else:
return err.unsupported_op_configuration(builder, node, graph, "Supports only 4d tensors")
elif len(perm) < 4:
diff = 4 - len(perm)
perm = [d for d in range(diff)] + [d + diff for d in perm]
perm = tuple(perm)
builder.add_permute(
name=node.name,
dim=perm,
input_name=node.inputs[0],
output_name=node.outputs[0]
)
_update_shape_mapping_unchanged(node, graph, err)
def _get_pool_params(builder, node, graph, err, params_dict, axis=None):
params_dict['pad_b'], params_dict['pad_l'], params_dict['pad_r'], params_dict['pad_t'] = 0, 0, 0, 0
params_dict['stride_height'], params_dict['stride_width'] = 1, 1
params_dict['padding_type'] = 'VALID'
params_dict['same_padding_asymmetry_mode'] = 'BOTTOM_RIGHT_HEAVY'
if params_dict['is_global']:
params_dict['height'], params_dict['width'] = 0, 0
params_dict['stride_height'], params_dict['stride_width'] = 1, 1
else:
kernel_shape = node.attrs["kernel_shape"]
if axis == 'height':
params_dict['height'] = kernel_shape[0]
elif axis == 'width':
params_dict['width'] = kernel_shape[0]
else:
params_dict['height'] = kernel_shape[0]
params_dict['width'] = kernel_shape[1]
pads = node.attrs.get('pads', None)
if pads:
if axis == 'height':
params_dict['pad_t'] = pads[0]
params_dict['pad_b'] = pads[1]
elif axis == 'width':
params_dict['pad_l'] = pads[0]
params_dict['pad_r'] = pads[1]
else:
params_dict['pad_t'] = pads[0]
params_dict['pad_l'] = pads[1]
params_dict['pad_b'] = pads[2]
params_dict['pad_r'] = pads[3]
strides = node.attrs.get('strides', [1, 1])
if axis == 'height':
params_dict['stride_height'] = strides[0]
elif axis == 'width':
params_dict['stride_width'] = strides[0]
else:
params_dict['stride_height'] = strides[0]
params_dict['stride_width'] = strides[1]
if "auto_pad" in node.attrs and \
not _compare(node.attrs["auto_pad"], 'VALID'):
params_dict['padding_type'] = 'SAME'
if _compare(node.attrs["auto_pad"], 'SAME_LOWER'):
params_dict['same_padding_asymmetry_mode'] = 'TOP_LEFT_HEAVY'
params_dict['exclude_pad_area'] = node.attrs.get('count_include_pad', 0) == 0
def _add_pool(input_names, output_names, **kwargs):
params_dict = kwargs['params_dict']
node = kwargs['node']
kwargs['builder'].add_pooling(
name=node.name,
height=params_dict.get('height',1),
width=params_dict.get('width',1),
stride_height=params_dict.get('stride_height',1),
stride_width=params_dict.get('stride_width',1),
layer_type=params_dict['layer_type'],
padding_type=params_dict['padding_type'],
exclude_pad_area=params_dict['exclude_pad_area'],
is_global=params_dict['is_global'],
input_name=input_names[0],
output_name=output_names[0],
padding_top=params_dict.get('pad_t',0),
padding_bottom=params_dict.get('pad_b',0),
padding_left=params_dict.get('pad_l',0),
padding_right=params_dict.get('pad_r',0),
same_padding_asymmetry_mode=params_dict['same_padding_asymmetry_mode']
)
def _convert_pool(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None
input_name = node.inputs[0]
output_name = node.outputs[0]
params_dict = dict()
params_dict['is_global'] = False
if node.op_type.startswith('Global'):
params_dict['is_global'] = True
if node.op_type.endswith("MaxPool"):
params_dict['layer_type'] = "MAX"
elif node.op_type.endswith("AveragePool"):
params_dict['layer_type'] = "AVERAGE"
else:
return err.unsupported_op_configuration(builder, node, graph, "Unsupported pool type")
if len(node.outputs) == 2:
return err.unsupported_op_configuration(builder, node, graph, "argmax with pool unsupported")
if 'ceil_mode' in node.attrs and node.attrs['ceil_mode'] == 1:
return err.unsupported_op_configuration(builder, node, graph, "ceil_mod=1 not supported")
if 'dilations' in node.attrs:
return err.unsupported_op_configuration(builder, node, graph, "dilations not supported")
_add_conv_like_op(_add_pool, _get_pool_params, params_dict,
builder, node, graph, err)
# update map
_update_shape_mapping_unchanged(node, graph, err)
def _convert_bn(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None
def add_bn(input_names, output_names, **kwargs):
kwargs['builder'].add_batchnorm(
name=node.name,
input_name=input_names[0],
output_name=output_names[0],
channels=kwargs['channels'][0],
gamma=kwargs['scale'],
beta=kwargs['bias'],
mean=kwargs['mean'],
variance=kwargs['var'],
epsilon=kwargs['epsilon'],)
if len(node.outputs) > 1:
return err.unsupported_op_configuration(builder, node, graph, "This converter only supports BatchNormalization with one output")
epsilon = node.attrs.get("epsilon", 1e-5)
channels = set()
for v in node.input_tensors.values():
channels.add(v.shape)
assert len(channels) == 1
channels = channels.pop()
scale = node.input_tensors[node.inputs[1]] if node.inputs[1] in node.input_tensors else \
np.ones(shape=channels, dtype=np.float32)
bias = node.input_tensors[node.inputs[2]] if node.inputs[2] in node.input_tensors else \
np.zeros(shape=channels, dtype=np.float32)
mean = node.input_tensors[node.inputs[3]] if node.inputs[3] in node.input_tensors else \
np.zeros(shape=channels, dtype=np.float32)
var = node.input_tensors[node.inputs[4]] if node.inputs[4] in node.input_tensors else \
np.ones(shape=channels, dtype=np.float32)
mapp = graph.onnx_coreml_shape_mapping.get(node.inputs[0], None)
if mapp == [2,3,4]:
_add_transpose_before_after(add_bn,
[node.inputs[0]],
node.outputs,
[0, 2, 1, 3],
builder=builder, node=node,scale=scale,bias=bias,mean=mean,var=var,epsilon=epsilon,channels=channels)
else:
builder.add_batchnorm(
name=node.name,
channels=channels[0],
gamma=scale,
beta=bias,
mean=mean,
variance=var,
input_name=node.inputs[0],
output_name=node.outputs[0],
epsilon=epsilon
)
_update_shape_mapping_unchanged(node, graph, err)
def _convert_instancenorm(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None
epsilon = node.attrs.get("epsilon", 1e-5)
scale = node.input_tensors[node.inputs[1]]
bias = node.input_tensors[node.inputs[2]]
builder.add_batchnorm(
name=node.name,
channels=scale.shape[0],
gamma=scale,
beta=bias,
compute_mean_var=True,
instance_normalization=True,
input_name=node.inputs[0],
output_name=node.outputs[0],
epsilon=epsilon
)
_update_shape_mapping_unchanged(node, graph, err)
def _convert_mul(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None
_convert_broadcast_op(builder, node, graph, err, "MULTIPLY")
def _convert_mean(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None
_convert_broadcast_op(builder, node, graph, err, "AVE")
def _convert_div(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None
builder.add_unary(name=node.name + '_inverse', #type: ignore
input_name=node.inputs[1],
output_name=node.inputs[1] + '_inverse',
mode='inverse')
builder.add_elementwise(
name=node.name,
input_names=[node.inputs[0], node.inputs[1] + '_inverse'],
output_name=node.outputs[0],
mode="MULTIPLY"
)
if _is_input_shape_mapping_defined(node, graph):
ranks = [len(graph.onnx_coreml_shape_mapping[input_]) for input_ in node.inputs]
max_id = np.argmax(np.array(ranks))
graph.onnx_coreml_shape_mapping[node.outputs[0]] = graph.onnx_coreml_shape_mapping[node.inputs[max_id]]
def _convert_leaky_relu(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None
alpha = node.attrs.get('alpha', 0.01)
builder.add_activation(
name=node.name,
non_linearity='LEAKYRELU',
params=[alpha],
input_name=node.inputs[0],
output_name=node.outputs[0]
)
_update_shape_mapping_unchanged(node, graph, err)
def _convert_concat(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None
def _add_concat(input_names, output_names, **kwargs):
kwargs['builder'].add_elementwise(
name=kwargs['node'].name,
input_names=input_names,
output_name=output_names[0],
mode=kwargs['mode']
)
axis = node.attrs.get("axis", 1)
parent_op_type = graph.blob_from_op_type.get(node.inputs[0], None)
if _is_input_shape_mapping_defined(node, graph):
mapp = graph.onnx_coreml_shape_mapping[node.inputs[0]]
caxis = mapp[axis]
if caxis == 0:
_add_concat(node.inputs, node.outputs, node=node, builder=builder, mode='SEQUENCE_CONCAT')
elif caxis == 2:
_add_concat(node.inputs, node.outputs, node=node, builder=builder, mode='CONCAT')
elif caxis == 3:
_add_transpose_before_after(_add_concat, node.inputs, node.outputs, [0,2,1,3], mode='CONCAT', node=node, builder=builder,)
elif caxis == 4:
_add_transpose_before_after(_add_concat, node.inputs, node.outputs, [0,3,2,1], mode='CONCAT', node=node, builder=builder,)
else:
return err.unsupported_op_configuration(builder, node, graph, "Concat not supported along batch axis")
else:
mode = None
first_input_shape = None
if node.inputs[0] in graph.shape_dict:
first_input_shape = graph.shape_dict[node.inputs[0]]
if parent_op_type in _SEQUENCE_LAYERS_REGISTRY and \
len(first_input_shape) == 3:
if axis == 0:
mode = 'SEQUENCE_CONCAT'
if axis == 2:
mode = 'CONCAT'
elif (len(first_input_shape) == 1 and axis == 0) or \
(len(first_input_shape) == 3 and axis == 0) or \
(len(first_input_shape) == 4 and axis == 1) or \
(len(first_input_shape) == 2 and axis == 1):
mode = 'CONCAT'
else: # shape info is not available. Fall back to guessing (ideally this should not happen)
if axis == 0:
mode = "SEQUENCE_CONCAT"
elif axis == 1:
mode = "CONCAT"
if mode is None:
return err.unsupported_op_configuration(builder, node, graph,
"Unsupported axis {} in input of shape".
format(axis, str(first_input_shape)))
_add_concat(node.inputs, node.outputs, node=node, builder=builder, mode=mode)
_update_shape_mapping_unchanged(node, graph, err)
def _convert_split(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None
def _add_split(input_names, output_names, **kwargs):
kwargs['builder'].add_split(
name=kwargs['node'].name,
input_name=input_names[0],
output_names=output_names
)
axis = node.attrs.get("axis", 0)
splits = node.attrs.get('split', None)
# check that splits are equal
if splits:
if splits.count(splits[0]) != len(splits):
return err.unsupported_op_configuration(builder, node, graph, 'Only Equal splits are supported')
if _is_input_shape_mapping_defined(node, graph):
mapp = graph.onnx_coreml_shape_mapping[node.inputs[0]]
if mapp[axis] == 2:
_add_split(node.inputs, node.outputs, node=node, builder=builder)
elif mapp[axis] == 0:
_add_transpose_before_after(_add_split, node.inputs, node.outputs, [1,0,2,3], builder=builder, node=node)
elif mapp[axis] == 3:
_add_transpose_before_after(_add_split, node.inputs, node.outputs, [0,2,1,3], builder=builder, node=node)
elif mapp[axis] == 4:
_add_transpose_before_after(_add_split, node.inputs, node.outputs, [0,3,2,1], builder=builder, node=node)
else:
err.unsupported_op_configuration(builder, node, graph, 'Split along Batch axis not supported')
else:
if not (axis == 0 or axis == 1):
return err.unsupported_op_configuration(builder, node, graph, "Unsupported axis {}".format(axis, ))
_add_split(node.inputs, node.outputs, node=node, builder=builder)
if _is_input_shape_mapping_defined(node, graph):
for out_ in node.outputs:
graph.onnx_coreml_shape_mapping[out_] = graph.onnx_coreml_shape_mapping[node.inputs[0]]
def _convert_argmax(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None
def _add_argmax_or_argmin(input_names, output_names, **kwargs):
input_name = input_names[0]
output_name = output_names[0]
if kwargs['node'].op_type == 'ArgMin':
kwargs['builder'].add_elementwise(name=kwargs['node'].name + '_multiply_minus_1', # type: ignore
input_names=[input_name],
output_name=input_name + '_multiply_minus_1',
mode='MULTIPLY',
alpha=-1)
input_name += '_multiply_minus_1'
kwargs['builder'].add_reduce(name=kwargs['node'].name,
input_name=input_name, output_name=output_name,
axis=kwargs['coreml_axis'],
mode='argmax')
'''
Conversion
'''
axis = node.attrs.get('axis', 0)
keepdims = node.attrs.get('keepdims', 1)
input_name = node.inputs[0]
output_name = node.outputs[0]
if _is_input_shape_mapping_defined(node, graph):
mapp = graph.onnx_coreml_shape_mapping[node.inputs[0]]
coreml_axis = mapp[axis]
coreml_axis_string = "C"
if coreml_axis == 1: # coreml_axis corresponds to the batch dimension
return err.unsupported_op_configuration(builder, node, graph,"Cannot apply operation along Batch axis")
if coreml_axis != 0:
coreml_axis_string = ['C','H','W'][coreml_axis-2]
_add_argmax_or_argmin([input_name], [output_name], builder=builder,node=node,coreml_axis=coreml_axis_string)
else: # coreml_axis corresponds to the sequence dimension
_add_transpose_before_after(_add_argmax_or_argmin,
[input_name],
[output_name],
[1,0,2,3],
builder=builder,node=node,coreml_axis=coreml_axis_string)
else:
coreml_axis_string = _get_coreml_axis([axis], builder, node, graph, err)
if coreml_axis_string not in ['C', 'H', 'W', 'HW', 'CHW']:
return err.unsupported_op_configuration(builder, node, graph,
"Unable to translate axes attribute to CoreML axis parameter for %s" % axis)
_add_argmax_or_argmin([input_name], [output_name], builder=builder, node=node, coreml_axis=coreml_axis_string)
'''
update output shape map
'''
if _is_input_shape_mapping_defined(node, graph):
mapp = graph.onnx_coreml_shape_mapping[node.inputs[0]]
if keepdims == 1:
graph.onnx_coreml_shape_mapping[node.outputs[0]] = mapp
else:
graph.onnx_coreml_shape_mapping[node.outputs[0]] = mapp[:axis] + mapp[axis+1:]
def _convert_reduce(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None
# CoreML reduction supported along: C, H, W, CHW, HW
def _add_reduce(input_names, output_names, **kwargs):
input_name = input_names[0]
output_name = output_names[0]
if 'add_log' in kwargs and kwargs['add_log']:
if kwargs['node'].op_type == 'ReduceLogSum':
output_name = output_names[0] + '_before_log'
kwargs['builder'].add_reduce(name=kwargs['node'].name + '_' + output_name,
input_name=input_name, output_name=output_name,