-
Notifications
You must be signed in to change notification settings - Fork 17
/
attacks.py
1867 lines (1580 loc) · 73.2 KB
/
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
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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from abc import ABCMeta
import numpy as np
from six.moves import xrange
import warnings
import collections
import cleverhans.utils as utils
from cleverhans.model import Model, CallableModelWrapper
from distutils.version import LooseVersion
from cleverhans.compat import reduce_sum, reduce_mean
from cleverhans.compat import reduce_max, reduce_min
from cleverhans.compat import reduce_any
_logger = utils.create_logger("cleverhans.attacks")
class Attack(object):
"""
Abstract base class for all attack classes.
"""
__metaclass__ = ABCMeta
def __init__(self, model, back='tf', sess=None, dtypestr='float32'):
"""
:param model: An instance of the cleverhans.model.Model class.
:param back: The backend to use. Currently 'tf' is the only option.
:param sess: The tf session to run graphs in
"""
if not (back == 'tf'):
raise ValueError("Backend argument must be 'tf'.")
if back == 'tf':
import tensorflow as tf
self.tf_dtype = tf.as_dtype(dtypestr)
if sess is None:
sess = tf.get_default_session()
self.np_dtype = np.dtype(dtypestr)
import cleverhans.attacks_tf as attacks_tf
attacks_tf.np_dtype = self.np_dtype
attacks_tf.tf_dtype = self.tf_dtype
if not isinstance(model, Model):
raise ValueError("The model argument should be an instance of"
" the cleverhans.model.Model class.")
# Prepare attributes
self.model = model
self.back = back
self.sess = sess
self.dtypestr = dtypestr
# We are going to keep track of old graphs and cache them.
self.graphs = {}
# When calling generate_np, arguments in the following set should be
# fed into the graph, as they are not structural items that require
# generating a new graph.
# This dict should map names of arguments to the types they should
# have.
# (Usually, the target class will be a feedable keyword argument.)
self.feedable_kwargs = {}
# When calling generate_np, arguments in the following set should NOT
# be fed into the graph, as they ARE structural items that require
# generating a new graph.
# This list should contain the names of the structural arguments.
self.structural_kwargs = []
def generate(self, x, **kwargs):
"""
Generate the attack's symbolic graph for adversarial examples. This
method should be overriden in any child class that implements an
attack that is expressable symbolically. Otherwise, it will wrap the
numerical implementation as a symbolic operator.
:param x: The model's symbolic inputs.
:param **kwargs: optional parameters used by child classes.
:return: A symbolic representation of the adversarial examples.
"""
error = "Sub-classes must implement generate."
raise NotImplementedError(error)
def construct_graph(self, fixed, feedable, x_val, hash_key):
"""
Construct the graph required to run the attack through generate_np.
:param fixed: Structural elements that require defining a new graph.
:param feedable: Arguments that can be fed to the same graph when
they take different values.
:param x_val: symbolic adversarial example
:param hash_key: the key used to store this graph in our cache
"""
# try our very best to create a TF placeholder for each of the
# feedable keyword arguments, and check the types are one of
# the allowed types
import tensorflow as tf
class_name = str(self.__class__).split(".")[-1][:-2]
_logger.info("Constructing new graph for attack " + class_name)
# remove the None arguments, they are just left blank
for k in list(feedable.keys()):
if feedable[k] is None:
del feedable[k]
# process all of the rest and create placeholders for them
new_kwargs = dict(x for x in fixed.items())
for name, value in feedable.items():
given_type = self.feedable_kwargs[name]
if isinstance(value, np.ndarray):
new_shape = [None] + list(value.shape[1:])
new_kwargs[name] = tf.placeholder(given_type, new_shape)
elif isinstance(value, utils.known_number_types):
new_kwargs[name] = tf.placeholder(given_type, shape=[])
else:
raise ValueError("Could not identify type of argument " +
name + ": " + str(value))
# x is a special placeholder we always want to have
x_shape = [None] + list(x_val.shape)[1:]
x = tf.placeholder(self.tf_dtype, shape=x_shape)
# now we generate the graph that we want
x_adv = self.generate(x, **new_kwargs)
self.graphs[hash_key] = (x, new_kwargs, x_adv)
if len(self.graphs) >= 10:
warnings.warn("Calling generate_np() with multiple different "
"structural paramaters is inefficient and should"
" be avoided. Calling generate() is preferred.")
def generate_np(self, x_val, **kwargs):
"""
Generate adversarial examples and return them as a NumPy array.
Sub-classes *should not* implement this method unless they must
perform special handling of arguments.
:param x_val: A NumPy array with the original inputs.
:param **kwargs: optional parameters used by child classes.
:return: A NumPy array holding the adversarial examples.
"""
if self.sess is None:
raise ValueError("Cannot use `generate_np` when no `sess` was"
" provided")
fixed, feedable, hash_key = self.construct_variables(kwargs)
if hash_key not in self.graphs:
self.construct_graph(fixed, feedable, x_val, hash_key)
else:
# remove the None arguments, they are just left blank
for k in list(feedable.keys()):
if feedable[k] is None:
del feedable[k]
x, new_kwargs, x_adv = self.graphs[hash_key]
feed_dict = {x: x_val}
for name in feedable:
feed_dict[new_kwargs[name]] = feedable[name]
return self.sess.run(x_adv, feed_dict)
def construct_variables(self, kwargs):
"""
Construct the inputs to the attack graph to be used by generate_np.
:param kwargs: Keyword arguments to generate_np.
:return: Structural and feedable arguments as well as a unique key
for the graph given these inputs.
"""
# the set of arguments that are structural properties of the attack
# if these arguments are different, we must construct a new graph
fixed = dict(
(k, v) for k, v in kwargs.items() if k in self.structural_kwargs)
# the set of arguments that are passed as placeholders to the graph
# on each call, and can change without constructing a new graph
feedable = dict(
(k, v) for k, v in kwargs.items() if k in self.feedable_kwargs)
if len(fixed) + len(feedable) < len(kwargs):
warnings.warn("Supplied extra keyword arguments that are not "
"used in the graph computation. They have been "
"ignored.")
if not all(
isinstance(value, collections.Hashable)
for value in fixed.values()):
# we have received a fixed value that isn't hashable
# this means we can't cache this graph for later use,
# and it will have to be discarded later
hash_key = None
else:
# create a unique key for this set of fixed paramaters
hash_key = tuple(sorted(fixed.items()))
return fixed, feedable, hash_key
def get_or_guess_labels(self, x, kwargs):
"""
Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not none, then assume it's a
targeted attack and use that as the label.
Otherwise, use the model's prediction as the label and perform an
untargeted attack.
"""
import tensorflow as tf
if 'y' in kwargs and 'y_target' in kwargs:
raise ValueError("Can not set both 'y' and 'y_target'.")
elif 'y' in kwargs:
labels = kwargs['y']
elif 'y_target' in kwargs and kwargs['y_target'] is not None:
labels = kwargs['y_target']
else:
preds = self.model.get_probs(x)
preds_max = reduce_max(preds, 1, keepdims=True)
original_predictions = tf.to_float(tf.equal(preds, preds_max))
labels = tf.stop_gradient(original_predictions)
if isinstance(labels, np.ndarray):
nb_classes = labels.shape[1]
else:
nb_classes = labels.get_shape().as_list()[1]
return labels, nb_classes
def parse_params(self, params=None):
"""
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
:param params: a dictionary of attack-specific parameters
:return: True when parsing was successful
"""
return True
class FastGradientMethod(Attack):
"""
This attack was originally implemented by Goodfellow et al. (2015) with the
infinity norm (and is known as the "Fast Gradient Sign Method"). This
implementation extends the attack to other norms, and is therefore called
the Fast Gradient Method.
Paper link: https://arxiv.org/abs/1412.6572
"""
def __init__(self, model, back='tf', sess=None, dtypestr='float32'):
"""
Create a FastGradientMethod instance.
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
"""
if not isinstance(model, Model):
model = CallableModelWrapper(model, 'probs')
super(FastGradientMethod, self).__init__(model, back, sess, dtypestr)
self.feedable_kwargs = {
'eps': self.np_dtype,
'y': self.np_dtype,
'y_target': self.np_dtype,
'clip_min': self.np_dtype,
'clip_max': self.np_dtype
}
self.structural_kwargs = ['ord']
def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param eps: (optional float) attack step size (input variation)
:param ord: (optional) Order of the norm (mimics NumPy).
Possible values: np.inf, 1 or 2.
:param y: (optional) A tensor with the model labels. Only provide
this parameter if you'd like to use true labels when crafting
adversarial samples. Otherwise, model predictions are used as
labels to avoid the "label leaking" effect (explained in this
paper: https://arxiv.org/abs/1611.01236). Default is None.
Labels should be one-hot-encoded.
:param y_target: (optional) A tensor with the labels to target. Leave
y_target=None if y is also set. Labels should be
one-hot-encoded.
:param clip_min: (optional float) Minimum input component value
:param clip_max: (optional float) Maximum input component value
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
from .attacks_tf import fgm
labels, nb_classes = self.get_or_guess_labels(x, kwargs)
return fgm(
x,
self.model.get_probs(x),
y=labels,
eps=self.eps,
ord=self.ord,
clip_min=self.clip_min,
clip_max=self.clip_max,
targeted=(self.y_target is not None))
def parse_params(self,
eps=0.3,
ord=np.inf,
y=None,
y_target=None,
clip_min=None,
clip_max=None,
**kwargs):
"""
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param eps: (optional float) attack step size (input variation)
:param ord: (optional) Order of the norm (mimics NumPy).
Possible values: np.inf, 1 or 2.
:param y: (optional) A tensor with the model labels. Only provide
this parameter if you'd like to use true labels when crafting
adversarial samples. Otherwise, model predictions are used as
labels to avoid the "label leaking" effect (explained in this
paper: https://arxiv.org/abs/1611.01236). Default is None.
Labels should be one-hot-encoded.
:param y_target: (optional) A tensor with the labels to target. Leave
y_target=None if y is also set. Labels should be
one-hot-encoded.
:param clip_min: (optional float) Minimum input component value
:param clip_max: (optional float) Maximum input component value
"""
# Save attack-specific parameters
self.eps = eps
self.ord = ord
self.y = y
self.y_target = y_target
self.clip_min = clip_min
self.clip_max = clip_max
if self.y is not None and self.y_target is not None:
raise ValueError("Must not set both y and y_target")
# Check if order of the norm is acceptable given current implementation
if self.ord not in [np.inf, int(1), int(2)]:
raise ValueError("Norm order must be either np.inf, 1, or 2.")
return True
class BasicIterativeMethod(Attack):
"""
The Basic Iterative Method (Kurakin et al. 2016). The original paper used
hard labels for this attack; no label smoothing.
Paper link: https://arxiv.org/pdf/1607.02533.pdf
"""
FGM_CLASS = FastGradientMethod
def __init__(self, model, back='tf', sess=None, dtypestr='float32'):
"""
Create a BasicIterativeMethod instance.
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
"""
if not isinstance(model, Model):
model = CallableModelWrapper(model, 'probs')
super(BasicIterativeMethod, self).__init__(model, back, sess, dtypestr)
self.feedable_kwargs = {
'eps': self.np_dtype,
'eps_iter': self.np_dtype,
'y': self.np_dtype,
'y_target': self.np_dtype,
'clip_min': self.np_dtype,
'clip_max': self.np_dtype
}
self.structural_kwargs = ['ord', 'nb_iter']
def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param eps: (required float) maximum distortion of adversarial example
compared to original input
:param eps_iter: (required float) step size for each attack iteration
:param nb_iter: (required int) Number of attack iterations.
:param y: (optional) A tensor with the model labels.
:param y_target: (optional) A tensor with the labels to target. Leave
y_target=None if y is also set. Labels should be
one-hot-encoded.
:param ord: (optional) Order of the norm (mimics Numpy).
Possible values: np.inf, 1 or 2.
:param clip_min: (optional float) Minimum input component value
:param clip_max: (optional float) Maximum input component value
"""
import tensorflow as tf
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
# Initialize loop variables
eta = tf.zeros_like(x)
# Fix labels to the first model predictions for loss computation
model_preds = self.model.get_probs(x)
preds_max = reduce_max(model_preds, 1, keepdims=True)
if self.y_target is not None:
y = self.y_target
targeted = True
elif self.y is not None:
y = self.y
targeted = False
else:
y = tf.to_float(tf.equal(model_preds, preds_max))
y = tf.stop_gradient(y)
targeted = False
y_kwarg = 'y_target' if targeted else 'y'
fgm_params = {
'eps': self.eps_iter,
y_kwarg: y,
'ord': self.ord,
'clip_min': self.clip_min,
'clip_max': self.clip_max
}
# Use getattr() to avoid errors in eager execution attacks
FGM = self.FGM_CLASS(
self.model,
back=getattr(self, 'back', None),
sess=getattr(self, 'sess', None),
dtypestr=self.dtypestr)
def cond(i, _):
return tf.less(i, self.nb_iter)
def body(i, e):
adv_x = FGM.generate(x + e, **fgm_params)
# Clipping perturbation according to clip_min and clip_max
if self.clip_min is not None and self.clip_max is not None:
adv_x = tf.clip_by_value(adv_x, self.clip_min, self.clip_max)
# Clipping perturbation eta to self.ord norm ball
eta = adv_x - x
from cleverhans.utils_tf import clip_eta
eta = clip_eta(eta, self.ord, self.eps)
return i + 1, eta
_, eta = tf.while_loop(cond, body, [tf.zeros([]), eta], back_prop=True)
# Define adversarial example (and clip if necessary)
adv_x = x + eta
if self.clip_min is not None and self.clip_max is not None:
adv_x = tf.clip_by_value(adv_x, self.clip_min, self.clip_max)
return adv_x
def parse_params(self,
eps=0.3,
eps_iter=0.05,
nb_iter=10,
y=None,
ord=np.inf,
clip_min=None,
clip_max=None,
y_target=None,
**kwargs):
"""
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param eps: (required float) maximum distortion of adversarial example
compared to original input
:param eps_iter: (required float) step size for each attack iteration
:param nb_iter: (required int) Number of attack iterations.
:param y: (optional) A tensor with the model labels.
:param y_target: (optional) A tensor with the labels to target. Leave
y_target=None if y is also set. Labels should be
one-hot-encoded.
:param ord: (optional) Order of the norm (mimics Numpy).
Possible values: np.inf, 1 or 2.
:param clip_min: (optional float) Minimum input component value
:param clip_max: (optional float) Maximum input component value
"""
# Save attack-specific parameters
self.eps = eps
self.eps_iter = eps_iter
self.nb_iter = nb_iter
self.y = y
self.y_target = y_target
self.ord = ord
self.clip_min = clip_min
self.clip_max = clip_max
if self.y is not None and self.y_target is not None:
raise ValueError("Must not set both y and y_target")
# Check if order of the norm is acceptable given current implementation
if self.ord not in [np.inf, 1, 2]:
raise ValueError("Norm order must be either np.inf, 1, or 2.")
return True
class MomentumIterativeMethod(Attack):
"""
The Momentum Iterative Method (Dong et al. 2017). This method won
the first places in NIPS 2017 Non-targeted Adversarial Attacks and
Targeted Adversarial Attacks. The original paper used hard labels
for this attack; no label smoothing.
Paper link: https://arxiv.org/pdf/1710.06081.pdf
"""
def __init__(self, model, back='tf', sess=None, dtypestr='float32'):
"""
Create a MomentumIterativeMethod instance.
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
"""
if not isinstance(model, Model):
model = CallableModelWrapper(model, 'probs')
super(MomentumIterativeMethod, self).__init__(model, back, sess,
dtypestr)
self.feedable_kwargs = {
'eps': self.np_dtype,
'eps_iter': self.np_dtype,
'y': self.np_dtype,
'y_target': self.np_dtype,
'clip_min': self.np_dtype,
'clip_max': self.np_dtype
}
self.structural_kwargs = ['ord', 'nb_iter', 'decay_factor']
def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param eps: (required float) maximum distortion of adversarial example
compared to original input
:param eps_iter: (required float) step size for each attack iteration
:param nb_iter: (required int) Number of attack iterations.
:param y: (optional) A tensor with the model labels.
:param y_target: (optional) A tensor with the labels to target. Leave
y_target=None if y is also set. Labels should be
one-hot-encoded.
:param ord: (optional) Order of the norm (mimics Numpy).
Possible values: np.inf, 1 or 2.
:param decay_factor: (optional) Decay factor for the momentum term.
:param clip_min: (optional float) Minimum input component value
:param clip_max: (optional float) Maximum input component value
"""
import tensorflow as tf
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
# Initialize loop variables
momentum = tf.zeros_like(x)
adv_x = x
# Fix labels to the first model predictions for loss computation
y, nb_classes = self.get_or_guess_labels(x, kwargs)
y = y / reduce_sum(y, 1, keepdims=True)
targeted = (self.y_target is not None)
from . import utils_tf
from . import loss as loss_module
def cond(i, _, __):
return tf.less(i, self.nb_iter)
def body(i, ax, m):
preds = self.model.get_probs(ax)
loss = loss_module.attack_softmax_cross_entropy(
y, preds, mean=False)
if targeted:
loss = -loss
# Define gradient of loss wrt input
grad, = tf.gradients(loss, ax)
# Normalize current gradient and add it to the accumulated gradient
red_ind = list(xrange(1, len(grad.get_shape())))
avoid_zero_div = tf.cast(1e-12, grad.dtype)
grad = grad / tf.maximum(
avoid_zero_div,
reduce_mean(tf.abs(grad), red_ind, keepdims=True))
m = self.decay_factor * m + grad
if self.ord == np.inf:
normalized_grad = tf.sign(m)
elif self.ord == 1:
norm = tf.maximum(
avoid_zero_div,
reduce_sum(tf.abs(m), red_ind, keepdims=True))
normalized_grad = m / norm
elif self.ord == 2:
square = reduce_sum(tf.square(m), red_ind, keepdims=True)
norm = tf.sqrt(tf.maximum(avoid_zero_div, square))
normalized_grad = m / norm
else:
raise NotImplementedError("Only L-inf, L1 and L2 norms are "
"currently implemented.")
# Update and clip adversarial example in current iteration
scaled_grad = self.eps_iter * normalized_grad
ax = ax + scaled_grad
ax = x + utils_tf.clip_eta(ax - x, self.ord, self.eps)
if self.clip_min is not None and self.clip_max is not None:
ax = tf.clip_by_value(ax, self.clip_min, self.clip_max)
ax = tf.stop_gradient(ax)
return i + 1, ax, m
_, adv_x, _ = tf.while_loop(
cond, body, [tf.zeros([]), adv_x, momentum], back_prop=True)
return adv_x
def parse_params(self,
eps=0.3,
eps_iter=0.06,
nb_iter=10,
y=None,
ord=np.inf,
decay_factor=1.0,
clip_min=None,
clip_max=None,
y_target=None,
**kwargs):
"""
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param eps: (required float) maximum distortion of adversarial example
compared to original input
:param eps_iter: (required float) step size for each attack iteration
:param nb_iter: (required int) Number of attack iterations.
:param y: (optional) A tensor with the model labels.
:param y_target: (optional) A tensor with the labels to target. Leave
y_target=None if y is also set. Labels should be
one-hot-encoded.
:param ord: (optional) Order of the norm (mimics Numpy).
Possible values: np.inf, 1 or 2.
:param decay_factor: (optional) Decay factor for the momentum term.
:param clip_min: (optional float) Minimum input component value
:param clip_max: (optional float) Maximum input component value
"""
# Save attack-specific parameters
self.eps = eps
self.eps_iter = eps_iter
self.nb_iter = nb_iter
self.y = y
self.y_target = y_target
self.ord = ord
self.decay_factor = decay_factor
self.clip_min = clip_min
self.clip_max = clip_max
if self.y is not None and self.y_target is not None:
raise ValueError("Must not set both y and y_target")
# Check if order of the norm is acceptable given current implementation
if self.ord not in [np.inf, 1, 2]:
raise ValueError("Norm order must be either np.inf, 1, or 2.")
return True
class SaliencyMapMethod(Attack):
"""
The Jacobian-based Saliency Map Method (Papernot et al. 2016).
Paper link: https://arxiv.org/pdf/1511.07528.pdf
"""
def __init__(self, model, back='tf', sess=None, dtypestr='float32'):
"""
Create a SaliencyMapMethod instance.
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
"""
if not isinstance(model, Model):
model = CallableModelWrapper(model, 'probs')
super(SaliencyMapMethod, self).__init__(model, back, sess, dtypestr)
import tensorflow as tf
self.feedable_kwargs = {'y_target': self.tf_dtype}
self.structural_kwargs = [
'theta', 'gamma', 'clip_max', 'clip_min', 'symbolic_impl'
]
def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param theta: (optional float) Perturbation introduced to modified
components (can be positive or negative)
:param gamma: (optional float) Maximum percentage of perturbed features
:param clip_min: (optional float) Minimum component value for clipping
:param clip_max: (optional float) Maximum component value for clipping
:param y_target: (optional) Target tensor if the attack is targeted
"""
import tensorflow as tf
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
if self.symbolic_impl:
from .attacks_tf import jsma_symbolic
# Create random targets if y_target not provided
if self.y_target is None:
from random import randint
def random_targets(gt):
result = gt.copy()
nb_s = gt.shape[0]
nb_classes = gt.shape[1]
for i in xrange(nb_s):
result[i, :] = np.roll(result[i, :],
randint(1, nb_classes - 1))
return result
labels, nb_classes = self.get_or_guess_labels(x, kwargs)
self.y_target = tf.py_func(random_targets, [labels],
self.tf_dtype)
self.y_target.set_shape([None, nb_classes])
x_adv = jsma_symbolic(
x,
model=self.model,
y_target=self.y_target,
theta=self.theta,
gamma=self.gamma,
clip_min=self.clip_min,
clip_max=self.clip_max)
else:
from .attacks_tf import jacobian_graph, jsma_batch
# Define Jacobian graph wrt to this input placeholder
preds = self.model.get_probs(x)
nb_classes = preds.get_shape().as_list()[-1]
grads = jacobian_graph(preds, x, nb_classes)
# Define appropriate graph (targeted / random target labels)
if self.y_target is not None:
def jsma_wrap(x_val, y_target):
return jsma_batch(
self.sess,
x,
preds,
grads,
x_val,
self.theta,
self.gamma,
self.clip_min,
self.clip_max,
nb_classes,
y_target=y_target)
# Attack is targeted, target placeholder will need to be fed
x_adv = tf.py_func(jsma_wrap, [x, self.y_target],
self.tf_dtype)
else:
def jsma_wrap(x_val):
return jsma_batch(
self.sess,
x,
preds,
grads,
x_val,
self.theta,
self.gamma,
self.clip_min,
self.clip_max,
nb_classes,
y_target=None)
# Attack is untargeted, target values will be chosen at random
x_adv = tf.py_func(jsma_wrap, [x], self.tf_dtype)
x_adv.set_shape(x.get_shape())
return x_adv
def parse_params(self,
theta=1.,
gamma=1.,
nb_classes=None,
clip_min=0.,
clip_max=1.,
y_target=None,
symbolic_impl=True,
**kwargs):
"""
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param theta: (optional float) Perturbation introduced to modified
components (can be positive or negative)
:param gamma: (optional float) Maximum percentage of perturbed features
:param nb_classes: (optional int) Number of model output classes
:param clip_min: (optional float) Minimum component value for clipping
:param clip_max: (optional float) Maximum component value for clipping
:param y_target: (optional) Target tensor if the attack is targeted
"""
if nb_classes is not None:
warnings.warn("The nb_classes argument is depricated and will "
"be removed on 2018-02-11")
self.theta = theta
self.gamma = gamma
self.clip_min = clip_min
self.clip_max = clip_max
self.y_target = y_target
self.symbolic_impl = symbolic_impl
return True
class VirtualAdversarialMethod(Attack):
"""
This attack was originally proposed by Miyato et al. (2016) and was used
for virtual adversarial training.
Paper link: https://arxiv.org/abs/1507.00677
"""
def __init__(self, model, back='tf', sess=None, dtypestr='float32'):
"""
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
"""
if not isinstance(model, Model):
model = CallableModelWrapper(model, 'logits')
super(VirtualAdversarialMethod, self).__init__(model, back, sess,
dtypestr)
import tensorflow as tf
self.feedable_kwargs = {
'eps': self.tf_dtype,
'xi': self.tf_dtype,
'clip_min': self.tf_dtype,
'clip_max': self.tf_dtype
}
self.structural_kwargs = ['num_iterations']
def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param eps: (optional float ) the epsilon (input variation parameter)
:param num_iterations: (optional) the number of iterations
:param xi: (optional float) the finite difference parameter
:param clip_min: (optional float) Minimum input component value
:param clip_max: (optional float) Maximum input component value
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
return vatm(
self.model,
x,
self.model.get_logits(x),
eps=self.eps,
num_iterations=self.num_iterations,
xi=self.xi,
clip_min=self.clip_min,
clip_max=self.clip_max)
def parse_params(self,
eps=2.0,
num_iterations=1,
xi=1e-6,
clip_min=None,
clip_max=None,
**kwargs):
"""
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param eps: (optional float )the epsilon (input variation parameter)
:param num_iterations: (optional) the number of iterations
:param xi: (optional float) the finite difference parameter
:param clip_min: (optional float) Minimum input component value
:param clip_max: (optional float) Maximum input component value
"""
# Save attack-specific parameters
self.eps = eps
self.num_iterations = num_iterations
self.xi = xi
self.clip_min = clip_min
self.clip_max = clip_max
return True
class CarliniWagnerL2(Attack):
"""
This attack was originally proposed by Carlini and Wagner. It is an
iterative attack that finds adversarial examples on many defenses that
are robust to other attacks.
Paper link: https://arxiv.org/abs/1608.04644
At a high level, this attack is an iterative attack using Adam and
a specially-chosen loss function to find adversarial examples with
lower distortion than other attacks. This comes at the cost of speed,
as this attack is often much slower than others.
"""
def __init__(self, model, back='tf', sess=None, dtypestr='float32'):
"""
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
"""
if not isinstance(model, Model):
model = CallableModelWrapper(model, 'logits')
super(CarliniWagnerL2, self).__init__(model, back, sess, dtypestr)
import tensorflow as tf
self.feedable_kwargs = {'y': self.tf_dtype, 'y_target': self.tf_dtype}
self.structural_kwargs = [
'batch_size', 'confidence', 'targeted', 'learning_rate',
'binary_search_steps', 'max_iterations', 'abort_early',
'initial_const', 'clip_min', 'clip_max'
]
def generate(self, x, **kwargs):
"""
Return a tensor that constructs adversarial examples for the given
input. Generate uses tf.py_func in order to operate over tensors.
:param x: (required) A tensor with the inputs.
:param y: (optional) A tensor with the true labels for an untargeted
attack. If None (and y_target is None) then use the
original labels the classifier assigns.
:param y_target: (optional) A tensor with the target labels for a
targeted attack.
:param confidence: Confidence of adversarial examples: higher produces
examples with larger l2 distortion, but more
strongly classified as adversarial.
:param batch_size: Number of attacks to run simultaneously.
:param learning_rate: The learning rate for the attack algorithm.
Smaller values produce better results but are
slower to converge.
:param binary_search_steps: The number of times we perform binary
search to find the optimal tradeoff-
constant between norm of the purturbation
and confidence of the classification.
:param max_iterations: The maximum number of iterations. Setting this
to a larger value will produce lower distortion
results. Using only a few iterations requires
a larger learning rate, and will produce larger
distortion results.
:param abort_early: If true, allows early aborts if gradient descent
is unable to make progress (i.e., gets stuck in
a local minimum).
:param initial_const: The initial tradeoff-constant to use to tune the
relative importance of size of the pururbation
and confidence of classification.
If binary_search_steps is large, the initial
constant is not important. A smaller value of
this constant gives lower distortion results.
:param clip_min: (optional float) Minimum input component value
:param clip_max: (optional float) Maximum input component value
"""
import tensorflow as tf
from .attacks_tf import CarliniWagnerL2 as CWL2
self.parse_params(**kwargs)
labels, nb_classes = self.get_or_guess_labels(x, kwargs)