-
Notifications
You must be signed in to change notification settings - Fork 7
/
copy_densenet_onlycopy.py
397 lines (268 loc) · 12 KB
/
copy_densenet_onlycopy.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
from __future__ import print_function, division
import torch
import torchvision
from torchvision import datasets, models, transforms
from torch.utils.data import DataLoader
from torchvision import transforms, utils
from getimagenetclasses import *
from dataset_imagenet2500 import dataset_imagenetvalpart_nolabels
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
import copy
try:
from torch.hub import load_state_dict_from_url
except ImportError:
from torch.utils.model_zoo import load_url as load_state_dict_from_url
from torchvision.models import DenseNet
#############
from lrp_general6 import *
class Modulenotfounderror(Exception):
pass
class densenet_x(models.DenseNet):
def __init__(self, growth_rate=32, block_config=(6, 12, 24, 16),
num_init_features=64, bn_size=4, drop_rate=0, num_classes=1000, memory_efficient=False):
super(densenet_x, self).__init__(growth_rate, block_config,num_init_features, bn_size, drop_rate, num_classes, memory_efficient)
self.toprelu=nn.ReLU()
self.toppool= nn.AdaptiveAvgPool2d([1,1]) #nn.AvgPool2d((7,7))
def forward(self, x):
features = self.features(x)
#print('mn',torch.mean(features))
out = self.toprelu(features)
#print('mn',features.shape)
out = self.toppool(out)
print('mn2',out.shape)
out = torch.flatten(out, 1)
#exit()
out = self.classifier(out)
return out
def setbyname(self,name,value):
##
def iteratset(obj,components,value):
#print('components',components)
if not hasattr(obj,components[0]):
return False
elif len(components)==1:
setattr(obj,components[0],value)
#print('found!!', components[0])
#exit()
return True
else:
nextobj=getattr(obj,components[0])
return iteratset(nextobj,components[1:],value)
##
components=name.split('.')
success=iteratset(self,components,value)
return success
##############
def copyfromdensenet(self,net):
assert(isinstance(net, models.DenseNet) )
name_prev2= None
mod_prev2= None
name_prev1= None
mod_prev1= None
updated_layers_names=[]
for name,mod in net.named_modules():
print('curchain:', name_prev2, name_prev1, name)
# treat the first conv in the NN and its subsequent BN layer
if name=='features.norm0': # fuse first conv with subsequent BatchNorm layer
print('trying to update ', 'features.norm0' , 'features.conv0')
if name_prev1 != 'features.conv0':
raise Modulenotfounderror( 'name_prev1 expected to be features.conv0, but found:'+name_prev1)
#
conv = copy.deepcopy(mod_prev1)
conv = bnafterconv_overwrite_intoconv(conv,bn = mod)
success = self.setbyname(name= 'features.conv0' ,value = conv)
if False==success:
raise Modulenotfounderror( ' could not find ','features.conv0' )
bn = resetbn( copy.deepcopy(mod) )
success = self.setbyname(name= 'features.norm0' ,value = bn)
if False==success:
raise Modulenotfounderror( ' could not find ','features.norm0' )
updated_layers_names.append('features.conv0')
updated_layers_names.append('features.norm0')
elif name == 'classifier': # fuse densenet head, which has a structure
#BN(norm5)-relu(toprelu)-adaptiveAvgPool(toppool)-linear
print('trying to update ', 'classifier' , 'features.norm5','toprelu')
if name_prev1 != 'features.norm5':
#if that fails, run an inner loop to get 'features.norm5'
raise Modulenotfounderror( 'name_prev1 expected to be features.norm5, but found:'+name_prev1)
# approach:
# BN(norm5)-relu(toprelu)-adaptiveAvgPool(toppool)-linear('classifier')
# = threshrelu - BN - adaptiveAvgPool(toppool)-linear
# = threshrelu - adaptiveAvgPool(toppool) - BN -linear # yes this should commute bcs of no zero padding!
# = threshrelu - adaptiveAvgPool(toppool) - fusedlinear with tensorbias
# = resetbn(BN) - threshrelu/clamplayer(toprelu) - adaptiveAvgPool(toppool) - fusedlinear with tensorbias
#resetbn(BN)
success = self.setbyname(name= 'features.norm5' ,value = resetbn(mod_prev1) )
if False==success:
raise Modulenotfounderror( ' could not find ','features.norm5' )
#get the right threshrelu/clamplayer
threshrelu= getclamplayer(mod_prev1)
success = self.setbyname(name= 'toprelu' ,value = threshrelu )
if False==success:
raise Modulenotfounderror( ' could not find ','toprelu')
#get the right linearlayer with tensor boas
linearlayer_with_biastensor = linearafterbn_returntensorbiasedlinearlayer(linearlayer=mod,bn= mod_prev1)
success = self.setbyname(name= 'classifier' , value = linearlayer_with_biastensor)
if False==success:
raise Modulenotfounderror( ' could not find ','features.classifier' )
#no need to touch the pooling
updated_layers_names.append('classifier')
updated_layers_names.append('features.norm5')
updated_layers_names.append('toprelu')
elif 'conv' in name: # fuse general BN-relu-conv triples in densenet
if name == 'features.conv0':
name_prev2= name_prev1
mod_prev2= mod_prev1
name_prev1 = name
mod_prev1 = mod
continue
# approach:
# BN-relu-conv
# = threshrelu/clamplayer-BN-conv
# = threshrelu/clamplayer-(fused conv with tensorbias) # the bias is tensorshaped
# with difference in spatial dimensions, whenever zero padding is used!!
# = resetbn(BN)- threshrelu/clamplayer- (fused conv with tensorbias)
print('trying to update BN-relu-conv chain: ', name_prev2,name_prev1,name)
# bn-relu-conv chain
if not isinstance(mod_prev2,nn.BatchNorm2d):
print( 'error: no bn at the start, ', name_prev2,name_prev1,name)
exit()
if not isinstance(mod_prev1,nn.ReLU):
print( 'error: no relu in the middle, ', name_prev2,name_prev1,name)
exit()
#get the right threshrelu/clamplayer
clampl2= getclamplayer(bn = mod_prev2 )
success = self.setbyname(name= name_prev2 ,value = clampl2)
if False==success:
raise Modulenotfounderror( ' could not find ',name_prev2 )
#get the right convolution, likely with tensorbias
convm2 = convafterbn_returntensorbiasedconv(conv = mod, bn = mod_prev2 )
success = self.setbyname(name= name ,value = convm2)
if False==success:
raise Modulenotfounderror( ' could not find ',name )
#reset batchnorm
success = self.setbyname(name= name_prev1 ,value = resetbn(copy.deepcopy(mod_prev2)))
if False==success:
raise Modulenotfounderror( ' could not find ',name_prev1 )
updated_layers_names.append(name)
updated_layers_names.append(name_prev1)
updated_layers_names.append(name_prev2)
# read
name_prev2= name_prev1
mod_prev2= mod_prev1
name_prev1 = name
mod_prev1 = mod
print('not updated ones:')
for target_module_name, target_module in self.named_modules():
if target_module_name not in updated_layers_names:
print('not updated:', target_module_name)
#############3
model_urls = {
'densenet121': 'https://download.pytorch.org/models/densenet121-a639ec97.pth',
'densenet169': 'https://download.pytorch.org/models/densenet169-b2777c0a.pth',
'densenet201': 'https://download.pytorch.org/models/densenet201-c1103571.pth',
'densenet161': 'https://download.pytorch.org/models/densenet161-8d451a50.pth',
}
import re
def _load_state_dict(model, model_url, progress):
# '.'s are no longer allowed in module names, but previous _DenseLayer
# has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'.
# They are also in the checkpoints in model_urls. This pattern is used
# to find such keys.
pattern = re.compile(
r'^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$')
state_dict = load_state_dict_from_url(model_url, progress=progress)
for key in list(state_dict.keys()):
res = pattern.match(key)
if res:
new_key = res.group(1) + res.group(2)
state_dict[new_key] = state_dict[key]
del state_dict[key]
model.load_state_dict(state_dict)
def _densenet_x(arch, growth_rate, block_config, num_init_features, pretrained, progress,
**kwargs):
model = densenet_x(growth_rate, block_config, num_init_features, **kwargs)
if pretrained:
_load_state_dict(model, model_urls[arch], progress)
return model
def densenet121_x(pretrained=False, progress=True, **kwargs):
r"""Densenet-121 model from
`"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient,
but slower. Default: *False*. See `"paper" <https://arxiv.org/pdf/1707.06990.pdf>`_
"""
return _densenet_x('densenet121', 32, (6, 12, 24, 16), 64, pretrained, progress,
**kwargs)
def test_model3(dataloader, dataset_size, model, device, printmodeldetails=False):
from torchvision.models.resnet import ResNet, Bottleneck, BasicBlock
if printmodeldetails:
print(model)
print('\n\n\n\n\n\n')
'''
for module_name, module in model.named_modules():
print('module_name', module_name )#,module )
foundsth=False
if isinstance(module, nn.Conv2d):
foundsth=True
print('is Conv2d')
if isinstance(module, nn.BatchNorm2d):
foundsth=True
print('is BatchNorm2d')
if False== foundsth:
print('!unidentified layer')
print('\n')
'''
model.train(False)
for data in dataloader:
# get the inputs
#inputs, labels, filenames = data
inputs=data['image']
labels=data['label']
fns=data['filename']
inputs = inputs.to(device)
labels = labels.to(device)
with torch.no_grad():
outputs = model(inputs)
print('shp ', outputs.shape)
m=torch.mean(outputs)
m0=torch.mean(inputs)
print(m.item(), m0.item() )
print(fns)
return m.item(), outputs
def runstuff(skip):
use_gpu=True
#transforms
data_transform = transforms.Compose([
transforms.Resize(224),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225]) # if you do five crop, then you must change this part here, as it cannot be applied to 4 tensors
])
root_dir='./img'
dset= dataset_imagenetvalpart_nolabels(root_dir, maxnum=1, transform=data_transform, skip= skip)
dataset_size=len(dset)
dataloader = torch.utils.data.DataLoader(dset, batch_size=1, shuffle=False) #, num_workers=1)
#model
#modeltrained = models.densenet121(pretrained=True)
modeltrained = densenet121_x(pretrained=True)
device=torch.device('cpu')
modeltrained = modeltrained.to(device)
model = densenet121_x(pretrained=False)
model.copyfromdensenet(modeltrained)
#for _,mod in modeltrained.named_modules():
# mod.register_forward_hook(hook_fn)
#for _,mod in model.named_modules():
# mod.register_forward_hook(hook_fn)
m1, outputs1=test_model3(dataloader, dataset_size, model, device=device, printmodeldetails=False)
m2, outputs2=test_model3(dataloader, dataset_size, modeltrained, device=device, printmodeldetails=False)
print('\n\n m1,m2',m1,m2 )
print('diff of means: ', m1-m2)
print('MAE diff of logits: ', torch.mean(torch.abs(outputs1-outputs2)).item() )
if __name__=='__main__':
runstuff(skip=50) # 16,20,24,21