-
Notifications
You must be signed in to change notification settings - Fork 16
/
adaptors.py
489 lines (388 loc) · 13.9 KB
/
adaptors.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
from args import args
import torch
from torch import optim
import math
import numpy as np
import pathlib
from models.modules import FastHopMaskBN
from models import module_util
from utils import kth_elt
from functools import partial
def adapt_test(
model,
test_loader,
alphas=None,
):
correct = 0
model.eval()
with torch.no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
if alphas is not None:
model.apply(lambda m: setattr(m, "alphas", alphas))
data, target = data.to(args.device), target.to(args.device)
output = model(data)
pred = output.argmax(
dim=1, keepdim=True
) # get the index of the max log-probability
correct += pred.eq(target.view_as(pred)).sum().item()
test_acc = float(correct) / len(test_loader.dataset)
print(
f"\nTest set: Accuracy: ({test_acc:.4f}%)\n"
)
return test_acc
# gt means ground truth task -- corresponds to GG
def gt(
model,
writer,
test_loader,
num_tasks_learned,
task,
):
model.zero_grad()
model.train()
alphas = (
torch.zeros(
[args.num_tasks, 1, 1, 1, 1], device=args.device, requires_grad=True
)
)
alphas[task] = 1
model.apply(lambda m: setattr(m, "alphas", alphas))
model.apply(lambda m: setattr(m, "task", task))
test_acc = adapt_test(
model,
test_loader,
alphas,
)
model.apply(lambda m: setattr(m, "alphas", None))
return test_acc
# The oneshot minimization algorithm.
def se_oneshot_minimization(
adaptation_criterion,
model,
writer,
test_loader,
num_tasks_learned,
task,
):
model.zero_grad()
model.train()
# stopping time tracks how many epochs were required to adapt.
correct = 0
task_correct = 0
for batch_idx, (data_, target) in enumerate(test_loader):
data, target = data_.to(args.device), target.to(args.device)
denominator = model.num_tasks_learned if args.trainer and "nns" in args.trainer else num_tasks_learned
# alphas_i contains the "beleif" that the task is i
alphas = (
torch.ones(
[args.num_tasks, 1, 1, 1, 1], device=args.device, requires_grad=True
)
/ denominator
)
model.apply(lambda m: setattr(m, "alphas", alphas))
# Compute the output
output = model(data)
if len(output.shape) == 1:
output = output.unsqueeze(0)
# Take the gradient w.r.t objective
grad = torch.autograd.grad(adaptation_criterion(output, model), alphas)
value, ind = grad[0].min(dim=0)
alphas = torch.zeros([args.num_tasks, 1, 1, 1, 1], device=args.device)
alphas[ind] = 1
print(ind)
predicted_task = ind.item()
if predicted_task == task:
task_correct += 1
else:
if args.unshared_labels:
continue
# Now do regular testing with inferred task.
model.apply(lambda m: setattr(m, "alphas", alphas))
with torch.no_grad():
output = model(data)
if len(output.shape) == 1:
output = output.unsqueeze(0)
pred = output.argmax(
dim=1, keepdim=True
) # get the index of the max log-probability
correct += pred.eq(target.view_as(pred)).sum().item()
test_acc = float(correct) / len(test_loader.dataset)
print(
f"\nTest set: Accuracy: ({test_acc:.4f}%)\n"
)
model.apply(lambda m: setattr(m, "alphas", None))
return test_acc
# The binary minimization algorithm.
def se_binary_minimization(
adaptation_criterion,
model,
writer,
test_loader,
num_tasks_learned,
task,
):
model.zero_grad()
model.train()
correct = 0
task_correct = 0
for batch_idx, (data_, target) in enumerate(test_loader):
data, target = data_.to(args.device), target.to(args.device)
# alphas_i contains the "beleif" that the task is i
alphas = (
torch.ones(
[args.num_tasks, 1, 1, 1, 1], device=args.device, requires_grad=True
)
/ num_tasks_learned
)
# store the "good" indecies, i.e. still valid for optimization
good_inds = torch.arange(args.num_tasks) < num_tasks_learned
good_inds = good_inds.view(args.num_tasks, 1, 1, 1, 1).to(args.device)
done = False
prevent_inf_loop_iter = 0
while not done:
prevent_inf_loop_iter += 1
if prevent_inf_loop_iter > np.log2(args.num_tasks) + 1:
print('InfLoop')
break
model.zero_grad()
model.apply(lambda m: setattr(m, "alphas", alphas))
# Compute the output.
output = model(data)
# Take the gradient w.r.t objective
grad = torch.autograd.grad(adaptation_criterion(output, model), alphas)
new_alphas = torch.zeros([args.num_tasks, 1, 1, 1, 1], device=args.device)
inds = grad[0] <= kth_elt(grad[0][good_inds], args.log_base)
good_inds = inds * good_inds
new_alphas[good_inds] = 1.0 / good_inds.float().sum().item()
alphas = new_alphas.clone().detach().requires_grad_(True)
if good_inds.float().sum() == 1.0:
predicted_task = good_inds.flatten().nonzero()[0].item()
done = True
if predicted_task == task:
task_correct += 1
else:
if args.unshared_labels:
continue
model.apply(lambda m: setattr(m, "alphas", alphas))
with torch.no_grad():
output = model(data)
if len(output.shape) == 1:
output = output.unsqueeze(0)
pred = output.argmax(
dim=1, keepdim=True
) # get the index of the max log-probability
correct += pred.eq(target.view_as(pred)).sum().item()
test_acc = float(correct) / len(test_loader.dataset)
task_correct = float(task_correct) / len(test_loader.dataset)
print(
f"\nTest set: Accuracy: ({test_acc:.4f}%)\n"
)
model.apply(lambda m: setattr(m, "alphas", None))
return test_acc
# ABatchE using entropy objective.
def se_be_adapt(
model,
writer,
test_loader,
num_tasks_learned,
task,
):
model.zero_grad()
model.train()
test_loss = 0
correct = 0
data_to_repeat = args.data_to_repeat
task_correct = 0
for batch_idx, (data_, target) in enumerate(test_loader):
data, target = data_.to(args.device), target.to(args.device)
model.apply(lambda m: setattr(m, "task", -1))
if data.shape[0] >= data_to_repeat:
rep_data = torch.cat(
tuple([
data[j].unsqueeze(0).repeat(model.num_tasks_learned, 1, 1, 1)
for j in range(data_to_repeat)
]),
dim=0
)
logits = model(rep_data)
ent = -(logits.softmax(dim=1) * logits.log_softmax(dim=1)).sum(1)
ent_reshape = ent.view(data_to_repeat, num_tasks_learned)
ent_reshape_mean = ent_reshape.mean(dim=0)
v, i = ent_reshape_mean.min(dim=0)
ind = i.item()
print(ind)
predicted_task = ind
if predicted_task == task:
task_correct += 1
else:
if args.unshared_labels:
continue
model.apply(lambda m: setattr(m, "task", ind))
with torch.no_grad():
output = model(data)
if len(output.shape) == 1:
output = output.unsqueeze(0)
pred = output.argmax(
dim=1, keepdim=True
) # get the index of the max log-probability
correct += pred.eq(target.view_as(pred)).sum().item()
test_acc = float(correct) / len(test_loader.dataset)
task_correct = float(task_correct) / len(test_loader.dataset)
print(
f"\nTest set: Accuracy: ({test_acc:.4f}%)\n"
)
return test_acc
# ABatchE using M objective.
def se_be_max_adapt(
model,
writer,
test_loader,
num_tasks_learned,
task,
):
model.zero_grad()
model.train()
correct = 0
data_to_repeat = args.data_to_repeat
task_correct = 0
for batch_idx, (data_, target) in enumerate(test_loader):
data, target = data_.to(args.device), target.to(args.device)
model.apply(lambda m: setattr(m, "task", -1))
rep_data = torch.cat(
tuple([
data[j].unsqueeze(0).repeat(model.num_tasks_learned, 1, 1, 1)
for j in range(data_to_repeat)
]),
dim=0
)
logits = model(rep_data)
sm = logits.softmax(dim=1)
ent, _ = sm.max(dim=1)
ent_reshape = ent.view(data_to_repeat, num_tasks_learned)
ent_reshape_mean = ent_reshape.mean(dim=0)
v, i = ent_reshape_mean.max(dim=0)
ind = i.item()
print(ind)
predicted_task = ind
if predicted_task == task:
task_correct += 1
else:
if args.unshared_labels:
continue
model.apply(lambda m: setattr(m, "task", ind))
with torch.no_grad():
output = model(data)
if len(output.shape) == 1:
output = output.unsqueeze(0)
pred = output.argmax(
dim=1, keepdim=True
) # get the index of the max log-probability
correct += pred.eq(target.view_as(pred)).sum().item()
test_acc = float(correct) / len(test_loader.dataset)
print(
f"\nTest set: Accuracy: ({test_acc:.4f}%)\n"
)
return test_acc
def se_oneshot_entropy_minimization(*arg, **kwargs):
def f(logits, model):
logits = logits[:args.data_to_repeat]
return -(logits.softmax(dim=1) * logits.log_softmax(dim=1)).sum(1).mean()
return partial(se_oneshot_minimization, f)(*arg, **kwargs)
def se_oneshot_g_minimization(*arg, **kwargs):
def f(logits, model):
logits = logits[:args.data_to_repeat]
m = (torch.arange(logits.size(1)) < args.real_neurons).float().unsqueeze(0).to(args.device)
logits = (logits * m).detach() + logits * (1-m)
return logits.logsumexp(dim=1).mean()
return partial(se_oneshot_minimization, f)(*arg, **kwargs)
def se_binary_entropy_minimization(*arg, **kwargs):
def f(logits, model):
logits = logits[:args.data_to_repeat]
return -(logits.softmax(dim=1) * logits.log_softmax(dim=1)).sum(1).mean()
return partial(se_binary_minimization, f)(*arg, **kwargs)
def se_binary_g_minimization(*arg, **kwargs):
def f(logits, model):
logits = logits[:args.data_to_repeat]
m = (torch.arange(logits.size(1)) < args.real_neurons).float().unsqueeze(0).to(args.device)
logits = (logits * m).detach() + logits * (1 - m)
return logits.logsumexp(dim=1).mean()
return partial(se_binary_minimization, f)(*arg, **kwargs)
# HopSupSup -- Hopfield recovery.
def hopfield_recovery(
model, writer, test_loader, num_tasks_learned, task,
):
model.zero_grad()
model.train()
# stopping time tracks how many epochs were required to adapt.
stopping_time = 0
correct = 0
taskname = f"{args.set}_{task}"
params = []
for n, m in model.named_modules():
if isinstance(m, FastHopMaskBN):
out = torch.stack(
[
2 * module_util.get_subnet_fast(m.scores[j]) - 1
for j in range(m.num_tasks_learned)
]
)
m.score = torch.nn.Parameter(out.mean(dim=0))
params.append(m.score)
optimizer = optim.SGD(
params, lr=500, momentum=args.momentum, weight_decay=args.wd,
)
for batch_idx, (data_, target) in enumerate(test_loader):
data, target = data_.to(args.device), target.to(args.device)
hop_loss = None
for n, m in model.named_modules():
if isinstance(m, FastHopMaskBN):
s = 2 * module_util.GetSubnetFast.apply(m.score) - 1
target = 2 * module_util.get_subnet_fast(m.scores[task]) - 1
distance = (s != target).sum().item()
writer.add_scalar(
f"adapt_{taskname}/distance_{n}",
distance,
batch_idx + 1,
)
optimizer.zero_grad()
model.zero_grad()
output = model(data)
logit_entropy = (
-(output.softmax(dim=1) * output.log_softmax(dim=1)).sum(1).mean()
)
for n, m in model.named_modules():
if isinstance(m, FastHopMaskBN):
s = 2 * module_util.GetSubnetFast.apply(m.score) - 1
if hop_loss is None:
hop_loss = (
-0.5 * s.unsqueeze(0).mm(m.W.mm(s.unsqueeze(1))).squeeze()
)
else:
hop_loss += (
-0.5 * s.unsqueeze(0).mm(m.W.mm(s.unsqueeze(1))).squeeze()
)
hop_lr = args.gamma * (
float(batch_idx + 1) / len(test_loader)
)
hop_loss = hop_lr * hop_loss
ent_lr = 1 - (float(batch_idx + 1) / len(test_loader))
logit_entropy = logit_entropy * ent_lr
(logit_entropy + hop_loss).backward()
optimizer.step()
writer.add_scalar(
f"adapt_{taskname}/{num_tasks_learned}/entropy",
logit_entropy.item(),
batch_idx + 1,
)
writer.add_scalar(
f"adapt_{taskname}/{num_tasks_learned}/hop_loss",
hop_loss.item(),
batch_idx + 1,
)
test_acc = adapt_test(
model,
test_loader,
alphas=None,
)
model.apply(lambda m: setattr(m, "alphas", None))
return test_acc