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

maml.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
  1. # This code is modified from https://github.com/dragen1860/MAML-Pytorch and https://github.com/katerakelly/pytorch-maml
  2. import models.backbone as backbone
  3. import torch
  4. import torch.nn as nn
  5. from torch.autograd import Variable
  6. import numpy as np
  7. import torch.nn.functional as F
  8. from methods.meta_template import MetaTemplate
  9. from utils.utils import Logger
  10. try:
  11. from apex.parallel import DistributedDataParallel as DDP
  12. from apex.fp16_utils import *
  13. from apex import amp, optimizers
  14. from apex.multi_tensor_apply import multi_tensor_applier
  15. except ImportError:
  16. print("AMP is not installed. If --amp is True, code will fail.")
  17. class MAML(MetaTemplate):
  18. def __init__(self, model_func, n_way, n_support, approx = False, jigsaw=False, \
  19. lbda=0.0, rotation=False, tracking=False, use_bn=True, pretrain=False, model="resnet18", lbda_jigsaw=None, lbda_rotation=None):
  20. super(MAML, self).__init__(model_func, n_way, n_support, use_bn, pretrain, change_way = False)
  21. self.loss_fn = nn.CrossEntropyLoss()
  22. self.classifier = backbone.Linear_fw(self.feat_dim, n_way)
  23. self.classifier.bias.data.fill_(0)
  24. self.n_task = 1
  25. self.task_update_num = 5
  26. self.train_lr = 0.01
  27. self.approx = approx #first order approx.
  28. self.global_count = 0
  29. self.jigsaw = jigsaw
  30. self.rotation = rotation
  31. self.lbda = lbda
  32. if self.jigsaw and self.rotation:
  33. self.fc6 = nn.Sequential()
  34. self.fc6.add_module('fc6_s1',backbone.Linear_fw(1024, 1024)) if model != "resnet18" else self.fc6.add_module('fc6_s1',backbone.Linear_fw(512, 512))#for resnet
  35. self.fc6.add_module('relu6_s1',nn.ReLU(inplace=True))
  36. self.fc6.add_module('drop6_s1',nn.Dropout(p=0.5))
  37. self.fc7_jigsaw = nn.Sequential()
  38. self.fc7_jigsaw.add_module('fc7',backbone.Linear_fw(9*1024,4096)) if model != "resnet18" else self.fc7_jigsaw.add_module('fc7',backbone.Linear_fw(9*512,4096))#for resnet
  39. self.fc7_jigsaw.add_module('relu7',nn.ReLU(inplace=True))
  40. self.fc7_jigsaw.add_module('drop7',nn.Dropout(p=0.5))
  41. self.classifier_jigsaw = nn.Sequential()
  42. self.classifier_jigsaw.add_module('fc8',backbone.Linear_fw(4096, 35))
  43. self.fc7_rotation = nn.Sequential()
  44. self.fc7_rotation.add_module('fc7',backbone.Linear_fw(1024,128)) if model != "resnet18" else self.fc7_rotation.add_module('fc7',backbone.Linear_fw(512,128))#for resnet
  45. self.fc7_rotation.add_module('relu7',nn.ReLU(inplace=True))
  46. self.fc7_rotation.add_module('drop7',nn.Dropout(p=0.5))
  47. self.classifier_rotation = nn.Sequential()
  48. self.classifier_rotation.add_module('fc8',backbone.Linear_fw(128, 4))
  49. elif self.jigsaw:
  50. self.fc6 = nn.Sequential()
  51. self.fc6.add_module('fc6_s1',backbone.Linear_fw(1024, 1024)) if model != "resnet18" else self.fc6.add_module('fc6_s1',backbone.Linear_fw(512, 512))#for resnet
  52. self.fc6.add_module('relu6_s1',nn.ReLU(inplace=True))
  53. self.fc6.add_module('drop6_s1',nn.Dropout(p=0.5))
  54. self.fc7 = nn.Sequential()
  55. self.fc7.add_module('fc7',backbone.Linear_fw(9*1024,4096)) if model != "resnet18" else self.fc7.add_module('fc7',backbone.Linear_fw(9*512,4096))#for resnet
  56. self.fc7.add_module('relu7',nn.ReLU(inplace=True))
  57. self.fc7.add_module('drop7',nn.Dropout(p=0.5))
  58. self.classifier_jigsaw = nn.Sequential()
  59. self.classifier_jigsaw.add_module('fc8',backbone.Linear_fw(4096, 35))
  60. elif self.rotation:
  61. self.fc6 = nn.Sequential()
  62. self.fc6.add_module('fc6_s1',backbone.Linear_fw(1024, 1024)) if model != "resnet18" else self.fc6.add_module('fc6_s1',backbone.Linear_fw(512, 512))#for resnet
  63. self.fc6.add_module('relu6_s1',nn.ReLU(inplace=True))
  64. self.fc6.add_module('drop6_s1',nn.Dropout(p=0.5))
  65. self.fc7 = nn.Sequential()
  66. self.fc7.add_module('fc7',backbone.Linear_fw(1024,128)) if model != "resnet18" else self.fc7.add_module('fc7',backbone.Linear_fw(512,128))#for resnet
  67. self.fc7.add_module('relu7',nn.ReLU(inplace=True))
  68. self.fc7.add_module('drop7',nn.Dropout(p=0.5))
  69. self.classifier_rotation = nn.Sequential()
  70. self.classifier_rotation.add_module('fc8',backbone.Linear_fw(128, 4))
  71. def forward(self,x):
  72. out = self.feature.forward(x)
  73. scores = self.classifier.forward(out.squeeze())
  74. return scores
  75. def set_forward(self,x, is_feature = False):
  76. assert is_feature == False, 'MAML do not support fixed feature'
  77. x = x.cuda()
  78. x_var = Variable(x)
  79. x_a_i = x_var[:,:self.n_support,:,:,:].contiguous().view( self.n_way* self.n_support, *x.size()[2:])
  80. x_b_i = x_var[:,self.n_support:,:,:,:].contiguous().view( self.n_way* self.n_query, *x.size()[2:])
  81. y_a_i = Variable( torch.from_numpy( np.repeat(range( self.n_way ), self.n_support ) )).cuda()
  82. fast_parameters = list(self.parameters())
  83. for weight in self.parameters():
  84. weight.fast = None
  85. self.zero_grad()
  86. for task_step in range(self.task_update_num):
  87. scores = self.forward(x_a_i)
  88. set_loss = self.loss_fn(scores, y_a_i)
  89. grad = torch.autograd.grad(set_loss, fast_parameters, create_graph=True, allow_unused=True)#added allow_unused=True
  90. if self.approx:
  91. # grad = [ g.detach() for g in grad ]
  92. # import ipdb; ipdb.set_trace()
  93. grad_mask = []
  94. for i,g in enumerate(grad):
  95. if g is None:
  96. grad_mask.append(i)
  97. grad = [g.detach() if g is not None else None for g in grad ]
  98. fast_parameters = []
  99. for k, weight in enumerate(self.parameters()):
  100. if k not in grad_mask:
  101. if weight.fast is None:
  102. weight.fast = weight - self.train_lr * grad[k] #link fast weight to weight
  103. else:
  104. weight.fast = weight.fast - self.train_lr * grad[k]
  105. fast_parameters.append(weight.fast)
  106. else:
  107. fast_parameters.append(weight)
  108. scores = self.forward(x_b_i)
  109. return scores
  110. def set_forward_adaptation(self,x, is_feature = False): #overwrite parrent function
  111. raise ValueError('MAML performs further adapation simply by increasing task_upate_num')
  112. def set_forward_loss(self, x):
  113. scores = self.set_forward(x, is_feature = False)
  114. y_b_i = Variable( torch.from_numpy( np.repeat(range( self.n_way ), self.n_query ) )).cuda()
  115. loss = self.loss_fn(scores, y_b_i)
  116. return loss
  117. def set_forward_loss_unlabel(self, patches=None, patches_label=None):
  118. if self.jigsaw:
  119. x_, y_ = self.set_forward_unlabel(patches=patches,patches_label=patches_label)
  120. pred = torch.max(x_,1)
  121. acc_jigsaw = torch.sum(pred[1] == y_).cpu().numpy()*1.0/len(y_)
  122. elif self.rotation:
  123. x_, y_ = self.set_forward_unlabel(patches=patches,patches_label=patches_label)
  124. pred = torch.max(x_,1)
  125. acc_rotation = torch.sum(pred[1] == y_).cpu().numpy()*1.0/len(y_)
  126. if self.jigsaw:
  127. return self.loss_fn(x_,y_), acc_jigsaw
  128. elif self.rotation:
  129. return self.loss_fn(x_,y_), acc_rotation
  130. def set_forward_unlabel(self, patches=None, patches_label=None):
  131. if len(patches.size()) == 6:
  132. Way,S,T,C,H,W = patches.size()#torch.Size([5, 15, 9, 3, 75, 75])
  133. B = Way*S
  134. elif len(patches.size()) == 5:
  135. B,T,C,H,W = patches.size()#torch.Size([5, 15, 9, 3, 75, 75])
  136. if self.jigsaw:
  137. patches = patches.view(B*T,C,H,W).cuda()#torch.Size([675, 3, 64, 64])
  138. if self.dual_cbam:
  139. patch_feat = self.feature(patches, jigsaw=True)#torch.Size([675, 512])
  140. else:
  141. patch_feat = self.feature(patches)#torch.Size([675, 512])
  142. x_ = patch_feat.view(B,T,-1)
  143. x_ = x_.transpose(0,1)#torch.Size([9, 75, 512])
  144. x_list = []
  145. for i in range(9):
  146. z = self.fc6(x_[i])#torch.Size([75, 512])
  147. z = z.view([B,1,-1])#torch.Size([75, 1, 512])
  148. x_list.append(z)
  149. x_ = torch.cat(x_list,1)#torch.Size([75, 9, 512])
  150. x_ = self.fc7(x_.view(B,-1))#torch.Size([75, 9*512])
  151. x_ = self.classifier_jigsaw(x_)
  152. y_ = patches_label.view(-1).cuda()
  153. return x_, y_
  154. elif self.rotation:
  155. patches = patches.view(B*T,C,H,W).cuda()
  156. x_ = self.feature(patches)#torch.Size([64, 512, 1, 1])
  157. x_ = x_.squeeze()
  158. x_ = self.fc6(x_)
  159. x_ = self.fc7(x_)#64,128
  160. x_ = self.classifier_rotation(x_)#64,4
  161. pred = torch.max(x_,1)
  162. y_ = patches_label.view(-1).cuda()
  163. return x_, y_
  164. def train_loop(self, epoch, train_loader, optimizer, base_loader_u=None, pbar=None, enable_amp=False, semi_sup=False): #overwrite parrent function
  165. print_freq = 10
  166. avg_loss=0
  167. avg_loss_maml=0
  168. avg_loss_jigsaw=0
  169. avg_loss_rotation=0
  170. task_count = 0
  171. loss_all = []
  172. optimizer.zero_grad()
  173. iter_num = 0
  174. #train
  175. for iter_num, inputs in enumerate(train_loader):
  176. self.global_count += 1
  177. x = inputs[0]
  178. self.n_query = x.size(1) - self.n_support
  179. assert self.n_way == x.size(0), "MAML do not support way change"
  180. loss_maml = self.set_forward_loss(x)
  181. if self.jigsaw:
  182. loss_jigsaw, acc_jigsaw = self.set_forward_loss_unlabel(inputs[2], inputs[3])# torch.Size([5, 21, 9, 3, 75, 75]), torch.Size([5, 21])
  183. loss = (1.0-self.lbda) * loss_maml + self.lbda * loss_jigsaw
  184. Logger.log({'train/loss_maml': float(loss_maml.item())}, step=self.global_count)
  185. Logger.log({'train/loss_jigsaw': float(loss_jigsaw.item())}, step=self.global_count)
  186. avg_loss_maml += loss_maml.item()
  187. avg_loss_jigsaw += loss_jigsaw.item()
  188. elif self.rotation:
  189. loss_rotation, acc_rotation = self.set_forward_loss_unlabel(inputs[2], inputs[3])# torch.Size([5, 21, 9, 3, 75, 75]), torch.Size([5, 21])
  190. loss = (1.0-self.lbda) * loss_maml + self.lbda * loss_rotation
  191. Logger.log({'train/loss_maml': float(loss_maml.item())}, step=self.global_count)
  192. Logger.log({'train/loss_rotation': float(loss_rotation.item())}, step=self.global_count)
  193. avg_loss_maml += loss_maml.item()
  194. avg_loss_rotation += loss_rotation.item()
  195. else:
  196. loss = loss_maml
  197. Logger.log({'train/loss_maml': float(loss_maml.item())}, step=self.global_count)
  198. avg_loss = avg_loss+loss.item()
  199. loss_all.append(loss)
  200. task_count += 1
  201. if pbar:
  202. pbar.update(1)
  203. if task_count == self.n_task:
  204. loss_q = torch.stack(loss_all).sum(0)
  205. Logger.log({'train/loss_maml': float(loss_maml.item())}, step=self.global_count)
  206. if enable_amp:
  207. with amp.scale_loss(loss_q, optimizer) as scaled_loss:
  208. scaled_loss.backward()
  209. else:
  210. loss_q.backward()
  211. optimizer.step()
  212. task_count = 0
  213. loss_all = []
  214. optimizer.zero_grad()
  215. return avg_loss
  216. def test_loop(self, test_loader, base_loader_u=None, semi_sup=False, proto_only=False, std_also=False):
  217. correct =0
  218. count = 0
  219. acc_all = []
  220. acc_all_jigsaw = []
  221. acc_all_rotation = []
  222. iter_num = len(test_loader)
  223. for i, inputs in enumerate(test_loader):
  224. x = inputs[0]
  225. self.n_query = x.size(1) - self.n_support
  226. assert self.n_way == x.size(0), "MAML do not support way change"
  227. correct_this, count_this = self.correct(x)
  228. acc_all.append(correct_this/ count_this *100)
  229. if not proto_only:
  230. if self.jigsaw:
  231. loss_jigsaw, acc_jigsaw = self.set_forward_loss_unlabel(inputs[2], inputs[3])
  232. acc_all_jigsaw.append(acc_jigsaw*100)
  233. elif self.rotation:
  234. loss_rotation, acc_rotation = self.set_forward_loss_unlabel(inputs[2], inputs[3])
  235. acc_all_rotation.append(acc_rotation*100)
  236. acc_all = np.asarray(acc_all)
  237. acc_mean = np.mean(acc_all)
  238. acc_std = np.std(acc_all)
  239. print('%d Test Acc = %4.2f%% +- %4.2f%%' %(iter_num, acc_mean, 1.96* acc_std/np.sqrt(iter_num)))
  240. if proto_only or (not self.jigsaw and not self.rotation):
  241. if std_also:
  242. return acc_mean, acc_std
  243. else:
  244. return acc_mean
  245. elif self.jigsaw:
  246. acc_all_jigsaw = np.asarray(acc_all_jigsaw)
  247. acc_mean_jigsaw = np.mean(acc_all_jigsaw)
  248. acc_std_jigsaw = np.std(acc_all_jigsaw)
  249. print('%d Test Jigsaw Acc = %4.2f%% +- %4.2f%%' %(iter_num, acc_mean_jigsaw, 1.96* acc_std_jigsaw/np.sqrt(iter_num)))
  250. return acc_mean, acc_mean_jigsaw
  251. elif self.rotation:
  252. acc_all_rotation = np.asarray(acc_all_rotation)
  253. acc_mean_rotation = np.mean(acc_all_rotation)
  254. acc_std_rotation = np.std(acc_all_rotation)
  255. print('%d Test Rotation Acc = %4.2f%% +- %4.2f%%' %(iter_num, acc_mean_rotation, 1.96* acc_std_rotation/np.sqrt(iter_num)))
  256. return acc_mean, acc_mean_rotation
Tip!

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

Comments

Loading...