-
Notifications
You must be signed in to change notification settings - Fork 4
/
utils02.py
362 lines (294 loc) · 11.9 KB
/
utils02.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
'''Some helper functions for PyTorch, including:
- get_mean_and_std: calculate the mean and std value of dataset.
- msr_init: net parameter initialization.
- progress_bar: progress bar mimic xlua.progress.
'''
import os
import sys
import time
import math
from TinyImageNet import TinyImageNet
import torch.nn as nn
import torch.nn.init as init
from torchvision import datasets, transforms
import torch
import torch.nn.functional as F
import torch.utils.data as data
from TinyImageNet import TinyImageNet
# cifar10_mean = (0.4914, 0.4822, 0.4465)
# cifar10_std = (0.2471, 0.2435, 0.2616)
cifar10_mean = (0.0, 0.0, 0.0)
cifar10_std = (1.0, 1.0, 1.0)
mu = torch.tensor(cifar10_mean).view(3,1,1).cuda()
std = torch.tensor(cifar10_std).view(3,1,1).cuda()
upper_limit = ((1 - mu)/ std)
lower_limit = ((0 - mu)/ std)
def clamp(X, lower_limit, upper_limit):
return torch.max(torch.min(X, upper_limit), lower_limit)
def get_loaders(dir_, batch_size):
train_transform = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
#transforms.Normalize(cifar10_mean, cifar10_std),
])
test_transform = transforms.Compose([
transforms.ToTensor(),
#transforms.Normalize(cifar10_mean, cifar10_std),
])
num_workers = 0
train_dataset = datasets.CIFAR10(
dir_, train=True, transform=train_transform, download=True)
test_dataset = datasets.CIFAR10(
dir_, train=False, transform=test_transform, download=True)
train_loader = torch.utils.data.DataLoader(
dataset=train_dataset,
batch_size=batch_size,
shuffle=True,
pin_memory=True,
num_workers=num_workers,
)
test_loader = torch.utils.data.DataLoader(
dataset=test_dataset,
batch_size=batch_size,
shuffle=False,
pin_memory=True,
num_workers=num_workers,
)
return train_loader, test_loader
def ImageNet_get_loaders(dir_, batch_size):
num_workers = {'train' : 0,'val' : 0,'test' : 0}
data_transforms = {
'train': transforms.Compose([
transforms.ToTensor(),
]),
'val': transforms.Compose([
transforms.ToTensor(),
]),
'test': transforms.Compose([
transforms.ToTensor(),
])}
num_workers = 0
image_datasets = {x: datasets.ImageFolder(os.path.join(dir_, x), data_transforms[x])
for x in ['train', 'val','test']}
dataloaders = {x: data.DataLoader(image_datasets[x], batch_size=batch_size, shuffle=True, pin_memory=True,num_workers=num_workers)
for x in ['train', 'val', 'test']}
return dataloaders
def ImageNet_get_loaders_32(dir_, batch_size):
num_workers = {'train' : 0,'val' : 0,'test' : 0}
data_transforms = {
'train': transforms.Compose([
transforms.Resize(32),
transforms.ToTensor(),
]),
'val': transforms.Compose([
transforms.Resize(32),
transforms.ToTensor(),
]),
'test': transforms.Compose([
transforms.Resize(32),
transforms.ToTensor(),
])}
num_workers = 0
image_datasets = {x: datasets.ImageFolder(os.path.join(dir_, x), data_transforms[x])
for x in ['train', 'val','test']}
dataloaders = {x: data.DataLoader(image_datasets[x], batch_size=batch_size, shuffle=True, pin_memory=True,num_workers=num_workers)
for x in ['train', 'val', 'test']}
return dataloaders
def New_ImageNet_get_loaders_32(dir_, batch_size):
transform_train = transforms.Compose([
transforms.Lambda(lambda x: x.convert("RGB")),
transforms.Resize(32),
transforms.ToTensor(),
])
transform_test = transforms.Compose([
transforms.Lambda(lambda x: x.convert("RGB")),
transforms.Resize(32),
transforms.ToTensor(),
])
trainset = TinyImageNet(dir_, 'train', transform=transform_train, in_memory=True)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=8)
testset = TinyImageNet(dir_, 'val', transform=transform_test, in_memory=True)
testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=8)
return trainloader, testloader
def New_ImageNet_get_loaders_32_testloader(dir_, batch_size):
transform_test = transforms.Compose([
transforms.Lambda(lambda x: x.convert("RGB")),
transforms.Resize(32),
transforms.ToTensor(),
])
testset = TinyImageNet(dir_, 'val', transform=transform_test, in_memory=True)
testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=8)
return testloader
def New_ImageNet_get_loaders_64(dir_, batch_size):
transform_train = transforms.Compose([
transforms.Lambda(lambda x: x.convert("RGB")),
transforms.ToTensor(),
])
transform_test = transforms.Compose([
transforms.Lambda(lambda x: x.convert("RGB")),
transforms.ToTensor(),
])
trainset = TinyImageNet(dir_, 'train', transform=transform_train, in_memory=True)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=8)
testset = TinyImageNet(dir_, 'val', transform=transform_test, in_memory=True)
testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=8)
return trainloader, testloader
def New_ImageNet_get_loaders_64_testloader(dir_, batch_size):
transform_test = transforms.Compose([
transforms.Lambda(lambda x: x.convert("RGB")),
transforms.ToTensor(),
])
testset = TinyImageNet(dir_, 'val', transform=transform_test, in_memory=True)
testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=8)
return testloader
def get_loaders_cifar100(dir_, batch_size):
train_transform = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
#transforms.Normalize(cifar10_mean, cifar10_std),
])
test_transform = transforms.Compose([
transforms.ToTensor(),
#transforms.Normalize(cifar10_mean, cifar10_std),
])
num_workers = 0
train_dataset = datasets.CIFAR100(
dir_, train=True, transform=train_transform, download=True)
test_dataset = datasets.CIFAR100(
dir_, train=False, transform=test_transform, download=True)
train_loader = torch.utils.data.DataLoader(
dataset=train_dataset,
batch_size=batch_size,
shuffle=True,
pin_memory=True,
num_workers=num_workers,
)
test_loader = torch.utils.data.DataLoader(
dataset=test_dataset,
batch_size=batch_size,
shuffle=False,
pin_memory=True,
num_workers=num_workers,
)
return train_loader, test_loader
def attack_pgd(model, X, y, epsilon, alpha, attack_iters, restarts):
max_loss = torch.zeros(y.shape[0]).cuda()
max_delta = torch.zeros_like(X).cuda()
for zz in range(restarts):
delta = torch.zeros_like(X).cuda()
for i in range(len(epsilon)):
delta[:, i, :, :].uniform_(-epsilon[i][0][0].item(), epsilon[i][0][0].item())
delta.data = clamp(delta, lower_limit - X, upper_limit - X)
delta.requires_grad = True
for _ in range(attack_iters):
output = model(X + delta)
index = torch.where(output.max(1)[1] == y)
if len(index[0]) == 0:
break
loss = F.cross_entropy(output, y)
loss.backward()
grad = delta.grad.detach()
d = delta[index[0], :, :, :]
g = grad[index[0], :, :, :]
d = clamp(d + alpha * torch.sign(g), -epsilon, epsilon)
d = clamp(d, lower_limit - X[index[0], :, :, :], upper_limit - X[index[0], :, :, :])
delta.data[index[0], :, :, :] = d
delta.grad.zero_()
all_loss = F.cross_entropy(model(X+delta), y, reduction='none').detach()
max_delta[all_loss >= max_loss] = delta.detach()[all_loss >= max_loss]
max_loss = torch.max(max_loss, all_loss)
return max_delta
def evaluate_pgd(test_loader, model, attack_iters, restarts,epsilon= (8 / 255.) / std):
print(epsilon)
alpha = (2 / 255.) / std
pgd_loss = 0
pgd_acc = 0
n = 0
model.eval()
for i, (X, y) in enumerate(test_loader):
X, y = X.cuda(), y.cuda()
pgd_delta = attack_pgd(model, X, y, epsilon, alpha, attack_iters, restarts)
with torch.no_grad():
output = model(X + pgd_delta)
loss = F.cross_entropy(output, y)
pgd_loss += loss.item() * y.size(0)
pgd_acc += (output.max(1)[1] == y).sum().item()
n += y.size(0)
return pgd_loss/n, pgd_acc/n
def evaluate_standard(test_loader, model):
test_loss = 0
test_acc = 0
n = 0
model.eval()
with torch.no_grad():
for i, (X, y) in enumerate(test_loader):
X, y = X.cuda(), y.cuda()
output = model(X)
loss = F.cross_entropy(output, y)
test_loss += loss.item() * y.size(0)
test_acc += (output.max(1)[1] == y).sum().item()
n += y.size(0)
return test_loss/n, test_acc/n
def CW_loss(x, y):
x_sorted, ind_sorted = x.sort(dim=1)
ind = (ind_sorted[:, -1] == y).float()
loss_value = -(x[np.arange(x.shape[0]), y] - x_sorted[:, -2] * ind - x_sorted[:, -1] * (1. - ind))
return loss_value.mean()
def cw_Linf_attack(model, X, y, epsilon, alpha, attack_iters, restarts):
max_loss = torch.zeros(y.shape[0]).cuda()
max_delta = torch.zeros_like(X).cuda()
# y_true=np.eye(10)[y.cuda().data.cpu().numpy()]
# y_true=torch.from_numpy(y_true).cuda()
for zz in range(restarts):
delta = torch.zeros_like(X).cuda()
for i in range(len(epsilon)):
delta[:, i, :, :].uniform_(-epsilon[i][0][0].item(), epsilon[i][0][0].item())
delta.data = clamp(delta, lower_limit - X, upper_limit - X)
delta.requires_grad = True
for _ in range(attack_iters):
output = model(X + delta)
index = torch.where(output.max(1)[1] == y)
if len(index[0]) == 0:
break
loss = CW_loss(output, y)
loss.backward()
grad = delta.grad.detach()
d = delta[index[0], :, :, :]
g = grad[index[0], :, :, :]
d = clamp(d + alpha * torch.sign(g), -epsilon, epsilon)
d = clamp(d, lower_limit - X[index[0], :, :, :], upper_limit - X[index[0], :, :, :])
delta.data[index[0], :, :, :] = d
delta.grad.zero_()
all_loss = F.cross_entropy(model(X + delta), y, reduction='none').detach()
max_delta[all_loss >= max_loss] = delta.detach()[all_loss >= max_loss]
max_loss = torch.max(max_loss, all_loss)
return max_delta
def evaluate_pgd_cw(test_loader, model, attack_iters, restarts):
alpha = (2 / 255.) / std
epsilon = (8 / 255.) / std
pgd_loss = 0
pgd_acc = 0
n = 0
model.eval()
for i, (X, y) in enumerate(test_loader):
X, y = X.cuda(), y.cuda()
pgd_delta = cw_Linf_attack(model, X, y, epsilon, alpha, attack_iters=attack_iters, restarts=restarts)
with torch.no_grad():
output = model(X + pgd_delta)
loss = F.cross_entropy(output, y)
pgd_loss += loss.item() * y.size(0)
pgd_acc += (output.max(1)[1] == y).sum().item()
n += y.size(0)
return pgd_loss/n, pgd_acc/n
import numpy as np
from torch.autograd import Variable
def get_variable(inputs, cuda=False, **kwargs):
if type(inputs) in [list, np.ndarray]:
inputs = torch.Tensor(inputs)
if cuda:
out = Variable(inputs.cuda(), **kwargs)
else:
out = Variable(inputs, **kwargs)
return out