-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathoptimize.py
4856 lines (4094 loc) · 207 KB
/
optimize.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 copy
import functools
import itertools
import re
import typing
import warnings
import igraph as ig
import numpy as np
from tinynn.util.util import class_conditional, get_logger
from ..schemas.tflite.schema_generated import ActivationFunctionType, Padding
from . import tflite as tfl
from .base import FUSE_ACTIVATION_MAP, ExtendedOperator
from .graph import CommonGraph
log = get_logger(__name__, 'INFO')
class GraphOptimizer(object):
graph: CommonGraph
fuse_tensor_count: int
fuse_attr_count: int
fuse_quant: bool
group_conv_rewrite: bool
tflite_micro_rewrite: bool
quantize_input_output_type: typing.Optional[str]
# Optimization levels
NO_OPTIMIZE: int = 0
FOLD_BUFFER: int = 1
FUSE_BN: int = 2
COMMON_OPTIMIZE: int = 3
BRANCH_OPTIMIZE: int = 4
BRANCH_OPTIMIZE_EXTENDED: int = 5
ALL_OPTIMIZE: int = 5
def __init__(
self,
graph: CommonGraph,
level: int,
fuse_quant: bool,
group_conv_rewrite: bool,
rewrite_quantizable: bool,
tflite_micro_rewrite: bool,
quantize_input_output_type: typing.Optional[str],
fuse_input_indices: typing.Optional[typing.List[int]] = None,
fuse_output_indices: typing.Optional[typing.List[int]] = None,
max_transpose_dims: int = -1,
bypass_elementwise_passthrough_constraint: bool = False,
group_tensors: bool = False,
conv_transpose_with_bias: bool = True,
hybrid_int16_lstm: bool = False,
) -> None:
self.graph = graph
self.fuse_tensor_count = 0
self.fuse_attr_count = 0
self.level = level
self.fuse_quant = fuse_quant
self.group_conv_rewrite = group_conv_rewrite
self.rewrite_quantizable = rewrite_quantizable
self.tflite_micro_rewrite = tflite_micro_rewrite
self.quantize_input_output_type = quantize_input_output_type
self.fuse_input_indices = fuse_input_indices
self.fuse_output_indices = fuse_output_indices
self.max_transpose_dims = max_transpose_dims
self.bypass_elementwise_passthrough_constraint = bypass_elementwise_passthrough_constraint
self.group_tensors = group_tensors
self.conv_transpose_with_bias = conv_transpose_with_bias
self.hybrid_int16_lstm = hybrid_int16_lstm
def create_attr_tensor(
self, tensor: tfl.Tensor, name: str = None, quantization: typing.Optional[tfl.QuantizationParameters] = None
):
if name is None:
if self.fuse_attr_count == 0:
name = 'fuse_attr'
else:
name = f'fuse_attr_{self.fuse_attr_count}'
self.fuse_attr_count += 1
return tfl.Tensor(tensor, name, has_buffer=True, quantization=quantization)
def create_transform_tensor(
self, tensor: tfl.Tensor, name: str = None, quantization: typing.Optional[tfl.QuantizationParameters] = None
):
if name is None:
if self.fuse_tensor_count == 0:
name = 'fuse_transform'
else:
name = f'fuse_transform_{self.fuse_tensor_count}'
self.fuse_tensor_count += 1
return tfl.Tensor(tensor, name, has_buffer=False, quantization=quantization)
@class_conditional(lambda self: self.level >= GraphOptimizer.FUSE_BN)
def fuse_conv_fc_bn(self):
# Find fusable ops
edges = self.graph.graph.es.select(functools.partial(is_bn_fusable_edge, graph_converter=self.graph.graph))
filtered_pairs = ((self.graph.graph.vs[x.source], self.graph.graph.vs[x.target], x) for x in edges)
remove_ids = []
actions = []
for conv, bn, tensor in filtered_pairs:
bn_activ = bn['op'].fusedActivationFunction
conv_activ = getattr(conv['op'], 'fusedActivationFunction', None)
if conv_activ is None and bn_activ != ActivationFunctionType.NONE:
continue
# Find out the output of the batch-norm nodes
new_output = bn['outputs'][0]
assert new_output in self.graph.tensor_map
# For each node that is next of a batch-norm node, we connect it with the conv node
self.graph.connect_next_tensors(bn, conv, new_output)
# Update graph, prepare to drop the output tensor of the conv node and use the output tensor of the
# batch-norm instead
conv['outputs'][0] = new_output
conv['op'].outputs[0] = self.graph.tensor_map[new_output]
self.graph.tensor_node_map[new_output] = conv['name']
tensor['name'] = bn['outputs'][0]
tensor['label'] = bn['outputs'][0]
if bn_activ != ActivationFunctionType.NONE and conv_activ == ActivationFunctionType.NONE:
conv['op'].fusedActivationFunction = bn_activ
# Collect the arguments of the conv and batch-norm nodes
weight = conv['op'].inputs[1]
bias = conv['op'].inputs[2] if len(conv['op'].inputs) > 2 else None
bn_w, bn_b, bn_mean, bn_var = bn['op'].inputs[1:]
bn_w, bn_b, bn_mean, bn_var = (
bn_w.tensor.copy(),
bn_b.tensor.copy(),
bn_mean.tensor.copy(),
bn_var.tensor.copy(),
)
activ_w = weight.tensor.copy()
activ_b = bias.tensor.copy() if bias is not None else None
eps = bn['op'].eps
# Fuse conv/fc and batch-norm
new_weight = fuse_bn_weight(
eps, bn_w, bn_var, activ_w, conv['node_type'] == ExtendedOperator.GENERIC_DECONV
)
new_bias = fuse_bn_bias(eps, bn_w, bn_var, bn_mean, bn_b, activ_b)
# New attribute tensors
new_w = self.create_attr_tensor(new_weight)
new_b = self.create_attr_tensor(new_bias)
# Collect the actions we should take here
# The reason that we don't do the actions here is because we are currently in the loop of vertices,
# the iterator will be invalidated once `replace_operator_input` is called
actions.append((self.graph.replace_operator_input, (conv, 1, new_w)))
if bias is not None:
actions.append((self.graph.replace_operator_input, (conv, 2, new_b)))
else:
actions.append((self.graph.append_operator_input, (conv, new_b)))
remove_ids.append(bn.index)
# Process actions
for func, args in actions:
func(*args)
# Delete batch-norm nodes
for id in remove_ids:
vertex = self.graph.graph.vs[id]
assert vertex['node_type'] == ExtendedOperator.BATCH_NORM
self.graph.graph.delete_vertices(remove_ids)
@class_conditional(lambda self: self.level >= GraphOptimizer.FUSE_BN)
def fuse_bn_conv(self):
edges = self.graph.graph.es.select(functools.partial(is_rev_bn_fusable_edge, graph_converter=self.graph.graph))
filtered_pairs = ((self.graph.graph.vs[x.source], self.graph.graph.vs[x.target]) for x in edges)
def _remove_last_pred(seq):
bn = seq[0]
conv = seq[1]
# Collect the arguments of the conv and batch-norm nodes
weight = conv['op'].inputs[1]
bias = conv['op'].inputs[2] if len(conv['op'].inputs) > 2 else None
bn_w, bn_b, bn_mean, bn_var = bn['op'].inputs[1:]
bn_w, bn_b, bn_mean, bn_var = (
bn_w.tensor.copy(),
bn_b.tensor.copy(),
bn_mean.tensor.copy(),
bn_var.tensor.copy(),
)
activ_w = weight.tensor.copy()
activ_b = bias.tensor.copy() if bias is not None else None
eps = bn['op'].eps
new_weight = fuse_rev_bn_weight(eps, bn_w, bn_var, activ_w)
new_bias = fuse_rev_bn_bias(eps, bn_w, bn_var, bn_mean, bn_b, activ_b, activ_w)
return False, (conv, bias, new_weight, new_bias)
def _remove_last_action(first_node, last_node, custom_data):
conv, bias, new_weight, new_bias = custom_data
new_w = self.create_attr_tensor(new_weight)
new_b = self.create_attr_tensor(new_bias)
actions = []
actions.append((self.graph.replace_operator_input, (conv, 1, new_w)))
if bias is not None:
actions.append((self.graph.replace_operator_input, (conv, 2, new_b)))
else:
actions.append((self.graph.append_operator_input, (conv, new_b)))
return actions
def _skip_pred(seq):
bn = seq[0]['op']
conv = seq[1]['op']
skip = bn.inputs[0].quantization is not None or (
conv.inputs[1].shape[1] == 1 and conv.inputs[1].shape[0] == conv.groups and conv.groups > 1
)
return skip
elinimate_sequences(
self.graph,
filtered_pairs,
True,
None,
_remove_last_pred,
_remove_last_action,
_skip_pred,
force_forward_input=True,
)
@class_conditional(lambda self: self.level >= GraphOptimizer.COMMON_OPTIMIZE)
def fuse_activation(self):
# Find fusable ops
edges = self.graph.graph.es.select(functools.partial(is_activ_fusable_edge, graph_converter=self.graph.graph))
filtered_pairs = ((self.graph.graph.vs[x.source], self.graph.graph.vs[x.target], x) for x in edges)
remove_ids = []
for pre_activ, activ, tensor in filtered_pairs:
if not self.conv_transpose_with_bias and pre_activ['node_type'] == ExtendedOperator.GENERIC_DECONV:
continue
# Find out the output of the batch-norm nodes
new_output = activ['outputs'][0]
assert new_output in self.graph.tensor_map
# For each node that is next of the activation node, we connect it with the previous node
self.graph.connect_next_tensors(activ, pre_activ, new_output)
# Update graph, prepare to drop the output tensor of the conv node and use the output tensor of the
# batch-norm instead
pre_activ['outputs'][0] = new_output
pre_activ['op'].outputs[0] = self.graph.tensor_map[new_output]
self.graph.tensor_node_map[new_output] = pre_activ['name']
tensor['name'] = activ['outputs'][0]
tensor['label'] = activ['outputs'][0]
# Fuse activation
pre_activ['op'].fusedActivationFunction = FUSE_ACTIVATION_MAP[activ['node_type']]
remove_ids.append(activ.index)
# Delete activation nodes
self.graph.graph.delete_vertices(remove_ids)
@class_conditional(lambda self: self.level >= GraphOptimizer.COMMON_OPTIMIZE)
def fuse_same_padding(self):
edges = self.graph.graph.es.select(functools.partial(is_padding_fusable_edge, graph_converter=self.graph.graph))
filtered_pairs = ((self.graph.graph.vs[x.source], self.graph.graph.vs[x.target]) for x in edges)
def _remove_last_pred(seq):
op = seq[1]['op']
return False, op
def _remove_last_action(first_node, last_node, custom_data):
op = custom_data
op.padding = Padding.SAME
return []
def _skip_pred(seq):
pad_op = seq[0]['op']
next_op = seq[1]['op']
input_shape = pad_op.inputs[0].shape[1:-1]
if seq[1]['node_type'] == ExtendedOperator.MAX_POOL_2D:
kernel_shape = (next_op.filterHeight, next_op.filterWidth)
strides = (next_op.strideH, next_op.strideW)
dilation = (1, 1)
elif seq[1]['node_type'] in (
ExtendedOperator.CONV_2D,
ExtendedOperator.DEPTHWISE_CONV_2D,
):
kernel_shape = next_op.inputs[1].shape[1:-1]
strides = (next_op.strideH, next_op.strideW)
dilation = (next_op.dilationHFactor, next_op.dilationWFactor)
elif seq[1]['node_type'] == ExtendedOperator.CONV_3D:
kernel_shape = next_op.inputs[1].shape[:3]
strides = (next_op.strideD, next_op.strideH, next_op.strideW)
dilation = (next_op.dilationDFactor, next_op.dilationHFactor, next_op.dilationWFactor)
pad_args = get_same_padding_args(input_shape, kernel_shape, strides, dilation)
pad_arr = np.array(pad_args, dtype='int32')
old_pad_arr = pad_op.inputs[1].tensor
skip = not np.array_equal(pad_arr, old_pad_arr)
return skip
elinimate_sequences(
self.graph,
filtered_pairs,
True,
None,
_remove_last_pred,
_remove_last_action,
_skip_pred,
force_forward_input=True,
)
@class_conditional(lambda self: self.level >= GraphOptimizer.COMMON_OPTIMIZE)
def fuse_same_padding_slicing(self):
edges = self.graph.graph.es.select(functools.partial(is_slicing_fusable_edge, graph_converter=self.graph.graph))
filtered_pairs = ((self.graph.graph.vs[x.source], self.graph.graph.vs[x.target], x) for x in edges)
remove_ids = []
actions = []
for prev_node, slice_node, tensor in filtered_pairs:
prev_op = prev_node['op']
slice_op = slice_node['op']
input_shape = slice_op.outputs[0].shape[1:-1]
if prev_node['node_type'] == ExtendedOperator.TRANSPOSE_CONV:
kernel_shape = prev_op.inputs[1].shape[1:-1]
strides = (prev_op.strideH, prev_op.strideW)
dilation = (1, 1)
elif prev_node['node_type'] == ExtendedOperator.CONV_3D_TRANSPOSE:
kernel_shape = prev_op.inputs[1].shape[:3]
strides = (prev_op.strideD, prev_op.strideH, prev_op.strideW)
dilation = (prev_op.dilationDFactor, prev_op.dilationHFactor, prev_op.dilationWFactor)
pad_args = get_same_padding_args(input_shape, kernel_shape, strides, dilation)
pad_arr = np.array(pad_args, dtype='int32')
start_arr = [x for x in slice_op.inputs[1].tensor]
end_arr = [slice_op.inputs[0].shape[i] - x - slice_op.outputs[0].shape[i] for i, x in enumerate(start_arr)]
old_pad_args = [[x, y] for x, y in zip(start_arr, end_arr)]
skip = not np.array_equal(pad_arr, old_pad_args)
if skip:
continue
# Find out the output of the slice nodes
new_output = slice_node['outputs'][0]
assert new_output in self.graph.tensor_map
# For each node that is next of the slice_nodeation node, we connect it with the previous node
self.graph.connect_next_tensors(slice_node, prev_node, new_output)
# Update graph, prepare to drop the output tensor of the conv node and use the output tensor of the
# slice op instead
prev_node['outputs'][0] = new_output
prev_node['op'].outputs[0] = self.graph.tensor_map[new_output]
self.graph.tensor_node_map[new_output] = prev_node['name']
tensor['name'] = slice_node['outputs'][0]
tensor['label'] = slice_node['outputs'][0]
# Fuse padding
prev_node['op'].padding = Padding.SAME
new_shape = np.array(prev_node['op'].outputs[0].shape, dtype='int32')
new_shape_tensor = self.create_attr_tensor(new_shape)
actions.append((self.graph.replace_operator_input, (prev_node, 0, new_shape_tensor)))
remove_ids.append(slice_node.index)
for func, args in actions:
func(*args)
# Delete activation nodes
self.graph.graph.delete_vertices(remove_ids)
@class_conditional(lambda self: self.level >= GraphOptimizer.COMMON_OPTIMIZE)
def fuse_requantize(self):
# Find fusable ops
edges = self.graph.graph.es.select(
functools.partial(is_requantize_fusable_edge, graph_converter=self.graph.graph)
)
filtered_pairs = ((self.graph.graph.vs[x.source], self.graph.graph.vs[x.target], x) for x in edges)
remove_ids = []
for pre_activ, activ, tensor in filtered_pairs:
if pre_activ.outdegree() > 1:
skip = False
pre_quantize = None
for out_edge in pre_activ.out_edges():
next_node = self.graph.graph.vs[out_edge.target]
while True:
if next_node['node_type'] == ExtendedOperator.QUANTIZE:
if pre_quantize is None:
pre_quantize = next_node['op'].outputs[0].quantization
else:
cur_quantize = next_node['op'].outputs[0].quantization
if (
pre_quantize.scale != cur_quantize.scale
or pre_quantize.zero_point != cur_quantize.zero_point
or pre_quantize.dim != cur_quantize.dim
):
skip = True
break
elif next_node['node_type'] == ExtendedOperator.DEQUANTIZE:
break
elif next_node['node_type'] in (ExtendedOperator.RESHAPE, ExtendedOperator.TRANSPOSE):
if next_node.outdegree() > 1:
skip = True
break
else:
next_node = self.graph.graph.vs[next_node.out_edges()[0].target]
else:
skip = True
break
if skip:
break
if skip:
continue
# Find out the output of the first node in the sequence
output_name = activ['op'].inputs[0].name
output_idx = pre_activ['outputs'].index(output_name)
new_output = pre_activ['outputs'][output_idx]
assert new_output in self.graph.tensor_map
# For each node that is next of the last node, we connect it with the first node
# Also, the replace the tensors when needed
self.graph.replace_next_tensors(activ, pre_activ, new_output)
new_tensor = pre_activ['op'].outputs[0]
old_tensor = activ['op'].outputs[0]
new_tensor.quantization = old_tensor.quantization
else:
# Find out the output of the batch-norm nodes
new_output = activ['outputs'][0]
assert new_output in self.graph.tensor_map
# For each node that is next of the activation node, we connect it with the previous node
self.graph.connect_next_tensors(activ, pre_activ, new_output)
# Update graph, prepare to drop the output tensor of the conv node and use the output tensor of the
# batch-norm instead
pre_activ['outputs'][0] = new_output
pre_activ['op'].outputs[0] = self.graph.tensor_map[new_output]
self.graph.tensor_node_map[new_output] = pre_activ['name']
tensor['name'] = activ['outputs'][0]
tensor['label'] = activ['outputs'][0]
remove_ids.append(activ.index)
# Delete activation nodes
self.graph.graph.delete_vertices(remove_ids)
@class_conditional(lambda self: self.level >= GraphOptimizer.COMMON_OPTIMIZE)
def fuse_reciprocal_sqrt(self):
# Find fusable ops
edges = self.graph.graph.es.select(functools.partial(is_reciprocal_sqrt_edge, graph_converter=self.graph.graph))
filtered_pairs = ((self.graph.graph.vs[x.source], self.graph.graph.vs[x.target], x) for x in edges)
remove_ids = []
for sqrt, div, tensor in filtered_pairs:
sqrt['node_type'] = ExtendedOperator.RSQRT
sqrt['op'] = tfl.RsqrtOperator(sqrt['op'].inputs, sqrt['op'].outputs)
div_op = div['op']
if (
div_op.inputs[0].buffer is not None
and np.all(div_op.inputs[0].tensor == 1.0)
and div['op'].fusedActivationFunction == ActivationFunctionType.NONE
):
new_output = div['outputs'][0]
assert new_output in self.graph.tensor_map
# For each node that is next of the div node, we connect it with the previous node
self.graph.connect_next_tensors(div, sqrt, new_output)
# Update graph, prepare to drop the output tensor of the div node and use the output tensor of the
# sqrt instead
sqrt['outputs'][0] = new_output
sqrt['op'].outputs[0] = self.graph.tensor_map[new_output]
self.graph.tensor_node_map[new_output] = sqrt['name']
tensor['name'] = div['outputs'][0]
tensor['label'] = div['outputs'][0]
# remove div op
remove_ids.append(div.index)
else:
div['node_type'] = ExtendedOperator.MUL
div['op'] = tfl.MulOperator(
div['op'].inputs, div['op'].outputs, fusedActivationFunction=div['op'].fusedActivationFunction
)
# Delete div nodes
self.graph.graph.delete_vertices(remove_ids)
@class_conditional(lambda self: self.level >= GraphOptimizer.COMMON_OPTIMIZE)
def remove_tile_before_binary_elementwise_ops(self):
# Find fusable ops
edges = self.graph.graph.es.select(functools.partial(is_tile_binary_op_edge, graph_converter=self.graph.graph))
filtered_pairs = ((self.graph.graph.vs[x.source], self.graph.graph.vs[x.target], x) for x in edges)
remove_ids = []
actions = []
binary_op_ids = set()
for tile, op_node, tensor in filtered_pairs:
tile_op = tile['op']
binary_op = op_node['op']
input_idx = None
for i in range(2):
try:
_ = tile['outputs'].index(binary_op.inputs[i].name)
input_idx = i
break
except ValueError:
pass
if input_idx is None:
continue
alter_input_idx = 1 - input_idx
try:
out_shape = np.broadcast_shapes(binary_op.inputs[alter_input_idx].shape, tile_op.inputs[0].shape)
if out_shape != binary_op.outputs[0].shape:
continue
except ValueError:
continue
if op_node.index not in binary_op_ids:
binary_op_ids.add(op_node.index)
else:
continue
new_tensor = tile_op.inputs[0]
# Replace input tensors
actions.append((self.graph.replace_operator_input, (op_node, input_idx, new_tensor)))
# remove tile op
remove_ids.append(tile.index)
# Process actions
for func, args in actions:
func(*args)
# Delete tile nodes
self.graph.graph.delete_vertices(remove_ids)
@class_conditional(lambda self: self.level >= GraphOptimizer.COMMON_OPTIMIZE)
def fuse_conv2d_gather(self):
# Find fusable ops
edges = self.graph.graph.es.select(functools.partial(is_conv2d_gather_edge, graph_converter=self.graph.graph))
filtered_pairs = ((self.graph.graph.vs[x.source], self.graph.graph.vs[x.target], x) for x in edges)
remove_ids = []
actions = []
for conv, gather, tensor in filtered_pairs:
# Find out the output of the batch-norm nodes
new_output = gather['outputs'][0]
assert new_output in self.graph.tensor_map
# For each node that is next of the activation node, we connect it with the previous node
self.graph.connect_next_tensors(gather, conv, new_output)
# Update graph, prepare to drop the output tensor of the gather node and use the output tensor of the
# conv instead
conv['outputs'][0] = new_output
conv_out_quant_param = conv['op'].outputs[0].quantization
conv['op'].outputs[0] = self.graph.tensor_map[new_output]
conv['op'].outputs[0].quantization = conv_out_quant_param
self.graph.tensor_node_map[new_output] = conv['name']
tensor['name'] = gather['outputs'][0]
tensor['label'] = gather['outputs'][0]
# permute weight of conv-op
indx = gather['op'].inputs[1].tensor.copy()
w = conv['op'].inputs[1].tensor.copy()
w_quant_param = conv['op'].inputs[1].quantization
new_w = np.take(w, indx, axis=0)
# permute bias of conv-op
b = conv['op'].inputs[2].tensor.copy() if len(conv['op'].inputs) > 2 else None
b_quant_param = conv['op'].inputs[2].quantization
new_b = np.take(b, indx, axis=0) if b is not None else None
if w_quant_param is not None and isinstance(w_quant_param.scale, list) and w_quant_param.dim == 0:
new_w_scale = np.take(w_quant_param.scale, indx, axis=0)
new_w_zeros = np.take(w_quant_param.zero_point, indx, axis=0)
w_quant_param.scale = new_w_scale
w_quant_param.zero_point = new_w_zeros
if new_b is not None:
new_b_scale = np.take(b_quant_param.scale, indx, axis=0)
new_b_zeros = np.take(b_quant_param.zero_point, indx, axis=0)
b_quant_param.scale = new_b_scale
b_quant_param.zero_point = new_b_zeros
new_w = self.create_attr_tensor(new_w, quantization=w_quant_param)
actions.append((self.graph.replace_operator_input, (conv, 1, new_w)))
new_b = self.create_attr_tensor(new_b, quantization=b_quant_param)
actions.append((self.graph.replace_operator_input, (conv, 2, new_b)))
# remove gather op
remove_ids.append(gather.index)
# Process actions
for func, args in actions:
func(*args)
# Delete activation nodes
self.graph.graph.delete_vertices(remove_ids)
@class_conditional(lambda self: self.level >= GraphOptimizer.COMMON_OPTIMIZE)
def fuse_gather_conv2d(self):
# Find fusable ops
edges = self.graph.graph.es.select(functools.partial(is_gather_conv2d_edge, graph_converter=self.graph.graph))
filtered_pairs = ((self.graph.graph.vs[x.source], self.graph.graph.vs[x.target]) for x in edges)
def _remove_last_pred(seq):
gather = seq[0]
conv = seq[1]
return False, (gather, conv)
def _remove_last_action(first_node, last_node, custom_data):
gather, conv = custom_data
actions = []
indx = np.argsort(gather['op'].inputs[1].tensor)
w = conv['op'].inputs[1].tensor.copy()
w_quant_param = conv['op'].inputs[1].quantization
new_w = np.take(w, indx, axis=3)
if w_quant_param is not None and isinstance(w_quant_param.scale, list) and w_quant_param.dim == 3:
new_w_scale = np.take(w_quant_param.scale, indx, axis=0)
new_w_zeros = np.take(w_quant_param.zero_point, indx, axis=0)
w_quant_param.scale = new_w_scale
w_quant_param.zero_point = new_w_zeros
new_w = self.create_attr_tensor(new_w, quantization=w_quant_param)
actions.append((self.graph.replace_operator_input, (conv, 1, new_w)))
return actions
elinimate_sequences(
self.graph,
filtered_pairs,
True,
None,
_remove_last_pred,
_remove_last_action,
False,
force_forward_input=True,
)
@class_conditional(lambda self: self.tflite_micro_rewrite)
def split_requantize(self):
vertices = self.graph.graph.vs.select(functools.partial(is_requantize_node, graph_converter=self.graph.graph))
remove_ids = []
ops = []
restore_mapping = []
for quantize in vertices:
restore_nodes = []
# For each node that is next of a transformable node,
# a. if it is an output node, remove it anyway since it will always be reconstructed
# b. otherwise, record the info of the edge so that we may restore it after reconstruction
for out_edge in quantize.out_edges():
next_node = self.graph.graph.vs[out_edge.target]
if next_node['node_type'] == ExtendedOperator.OUTPUT_NODE:
remove_ids.append(next_node.index)
del self.graph.tensor_map[next_node['outputs'][0]]
del self.graph.tensor_node_map[next_node['outputs'][0]]
else:
restore_nodes.append((out_edge['name'], next_node['name']))
# Remove the mapping since they are going to be removed
for output_name in quantize['outputs']:
del self.graph.tensor_map[output_name]
del self.graph.tensor_node_map[output_name]
restore_mapping.append(restore_nodes)
remove_ids.append(quantize.index)
# Make sure the nodes are topologically sorted
sorted_ops = [node['op'] for node in sorted(vertices, key=lambda x: int(re.search(r'\d+', x['name'])[0]))]
# Delete nodes before transformation in the graph
self.graph.graph.delete_vertices(remove_ids)
for quantize, mapping in zip(sorted_ops, restore_mapping):
input_tensor = quantize.inputs[0]
output_tensor = quantize.outputs[0]
intermediate = self.create_transform_tensor(input_tensor.tensor.astype('float32'))
ops.append(tfl.DequantizeOperator([input_tensor], [intermediate]))
ops.append(tfl.QuantizeOperator([intermediate], [output_tensor]))
for op in ops:
self.graph.add_operator(op, transform=True)
self.graph.try_restore_edges(mapping)
def transform_graph(self):
# Find transformable ops
filtered_nodes = self.graph.graph.vs.select(
functools.partial(is_transformable_node, graph_converter=self.graph.graph)
)
remove_ids = []
ops = []
restore_mapping = []
for node in filtered_nodes:
restore_nodes = []
# For each node that is next of a transformable node,
# a. if it is an output node, remove it anyway since it will always be reconstructed
# b. otherwise, record the info of the edge so that we may restore it after reconstruction
for out_edge in node.out_edges():
next_node = self.graph.graph.vs[out_edge.target]
if next_node['node_type'] == ExtendedOperator.OUTPUT_NODE:
remove_ids.append(next_node.index)
del self.graph.tensor_map[next_node['outputs'][0]]
del self.graph.tensor_node_map[next_node['outputs'][0]]
else:
restore_nodes.append((out_edge['name'], next_node['name']))
# Remove the mapping since they are going to be removed
for output_name in node['outputs']:
del self.graph.tensor_map[output_name]
del self.graph.tensor_node_map[output_name]
restore_mapping.append(restore_nodes)
ops.append(node)
remove_ids.append(node.index)
# Make sure the nodes are topologically sorted
sorted_ops = [node['op'] for node in sorted(ops, key=lambda x: int(re.search(r'\d+', x['name'])[0]))]
# Delete nodes before transformation in the graph
self.graph.graph.delete_vertices(remove_ids)
# Do transformation
for op, mapping in zip(sorted_ops, restore_mapping):
op.transform(self.graph, mapping)
@class_conditional(lambda self: self.level >= GraphOptimizer.COMMON_OPTIMIZE)
def fuse_simple_transpose_pass(self):
edges = self.graph.graph.es.select(
functools.partial(is_transpose_fusable_edge, graph_converter=self.graph.graph)
)
filtered_pairs = [[self.graph.graph.vs[x.source], self.graph.graph.vs[x.target]] for x in edges]
# Try to fuse the edges
filtered_pairs = fuse_connected_edges(filtered_pairs)
def _remove_first_pred(seq):
new_perm = fuse_transpose_perms(seq)
hints = set()
for node in seq:
if 'direction' in node['op'].extra_hints:
hints.add(node['op'].extra_hints['direction'])
if len(hints) == 1:
hint = next(iter(hints))
else:
hint = None
remove_first = np.array_equal(new_perm, np.sort(new_perm))
return remove_first, (new_perm, hint)
def _remove_first_action(first_node, last_node, custom_data):
# Set fused perm to the first transpose node
new_perm, hint = custom_data
if hint is None:
if 'direction' in first_node['op'].extra_hints:
del first_node['op'].extra_hints['direction']
else:
first_node['op'].extra_hints['direction'] = hint
new_perm_tensor = self.create_attr_tensor(new_perm)
action = (self.graph.replace_operator_input, (first_node, 1, new_perm_tensor))
return [action]
elinimate_sequences(self.graph, filtered_pairs, _remove_first_pred, _remove_first_action)
@class_conditional(lambda self: self.level >= GraphOptimizer.COMMON_OPTIMIZE)
def fuse_simple_gather_pass(self):
edges = self.graph.graph.es.select(functools.partial(is_gather_fusable_edge, graph_converter=self.graph.graph))
filtered_pairs = [[self.graph.graph.vs[x.source], self.graph.graph.vs[x.target]] for x in edges]
# Try to fuse the edges
filtered_pairs = fuse_connected_edges(filtered_pairs)
def _remove_first_pred(seq):
new_perm = fuse_transpose_perms(seq)
hints = set()
for node in seq:
if 'direction' in node['op'].extra_hints:
hints.add(node['op'].extra_hints['direction'])
if len(hints) == 1:
hint = next(iter(hints))
else:
hint = None
remove_first = np.array_equal(new_perm, np.sort(new_perm))
return remove_first, (new_perm, hint)
def _remove_first_action(first_node, last_node, custom_data):
# Set fused perm to the first transpose node
new_perm, hint = custom_data
if hint is None:
if 'direction' in first_node['op'].extra_hints:
del first_node['op'].extra_hints['direction']
else:
first_node['op'].extra_hints['direction'] = hint
new_perm_tensor = self.create_attr_tensor(new_perm)
action = (self.graph.replace_operator_input, (first_node, 1, new_perm_tensor))
return [action]
def _skip_pred(seq):
for node in seq:
op = node['op']
idx_tensor = op.inputs[1]
if idx_tensor.buffer is None:
return True
if len(idx_tensor.shape) > 1:
return True
return False
elinimate_sequences(self.graph, filtered_pairs, _remove_first_pred, _remove_first_action, skip_pred=_skip_pred)
@class_conditional(lambda self: self.level >= GraphOptimizer.COMMON_OPTIMIZE)
def fuse_dequant_quant_pass(self, q_first):
edges = self.graph.graph.es.select(
functools.partial(is_dequant_quant_fusable_edge, graph_converter=self.graph.graph, q_first=q_first)
)
filtered_pairs = [[self.graph.graph.vs[x.source], self.graph.graph.vs[x.target]] for x in edges]
r_edges = self.graph.graph.es.select(
functools.partial(is_dequant_quant_fusable_edge, graph_converter=self.graph.graph, q_first=not q_first)
)
r_filtered_pairs = [[self.graph.graph.vs[x.source], self.graph.graph.vs[x.target]] for x in r_edges]
filtered_pairs = fuse_connected_edges(filtered_pairs + r_filtered_pairs)
new_pairs = []
for seq in filtered_pairs:
start_idx = 0
end_idx = len(seq)
if q_first:
if seq[0]['node_type'] != ExtendedOperator.QUANTIZE:
start_idx += 1
if seq[-1]['node_type'] != ExtendedOperator.DEQUANTIZE:
end_idx -= 1
else:
if seq[0]['node_type'] != ExtendedOperator.DEQUANTIZE:
start_idx += 1
if seq[-1]['node_type'] != ExtendedOperator.QUANTIZE:
end_idx -= 1
new_seq = seq[start_idx:end_idx]
if len(new_seq) >= 2:
new_pairs.append(new_seq)
filtered_pairs = new_pairs
def _remove_first_pred(seq):
first_node, last_node = seq[0], seq[-1]
new_qparams = last_node['op'].outputs[0].quantization
orig_qparams = first_node['op'].inputs[0].quantization
if (
first_node['node_type'] == ExtendedOperator.DEQUANTIZE
and last_node['node_type'] == ExtendedOperator.QUANTIZE
):
assert new_qparams is not None
assert orig_qparams is not None
remove_first = (
new_qparams.scale == orig_qparams.scale
and new_qparams.zero_point == orig_qparams.zero_point
and new_qparams.dim == orig_qparams.dim
)
else:
assert new_qparams is None
assert orig_qparams is None
remove_first = True
return remove_first, None
def _remove_first_action(first_node, last_node, custom_data):
# Set new node type to first node
first_node['node_type'] = ExtendedOperator.QUANTIZE
old_op = first_node['op']
first_node['op'] = tfl.QuantizeOperator(old_op.inputs, old_op.outputs)
return []
elinimate_sequences(self.graph, filtered_pairs, _remove_first_pred, _remove_first_action)
@class_conditional(lambda self: self.level >= GraphOptimizer.COMMON_OPTIMIZE)
def fuse_simple_reshape_pass(self):
edges = self.graph.graph.es.select(functools.partial(is_reshape_fusable_edge, graph_converter=self.graph.graph))
filtered_pairs = [[self.graph.graph.vs[x.source], self.graph.graph.vs[x.target]] for x in edges]
# Try to fuse the edge
filtered_pairs = fuse_connected_edges(filtered_pairs)
def _remove_first_pred(seq):
first_node, last_node = seq[0], seq[-1]
new_shape = last_node['op'].inputs[1].tensor
orig_shape = np.array(first_node['op'].inputs[0].shape, dtype='int32')
hints = set()
for node in seq:
if 'direction' in node['op'].extra_hints:
hints.add(node['op'].extra_hints['direction'])
if len(hints) == 1:
hint = next(iter(hints))
else:
hint = None
remove_first = np.array_equal(new_shape, orig_shape)
return remove_first, (new_shape, hint)
def _remove_first_action(first_node, last_node, custom_data):
# Set final shape to the first reshape node
new_shape, hint = custom_data
if hint is None:
if 'direction' in first_node['op'].extra_hints:
del first_node['op'].extra_hints['direction']
else:
first_node['op'].extra_hints['direction'] = hint
new_shape_tensor = self.create_attr_tensor(np.array(new_shape, dtype='int32'))
first_node['op'].newShape = new_shape_tensor.tensor
action = (self.graph.replace_operator_input, (first_node, 1, new_shape_tensor))
return [action]
elinimate_sequences(self.graph, filtered_pairs, _remove_first_pred, _remove_first_action)
@class_conditional(lambda self: self.level >= GraphOptimizer.COMMON_OPTIMIZE)
def fuse_simple_slice_pass(self):
edges = self.graph.graph.es.select(functools.partial(is_slice_fusable_edge, graph_converter=self.graph.graph))
filtered_pairs = [[self.graph.graph.vs[x.source], self.graph.graph.vs[x.target]] for x in edges]
# Try to fuse the edge
filtered_pairs = fuse_connected_edges(filtered_pairs)
def _remove_first_pred(seq):
fused_info = fuse_slices(seq)
return False, fused_info
def _remove_first_action(first_node, last_node, custom_data):
# Set final shape to the first reshape node
start, end, stride = custom_data
if all((x == 1 for x in stride)):
target_class = tfl.SliceOperator
target_type = ExtendedOperator.SLICE
else:
target_class = tfl.StridedSliceOperator
target_type = ExtendedOperator.STRIDED_SLICE
if target_type == ExtendedOperator.SLICE:
size = end - start
start_tensor = self.create_attr_tensor(np.array(start, dtype='int32'))
size_tensor = self.create_attr_tensor(np.array(size, dtype='int32'))
actions = [
(self.graph.replace_operator_input, (first_node, 1, start_tensor)),
(self.graph.replace_operator_input, (first_node, 2, size_tensor)),
]
if first_node['node_type'] != ExtendedOperator.SLICE:
old_slice_op = first_node['op']
first_node['node_type'] = ExtendedOperator.SLICE
first_node['op'] = target_class(old_slice_op.inputs, old_slice_op.outputs)
actions.append((self.graph.remove_operator_input, (first_node, 3)))
else:
size = end - start
start_tensor = self.create_attr_tensor(np.array(start, dtype='int32'))
end_tensor = self.create_attr_tensor(np.array(end, dtype='int32'))
stride_tensor = self.create_attr_tensor(np.array(stride, dtype='int32'))
if first_node['node_type'] == ExtendedOperator.STRIDED_SLICE:
actions = [
(self.graph.replace_operator_input, (first_node, 1, start_tensor)),
(self.graph.replace_operator_input, (first_node, 2, end_tensor)),
(self.graph.replace_operator_input, (first_node, 3, stride_tensor)),
]
else:
old_slice_op = first_node['op']
first_node['node_type'] = ExtendedOperator.STRIDED_SLICE
first_node['op'] = target_class(old_slice_op.inputs, old_slice_op.outputs)
actions = [
(self.graph.replace_operator_input, (first_node, 1, start_tensor)),
(self.graph.replace_operator_input, (first_node, 2, end_tensor)),
(self.graph.append_operator_input, (first_node, stride_tensor)),