-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathTTEParser.py
More file actions
2149 lines (1918 loc) · 80.8 KB
/
Copy pathTTEParser.py
File metadata and controls
2149 lines (1918 loc) · 80.8 KB
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 json
import math
import pickle
import warnings
import numpy as np
from .constant import (
FUSE_INT8CAST_STR,
FUSE_SGD_UPDATE_STR,
FUSE_TILE_STR,
FUSE_WHERE_ZEROSSTR,
FUSHION_CONFIG,
INPLACE_MUL_STR,
INPLACE_WHERE_STR,
REORDER_STR,
USE_BIT_MASK,
op_name_translation,
)
from .FusionUtil import (
_accessTrainable,
_castisFusable,
_castisFusable_for_gconv,
_fileTileRepAsWeights,
_findBinMaskPattern,
_findBinMaskPatternint8,
_findConv2dwithScaleName,
_findKeyinTensors,
_findMultiplyAbsMaxDivide,
_findPartialConv,
_findTargetWeightforGconv,
_findTransposeMultiplyAbsMaxDivide,
_findWhereTensorFrom,
_removeLayers,
_updateIdx,
_updateIdxParameter,
_updateOutputDtype,
)
from .GraphReorder import reorderGroupConv_TransponseConv, reorderGroupConv_TransponseConv_int8
from .operators import (
add,
add1d,
avgpool2d,
bias_add,
bias_update,
cast,
collapse_sum_like,
conv2d,
dense,
depthwiseConv2d,
div,
exp,
greater,
group_conv2d,
less,
log_softmax,
mat_mul,
mul,
negative,
nll_loss,
ones_like,
permute_4D_3012,
permute_groupconv_out,
relu,
reshape,
reshape_like,
strided_slice,
sub,
sum,
tile,
transpose,
transpose_conv2d,
where,
zeros_like,
)
from .operators.basic_utils import isconstanttstr
from .QAS_util import get_effective_scalename_with_input_key, get_QAS
MAX_DAGOP_OUTPUTS = 5
fused_op = {"clip", "nn.batch_flatten", "squeeze", "reshape", "reshape_like"}
class outputInfo:
def __init__(self, name, idx, len, dtype):
self.name = name
self.idx = idx
self.len = len
self.dtype = dtype
class TTEParser(object):
def __init__(self, model, data, scale_params=None):
self.layer = []
self.gout = []
self.det_outputs = None
with open(model, "r") as f:
self.model = json.load(f)
with open(data, "rb") as f:
w_params = pickle.load(f)
self.data = {}
for k in w_params:
if k[0] != "v":
self.data[f"v{k}"] = w_params[k]
else:
self.data[k] = w_params[k]
self.scale_params = scale_params
self.layer = []
self.trainedWeights = [] # key, weight_ip
self.trainedBias = [] # key, weight_ip
self.fusedInputTable = {}
self.outputTables = []
self.regularFunctionTable = {
"cast": self._convert_cast,
"cast_like": self._convert_cast,
"exp": self._convert_exp,
"transpose": self._convert_transpose,
"where": self._convert_where,
"nn.conv2d_transpose": self._convert_transpose_conv2d,
"strided_slice": self._convert_strided_slice,
"nn.bias_add": self._convert_bias_add,
"nn.relu": self._convert_relu,
"zeros_like": self._convert_zeros_like,
"zeros": self._convert_zeros,
"ones_like": self._convert_ones_like,
"ones": self._convert_ones,
"collapse_sum_like": self._convert_collapse_sum_like,
"less": self._convert_less,
"less_equal": self._convert_less,
"nn.log_softmax": self._convert_log_softmax,
"nn.cross_entropy_with_logits": self._convert_cross_entropy_with_logits,
"divide": self._convert_div,
"tile": self._convert_tile,
"negative": self._convert_negative,
"greater": self._convert_greater,
"greater_equal": self._convert_greater,
"multiply": self._convert_mul,
"nn.matmul": self._convert_matmul,
"nn.dense": self._convert_dense,
"mcumean": self._convert_average_pool,
}
self.partialChannelList = {} # "idx": first_k_channel
def loadModel(self):
last_op = None
has_zero_x = False
zero_x = None
self.fusedInputTable[self.model[0]["inputs"][0]["name"]] = self.model[0]["inputs"][0]["name"]
# reorder the group conv and transpose conv to calculate weight gradients first
if FUSHION_CONFIG[REORDER_STR]:
self.model = reorderGroupConv_TransponseConv(self.model)
self.model = reorderGroupConv_TransponseConv_int8(self.model)
for cnt, op in enumerate(self.model):
op_type = op["type"]
if op_type in {"nn.conv2d", "nn.mcuconv2d"}:
last_op = self._convert_convolution(op)
# Float bp fusion
# check if we need to have binary mask for this conv2d
# conv2d (int32) -> cast -> greater/less -> multiply -> where (which take the map)
# fusion | --------------------------------------|
if op["outputs"][0]["dtype"] == "int32":
pattern_found, op_dict = _findBinMaskPattern(self.model, op["outputs"][0]["name"])
if pattern_found:
# add second output in the output tensors
b_mask_info = op_dict["multiply"]["outputs"][0]
if USE_BIT_MASK:
last_op._add_output(
b_mask_info["name"],
"bool",
int(math.ceil(last_op.params["output_c"] / 8)),
last_op.params["output_w"],
last_op.params["output_h"],
)
else:
last_op._add_output(
b_mask_info["name"],
b_mask_info["dtype"],
last_op.params["output_c"],
last_op.params["output_w"],
last_op.params["output_h"],
)
# update params in conv2d
last_op.params["need_Bmask"] = True
last_op.params["output2_h"] = last_op.params["output_h"]
last_op.params["output2_w"] = last_op.params["output_w"]
last_op.params["output2_c"] = last_op.params["output_c"]
last_op.params["output2_dtype"] = b_mask_info["dtype"]
last_op.params["output2_idx"] = b_mask_info["name"]
# remove fused ops in the graph
_removeLayers(self.model, op_dict)
# int8 bp fusion
# check if we need to have binary mask for this conv2d
# conv2d (int32) -> greater/less -> multiply -> where (which take the map)
# fusion | ------------------------------|
if op["outputs"][0]["dtype"] == "int32":
pattern_found, op_dict = _findBinMaskPatternint8(self.model, op["outputs"][0]["name"])
if pattern_found:
# add second output in the output tensors
b_mask_info = op_dict["multiply"]["outputs"][0]
if USE_BIT_MASK:
last_op._add_output(
b_mask_info["name"],
"bool",
int(math.ceil(last_op.params["output_c"] / 8)),
last_op.params["output_w"],
last_op.params["output_h"],
)
else:
last_op._add_output(
b_mask_info["name"],
b_mask_info["dtype"],
last_op.params["output_c"],
last_op.params["output_w"],
last_op.params["output_h"],
)
# update params in conv2d
last_op.params["need_Bmask"] = True
last_op.params["output2_h"] = last_op.params["output_h"]
last_op.params["output2_w"] = last_op.params["output_w"]
last_op.params["output2_c"] = last_op.params["output_c"]
last_op.params["output2_dtype"] = b_mask_info["dtype"]
last_op.params["output2_idx"] = b_mask_info["name"]
# remove fused ops in the graph
_removeLayers(self.model, op_dict)
# we use hwc for computation, but in bp the 'c' may mean output channel for the training weights.
# in this case, we need to insert an op to permute the weight tensor before running this conv2d op
# TODO: make sure this is not longer needed after we optimize tile + group_conv2d
# if len(self.model) > 0 and "weight" not in op["inputs"][1]["name"]:
# permute_params = {
# "input_idx": op["inputs"][1]["name"],
# "input_dim": 3,
# "input_h": op["inputs"][1]["shape"][-2],
# "input_w": op["inputs"][1]["shape"][-1],
# "input_c": op["inputs"][1]["shape"][-4], # IOHW
# }
# permute_op = permute_3D_120.permute_3D_120(permute_params)
# self.layer.append(permute_op)
if has_zero_x:
last_op.set_input_zero_point(zero_x)
has_zero_x = False
zero_x = None
self.layer.append(last_op)
elif op_type == "nn.mcuadd":
# fp32
pattern_found, op_dict = _findBinMaskPattern(self.model, op["outputs"][0]["name"])
# try int8
if not pattern_found:
pattern_found, op_dict = _findBinMaskPatternint8(self.model, op["outputs"][0]["name"])
last_op = self._convert_qadd(op)
if pattern_found:
# add second output in the output tensors
b_mask_info = op_dict["multiply"]["outputs"][0]
last_op._add_output(
b_mask_info["name"],
b_mask_info["dtype"],
last_op.params["output_c"],
last_op.params["output_w"],
last_op.params["output_h"],
)
# update params in conv2d
last_op.params["need_Bmask"] = True
last_op.params["output2_h"] = last_op.params["output_h"]
last_op.params["output2_w"] = last_op.params["output_w"]
last_op.params["output2_c"] = last_op.params["output_c"]
last_op.params["output2_dtype"] = b_mask_info["dtype"]
last_op.params["output2_idx"] = b_mask_info["name"]
# remove fused ops in the graph
_removeLayers(self.model, op_dict)
self.layer.append(last_op)
elif (
op_type == "cast" and op["inputs"][0]["dtype"] == "int8" and op["outputs"][0]["dtype"] == "int32"
): # int8 gradient for bias
# skip this one
_updateIdx(self.model, self.layer, op["inputs"][0]["name"], op["outputs"][0]["name"])
elif op_type == "cast" and _castisFusable(self.model, op)[0] and FUSHION_CONFIG[FUSE_INT8CAST_STR]:
_, transpose_conv_json = _castisFusable(self.model, op)
transpose_conv_json["inputs"][1] = op["inputs"][0] # pass the int8 input to transpose conv2d
elif (
op_type == "cast" and _castisFusable_for_gconv(self.model, op)[0] and FUSHION_CONFIG[FUSE_INT8CAST_STR]
):
_, group_conv_json = _castisFusable_for_gconv(self.model, op)
group_conv_json["inputs"][0] = op["inputs"][0] # pass the int8 input to group conv2d
group_conv_json["inplace_int8_input"] = True
elif op_type == "tile" and FUSHION_CONFIG[FUSE_TILE_STR]:
# check if we need to fuse ops for tile
# ########## tile -> reshape -> conv2d (which takes it as weights)
# fusion | ------------------------|
pattern_found, op_dict = _fileTileRepAsWeights(self.model, op)
if pattern_found:
# remove reshape
_removeLayers(self.model, {"reshape": op_dict["reshape"]})
# redirect the input of tile to conv2d's weight
op_dict["conv2d"]["inputs"][1] = op_dict["tile"]["inputs"][0]
else:
raise NotImplementedError
elif op_type == "add":
if len(op["inputs"][0]["shape"]) == 4 and op["inputs"][0]["dtype"] == "int8":
if "zero_y" in op["inputs"][1]["name"]:
zero_y = int(self.data[op["inputs"][1]["name"]])
last_op.set_output_zero_point(zero_y)
continue
last_op = self._convert_add(op)
self.layer.append(last_op)
else:
last_op = self._convert_add1d(op)
self.layer.append(last_op)
elif op_type == "nn.bias_add" and op["inputs"][1]["dtype"] == "int8":
last_op.params["bias"] = self.data[op["inputs"][1]["name"]].astype(int)
# redirect the index
last_op.change_output_tensor_idx(op["outputs"][0]["name"])
# fixing HWC -> CHW alginment
elif (
op_type == "reshape"
and len(op["inputs"][0]["shape"]) == 4
and (op["inputs"][0]["shape"][2] != 1 and op["inputs"][0]["shape"][3] != 1)
and op["inputs"][0]["shape"][2] != op["outputs"][0]["shape"][2]
and op["inputs"][0]["shape"][3] != op["outputs"][0]["shape"][3]
):
last_op = self._convert_reshape(op)
self.layer.append(last_op)
# input might be parameters, we handle the inside ops since we only support for scales in `multiply`
elif op_type == "reshape" and op["inputs"][0]["var_type"] == "parameter":
# find out ops taking the output
for other_op in self.model:
for input_tensor in other_op["inputs"]:
if input_tensor["name"] == op["outputs"][0]["name"]:
if other_op["type"] in {"multiply", "divide"}:
_updateIdxParameter(self.model, op["inputs"][0]["name"], op["outputs"][0]["name"])
else:
raise NotImplementedError
# fixing CHW -> HWC alginment
elif (
op_type == "reshape_like"
and len(op["inputs"][1]["shape"]) == 4
and (op["inputs"][1]["shape"][2] != 1 and op["inputs"][1]["shape"][3] != 1)
and op["inputs"][0]["shape"][2] != op["outputs"][0]["shape"][2]
and op["inputs"][0]["shape"][3] != op["outputs"][0]["shape"][3]
):
last_op = self._convert_reshape_like(op)
self.layer.append(last_op)
# bypass this layer by fusing it into the last layer, TODO: revisit this for clipping fp results
elif op_type in fused_op and op:
# update tensors
_updateIdx(self.model, self.layer, op["inputs"][0]["name"], op["outputs"][0]["name"])
elif op_type in "nn.mcutruncate":
# update output dtype
_updateOutputDtype(self.layer, op["inputs"][0]["name"], "int8")
# update tensor idx
_updateIdx(self.model, self.layer, op["inputs"][0]["name"], op["outputs"][0]["name"])
elif op_type == "subtract":
is_fuse = False
for tensor in op["inputs"]:
if "zero_x" in tensor["name"]:
has_zero_x = True
zero_x = int(self.data[tensor["name"]])
is_fuse = True
if not is_fuse:
last_op = self._convert_sub(op)
self.layer.append(last_op)
elif op_type == "sum":
input_length = np.prod(op["inputs"][0]["shape"])
output_length = np.prod(op["outputs"][0]["shape"])
if input_length != output_length:
last_op = self._convert_sum(op)
self.layer.append(last_op)
if op["outputs"][0] and "output_info" in op["outputs"][0]["meta"]:
if op["outputs"][0]["meta"]["output_info"][0] == "v":
key = op["outputs"][0]["meta"]["output_info"]
else:
key = "v" + op["outputs"][0]["meta"]["output_info"]
if self.scale_params is not None:
e_s_name = get_effective_scalename_with_input_key(key, self.model)
QAS = get_QAS(key, self.scale_params, self.data[e_s_name])
else:
QAS = np.zeros(int(output_length)) + 0.000000001 # avoid zero division
bias_update_params = {
"input_idx": last_op.params["output_idx"],
"output_idx": key,
# tensor related
"input_size": int(output_length),
"input_buf_add": None,
"input_buf_add_offset": None,
"QAS": QAS,
"input_dtype": last_op.params["input_dtype"],
"output_dtype": "float32",
}
bias_update_op = bias_update.bias_update(bias_update_params)
self.layer.append(bias_update_op)
else: # skip this, no need to do anything on the data
input_idx = op["inputs"][0]["name"]
output_idx = op["outputs"][0]["name"]
# update the bias
if op["outputs"][0] and "output_info" in op["outputs"][0]["meta"]:
if op["outputs"][0]["meta"]["output_info"][0] == "v":
key = op["outputs"][0]["meta"]["output_info"]
else:
key = "v" + op["outputs"][0]["meta"]["output_info"]
if self.scale_params is not None:
e_s_name = get_effective_scalename_with_input_key(key, self.model)
QAS = get_QAS(key, self.scale_params, self.data[e_s_name])
else:
QAS = np.zeros(int(output_length)) + 0.000000001 # avoid zero division
bias_update_params = {
"input_idx": last_op.params["output_idx"],
"output_idx": key,
# tensor related
"input_size": int(output_length),
"input_buf_add": None,
"input_buf_add_offset": None,
"QAS": QAS,
"input_dtype": "float32",
"output_dtype": "float32",
}
bias_update_op = bias_update.bias_update(bias_update_params)
self.layer.append(bias_update_op)
# # update tensors
_updateIdx(self.model, self.layer, input_idx, output_idx)
# assume weights are updated once we obtain its gradient
elif op_type == "transpose" and FUSHION_CONFIG[FUSE_SGD_UPDATE_STR]:
fuseable, op_dict = _findTransposeMultiplyAbsMaxDivide(self.model, op)
# old IR
if op["outputs"][0]["meta"]["children"] == 0:
# update tensors
_updateIdx(self.model, self.layer, op["inputs"][0]["name"], op["outputs"][0]["name"])
elif fuseable:
# fuse "transpose" -> [max -> divide -> divide (int8 bp)]
_updateIdx(self.model, self.layer, op["inputs"][0]["name"], op_dict["cast"]["outputs"][0]["name"])
# add the output to output table
name = op_dict["cast"]["outputs"][0]["meta"]["output_info"]
idx = op_dict["cast"]["outputs"][0]["name"]
length = np.prod(op_dict["cast"]["outputs"][0]["shape"])
dtype = op_dict["cast"]["outputs"][0]["dtype"]
self.outputTables.append(outputInfo(name, idx, int(length), dtype))
_removeLayers(self.model, op_dict)
else:
raise NotImplementedError
elif (
FUSHION_CONFIG[FUSE_WHERE_ZEROSSTR]
and op_type == "where"
and (op["inputs"][2]["dtype"] in ["int8", "int32", "float32"])
and _findWhereTensorFrom(self.layer, op["inputs"][2]["name"]) is not None
and _findWhereTensorFrom(self.layer, op["inputs"][2]["name"]).params["op"]
== "ZEROS" # third input is from zeros
):
zeros_op = _findWhereTensorFrom(self.layer, op["inputs"][2]["name"])
# remove previous the zeros layer
self.layer.remove(zeros_op)
# parse the where but remove the third input and set "input3_is_zeros" in params
last_op = self._convert_where(op)
last_op.params["input3_is_zeros"] = True
last_op.input_tensors.remove(last_op.input_tensors[2])
# check where we can update input2 inplace
# if input2 is not used by following ops
# (1) make input2_inplace
# (2) update the following op's input idx (normally it is MUL)
can_be_inplace = None
# check if the last_op["input2_idx"] == some_op["ouptuts"][0]
for from_op in self.model:
if from_op["outputs"][0]["name"] == last_op.params["input2_idx"]:
if from_op["outputs"][0]["meta"]["children"] != 1:
can_be_inplace = False
else:
can_be_inplace = True
assert can_be_inplace is not None
if can_be_inplace and FUSHION_CONFIG[INPLACE_WHERE_STR]:
# find the where the output of where goes and link it to the second input of where
for following_op in self.model:
for inp in following_op["inputs"]:
if inp["name"] == op["outputs"][0]["name"]:
inp["name"] = op["inputs"][1]["name"]
# remove output tensor of where
last_op.output_tensors.remove(last_op.output_tensors[0])
# set where to inplace
last_op.params["inplace"] = True
# add the op
self.layer.append(last_op)
elif op_type == "multiply" and FUSHION_CONFIG[INPLACE_MUL_STR]:
last_op = self._convert_mul(op)
last_op_input = last_op.params["input_idx"]
last_op_output = last_op.params["output_idx"]
if last_op.params["input2_size"] > 1 and last_op.params["input_size"] > last_op.params["input2_size"]:
# good to be updated inplace
last_op.params["inplace"] = True
last_op.output_tensors.remove(last_op.output_tensors[0])
# redirect the following op's input as the inplace input
for following_op in self.model:
# if following_op["type"] in {"sum", "nn.conv2d_transpose", "nn.conv2d"}:
for inp in following_op["inputs"]:
if inp["name"] == last_op_output:
inp["name"] = last_op_input
# _updateIdx(self.model, self.layer, last_op_input, last_op_output)
# replace the following
self.layer.append(last_op)
elif op_type in self.regularFunctionTable:
last_op = self.regularFunctionTable[op_type](op)
self.layer.append(last_op)
elif op_type == "abs":
if FUSHION_CONFIG[FUSE_SGD_UPDATE_STR]:
cliping_pattern, op_dict = _findMultiplyAbsMaxDivide(self.model, abs_op=op)
if cliping_pattern:
# For transpose conv2d, this could be float32 -> int8 if it connects to abs
previous_op = _findWhereTensorFrom(self.layer, op["inputs"][0]["name"])
if (
previous_op.params["op"] == "TRANSPOSE_CONV_2D"
and previous_op.params["output_dtype"] == "float32"
):
previous_op.params["float_to_int8"] = True
previous_op.params["output_dtype"] = "int8"
previous_op.output_tensors[0].dtype = "int8"
previous_op.add_int32_buffer_tensor()
_updateIdx(
self.model, self.layer, op["inputs"][0]["name"], op_dict["cast"]["outputs"][0]["name"]
)
_removeLayers(self.model, op_dict)
else:
raise NotImplementedError
else:
cliping_pattern, op_dict = _findMultiplyAbsMaxDivide(self.model, abs_op=op)
if cliping_pattern:
_updateIdx(
self.model, self.layer, op["inputs"][0]["name"], op_dict["cast"]["outputs"][0]["name"]
)
_removeLayers(self.model, op_dict)
# Baseline for int8 fp without graph optimization
# Adding outputTable for accurate trainable measuremnet
if "output_info" in op_dict["cast"]["outputs"][0]["meta"]:
name = op_dict["cast"]["outputs"][0]["meta"]["output_info"]
idx = op_dict["cast"]["outputs"][0]["name"]
length = np.prod(op_dict["cast"]["outputs"][0]["shape"])
dtype = "int8"
self.outputTables.append(outputInfo(name, idx, int(length), dtype))
else:
raise NotImplementedError
else:
warnings.warn("%s op is not `supported" % op_type)
raise NotImplementedError
# GROUP CONV
if self.layer[-1].params["op"] == "GROUP_CONV":
# for group conv the output is actually h, w, IxO, we need to permute it to OHWI
if not FUSHION_CONFIG[FUSE_SGD_UPDATE_STR]:
params = {
# op related
"op": "PERMUTE_GROUPCONV_OUT",
"input_idx": last_op.params["output_idx"],
# tensor related
"input_dim": 3,
"input_h": last_op.params["output_h"],
"input_w": last_op.params["output_w"],
"input_c": last_op.params["output_c"],
"groups": last_op.params["groups"],
"input_dtype": "float32",
"output_dtype": "float32",
}
self.layer.append(permute_groupconv_out.permute_groupconv_out(params))
# we inplace update the weights, for output stantionary group conv
# here we need to
# (1) update the graph: remove gconv -> reshape -> sum -> transpose (done in "transpose" op)
# -> [max -> divide -> divide (int8 bp)]
# (2) remove the output tensor in gconv
# (3) replace the output address with int8 weight in SRAM
# TODO: we also need to back trace the int8 conv and make it use wegiht in both SRAM and Flash
elif len(self.layer[-1].output_tensors) > 0:
# find the target weigth
weight_idx = _findTargetWeightforGconv(self.model, self.layer[-1].output_tensors[0].graph_idx)
assert weight_idx is not None
self.layer[-1].params["inplace_weight_name"] = weight_idx
# back trace to the int8 conv
conv_partial_layer = _findPartialConv(self.layer, weight_idx)
conv_p = conv_partial_layer.params
gconv_output_len = np.prod(self.layer[-1].output_tensors[0].size)
conv_weight_size = conv_p["input_c"] * conv_p["output_c"] * conv_p["kernel_h"] * conv_p["kernel_w"]
if conv_weight_size != gconv_output_len:
# this is partial
# find the first k channel
fisrt_k_channel = int(conv_p["input_c"] * gconv_output_len / conv_weight_size)
conv_partial_layer.params["first_k_channel"] = fisrt_k_channel
self.partialChannelList[weight_idx] = fisrt_k_channel
#
if self.scale_params is not None:
key = weight_idx
e_s_name = get_effective_scalename_with_input_key(key, self.model)
QAS = get_QAS(key, self.scale_params, self.data[e_s_name])
else:
QAS = np.zeros(int(output_length)) + 0.000000001 # avoid zero division
self.layer[-1].params["QAS"] = QAS
# remove for inplace
self.layer[-1].output_tensors.remove(self.layer[-1].output_tensors[0])
# add the gradient_output to table, we will use a custom layer to perform SGD
if (
"meta" in op["outputs"][0]
and op["outputs"][0]["meta"]["children"] == 0
and "output_info" in op["outputs"][0]["meta"]
):
name = op["outputs"][0]["meta"]["output_info"]
idx = op["outputs"][0]["name"]
length = np.prod(op["outputs"][0]["shape"])
dtype = op["outputs"][0]["dtype"]
self.outputTables.append(outputInfo(name, idx, int(length), dtype))
# loop over the graph and find transpose conv that use partial weights
for layer in self.layer:
if (
layer.params["op"] == op_name_translation["nn.conv2d_transpose"]
and layer.params["weight_name"] in self.partialChannelList
):
layer.params["first_k_channel"] = self.partialChannelList[layer.params["weight_name"]]
def _convert_cast(self, op):
# shape
input_info = op["inputs"][0]
input_dtype = get_dtype(op["inputs"][0])
input_shape = input_info["shape"]
output_c = input_c = input_h = input_w = 1
if len(input_shape) == 4:
output_c, input_c, input_h, input_w = input_shape # OIHW
elif len(input_shape) == 2:
input_h, input_w = input_shape
input_c = 1
elif len(input_shape) == 1:
input_h = input_w = 1
input_c = input_shape[0]
else:
raise NotImplementedError
output_info = op["outputs"][0]
output_dtype = get_dtype(op["outputs"][0])
# dtype
input_dtype = get_dtype(input_info)
output_dtype = get_dtype(output_info)
params = {
# operator
"op": op_name_translation[op["type"]],
# tensor
"input_idx": input_info["name"],
"output_idx": output_info["name"],
"input_size": output_c * input_c * input_h * input_w,
"input_dim": 4,
"output_dim": 4,
"input_dtype": input_dtype,
"output_dtype": output_dtype,
"input_meta": op["inputs"][0]["meta"],
}
op = cast.cast(params)
return op
def _convert_relu(self, op):
# shape
input_info = op["inputs"][0]
input_dtype = get_dtype(op["inputs"][0])
input_shape = input_info["shape"]
if len(input_shape) == 4:
_, input_c, input_h, input_w = input_shape
elif len(input_shape) == 2:
input_h, input_w = input_shape
input_c = 1
else:
raise NotImplementedError
output_info = op["outputs"][0]
output_dtype = get_dtype(op["outputs"][0])
output_c = input_c
output_h = input_h
output_w = input_w
# dtype
input_dtype = get_dtype(input_info)
output_dtype = get_dtype(output_info)
params = {
# operator
"op": op_name_translation[op["type"]],
# tensor
"input_idx": input_info["name"],
"output_idx": output_info["name"],
"input_h": input_h,
"input_w": input_w,
"input_c": input_c,
"input_dim": 3,
"output_dim": 3,
"output_h": output_h,
"output_w": output_w,
"output_c": output_c,
"input_dtype": input_dtype,
"output_dtype": output_dtype,
}
op = relu.relu(params)
return op
def _convert_bias_add(self, op):
# shape
input_info = op["inputs"][0]
input_dtype = get_dtype(op["inputs"][0])
input_shape = input_info["shape"]
if len(input_shape) == 2:
input_h = 1
input_w = input_shape[0]
input_c = input_shape[1]
else:
input_c, input_h, input_w = get_chw_shape(input_shape)
output_info = op["outputs"][0]
output_shape = output_info["shape"]
output_c, output_h, output_w = get_chw_shape(output_shape)
# dtype
input_dtype = get_dtype(input_info)
output_dtype = get_dtype(output_info)
bias_name = op["inputs"][1]["name"]
if bias_name not in self.data:
bias_value = bias_name
else:
bias_value = self.data[bias_name]
params = {
# operator
"op": op_name_translation[op["type"]],
# tensor
"input_idx": input_info["name"],
"output_idx": output_info["name"],
"input_h": input_h,
"input_w": input_w,
"input_c": input_c,
"input_dim": 3,
"output_dim": 3,
"output_h": input_h,
"output_w": input_w,
"output_c": input_c,
"input_dtype": input_dtype,
"output_dtype": output_dtype,
"bias": bias_value,
"bias_name": bias_name,
}
op = bias_add.biasAdd(params)
return op
def _convert_reshape(self, op):
# shape
input_info = op["inputs"][0]
input_dtype = get_dtype(op["inputs"][0])
input_shape = input_info["shape"]
input_c, input_h, input_w = get_chw_shape(input_shape)
output_info = op["outputs"][0]
output_shape = output_info["shape"]
output_c, output_h, output_w = get_chw_shape(output_shape)
# dtype
input_dtype = get_dtype(input_info)
output_dtype = get_dtype(output_info)
params = {
# operator
"op": op_name_translation[op["type"]],
# tensor
"input_idx": input_info["name"],
"output_idx": output_info["name"],
"input_h": input_h,
"input_w": input_w,
"input_c": input_c,
"output_h": output_h,
"output_w": output_w,
"output_c": output_c,
"input_dtype": input_dtype,
"output_dtype": output_dtype,
}
op = reshape.reshape(params)
return op
def _convert_reshape_like(self, op):
# shape
input_info = op["inputs"][0]
input_dtype = get_dtype(op["inputs"][0])
input_shape = input_info["shape"]
input_c, input_h, input_w = get_chw_shape(input_shape)
input2_info = op["inputs"][1]
input2_dtype = get_dtype(op["inputs"][1])
input2_shape = input2_info["shape"]
input2_c, input2_h, input2_w = get_chw_shape(input2_shape)
output_info = op["outputs"][0]
output_shape = output_info["shape"]
output_c, output_h, output_w = get_chw_shape(output_shape)
# dtype
input_dtype = get_dtype(input_info)
output_dtype = get_dtype(output_info)
params = {
# operator
"op": op_name_translation[op["type"]],
# tensor
"input_idx": input_info["name"],
"output_idx": output_info["name"],
"input_h": input_h,
"input_w": input_w,
"input_c": input_c,
"input2_h": input2_h,
"input2_w": input2_w,
"input2_c": input2_c,
"output_h": output_h,
"output_w": output_w,
"output_c": output_c,
"input_dtype": input_dtype,
"input2_dtype": input2_dtype,
"output_dtype": output_dtype,
}
op = reshape_like.reshape_like(params)
return op
def _convert_exp(self, op):
# shape
input_info = op["inputs"][0]
input_dtype = get_dtype(op["inputs"][0])
input_shape = input_info["shape"]
input_c, input_h, input_w = get_chw_shape(input_shape)
output_info = op["outputs"][0]
output_shape = output_info["shape"]
output_c, output_h, output_w = get_chw_shape(output_shape)
# dtype
input_dtype = get_dtype(input_info)
output_dtype = get_dtype(output_info)
params = {
# operator
"op": op_name_translation[op["type"]],
# tensor
"input_idx": input_info["name"],
"output_idx": output_info["name"],
"input_size": input_h * input_w * input_c,
"input_dtype": input_dtype,
"output_dtype": output_dtype,
}
op = exp.exp(params)
return op
def _convert_transpose(self, op):
# shape
input_info = op["inputs"][0]
input_dtype = get_dtype(op["inputs"][0])
input_shape = input_info["shape"]
input_c, input_h, input_w = get_chw_shape(input_shape)
output_info = op["outputs"][0]
output_shape = output_info["shape"]
output_c, output_h, output_w = get_chw_shape(output_shape)
# dtype
input_dtype = get_dtype(input_info)
output_dtype = get_dtype(output_info)
params = {
# operator
"op": op_name_translation[op["type"]],
# tensor
"input_idx": input_info["name"],
"output_idx": output_info["name"],
"input_h": input_h,
"input_w": input_w,
"input_c": input_c,
"input_dim": 3,
"output_dim": 3,
"output_h": output_h,
"output_w": output_w,
"output_c": output_c,
"input_dtype": input_dtype,
"input_vartype": input_info["var_type"],
"output_dtype": output_dtype,
}
if "axes" in op["attrs"] and op["attrs"]["axes"] is not None:
if op["attrs"]["axes"] == [1, 0, 2, 3]:
# torch: OIHW -> IOHW -> permute 1023
# tinyengine: OHWI -> IOHW -> permute 3012
params["d1"], params["d2"], params["d3"], params["d4"] = input_shape
params["op"] = "permute_4D_3012"
op = permute_4D_3012.permute_4D_3012(params)
else:
raise NotImplementedError
else:
op = transpose.transpose(params)
return op
def _convert_strided_slice(self, op):
# shape
input_info = op["inputs"][0]
input_dtype = get_dtype(op["inputs"][0])
input_shape = input_info["shape"]
d1, d2, d3, d4 = input_shape # OHWI
output_info = op["outputs"][0]
output_shape = output_info["shape"]
o_d1, o_d2, o_d3, o_d4 = output_shape # OHWI
# dtype
input_dtype = get_dtype(input_info)
output_dtype = get_dtype(output_info)
b_list = op["attrs"]["begin"]
e_list = op["attrs"]["end"]
begin = b_list # [b_list[0], b_list[2], b_list[3], b_list[1]]
end = e_list # [e_list[0], e_list[2], e_list[3], e_list[1]]
strides = op["attrs"]["strides"]
params = {
# operator
"op": op_name_translation[op["type"]],
# tensor
"input_idx": input_info["name"],
"output_idx": output_info["name"],
"d1": d1,
"d2": d2,
"d3": d3,
"d4": d4,
"begin": begin,
"end": end,
"strides": strides,
"input_dim": 4,
"output_dim": 4,
"o_d1": o_d1,
"o_d2": o_d2,
"o_d3": o_d3,
"o_d4": o_d4,
"input_dtype": input_dtype,
"output_dtype": output_dtype,
}
op = strided_slice.stridedSlice(params)
return op
def _convert_average_pool(self, op):
# shape
input_info = op["inputs"][0]
input_dtype = get_dtype(op["inputs"][0])
input_shape = input_info["shape"]
input_c, input_h, input_w = get_chw_shape(input_shape)
output_info = op["outputs"][0]
output_dtype = get_dtype(op["outputs"][0])
output_shape = output_info["shape"]
output_c, output_h, output_w = get_chw_shape(output_shape)
# dtype
input_dtype = get_dtype(input_info)
output_dtype = get_dtype(output_info)
params = {
# operator
"op": "AVERAGE_POOL_2D",
# pool parameters
"filter_h": input_h,
"filter_w": input_w,
"stride_h": 1,
"stride_w": 1,
"pad_h": 0,
"pad_w": 0,
# tensor
"input_idx": input_info["name"],
"output_idx": output_info["name"],
"input_h": input_h,
"input_w": input_w,
"input_c": input_c,
"input_dim": 3,
"output_dim": 3,
"output_h": output_h,
"output_w": output_w,
"output_c": output_c,
"input_dtype": input_dtype,
"output_dtype": output_dtype,
}
op = avgpool2d.AvgPool2d(params)
return op
def _convert_zeros(self, op):