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

backbone.py 14 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
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
  1. # This code is modified from https://github.com/facebookresearch/low-shot-shrink-hallucinate
  2. import torch
  3. from torch.autograd import Variable
  4. import torch.nn as nn
  5. import math
  6. import numpy as np
  7. import torch.nn.functional as F
  8. from torch.nn.utils.weight_norm import WeightNorm
  9. # Basic ResNet model
  10. def init_layer(L):
  11. # Initialization using fan-in
  12. if isinstance(L, nn.Conv2d):
  13. n = L.kernel_size[0]*L.kernel_size[1]*L.out_channels
  14. L.weight.data.normal_(0,math.sqrt(2.0/float(n)))
  15. elif isinstance(L, nn.BatchNorm2d):
  16. L.weight.data.fill_(1)
  17. L.bias.data.fill_(0)
  18. class distLinear(nn.Module):
  19. def __init__(self, indim, outdim):
  20. super(distLinear, self).__init__()
  21. self.L = nn.Linear( indim, outdim, bias = False)
  22. WeightNorm.apply(self.L, 'weight', dim=0) #split the weight update component to direction and norm
  23. if outdim <=200:
  24. self.scale_factor = 2; #a fixed scale factor to scale the output of cos value into a reasonably large input for softmax
  25. else:
  26. self.scale_factor = 10; #in omniglot, a larger scale factor is required to handle >1000 output classes.
  27. def forward(self, x):
  28. x_norm = torch.norm(x, p=2, dim =1).unsqueeze(1).expand_as(x)
  29. x_normalized = x.div(x_norm+ 0.00001)
  30. L_norm = torch.norm(self.L.weight.data, p=2, dim =1).unsqueeze(1).expand_as(self.L.weight.data)
  31. self.L.weight.data = self.L.weight.data.div(L_norm + 0.00001)
  32. cos_dist = self.L(x_normalized) #matrix product by forward function
  33. scores = self.scale_factor* (cos_dist)
  34. return scores
  35. class Flatten(nn.Module):
  36. def __init__(self):
  37. super(Flatten, self).__init__()
  38. def forward(self, x):
  39. return x.view(x.size(0), -1)
  40. class Linear_fw(nn.Linear): #used in MAML to forward input with fast weight
  41. def __init__(self, in_features, out_features):
  42. super(Linear_fw, self).__init__(in_features, out_features)
  43. self.weight.fast = None #Lazy hack to add fast weight link
  44. self.bias.fast = None
  45. def forward(self, x):
  46. if self.weight.fast is not None and self.bias.fast is not None:
  47. out = F.linear(x, self.weight.fast, self.bias.fast)
  48. else:
  49. out = super(Linear_fw, self).forward(x)
  50. return out
  51. class Conv2d_fw(nn.Conv2d): #used in MAML to forward input with fast weight
  52. def __init__(self, in_channels, out_channels, kernel_size, stride=1,padding=0, bias = True):
  53. super(Conv2d_fw, self).__init__(in_channels, out_channels, kernel_size, stride=stride, padding=padding, bias=bias)
  54. self.weight.fast = None
  55. if not self.bias is None:
  56. self.bias.fast = None
  57. def forward(self, x):
  58. if self.bias is None:
  59. if self.weight.fast is not None:
  60. out = F.conv2d(x, self.weight.fast, None, stride= self.stride, padding=self.padding)
  61. else:
  62. out = super(Conv2d_fw, self).forward(x)
  63. else:
  64. if self.weight.fast is not None and self.bias.fast is not None:
  65. out = F.conv2d(x, self.weight.fast, self.bias.fast, stride= self.stride, padding=self.padding)
  66. else:
  67. out = super(Conv2d_fw, self).forward(x)
  68. return out
  69. class BatchNorm2d_fw(nn.BatchNorm2d): #used in MAML to forward input with fast weight
  70. def __init__(self, num_features):
  71. super(BatchNorm2d_fw, self).__init__(num_features)
  72. self.weight.fast = None
  73. self.bias.fast = None
  74. def forward(self, x):
  75. running_mean = torch.zeros(x.data.size()[1]).cuda()
  76. running_var = torch.ones(x.data.size()[1]).cuda()
  77. if self.weight.fast is not None and self.bias.fast is not None:
  78. out = F.batch_norm(x, running_mean, running_var, self.weight.fast, self.bias.fast, training = True, momentum = 1)
  79. #batch_norm momentum hack: follow hack of Kate Rakelly in pytorch-maml/src/layers.py
  80. else:
  81. out = F.batch_norm(x, running_mean, running_var, self.weight, self.bias, training = True, momentum = 1)
  82. return out
  83. # Simple Conv Block
  84. class ConvBlock(nn.Module):
  85. maml = False #Default
  86. def __init__(self, indim, outdim, pool = True, padding = 1):
  87. super(ConvBlock, self).__init__()
  88. self.indim = indim
  89. self.outdim = outdim
  90. if self.maml:
  91. self.C = Conv2d_fw(indim, outdim, 3, padding = padding)
  92. self.BN = BatchNorm2d_fw(outdim)
  93. else:
  94. self.C = nn.Conv2d(indim, outdim, 3, padding= padding)
  95. self.BN = nn.BatchNorm2d(outdim)
  96. self.relu = nn.ReLU(inplace=True)
  97. self.parametrized_layers = [self.C, self.BN, self.relu]
  98. if pool:
  99. self.pool = nn.MaxPool2d(2)
  100. self.parametrized_layers.append(self.pool)
  101. for layer in self.parametrized_layers:
  102. init_layer(layer)
  103. self.trunk = nn.Sequential(*self.parametrized_layers)
  104. def forward(self,x):
  105. out = self.trunk(x)
  106. return out
  107. # Simple ResNet Block
  108. class SimpleBlock(nn.Module):
  109. maml = False #Default
  110. def __init__(self, indim, outdim, half_res):
  111. super(SimpleBlock, self).__init__()
  112. self.indim = indim
  113. self.outdim = outdim
  114. if self.maml:
  115. self.C1 = Conv2d_fw(indim, outdim, kernel_size=3, stride=2 if half_res else 1, padding=1, bias=False)
  116. self.BN1 = BatchNorm2d_fw(outdim)
  117. self.C2 = Conv2d_fw(outdim, outdim,kernel_size=3, padding=1,bias=False)
  118. self.BN2 = BatchNorm2d_fw(outdim)
  119. else:
  120. self.C1 = nn.Conv2d(indim, outdim, kernel_size=3, stride=2 if half_res else 1, padding=1, bias=False)
  121. self.BN1 = nn.BatchNorm2d(outdim)
  122. self.C2 = nn.Conv2d(outdim, outdim,kernel_size=3, padding=1,bias=False)
  123. self.BN2 = nn.BatchNorm2d(outdim)
  124. self.relu1 = nn.ReLU(inplace=True)
  125. self.relu2 = nn.ReLU(inplace=True)
  126. self.parametrized_layers = [self.C1, self.C2, self.BN1, self.BN2]
  127. self.half_res = half_res
  128. # if the input number of channels is not equal to the output, then need a 1x1 convolution
  129. if indim!=outdim:
  130. if self.maml:
  131. self.shortcut = Conv2d_fw(indim, outdim, 1, 2 if half_res else 1, bias=False)
  132. self.BNshortcut = BatchNorm2d_fw(outdim)
  133. else:
  134. self.shortcut = nn.Conv2d(indim, outdim, 1, 2 if half_res else 1, bias=False)
  135. self.BNshortcut = nn.BatchNorm2d(outdim)
  136. self.parametrized_layers.append(self.shortcut)
  137. self.parametrized_layers.append(self.BNshortcut)
  138. self.shortcut_type = '1x1'
  139. else:
  140. self.shortcut_type = 'identity'
  141. for layer in self.parametrized_layers:
  142. init_layer(layer)
  143. def forward(self, x):
  144. out = self.C1(x)
  145. out = self.BN1(out)
  146. out = self.relu1(out)
  147. out = self.C2(out)
  148. out = self.BN2(out)
  149. short_out = x if self.shortcut_type == 'identity' else self.BNshortcut(self.shortcut(x))
  150. out = out + short_out
  151. out = self.relu2(out)
  152. return out
  153. # Bottleneck block
  154. class BottleneckBlock(nn.Module):
  155. maml = False #Default
  156. def __init__(self, indim, outdim, half_res):
  157. super(BottleneckBlock, self).__init__()
  158. bottleneckdim = int(outdim/4)
  159. self.indim = indim
  160. self.outdim = outdim
  161. if self.maml:
  162. self.C1 = Conv2d_fw(indim, bottleneckdim, kernel_size=1, bias=False)
  163. self.BN1 = BatchNorm2d_fw(bottleneckdim)
  164. self.C2 = Conv2d_fw(bottleneckdim, bottleneckdim, kernel_size=3, stride=2 if half_res else 1,padding=1)
  165. self.BN2 = BatchNorm2d_fw(bottleneckdim)
  166. self.C3 = Conv2d_fw(bottleneckdim, outdim, kernel_size=1, bias=False)
  167. self.BN3 = BatchNorm2d_fw(outdim)
  168. else:
  169. self.C1 = nn.Conv2d(indim, bottleneckdim, kernel_size=1, bias=False)
  170. self.BN1 = nn.BatchNorm2d(bottleneckdim)
  171. self.C2 = nn.Conv2d(bottleneckdim, bottleneckdim, kernel_size=3, stride=2 if half_res else 1,padding=1)
  172. self.BN2 = nn.BatchNorm2d(bottleneckdim)
  173. self.C3 = nn.Conv2d(bottleneckdim, outdim, kernel_size=1, bias=False)
  174. self.BN3 = nn.BatchNorm2d(outdim)
  175. self.relu = nn.ReLU()
  176. self.parametrized_layers = [self.C1, self.BN1, self.C2, self.BN2, self.C3, self.BN3]
  177. self.half_res = half_res
  178. # if the input number of channels is not equal to the output, then need a 1x1 convolution
  179. if indim!=outdim:
  180. if self.maml:
  181. self.shortcut = Conv2d_fw(indim, outdim, 1, stride=2 if half_res else 1, bias=False)
  182. else:
  183. self.shortcut = nn.Conv2d(indim, outdim, 1, stride=2 if half_res else 1, bias=False)
  184. self.parametrized_layers.append(self.shortcut)
  185. self.shortcut_type = '1x1'
  186. else:
  187. self.shortcut_type = 'identity'
  188. for layer in self.parametrized_layers:
  189. init_layer(layer)
  190. def forward(self, x):
  191. short_out = x if self.shortcut_type == 'identity' else self.shortcut(x)
  192. out = self.C1(x)
  193. out = self.BN1(out)
  194. out = self.relu(out)
  195. out = self.C2(out)
  196. out = self.BN2(out)
  197. out = self.relu(out)
  198. out = self.C3(out)
  199. out = self.BN3(out)
  200. out = out + short_out
  201. out = self.relu(out)
  202. return out
  203. class ConvNet(nn.Module):
  204. def __init__(self, depth, flatten = True):
  205. super(ConvNet,self).__init__()
  206. trunk = []
  207. for i in range(depth):
  208. indim = 3 if i == 0 else 64
  209. outdim = 64
  210. B = ConvBlock(indim, outdim, pool = ( i <4 ) ) #only pooling for fist 4 layers
  211. trunk.append(B)
  212. if flatten:
  213. trunk.append(Flatten())
  214. self.trunk = nn.Sequential(*trunk)
  215. self.final_feat_dim = 1600
  216. def forward(self,x):
  217. out = self.trunk(x)
  218. return out
  219. class ConvNetNopool(nn.Module): #Relation net use a 4 layer conv with pooling in only first two layers, else no pooling
  220. def __init__(self, depth):
  221. super(ConvNetNopool,self).__init__()
  222. trunk = []
  223. for i in range(depth):
  224. indim = 3 if i == 0 else 64
  225. outdim = 64
  226. B = ConvBlock(indim, outdim, pool = ( i in [0,1] ), padding = 0 if i in[0,1] else 1 ) #only first two layer has pooling and no padding
  227. trunk.append(B)
  228. self.trunk = nn.Sequential(*trunk)
  229. self.final_feat_dim = [64,19,19]
  230. def forward(self,x):
  231. out = self.trunk(x)
  232. return out
  233. class ConvNetS(nn.Module): #For omniglot, only 1 input channel, output dim is 64
  234. def __init__(self, depth, flatten = True):
  235. super(ConvNetS,self).__init__()
  236. trunk = []
  237. for i in range(depth):
  238. indim = 1 if i == 0 else 64
  239. outdim = 64
  240. B = ConvBlock(indim, outdim, pool = ( i <4 ) ) #only pooling for fist 4 layers
  241. trunk.append(B)
  242. if flatten:
  243. trunk.append(Flatten())
  244. self.trunk = nn.Sequential(*trunk)
  245. self.final_feat_dim = 64
  246. def forward(self,x):
  247. out = x[:,0:1,:,:] #only use the first dimension
  248. out = self.trunk(out)
  249. return out
  250. class ConvNetSNopool(nn.Module): #Relation net use a 4 layer conv with pooling in only first two layers, else no pooling. For omniglot, only 1 input channel, output dim is [64,5,5]
  251. def __init__(self, depth):
  252. super(ConvNetSNopool,self).__init__()
  253. trunk = []
  254. for i in range(depth):
  255. indim = 1 if i == 0 else 64
  256. outdim = 64
  257. B = ConvBlock(indim, outdim, pool = ( i in [0,1] ), padding = 0 if i in[0,1] else 1 ) #only first two layer has pooling and no padding
  258. trunk.append(B)
  259. self.trunk = nn.Sequential(*trunk)
  260. self.final_feat_dim = [64,5,5]
  261. def forward(self,x):
  262. out = x[:,0:1,:,:] #only use the first dimension
  263. out = self.trunk(out)
  264. return out
  265. class ResNet(nn.Module):
  266. maml = False #Default
  267. def __init__(self,block,list_of_num_layers, list_of_out_dims, flatten = True):
  268. # list_of_num_layers specifies number of layers in each stage
  269. # list_of_out_dims specifies number of output channel for each stage
  270. super(ResNet,self).__init__()
  271. assert len(list_of_num_layers)==4, 'Can have only four stages'
  272. if self.maml:
  273. conv1 = Conv2d_fw(3, 64, kernel_size=7, stride=2, padding=3,
  274. bias=False)
  275. bn1 = BatchNorm2d_fw(64)
  276. else:
  277. conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
  278. bias=False)
  279. bn1 = nn.BatchNorm2d(64)
  280. relu = nn.ReLU()
  281. pool1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
  282. init_layer(conv1)
  283. init_layer(bn1)
  284. trunk = [conv1, bn1, relu, pool1]
  285. indim = 64
  286. for i in range(4):
  287. for j in range(list_of_num_layers[i]):
  288. half_res = (i>=1) and (j==0)
  289. B = block(indim, list_of_out_dims[i], half_res)
  290. trunk.append(B)
  291. indim = list_of_out_dims[i]
  292. if flatten:
  293. avgpool = nn.AvgPool2d(7)
  294. trunk.append(avgpool)
  295. trunk.append(Flatten())
  296. self.final_feat_dim = indim
  297. else:
  298. self.final_feat_dim = [ indim, 7, 7]
  299. self.trunk = nn.Sequential(*trunk)
  300. def forward(self,x):
  301. out = self.trunk(x)
  302. return out
  303. def Conv4():
  304. return ConvNet(4,flatten=True)
  305. def Conv6():
  306. return ConvNet(6)
  307. def Conv4NP():
  308. return ConvNetNopool(4)
  309. def Conv6NP():
  310. return ConvNetNopool(6)
  311. def Conv4S():
  312. return ConvNetS(4)
  313. def Conv4SNP():
  314. return ConvNetSNopool(4)
  315. def ResNet10( flatten = True):
  316. return ResNet(SimpleBlock, [1,1,1,1],[64,128,256,512], flatten)
  317. def ResNet18( flatten = True):
  318. return ResNet(SimpleBlock, [2,2,2,2],[64,128,256,512], flatten)
  319. def ResNet34( flatten = True):
  320. return ResNet(SimpleBlock, [3,4,6,3],[64,128,256,512], flatten)
  321. def ResNet50( flatten = True):
  322. return ResNet(BottleneckBlock, [3,4,6,3], [256,512,1024,2048], flatten)
  323. def ResNet101( flatten = True):
  324. return ResNet(BottleneckBlock, [3,4,23,3],[256,512,1024,2048], flatten)
Tip!

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

Comments

Loading...