-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlwf.py
executable file
·95 lines (77 loc) · 3.92 KB
/
lwf.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
# Copyright 2022-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
from datasets import get_dataset
from torch.optim import SGD
from models.utils.continual_model import ContinualModel
from utils.args import add_management_args, add_experiment_args, add_rehearsal_args, ArgumentParser
def get_parser() -> ArgumentParser:
parser = ArgumentParser(description='Continual learning via'
' Learning without Forgetting.')
add_management_args(parser)
add_experiment_args(parser)
parser.add_argument('--alpha', type=float, default=0.5,
help='Penalty weight.')
parser.add_argument('--softmax_temp', type=float, default=2,
help='Temperature of the softmax function.')
return parser
def smooth(logits, temp, dim):
log = logits ** (1 / temp)
return log / torch.sum(log, dim).unsqueeze(1)
def modified_kl_div(old, new):
return -torch.mean(torch.sum(old * torch.log(new), 1))
class Lwf(ContinualModel):
NAME = 'lwf'
COMPATIBILITY = ['class-il', 'task-il']
def __init__(self, backbone, loss, args, transform):
super(Lwf, self).__init__(backbone, loss, args, transform)
self.old_net = None
self.soft = torch.nn.Softmax(dim=1)
self.logsoft = torch.nn.LogSoftmax(dim=1)
self.dataset = get_dataset(args)
self.current_task = 0
self.cpt = get_dataset(args).N_CLASSES_PER_TASK
nc = get_dataset(args).N_TASKS * self.cpt
self.eye = torch.tril(torch.ones((nc, nc))).bool().to(self.device)
def begin_task(self, dataset):
self.net.eval()
if self.current_task > 0:
# warm-up
opt = SGD(self.net.classifier.parameters(), lr=self.args.lr)
for epoch in range(self.args.n_epochs):
for i, data in enumerate(dataset.train_loader):
inputs, labels, not_aug_inputs = data
inputs, labels = inputs.to(self.device), labels.to(self.device)
opt.zero_grad()
with torch.no_grad():
feats = self.net(inputs, returnt='features')
mask = self.eye[(self.current_task + 1) * self.cpt - 1] ^ self.eye[self.current_task * self.cpt - 1]
outputs = self.net.classifier(feats)[:, mask]
loss = self.loss(outputs, labels - self.current_task * self.cpt)
loss.backward()
opt.step()
logits = []
with torch.no_grad():
for i in range(0, dataset.train_loader.dataset.data.shape[0], self.args.batch_size):
inputs = torch.stack([dataset.train_loader.dataset.__getitem__(j)[2]
for j in range(i, min(i + self.args.batch_size,
len(dataset.train_loader.dataset)))])
log = self.net(inputs.to(self.device)).cpu()
logits.append(log)
setattr(dataset.train_loader.dataset, 'logits', torch.cat(logits))
self.net.train()
self.current_task += 1
def observe(self, inputs, labels, not_aug_inputs, logits=None):
self.opt.zero_grad()
outputs = self.net(inputs)
mask = self.eye[self.current_task * self.cpt - 1]
loss = self.loss(outputs[:, mask], labels)
if logits is not None:
mask = self.eye[(self.current_task - 1) * self.cpt - 1]
loss += self.args.alpha * modified_kl_div(smooth(self.soft(logits[:, mask]).to(self.device), 2, 1),
smooth(self.soft(outputs[:, mask]), 2, 1))
loss.backward()
self.opt.step()
return loss.item()