-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathmodifier.py
3428 lines (2711 loc) · 138 KB
/
modifier.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from collections import OrderedDict
from copy import deepcopy
import torch
import torch.nn as nn
import typing
from tinynn.graph.tracer import TraceNode, TraceGraph
from tinynn.util.util import get_logger
from tinynn.graph import masker
import numpy as np
log = get_logger(__name__)
def complementary_list(a, b):
return list(set(a).difference(set(b)))
def get_smallest_k(lst, k, offset=0):
idx_lst = [(i, float(lst[i])) for i in range(len(lst))]
sorted_lst = sorted(idx_lst, key=lambda x: x[1])
sorted_lst_k = sorted_lst[:k]
idx = [sorted_lst_k[i][0] + offset for i in range(len(sorted_lst_k))]
return sorted(idx)
def rnn_gate_size(module: nn.Module) -> int:
"""the gate size of the recurrent modules"""
if isinstance(module, nn.RNN):
return 1
elif isinstance(module, nn.GRU):
return 3
elif isinstance(module, nn.LSTM):
return 4
else:
raise AttributeError(f'gate size of {type(module)} is unknown')
def update_weight_metric(importance, metric_func, module, name):
if type(module) in [nn.Linear, nn.Conv2d, nn.Conv1d, nn.ConvTranspose2d, nn.ConvTranspose1d]:
importance[name] = metric_func(module.weight, module)
elif type(module) in [nn.GRU, nn.LSTM, nn.RNN]:
num_directions = 2 if module.bidirectional else 1
has_proj = hasattr(module, 'proj_size') and module.proj_size > 0
gs = rnn_gate_size(module)
weights = []
if has_proj:
for i in range(module.num_layers):
weight_hrs = []
for j in range(num_directions):
suffix = '_reverse' if j > 0 else ''
weight_hr = getattr(module, f'weight_hr_l{i}{suffix}')
weight_hrs.append(weight_hr)
weights.append(torch.cat(weight_hrs, dim=0))
importance[name] = metric_func(weights, module)
weights.clear()
name = f'{name}:h'
for i in range(module.num_layers):
weight_ihs = []
weight_hhs = []
for j in range(num_directions):
suffix = '_reverse' if j > 0 else ''
weight_ih = getattr(module, f'weight_ih_l{i}{suffix}')
weight_hh = getattr(module, f'weight_hh_l{i}{suffix}')
weight_ihs.append(weight_ih)
weight_hhs.append(weight_hh)
if gs == 1:
weights.append(torch.cat(weight_ihs, dim=0))
weights.append(torch.cat(weight_hhs, dim=0))
else:
w_ih_splits = zip(*[torch.unbind(x.view(gs, module.hidden_size, -1)) for x in weight_ihs])
w_hh_splits = zip(*[torch.unbind(x.view(gs, module.hidden_size, -1)) for x in weight_hhs])
ih_gate_weights = [torch.cat(x) for x in w_ih_splits]
hh_gate_weights = [torch.cat(x) for x in w_hh_splits]
weights.extend(ih_gate_weights)
weights.extend(hh_gate_weights)
importance[name] = metric_func(weights, module)
else:
raise AttributeError(f'{type(module).__name__}({name}) is not supported for importance calculation')
def random(tensor, module):
if type(module) in [nn.Linear, nn.Conv2d, nn.Conv1d]:
return torch.randperm(tensor.shape[0])
if type(module) in [nn.ConvTranspose2d, nn.ConvTranspose1d]:
return torch.randperm(tensor.shape[1])
if type(module) in [nn.GRU, nn.LSTM, nn.RNN]:
assert isinstance(tensor, (tuple, list))
return torch.randperm(tensor[0].shape[1])
def l1_norm(tensor, module):
"""Calculate the L1-normalization of each channel"""
if type(module) in [nn.Conv2d]:
return torch.norm(tensor, p=1, dim=[1, 2, 3])
if type(module) in [nn.Conv1d]:
return torch.norm(tensor, p=1, dim=[1, 2])
if type(module) in [nn.Linear]:
return torch.norm(tensor, p=1, dim=[1])
if type(module) in [nn.ConvTranspose2d]:
return torch.norm(tensor, p=1, dim=[0, 2, 3])
if type(module) in [nn.ConvTranspose1d]:
return torch.norm(tensor, p=1, dim=[0, 2])
if type(module) in [nn.GRU, nn.LSTM, nn.RNN]:
assert isinstance(tensor, (tuple, list))
return torch.sum(torch.stack([torch.norm(t, p=1, dim=[1]) for t in tensor]), dim=0)
def l2_norm(tensor, module):
"""Calculate the L2-normalization of each channel"""
if type(module) in [nn.Conv2d]:
return torch.norm(tensor, p=2, dim=[1, 2, 3])
if type(module) in [nn.Conv1d]:
return torch.norm(tensor, p=2, dim=[1, 2])
if type(module) in [nn.Linear]:
return torch.norm(tensor, p=2, dim=[1])
if type(module) in [nn.ConvTranspose2d]:
return torch.norm(tensor, p=2, dim=[0, 2, 3])
if type(module) in [nn.ConvTranspose1d]:
return torch.norm(tensor, p=2, dim=[0, 2])
if type(module) in [nn.GRU, nn.LSTM, nn.RNN]:
assert isinstance(tensor, (tuple, list))
return torch.sum(torch.stack([torch.norm(t, p=2, dim=[1]) for t in tensor]), dim=0)
def fpgm(tensor, module):
"""Calculate the geometric median (Filter Pruning via Geometric Median for Deep Convolutional Neural
Networks Acceleration, https://arxiv.org/abs/1811.00250)"""
assert type(module) in [nn.Linear, nn.Conv2d]
num_channels = tensor.shape[0]
batched_weight = tensor.view(num_channels, -1)
return torch.cdist(batched_weight, batched_weight, p=2).abs().sum(0)
def is_dw_conv(module):
"""Check whether the model is depth-wise convolution"""
if isinstance(module, (nn.Conv2d, nn.ConvTranspose2d, nn.Conv1d, nn.ConvTranspose1d)):
if module.in_channels == module.groups == module.out_channels:
return True
return False
def merge_group(group: list):
new_group = []
while len(group) > 0:
loop = False
a = group[0]
for b in group[1:]:
if len(a & b) > 0:
k = a & b
m = a - k
n = b - k
group.remove(a)
group.remove(b)
group += [i for i in [m, n, k] if len(i) > 0]
loop = True
break
if loop:
continue
new_group.append(a)
group.remove(a)
group[:] = new_group[:]
for i in range(len(group)):
gi = group[i]
for gj in group[i + 1 :]:
if gi == gj and gi is not gj:
new_group.remove(gi)
break
group[:] = new_group[:]
group.sort()
return group
def merge_constraint(constraint: typing.List[typing.Set]):
"""Merge all constraints with intersection"""
if {-1.0} in constraint:
constraint.remove({-1.0})
value_mapping = dict()
# remove empty constraint
for idx in reversed(range(len(constraint))):
if len(constraint[idx]) == 0:
del constraint[idx]
continue
# build value_map,used to quickly find which sets the value is in
for idx in range(len(constraint)):
for value in constraint[idx]:
value_mapping[value] = value_mapping.get(value, [])
value_mapping[value].append(idx)
reindex_list = [i for i in range(len(constraint))]
# for quickly finding all sets that redirect to the same set,
homology_idx = {i: [i] for i in range(len(constraint))}
for value, idx_need_merge in value_mapping.items():
if len(idx_need_merge) <= 1:
continue
target_idx = reindex_list[idx_need_merge[0]]
for i in idx_need_merge:
if reindex_list[i] == target_idx:
continue
src_idx = reindex_list[i]
constraint[target_idx] = constraint[target_idx] | constraint[src_idx]
for j in homology_idx[src_idx]:
reindex_list[j] = target_idx
homology_idx[target_idx].append(j)
homology_idx[src_idx] = []
valid_idx = sorted(list(set(reindex_list)))
new_constraint = [constraint[i] for i in valid_idx]
constraint[:] = new_constraint[:]
return constraint
def calc_dim_constraint(tensor: torch.Tensor, dim_changes: typing.List):
"""Count all constraints under a dimension"""
constraints = {}
arr = tensor.detach().numpy()
for dim in dim_changes:
constraints[dim] = []
for i in range(tensor.shape[dim]):
arr_i = arr.take(i, axis=dim)
constraint = np.unique(arr_i)
constraint = set(constraint.tolist())
constraints[dim].append(constraint)
return constraints
def calc_dim_changes(node, tensors_i, tensors_o=None) -> typing.List[typing.Tuple[typing.List, torch.Tensor]]:
"""Calculate which dimensions of tensor have changed"""
def vector_wrapper(t):
if type(t) not in [tuple, list]:
return (t,)
else:
return t
# operator inference
if isinstance(node, nn.Module):
tensors = vector_wrapper(node(*tensors_i))
else:
with torch.no_grad():
tensors = vector_wrapper(node(vector_wrapper(tensors_i)))
if tensors_o is not None:
for i in range(len(tensors_o)):
tensors_o[i].data.copy_(tensors[i].clone().data)
else:
tensors_o = tensors
dim_changes = []
for tensor_o in tensors_o:
dim_change = []
for i in range(len(tensor_o.shape)):
reduce_dim = [j for j in range(len(tensor_o.shape)) if j != i]
if not reduce_dim:
value = set(tensor_o.detach().tolist())
else:
value = set(torch.sum(tensor_o, dim=reduce_dim).detach().tolist())
if len(value) > 1:
if i not in dim_change:
dim_change.append(i)
dim_changes.append((dim_change, tensor_o))
return dim_changes
class DimensionChangeInfo(object):
def __init__(self, modifier: 'Modifier'):
self.modifier = modifier
# Which dimensions of the input/output tensor will change
self.dim_changes_i = OrderedDict()
self.dim_changes_o = OrderedDict()
# All center nodes(operators that change actively, such as conv2d, linear in the pruning process)
self.centers = OrderedDict()
self.tensor_changes = OrderedDict()
self.tensor_keys = OrderedDict()
# The dimension of the final pruning (when multiple dimensions may change, a dimension will be
# selected through dependency analysis and conflict elimination)
self.dim_choices = OrderedDict()
self.tensor_choices = OrderedDict()
self.dim_transform = None
# The mapping relationship between the current node and the central node
self.constraints_i = OrderedDict()
self.constraints_o = OrderedDict()
# In operators such as grouped convolution and bidirectional LSTM, each tensor needs to be
# modified uniformly according to the group.
self.groups_i = []
self.groups_o = []
# Pruning index for input and output ( for structured pruning, it may be a channel,
# for unstructured pruning, it may be every point)
self.pruned_idx_i = []
self.pruned_idx_o = []
def build_key(self, center, tensor):
"""Generate human-readable keys to reduce the debugging cost of complex computational graphs"""
pre_tensor_idx = [id(t) for t in self.modifier.pre_tensors()]
nxt_tensor_idx = [id(t) for t in self.modifier.next_tensors()]
if id(tensor) in pre_tensor_idx:
tensor_idx = pre_tensor_idx.index(id(tensor))
return f'{center.unique_name()}:input_{tensor_idx}'
elif id(tensor) in nxt_tensor_idx:
tensor_idx = nxt_tensor_idx.index(id(tensor))
return f'{center.unique_name()}:output_{tensor_idx}'
else:
assert False
def build_choice_key(self, tensor):
"""Generate human-readable keys to reduce the debugging cost of complex computational graphs"""
pre_tensor_idx = [id(t) for t in self.modifier.pre_tensors()]
nxt_tensor_idx = [id(t) for t in self.modifier.next_tensors()]
if id(tensor) in pre_tensor_idx:
tensor_idx = pre_tensor_idx.index(id(tensor))
return f'input_{tensor_idx}'
elif id(tensor) in nxt_tensor_idx:
tensor_idx = nxt_tensor_idx.index(id(tensor))
return f'output_{tensor_idx}'
else:
assert False
def is_multi_dim_changed(self):
dim_change_i = self.merge_i()
dim_change_o = self.merge_o()
if len(dim_change_i) > 1 or len(dim_change_o) > 1:
return True
return False
def is_changes_conflict(self, tensor_changes):
if len(tensor_changes) == 0 and len(self.tensor_changes) > 0:
return True
for tensor_id, dim_choose in tensor_changes.items():
dim_changes_flat = list()
for dim_changes in self.tensor_changes[tensor_id]:
dim_changes_flat += dim_changes
if not set(dim_choose).issubset(set(dim_changes_flat)):
return True
return False
def merge_t(self, tensor):
"""Merge the dimension change information of all tensors"""
dim_change = set()
for change in self.tensor_changes[id(tensor)]:
dim_change.update(change)
return sorted(list(dim_change))
def merge_i(self) -> typing.List:
"""Merge the dimension change information of input tensors"""
dim_change = set()
for t in self.modifier.pre_tensors():
if id(t) not in self.tensor_changes.keys():
continue
for change in self.tensor_changes[id(t)]:
dim_change.update(change)
return sorted(list(dim_change))
def merge_o(self) -> typing.List:
"""Merge the dimension change information of output tensors"""
dim_change = set()
for t in self.modifier.next_tensors():
# The tensor used internally such as hidden state in RNN is not included in the dependency analysis
if id(t) in self.tensor_changes:
for change in self.tensor_changes[id(t)]:
dim_change.update(change)
return sorted(list(dim_change))
def update_i(
self,
center: 'Modifier',
tensor: torch.Tensor,
dim_changes: typing.List,
dim_transform=None,
update_constraint=True,
tensor_constraint=None,
):
"""Update the dimension change information of the input tensor"""
if dim_transform is not None:
self.dim_transform = dim_transform
constraint_i = None
if update_constraint:
if tensor_constraint is not None:
constraint_i = tensor_constraint
else:
constraint_i = calc_dim_constraint(tensor, dim_changes)
# Redirect pruning constraints to central node
if dim_transform:
for dim, constraint in constraint_i.items():
for i in range(len(constraint)):
new_constraint = set()
for c in constraint[i]:
if c in dim_transform.keys():
transformed_idx = dim_transform[c]
new_constraint.update(transformed_idx)
if len(new_constraint) > 0:
constraint[i] = new_constraint
for dim, constraint in constraint_i.items():
if dim not in self.constraints_i:
self.constraints_i[dim] = {}
self.constraints_i[dim][center.unique_name()] = self.constraints_i[dim].get(center.unique_name(), [])
self.constraints_i[dim][center.unique_name()].append(constraint)
self.update_(self.dim_changes_i, center, tensor, dim_changes)
return constraint_i
def update_o(
self,
center: 'Modifier',
tensor: torch.Tensor,
dim_changes: typing.List,
update_constraint=False,
default_constraint=None,
):
"""Update the dimension change information of the output tensor"""
constraint_o = None
if update_constraint:
if default_constraint is not None:
constraint_o = default_constraint
else:
constraint_o = calc_dim_constraint(tensor, dim_changes)
for dim, constraint in constraint_o.items():
if dim not in self.constraints_o:
self.constraints_o[dim] = {}
self.constraints_o[dim][center.unique_name()] = self.constraints_o[dim].get(center.unique_name(), [])
self.constraints_o[dim][center.unique_name()].append(constraint)
self.update_(self.dim_changes_o, center, tensor, dim_changes)
return constraint_o
def update_(self, dim_changes_dict: typing.Dict, center: 'Modifier', tensor, dim_changes: typing.List):
key = self.build_key(center, tensor)
if key not in dim_changes_dict.keys():
dim_changes_dict[key] = dim_changes
if id(tensor) not in self.tensor_changes:
self.tensor_changes[id(tensor)] = []
self.tensor_keys[id(tensor)] = []
self.tensor_changes[id(tensor)].append(dim_changes)
self.tensor_keys[id(tensor)].append(key)
self.tensor_keys[id(tensor)] = list(set(self.tensor_keys[id(tensor)]))
self.centers[center.unique_name()] = center
return self
def update_choice(self, tensor, choice):
key = self.build_choice_key(tensor)
self.dim_choices[key] = choice
self.tensor_choices[id(tensor)] = choice
def get_neighbor_changes(self, center, neighbor):
if isinstance(center, TraceNode) and isinstance(neighbor, TraceNode):
center = center.modifier
neighbor = neighbor.modifier
changes = []
if neighbor in self.modifier.pre_modifiers():
for t in self.modifier.pre_tensors(neighbor):
changes.append(self.dim_changes_i.get(self.build_key(center, t), None))
else:
for t in self.modifier.next_tensors(neighbor):
changes.append(self.dim_changes_o.get(self.build_key(center, t), None))
if changes == [None]:
return None
return changes
def get_neighbor_choices(self, neighbor):
if isinstance(neighbor, TraceNode):
neighbor = neighbor.modifier
choices = []
if neighbor in self.modifier.pre_modifiers():
for t in self.modifier.pre_tensors(neighbor):
choices.append(self.get_tensor_choices(t))
else:
for t in self.modifier.next_tensors(neighbor):
choices.append(self.get_tensor_choices(t))
if choices == [None]:
return None
return choices
def get_tensor_choices(self, tensor) -> typing.List:
return self.dim_choices.get(self.build_choice_key(tensor), None)
def get_tensor_changes(self, tensor) -> typing.List:
return self.tensor_changes[id(tensor)]
def get_input_centers(self):
center_names = []
for key, value in self.dim_changes_i.items():
center_names.append(key.split(":")[0])
return center_names
def rebuild(self):
"""Reconstruct the entire dimension change information according to dim_choice"""
valid_changes = []
for tensor_id, choice in self.tensor_choices.items():
for key in self.tensor_keys[tensor_id]:
if 'input' in key:
tensor_change = self.dim_changes_i[key]
else:
tensor_change = self.dim_changes_o[key]
if set(choice).issubset(set(tensor_change)):
center_name = key.split(":")[0]
center = self.centers[center_name]
all_tensors = self.modifier.pre_tensors() + self.modifier.next_tensors()
tensor = [t for t in all_tensors if id(t) == tensor_id][0]
valid_changes.append((center, tensor, tensor_change))
self.dim_changes_i = OrderedDict()
self.dim_changes_o = OrderedDict()
self.centers = OrderedDict()
self.tensor_changes = OrderedDict()
self.tensor_keys = OrderedDict()
constraint_i_new = OrderedDict()
constraint_o_new = OrderedDict()
for changes in valid_changes:
center, tensor, tensor_change = changes
if self.modifier.is_pre_tensor(tensor):
self.update_i(center, tensor, tensor_change, update_constraint=False)
constraint_old = self.constraints_i
constraint_new = constraint_i_new
else:
self.update_o(center, tensor, tensor_change, update_constraint=False)
constraint_old = self.constraints_o
constraint_new = constraint_o_new
choice = self.get_tensor_choices(tensor)
for dim, constraints in constraint_old.items():
if dim in choice:
if dim not in constraint_new:
constraint_new[dim] = {}
constraint_new[dim] = constraints
for dim, dim_constraints in constraint_i_new.items():
for center_name, constraints in dim_constraints.items():
if len(constraints) == 1:
continue
merge = [set() for i in constraints[0]]
for constraint in constraints:
for i in range(len(constraint)):
if constraint[i] != {-1}:
merge[i].update(constraint[i])
constraints[:] = [merge]
self.constraints_i = constraint_i_new
self.constraints_o = constraint_o_new
def __str__(self):
return (
f"dim_changes_i:{str(self.dim_changes_i)}, dim_changes_o:{str(self.dim_changes_o)},"
f" dim_choices:{str(self.dim_choices)}"
)
class Modifier(object):
graph_modifier: "GraphChannelModifier"
node: TraceNode
dim_changes_info: DimensionChangeInfo
forward_dim_mapping: typing.Dict[int, typing.Dict[int, typing.Dict[int, typing.Set]]]
backward_dim_mapping: typing.Dict[int, typing.Dict[int, typing.Dict[int, typing.Set]]]
prunable: bool
weight_mask: typing.Dict[str, torch.Tensor]
bias_mask: typing.Dict[str, torch.Tensor]
def __init__(self, node: TraceNode):
self.graph_modifier = None
self.node = node
# Tensor change dependencies between this operator and other operators
self.dim_changes_info = DimensionChangeInfo(self)
# When the dimension of the input/output tensor changes, the dimension of the affected output/input tensor
self.forward_dim_mapping = OrderedDict()
self.backward_dim_mapping = OrderedDict()
# Whether the operator allows pruning (for example, conv2d, linear, rnn, etc. are pruned,
# add, mul, etc. are not pruned)
self.prunable = False
self.weight_mask = OrderedDict()
self.bias_mask = OrderedDict()
self.mask_applied = False
self.tensor_id_to_str = {}
for i in range(len(self.pre_tensors())):
self.tensor_id_to_str[id(self.pre_tensors()[i])] = f"input_{i}"
for i in range(len(self.next_tensors())):
self.tensor_id_to_str[id(self.next_tensors()[i])] = f"output_{i}"
self.constant_node = False
if len(self.pre_tensors()) == 1:
self.constant_node = True
for t in self.next_tensors():
if isinstance(t, torch.Tensor) and len(t.shape) > 0:
self.constant_node = False
break
def __hash__(self):
return hash(self.unique_name())
def __eq__(self, other: 'Modifier'):
return self.unique_name() == other.unique_name()
def args_parsed(self):
return self.node.module.args_parsed
def masker(self) -> masker.ChannelMasker:
return getattr(self.node.module, "masker", None)
def enable_mask(self):
if self.masker() is not None:
self.masker().enable()
def disable_mask(self):
if self.masker() is not None:
self.masker().disable()
def reset_mask(self):
self.weight_mask.clear()
self.bias_mask.clear()
if hasattr(self.module(), "weight"):
self.weight_mask["weight"] = torch.ones_like(self.module().weight)
if hasattr(self.module(), "bias"):
self.bias_mask["bias"] = (
torch.ones_like(self.module().bias) if type(self.module().bias) is torch.nn.Parameter else None
)
def register_mask(self, modifiers, importance, sparsity):
if self.masker() is not None:
self.masker().set_in_remove_idx(self.dim_changes_info.pruned_idx_i)
self.masker().set_ot_remove_idx(self.dim_changes_info.pruned_idx_o)
def apply_mask(self, modifiers):
"""Use mask to modify the channel of the operator"""
if self.masker() is not None and self.masker().in_remove_idx is not None:
self.modify_input(self.masker().in_remove_idx)
if self.masker() is not None and self.masker().ot_remove_idx is not None:
self.modify_output(self.masker().ot_remove_idx)
self.mask_applied = True
def modify_input(self, remove_idx):
"""Modify the input tensor of the operator"""
pass
def modify_output(self, remove_idx):
"""Modify the output tensor of the operator"""
pass
def module(self):
return self.node.module
def unique_name(self):
return self.node.unique_name
def is_pre_tensor(self, tensor):
return id(tensor) in [id(x) for x in self.pre_tensors()]
def is_nxt_tensor(self, tensor):
return id(tensor) in [id(x) for x in self.next_tensors()]
def pre_tensors(self, parent: 'Modifier' = None, non_constant=False):
if parent is None:
if non_constant:
return [t for t in self.node.prev_tensors if len(t.shape) > 0]
return self.node.prev_tensors
tensors = []
for t in parent.next_tensors():
if self.is_pre_tensor(t):
if non_constant and len(t.shape) == 0:
continue
tensors.append(t)
return tensors
def next_tensors(self, child: 'Modifier' = None, non_constant=False):
if child is None:
if non_constant:
return [t for t in self.node.next_tensors if len(t.shape) > 0]
return self.node.next_tensors
tensors = []
for t in child.pre_tensors():
if self.is_nxt_tensor(t):
if non_constant and len(t.shape) == 0:
continue
tensors.append(t)
return tensors
def pre_modifiers(self, edge: torch.Tensor = None) -> typing.List['Modifier']:
if edge is None:
return [n.modifier for n in self.node.prev_nodes]
modifiers = []
for m in self.pre_modifiers():
for t in m.next_tensors():
if t is edge:
modifiers.append(m)
return modifiers
def next_modifiers(self, edge: torch.Tensor = None) -> typing.List['Modifier']:
if edge is None:
return [n.modifier for n in self.node.next_nodes]
modifiers = []
for m in self.next_modifiers():
for t in m.pre_tensors():
if t is edge:
modifiers.append(m)
return modifiers
def get_pruned_idx(self, modifiers):
"""Obtain the input tensor pruning information from the pruning information of other operators"""
pruned_idx = set()
input_modify_dim = self.dim_changes_info.get_tensor_choices(self.pre_tensors()[0])[0]
for center_name, _ in self.dim_changes_info.centers.items():
center = modifiers[center_name]
center_pruned_idx = set(center.dim_changes_info.pruned_idx_o)
constraints_i = self.dim_changes_info.constraints_i[input_modify_dim][center_name]
for constraint_i in constraints_i:
for leaf_idx in range(len(constraint_i)):
center_idx = constraint_i[leaf_idx]
if len(center_idx & center_pruned_idx) > 0:
pruned_idx.add(leaf_idx)
pruned_idx = list(pruned_idx)
pruned_idx.sort()
sparsity = len(pruned_idx) / self.pre_tensors()[0].shape[input_modify_dim]
return pruned_idx, sparsity
def calc_idx_group(self):
return None
def calc_dim_changes(self) -> typing.List[typing.Tuple[typing.List, torch.Tensor]]:
return calc_dim_changes(self.module(), self.pre_tensors(), self.next_tensors())
def change_dimension(self) -> bool:
return False
def dim_change_forward(self, center, tensor, dim_changes_i: typing.List, dim_transform, tensor_constraint):
# Leaf nodes require no additional computation
if len(self.next_tensors()) == 0:
if len(self.pre_tensors()) > 1:
for dim_change_i in dim_changes_i:
dims = [t.shape[dim_change_i] for t in self.pre_tensors()]
if len(set(dims)) > 1:
log.warning(f"Skip the {self.unique_name()} because the input shape is inconsistent")
return True
self.dim_changes_info.update_i(center, tensor, dim_changes_i, dim_transform)
return True
if self.node.kind() == "data":
return True
# Skip constant node
if self.constant_node:
return True
# The default implementation is regarded as Identity()
# Directly inheriting the dim_constraint of the previous layer, reducing the amount of calculation
tensor_constraint = self.dim_changes_info.update_i(
center, tensor, dim_changes_i, dim_transform, tensor_constraint=tensor_constraint
)
for tensor_o in self.next_tensors():
if id(tensor) == id(tensor_o):
continue
try:
tensor_o.copy_(tensor.clone())
except Exception as e:
log.error(
f"error modifier = {self.unique_name()}, type = {type(self.module())}, kind = {self.node.kind()}"
)
raise e
for tensor_o in self.next_tensors():
# Case [1, c0, c1] + [c0, c1](center_node) -> [1, c0, c1], to keep dim_change_o keep consistent.
if len(tensor_o.shape) > len(tensor.shape) and tensor_o.shape[0] == 1:
old_dim_change_i = dim_changes_i
omitted_dim_len = 1
dim_changes_i = [i + omitted_dim_len for i in dim_changes_i]
for dim_ in old_dim_change_i:
tensor_constraint[dim_ + omitted_dim_len] = tensor_constraint[dim_]
tensor_constraint.pop(dim_)
self.dim_changes_info.update_o(center, tensor_o, dim_changes_i)
for m in self.next_modifiers(tensor_o):
# The identity() operator does not change the constraint, so it can directly pass its own
# constraints to reduce the calculation of the next layer
m.dim_change_forward(center, tensor_o, dim_changes_i, dim_transform, tensor_constraint)
def calc_dim_mapping(self) -> bool:
"""Calculate the dimension change map between input and output tensor"""
pre_tensors = self.pre_tensors(non_constant=True)
# input 的维度数量必须相同,否则需要创建一个子类单独实现
input_dim_num = len(pre_tensors[0].shape)
for dim_change_i in range(input_dim_num):
for tensor_i in self.pre_tensors(non_constant=True):
fill_tensor_by_dim_changes(tensor_i, [dim_change_i])
for dim_changes in self.calc_dim_changes():
dim_changes_o, tensor_o = dim_changes
for dim_change_o in dim_changes_o:
id_o = id(tensor_o)
for tensor_i in self.pre_tensors(non_constant=True):
id_i = id(tensor_i)
self.forward_dim_mapping[id_i][dim_change_i][id_o].add(dim_change_o)
if len(tensor_o.shape) > 0:
self.backward_dim_mapping[id_o][dim_change_o][id_i].add(dim_change_i)
return True
def init_dim_mapping(self) -> bool:
# Init the dimension change map between input and output tensor
# TODO:use cache to speed up
if len(self.forward_dim_mapping) > 0:
return True
# this is a constant or I/O node
if len(self.pre_tensors()) == 0 or len(self.next_tensors()) == 0:
return False
pre_tensors = self.pre_tensors(non_constant=True)
nxt_tensors = self.next_tensors(non_constant=True)
for tensor_i in pre_tensors:
self.forward_dim_mapping[id(tensor_i)] = OrderedDict()
for i in range(len(tensor_i.shape)):
self.forward_dim_mapping[id(tensor_i)][i] = OrderedDict()
for tensor_o in nxt_tensors:
self.forward_dim_mapping[id(tensor_i)][i][id(tensor_o)] = set()
for tensor_o in nxt_tensors:
self.backward_dim_mapping[id(tensor_o)] = OrderedDict()
for i in range(len(tensor_o.shape)):
self.backward_dim_mapping[id(tensor_o)][i] = OrderedDict()
for tensor_i in pre_tensors:
self.backward_dim_mapping[id(tensor_o)][i][id(tensor_i)] = set()
if not self.calc_dim_mapping():
return False
return True
def print_dim_mapping(self):
mapping_str = []
mappings = OrderedDict({**self.forward_dim_mapping, **self.backward_dim_mapping})
for id_1, v1 in mappings.items():
name_1 = self.tensor_id_to_str[id_1]
for dim_1, v2 in v1.items():
for id_2, dim_2 in v2.items():
name_2 = self.tensor_id_to_str[id_2]
format_str = f"{name_1}:{dim_1}->{name_2}:{dim_2}"
mapping_str.append(format_str)
log.debug("\n".join(mapping_str))
return mapping_str
def dim_choose(self, tensor_changes: typing.Dict[int, typing.List]):
"""When multiple dimensions are variable, select one of the dimensions.
The selection method of each operator and pruning algorithm may be different"""
return True
def dim_choose_traversal(
self,
modifiers: typing.List,
tensor_choices: typing.Dict[int, typing.List],
tensor: torch.Tensor,
):
"""Propagate the selected dimension to all relevant operators"""
if self in modifiers:
return True
if self.constant_node:
return True
dim_choice = tensor_choices[id(tensor)]
changed = False
dim_changes = self.dim_changes_info.get_tensor_changes(tensor)
for dim_change in dim_changes:
if dim_choice != dim_change:
changed = True
break
# dim choose 和 dim_change 完全相同,说明此tensor完全未发生变化,无需传播
if not changed:
return True
# 根据dim choose重新计算input、output的dim change
tensor_choices_cur = self.calc_dim_choices(tensor, dim_choice)
if len(tensor_choices_cur) == 0 and len(dim_choice) > 0:
return True
# 根据dim choose计算出的dim change存在冲突(例如input_0只支持裁剪dim=0,而input_1只支持裁剪dim=1)
if self.dim_changes_info.is_changes_conflict(tensor_choices_cur):
log.warning(
f'[{self.unique_name()}][{self.tensor_id_to_str[id(tensor)]}][{dim_choice}] dim choose conflict'
)
return False
modifiers.append(self)
tensor_choices.update(tensor_choices_cur)
valid = True
for m in self.pre_modifiers():
if not valid:
break