-
Notifications
You must be signed in to change notification settings - Fork 6
/
calculate_feature_maps.py
203 lines (168 loc) · 5.54 KB
/
calculate_feature_maps.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
import os
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
from data import cifar10, imagenet
import time
from models.resnet_cifar10 import resnet_56,resnet_110
from models.resnet_imagenet import resnet_50
parser = argparse.ArgumentParser(description='Calculate Feature Maps')
parser.add_argument(
'--arch',
type=str,
default='resnet_56',
choices=('vgg_16_bn','resnet_56','resnet_110','resnet_50'),
help='architecture to calculate feature maps')
parser.add_argument(
'--dataset',
type=str,
default='cifar10',
choices=('cifar10','imagenet'),
help='cifar10 or imagenet')
parser.add_argument(
'--data_dir',
type=str,
default='./data',
help='dataset path')
parser.add_argument(
'--pretrain_dir',
type=str,
default=None,
help='dir for the pretriained model to calculate feature maps')
parser.add_argument(
'--batch_size',
type=int,
default=128,
help='batch size for one batch.')
parser.add_argument(
'--repeat',
type=int,
default=5,
help='the number of different batches for calculating feature maps.')
parser.add_argument(
'--gpu',
type=str,
default='0',
help='gpu id')
args = parser.parse_args()
# gpu setting
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
cudnn.benchmark = True
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# prepare data
if args.dataset=='cifar10':
train_loader, _ = cifar10.load_cifar_data(args)
elif args.dataset=='imagenet':
data_tmp = imagenet.Data(args)
train_loader = data_tmp.train_loader
# Model
model = eval(args.arch)(sparsity=[0.]*100).to(device)
# Load pretrained model.
print('Loading Pretrained Model...')
if args.arch=='vgg_16_bn' or args.arch=='resnet_56':
checkpoint = torch.load(args.pretrain_dir, map_location='cuda:'+args.gpu)
else:
checkpoint = torch.load(args.pretrain_dir)
if args.arch=='resnet_50':
model.load_state_dict(checkpoint)
else:
model.load_state_dict(checkpoint['state_dict'])
conv_index = torch.tensor(1)
def get_feature_hook(self, input, output):
global conv_index
if not os.path.isdir('conv_feature_map/' + args.arch + '_repeat%d' % (args.repeat)):
os.makedirs('conv_feature_map/' + args.arch + '_repeat%d' % (args.repeat))
np.save('conv_feature_map/' + args.arch + '_repeat%d' % (args.repeat) + '/conv_feature_map_'+ str(conv_index) + '.npy',
output.cpu().numpy())
conv_index += 1
def inference():
model.eval()
repeat = args.repeat
with torch.no_grad():
for batch_idx, (inputs, targets) in enumerate(train_loader):
#use 5 batches to get feature maps.
if batch_idx >= repeat:
break
inputs, targets = inputs.to(device), targets.to(device)
model(inputs)
if args.arch=='vgg_16_bn':
if len(args.gpu) > 1:
relucfg = model.module.relucfg
else:
relucfg = model.relucfg
start = time.time()
for i, cov_id in enumerate(relucfg):
cov_layer = model.features[cov_id]
handler = cov_layer.register_forward_hook(get_feature_hook)
inference()
handler.remove()
elif args.arch=='resnet_56':
cov_layer = eval('model.relu')
handler = cov_layer.register_forward_hook(get_feature_hook)
inference()
handler.remove()
# ResNet56 per block
cnt=1
for i in range(3):
block = eval('model.layer%d' % (i + 1))
for j in range(9):
cov_layer = block[j].relu1
handler = cov_layer.register_forward_hook(get_feature_hook)
inference()
handler.remove()
cnt+=1
cov_layer = block[j].relu2
handler = cov_layer.register_forward_hook(get_feature_hook)
inference()
handler.remove()
cnt += 1
elif args.arch=='resnet_110':
cov_layer = eval('model.relu')
handler = cov_layer.register_forward_hook(get_feature_hook)
inference()
handler.remove()
cnt = 1
# ResNet110 per block
for i in range(3):
block = eval('model.layer%d' % (i + 1))
for j in range(18):
cov_layer = block[j].relu1
handler = cov_layer.register_forward_hook(get_feature_hook)
inference()
handler.remove()
cnt += 1
feature_result = torch.tensor(0.)
total = torch.tensor(0.)
cov_layer = block[j].relu2
handler = cov_layer.register_forward_hook(get_feature_hook)
inference()
handler.remove()
cnt += 1
elif args.arch=='resnet_50':
cov_layer = eval('model.maxpool')
handler = cov_layer.register_forward_hook(get_feature_hook)
inference()
handler.remove()
# ResNet50 per bottleneck
for i in range(4):
block = eval('model.layer%d' % (i + 1))
for j in range(model.num_blocks[i]):
cov_layer = block[j].relu1
handler = cov_layer.register_forward_hook(get_feature_hook)
inference()
handler.remove()
cov_layer = block[j].relu2
handler = cov_layer.register_forward_hook(get_feature_hook)
inference()
handler.remove()
cov_layer = block[j].relu3
handler = cov_layer.register_forward_hook(get_feature_hook)
inference()
handler.remove()
if j==0:
cov_layer = block[j].relu3
handler = cov_layer.register_forward_hook(get_feature_hook)
inference()
handler.remove()