Repository navigation
Expand file tree
/
Copy pathtest_channel_pruner.py
More file actions
1632 lines (1422 loc) · 71.2 KB
/
Copy pathtest_channel_pruner.py
File metadata and controls
1632 lines (1422 loc) · 71.2 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
from pruning import ranked_structures_pruner
from pruning import automated_gradual_pruner
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torchvision import datasets, transforms
import torchvision.models as models
import numpy as np
from numpy import linalg as LA
import datetime
from tensorboardX import SummaryWriter
import scipy.misc
from pruning import admm_pruner
import model_zoo as mz
from scheduler import ParameterMasker, create_model_masks_dict
import time
import thresholding
from collections import OrderedDict
from modules import eltwise
from functools import partial
import distiller
from sklearn.linear_model import Lasso, LassoLars, LinearRegression
import math
import logging
from main_nat import data_processing, _validate
'''
_prune_ratio = {
#"conv1.weight: # 0.75
"conv2.weight": 0.75,
"conv3.weight": 0.75,
"conv4.weight": 0.75,
"conv5.weight": 0.75,
"conv6.weight": 0.75,
"conv7.weight": 0.75,
"conv8.weight": 0.75,
"conv9.weight": 0.75,
"conv10.weight": 0.75,
"conv11.weight": 0.75,
"conv12.weight": 0.75,
"conv13.weight": 0.75,
"conv14.weight": 0.75,
"conv15.weight": 0.75,
"conv16.weight": 0.75,
"conv17.weight": 0.75,
"conv18.weight": 0.75,
"conv19.weight": 0.75,
"conv20.weight": 0.75,
"conv21.weight": 0.75,
"conv22.weight": 0.75,
"conv23.weight": 0.75,
"conv24.weight": 0.75,
"conv25.weight": 0.75,
"conv26.weight": 0.75,
"conv27.weight": 0.75,
"fc1.weight": 0.75,
}
'''
_prune_ratio = {
"fc1.weight": 0.75,
}
prune_ratios = {}
conv_names = []
bn_names = []
fc_names = []
name_encoder = {}
def prepare_pruning(model):
_extract_layer_names(model)
for good_name, ratio in _prune_ratio.items():
_encode(good_name)
for good_name,ratio in _prune_ratio.items():
prune_ratios[name_encoder[good_name]] = ratio
#for k in self.prune_ratios.keys():
# self.rhos[k] = rho # this version we assume all rhos are equal
print ('<========={} conv names'.format(len(conv_names)))
print (conv_names)
print ('<========={} bn names'.format(len(bn_names)))
print (bn_names)
print ('<========={} targeted pruned layers'.format(len(prune_ratios)))
print (prune_ratios.keys())
for k, v in prune_ratios.items():
print ('target sparsity in {} is {}'.format(k,v))
def _extract_layer_names(model):#, conv_names, bn_names, fc_names):
"""
Store layer name of different types in arrays for indexing
"""
for name, W in model.named_modules():
name += '.weight' # name in named_modules looks like module.features.0. We add .weight into it
print(name)
# This is only for the CNN compression usage.
if isinstance(W,nn.Conv2d):
conv_names.append(name)
if isinstance(W,nn.BatchNorm2d):
bn_names.append(name)
if isinstance(W,nn.Linear):
fc_names.append(name)
def _encode(name):
"""
Examples:
conv1.weight -> conv 1 weight
conv1-> prefix weight->postfix
conv->layer_type 1-> layer_id + 1 weight-> postfix
Use buffer for efficient look up
"""
prefix,postfix = name.split('.')
dot_position = prefix.find('.')
layer_id = ''
for s in prefix:
if s.isdigit():
layer_id+=s
id_length = len(layer_id)
layer_type = prefix[:-id_length]
layer_id = int(layer_id)-1
if layer_type =='conv' and len(conv_names)!=0:
name_encoder[name] = conv_names[layer_id]
elif layer_type =='fc' and len(fc_names)!=0:
name_encoder[name] = fc_names[layer_id]
elif layer_type =='bn' and len(bn_names)!=0:
name_encoder[name] = bn_names[layer_id]
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
def conv_bn(inp, oup, stride):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
nn.BatchNorm2d(oup),
nn.ReLU(inplace=True)
)
def conv_dw(inp, oup, stride):
return nn.Sequential(
nn.Conv2d(inp, inp, 3, stride, 1, groups=inp, bias=False),
nn.BatchNorm2d(inp),
nn.ReLU(inplace=True),
nn.Conv2d(inp, oup, 1, 1, 0, bias=False),
nn.BatchNorm2d(oup),
nn.ReLU(inplace=True),
)
self.model = nn.Sequential(
conv_bn( 3, 32, 2),
conv_dw( 32, 64, 1),
conv_dw( 64, 128, 2),
conv_dw(128, 128, 1),
conv_dw(128, 256, 2),
conv_dw(256, 256, 1),
conv_dw(256, 512, 2),
conv_dw(512, 512, 1),
conv_dw(512, 512, 1),
conv_dw(512, 512, 1),
conv_dw(512, 512, 1),
conv_dw(512, 512, 1),
conv_dw(512, 1024, 2),
conv_dw(1024, 1024, 1),
nn.AvgPool2d(7),
)
self.fc = nn.Linear(1024, 1000)
def forward(self, x):
x = self.model(x)
x = x.view(-1, 1024)
x = self.fc(x)
return x
def assign_layer_fq_names(container, name=None):
"""Assign human-readable names to the modules (layers).
Sometimes we need to access modules by their names, and we'd like to use
fully-qualified names for convenience.
"""
for name, module in container.named_modules():
module.distiller_name = name
"""
# fIND THE ARGS IN CLASSIFIER amc.
amc_cfg = distiller.utils.MutableNamedTuple({
'modules_dict': compression_cfg["network"], # dict of modules, indexed by arch name
'save_chkpts': args.amc_save_chkpts,
'protocol': args.amc_protocol,
'agent_algo': args.amc_agent_algo,
'num_ft_epochs': num_ft_epochs,
'action_range': action_range,
'reward_frequency': args.amc_reward_frequency,
'ft_frequency': args.amc_ft_frequency,
'pruning_pattern': args.amc_prune_pattern,
'pruning_method': args.amc_prune_method,
'group_size': args.amc_group_size,
'n_points_per_fm': args.amc_fm_reconstruction_n_pts,
'ddpg_cfg': ddpg_cfg,
'ranking_noise': args.amc_ranking_noise})
"""
# partial(acceptance_criterion, mod_names=modules_list) modules_dict defined in their yaml file, just copy whilst revsing to our favorite style.
# here comes the module_filter_fn, and it's also a partial function...
# here is the validation function, which comes from distiller.apptutils.classifier. Thus , we can further import our test function to test whether this class can be executable.
# validate_fn = partial(classifier.test, test_loader=val_loader, criterion=self.criterion,
# loggers=self.pylogger, args=self.args, activations_collectors=None)
#model = Net()
#collect_intermediate_featuremap_samples(model, validate_fn, acceptance_criterion, cache_featuremaps_fwd_hook)
#model = models.resnet18()
def build_dictionary(net, residual_layer=2):
# If bottlenect (resnet 50, mobilenet v2, inception v4), residual_layer = 3
# Different arch may use different dictionary function!
net_name = []
for name, module in net.named_modules():
if isinstance(module, (torch.nn.Conv2d, torch.nn.Linear, eltwise.EltwiseAdd)):
net_name.append(name)
name_to_ind = OrderedDict()
ind_to_name = OrderedDict()
meta_data = OrderedDict()
name_to_next_name = OrderedDict()
modules = list(net.modules())
prunable_layer_types = [torch.nn.modules.conv.Conv2d]
# if residual net, we can not prune the fc layer.
f_size = 32
last_layer = 'conv0'
layer_index = 0
name_transfer_dict = OrderedDict()
for ind, module in enumerate(modules):
if type(module) in prunable_layer_types:
stride = module.stride[0]
kernel_size = module.kernel_size[0]
if stride == 2:
f_size /= 2
if layer_index == 0 :
name = "input_conv"
layer_index +=1
else:
if kernel_size == 1: # also called shorcut
i = (layer_index-1) // residual_layer
j = 2
name = 'conv'+str(i)+'_downsample'
name_to_ind[name] = (i, j)
ind_to_name[(i, j)] = name
else:
i = (layer_index -1) // residual_layer
j = 1 - (layer_index % residual_layer)
name = 'conv%d_%d' %(i, j)
name_to_ind[name] = (i, j)
ind_to_name[(i, j)] = name
layer_index += 1
name_to_next_name[last_layer] = name
last_layer = name
meta_data[name] = { 'n': module.out_channels,
'c': module.in_channels,
'ksize': kernel_size,
'padding': module.padding,
'fsize': f_size,
'stride':stride
}
elif type(module) == eltwise.EltwiseAdd:
name = "add" + str(ind)
name_transfer_dict[net_name[layer_index]] = name
#print(module)
layer_index += 1
elif type(module) == torch.nn.Linear:
name = "linear" + str(ind)
name_transfer_dict[net_name[layer_index]] = name
#print(module)
layer_index += 1
#print(module)
#print(name_to_ind)
print(name_transfer_dict)
#for name, module in net.named_modules():
# print(name)
# print(module)
#print(meta_data)
#print(len(list(meta_data.keys())))
#assign_layer_fq_names(net)
return name_to_ind, ind_to_name, meta_data, name_to_next_name, name_transfer_dict
# Below code is to test wether the residual connection can be attained correctly from register foward hook.
# 首先我们定义一个模型
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.fc1 = nn.Linear(3, 4)
self.relu1 = nn.ReLU()
#self.identity = nn.Identity()
self.fc2 = nn.Linear(4, 1)
self.fc3 = nn.Linear(3, 1)
self.add = eltwise.EltwiseAdd()
#self.add =
self.initialize()
# 为了方便验证,我们将指定特殊的weight和bias
def initialize(self):
with torch.no_grad():
self.fc1.weight = torch.nn.Parameter(
torch.Tensor([[1., 2., 3.],
[-4., -5., -6.],
[7., 8., 9.],
[-10., -11., -12.]]))
#self.fc1.bias = torch.nn.Parameter(torch.Tensor([1.0, 2.0, 3.0, 4.0]))
self.fc1.bias = torch.nn.Parameter(torch.Tensor([0.0, 0.0, 0.0, 0.0]))
self.fc2.weight = torch.nn.Parameter(torch.Tensor([[1.0, 2.0, 3.0, 4.0]]))
self.fc2.bias = torch.nn.Parameter(torch.Tensor([0.0]))
self.fc3.weight = torch.nn.Parameter(torch.Tensor([[1.0, 2.0, 3.0]]))
self.fc3.bias = torch.nn.Parameter(torch.Tensor([[0.0]]))
def forward(self, x):
o = self.fc1(x)
o = self.relu1(o)
o = self.fc2(o)
q_mapping = self.fc3(x)
o = self.add(o, q_mapping) # If using add module, first one is input and last one is output.
#o += q_mapping
return o
# 全局变量,用于存储中间层的 feature
total_feat_out = []
total_feat_in = []
# 定义 forward hook function
def hook_fn_forward(module, input, output):
print(module) # 用于区分模块
print('input', input) # 首先打印出来
print('output', output)
total_feat_out.append(output) # 然后分别存入全局 list 中
total_feat_in.append(input)
model = Model()
modules = model.named_children() #
#print(modules)
modules = list(model.modules())
#print(modules)
#for name, module in modules:
#for module in modules:
# if isinstance(module, (torch.nn.Conv2d, torch.nn.Linear, eltwise.EltwiseAdd)):
# module.register_forward_hook(hook_fn_forward)
#modules[5].register_forward_hook(hook_fn_forward)
# 注意下面代码中 x 的维度,对于linear module,输入一定是大于等于二维的
# (第一维是 batch size)。在 forward hook 中看不出来,但是 backward hook 中,
# 得到的梯度完全不对。
# 有一篇 hook 的教程就是这里出了错,作者还强行解释
x = torch.Tensor([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [1.0, 1.0, 1.0]]).requires_grad_()
#o = model(x)
#o.backward()
print('==========Saved inputs and outputs==========')
for idx in range(len(total_feat_in)):
print('input: ', total_feat_in[idx])
print('output: ', total_feat_out[idx])
class PreActBlock(nn.Module):
def __init__(self, in_planes, out_planes, stride=1):
super(PreActBlock, self).__init__()
self.bn0 = nn.BatchNorm2d(in_planes)
self.conv0 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
#self.register_buffer('mask0', torch.ones(1, out_planes, 1, 1))
self.bn1 = nn.BatchNorm2d(out_planes)
self.conv1 = nn.Conv2d(out_planes, out_planes, kernel_size=3, stride=1, padding=1, bias=False)
#self.register_buffer('mask1', torch.ones(1, out_planes, 1, 1))
self.skip_conv = None
if stride != 1:
self.skip_conv = nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, padding=0, bias=False)
self.skip_bn = nn.BatchNorm2d(out_planes)
self.add = eltwise.EltwiseAdd()
def forward(self, x):
out = F.relu(self.bn0(x))
shortcut_out = None
if self.skip_conv is not None:
shortcut = self.skip_conv(out)
shortcut_out = shortcut
shortcut = self.skip_bn(shortcut)
else:
shortcut = x
conv0_input = out
out = self.conv0(out)
conv0_out = out
out = F.relu(self.bn1(out))
#out = out * self.mask0
conv1_input = out
out = self.conv1(out)
#out = out * self.mask1
out = self.add(shortcut, out)
#out += shortcut
conv1_out = out
return out#, (conv0_input, conv1_input), (conv0_out, conv1_out, shortcut_out), shortcut
class PreActResNet(nn.Module):
def __init__(self, block, num_units, num_classes):
super(PreActResNet, self).__init__()
self.conv0 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1, bias=False)
self.name_to_ind = OrderedDict()
self.ind_to_name = OrderedDict()
self.meta_data = OrderedDict()
self.name_to_next_name = OrderedDict()
self.layers = nn.ModuleList()
last_layer = 'conv0'
last_n = 16
fsize = 32
strides = [1] * num_units[0] + \
[2] + [1] * (num_units[1] - 1) + \
[2] + [1] * (num_units[2] - 1)
out_planes = [16] * num_units[0] + [32] * num_units[1] + [64] * num_units[2]
for i, (stride, n) in enumerate(zip(strides, out_planes)):
self.layers.append(block(last_n, n, stride))
if stride != 1:
fsize /= 2
for j in range(2):
name = 'conv%d_%d' % (i, j)
self.name_to_ind[name] = (i, j)
self.ind_to_name[(i, j)] = name
self.meta_data[name] = {'n': n,
'c': last_n,
'ksize': 3,
'padding': 1,
'fsize': fsize,
'stride': stride}
self.name_to_next_name[last_layer] = name
last_layer = name
last_n = n
stride = 1
self.bn = nn.BatchNorm2d(64)
self.fc = nn.Linear(64, num_classes)
# Initialize weights
#for m in self.modules():
# if isinstance(m, nn.Conv2d):
# init.kaiming_normal_(m.weight, nonlinearity='relu')
def forward(self, x):
out = self.conv0(x)
for layer in self.layers:
out = layer(out)
out = self.bn(out)
out = out.mean(2).mean(2)
out = self.fc(out)
return out
def resnet20():
return PreActResNet(PreActBlock, [3, 3, 3], num_classes=10)
def build_dictionary(net, arch, module_list):
# If bottlenect (resnet 50, mobilenet v2, inception v4), residual_layer = 3
# Different arch may use different dictionary function!
if arch.startswith('resnet'):
# Should consider resenet 152....
layer_num = int(arch[::-1][:2])
block_layer_num = 2 if layer_num < 50 else 3
block_layer_num += 1 # Module number, which excludes the skip_conv/shortcup layer.
#net_name = []
#for name, module in net.named_modules():
# if isinstance(module, (torch.nn.Conv2d, torch.nn.Linear, eltwise.EltwiseAdd)):
# net_name.append(name)
name_to_ind = OrderedDict()
ind_to_name = OrderedDict()
meta_data = OrderedDict()
name_to_next_name = OrderedDict()
modules = list(net.modules())
# if residual net, we can not prune the fc layer (output layer).
f_size = 224
last_layer = 'conv0'
layer_index = 0
conv_list_record = []
add_index = 0
linear_index = 0
skip_conv = 0
name_transfer_dict = OrderedDict()
for ind, module in enumerate(modules):
if type(module) == torch.nn.modules.conv.Conv2d:
stride = module.stride[0]
kernel_size = module.kernel_size[0]
if stride == 2:
f_size /= 2
if layer_index == 0 :
name = "input_conv"
layer_index +=1
else:
if kernel_size == 1: # also called shorcut
print(layer_index)
#i = (layer_index-1) // block_layer_num
j = 2 if layer_num < 50 else 3
name = 'conv'+str(i)+'_downsample'
name_to_ind[name] = (i, j)
ind_to_name[(i, j)] = name
name_transfer_dict[module_list[layer_index]] = name
layer_index += 1
skip_conv += 1
else:
i = (layer_index - 1 - skip_conv) // block_layer_num
# Formalize the
#j = (block_layer_num - 2) - (layer_index % block_layer_num)
j = (layer_index - 1 - skip_conv) % block_layer_num
name = 'conv%d_%d' %(i, j)
name_to_ind[name] = (i, j)
ind_to_name[(i, j)] = name
name_transfer_dict[module_list[layer_index]] = name
layer_index += 1
name_to_next_name[last_layer] = name
last_layer = name
meta_data[name] = { 'n': module.out_channels,
'c': module.in_channels,
'ksize': kernel_size,
'padding': module.padding,
'fsize': f_size,
'stride':stride
}
elif type(module) == eltwise.EltwiseAdd:
print(module)
#i = layer_index // (block_layer_num + 1)
#i = (layer_index - 1 - skip_conv) // block_layer_num
name = "conv"+str(i)+"_add"
name_transfer_dict[module_list[layer_index]] = name
#print(module)
layer_index += 1
elif type(module) == torch.nn.Linear:
name = "linear" + str(linear_index)
name_transfer_dict[module_list[layer_index]] = name
#print(module)
#layer_index += 1
#linear_index += 1
#print(module)
print(module_list)
print(ind_to_name)
print(name_transfer_dict)
return name_to_ind, ind_to_name, meta_data, name_to_next_name, name_transfer_dict
def build_module_list(model):
# Refer to the distiller AMC script
# We can load the module list using the config file!
module_list = []
# how to add add module to it?
for name, module in model.named_modules():
if isinstance(module, (torch.nn.Conv2d, torch.nn.Linear, eltwise.EltwiseAdd)):
module_list.append(name)
return module_list
model = resnet20()
#modules = list(model.modules())
#module_list = build_module_list(model)
#build_dictionary(model, 'resnet_20', module_list)
#for name, module in modules:
"""
for module in modules:
if isinstance(module, (torch.nn.Conv2d, torch.nn.Linear, eltwise.EltwiseAdd)):
print(module)
module.register_forward_hook(hook_fn_forward)
"""
def foward_fn(model, x):
print(x.shape)
model(x)
#print(foward_fn(model, torch.rand((1, 3, 32, 32))))
def _least_square_sklearn(X, Y):
model = LinearRegression(fit_intercept=False)
model.fit(X, Y)
return model.coef_
#foward_fn()
#for name, weight in model.named_parameters():
# print(name)
#for name, module in model.named_modules():
#module.distiller_name = name
# print(name)
#name_to_ind, ind_to_name, meta_data, \
# name_to_next_name, name_transfer_dict = build_dictionary(model, residual_layer=1)
# Build module_list function should be revised, in which are some reference in AMC script.
"""
modules_list = ['fc1', 'fc2', 'fc3', 'add'] # insert "Add" module is to attain the output that is summation of last layer of res block and its branch.
acceptance_criterion = partial(acceptance_criterion, mod_names=modules_list)
forward_arg = partial(foward_fn, model=model, x=x)
hook_fn = partial(cache_featuremaps_fwd_hook, n_points_per_fm=10)
collect_intermediate_featuremap_samples(model, forward_arg, acceptance_criterion, hook_fn)
recollect_featuremap_samples(modules[5], forward_arg, acceptance_criterion, hook_fn)
print(model.intermediate_fms)
"""
msglogger = logging.getLogger(__name__)
from torch.nn import functional as f
class Channel_pruner_FMR:#(_ParameterPruner):
# Bowei convert the config format into ADMM's patter, while bulding a new policy to enable it.
def __init__(self, name, pruning_ratio, use_lasso, n_points_per_fm, #desired_sparsity, weights, # or weights?
model, arch, group_dependency=None, kwargs=None,
magnitude_fn=distiller.norms.l1_norm, group_size=1, rounding_fn=math.floor, ranking_noise=0):
# Add forward_fn or dataloader to the channel pruner policy.
assert magnitude_fn is not None
#super().__init__(name, desired_sparsity, weights, group_dependency,
# group_size=group_size, rounding_fn=rounding_fn, noise=ranking_noise)
#super().__init__(name)
#self.arch = arch
# Below list will be revised by local user if their designed model is with residual connections.
#connection_exist_list = ['resnet', 'inception']
self.connection = False
if arch == 'mobilenet_v2' or arch.startswith(('resnet', 'inception', 'efficient')):
self.connection = True
self.model = model
self.use_lasso = use_lasso
#self.weights = weights
#data_processing(dataset, data_dir, batch_size, workers=workers=, split_ratio=0.1)
#self.desired_sparsity = desired_sparsity
self.pruning_ratios = pruning_ratio
self.magnitude_fn = magnitude_fn
# Indicate that the pruning is true applied in a certain layer in the DNN,
# thus we can start weights reconstruct to compensate the error among different layers.
self.is_pruned = False
self.assign_layer_fq_names(model)
self.modules, self.non_pruned_modules = self.build_module_list(model)
self.n_points_per_fm = n_points_per_fm
self.layer_indice = OrderedDict()
# TODO should think what this constraint is reasonable.
if self.connection:
# Build dictionary and inverse-key dict for residual block.
self.name_to_ind, self.ind_to_name, self.meta_data, \
name_to_next_name, self.name_transfer_dict = self.build_dictionary(model, self.arch, self.modules)
self.reverse_transfer_dict = OrderedDict()
for module_name, local_name in self.name_transfer_dict.items():
self.reverse_transfer_dict[local_name] = module_name
self.hook_fn = partial(self.cache_featuremaps_fwd_hook, n_points_per_fm=self.n_points_per_fm,
layer_indice=self.layer_indice, arch=self.arch,
name_transfer_dict=self.name_transfer_dict,
reverse_transfer_dict=self.reverse_transfer_dict)
else:
self.hook_fn = partial(self.cache_featuremaps_fwd_hook, n_points_per_fm=self.n_points_per_fm,
layer_indice=self.layer_indice, arch=arch)
self.acceptance_criterion = partial(self.acceptance_criterion, mod_names=self.modules)
# import validate, how to incorporate it into our function?
x = torch.rand((2, 3, 224, 224))
self.forward_fn = partial(foward_fn, model=model, x=x)
#forward_arg = partial(foward_fn, model=model, x=x)
# First collect all the groud truth feature maps from original model. (Time-consuming?)
#intermediate_fms = {"output_fms": dict(), "input_fms": dict()}
"""
hook_handles = []
m = list(model.modules())
m = self.find_module_by_fq_name(model, 'layers.0.conv1')
intermediate_fms['output_fms'][m.distiller_name] = []
intermediate_fms['input_fms'][m.distiller_name] = []
hook_handles.append(m.register_forward_hook(partial(self.cache_featuremaps_fwd_hook,
intermediate_fms=intermediate_fms,
n_points_per_fm=5)))
self.forward_fn()
"""
#print(self.name_to_ind)
#print(self.name_transfer_dict)
self.collect_intermediate_featuremap_samples(model, self.forward_fn,
self.acceptance_criterion, self.hook_fn)
#recollect_featuremap_samples(modules[5], forward_arg, acceptance_criterion, hook_fn)
def prune_group(self, fraction_to_prune, param, param_name, zeros_mask_dict, model=None, binary_map=None):
if fraction_to_prune == 0:
return
binary_map = self.rank_and_prune_channels(fraction_to_prune, param, param_name,
zeros_mask_dict, model, binary_map,
group_size=self.group_size,
rounding_fn=self.rounding_fn,
noise=self.noise)
return binary_map
@staticmethod
def assign_layer_fq_names(container, name=None):
"""
Assign human-readable names to the modules (layers).
Sometimes we need to access modules by their names, and we'd like to use
fully-qualified names for convenience.
"""
for name, module in container.named_modules():
#print(name)
module.distiller_name = name
def build_module_list(self, model):
# Refer to the distiller AMC script
# We can load the module list using the config file!
module_list = []
non_prune_module = []
# how to add add module to it?
for name, module in model.named_modules():
if isinstance(module, (torch.nn.Conv2d, torch.nn.Linear, eltwise.EltwiseAdd)):
module_list.append(name)
name_weight = name + ".weight"
if name_weight not in self.pruning_ratios:
non_prune_module.append(name)
return module_list, non_prune_module
# THis function includes in the pruner class, staticmethod.
#@staticmethod
def cache_featuremaps_fwd_hook(self, module, input, output, intermediate_fms, n_points_per_fm,
layer_indice, arch, name_transfer_dict=None, reverse_transfer_dict=None):
"""
Create a cached dictionary of each layer's input and output feature-maps.
For reconstruction of weights, we need to collect pairs of (layer_input, layer_output)
using a sample subset of the input dataset.
This is a forward-hook function, invoked from forward_hooks of Convolution layers.
Use this in conjunction with distiller.features_collector.collect_intermediate_featuremap_samples,
which orchestrates the process of feature-map collection.
This foward-hook samples random points in the output feature-maps of 'module'.
After collecting the feature-map samples, distiller.FMReconstructionChannelPruner can be used.
Arguments:
module - the module who's forward_hook is invoked
input, output - the input and output arguments to the forward_hook
intermediate_fms - a dictionary of lists of feature-map samples, per layer
(use module.distiller_name as key)
n_points_per_fm - number of points to sample, per feature-map.
"""
def im2col(x, conv):
x_unfold = f.unfold(x, kernel_size=conv.kernel_size, stride=conv.stride, padding=conv.padding)
return x_unfold
# Sample random (uniform) points in each feature-map.
# This method is biased toward small feature-maps.
#print(module.distiller_name)
if isinstance(module, (torch.nn.Conv2d, eltwise.EltwiseAdd)):
# Only resnet needs this if condition:
if module.distiller_name in layer_indice:
randx, randy = layer_indice[module.distiller_name]
else:
randx = np.random.randint(0, output.size(2), n_points_per_fm)
randy = np.random.randint(0, output.size(3), n_points_per_fm)
# Should give another options that can use whole features map as the input/output of regression problem, no need it, since Prof. Han also adopt this implementations.
X = input[0]
B = X.shape[0]
C = X.shape[1]
if isinstance(module, torch.nn.Linear):
X = X.detach().cpu().clone()
Y = output.detach().cpu().clone()
elif isinstance(module, eltwise.EltwiseAdd):
if self.connection:
layer_name_with_indice = name_transfer_dict[module.distiller_name]
conv_name = layer_name_with_indice.split("_")[0]
# TODO we should consider more deeper residual network. the str("1") is no longer useful as layer_num >50
randx, randy = layer_indice[reverse_transfer_dict[conv_name+"_1"]]
#X = X.detach().cpu().clone()
# Bowei revision, in which I follow the same computation as getting the feature maps Y.
X = X[:, :, randx, randy]
X = X.permute([0, 2, 1]).contiguous()
X = X.view(-1, X.shape[-1]).cpu().clone()
#Y = output.detach().cpu().clone()
Y = output[:, :, randx, randy].detach().cpu().clone()
elif module.kernel_size == (1, 1):
if self.connection:
layer_name_with_indice = name_transfer_dict[module.distiller_name]
conv_name = layer_name_with_indice.split("_")[0]
randx, randy = layer_indice[reverse_transfer_dict[conv_name+"_0"]]
# Bowie revise the code here:
w_out = output.size(2)
pts = randx * w_out + randy
X = X[:, :, randx, randy].detach().cpu().clone()
# Form pytorch AMC:
#X = im2col(X.detach().cpu().clone(), module)
#X = X[:, :, pts].detach().cpu().clone()
#X = X.view(B, C, 1, 1, -1)
#X = X.permute([0, 4, 1, 2, 3]).contiguous()
#X = X.view(-1, C, module.kernel_size[0], module.kernel_size[1])
Y = output[:, :, randx, randy].detach().cpu().clone()
layer_indice[module.distiller_name] = (randx, randy)
else:
w, h = X.size(2), X.size(3)
X = im2col(X.detach().cpu().clone(), module)#.squeeze()
w_out = output.size(2)
pts = randx * w_out + randy
X = X[:, :, pts].detach().cpu().clone()
Y = output[:, :, randx, randy].detach().cpu().clone()
# Bowei adds the follow code from pytorch-AMC, more specifially, it's conv_input/output function.
#X = X.view(B, C, module.kernel_size[0], module.kernel_size[1], -1)
#X = X.permute([0, 4, 1, 2, 3]).contiguous()
#X = X.view(-1, C, module.kernel_size[0], module.kernel_size[1])
# We can save the indices in this way, since the output and input dimension are not changed during training.
layer_indice[module.distiller_name] = (randx, randy)
# Preprocess the outputs: transpose the batch and channel dimensions, create a flattened view, and transpose.
# The outputs originally have shape: (batch size, num channels, feature-map width, feature-map height).
Y = Y.view(Y.size(0), Y.size(1), -1)
Y = Y.transpose(2, 1)
Y = Y.contiguous().view(-1, Y.size(2))
#print(Y.shape)
#print(X.shape)
intermediate_fms['output_fms'][module.distiller_name].append(Y)
intermediate_fms['input_fms'][module.distiller_name].append(X)
# This will be used in recoolect function, since the smaple indice should keep the same.
#layer_name_with_indice = self.name_transfer_dict[module.distiller_name]
#self.layer_indice[module.distiller_name] = (randx, randy)
"""
DEBUG FUNCTION :
X = X.view(X.size(0), -1, np.prod(module.kernel_size), X.size(2))
print(X.shape)
#X = X[:, binary_map, :, :]
X = X.view(X.size(0), -1, X.size(3))
X = X.transpose(1, 2)
X = X.contiguous().view(-1, X.size(2))
print(X.shape)
new_w = _least_square_sklearn(X, Y)
new_w = torch.from_numpy(new_w)
print(new_w.shape)
retained_channel = module.in_channels
new_w = new_w.contiguous().view(-1, retained_channel, module.kernel_size[0], module.kernel_size[1])
print(new_w.shape)
print(module)
"""
def basic_featuremaps_caching_fwd_hook(module, input, output, intermediate_fms):
"""
A trivial function to cache input/output feature-maps
The input feature-maps are appended to a list of input-maps that are input to
this module. This list is provided by an external context. A similar setup
exists for output feature-maps.
This function is invoked from the forward-hook of modules and can be called from
various threads and the modules can exist on multiple GPUs. Therefore, we use Python
lists (on the CPU) to protect against race-conditions and synchronize the data.
Using the CPU to store the lists also benefits from the larger CPU DRAM.
"""
intermediate_fms['output_fms'][module.distiller_name].append(output)
intermediate_fms['input_fms'][module.distiller_name].append(input[0])
@staticmethod
def recollect_featuremap_samples(moodel, forward_fn, modules_filter_fn, fm_caching_fwd_hook=basic_featuremaps_caching_fwd_hook):
# This function is designed for recollection the "input" features after last layer is already pruned.
from functools import partial
intermediate_fms = {"output_fms": dict(), "input_fms": dict()}
hook_handles = []
def install_io_collectors(m, intermediate_fms):
if modules_filter_fn(m):
intermediate_fms['output_fms'][m.distiller_name] = []
intermediate_fms['input_fms'][m.distiller_name] = []
hook_handles.append(m.register_forward_hook(partial(fm_caching_fwd_hook,
intermediate_fms=intermediate_fms)))
"""
if modules_filter_fn(module):
intermediate_fms['output_fms'][module.distiller_name] = []
intermediate_fms['input_fms'][module.distiller_name] = []
hook_handles.append(module.register_forward_hook(partial(fm_caching_fwd_hook,
intermediate_fms=intermediate_fms)))
"""
# Register to the forward hooks, then run the forward-pass and collect the data
msglogger.warning("==> Collecting single input feature-map pairs")
model.apply(partial(install_io_collectors, intermediate_fms=intermediate_fms))
forward_fn()
# Unregister from the forward hooks
for handle in hook_handles:
handle.remove()
# We now need to concatenate the list of feature-maps to torch tensors.
msglogger.info("Concatenating Input FMs...")
#outputs = model.intermediate_fms['output_fms']
inputs = model.intermediate_fms['input_fms']
for (layer_name, X), Y in zip(intermediate_fms['input_fms'].items(), intermediate_fms['output_fms'].values()):
inputs[layer_name] = torch.cat(X, dim=0)
#outputs[layer_name] = torch.cat(Y, dim=0)
msglogger.warning("<== Single collector is Done.")
del intermediate_fms
@staticmethod
def _param_name_2_layer_name(param_name):
"""
Convert a weights tensor's name to the name of the layer using the tensor.
By convention, PyTorch modules name their weights parameters as self.weight
(see for example: torch.nn.modules.conv) which means that their fully-qualified
name when enumerating a model's parameters is the modules name followed by '.weight'.
We exploit this convention to convert a weights tensor name to the fully-qualified
module name.
"""
return param_name[:-len('.weight')]
# Example of module_filter_fn used in the Distiller's AMC
@staticmethod
def acceptance_criterion(m, mod_names):
# Collect feature-maps only for Conv2d layers and fc layers, if they are in our modules list.
return isinstance(m, (torch.nn.Conv2d, torch.nn.Linear, eltwise.EltwiseAdd)) and m.distiller_name in mod_names
@staticmethod
def find_module_by_fq_name(model, fq_mod_name):
"""
Given a module's fully-qualified name, find the module in the provided model.
A fully-qualified name is assigned to modules in function assign_layer_fq_names.
Arguments:
model: the model to search
fq_mod_name: the module whose name we want to look up
Returns:
The module or None, if the module was not found.
"""
for module in model.modules():
if hasattr(module, 'distiller_name') and fq_mod_name == module.distiller_name:
return module
return None
@staticmethod
def collect_intermediate_featuremap_samples(model, forward_fn, module_filter_fn,
fm_caching_fwd_hook=basic_featuremaps_caching_fwd_hook): #cache_featuremaps_fwd_hook
'''
Collect pairs of input/output feature-maps (all intermediate layers)!
**
Some Note here:
foward_fn: feed validation set and get the feature maps from hook, and services argument is just a nametuple which includes three callable function.
module_filter_fn: check layer's property
fm_caching_fwd_hood: your register function.
**
'''
from functools import partial
def install_io_collectors(m, intermediate_fms):
if module_filter_fn(m):
intermediate_fms['output_fms'][m.distiller_name] = []
intermediate_fms['input_fms'][m.distiller_name] = []
hook_handles.append(m.register_forward_hook(partial(fm_caching_fwd_hook,
intermediate_fms=intermediate_fms)))
# Register to the forward hooks, then run the forward-pass and collect the data
msglogger.warning("==> Collecting input/ouptput feature-map pairs")
# *****
# why ?
# *****
#self.assign_layer_fq_names(model)
hook_handles = []
intermediate_fms = {"output_fms": dict(), "input_fms": dict()}
# Get all the feature maps at the same time.
model.apply(partial(install_io_collectors, intermediate_fms=intermediate_fms))
forward_fn() # In distiller's example, use partial to wrap this foward function
# Unregister from the forward hooks
for handle in hook_handles:
handle.remove()