-
Notifications
You must be signed in to change notification settings - Fork 0
/
tests.py
1901 lines (1733 loc) · 76.5 KB
/
tests.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
"""
This module runs attack performance and correctness tests against other AML
libraries. Specifically, this defines three types of tests: (1) functional, (2)
performance, and (3) identity. Details surrounding these tests can be found in
the respecetive classes: FunctionalTests, PerformanceTests, and IdentityTests.
Aside from these standard tests, special tests can be found in the SpecialTests
class, which evaluate particulars of the implementation in the Space of
Adversarial Strategies (https://arxiv.org/pdf/2209.04521.pdf).
"""
import importlib
import pathlib
import pickle
import unittest
import dlm
import mlds
import numpy as np
import torch
import aml
class BaseTest(unittest.TestCase):
"""
The following class serves as the base test for all tests cases. It
provides: (1) common initializations required by all tests, such as
retrieving data and training models (since there is apparently no elegant
way to set up text fixtures *across test cases*, even though setUpModule
sounds like it ought to fit the bill...), (2) initializations required by
some tests (e.g., instantiating objects specific to other adversarial
machine learning frameworks), and (3) methods to craft adversarial examples
from aml and other supported adversarial machine learning frameworks.
The following frameworks are supported:
AdverTorch (https://github.com/BorealisAI/advertorch)
ART (https://github.com/Trusted-AI/adversarial-robustness-toolbox)
CleverHans (https://github.com/cleverhans-lab/cleverhans)
Foolbox (https://github.com/bethgelab/foolbox)
Torchattacks (https://github.com/Harry24k/adversarial-attacks-pytorch)
The following attacks are supported:
APGD-CE (Auto-PGD with CE loss) (https://arxiv.org/pdf/2003.01690.pdf)
APGD-DLR (Auto-PGD with DLR loss) (https://arxiv.org/pdf/2003.01690.pdf)
BIM (Basic Iterative Method) (https://arxiv.org/pdf/1611.01236.pdf)
CW-L2 (Carlini-Wagner with l2 norm) (https://arxiv.org/pdf/1608.04644.pdf)
DF (DeepFool) (https://arxiv.org/pdf/1511.04599.pdf)
FAB (Fast Adaptive Boundary) (https://arxiv.org/pdf/1907.02044.pdf)
JSMA (Jacobian Saliency Map Approach) (https://arxiv.org/pdf/1511.07528.pdf)
PGD (Projected Gradient Descent) (https://arxiv.org/pdf/1706.06083.pdf)
:func:`setUpClass`: initializes the setup for all tests cases
:func:`build_art_classifier`: instantiates an art pytorch classifier
:func:`build_fb_classifier`: instantiates a foolbox pytorch classifier
:func:`l0_proj`: projects inputs onto l0-based threat models
:func:`l2_proj`: projects inputs onto l2-based threat models
:func:`linf_proj`: projects inputs onto l∞-based threat models
:func:`reset_seeds`: resets seeds for RNGs
:func:`apgdce`: craft adversarial examples with APGD-CE
:func:`apgddlr`: craft adversarial examples with APGD-DLR
:func:`bim`: craft adversarial examples with BIM
:func:`cwl2`: craft adversarial examples with CW-L2
:func:`df`: craft adversarial examples with DF
:func:`fab`: craft adversarial examples with FAB
:func:`jsma`: craft adversarial examples with JSMA
:func:`pgd`: craft adversarial examples with PGD
"""
@classmethod
def setUpClass(
cls,
alpha=0.01,
dataset="phishing",
debug=False,
epochs=100,
norm=0.15,
seed=5115,
verbose=False,
):
"""
This function initializes the setup necessary for all test cases within
this module. Specifically, this method retrieves data, processes it,
trains a model, instantiates attacks, imports availabe external
libraries (used for performance and identity tests), loads PyTorch in
debug mode if desired (to assist debugging autograd), and sets the seed
used to make attacks with randomized components deterministic.
:param alpha: perturbation strength
:type alpha: float
:param dataset: dataset to run tests over
:type dataset: str
:param debug: whether to set the autograd engine in debug mode
:type debug: bool
:param epochs: number of attack iterations
:type epochs: int
:param norm: maximum percentage of lp-budget consumption
:type norm: float
:param seed: the seed to use to make randomized components determinisitc
:type seed: int
:param verbose: print attack status during crafting
:type verbose float
:return: None
:rtype: NoneType
"""
# set debug, seed, and load appropriate data partitions
print("Initializing module for all test cases...")
torch.autograd.set_detect_anomaly(debug)
cls.seed = seed
data = getattr(mlds, dataset)
try:
x = torch.from_numpy(data.train.data)
y = torch.from_numpy(data.train.labels).long()
cls.x = torch.from_numpy(data.test.data)
cls.y = torch.from_numpy(data.test.labels).long()
has_test = True
except AttributeError:
has_test = False
cls.x = torch.from_numpy(data.dataset.data)
cls.y = torch.from_numpy(data.dataset.labels).long()
# determine clipping range (non-image datasets may not be 0-1)
mins, maxs = cls.x.min(0).values.clamp(max=0), cls.x.max(0).values.clamp(min=1)
clip = (mins, maxs)
p_clip = (mins.sub(cls.x), maxs.sub(cls.x))
clip_info = (
(mins[0].item(), maxs[0].item())
if (mins[0].eq(mins).all() and maxs[0].eq(maxs).all())
else f"(({mins.min().item()}, ..., {mins.max().item()}), "
f"({maxs.min().item()}, ..., {maxs.max().item()}))"
)
# load model hyperparameters
cls.reset_seeds()
template = getattr(dlm.templates, dataset)
cls.model, hyperparameters = (
(dlm.CNNClassifier(**template.cnn), template.cnn)
if hasattr(template, "cnn")
else (dlm.MLPClassifier(**template.mlp), template.mlp)
)
# train (or load) model and save craftset accuracy (for performance tests)
try:
path = pathlib.Path(f"/tmp/aml_trained_{dataset}_model.pkl")
with path.open("rb") as f:
state = pickle.load(f)
assert state["template"] == hyperparameters, "Hyperparameters have changed"
assert state["seed"] == seed, f"Seed changed: {state['seed']} != {seed}"
cls.model = state["model"]
print(f"Using pretrained {dataset} model from {path}.")
cls.model.summary()
except (FileNotFoundError, AssertionError) as e:
print(f"Training new model... ({e})")
cls.model.fit(*(x, y) if has_test else (cls.x, cls.y))
cls.reset_seeds()
state = {
"model": cls.model,
"template": hyperparameters,
"seed": seed,
}
with path.open("wb") as f:
pickle.dump(state, f)
cls.clean_acc = cls.model.accuracy(cls.x, cls.y).item()
# instantiate attacks and save attack parameters
cls.l0_max = cls.x.size(1)
cls.l0 = int(cls.l0_max * norm) + 1
cls.l2_max = maxs.sub(mins).norm(2).item()
cls.l2 = cls.l2_max * norm
cls.linf_max = 1
cls.linf = norm
cls.clip_min, cls.clip_max = clip
cls.p_min, cls.p_max = p_clip
cls.verbose = verbose
cls.atk_params = {
"alpha": alpha,
"epochs": epochs,
"model": cls.model,
"statistics": verbose,
"verbosity": 0.1 if verbose else 1,
}
cls.attacks = {
"apgdce": aml.attacks.apgdce(**cls.atk_params | {"epsilon": cls.linf}),
"apgddlr": aml.attacks.apgddlr(**cls.atk_params | {"epsilon": cls.linf}),
"bim": aml.attacks.bim(**cls.atk_params | {"epsilon": cls.linf}),
"cwl2": aml.attacks.cwl2(**cls.atk_params | {"epsilon": cls.l2}),
"df": aml.attacks.df(**cls.atk_params | {"epsilon": cls.l2}),
"fab": aml.attacks.fab(**cls.atk_params | {"epsilon": cls.l2}),
"jsma": aml.attacks.jsma(**cls.atk_params | {"epsilon": cls.l0}),
"pgd": aml.attacks.pgd(**cls.atk_params | {"epsilon": cls.linf}),
}
# determine available frameworks and set both art & foolbox classifiers
supported = ("advertorch", "art", "cleverhans", "foolbox", "torchattacks")
cls.available = [f for f in supported if importlib.util.find_spec(f)]
frameworks = ", ".join(cls.available)
cls.art_classifier = (
cls.build_art_classifier()
if cls in (IdentityTests, PerformanceTests, SpecialTests)
and "art" in cls.available
else None
)
cls.fb_classifier = (
cls.build_fb_classifier()
if cls in (IdentityTests, PerformanceTests, SpecialTests)
and "foolbox" in cls.available
else None
)
print(
"Module Setup complete. Testing Parameters:",
f"Dataset: {dataset}, Test Set: {has_test}",
f"Craftset shape: ({cls.x.size(0)}, {cls.x.size(1)})",
f"Model Type: {type(cls.model).__name__}",
f"Train Acc: {cls.model.res.training_accuracy.iloc[-1]:.1%}",
f"Craftset Acc: {cls.clean_acc:.1%}",
f"Attack Clipping Values: {clip_info}",
f"Attack Strength α: {cls.atk_params['alpha']}",
f"Attack Epochs: {cls.atk_params['epochs']}",
f"Max Norm Radii: l0: {cls.l0}, l2: {cls.l2:.3}, l∞: {cls.linf}",
f"Available Frameworks: {frameworks}",
sep="\n",
)
return None
@classmethod
def build_art_classifier(cls):
"""
This method instantiates an ART (PyTorch) classifier (as required by
ART evasion attacks).
:return: an ART (PyTorch) classifier
:rtype: art.estimators.classification PyTorchClassifier object
"""
from art.estimators.classification import PyTorchClassifier
return PyTorchClassifier(
model=cls.atk_params["model"].model,
clip_values=(cls.clip_min.max().item(), cls.clip_max.min().item()),
loss=cls.atk_params["model"].loss,
optimizer=cls.atk_params["model"].optimizer,
input_shape=(cls.x.size(1),),
nb_classes=cls.atk_params["model"].params["classes"],
)
@classmethod
def build_fb_classifier(cls):
"""
This method instantiates a Foolbox (PyTorch) classifier (as required by
Foolbox evasion attacks).
:return: a Foolbox (PyTorch) classifier
:rtype: Foolbox PyTorchModel object
"""
from foolbox import PyTorchModel
return PyTorchModel(
model=cls.atk_params["model"].model,
bounds=(cls.clip_min.min().item(), cls.clip_max.max().item()),
)
@classmethod
def l0_proj(cls, p):
"""
This method projects perturbation vectors so that they are complaint
with the specified l0 threat model. Specifically, the components of
perturbations that exceed the threat model are set to zero, sorted by
increasing magnitude.
:param p: perturbation vectors
:type p: torch Tensor object (n, m)
:return: threat-model-compliant perturbation vectors
:rtype: torch Tensor object (n, m)
"""
return p.scatter(1, p.abs().sort(1).indices[:, : p.size(1) - cls.l0], 0)
@classmethod
def l2_proj(cls, p):
"""
This method projects perturbation vectors so that they are complaint
with the specified l2 threat model Specifically,
perturbation vectors whose l2-norms exceed the threat model are
normalized by their l2-norms times epsilon.
:param p: perturbation vectors
:type p: torch Tensor object (n, m)
:return: threat-model-compliant perturbation vectors
:rtype: torch Tensor object (n, m)
"""
return p.renorm(2, 0, cls.l2)
@classmethod
def linf_proj(cls, p):
"""
This method projects perturbation vectors so that they are complaint
with the specified l∞ threat model Specifically,
perturbation vectors whose l∞-norms exceed the threat model are
are clipped to ±epsilon.
:param p: perturbation vectors
:type p: torch Tensor object (n, m)
:return: threat-model-compliant perturbation vectors
:rtype: torch Tensor object (n, m)
"""
return p.clamp(-cls.linf, cls.linf)
@classmethod
def reset_seeds(cls):
"""
This method resets the seeds for random number generators used
in attacks with randomized components throughtout adversarial machine
learning frameworks.
:return: None
:rtype: NoneType
"""
torch.manual_seed(cls.seed)
np.random.seed(cls.seed)
def apgdce(self, norm="inf"):
"""
This method crafts adversarial examples with APGD-CE (Auto-PGD with CE
loss) (https://arxiv.org/pdf/2003.01690.pdf). The supported frameworks
for APGD-CE include ART and Torchattacks. Notably, the Torchattacks
implementation assumes an image (batches, channels, width, height).
:param norm: norm to use (only modified for special tests)
:type norm: str or int
:return: APGD-CE adversarial examples
:rtype: tuple of tuples: torch Tensor object (n, m) and str
"""
(model, eps, eps_step, max_iter, nb_random_init, rho) = (
self.atk_params["model"],
{2: self.l2, "inf": self.linf}[norm],
self.atk_params["alpha"],
self.atk_params["epochs"],
self.attacks["apgdce"].num_restarts,
self.attacks["apgdce"].atk.traveler.optimizer.param_groups[0]["rho"],
)
art_adv = ta_adv = None
if "art" in self.available:
from art.attacks.evasion import AutoProjectedGradientDescent
print("Producing APGD-CE adversarial examples with ART...")
self.reset_seeds()
art_adv = (
torch.from_numpy(
AutoProjectedGradientDescent(
estimator=self.art_classifier,
norm=norm,
eps=eps,
eps_step=eps_step,
max_iter=max_iter,
targeted=False,
nb_random_init=nb_random_init,
batch_size=self.x.size(0),
loss_type="cross_entropy",
verbose=self.verbose,
).generate(x=self.x.clone().numpy())
),
"ART",
)
if "torchattacks" in self.available and hasattr(model, "shape"):
from torchattacks import APGD
print("Producing APGD-CE adversarial examples with Torchattacks...")
self.reset_seeds()
ta_x = self.x.clone().unflatten(1, model.shape)
ta_adv = (
APGD(
model=model,
norm={2: "L2", "inf": "Linf"}[norm],
eps=eps,
steps=max_iter,
n_restarts=nb_random_init,
seed=self.seed,
loss="ce",
eot_iter=1,
rho=rho,
verbose=self.verbose,
)(inputs=ta_x, labels=self.y)
.flatten(1)
.detach(),
"Torchattacks",
)
self.reset_seeds()
return tuple(fw for fw in (art_adv, ta_adv) if fw is not None)
def apgddlr(self, norm="inf"):
"""
This method crafts adversarial examples with APGD-DLR (Auto-PGD with
DLR loss) (https://arxiv.org/pdf/2003.01690.pdf). The supported
frameworks for APGD-DLR include ART and Torchattacks. Notably, DLR loss
is undefined for these frameworks when there are only two classes.
Moreover, the Torchattacks implementation assumes an image (batches,
channels, width, height).
:param norm: norm to use (only modified for special tests)
:type norm: str or int
:return: APGD-DLR adversarial examples
:rtype: tuple of tuples: torch Tensor object (n, m) and str
"""
(model, eps, eps_step, max_iter, nb_random_init, rho) = (
self.atk_params["model"],
{2: self.l2, "inf": self.linf}[norm],
self.atk_params["alpha"],
self.atk_params["epochs"],
self.attacks["apgddlr"].num_restarts,
self.attacks["apgddlr"].atk.traveler.optimizer.param_groups[0]["rho"],
)
art_adv = ta_adv = None
if "art" in self.available and self.art_classifier.nb_classes > 2:
from art.attacks.evasion import AutoProjectedGradientDescent
print("Producing APGD-DLR adversarial examples with ART...")
self.reset_seeds()
art_adv = (
torch.from_numpy(
AutoProjectedGradientDescent(
estimator=self.art_classifier,
norm=norm,
eps=eps,
eps_step=eps_step,
max_iter=max_iter,
targeted=False,
nb_random_init=nb_random_init,
batch_size=self.x.size(0),
loss_type="difference_logits_ratio",
verbose=self.verbose,
).generate(x=self.x.clone().numpy())
),
"ART",
)
if (
"torchattacks" in self.available
and self.art_classifier.nb_classes > 2
and hasattr(model, "shape")
):
from torchattacks import APGD
print("Producing APGD-DLR adversarial examples with Torchattacks...")
self.reset_seeds()
ta_x = self.x.clone().unflatten(1, model.shape)
ta_adv = (
APGD(
model=model,
norm={2: "L2", "inf": "Linf"}[norm],
eps=eps,
steps=max_iter,
n_restarts=nb_random_init,
seed=self.seed,
loss="dlr",
eot_iter=1,
rho=rho,
verbose=self.verbose,
)(inputs=ta_x, labels=self.y)
.flatten(1)
.detach(),
"Torchattacks",
)
self.reset_seeds()
return tuple(fw for fw in (art_adv, ta_adv) if fw is not None)
def bim(self, norm="inf"):
"""
This method crafts adversarial examples with BIM (Basic Iterative
Method) (https://arxiv.org/pdf/1611.01236.pdf). The supported
frameworks for BIM include AdverTorch, ART, CleverHans, Foolbox, and
Torchattacks. Notably, CleverHans does not have an explicit
implementation of BIM, so we call PGD, but with random initialization
disabled.
:param norm: norm to use (only modified for special tests)
:type norm: str or int
:return: BIM adversarial examples
:rtype: tuple of tuples: torch Tensor object (n, m) and str
"""
(model, eps, nb_iter, eps_iter) = (
self.atk_params["model"],
{2: self.l2, "inf": self.linf}[norm],
self.atk_params["epochs"],
self.atk_params["alpha"],
)
at_adv = art_adv = ch_adv = fb_adv = ta_adv = None
if "advertorch" in self.available:
if norm == "inf":
from advertorch.attacks import (
LinfBasicIterativeAttack as BasicIterativeAttack,
)
elif norm == 2:
from advertorch.attacks import (
L2BasicIterativeAttack as BasicIterativeAttack,
)
print("Producing BIM adversarial examples with AdverTorch...")
at_adv = (
BasicIterativeAttack(
predict=model,
loss_fn=torch.nn.CrossEntropyLoss(reduction="sum"),
eps=eps,
nb_iter=nb_iter,
eps_iter=eps_iter,
clip_min=self.clip_min,
clip_max=self.clip_max,
targeted=False,
).perturb(x=self.x.clone(), y=self.y.clone()),
"AdverTorch",
)
if "art" in self.available and norm == "inf":
from art.attacks.evasion import BasicIterativeMethod
print("Producing BIM adversarial examples with ART...")
art_adv = (
torch.from_numpy(
BasicIterativeMethod(
estimator=self.art_classifier,
eps=eps,
eps_step=eps_iter,
max_iter=nb_iter,
targeted=False,
batch_size=self.x.size(0),
verbose=self.verbose,
).generate(x=self.x.clone().numpy())
),
"ART",
)
if "cleverhans" in self.available:
from cleverhans.torch.attacks.projected_gradient_descent import (
projected_gradient_descent as basic_iterative_method,
)
print("Producing BIM adversarial examples with CleverHans...")
ch_adv = (
basic_iterative_method(
model_fn=model,
x=self.x.clone(),
eps=eps,
eps_iter=eps_iter,
nb_iter=nb_iter,
norm={2: 2, "inf": float("inf")}[norm],
clip_min=self.clip_min.max(),
clip_max=self.clip_max.min(),
y=self.y,
targeted=False,
rand_init=False,
rand_minmax=0,
sanity_checks=False,
).detach(),
"CleverHans",
)
if "foolbox" in self.available:
if norm == "inf":
from foolbox.attacks import (
LinfBasicIterativeAttack as BasicIterativeAttack,
)
elif norm == 2:
from foolbox.attacks import (
L2BasicIterativeAttack as BasicIterativeAttack,
)
print("Producing BIM adversarial examples with Foolbox...")
_, fb_adv, _ = BasicIterativeAttack(
rel_stepsize=None,
abs_stepsize=eps_iter,
steps=nb_iter,
random_start=False,
)(
self.fb_classifier,
self.x.clone(),
self.y.clone(),
epsilons=eps,
)
fb_adv = (fb_adv, "Foolbox")
if "torchattacks" in self.available and norm == "inf":
from torchattacks import BIM
print("Producing BIM adversarial examples with Torchattacks...")
ta_adv = (
BIM(
model=model,
eps=eps,
alpha=eps_iter,
steps=nb_iter,
)(inputs=self.x.clone(), labels=self.y),
"Torchattacks",
)
return tuple(
fw for fw in (at_adv, art_adv, ch_adv, fb_adv, ta_adv) if fw is not None
)
def cwl2(self, norm=2):
"""
This method crafts adversariale examples with CW-L2 (Carlini-Wagner
with l2 norm) (https://arxiv.org/pdf/1608.04644.pdf). The supported
frameworks for CW-L2 include AdverTorch, ART, CleverHans, Foolbox, and
Torchattacks. Notably, Torchattacks does not explicitly support binary
searching on c (it expects searching manually). Notably, while our
implementation shows competitive performance with low iterations, other
implementations (sans ART) require a substantial number of additional
iterations, so the minimum number of steps is set to be at least 300.
Moreover, the ART CW-L0 implementation assumes an image (batches,
channels, width, height). Finally, while ART does offer a CW-L∞, it
does not appear to be complete (in that it does not support binary
search on c at all), so it is omitted for comparison.
:param norm: norm to use (only modified for special tests)
:type norm: str or int
:return: CW-L2 adversarial examples
:rtype: tuple of tuples: torch Tensor object (n, m) and str
"""
(
variant,
model,
classes,
confidence,
learning_rate,
binary_search_steps,
max_iterations,
initial_const,
) = (
norm,
self.atk_params["model"],
self.atk_params["model"].params["classes"],
self.attacks["cwl2"].surface.loss.k,
self.atk_params["alpha"],
self.attacks["cwl2"].hparam_steps,
max(self.atk_params["epochs"], 300),
self.attacks["cwl2"].surface.loss.c.item(),
)
at_adv = art_adv = ch_adv = fb_adv = ta_adv = None
if "advertorch" in self.available and norm == 2:
from advertorch.attacks import CarliniWagnerL2Attack
print(f"Producing CW-L{variant} adversarial examples with AdverTorch...")
at_adv = (
CarliniWagnerL2Attack(
predict=model,
num_classes=classes,
confidence=confidence,
targeted=False,
learning_rate=learning_rate,
binary_search_steps=binary_search_steps,
max_iterations=max_iterations,
abort_early=True,
initial_const=initial_const,
clip_min=self.clip_min,
clip_max=self.clip_max,
).perturb(x=self.x.clone(), y=self.y.clone()),
"AdverTorch",
)
if "art" in self.available and norm == 2 or hasattr(model, "shape"):
if norm == 0:
from art.attacks.evasion import CarliniL0Method as CarliniWagner
elif norm == 2:
from art.attacks.evasion import CarliniL2Method as CarliniWagner
print(f"Producing CW-L{variant} adversarial examples with ART...")
art_adv = (
torch.from_numpy(
CarliniWagner(
classifier=self.art_classifier,
confidence=confidence,
targeted=False,
learning_rate=learning_rate,
binary_search_steps=binary_search_steps,
max_iter=max_iterations,
initial_const=initial_const,
max_halving=binary_search_steps // 2,
max_doubling=binary_search_steps // 2,
batch_size=self.x.size(0),
verbose=self.verbose,
).generate(x=self.x.clone().numpy())
),
"ART",
)
if "cleverhans" in self.available and norm == 2:
from cleverhans.torch.attacks.carlini_wagner_l2 import carlini_wagner_l2
print(f"Producing CW-L{variant} adversarial examples with CleverHans...")
ch_adv = (
carlini_wagner_l2(
model_fn=model,
x=self.x.clone(),
n_classes=classes,
y=self.y,
lr=learning_rate,
confidence=confidence,
clip_min=self.clip_min.max(),
clip_max=self.clip_max.min(),
initial_const=initial_const,
binary_search_steps=binary_search_steps,
max_iterations=max_iterations,
).detach(),
"CleverHans",
)
if "foolbox" in self.available and norm == 2:
from foolbox.attacks import L2CarliniWagnerAttack
print(f"Producing CW-L{variant} adversarial examples with Foolbox...")
_, fb_adv, _ = L2CarliniWagnerAttack(
binary_search_steps=binary_search_steps,
steps=max_iterations,
stepsize=learning_rate,
confidence=confidence,
initial_const=initial_const,
abort_early=True,
)(
self.fb_classifier,
self.x.clone(),
self.y.clone(),
epsilons=self.l2,
)
fb_adv = (fb_adv, "Foolbox")
if "torchattacks" in self.available and norm == 2:
from torchattacks import CW
print(f"Producing CW-L{variant} adversarial examples with Torchattacks...")
ta_adv = CW(
model=model,
c=initial_const,
kappa=confidence,
steps=max_iterations,
lr=learning_rate,
)(inputs=self.x.clone(), labels=self.y)
# torchattack's implementation can return nans
ta_adv = (torch.where(ta_adv.isnan(), self.x, ta_adv), "Torchattacks")
return tuple(
fw for fw in (at_adv, art_adv, ch_adv, fb_adv, ta_adv) if fw is not None
)
def df(self, norm=2):
"""
This method crafts adversarial examples with DF (DeepFool)
(https://arxiv.org/pdf/1611.01236.pdf). The supported frameworks for DF
include ART, Foolbox, and Torchattacks. Notably, the DF implementation
in ART, Foolbox, and Torchattacks have an overshoot parameter which we
set to aml DF's learning rate alpha minus one (not to be confused with
the epsilon parameter used in aml, which governs the norm-ball size).
:param norm: norm to use (only modified for special tests)
:type norm: str or int
:return: DeepFool adversarial examples
:rtype: tuple of tuples: torch Tensor object (n, m) and str
"""
model, max_iter, epsilon, nb_grads, epsilons = (
self.atk_params["model"],
self.atk_params["epochs"],
self.attacks["df"].params["α"] - 1,
self.atk_params["model"].params["classes"],
{2: self.l2, "inf": self.linf}[norm],
)
art_adv = fb_adv = ta_adv = None
if "art" in self.available and norm == 2:
from art.attacks.evasion import DeepFool
print("Producing DF adversarial examples with ART...")
art_adv = (
torch.from_numpy(
DeepFool(
classifier=self.art_classifier,
max_iter=max_iter,
epsilon=epsilon,
nb_grads=nb_grads,
batch_size=self.x.size(0),
verbose=self.verbose,
).generate(x=self.x.clone().numpy())
),
"ART",
)
if "foolbox" in self.available:
if norm == 2:
from foolbox.attacks import L2DeepFoolAttack as DeepFoolAttack
elif norm == "inf":
from foolbox.attacks import LinfDeepFoolAttack as DeepFoolAttack
print("Producing DF adversarial examples with Foolbox...")
_, fb_adv, _ = DeepFoolAttack(
steps=max_iter,
candidates=nb_grads,
overshoot=epsilon,
loss="logits",
)(
self.fb_classifier,
self.x.clone(),
self.y.clone(),
epsilons=epsilons,
)
fb_adv = (fb_adv, "Foolbox")
if "torchattacks" in self.available and norm == 2:
from torchattacks import DeepFool
print("Producing DF adversarial examples with Torchattacks...")
ta_adv = DeepFool(
model=model,
steps=max_iter,
overshoot=epsilon,
)(inputs=self.x.clone(), labels=self.y)
# torchattack's implementation can return nans
ta_adv = (torch.where(ta_adv.isnan(), self.x, ta_adv), "Torchattacks")
return tuple(fw for fw in (art_adv, fb_adv, ta_adv) if fw is not None)
def fab(self, norm=2):
"""
This method crafts adversarial examples with FAB (Fast Adaptive
Boundary) (https://arxiv.org/pdf/1907.02044.pdf). The supported
frameworks for FAB include AdverTorch and Torchattacks.
:param norm: norm to use (only modified for special tests)
:type norm: str or int
:return: FAB adversarial examples
:rtype: tuple of tuples: torch Tensor object (n, m) and str
"""
(model, n_restarts, n_iter, eps, alpha, eta, beta, n_classes) = (
self.atk_params["model"],
self.attacks["fab"].params["num_restarts"] + 1,
self.atk_params["epochs"],
{2: self.l2, "inf": self.linf}[norm],
self.attacks["fab"].traveler.optimizer.param_groups[0]["alpha_max"],
self.attacks["fab"].atk.params["α"],
self.attacks["fab"].traveler.optimizer.param_groups[0]["beta"],
self.atk_params["model"].params["classes"],
)
at_adv = ta_adv = None
if "advertorch" in self.available:
from advertorch.attacks import FABAttack
print("Producing FAB adversarial examples with AdverTorch...")
self.reset_seeds()
at_adv = (
FABAttack(
predict=model,
norm={2: "L2", "inf": "Linf"}[norm],
n_restarts=n_restarts,
n_iter=n_iter,
eps=eps,
alpha_max=alpha,
eta=eta,
beta=beta,
verbose=self.verbose,
).perturb(x=self.x.clone(), y=self.y.clone()),
"AdverTorch",
)
if "torchattacks" in self.available:
from torchattacks import FAB
print("Producing FAB adversarial examples with Torchattacks...")
self.reset_seeds()
ta_adv = (
FAB(
model=model,
norm={2: "L2", "inf": "Linf"}[norm],
eps=eps,
steps=self.atk_params["epochs"],
n_restarts=n_restarts,
alpha_max=alpha,
eta=eta,
beta=beta,
verbose=self.verbose,
seed=self.seed,
multi_targeted=False,
n_classes=n_classes,
)(inputs=self.x.clone(), labels=self.y),
"Torchattacks",
)
self.reset_seeds()
return tuple(fw for fw in (at_adv, ta_adv) if fw is not None)
def jsma(self):
"""
This method crafts adversarial examples with JSMA (Jacobian Saliency
Map Approach) (https://arxiv.org/pdf/1511.07528.pdf). The supported
frameworks for the JSMA include AdverTorch and ART. Notably, the JSMA
implementation in AdverTorch and ART both assume the l0-norm is passed
in as a percentage (which is why we pass in linf) and we set theta to
be 1 since features can only be perturbed once. moreover, the
advertorch implementation: (1) does not suport an untargetted scheme
(so we supply random targets), and (2) computes every pixel pair at
once, often leading to memory crashes (e.g., it'll terminate on a 16GB
system with MNIST).
:return: JSMA adversarial examples
:rtype: tuple of tuples: torch Tensor object (n, m) and str
"""
(model, num_classes, gamma, theta) = (
self.atk_params["model"],
self.atk_params["model"].params["classes"],
self.linf,
1,
)
at_adv = art_adv = None
if "advertorch" in self.available and self.x.size(1) < 784:
from advertorch.attacks import JacobianSaliencyMapAttack
print("Producing JSMA adversarial examples with AdverTorch...")
at_adv = (
JacobianSaliencyMapAttack(
predict=model,
num_classes=num_classes,
clip_min=self.clip_min,
clip_max=self.clip_max,
gamma=gamma,
theta=theta,
).perturb(
x=self.x.clone(), y=torch.randint(num_classes, self.y.size())
),
"AdverTorch",
)
if "art" in self.available:
from art.attacks.evasion import SaliencyMapMethod
print("Producing JSMA adversarial examples with ART...")
art_adv = (
torch.from_numpy(
SaliencyMapMethod(
classifier=self.art_classifier,
theta=theta,
gamma=gamma,
batch_size=self.x.size(0),
verbose=self.verbose,
).generate(x=self.x.clone().numpy())
),
"ART",
)
return tuple(fw for fw in (at_adv, art_adv) if fw is not None)
def pgd(self, norm="inf"):
"""
This method crafts adversarial examples with PGD (Projected Gradient
Descent)) (https://arxiv.org/pdf/1706.06083.pdf). The supported
frameworks for PGD include AdverTorch, ART, CleverHans, and
Torchattacks. Notably, the Torchattacks PGD l2 implementation assumes
an image (batches, channels, width, height).
:param norm: norm to use (only modified for special tests)
:type norm: str or int
:return: PGD adversarial examples
:rtype: tuple of tuples: aml Attack object & torch Tensor object (n, m)
"""
(model, eps, nb_iter, eps_iter) = (
self.atk_params["model"],
{2: self.l2, "inf": self.linf}[norm],
self.atk_params["epochs"],
self.atk_params["alpha"],
)
at_adv = art_adv = ch_adv = fb_adv = ta_adv = None
if "advertorch" in self.available:
from advertorch.attacks import PGDAttack
print("Producing PGD adversarial examples with AdverTorch...")
self.reset_seeds()
at_adv = (
PGDAttack(
predict=model,
loss_fn=torch.nn.CrossEntropyLoss(reduction="sum"),
eps=eps,
nb_iter=nb_iter,
eps_iter=eps_iter,
rand_init=True,
clip_min=self.clip_min,
clip_max=self.clip_max,
ord={2: 2, "inf": float("inf")}[norm],
targeted=False,
).perturb(x=self.x.clone(), y=self.y.clone()),
"AdverTorch",
)
if "art" in self.available:
from art.attacks.evasion import ProjectedGradientDescent
print("Producing PGD adversarial examples with ART...")
self.reset_seeds()
art_adv = (
torch.from_numpy(
ProjectedGradientDescent(
estimator=self.art_classifier,
norm=norm,
eps=eps,
eps_step=eps_iter,
decay=None,
max_iter=nb_iter,
targeted=False,
num_random_init=1,
batch_size=self.x.size(0),
random_eps=True,
summary_writer=False,
verbose=self.verbose,
).generate(x=self.x.clone().numpy())
),
"ART",
)
if "cleverhans" in self.available:
from cleverhans.torch.attacks.projected_gradient_descent import (
projected_gradient_descent,
)
print("Producing PGD adversarial examples with CleverHans...")
self.reset_seeds()
ch_adv = (
projected_gradient_descent(
model_fn=model,