-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
443 lines (361 loc) · 13.8 KB
/
utils.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
"""
setup model and datasets
"""
import copy
import os
import random
# from advertorch.utils import NormalizeByChannelMeanStd
import shutil
import sys
import time
import numpy as np
import torch
from dataset import *
from dataset import TinyImageNet
from models import *
from torchvision import transforms
import torch.optim as optim
from torch.autograd import grad
from torch.autograd.functional import jacobian
import matplotlib.pyplot as plt
__all__ = [
"setup_model_dataset",
"AverageMeter",
"warmup_lr",
"save_checkpoint",
"setup_seed",
"accuracy",
]
def warmup_lr(epoch, step, optimizer, one_epoch_step, args):
overall_steps = args.warmup * one_epoch_step
current_steps = epoch * one_epoch_step + step
lr = args.lr * current_steps / overall_steps
lr = min(lr, args.lr)
for p in optimizer.param_groups:
p["lr"] = lr
def save_checkpoint(
state, is_SA_best, save_path, pruning, filename="checkpoint.pth.tar"
):
filepath = os.path.join(save_path, str(pruning) + filename)
torch.save(state, filepath)
if is_SA_best:
shutil.copyfile(
filepath, os.path.join(save_path, str(pruning) + "model_SA_best.pth.tar")
)
def load_checkpoint(device, save_path, pruning, filename="checkpoint.pth.tar"):
filepath = os.path.join(save_path, str(pruning) + filename)
if os.path.exists(filepath):
print("Load checkpoint from:{}".format(filepath))
return torch.load(filepath, device)
print("Checkpoint not found! path:{}".format(filepath))
return None
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def dataset_convert_to_train(dataset):
train_transform = transforms.Compose(
[
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
]
)
while hasattr(dataset, "dataset"):
dataset = dataset.dataset
dataset.transform = train_transform
dataset.train = False
def dataset_convert_to_test(dataset, args=None):
if args.dataset == "TinyImagenet":
test_transform = transforms.Compose([])
elif args.dataset == "trans_cifar10":
test_transform = transforms.Compose(
[
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor()
]
)
elif args.dataset == "celeba":
test_transform = transforms.Compose(
# [
# transforms.Resize(256),
# transforms.CenterCrop(224),
# transforms.ToTensor(),
# ]
[
transforms.CenterCrop((178, 178)),
transforms.Resize((128, 128)),
transforms.ToTensor(),
]
)
else:
test_transform = transforms.Compose(
[
transforms.ToTensor(),
]
)
while hasattr(dataset, "dataset"):
dataset = dataset.dataset
dataset.transform = test_transform
dataset.train = False
def setup_model_dataset(args):
if args.dataset == "cifar10":
classes = 10
normalization = NormalizeByChannelMeanStd(
mean=[0.4914, 0.4822, 0.4465], std=[0.2470, 0.2435, 0.2616]
)
train_set, valid_set, test_set = cifar10_datasets(data_dir=args.data)
print("dataset length: ", len(train_set), len(valid_set), len(test_set))
elif args.dataset == "cifar100":
classes = 100
normalization = NormalizeByChannelMeanStd(
mean=[0.5071, 0.4866, 0.4409], std=[0.2673, 0.2564, 0.2762]
)
train_set, valid_set, test_set = cifar100_datasets(data_dir=args.data)
elif args.dataset == "celeba":
classes = 2
# https://github.com/ssagawa/overparam_spur_corr/blob/09df90db3bae9a9686e509152c20a88e22670bba/data/celebA_dataset.py#L94
normalization = NormalizeByChannelMeanStd(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
)
train_set, valid_set, test_set = celeba_datasets(data_dir=args.data)
elif args.dataset == "TinyImagenet":
classes = 200
normalization = NormalizeByChannelMeanStd(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
)
train_set, valid_set, test_set = TinyImageNet(args).datasets(
seed=args.seed
)
if args.imagenet_arch or args.dataset == 'celeba':
model = model_dict[args.arch](num_classes=classes, imagenet=True)
elif args.arch == 'swin_t':
model = swin_t(window_size=4,num_classes=10,downscaling_factors=(2,2,2,1))
else:
model = model_dict[args.arch](num_classes=classes)
model.normalize = normalization
print(model)
return model, train_set, valid_set, test_set
def setup_model_indexdataset(args):
if args.dataset == "cifar10":
classes = 10
normalization = NormalizeByChannelMeanStd(
mean=[0.4914, 0.4822, 0.4465], std=[0.2470, 0.2435, 0.2616]
)
train_set, valid_set, test_set = cifar10_index_datasets(data_dir=args.data)
print("dataset length: ", len(train_set), len(valid_set), len(test_set))
elif args.dataset == "cifar100":
classes = 100
normalization = NormalizeByChannelMeanStd(
mean=[0.5071, 0.4866, 0.4409], std=[0.2673, 0.2564, 0.2762]
)
train_set, valid_set, test_set = cifar100_index_datasets(data_dir=args.data)
elif args.dataset == "TinyImagenet":
classes = 200
normalization = NormalizeByChannelMeanStd(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
)
train_set, valid_set, test_set = TinyImageNet(args).index_datasets(
seed=args.seed
)
elif args.dataset == 'celeba':
classes = 2
normalization = NormalizeByChannelMeanStd(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
train_set, valid_set, test_set = celeba_index_datasets(data_dir=args.data)
if args.imagenet_arch or args.dataset == 'celeba':
model = model_dict[args.arch](num_classes=classes, imagenet=True)
elif args.arch == 'swin_t':
model = swin_t(window_size=4,num_classes=10,downscaling_factors=(2,2,2,1))
else:
model = model_dict[args.arch](num_classes=classes)
model.normalize = normalization
print(model)
return model, train_set, valid_set, test_set
def setup_seed(seed):
# print("setup random seed = {}".format(seed))
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
class NormalizeByChannelMeanStd(torch.nn.Module):
def __init__(self, mean, std):
super(NormalizeByChannelMeanStd, self).__init__()
if not isinstance(mean, torch.Tensor):
mean = torch.tensor(mean)
if not isinstance(std, torch.Tensor):
std = torch.tensor(std)
self.register_buffer("mean", mean)
self.register_buffer("std", std)
def forward(self, tensor):
return self.normalize_fn(tensor, self.mean, self.std)
def extra_repr(self):
return "mean={}, std={}".format(self.mean, self.std)
def normalize_fn(self, tensor, mean, std):
"""Differentiable version of torchvision.functional.normalize"""
# here we assume the color channel is in at dim=1
mean = mean[None, :, None, None]
std = std[None, :, None, None]
return tensor.sub(mean).div(std)
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0)
res.append(correct_k.mul_(100.0 / batch_size))
return res
def update_w(
origin_train_set,
w=None,
class_to_replace: int = None,
num_indexes_to_replace: int = None,
seed: int = 1,
batch_size:int = 128,
shuffle: bool = False,
only_mark: bool = True,
args=None
):
def replace_loader_dataset(
dataset, batch_size=batch_size, seed=seed, shuffle=True
):
setup_seed(seed)
return torch.utils.data.DataLoader(
dataset,
batch_size=batch_size,
num_workers=0,
pin_memory=True,
shuffle=shuffle,
)
train_full_loader = replace_loader_dataset(
origin_train_set, batch_size=batch_size, seed=seed, shuffle=shuffle
)
train_set = copy.deepcopy(origin_train_set)
if w is None:
if class_to_replace is not None:
indexes = replace_class(
train_set,
class_to_replace,
num_indexes_to_replace=num_indexes_to_replace,
seed=seed - 1,
only_mark=only_mark,
)
# binary
w = torch.zeros(len(train_set))
w[indexes] = 1
# uniform
# w = torch.ones(len(train_set)) / len(train_set)
else:
indexes = torch.where(w == 1)[0].tolist()
replace_indexes(train_set, indexes, seed, only_mark)
if args.dataset == "cifar10" or args.dataset == "cifar100" or args.dataset == "trans_cifar10":
forget_dataset = copy.deepcopy(train_set)
marked = forget_dataset.targets < 0
forget_dataset.data = forget_dataset.data[marked]
forget_dataset.targets = -forget_dataset.targets[marked] - 1
forget_loader = replace_loader_dataset(
forget_dataset, batch_size=batch_size, seed=seed, shuffle=shuffle
)
retain_dataset = copy.deepcopy(train_set)
marked = retain_dataset.targets >= 0
retain_dataset.data = retain_dataset.data[marked]
retain_dataset.targets = retain_dataset.targets[marked]
retain_loader = replace_loader_dataset(
retain_dataset, batch_size=batch_size, seed=seed, shuffle=shuffle
)
elif args.dataset == "TinyImagenet":
forget_dataset = copy.deepcopy(train_set)
marked = forget_dataset.targets < 0
forget_dataset.imgs = forget_dataset.imgs[marked]
forget_dataset.targets = -forget_dataset.targets[marked] - 1
forget_loader = replace_loader_dataset(
forget_dataset, batch_size=batch_size, seed=seed, shuffle=shuffle
)
retain_dataset = copy.deepcopy(train_set)
marked = retain_dataset.targets >= 0
retain_dataset.imgs = retain_dataset.imgs[marked]
retain_dataset.targets = retain_dataset.targets[marked]
retain_loader = replace_loader_dataset(
retain_dataset, batch_size=batch_size, seed=seed, shuffle=shuffle
)
elif args.dataset == "celeba":
forget_dataset = copy.deepcopy(train_set)
marked = forget_dataset.labels < 0
forget_dataset.filenames = np.array(forget_dataset.filenames)[marked].tolist()
forget_dataset.labels = -forget_dataset.labels[marked] - 1
forget_loader = replace_loader_dataset(
forget_dataset, batch_size=batch_size, seed=seed, shuffle=shuffle
)
retain_dataset = copy.deepcopy(train_set)
marked = retain_dataset.labels >= 0
retain_dataset.filenames = np.array(retain_dataset.filenames)[marked].tolist()
retain_dataset.labels = retain_dataset.labels[marked]
retain_loader = replace_loader_dataset(
retain_dataset, batch_size=batch_size, seed=seed, shuffle=shuffle
)
return train_full_loader, forget_loader, retain_loader, w,
class SignSGD(optim.SGD):
def __init__(self, params, lr, momentum, weight_decay):
super().__init__(params, lr, momentum, weight_decay)
def sign_step(self):
"""Performs a single optimization step using the sign of gradients."""
for group in self.param_groups:
for p in group['params']:
if p.grad is None:
continue
d_p = p.grad.sign()
p.data.add_(d_p, alpha=-group['lr'])
def weights_init(m):
if isinstance(m, torch.nn.Linear) or isinstance(m, torch.nn.Conv2d):
torch.nn.init.xavier_uniform_(m.weight.data)
if m.bias is not None:
torch.nn.init.zeros_(m.bias.data)
# torch
def bisection(a, eps, xi=1e-5, ub=1, max_iter=1e2):
mu_l = torch.min(a - 1)
mu_u = torch.max(a)
iter_count = 0
mu_a = (mu_u + mu_l) / 2
while torch.abs(mu_u - mu_l) > xi:
# print(torch.abs(mu_u - mu_l))
mu_a = (mu_u + mu_l) / 2
gu = torch.sum(torch.clamp(a - mu_a, 0, ub)) - eps
gu_l = torch.sum(torch.clamp(a - mu_l, 0, ub)) - eps
if gu == 0 or iter_count >= max_iter:
break
if torch.sign(gu) == torch.sign(gu_l):
mu_l = mu_a
else:
mu_u = mu_a
iter_count += 1
upper_S_update = torch.clamp(a - mu_a, 0, ub)
return upper_S_update
def compute_gradients(images, targets, model, optimizer, criterion, sign):
gradients = []
for image, target in zip(images, targets):
optimizer.zero_grad()
output = model(image.unsqueeze(0)) # Unsqueeze to add a batch dimension
loss = criterion(output, target.unsqueeze(0)) # Unsqueeze to add a batch dimension
grad_loss = grad(loss, model.parameters())
gradients.append([g.detach().cpu().numpy() for g in grad_loss])
if sign:
optimizer.sign_step()
else:
optimizer.step()
return gradients