-
Notifications
You must be signed in to change notification settings - Fork 0
/
rehearsal.py
280 lines (220 loc) · 8.85 KB
/
rehearsal.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
import copy
import numpy as np
import torch
class Memory:
def __init__(self, memory_size, nb_total_classes, rehearsal, fixed=True, modes=1):
self.memory_size = memory_size
self.nb_total_classes = nb_total_classes
self.rehearsal = rehearsal
self.fixed = fixed
self.modes = modes
self.x = self.y = self.t = None
self.nb_classes = 0
@property
def memory_per_class(self):
if self.fixed:
return self.memory_size // self.nb_total_classes
return self.memory_size // self.nb_classes if self.nb_classes > 0 else self.memory_size
def get_dataset(self, base_dataset):
dataset = copy.deepcopy(base_dataset)
dataset._x = self.x
dataset._y = self.y
dataset._t = self.t
return dataset
def get(self):
return self.x, self.y, self.t
def __len__(self):
return len(self.x) if self.x is not None else 0
def save(self, path):
np.savez(
path,
x=self.x, y=self.y, t=self.t
)
def load(self, path):
data = np.load(path)
self.x = data["x"]
self.y = data["y"]
self.t = data["t"]
assert len(self) <= self.memory_size, len(self)
self.nb_classes = len(np.unique(self.y))
def reduce(self):
x, y, t = [], [], []
for class_id in np.unique(self.y):
indexes = np.where(self.y == class_id)[0]
if self.modes > 1:
selected_indexes = np.concatenate([
indexes[:len(indexes)//2][:self.memory_per_class//2],
indexes[len(indexes)//2:][:self.memory_per_class//2],
])
else:
selected_indexes = indexes[:self.memory_per_class]
x.append(self.x[selected_indexes])
y.append(self.y[selected_indexes])
t.append(self.t[selected_indexes])
self.x = np.concatenate(x)
self.y = np.concatenate(y)
self.t = np.concatenate(t)
def add(self, dataset, model, nb_new_classes):
self.nb_classes += nb_new_classes
if self.modes > 1: # todo modes more than 2
assert self.modes == 2
x1, y1, t1 = herd_samples(dataset, model, self.memory_per_class//2, self.rehearsal)
x2, y2, t2 = herd_samples(dataset, model, self.memory_per_class//2, self.rehearsal)
x = np.concatenate((x1, x2))
y = np.concatenate((y1, y2))
t = np.concatenate((t1, t2))
else:
x, y, t = herd_samples(dataset, model, self.memory_per_class, self.rehearsal)
#assert len(y) == self.memory_per_class * nb_new_classes, (len(y), self.memory_per_class, nb_new_classes)
if self.x is None:
self.x, self.y, self.t = x, y, t
else:
if not self.fixed:
self.reduce()
self.x = np.concatenate((self.x, x))
self.y = np.concatenate((self.y, y))
self.t = np.concatenate((self.t, t))
def herd_samples(dataset, model, memory_per_class, rehearsal):
x, y, t = dataset._x, dataset._y, dataset._t
if rehearsal == "random":
indexes = []
for class_id in np.unique(y):
class_indexes = np.where(y == class_id)[0]
indexes.append(
np.random.choice(class_indexes, size=memory_per_class)
)
indexes = np.concatenate(indexes)
return x[indexes], y[indexes], t[indexes]
elif "closest" in rehearsal:
if rehearsal == 'closest_token':
handling = 'last'
else:
handling = 'all'
features, targets = extract_features(dataset, model, handling)
indexes = []
for class_id in np.unique(y):
class_indexes = np.where(y == class_id)[0]
class_features = features[class_indexes]
class_mean = np.mean(class_features, axis=0, keepdims=True)
distances = np.power(class_features - class_mean, 2).sum(-1)
class_closest_indexes = np.argsort(distances)
indexes.append(
class_indexes[class_closest_indexes[:memory_per_class]]
)
indexes = np.concatenate(indexes)
return x[indexes], y[indexes], t[indexes]
elif "furthest" in rehearsal:
if rehearsal == 'furthest_token':
handling = 'last'
else:
handling = 'all'
features, targets = extract_features(dataset, model, handling)
indexes = []
for class_id in np.unique(y):
class_indexes = np.where(y == class_id)[0]
class_features = features[class_indexes]
class_mean = np.mean(class_features, axis=0, keepdims=True)
distances = np.power(class_features - class_mean, 2).sum(-1)
class_furthest_indexes = np.argsort(distances)[::-1]
indexes.append(
class_indexes[class_furthest_indexes[:memory_per_class]]
)
indexes = np.concatenate(indexes)
return x[indexes], y[indexes], t[indexes]
elif "icarl":
if rehearsal == 'icarl_token':
handling = 'last'
else:
handling = 'all'
features, targets = extract_features(dataset, model, handling)
indexes = []
for class_id in np.unique(y):
class_indexes = np.where(y == class_id)[0]
class_features = features[class_indexes]
indexes.append(
class_indexes[icarl_selection(class_features, memory_per_class)]
)
indexes = np.concatenate(indexes)
return x[indexes], y[indexes], t[indexes]
else:
raise ValueError(f"Unknown rehearsal method {rehearsal}!")
def extract_features(dataset, model, ensemble_handling='last'):
#transform = copy.deepcopy(dataset.trsf.transforms)
#dataset.trsf = transforms.Compose(transform[-2:])
loader = torch.utils.data.DataLoader(
dataset,
batch_size=128,
num_workers=2,
pin_memory=True,
drop_last=False,
shuffle=False
)
features, targets = [], []
with torch.no_grad():
for x, y, _ in loader:
if hasattr(model, 'module'):
feats= model.module.forward_features(x.cuda())
else:
feats= model.forward_features(x.cuda())
if isinstance(feats, list):
if ensemble_handling == 'last':
feats = feats[-1]
elif ensemble_handling == 'all':
feats = torch.cat(feats, dim=1)
else:
raise NotImplementedError(f'Unknown handdling of multiple features {ensemble_handling}')
elif len(feats.shape) == 3: # joint tokens
if ensemble_handling == 'last':
feats = feats[-1]
elif ensemble_handling == 'all':
feats = feats.permute(1, 0, 2).view(len(x), -1)
else:
raise NotImplementedError(f'Unknown handdling of multiple features {ensemble_handling}')
feats = feats.cpu().numpy()
y = y.numpy()
features.append(feats)
targets.append(y)
features = np.concatenate(features)
targets = np.concatenate(targets)
#dataset.trsf = transforms.Compose(transform)
return features, targets
def icarl_selection(features, nb_examplars):
D = features.T
D = D / (np.linalg.norm(D, axis=0) + 1e-8)
mu = np.mean(D, axis=1)
herding_matrix = np.zeros((features.shape[0],))
w_t = mu
iter_herding, iter_herding_eff = 0, 0
while not (
np.sum(herding_matrix != 0) == min(nb_examplars, features.shape[0])
) and iter_herding_eff < 1000:
tmp_t = np.dot(w_t, D)
ind_max = np.argmax(tmp_t)
iter_herding_eff += 1
if herding_matrix[ind_max] == 0:
herding_matrix[ind_max] = 1 + iter_herding
iter_herding += 1
w_t = w_t + mu - D[:, ind_max]
herding_matrix[np.where(herding_matrix == 0)[0]] = 10000
return herding_matrix.argsort()[:nb_examplars]
def get_finetuning_dataset(dataset, memory, finetuning='balanced', oversample_old=1, task_id=0):
if finetuning == 'balanced':
x, y, t = memory.get()
if oversample_old > 1:
old_indexes = np.where(t < task_id)[0]
assert len(old_indexes) > 0
new_indexes = np.where(t >= task_id)[0]
indexes = np.concatenate([
np.repeat(old_indexes, oversample_old),
new_indexes
])
x, y, t = x[indexes], y[indexes], t[indexes]
new_dataset = copy.deepcopy(dataset)
new_dataset._x = x
new_dataset._y = y
new_dataset._t = t
elif finetuning in ('all', 'none'):
new_dataset = dataset
else:
raise NotImplementedError(f'Unknown finetuning method {finetuning}')
return new_dataset