-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrecon_attacks.py
471 lines (378 loc) · 17.9 KB
/
recon_attacks.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
from abc import ABCMeta, abstractmethod
import numpy as np
import torch
from torch.autograd import Variable
from torch.nn import CrossEntropyLoss
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from typing import Optional
from train_utils import init_logfile, log
class Attacker(metaclass=ABCMeta):
@abstractmethod
def attack(self, inputs, targets):
raise NotImplementedError
# Modification of the code from https://github.com/jeromerony/fast_adversarial
class recon_PGD_L2(Attacker):
"""
PGD attack
Parameters
----------
steps : int
Number of steps for the optimization.
max_norm : float or None, optional
If specified, the norms of the perturbations will not be greater than this value which might lower success rate.
device : torch.device, optional
Device on which to perform the attack.
"""
def __init__(self,
steps: int,
random_start: bool = True,
max_norm: Optional[float] = None,
device: torch.device = torch.device('cpu')) -> None:
super(recon_PGD_L2, self).__init__()
self.steps = steps
self.random_start = random_start
self.max_norm = max_norm
self.device = device
def attack(self, model: nn.Module, inputs: torch.Tensor, target: torch.Tensor, criterion, targeted: bool = False) -> torch.Tensor:
return self._attack(model, inputs, target, criterion, targeted)
def _attack(self, model: nn.Module, img: torch.Tensor, img_original: torch.Tensor, criterion, targeted: bool = False) -> torch.Tensor:
"""
Performs the attack of the model for the inputs and labels.
Parameters
----------
model : nn.Module
Model to attack.
inputs : torch.Tensor
Batch of samples to attack. Values should be in the [0, 1] range.
labels : torch.Tensor
Labels of the samples to attack if untargeted, else labels of targets.
targeted : bool, optional
Whether to perform a targeted attack or not.
Returns
-------
torch.Tensor
Batch of samples modified to be adversarial to the model.
"""
#print("Attack Start")
logfilename = 'AdvAttack_Loss.txt'
init_logfile(logfilename, "step\tAttack_Loss")
multiplier = 1 if targeted else -1
#delta = torch.zeros_like(img, requires_grad=True)
delta = torch.FloatTensor(img.size()).uniform_(-self.max_norm, self.max_norm)
delta.data.renorm_(p=2, dim=0, maxnorm=self.max_norm)
delta = delta.cuda()
delta.requires_grad = True
#print(delta.device)
# Obtain the Shape of Inputs (Batch_size x Channel x H x W)
batch_size = img.size()[0]
img = img.cuda() # input x (batch, channel, h, w)
img_original = img_original.cuda()
# Setup optimizers
optimizer = optim.SGD([delta], lr=self.max_norm/self.steps*2)
for i in range(self.steps):
#print("Attack Step %d" % ( i ))
adv = img + delta
recon = model(adv)
loss = criterion(recon, img_original)
loss = multiplier * loss
log(logfilename,"{}\t{:.3}".format(i, loss))
optimizer.zero_grad()
loss.backward()
# renorming gradient
grad_norms = delta.grad.view(batch_size, -1).norm(p=2, dim=1)
delta.grad.div_(grad_norms.view(-1, 1, 1, 1))
# avoid nan or inf if gradient is 0
if (grad_norms == 0).any():
delta.grad[grad_norms == 0] = torch.randn_like(delta.grad[grad_norms == 0])
optimizer.step()
delta.data.add_(img)
delta.data.clamp_(0, 1).sub_(img)
delta.data.renorm_(p=2, dim=0, maxnorm=self.max_norm)
#print("Attack Finished")
return img + delta
class recon_PGD_Linf(Attacker):
"""
PGD attack
Parameters
----------
steps : int
Number of steps for the optimization.
max_norm : float or None, optional
If specified, the norms of the perturbations will not be greater than this value which might lower success rate.
device : torch.device, optional
Device on which to perform the attack.
"""
def __init__(self,
steps: int,
random_start: bool = True,
max_norm: Optional[float] = None,
device: torch.device = torch.device('cpu')) -> None:
super(recon_PGD_Linf, self).__init__()
self.steps = steps
self.random_start = random_start
self.max_norm = max_norm
self.device = device
def attack(self, model: nn.Module, inputs: torch.Tensor, target: torch.Tensor, criterion,
targeted: bool = False) -> torch.Tensor:
return self._attack(model, inputs, target, criterion, targeted)
def _attack(self, model: nn.Module, img: torch.Tensor, img_original: torch.Tensor, criterion,
targeted: bool = False) -> torch.Tensor:
"""
Performs the attack of the model for the inputs and labels.
Parameters
----------
model : nn.Module
Model to attack.
inputs : torch.Tensor
Batch of samples to attack. Values should be in the [0, 1] range.
labels : torch.Tensor
Labels of the samples to attack if untargeted, else labels of targets.
targeted : bool, optional
Whether to perform a targeted attack or not.
Returns
-------
torch.Tensor
Batch of samples modified to be adversarial to the model.
"""
multiplier = 1 if targeted else -1
delta = torch.zeros_like(img, requires_grad=True)
# Obtain the Shape of Inputs (Batch_size x Channel x H x W)
batch_size = img.size()[0]
img = img.cuda() # input x (batch, channel, h, w)
img_original = img_original.cuda()
# Setup optimizers
optimizer = optim.SGD([delta], lr=self.max_norm / self.steps * 2)
for i in range(self.steps):
adv = img + delta
recon = model(adv)
loss = criterion(recon, img_original)
loss = multiplier * loss
optimizer.zero_grad()
loss.backward()
# renorming gradient
grad_norms = delta.grad.view(batch_size, -1).norm(p=2, dim=1)
delta.grad.div_(grad_norms.view(-1, 1, 1, 1))
# avoid nan or inf if gradient is 0
if (grad_norms == 0).any():
delta.grad[grad_norms == 0] = torch.randn_like(delta.grad[grad_norms == 0])
optimizer.step()
delta.data.add_(img)
delta.data.clamp_(0, 1).sub_(img)
delta.data.renorm_(p=float('inf'), dim=0, maxnorm=self.max_norm)
return img + delta
# Source code from https://github.com/jeromerony/fast_adversarial
class DDN(Attacker):
"""
DDN attack: decoupling the direction and norm of the perturbation to achieve a small L2 norm in few steps.
Parameters
----------
steps : int
Number of steps for the optimization.
gamma : float, optional
Factor by which the norm will be modified. new_norm = norm * (1 + or - gamma).
init_norm : float, optional
Initial value for the norm.
quantize : bool, optional
If True, the returned adversarials will have quantized values to the specified number of levels.
levels : int, optional
Number of levels to use for quantization (e.g. 256 for 8 bit images).
max_norm : float or None, optional
If specified, the norms of the perturbations will not be greater than this value which might lower success rate.
device : torch.device, optional
Device on which to perform the attack.
callback : object, optional
Visdom callback to display various metrics.
"""
def __init__(self,
steps: int,
gamma: float = 0.05,
init_norm: float = 1.,
quantize: bool = True,
levels: int = 256,
max_norm: Optional[float] = None,
device: torch.device = torch.device('cpu'),
callback: Optional = None) -> None:
super(DDN, self).__init__()
self.steps = steps
self.gamma = gamma
self.init_norm = init_norm
self.quantize = quantize
self.levels = levels
self.max_norm = max_norm
self.device = device
self.callback = callback
def attack(self, model: nn.Module, inputs: torch.Tensor, labels: torch.Tensor,
noise: torch.Tensor = None, num_noise_vectors=1, targeted: bool = False, no_grad=False) -> torch.Tensor:
if num_noise_vectors == 1:
return self._attack(model, inputs, labels, noise, targeted)
# return self._attack_mutlinoise(model, inputs, labels, noise, num_noise_vectors, targeted)
else:
if no_grad:
raise NotImplementedError
else:
return self._attack_mutlinoise(model, inputs, labels, noise, num_noise_vectors, targeted)
def _attack(self, model: nn.Module, inputs: torch.Tensor, labels: torch.Tensor,
noise: torch.Tensor = None, targeted: bool = False) -> torch.Tensor:
"""
Performs the attack of the model for the inputs and labels.
Parameters
----------
model : nn.Module
Model to attack.
inputs : torch.Tensor
Batch of samples to attack. Values should be in the [0, 1] range.
labels : torch.Tensor
Labels of the samples to attack if untargeted, else labels of targets.
targeted : bool, optional
Whether to perform a targeted attack or not.
Returns
-------
torch.Tensor
Batch of samples modified to be adversarial to the model.
"""
if inputs.min() < 0 or inputs.max() > 1: raise ValueError('Input values should be in the [0, 1] range.')
batch_size = inputs.shape[0]
multiplier = 1 if targeted else -1
delta = torch.zeros_like(inputs, requires_grad=True)
norm = torch.full((batch_size,), self.init_norm, device=self.device, dtype=torch.float)
worst_norm = torch.max(inputs, 1 - inputs).view(batch_size, -1).norm(p=2, dim=1)
# Setup optimizers
optimizer = optim.SGD([delta], lr=1)
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=self.steps, eta_min=0.01)
best_l2 = worst_norm.clone()
best_delta = torch.zeros_like(inputs)
adv_found = torch.zeros(inputs.size(0), dtype=torch.uint8, device=self.device)
for i in range(self.steps):
scheduler.step()
l2 = delta.data.view(batch_size, -1).norm(p=2, dim=1)
adv = inputs + delta
if noise is not None:
adv = adv + noise
logits = model(adv)
pred_labels = logits.argmax(1)
ce_loss = F.cross_entropy(logits, labels, reduction='sum')
loss = multiplier * ce_loss
is_adv = (pred_labels == labels) if targeted else (pred_labels != labels)
is_smaller = l2 < best_l2
is_both = is_adv * is_smaller
adv_found[is_both] = 1
best_l2[is_both] = l2[is_both]
best_delta[is_both] = delta.data[is_both]
optimizer.zero_grad()
loss.backward()
# renorming gradient
grad_norms = delta.grad.view(batch_size, -1).norm(p=2, dim=1)
delta.grad.div_(grad_norms.view(-1, 1, 1, 1))
# avoid nan or inf if gradient is 0
if (grad_norms == 0).any():
delta.grad[grad_norms == 0] = torch.randn_like(delta.grad[grad_norms == 0])
if self.callback:
cosine = F.cosine_similarity(-delta.grad.view(batch_size, -1),
delta.data.view(batch_size, -1), dim=1).mean().item()
self.callback.scalar('ce', i, ce_loss.item() / batch_size)
self.callback.scalars(
['max_norm', 'l2', 'best_l2'], i,
[norm.mean().item(), l2.mean().item(),
best_l2[adv_found].mean().item() if adv_found.any() else norm.mean().item()]
)
self.callback.scalars(['cosine', 'lr', 'success'], i,
[cosine, optimizer.param_groups[0]['lr'], adv_found.float().mean().item()])
optimizer.step()
norm.mul_(1 - (2 * is_adv.float() - 1) * self.gamma)
norm = torch.min(norm, worst_norm)
delta.data.mul_((norm / delta.data.view(batch_size, -1).norm(2, 1)).view(-1, 1, 1, 1))
delta.data.add_(inputs)
if self.quantize:
delta.data.mul_(self.levels - 1).round_().div_(self.levels - 1)
delta.data.clamp_(0, 1).sub_(inputs)
if self.max_norm is not None:
best_delta.renorm_(p=2, dim=0, maxnorm=self.max_norm)
if self.quantize:
best_delta.mul_(self.levels - 1).round_().div_(self.levels - 1)
return inputs + best_delta
def _attack_mutlinoise(self, model: nn.Module, inputs: torch.Tensor, labels: torch.Tensor,
noise: torch.Tensor = None, num_noise_vectors: int = 1,targeted: bool = False) -> torch.Tensor:
"""
Performs the attack of the model for the inputs and labels.
Parameters
----------
model : nn.Module
Model to attack.
inputs : torch.Tensor
Batch of samples to attack. Values should be in the [0, 1] range.
labels : torch.Tensor
Labels of the samples to attack if untargeted, else labels of targets.
targeted : bool, optional
Whether to perform a targeted attack or not.
Returns
-------
torch.Tensor
Batch of samples modified to be adversarial to the model.
"""
if inputs.min() < 0 or inputs.max() > 1: raise ValueError('Input values should be in the [0, 1] range.')
batch_size = labels.shape[0]
multiplier = 1 if targeted else -1
delta = torch.zeros((len(labels), *inputs.shape[1:]), requires_grad=True, device=self.device)
norm = torch.full((batch_size,), self.init_norm, device=self.device, dtype=torch.float)
worst_norm = torch.max(inputs[::num_noise_vectors], 1 - inputs[::num_noise_vectors]).view(batch_size, -1).norm(p=2, dim=1)
# Setup optimizers
optimizer = optim.SGD([delta], lr=1)
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=self.steps, eta_min=0.01)
best_l2 = worst_norm.clone()
best_delta = torch.zeros_like(inputs[::num_noise_vectors])
adv_found = torch.zeros(inputs[::num_noise_vectors].size(0), dtype=torch.uint8, device=self.device)
for i in range(self.steps):
scheduler.step()
l2 = delta.data.view(batch_size, -1).norm(p=2, dim=1)
adv = inputs + delta.repeat(1,num_noise_vectors,1,1).view_as(inputs)
if noise is not None:
adv = adv + noise
logits = model(adv)
pred_labels = logits.argmax(1).reshape(-1, num_noise_vectors).mode(1)[0]
# safe softamx
softmax = F.softmax(logits, dim=1)
# average the probabilities across noise
average_softmax = softmax.reshape(-1, num_noise_vectors, logits.shape[-1]).mean(1, keepdim=True).squeeze(1)
logsoftmax = torch.log(average_softmax.clamp(min=1e-20))
ce_loss = F.nll_loss(logsoftmax, labels)
loss = multiplier * ce_loss
is_adv = (pred_labels == labels) if targeted else (pred_labels != labels)
is_smaller = l2 < best_l2
is_both = is_adv * is_smaller
adv_found[is_both] = 1
best_l2[is_both] = l2[is_both]
best_delta[is_both] = delta.data[is_both]
optimizer.zero_grad()
loss.backward()
# renorming gradient
grad_norms = delta.grad.view(batch_size, -1).norm(p=2, dim=1)
delta.grad.div_(grad_norms.view(-1, 1, 1, 1))
# avoid nan or inf if gradient is 0
if (grad_norms == 0).any():
delta.grad[grad_norms == 0] = torch.randn_like(delta.grad[grad_norms == 0])
if self.callback:
cosine = F.cosine_similarity(-delta.grad.view(batch_size, -1),
delta.data.view(batch_size, -1), dim=1).mean().item()
self.callback.scalar('ce', i, ce_loss.item() / batch_size)
self.callback.scalars(
['max_norm', 'l2', 'best_l2'], i,
[norm.mean().item(), l2.mean().item(),
best_l2[adv_found].mean().item() if adv_found.any() else norm.mean().item()]
)
self.callback.scalars(['cosine', 'lr', 'success'], i,
[cosine, optimizer.param_groups[0]['lr'], adv_found.float().mean().item()])
optimizer.step()
norm.mul_(1 - (2 * is_adv.float() - 1) * self.gamma)
norm = torch.min(norm, worst_norm)
delta.data.mul_((norm / delta.data.view(batch_size, -1).norm(2, 1)).view(-1, 1, 1, 1))
delta.data.add_(inputs[::num_noise_vectors])
if self.quantize:
delta.data.mul_(self.levels - 1).round_().div_(self.levels - 1)
delta.data.clamp_(0, 1).sub_(inputs[::num_noise_vectors])
if self.max_norm is not None:
best_delta.renorm_(p=2, dim=0, maxnorm=self.max_norm)
if self.quantize:
best_delta.mul_(self.levels - 1).round_().div_(self.levels - 1)
return inputs + best_delta.repeat(1,num_noise_vectors,1,1).view_as(inputs)