-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiterative.py
864 lines (746 loc) · 32.2 KB
/
iterative.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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
from __future__ import division
import numpy as np
from abc import abstractmethod
import logging
import warnings
from foolbox2 import models
from foolbox2.utils import crossentropy
from foolbox2.attacks.base import Attack, call_decorator
# from foolbox.models.base import Attack, call_decorator
from foolbox2 import distances
from foolbox2.utils import crossentropy
def find_salience(model_path, im):
pass
class IterativeProjectedGradientBaseAttack(Attack):
"""Base class for iterative (projected) gradient attacks.
Concrete subclasses should implement __call__, _gradient
and _clip_perturbation.
TODO: add support for other loss-functions, e.g. the CW loss function,
see https://github.com/MadryLab/mnist_challenge/blob/master/pgd_attack.py
"""
@abstractmethod
def _gradient(self, a, x, class_, strict=True):
raise NotImplementedError
@abstractmethod
def _clip_perturbation(self, a, noise, epsilon):
raise NotImplementedError
@abstractmethod
def _check_distance(self, a):
raise NotImplementedError
def _get_mode_and_class(self, a):
# determine if the attack is targeted or not
target_class = a.target_class()
targeted = target_class is not None
if targeted:
class_ = target_class
else:
class_ = a.original_class
return targeted, class_
def _run(self, a, binary_search,
epsilon, stepsize, iterations,
random_start, return_early):
if not a.has_gradient():
warnings.warn('applied gradient-based attack to model that'
' does not provide gradients')
return
self._check_distance(a)
targeted, class_ = self._get_mode_and_class(a)
if binary_search:
if isinstance(binary_search, bool):
k = 20
else:
k = int(binary_search)
return self._run_binary_search(
a, epsilon, stepsize, iterations,
random_start, targeted, class_, return_early, k=k)
else:
return self._run_one(
a, epsilon, stepsize, iterations,
random_start, targeted, class_, return_early)
def _run_binary_search(self, a, epsilon, stepsize, iterations,
random_start, targeted, class_, return_early, k):
factor = stepsize / epsilon
def try_epsilon(epsilon):
stepsize = factor * epsilon
return self._run_one(
a, epsilon, stepsize, iterations,
random_start, targeted, class_, return_early)
for i in range(k):
if try_epsilon(epsilon):
logging.info('successful for eps = {}'.format(epsilon))
break
logging.info('not successful for eps = {}'.format(epsilon))
epsilon = epsilon * 1.5
else:
logging.warning('exponential search failed')
return
bad = 0
good = epsilon
for i in range(k):
epsilon = (good + bad) / 2
if try_epsilon(epsilon):
good = epsilon
logging.info('successful for eps = {}'.format(epsilon))
else:
bad = epsilon
logging.info('not successful for eps = {}'.format(epsilon))
def _run_one(self, a, epsilon, stepsize, iterations,
random_start, targeted, class_, return_early):
min_, max_ = a.bounds()
s = max_ - min_
original = a.original_image.copy()
if random_start:
# using uniform noise even if the perturbation clipping uses
# a different norm because cleverhans does it the same way
noise = np.random.uniform(
-epsilon * s, epsilon * s, original.shape).astype(
original.dtype)
x = original + self._clip_perturbation(a, noise, epsilon)
strict = False # because we don't enforce the bounds here
else:
x = original
strict = True
success = False
for _ in range(iterations):
gradient = self._gradient(a, x, class_, strict=strict)
# non-strict only for the first call and
# only if random_start is True
strict = True
if targeted:
gradient = -gradient
# untargeted: gradient ascent on cross-entropy to original class
# targeted: gradient descent on cross-entropy to target class
x = x + stepsize * gradient
x = original + self._clip_perturbation(a, x - original, epsilon)
x = np.clip(x, min_, max_)
logits, is_adversarial = a.predictions(x)
if logging.getLogger().isEnabledFor(logging.DEBUG):
if targeted:
ce = crossentropy(a.original_class, logits)
logging.debug('crossentropy to {} is {}'.format(
a.original_class, ce))
ce = crossentropy(class_, logits)
logging.debug('crossentropy to {} is {}'.format(class_, ce))
if is_adversarial:
if return_early:
return True
else:
success = True
return success
class LinfinityGradientMixin(object):
def _gradient(self, a, x, class_, strict=True):
gradient = a.gradient(x, class_, strict=strict)
gradient = np.sign(gradient)
min_, max_ = a.bounds()
gradient = (max_ - min_) * gradient
return gradient
class L1GradientMixin(object):
def _gradient(self, a, x, class_, strict=True):
gradient = a.gradient(x, class_, strict=strict)
# using mean to make range of epsilons comparable to Linf
gradient = gradient / np.mean(np.abs(gradient))
min_, max_ = a.bounds()
gradient = (max_ - min_) * gradient
return gradient
class L2GradientMixin(object):
def _gradient(self, a, x, class_, strict=True):
gradient = a.gradient(x, class_, strict=strict)
# using mean to make range of epsilons comparable to Linf
gradient = gradient / np.sqrt(np.mean(np.square(gradient)))
min_, max_ = a.bounds()
gradient = (max_ - min_) * gradient
return gradient
class LinfinityClippingMixin(object):
def _clip_perturbation(self, a, perturbation, epsilon):
min_, max_ = a.bounds()
s = max_ - min_
clipped = np.clip(perturbation, -epsilon * s, epsilon * s)
return clipped
class L1ClippingMixin(object):
def _clip_perturbation(self, a, perturbation, epsilon):
# using mean to make range of epsilons comparable to Linf
norm = np.mean(np.abs(perturbation))
norm = max(1e-12, norm) # avoid divsion by zero
min_, max_ = a.bounds()
s = max_ - min_
# clipping, i.e. only decreasing norm
factor = min(1, epsilon * s / norm)
return perturbation * factor
class L2ClippingMixin(object):
def _clip_perturbation(self, a, perturbation, epsilon):
# using mean to make range of epsilons comparable to Linf
norm = np.sqrt(np.mean(np.square(perturbation)))
norm = max(1e-12, norm) # avoid divsion by zero
min_, max_ = a.bounds()
s = max_ - min_
# clipping, i.e. only decreasing norm
factor = min(1, epsilon * s / norm)
return perturbation * factor
class LinfinityDistanceCheckMixin(object):
def _check_distance(self, a):
if not isinstance(a.distance, distances.Linfinity):
logging.warning('Running an attack that tries to minimize the'
' Linfinity norm of the perturbation without'
' specifying foolbox.distances.Linfinity as'
' the distance metric might lead to suboptimal'
' results.')
class L1DistanceCheckMixin(object):
def _check_distance(self, a):
if not isinstance(a.distance, distances.MAE):
logging.warning('Running an attack that tries to minimize the'
' L1 norm of the perturbation without'
' specifying foolbox.distances.MAE as'
' the distance metric might lead to suboptimal'
' results.')
class L2DistanceCheckMixin(object):
def _check_distance(self, a):
if not isinstance(a.distance, distances.MSE):
logging.warning('Running an attack that tries to minimize the'
' L2 norm of the perturbation without'
' specifying foolbox.distances.MSE as'
' the distance metric might lead to suboptimal'
' results.')
class IterativeProjectedGradientBaseAttack(Attack):
"""Base class for iterative (projected) gradient attacks.
Concrete subclasses should implement __call__, _gradient
and _clip_perturbation.
TODO: add support for other loss-functions, e.g. the CW loss function,
see https://github.com/MadryLab/mnist_challenge/blob/master/pgd_attack.py
"""
@abstractmethod
def _gradient(self, a, x, class_, strict=True):
raise NotImplementedError
@abstractmethod
def _clip_perturbation(self, a, noise, epsilon):
raise NotImplementedError
@abstractmethod
def _check_distance(self, a):
raise NotImplementedError
def _get_mode_and_class(self, a):
# determine if the attack is targeted or not
target_class = a.target_class()
targeted = target_class is not None
if targeted:
class_ = target_class
else:
class_ = a.original_class
return targeted, class_
def _run(self, a, positive_salience, binary_search,
epsilon, stepsize, iterations,
random_start, return_early):
if not a.has_gradient():
warnings.warn('applied gradient-based attack to model that'
' does not provide gradients')
return
self._check_distance(a)
targeted, class_ = self._get_mode_and_class(a)
if binary_search:
if isinstance(binary_search, bool):
k = 20
else:
k = int(binary_search)
return self._run_binary_search(
a, positive_salience, epsilon, stepsize, iterations,
random_start, targeted, class_, return_early, k=k)
else:
return self._run_one(
a, positive_salience, epsilon, stepsize, iterations,
random_start, targeted, class_, return_early)
def _run_binary_search(self, a, positive_salience, epsilon, stepsize, iterations,
random_start, targeted, class_, return_early, k):
factor = stepsize / epsilon
def try_epsilon(epsilon):
stepsize = factor * epsilon
return self._run_one(
a, positive_salience, epsilon, stepsize, iterations,
random_start, targeted, class_, return_early)
for i in range(k):
if try_epsilon(epsilon):
logging.info('successful for eps = {}'.format(epsilon))
break
logging.info('not successful for eps = {}'.format(epsilon))
epsilon = epsilon * 1.5
else:
logging.warning('exponential search failed')
return
bad = 0
good = epsilon
for i in range(k):
epsilon = (good + bad) / 2
if try_epsilon(epsilon):
good = epsilon
logging.info('successful for eps = {}'.format(epsilon))
else:
bad = epsilon
logging.info('not successful for eps = {}'.format(epsilon))
def _run_one(self, a, positive_salience, epsilon, stepsize, iterations,
random_start, targeted, class_, return_early):
min_, max_ = a.bounds()
s = max_ - min_
original = a.original_image.copy()
if random_start:
# using uniform noise even if the perturbation clipping uses
# a different norm because cleverhans does it the same way
noise = np.random.uniform(
-epsilon * s, epsilon * s, original.shape).astype(
original.dtype)
x = original + self._clip_perturbation(a, noise, epsilon)
strict = False # because we don't enforce the bounds here
else:
x = original
strict = True
success = False
for _ in range(iterations):
gradient = self._gradient(a, x, class_, strict=strict)
# non-strict only for the first call and
# only if random_start is True
strict = True
if targeted:
gradient = -gradient
# untargeted: gradient ascent on cross-entropy to original class
# targeted: gradient descent on cross-entropy to target class
x = x + stepsize * gradient
x = original + self._clip_perturbation(a, x - original, epsilon)
x = np.clip(x, min_, max_)
if positive_salience is not None:
and_with_pos = np.logical_and(positive_salience, x)
noise_mask = and_with_pos.astype(int)
original_mask = abs(1 - noise_mask)
x = x * noise_mask + original * original_mask
logits, is_adversarial = a.predictions(x)
if logging.getLogger().isEnabledFor(logging.DEBUG):
if targeted:
ce = crossentropy(a.original_class, logits)
logging.debug('crossentropy to {} is {}'.format(
a.original_class, ce))
ce = crossentropy(class_, logits)
logging.debug('crossentropy to {} is {}'.format(class_, ce))
if is_adversarial:
if return_early:
return True
else:
success = True
return success
class LinfinityGradientMixin(object):
def _gradient(self, a, x, class_, strict=True):
gradient = a.gradient(x, class_, strict=strict)
gradient = np.sign(gradient)
min_, max_ = a.bounds()
gradient = (max_ - min_) * gradient
return gradient
class L1GradientMixin(object):
def _gradient(self, a, x, class_, strict=True):
gradient = a.gradient(x, class_, strict=strict)
# using mean to make range of epsilons comparable to Linf
gradient = gradient / np.mean(np.abs(gradient))
min_, max_ = a.bounds()
gradient = (max_ - min_) * gradient
return gradient
class L2GradientMixin(object):
def _gradient(self, a, x, class_, strict=True):
gradient = a.gradient(x, class_, strict=strict)
# using mean to make range of epsilons comparable to Linf
gradient = gradient / np.sqrt(np.mean(np.square(gradient)))
min_, max_ = a.bounds()
gradient = (max_ - min_) * gradient
return gradient
class LinfinityClippingMixin(object):
def _clip_perturbation(self, a, perturbation, epsilon):
min_, max_ = a.bounds()
s = max_ - min_
clipped = np.clip(perturbation, -epsilon * s, epsilon * s)
return clipped
class L1ClippingMixin(object):
def _clip_perturbation(self, a, perturbation, epsilon):
# using mean to make range of epsilons comparable to Linf
norm = np.mean(np.abs(perturbation))
norm = max(1e-12, norm) # avoid divsion by zero
min_, max_ = a.bounds()
s = max_ - min_
# clipping, i.e. only decreasing norm
factor = min(1, epsilon * s / norm)
return perturbation * factor
class L2ClippingMixin(object):
def _clip_perturbation(self, a, perturbation, epsilon):
# using mean to make range of epsilons comparable to Linf
norm = np.sqrt(np.mean(np.square(perturbation)))
norm = max(1e-12, norm) # avoid divsion by zero
min_, max_ = a.bounds()
s = max_ - min_
# clipping, i.e. only decreasing norm
factor = min(1, epsilon * s / norm)
return perturbation * factor
class LinfinityDistanceCheckMixin(object):
def _check_distance(self, a):
if not isinstance(a.distance, distances.Linfinity):
logging.warning('Running an attack that tries to minimize the'
' Linfinity norm of the perturbation without'
' specifying foolbox.distances.Linfinity as'
' the distance metric might lead to suboptimal'
' results.')
class L1DistanceCheckMixin(object):
def _check_distance(self, a):
if not isinstance(a.distance, distances.MAE):
logging.warning('Running an attack that tries to minimize the'
' L1 norm of the perturbation without'
' specifying foolbox.distances.MAE as'
' the distance metric might lead to suboptimal'
' results.')
class L2DistanceCheckMixin(object):
def _check_distance(self, a):
if not isinstance(a.distance, distances.MSE):
logging.warning('Running an attack that tries to minimize the'
' L2 norm of the perturbation without'
' specifying foolbox.distances.MSE as'
' the distance metric might lead to suboptimal'
' results.')
class SAIterativeAttack(
L2ClippingMixin,
L2DistanceCheckMixin,
IterativeProjectedGradientBaseAttack):
def _gradient(self, a, x, class_, strict=True):
# get current gradient
gradient = a.gradient(x, class_, strict=strict)
gradient = gradient / max(1e-12, np.mean(np.abs(gradient)))
# combine with history of gradient as new history
self._momentum_history = \
self._decay_factor * self._momentum_history + gradient
# use history
gradient = self._momentum_history
gradient = np.sign(gradient)
min_, max_ = a.bounds()
gradient = (max_ - min_) * gradient
return gradient
def _run_one(self, *args, **kwargs):
# reset momentum history every time we restart
# gradient descent
self._momentum_history = 0
return super(SAIterativeAttack, self)._run_one(*args, **kwargs)
@call_decorator
def __call__(self, input_or_adv, model_path = None, label=None, unpack=True,
binary_search=True,
epsilon=0.3,
stepsize=0.06,
iterations=10,
decay_factor=1.0,
random_start=False,
return_early=True):
"""Momentum-based iterative gradient attack known as
Momentum Iterative Method.
Parameters
----------
input_or_adv : `numpy.ndarray` or :class:`Adversarial`
The original, unperturbed input as a `numpy.ndarray` or
an :class:`Adversarial` instance.
label : int
The reference label of the original input. Must be passed
if `a` is a `numpy.ndarray`, must not be passed if `a` is
an :class:`Adversarial` instance.
unpack : bool
If true, returns the adversarial input, otherwise returns
the Adversarial object.
binary_search : bool
Whether to perform a binary search over epsilon and stepsize,
keeping their ratio constant and using their values to start
the search. If False, hyperparameters are not optimized.
Can also be an integer, specifying the number of binary
search steps (default 20).
epsilon : float
Limit on the perturbation size; if binary_search is True,
this value is only for initialization and automatically
adapted.
stepsize : float
Step size for gradient descent; if binary_search is True,
this value is only for initialization and automatically
adapted.
iterations : int
Number of iterations for each gradient descent run.
decay_factor : float
Decay factor used by the momentum term.
random_start : bool
Start the attack from a random point rather than from the
original input.
return_early : bool
Whether an individual gradient descent run should stop as
soon as an adversarial is found.
"""
a = input_or_adv
del input_or_adv
del label
del unpack
assert epsilon > 0
self._decay_factor = decay_factor
# self._initial_temperature = _initial_temperature
original = a.original_image.copy()
positive_salience = None
if model_path:
positive_salience = find_salience(model_path, original)
self._run(a, positive_salience, binary_search,
epsilon, stepsize, iterations,
random_start, return_early)
class RMSIterativeAttack(
L2ClippingMixin,
L2DistanceCheckMixin,
IterativeProjectedGradientBaseAttack):
def _gradient(self, a, x, class_, strict=True):
# get current gradient
gradient = a.gradient(x, class_, strict=strict)
noise = gradient / max(1e-12, np.mean(np.abs(gradient)))
# gradient = np.multiply(gradient, gradient)
# combine with history of gradient as new history
# the new noise becomes the momentum history
# use history
noise = noise * noise;
noise = self._gamma * self._gradient_history + (1 - self._gamma) * noise
self._gradient_history = noise
#det = np.clip(np.round(noise), 0, 1) - 0.5
noise = self._alpha/np.sqrt(noise) * gradient
# gradient = self._momentum_history
# gradient = np.sign(gradient)
min_, max_ = a.bounds()
noise = (max_ - min_) * noise
return noise
def _run_one(self, *args, **kwargs):
# reset momentum history every time we restart
# gradient descent
self._gradient_history = 0
return super(RMSIterativeAttack, self)._run_one(*args, **kwargs)
@call_decorator
def __call__(self, input_or_adv, model_path=None, label=None, unpack=True,
binary_search=True,
epsilon=0.3,
stepsize=0.06,
iterations=10,
decay_factor=1.0,
gamma = 0.4,
random_start=False,
return_early=True):
"""Momentum-based iterative gradient attack known as
Momentum Iterative Method.
Parameters
----------
input_or_adv : `numpy.ndarray` or :class:`Adversarial`
The original, unperturbed input as a `numpy.ndarray` or
an :class:`Adversarial` instance.
label : int
The reference label of the original input. Must be passed
if `a` is a `numpy.ndarray`, must not be passed if `a` is
an :class:`Adversarial` instance.
unpack : bool
If true, returns the adversarial input, otherwise returns
the Adversarial object.
binary_search : bool
Whether to perform a binary search over epsilon and stepsize,
keeping their ratio constant and using their values to start
the search. If False, hyperparameters are not optimized.
Can also be an integer, specifying the number of binary
search steps (default 20).
epsilon : float
Limit on the perturbation size; if binary_search is True,
this value is only for initialization and automatically
adapted.
stepsize : float
Step size for gradient descent; if binary_search is True,
this value is only for initialization and automatically
adapted.
iterations : int
Number of iterations for each gradient descent run.
decay_factor : float
Decay factor used by the momentum term.
random_start : bool
Start the attack from a random point rather than from the
original input.
return_early : bool
Whether an individual gradient descent run should stop as
soon as an adversarial is found.
"""
a = input_or_adv
del input_or_adv
del label
del unpack
assert epsilon > 0
self._decay_factor = decay_factor
self._gamma = gamma
self._alpha = epsilon / 12.0
# self._initial_temperature = _initial_temperature
original = a.original_image.copy()
positive_salience = None
if model_path:
positive_salience = find_salience(model_path, original)
self._run(a, positive_salience, binary_search,
epsilon, stepsize, iterations,
random_start, return_early)
class AdamIterativeAttack(
L2ClippingMixin,
L2DistanceCheckMixin,
IterativeProjectedGradientBaseAttack):
def _gradient(self, a, x, class_, strict=True):
# get current gradient
noise = a.gradient(x, class_, strict=strict)
noise = noise / max(1e-12, np.mean(np.abs(noise)))
momentum = self._beta1 * self._gradient_history + (1 - self._beta1) * noise
loss = self._beta2 * self._squared_gradient_history + (1 - self._beta2) * noise * noise
self._gradient_history = momentum
self._squared_gradient_history = loss
noise = self._alpha * (momentum/(np.sqrt(loss) + self._correction))
min_, max_ = a.bounds()
noise = (max_ - min_) * noise
return noise
def _run_one(self, *args, **kwargs):
# reset momentum history every time we restart
# gradient descent
self._gradient_history = 0
self._squared_gradient_history = 0
return super(AdamIterativeAttack, self)._run_one(*args, **kwargs)
@call_decorator
def __call__(self, input_or_adv, model_path=None,label=None, unpack=True,
binary_search=True,
epsilon=0.3,
stepsize=0.06,
iterations=10,
decay_factor=1.0,
beta1 = 0.4,
beta2 = 0.4,
correction = 0.00001,
random_start=False,
return_early=True):
"""Momentum-based iterative gradient attack known as
Momentum Iterative Method.
Parameters
----------
input_or_adv : `numpy.ndarray` or :class:`Adversarial`
The original, unperturbed input as a `numpy.ndarray` or
an :class:`Adversarial` instance.
label : int
The reference label of the original input. Must be passed
if `a` is a `numpy.ndarray`, must not be passed if `a` is
an :class:`Adversarial` instance.
unpack : bool
If true, returns the adversarial input, otherwise returns
the Adversarial object.
binary_search : bool
Whether to perform a binary search over epsilon and stepsize,
keeping their ratio constant and using their values to start
the search. If False, hyperparameters are not optimized.
Can also be an integer, specifying the number of binary
search steps (default 20).
epsilon : float
Limit on the perturbation size; if binary_search is True,
this value is only for initialization and automatically
adapted.
stepsize : float
Step size for gradient descent; if binary_search is True,
this value is only for initialization and automatically
adapted.
iterations : int
Number of iterations for each gradient descent run.
decay_factor : float
Decay factor used by the momentum term.
random_start : bool
Start the attack from a random point rather than from the
original input.
return_early : bool
Whether an individual gradient descent run should stop as
soon as an adversarial is found.
"""
a = input_or_adv
del input_or_adv
del label
del unpack
assert epsilon > 0
self._decay_factor = decay_factor
self._beta1 = beta1
self._beta2 = beta2
self._alpha = epsilon / 12.0
self._correction = correction
original = a.original_image.copy()
positive_salience = None
if model_path:
positive_salience = find_salience(model_path, original)
self._run(a, positive_salience, binary_search,
epsilon, stepsize, iterations,
random_start, return_early)
class AdagradIterativeAttack(
L2ClippingMixin,
L2DistanceCheckMixin,
IterativeProjectedGradientBaseAttack):
def _gradient(self, a, x, class_, strict=True):
# get current gradient
gradient = a.gradient(x, class_, strict=strict)
noise = gradient / max(1e-12, np.mean(np.abs(gradient)))
noise = noise * noise
if self._gradient_history is None:
self._gradient_history = noise
else:
assert self._gradient_history.shape == noise.shape
self._gradient_history = self._gradient_history + noise
noise = self._alpha/np.sqrt(self._gradient_history) * gradient
# gradient = self._momentum_history
# gradient = np.sign(gradient)
min_, max_ = a.bounds()
noise = (max_ - min_) * noise
return noise
def _run_one(self, *args, **kwargs):
# reset momentum history every time we restart
# gradient descent
self._gradient_history = None
return super(AdagradIterativeAttack, self)._run_one(*args, **kwargs)
@call_decorator
def __call__(self, input_or_adv, model_path = None, label=None, unpack=True,
binary_search=True,
epsilon=0.3,
stepsize=0.06,
iterations=10,
decay_factor=1.0,
random_start=False,
return_early=True):
"""Momentum-based iterative gradient attack known as
Momentum Iterative Method.
Parameters
----------
input_or_adv : `numpy.ndarray` or :class:`Adversarial`
The original, unperturbed input as a `numpy.ndarray` or
an :class:`Adversarial` instance.
label : int
The reference label of the original input. Must be passed
if `a` is a `numpy.ndarray`, must not be passed if `a` is
an :class:`Adversarial` instance.
unpack : bool
If true, returns the adversarial input, otherwise returns
the Adversarial object.
binary_search : bool
Whether to perform a binary search over epsilon and stepsize,
keeping their ratio constant and using their values to start
the search. If False, hyperparameters are not optimized.
Can also be an integer, specifying the number of binary
search steps (default 20).
epsilon : float
Limit on the perturbation size; if binary_search is True,
this value is only for initialization and automatically
adapted.
stepsize : float
Step size for gradient descent; if binary_search is True,
this value is only for initialization and automatically
adapted.
iterations : int
Number of iterations for each gradient descent run.
decay_factor : float
Decay factor used by the momentum term.
random_start : bool
Start the attack from a random point rather than from the
original input.
return_early : bool
Whether an individual gradient descent run should stop as
soon as an adversarial is found.
"""
a = input_or_adv
del input_or_adv
del label
del unpack
assert epsilon > 0
self._decay_factor = decay_factor
self._alpha = epsilon / 12.0
# self._initial_temperature = _initial_temperature
self._run(a, None, binary_search,
epsilon, stepsize, iterations,
random_start, return_early)