Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

model_resnet.py 13 KB

You have to be logged in to leave a comment. Sign In
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
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. import math
  5. from torch.nn import init
  6. # track_running_stats=False
  7. class Linear_fw(nn.Linear): #used in MAML to forward input with fast weight
  8. def __init__(self, in_features, out_features):
  9. super(Linear_fw, self).__init__(in_features, out_features)
  10. self.weight.fast = None #Lazy hack to add fast weight link
  11. self.bias.fast = None
  12. def forward(self, x):
  13. if self.weight.fast is not None and self.bias.fast is not None:
  14. out = F.linear(x, self.weight.fast, self.bias.fast)
  15. else:
  16. out = super(Linear_fw, self).forward(x)
  17. return out
  18. class Conv2d_fw(nn.Conv2d): #used in MAML to forward input with fast weight
  19. def __init__(self, in_channels, out_channels, kernel_size, stride=1,padding=0, bias = True):
  20. super(Conv2d_fw, self).__init__(in_channels, out_channels, kernel_size, stride=stride, padding=padding, bias=bias)
  21. self.weight.fast = None
  22. if not self.bias is None:
  23. self.bias.fast = None
  24. def forward(self, x):
  25. if self.bias is None:
  26. if self.weight.fast is not None:
  27. out = F.conv2d(x, self.weight.fast, None, stride= self.stride, padding=self.padding)
  28. else:
  29. out = super(Conv2d_fw, self).forward(x)
  30. else:
  31. if self.weight.fast is not None and self.bias.fast is not None:
  32. out = F.conv2d(x, self.weight.fast, self.bias.fast, stride= self.stride, padding=self.padding)
  33. else:
  34. out = super(Conv2d_fw, self).forward(x)
  35. return out
  36. class BatchNorm2d_fw(nn.BatchNorm2d): #used in MAML to forward input with fast weight
  37. def __init__(self, num_features):
  38. super(BatchNorm2d_fw, self).__init__(num_features)
  39. self.weight.fast = None
  40. self.bias.fast = None
  41. def forward(self, x):
  42. running_mean = torch.zeros(x.data.size()[1]).cuda()
  43. running_var = torch.ones(x.data.size()[1]).cuda()
  44. if self.weight.fast is not None and self.bias.fast is not None:
  45. out = F.batch_norm(x, running_mean, running_var, self.weight.fast, self.bias.fast, training = True, momentum = 1)
  46. #batch_norm momentum hack: follow hack of Kate Rakelly in pytorch-maml/src/layers.py
  47. else:
  48. out = F.batch_norm(x, running_mean, running_var, self.weight, self.bias, training = True, momentum = 1)
  49. return out
  50. def conv3x3(in_planes, out_planes, stride=1):
  51. "3x3 convolution with padding"
  52. return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
  53. padding=1, bias=False)
  54. def conv3x3_fw(in_planes, out_planes, stride=1):
  55. "3x3 convolution with padding"
  56. return Conv2d_fw(in_planes, out_planes, kernel_size=3, stride=stride,
  57. padding=1, bias=False)
  58. class BasicBlock(nn.Module):
  59. maml = False #Default
  60. expansion = 1
  61. def __init__(self, inplanes, planes, stride=1, downsample=None, downsample_jigsaw=None, track_running_stats=True, use_bn=True):
  62. super(BasicBlock, self).__init__()
  63. # print('use bn in block:',use_bn)
  64. self.use_bn = use_bn
  65. if self.maml:
  66. self.conv1 = conv3x3_fw(inplanes, planes, stride)
  67. else:
  68. self.conv1 = conv3x3(inplanes, planes, stride)
  69. if self.use_bn:
  70. if self.maml:
  71. self.bn1 = BatchNorm2d_fw(planes)
  72. else:
  73. self.bn1 = nn.BatchNorm2d(planes, track_running_stats=track_running_stats)
  74. self.relu = nn.ReLU(inplace=True)
  75. if self.maml:
  76. self.conv2 = conv3x3_fw(planes, planes)
  77. else:
  78. self.conv2 = conv3x3(planes, planes)
  79. if self.use_bn:
  80. if self.maml:
  81. self.bn2 = BatchNorm2d_fw(planes)
  82. else:
  83. self.bn2 = nn.BatchNorm2d(planes, track_running_stats=track_running_stats)
  84. self.downsample = downsample
  85. self.downsample_jigsaw = downsample_jigsaw
  86. self.stride = stride
  87. def forward(self, x, jigsaw=False):
  88. residual = x
  89. out = self.conv1(x)
  90. if self.use_bn:
  91. out = self.bn1(out)
  92. out = self.relu(out)
  93. out = self.conv2(out)
  94. if self.use_bn:
  95. out = self.bn2(out)
  96. if self.downsample is not None:
  97. residual = self.downsample(x)
  98. out += residual
  99. out = self.relu(out)
  100. return out
  101. class Bottleneck(nn.Module):
  102. maml = False #Default
  103. expansion = 4
  104. def __init__(self, inplanes, planes, stride=1, downsample=None, track_running_stats=True, use_bn=True):
  105. super(Bottleneck, self).__init__()
  106. # print('use bn in block:',use_bn)
  107. self.use_bn = use_bn
  108. if self.maml:
  109. self.conv1 = Conv2d_fw(inplanes, planes, kernel_size=1, bias=False)
  110. else:
  111. self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
  112. if self.use_bn:
  113. if self.maml:
  114. self.bn1 = BatchNorm2d_fw(planes)
  115. else:
  116. self.bn1 = nn.BatchNorm2d(planes, track_running_stats=track_running_stats)
  117. if self.maml:
  118. self.conv2 = Conv2d_fw(planes, planes, kernel_size=3, stride=stride,
  119. padding=1, bias=False)
  120. else:
  121. self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
  122. padding=1, bias=False)
  123. if self.use_bn:
  124. if self.maml:
  125. self.bn2 = BatchNorm2d_fw(planes)
  126. else:
  127. self.bn2 = nn.BatchNorm2d(planes, track_running_stats=track_running_stats)
  128. if self.use_bn:
  129. self.conv3 = Conv2d_fw(planes, planes * 4, kernel_size=1, bias=False)
  130. else:
  131. self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
  132. if self.use_bn:
  133. if self.maml:
  134. self.bn3 = BatchNorm2d_fw(planes * 4)
  135. else:
  136. self.bn3 = nn.BatchNorm2d(planes * 4, track_running_stats=track_running_stats)
  137. self.relu = nn.ReLU(inplace=True)
  138. self.downsample = downsample
  139. self.stride = stride
  140. def forward(self, x):
  141. residual = x
  142. out = self.conv1(x)
  143. if self.use_bn:
  144. out = self.bn1(out)
  145. out = self.relu(out)
  146. out = self.conv2(out)
  147. if self.use_bn:
  148. out = self.bn2(out)
  149. out = self.relu(out)
  150. out = self.conv3(out)
  151. if self.use_bn:
  152. out = self.bn3(out)
  153. if self.downsample is not None:
  154. residual = self.downsample(x)
  155. out += residual
  156. out = self.relu(out)
  157. return out
  158. class MyModule(nn.Module):
  159. maml = False #Default
  160. def __init__(self, layers):
  161. super(MyModule, self).__init__()
  162. self.layers = layers
  163. def forward(self, x, jigsaw=False):
  164. for _,layer in enumerate(self.layers):
  165. x = layer(x, jigsaw)
  166. return x
  167. class ResNet(nn.Module):
  168. maml = False #Default
  169. def __init__(self, block, layers, network_type, num_classes, att_type=None, tracking=True, use_bn=True):
  170. self.track_running_stats = tracking
  171. self.use_bn = use_bn
  172. self.inplanes = 64
  173. super(ResNet, self).__init__()
  174. self.network_type = network_type
  175. # different model config between ImageNet and CIFAR
  176. if network_type == "ImageNet":
  177. if self.maml:
  178. self.conv1 = Conv2d_fw(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
  179. else:
  180. self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
  181. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
  182. # self.avgpool = nn.AvgPool2d(7)
  183. self.avgpool = nn.AdaptiveAvgPool2d(1)
  184. else:
  185. if self.maml:
  186. self.conv1 = Conv2d_fw(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
  187. else:
  188. self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
  189. if self.use_bn:
  190. if self.maml:
  191. self.bn1 = BatchNorm2d_fw(64)
  192. else:
  193. self.bn1 = nn.BatchNorm2d(64, track_running_stats=self.track_running_stats)
  194. self.relu = nn.ReLU(inplace=True)
  195. self.layer1 = self._make_layer(block, 64, layers[0], att_type=att_type, use_bn=self.use_bn)
  196. self.layer2 = self._make_layer(block, 128, layers[1], stride=2, att_type=att_type, use_bn=self.use_bn)
  197. self.layer3 = self._make_layer(block, 256, layers[2], stride=2, att_type=att_type, use_bn=self.use_bn)
  198. self.layer4 = self._make_layer(block, 512, layers[3], stride=2, att_type=att_type, use_bn=self.use_bn)
  199. # self.fc = nn.Linear(512 * block.expansion, num_classes)
  200. # init.kaiming_normal(self.fc.weight)
  201. for key in self.state_dict():
  202. if key.split('.')[-1]=="weight":
  203. if "conv" in key:
  204. init.kaiming_normal_(self.state_dict()[key], mode='fan_out')
  205. if "bn" in key:
  206. if "SpatialGate" in key:
  207. self.state_dict()[key][...] = 0
  208. else:
  209. self.state_dict()[key][...] = 1
  210. elif key.split(".")[-1]=='bias':
  211. self.state_dict()[key][...] = 0
  212. # import ipdb; ipdb.set_trace()
  213. # self.layer1 = MyModule(self.layer1)
  214. # self.layer2 = MyModule(self.layer2)
  215. # self.layer3 = MyModule(self.layer3)
  216. # self.layer4 = MyModule(self.layer4)
  217. def _make_layer(self, block, planes, blocks, stride=1, att_type=None, use_bn=True):
  218. downsample = None
  219. downsample_jigsaw = None
  220. if stride != 1 or self.inplanes != planes * block.expansion:
  221. # print('use bn:',use_bn)
  222. if use_bn:
  223. if self.maml:
  224. downsample = nn.Sequential(
  225. Conv2d_fw(self.inplanes, planes * block.expansion,
  226. kernel_size=1, stride=stride, bias=False),
  227. BatchNorm2d_fw(planes * block.expansion),
  228. )
  229. else:
  230. downsample = nn.Sequential(
  231. nn.Conv2d(self.inplanes, planes * block.expansion,
  232. kernel_size=1, stride=stride, bias=False),
  233. nn.BatchNorm2d(planes * block.expansion, track_running_stats=self.track_running_stats),
  234. )
  235. else:
  236. if self.maml:
  237. downsample = nn.Sequential(
  238. Conv2d_fw(self.inplanes, planes * block.expansion,
  239. kernel_size=1, stride=stride, bias=False),
  240. )
  241. else:
  242. downsample = nn.Sequential(
  243. nn.Conv2d(self.inplanes, planes * block.expansion,
  244. kernel_size=1, stride=stride, bias=False),
  245. )
  246. layers = []
  247. layers.append(block(self.inplanes, planes, stride, downsample, \
  248. downsample_jigsaw=downsample_jigsaw, track_running_stats=self.track_running_stats, use_bn=self.use_bn))
  249. self.inplanes = planes * block.expansion
  250. for i in range(1, blocks):
  251. layers.append(block(self.inplanes, planes, track_running_stats=self.track_running_stats, use_bn=self.use_bn))
  252. return nn.Sequential(*layers)
  253. # return MyModule(layers)
  254. def forward(self, x, jigsaw=False):
  255. # import ipdb; ipdb.set_trace()
  256. x = self.conv1(x)
  257. if self.use_bn:
  258. x = self.bn1(x)
  259. x = self.relu(x)
  260. if self.network_type == "ImageNet":
  261. x = self.maxpool(x)
  262. x = self.layer1(x)
  263. x = self.layer2(x)
  264. x = self.layer3(x)
  265. x = self.layer4(x)
  266. # print(x.shape)
  267. if self.network_type == "ImageNet":
  268. x = self.avgpool(x)
  269. # x = F.avg_pool2d(x, 2)
  270. else:
  271. x = F.avg_pool2d(x, 4)
  272. # print('after pool',x.shape)
  273. # x = x.view(x.size(0), -1)
  274. # x = self.fc(x)
  275. return x
  276. def ResidualNet(network_type, depth, num_classes, att_type, tracking=True, use_bn=True):
  277. maml = False #Default
  278. # print("USE BN:",use_bn)
  279. assert network_type in ["ImageNet", "CIFAR10", "CIFAR100"], "network type should be ImageNet or CIFAR10 / CIFAR100"
  280. assert depth in [18, 34, 50, 101], 'network depth should be 18, 34, 50 or 101'
  281. if depth == 18:
  282. model = ResNet(BasicBlock, [2, 2, 2, 2], network_type, num_classes, att_type, tracking, use_bn)
  283. elif depth == 34:
  284. model = ResNet(BasicBlock, [3, 4, 6, 3], network_type, num_classes, att_type, tracking, use_bn)
  285. elif depth == 50:
  286. model = ResNet(Bottleneck, [3, 4, 6, 3], network_type, num_classes, att_type, tracking, use_bn)
  287. elif depth == 101:
  288. model = ResNet(Bottleneck, [3, 4, 23, 3], network_type, num_classes, att_type, tracking, use_bn)
  289. return model
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...