forked from alibaba/TinyNeuralNetwork
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aten.py
4052 lines (3047 loc) · 167 KB
/
aten.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
import warnings
import numpy as np
import torch
from tinynn.util.util import get_logger
from ...schemas.tflite import schema_generated as tfl_schema
from ...schemas.torch.aten_schema import *
from .. import CommonGraph
from .. import tflite as tfl
log = get_logger(__name__, 'INFO')
class AtenSignOperator(ATenSignSchema):
def parse(self, node, attrs, args, graph_converter):
super().parse(node, attrs, args, graph_converter)
self.run(node)
self.elementwise_unary(tfl.SignOperator, graph_converter)
class ATenLstmOperator(ATenLstmSchema):
def lstm_input_helper(
self, input_tensors, params_tensors, has_biases, param_start_index, input_start_index, layer_idx, suffix
):
hybrid = isinstance(self, ATenQuantizedLstmOperator)
weight_ih_slices = torch.chunk(params_tensors[param_start_index], 4, 0)
gates = ["input", "forget", "cell", "output"]
for idx, (weight_ih, gate) in enumerate(zip(weight_ih_slices, gates)):
input_tensors[input_start_index + idx] = self.create_attr_tensor(weight_ih, hybrid=hybrid)
weight_hh_slices = torch.chunk(params_tensors[param_start_index + 1], 4, 0)
for idx, (weight_hh, gate) in enumerate(zip(weight_hh_slices, gates)):
input_tensors[input_start_index + 4 + idx] = self.create_attr_tensor(weight_hh, hybrid=hybrid)
if has_biases:
assert params_tensors[param_start_index + 2].dtype == torch.float32
assert params_tensors[param_start_index + 3].dtype == torch.float32
fused_bias = params_tensors[param_start_index + 2] + params_tensors[param_start_index + 3]
fused_bias_slices = torch.chunk(fused_bias, 4, 0)
for idx, (bias, gate) in enumerate(zip(fused_bias_slices, gates)):
input_tensors[input_start_index + 11 + idx] = self.create_attr_tensor(bias)
else:
bias_shape = input_tensors[input_start_index + 3].shape[:1]
for idx, gate in enumerate(gates):
bias = torch.zeros(bias_shape, dtype=torch.float32)
input_tensors[input_start_index + 11 + idx] = self.create_attr_tensor(bias)
def lstm_hidden_state_helper(
self,
input_tensors,
hidden_state_tensors,
hidden_state_index,
input_index,
num_directions,
direction_idx,
num_layers,
layer_idx,
suffix,
state_type,
tf_state_tensors,
):
hidden_state_tensor = hidden_state_tensors[hidden_state_index]
tf_state_tensor = tf_state_tensors[hidden_state_index]
assert hidden_state_tensor.dim() == 3
slice_idx = layer_idx * num_directions + direction_idx
if tf_state_tensor[slice_idx] is None:
input_tensors[input_index] = self.create_attr_tensor(hidden_state_tensor[slice_idx])
input_tensors[input_index].is_variable = True
else:
assert self.unroll_rnn, "Input state tensors are only supported when unroll_rnn=True is specified"
input_tensors[input_index] = tf_state_tensor[slice_idx]
def parse_common(
self,
input_tensor,
hidden_state_tensors,
params_tensors,
has_biases,
num_layers,
dropout,
is_train,
bidirectional,
batch_first,
graph_converter,
):
assert is_train in (False, 0)
expected_num_params = 2 * num_layers
params_step = 2
if has_biases:
expected_num_params *= 2
params_step *= 2
if bidirectional:
expected_num_params *= 2
assert (
len(params_tensors) == expected_num_params
), f'num of params in LSTM is wrong. got: {len(params_tensors)}, expected: {expected_num_params}'
num_input_tensors = 24
num_directions = 1
state_start_index = 18
if bidirectional:
num_input_tensors *= 2
num_directions *= 2
state_start_index = 35
suffixes = ["_fw", "_bw"]
state_kinds = ["act", "cell"]
param_start_indices = [0, params_step]
input_start_indices = [1, 18]
ops = []
names = graph_converter.get_list_expanded_names(self.input_names[1])
tf_in_state_tensors = [graph_converter.tensor_map.get(n, None) for n in names]
tf_state_tensors = []
unpacked_tensors = {}
for t in tf_in_state_tensors:
if t is not None and self.unroll_rnn:
tensors = [
self.create_transform_tensor(np.squeeze(x, 0))
for x in np.split(t.tensor, num_directions * num_layers, 0)
]
tf_state_tensors.append(tensors)
ops.append(tfl.UnpackOperator([t], tensors, len(tensors), 0))
else:
tf_state_tensors.append([None] * num_directions * num_layers)
current_input = self.find_or_create_input(0, graph_converter)
lstm_output = self.to_tfl_tensors(self.output_names[:1], self.output_tensors[:1])[0]
params_offset = 0
tf_out_state_tensors = [[], []]
for layer_idx in range(num_layers):
inputs = [current_input] + [tfl.OptionalTensorInstance] * (num_input_tensors - 1)
for direction_idx in range(num_directions):
self.lstm_input_helper(
inputs,
params_tensors,
has_biases,
params_offset + param_start_indices[direction_idx],
input_start_indices[direction_idx],
layer_idx,
suffixes[direction_idx],
)
for direction_idx in range(num_directions):
for state_kind_idx in range(len(state_kinds)):
self.lstm_hidden_state_helper(
inputs,
hidden_state_tensors,
state_kind_idx,
state_start_index + direction_idx * num_directions + state_kind_idx,
num_directions,
direction_idx,
num_layers,
layer_idx,
suffixes[direction_idx],
state_kinds[state_kind_idx],
tf_state_tensors,
)
if layer_idx == num_layers - 1:
layer_output = lstm_output
else:
output_shape = list(input_tensor.shape)
output_shape[-1] = inputs[6].shape[1] * num_directions
layer_output = self.create_transform_tensor(np.empty(output_shape, dtype=inputs[0].dtype))
outputs = [layer_output]
if self.unroll_rnn:
ts_axis = 1 if batch_first else 0
num_timestep = inputs[0].shape[ts_axis]
if inputs[0].name in unpacked_tensors:
input_ts = unpacked_tensors[inputs[0].name]
else:
input_ts = [
self.create_transform_tensor(np.squeeze(x, ts_axis))
for x in np.split(inputs[0].tensor, num_timestep, ts_axis)
]
ops.append(tfl.UnpackOperator([inputs[0]], input_ts, num_timestep, ts_axis))
strides = [1, -1]
output_ts = []
for direction_idx in range(num_directions):
input_start = input_start_indices[direction_idx]
if not self.separated_rnn_gate_calc:
w_i = self.create_attr_tensor(
np.concatenate([inputs[x].tensor for x in range(input_start, input_start + 4)], 0),
quantization=inputs[input_start].quantization,
)
w_r = self.create_attr_tensor(
np.concatenate([inputs[x].tensor for x in range(input_start + 4, input_start + 8)], 0),
quantization=inputs[input_start + 4].quantization,
)
b_i = self.create_attr_tensor(
np.concatenate([inputs[x].tensor for x in range(input_start + 11, input_start + 15)], 0)
)
b_r = self.create_attr_tensor(np.zeros_like(b_i.tensor))
else:
w_i_list = [inputs[x] for x in range(input_start, input_start + 4)]
w_r_list = [inputs[x] for x in range(input_start + 4, input_start + 8)]
b_i_list = [inputs[x] for x in range(input_start + 11, input_start + 15)]
b_r_list = [self.create_attr_tensor(np.zeros_like(b_i.tensor)) for b_i in b_i_list]
state_start = state_start_index + direction_idx * num_directions
h = inputs[state_start]
c = inputs[state_start + 1]
stride = strides[direction_idx]
# Skip some computations for the first timestep
compute_h = h.buffer is None or np.any(h.tensor)
compute_c = c.buffer is None or np.any(c.tensor)
stacked_hs = []
for i, t in enumerate(input_ts[::stride]):
if not self.separated_rnn_gate_calc:
input_mm = self.create_transform_tensor(
np.matmul(t.tensor, np.transpose(w_i.tensor, [1, 0])) + b_i.tensor
)
ops.append(tfl.FullyConnectedOperator([t, w_i, b_i], [input_mm]))
else:
input_mm_list = []
for j, (w_i, b_i) in enumerate(zip(w_i_list, b_i_list)):
if j == 1 and i == 0 and not compute_c:
input_mm_list.append(None)
continue
input_mm = self.create_transform_tensor(
np.matmul(t.tensor, np.transpose(w_i.tensor, [1, 0])) + b_i.tensor
)
ops.append(tfl.FullyConnectedOperator([t, w_i, b_i], [input_mm]))
input_mm_list.append(input_mm)
if i != 0 or compute_h:
if not self.separated_rnn_gate_calc:
hidden_mm = self.create_transform_tensor(
np.matmul(h.tensor, np.transpose(w_r.tensor, [1, 0])) + b_r.tensor
)
ops.append(tfl.FullyConnectedOperator([h, w_r, b_r], [hidden_mm]))
add_out = self.create_transform_tensor(input_mm.tensor + hidden_mm.tensor)
ops.append(tfl.AddOperator([input_mm, hidden_mm], [add_out]))
else:
hidden_mm_list = []
for j, (w_r, b_r) in enumerate(zip(w_r_list, b_r_list)):
if j == 1 and i == 0 and not compute_c:
hidden_mm_list.append(None)
continue
hidden_mm = self.create_transform_tensor(
np.matmul(h.tensor, np.transpose(w_r.tensor, [1, 0])) + b_r.tensor
)
ops.append(tfl.FullyConnectedOperator([h, w_r, b_r], [hidden_mm]))
hidden_mm_list.append(hidden_mm)
gate_outs = []
for input_mm, hidden_mm in zip(input_mm_list, hidden_mm_list):
if input_mm is not None and hidden_mm is not None:
add_out = self.create_transform_tensor(input_mm.tensor + hidden_mm.tensor)
ops.append(tfl.AddOperator([input_mm, hidden_mm], [add_out]))
gate_outs.append(add_out)
else:
if not self.separated_rnn_gate_calc:
add_out = input_mm
else:
gate_outs = input_mm_list
if not self.separated_rnn_gate_calc:
gate_outs = [self.create_transform_tensor(t) for t in np.split(add_out.tensor, 4, 1)]
split_dim_tensor = self.create_attr_tensor(np.array([1], dtype='int32'))
ops.append(tfl.SplitOperator([split_dim_tensor, add_out], gate_outs, 4))
gate_i = self.create_transform_tensor(
torch.sigmoid(torch.from_numpy(gate_outs[0].tensor)).numpy()
)
ops.append(tfl.LogisticOperator([gate_outs[0]], [gate_i]))
if i != 0 or compute_c:
gate_f = self.create_transform_tensor(
torch.sigmoid(torch.from_numpy(gate_outs[1].tensor)).numpy()
)
ops.append(tfl.LogisticOperator([gate_outs[1]], [gate_f]))
gate_g = self.create_transform_tensor(np.tanh(gate_outs[2].tensor))
ops.append(tfl.TanhOperator([gate_outs[2]], [gate_g]))
gate_o = self.create_transform_tensor(
torch.sigmoid(torch.from_numpy(gate_outs[3].tensor)).numpy()
)
ops.append(tfl.LogisticOperator([gate_outs[3]], [gate_o]))
if i != 0 or compute_c:
c_left = self.create_transform_tensor(gate_f.tensor * c.tensor)
ops.append(tfl.MulOperator([gate_f, c], [c_left]))
c_right = self.create_transform_tensor(gate_i.tensor * gate_g.tensor)
ops.append(tfl.MulOperator([gate_i, gate_g], [c_right]))
if i != 0 or compute_c:
c = self.create_transform_tensor(c_left.tensor + c_right.tensor)
ops.append(tfl.AddOperator([c_left, c_right], [c]))
else:
c = c_right
c_act = self.create_transform_tensor(np.tanh(c.tensor))
ops.append(tfl.TanhOperator([c], [c_act]))
h = self.create_transform_tensor(gate_o.tensor * c_act.tensor)
ops.append(tfl.MulOperator([gate_o, c_act], [h]))
stacked_hs.append(h)
tf_out_state_tensors[0].append(h)
tf_out_state_tensors[1].append(c)
output_ts.extend(stacked_hs[::stride])
if bidirectional:
# For bidirectional LSTMs, the forward output tensors and the backward output tensors are
# concatenated before we pack them together
fw_out = self.create_transform_tensor(
np.stack([x.tensor for x in output_ts[:num_timestep]], ts_axis)
)
ops.append(tfl.PackOperator(output_ts[:num_timestep], [fw_out], num_timestep, axis=ts_axis))
bw_out = self.create_transform_tensor(
np.stack([x.tensor for x in output_ts[num_timestep:]], ts_axis)
)
ops.append(tfl.PackOperator(output_ts[num_timestep:], [bw_out], num_timestep, axis=ts_axis))
ops.append(tfl.ConcatenationOperator([fw_out, bw_out], outputs, axis=2))
elif layer_idx != num_layers - 1:
# Reusing unpacked tensors for the logic in the next layer
unpacked_tensors[outputs[0].name] = output_ts
else:
# For the last layer, we have to pack the together
ops.append(tfl.PackOperator(output_ts, outputs, len(output_ts), axis=ts_axis))
elif bidirectional:
if not self.map_bilstm_to_lstm:
ops.append(
tfl.BidirectionalSequenceLstmOperator(
inputs,
outputs,
fusedActivationFunction=tfl_schema.ActivationFunctionType.TANH,
timeMajor=not batch_first,
mergeOutputs=True,
asymmetricQuantizeInputs=self.hybrid_asymmetric_inputs,
)
)
else:
fw_i_end = input_start_indices[-1]
fw_s_start = state_start_index
fw_s_end = state_start_index + len(state_kinds)
fw_pad = num_input_tensors // 2 - fw_s_end
fw_lstm_inputs = (
inputs[:fw_i_end] + inputs[fw_s_start:fw_s_end] + [tfl.OptionalTensorInstance] * fw_pad
)
fw_out, bw_out = [
self.create_transform_tensor(t, quantization=outputs[0].quantization)
for t in np.split(outputs[0].tensor, 2, -1)
]
ops.append(
tfl.UnidirectionalSequenceLstmOperator(
fw_lstm_inputs,
[fw_out],
fusedActivationFunction=tfl_schema.ActivationFunctionType.TANH,
timeMajor=not batch_first,
asymmetricQuantizeInputs=self.hybrid_asymmetric_inputs,
)
)
time_dim = 1 if batch_first else 0
bw_in = self.create_transform_tensor(np.flip(current_input.tensor, time_dim))
bw_dim = self.create_attr_tensor(np.array([time_dim], dtype='int32'))
ops.append(tfl.ReverseV2Operator([current_input, bw_dim], [bw_in]))
bw_raw_out = self.create_transform_tensor(np.flip(bw_out.tensor, time_dim))
bw_o_start = input_start_indices[-1]
bw_o_end = state_start_index
bw_s_start = state_start_index + len(state_kinds)
bw_s_end = state_start_index + len(state_kinds) * num_directions
bw_pad = num_input_tensors // 2 - bw_s_end
bw_lstm_inputs = (
[bw_in]
+ inputs[bw_o_start:bw_o_end]
+ inputs[bw_s_start:bw_s_end]
+ [tfl.OptionalTensorInstance] * bw_pad
)
ops.append(
tfl.UnidirectionalSequenceLstmOperator(
bw_lstm_inputs,
[bw_raw_out],
fusedActivationFunction=tfl_schema.ActivationFunctionType.TANH,
timeMajor=not batch_first,
asymmetricQuantizeInputs=self.hybrid_asymmetric_inputs,
)
)
ops.append(tfl.ReverseV2Operator([bw_raw_out, bw_dim], [bw_out]))
ops.append(tfl.ConcatenationOperator([fw_out, bw_out], outputs, axis=2))
else:
ops.append(
tfl.UnidirectionalSequenceLstmOperator(
inputs,
outputs,
fusedActivationFunction=tfl_schema.ActivationFunctionType.TANH,
timeMajor=not batch_first,
asymmetricQuantizeInputs=self.hybrid_asymmetric_inputs,
)
)
current_input = outputs[0]
params_offset += params_step * num_directions
if self.unroll_rnn:
state_outputs = self.to_tfl_tensors(self.output_names[1:], self.output_tensors[1:])
for i, (orig, new) in enumerate(zip(tf_in_state_tensors, tf_out_state_tensors)):
if orig is not None:
pack_op = tfl.PackOperator(new, state_outputs[i : i + 1], len(new), 0)
pack_op.extra_hints['warn_on_unused'] = False
ops.append(pack_op)
else:
common_names = set(self.output_names[1:]) & set(graph_converter.outputs)
assert len(common_names) == 0, (
f"Please remove the LSTM state outputs ({common_names}) from the model. Alternatively, you can try"
" unroll_rnn=True"
)
for op in ops:
graph_converter.add_operator(op)
def parse(self, node, attrs, args, graph_converter):
super().parse(node, attrs, args, graph_converter)
self.run(node)
input_tensor, hidden_state_tensors, params_tensors = self.input_tensors[:3]
has_biases, num_layers, dropout, is_train, bidirectional, batch_first = self.input_tensors[3:]
self.parse_common(
input_tensor,
hidden_state_tensors,
params_tensors,
has_biases,
num_layers,
dropout,
is_train,
bidirectional,
batch_first,
graph_converter,
)
class ATenGruOperator(ATenGruSchema):
def gru_input_helper(
self, input_tensors, params_tensors, has_biases, param_start_index, input_start_index, layer_idx, suffix
):
wir, wiz, win = torch.chunk(params_tensors[param_start_index], 3, 0)
whr, whz, whn = torch.chunk(params_tensors[param_start_index + 1], 3, 0)
wr = torch.cat((wir, whr), -1)
wz = torch.cat((wiz, whz), -1)
# [2*n_output, n_input+n_output]
input_tensors[input_start_index] = self.create_attr_tensor(torch.cat((wr, wz), 0))
# [n_output, n_input+n_output]
input_tensors[input_start_index + 2] = self.create_attr_tensor(torch.cat((win, whn), -1))
w_i_list = [self.create_attr_tensor(wir), self.create_attr_tensor(wiz), self.create_attr_tensor(win)]
w_r_list = [self.create_attr_tensor(whr), self.create_attr_tensor(whz), self.create_attr_tensor(whn)]
if has_biases:
assert params_tensors[param_start_index + 2].dtype == torch.float32
assert params_tensors[param_start_index + 3].dtype == torch.float32
bir, biz, bin = torch.chunk(params_tensors[param_start_index + 2], 3, 0)
bhr, bhz, bhn = torch.chunk(params_tensors[param_start_index + 3], 3, 0)
br = torch.cat((bir, bhr), -1)
bz = torch.cat((biz, bhz), -1)
input_tensors[input_start_index + 1] = self.create_attr_tensor(torch.cat((br, bz), -1)) # [2*n_output]
input_tensors[input_start_index + 3] = self.create_attr_tensor(torch.cat((bin, bhn), -1)) # [n_output]
b_i_list = [self.create_attr_tensor(bir), self.create_attr_tensor(biz), self.create_attr_tensor(bin)]
b_r_list = [self.create_attr_tensor(bhr), self.create_attr_tensor(bhz), self.create_attr_tensor(bhn)]
else:
bir = torch.zeros(input_tensors[input_start_index + 2].shape[0])
biz = torch.zeros_like(bir)
bin = torch.zeros_like(biz)
bhr = torch.zeros_like(bin)
bhz = torch.zeros_like(bhr)
bhn = torch.zeros_like(bhz)
input_tensors[input_start_index + 1] = self.create_attr_tensor(
torch.zeros(input_tensors[input_start_index].shape[0], dtype=torch.float32)
)
input_tensors[input_start_index + 3] = self.create_attr_tensor(
torch.zeros(input_tensors[input_start_index + 2].shape[0], dtype=torch.float32)
)
b_i_list = [self.create_attr_tensor(bir), self.create_attr_tensor(biz), self.create_attr_tensor(bin)]
b_r_list = [self.create_attr_tensor(bhr), self.create_attr_tensor(bhz), self.create_attr_tensor(bhn)]
return w_i_list, w_r_list, b_i_list, b_r_list
def gru_hidden_state_helper(
self,
input_tensors,
hidden_state_tensor,
input_index,
num_directions,
direction_idx,
num_layers,
layer_idx,
suffix,
state_type,
tf_state_tensors,
):
tf_state_tensor = tf_state_tensors[0]
assert hidden_state_tensor.dim() == 3
slice_idx = layer_idx * num_directions + direction_idx
if tf_state_tensor[slice_idx] is None:
input_tensors[input_index] = self.create_attr_tensor(hidden_state_tensor[slice_idx])
input_tensors[input_index].is_variable = True
else:
assert self.unroll_rnn, "Input state tensors are only supported when unroll_rnn=True is specified"
input_tensors[input_index] = tf_state_tensor[slice_idx]
def parse_common(
self,
input_tensor,
hidden_state_tensor,
params_tensors,
has_biases,
num_layers,
dropout,
is_train,
bidirectional,
batch_first,
graph_converter,
):
assert is_train in (False, 0)
self.unroll_rnn = True
self.separated_rnn_gate_calc = True
expected_num_params = 2 * num_layers
params_step = 2
if has_biases:
expected_num_params *= 2
params_step *= 2
if bidirectional:
expected_num_params *= 2
assert (
len(params_tensors) == expected_num_params
), f'num of params in GRU is wrong. got: {len(params_tensors)}, expected: {expected_num_params}'
num_input_tensors = 7
num_directions = 1
state_start_index = [1, 8]
if bidirectional:
num_input_tensors *= 2
num_directions *= 2
suffixes = ["_fw", "_bw"]
state_kinds = ["hidden"]
param_start_indices = [0, params_step]
input_start_indices = [2, 9]
ops = []
name = self.input_names[1]
tf_in_state_tensors = [graph_converter.tensor_map.get(n, None) for n in name]
tf_in_state_tensors = [
self.find_or_create_input(1, graph_converter) if name in graph_converter.tensor_map else None
]
tf_state_tensors = []
unpacked_tensors = {}
for t in tf_in_state_tensors:
if t is not None and self.unroll_rnn:
tensors = [
self.create_transform_tensor(np.squeeze(x, 0))
for x in np.split(t.tensor, num_directions * num_layers, 0)
]
tf_state_tensors.append(tensors)
ops.append(tfl.UnpackOperator([t], tensors, len(tensors), 0))
else:
tf_state_tensors.append([None] * num_directions * num_layers)
current_input = self.find_or_create_input(0, graph_converter)
gru_output = self.to_tfl_tensors(self.output_names[:1], self.output_tensors[:1])[0]
params_offset = 0
tf_out_state_tensors = [[]]
for layer_idx in range(num_layers):
inputs = [current_input] + [tfl.OptionalTensorInstance] * (num_input_tensors - 1)
for direction_idx in range(num_directions):
w_i_list, w_r_list, b_i_list, b_r_list = self.gru_input_helper(
inputs,
params_tensors,
has_biases,
params_offset + param_start_indices[direction_idx],
input_start_indices[direction_idx],
layer_idx,
suffixes[direction_idx],
)
self.gru_hidden_state_helper(
inputs,
hidden_state_tensor,
state_start_index[direction_idx],
num_directions,
direction_idx,
num_layers,
layer_idx,
suffixes[direction_idx],
state_kinds[0],
tf_state_tensors,
)
if layer_idx == num_layers - 1:
layer_output = gru_output
else:
output_shape = list(input_tensor.shape)
output_shape[-1] = inputs[4].shape[0] * num_directions
layer_output = self.create_transform_tensor(np.empty(output_shape, dtype=inputs[0].dtype))
outputs = [layer_output]
if self.unroll_rnn:
ts_axis = 1 if batch_first else 0
num_timestep = inputs[0].shape[ts_axis]
if inputs[0].name in unpacked_tensors:
input_ts = unpacked_tensors[inputs[0].name]
else:
input_ts = [
self.create_transform_tensor(np.squeeze(x, ts_axis))
for x in np.split(inputs[0].tensor, num_timestep, ts_axis)
]
ops.append(tfl.UnpackOperator([inputs[0]], input_ts, num_timestep, ts_axis))
strides = [1, -1]
output_ts = []
for direction_idx in range(num_directions):
w_i_list, w_r_list, b_i_list, b_r_list = self.gru_input_helper(
inputs,
params_tensors,
has_biases,
params_offset + param_start_indices[direction_idx],
input_start_indices[direction_idx],
layer_idx,
suffixes[direction_idx],
)
state_start = state_start_index[direction_idx]
h = inputs[state_start]
stride = strides[direction_idx]
# Skip some computations for the first timestep
compute_h = h.buffer is None or np.any(h.tensor)
stacked_hs = []
for i, t in enumerate(input_ts[::stride]):
input_mm_list = []
for j, (w_i, b_i) in enumerate(zip(w_i_list, b_i_list)):
input_mm = self.create_transform_tensor(
np.matmul(t.tensor, np.transpose(w_i.tensor, [1, 0])) + b_i.tensor
)
ops.append(tfl.FullyConnectedOperator([t, w_i, b_i], [input_mm]))
input_mm_list.append(input_mm)
if i != 0 or compute_h:
hidden_mm_list = []
for j, (w_r, b_r) in enumerate(zip(w_r_list, b_r_list)):
hidden_mm = self.create_transform_tensor(
np.matmul(h.tensor, np.transpose(w_r.tensor, [1, 0])) + b_r.tensor
)
ops.append(tfl.FullyConnectedOperator([h, w_r, b_r], [hidden_mm]))
hidden_mm_list.append(hidden_mm)
else:
hidden_mm_list = b_r_list
# calculate r,z,n gates
rgate_in = self.create_transform_tensor(input_mm_list[0].tensor + hidden_mm_list[0].tensor)
ops.append(tfl.AddOperator([input_mm_list[0], hidden_mm_list[0]], [rgate_in]))
zgate_in = self.create_transform_tensor(input_mm_list[1].tensor + hidden_mm_list[1].tensor)
ops.append(tfl.AddOperator([input_mm_list[1], hidden_mm_list[1]], [zgate_in]))
zgate_out = self.create_transform_tensor(
torch.sigmoid(torch.from_numpy(zgate_in.tensor)).numpy()
)
ops.append(tfl.LogisticOperator([zgate_in], [zgate_out]))
rgate_out = self.create_transform_tensor(
torch.sigmoid(torch.from_numpy(rgate_in.tensor)).numpy()
)
ops.append(tfl.LogisticOperator([rgate_in], [rgate_out]))
ngate_in_hside = self.create_transform_tensor(rgate_out.tensor * hidden_mm_list[2].tensor)
ops.append(tfl.MulOperator([rgate_out, hidden_mm_list[2]], [ngate_in_hside]))
ngate_in = self.create_transform_tensor(input_mm_list[2].tensor + ngate_in_hside.tensor)
ops.append(tfl.AddOperator([input_mm_list[2], ngate_in_hside], [ngate_in]))
ngate_out = self.create_transform_tensor(torch.tanh(torch.from_numpy(ngate_in.tensor)).numpy())
ops.append(tfl.TanhOperator([ngate_in], [ngate_out]))
constant_tensor = self.create_attr_tensor(torch.tensor(1, dtype=torch.float32))
h_left_0 = self.create_transform_tensor(constant_tensor.tensor - zgate_out.tensor)
ops.append(tfl.SubOperator([constant_tensor, zgate_out], [h_left_0]))
h_left = self.create_transform_tensor(h_left_0.tensor * ngate_out.tensor)
ops.append(tfl.MulOperator([h_left_0, ngate_out], [h_left]))
if i != 0 or compute_h:
h_right = self.create_transform_tensor(zgate_out.tensor * h.tensor)
ops.append(tfl.MulOperator([zgate_out, h], [h_right]))
h = self.create_transform_tensor(h_left.tensor + h_right.tensor)
ops.append(tfl.AddOperator([h_left, h_right], [h]))
elif i == 0 and not compute_h:
h = h_left
stacked_hs.append(h)
tf_out_state_tensors[0].append(h)
output_ts.extend(stacked_hs[::stride])
if bidirectional:
fw_out = self.create_transform_tensor(
np.stack([x.tensor for x in output_ts[:num_timestep]], ts_axis)
)
ops.append(tfl.PackOperator(output_ts[:num_timestep], [fw_out], num_timestep, axis=ts_axis))
bw_out = self.create_transform_tensor(
np.stack([x.tensor for x in output_ts[:num_timestep]], ts_axis)
)
ops.append(tfl.PackOperator(output_ts[num_timestep:], [bw_out], num_timestep, axis=ts_axis))
ops.append(tfl.ConcatenationOperator([fw_out, bw_out], outputs, axis=2))
elif layer_idx != num_layers - 1:
# Reusing unpacked tensors for the logic in the next layer
unpacked_tensors[outputs[0].name] = output_ts
else:
# For the last layer, we have to pack the together
ops.append(tfl.PackOperator(output_ts, outputs, len(output_ts), axis=ts_axis))
current_input = outputs[0]
params_offset += params_step * num_directions
if self.unroll_rnn:
state_outputs = self.to_tfl_tensors(self.output_names[1:], self.output_tensors[1:])
for i, (orig, new) in enumerate(zip(tf_in_state_tensors, tf_out_state_tensors)):
if orig is not None:
pack_op = tfl.PackOperator(new, state_outputs[i : i + 1], len(new), 0)
pack_op.extra_hints['warn_on_unused'] = False
ops.append(pack_op)
for op in ops:
graph_converter.add_operator(op)
def parse(self, node, attrs, args, graph_converter):
super().parse(node, attrs, args, graph_converter)
self.run(node)
input_tensor, hidden_state_tensor, params_tensors = self.input_tensors[:3]
has_biases, num_layers, dropout, is_train, bidirectional, batch_first = self.input_tensors[3:]
self.parse_common(
input_tensor,
hidden_state_tensor,
params_tensors,
has_biases,
num_layers,
dropout,
is_train,
bidirectional,
batch_first,
graph_converter,
)
class ATenBatchNormOperator(ATenBatchNormSchema):
def parse(self, node, attrs, args, graph_converter):
super().parse(node, attrs, args, graph_converter)
self.run(node)
eps = self.input_tensors[args['eps']]
# weight
if self.input_tensors[1] is None:
self.input_names[1] = self.get_unique_attr_name()
self.input_tensors[1] = torch.ones(self.input_tensors[0].size(1), dtype=torch.float32)
# bias
if self.input_tensors[2] is None:
self.input_names[2] = self.get_unique_attr_name()
self.input_tensors[2] = torch.zeros(self.input_tensors[0].size(1), dtype=torch.float32)
# running mean & var
assert (
self.input_tensors[3] is not None and self.input_tensors[4] is not None
), "Running mean and variance should not be None for aten::batch_norm. Otherwise, use LayerNorm instead."
inputs = [self.find_or_create_input(i, graph_converter) for i in range(5)]
outputs = self.to_tfl_tensors(self.output_names, self.output_tensors)
graph_converter.add_operator(tfl.BatchNormOperator(inputs, outputs, eps))
class ATenConstantPadNdOperator(ATenConstantPadNdSchema):
def parse(self, node, attrs, args, graph_converter):
super().parse(node, attrs, args, graph_converter)
self.run(node)
input_tensor = self.find_or_create_input(0, graph_converter)
pads = self.input_tensors[1]
constant_value = self.input_tensors[2]
orig_pad = np.array(pads, dtype='int32').reshape(-1, 2)
pad_fill = np.zeros((input_tensor.tensor.ndim - orig_pad.shape[0], 2), dtype='int32')
pad_arr = np.flip(np.concatenate((orig_pad, pad_fill)), 0)
pad_tensor = self.create_attr_tensor(pad_arr)
inputs = [input_tensor, pad_tensor]
outputs = self.to_tfl_tensors(self.output_names, self.output_tensors)
if constant_value not in (0, 0.0):
output = outputs[0]
if output.quantization is None:
constant_arr = np.array([constant_value], dtype='float32')
else:
float_arr = torch.tensor([constant_value], dtype=torch.float32)
constant_arr = torch.quantize_per_tensor(
float_arr, output.quantization.scale, output.quantization.zero_point, torch.quint8
)
inputs.append(self.create_attr_tensor(constant_arr))
graph_converter.add_operator(tfl.Padv2Operator(inputs, outputs))
else:
graph_converter.add_operator(tfl.PadOperator(inputs, outputs))
class ATenUpsampleNearest2dOperator(ATenUpsampleNearest2dSchema):
def parse(self, node, attrs, args, graph_converter):
super().parse(node, attrs, args, graph_converter)
self.run(node)
input_tensor = self.find_or_create_input(0, graph_converter)
output_size = self.input_tensors[1]
if output_size is None:
scale_factors = np.array(self.input_tensors[2], dtype='float64')
input_sizes = np.array(input_tensor.shape[2:], dtype='float64')
output_size = (input_sizes * scale_factors).astype('int32')
output_sizes = self.create_attr_tensor(np.array(output_size, dtype='int32'))
inputs = [input_tensor, output_sizes]
outputs = self.to_tfl_tensors(self.output_names, self.output_tensors)
ops = [tfl.ResizeNearestNeighborOperator(inputs, outputs, halfPixelCenters=False)]
ops = self.wrap_ops_with_nhwc_nchw_transposes(ops)
for op in ops:
graph_converter.add_operator(op)
class ATenUpsampleBilinear2dOperator(ATenUpsampleBilinear2dSchema):
def parse(self, node, attrs, args, graph_converter):
super().parse(node, attrs, args, graph_converter)
self.run(node)
input_tensor = self.find_or_create_input(0, graph_converter)
output_size = self.input_tensors[1]
if output_size is None:
scale_factors = np.array(self.input_tensors[3], dtype='float64')
input_sizes = np.array(input_tensor.shape[2:], dtype='float64')
output_size = (input_sizes * scale_factors).astype('int32')
output_sizes = self.create_attr_tensor(np.array(output_size, dtype='int32'))
align_corners = self.input_tensors[2] in (True, 1)
half_pixel_centers = not align_corners
inputs = [input_tensor, output_sizes]
outputs = self.to_tfl_tensors(self.output_names, self.output_tensors)
ops = [tfl.ResizeBilinearOperator(inputs, outputs, align_corners, half_pixel_centers)]
ops = self.wrap_ops_with_nhwc_nchw_transposes(ops)
for op in ops:
graph_converter.add_operator(op)
class ATenAvgPool2dOperator(ATenAvgPool2dSchema):
def parse(self, node, attrs, args, graph_converter):
super().parse(node, attrs, args, graph_converter)
self.run(node)
inputs = [self.find_or_create_input(0, graph_converter)]
outputs = self.to_tfl_tensors(self.output_names, self.output_tensors)
kernel_h, kernel_w = self.input_tensors[1]
stride_h, stride_w = self.input_tensors[2] or (kernel_h, kernel_w)
padding_h, padding_w = self.input_tensors[3]
ceil_mode = self.input_tensors[4] in (True, 1)
count_include_pad = self.input_tensors[5] in (True, 1)
divisor_override = self.input_tensors[6]
assert (
divisor_override is None or divisor_override == kernel_h == kernel_w
), "Only divisor_override == kernel_h == kernel_w is supported"
padding = tfl_schema.Padding.VALID
avgpool_op = tfl.AveragePool2dOperator(inputs, outputs, padding, stride_w, stride_h, kernel_w, kernel_h)
ops = self.wrap_ops_with_nhwc_nchw_transposes([avgpool_op])
self.handle_padding(padding_h, padding_w, 1, ops, ceil_mode)
if not count_include_pad:
mask = 1.0 / torch.nn.functional.avg_pool2d(
torch.ones_like(self.input_tensors[0]),
(kernel_h, kernel_w),
(stride_h, stride_w),
(padding_h, padding_w),
ceil_mode,
count_include_pad=True,
)
mask_permuted = mask.permute(0, 2, 3, 1)
mask_t = self.create_attr_tensor(mask_permuted)
before_mask = outputs[0].tensor / mask_permuted.cpu()
before_mask_t = self.create_transform_tensor(before_mask)
actual_out = ops[-2].outputs[0]
ops[-2].outputs[0] = before_mask_t
ops.insert(-1, tfl.MulOperator([before_mask_t, mask_t], [actual_out]))
for op in ops:
graph_converter.add_operator(op)
class ATenAdaptiveAvgPool2dOperator(ATenAdaptiveAvgPool2dSchema):
def parse(self, node, attrs, args, graph_converter):
super().parse(node, attrs, args, graph_converter)
self.run(node)
input_tensor = self.find_or_create_input(0, graph_converter)
output_h, output_w = self.input_tensors[1]
dim_h, dim_w = input_tensor.shape[2:]
assert (
dim_h % output_h == 0 and dim_w % output_w == 0
), f'not supported: input dim: [{dim_h}, {dim_w}], output size: [{output_h}, {output_w}]'
assert input_tensor.tensor.ndim == 4, 'Only 4D input is supported'
ops = []
dims = self.create_attr_tensor(np.array([1, 2], dtype='int32'))
outputs = self.to_tfl_tensors(self.output_names, self.output_tensors)
if output_h == 1 and output_w == 1:
inputs = [input_tensor, dims]
ops.append(tfl.MeanOperator(inputs, outputs, True))
else:
inputs = [input_tensor]
padding = tfl_schema.Padding.VALID
stride_h, stride_w = dim_h // output_h, dim_w // output_w
kernel_h, kernel_w = dim_h - (output_h - 1) * stride_h, dim_w - (output_w - 1) * stride_w
ops.append(tfl.AveragePool2dOperator(inputs, outputs, padding, stride_w, stride_h, kernel_w, kernel_h))