-
Notifications
You must be signed in to change notification settings - Fork 1
/
AdversarialAttacks.py
1527 lines (1156 loc) · 69.1 KB
/
AdversarialAttacks.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
import torch.nn.functional as F
from typing import List, Tuple
from tqdm.notebook import tqdm
from scipy import signal
import librosa
import numpy as np
import torch
import scipy
from functools import reduce
class ASRAttacks(object):
'''
Adversarial Attack on ASR model. Right now it is specifically implemented for
wav2vec2.0 model from torchaudio hub.
It support the following attacks:
1) Fast Gradient Sign Method (FGSM)
2) Basic Iterative Moment (BIM)
3) Projected Gradient Descent (PGD)
4) Carlini and Wagner Attack (CW)
5) Imperceptible ASR Attack (I-ASR)
'''
def __init__(self, model, device, labels: List[str]):
'''
Creates an instance of the class "ASRAttacks".
INPUT ARGUMENTS:
model : The model on which the attack is supposed to be performed.
device : Either 'cpu' if we have only CPU or 'cuda' if we have GPU
labels : Label/Dictionary of the model.
'''
self.model = model
self.device = device
self.labels = labels
def _encode_transcription(self, transcription: List[str]) -> List[str]: #in future add dictionary input over here
'''
Will encode transcription according to the dictionary of the model.
INPUT ARGUMENTS:
transcription : transcription in a list. Ex: ["my name is mango"].
CAUTION:
Please make sure these characters are also present in the
dictionary of the model also.
'''
# Define the dictionary
dictionary = {'-': 0, '|': 1, 'E': 2, 'T': 3, 'A': 4,
'O': 5, 'N': 6, 'I': 7, 'H': 8, 'S': 9,
'R': 10, 'D': 11, 'L': 12, 'U': 13, 'M': 14,
'W': 15, 'C': 16, 'F': 17, 'G': 18, 'Y': 19,
'P': 20, 'B': 21, 'V': 22, 'K': 23, "'": 24,
'X': 25, 'J': 26, 'Q': 27, 'Z': 28} #wav2vec uses this dictionary
# Convert transcription string to list of characters
chars = list(transcription)
# Encode each character using the dictionary
encoded_chars = [dictionary[char] for char in chars]
# Concatenate the encoded characters to form the final encoded transcription
encoded_transcription = torch.tensor(encoded_chars)
# Returning the encoded transcription
return encoded_transcription
def FGSM_ATTACK(self, input__: torch.Tensor, target: List[str]= None,
epsilon: float = 0.2, targeted: bool = False) -> np.ndarray:
'''
Simple fast gradient sign method attack is implemented which is the simplest
adversarial attack in this domain.
For more information, see the paper: https://arxiv.org/pdf/1412.6572.pdf
INPUT ARGUMENTS:
input__ : Input audio. Ex: Tensor[0.1,0.3,...] or (samples,)
Type: torch.Tensor
target : Target transcription (needed if the you want targeted
attack) Ex: ["my name is mango."].
Type: List[str]
CAUTION:
Please make sure these characters are also present in the
dictionary of the model also.
epsilon : Noise controlling parameter or step size.
Type: float
targeted : If the attack should be targeted towards your desired
transcription or not.
Type: bool
CAUTION:
Please make to pass your targetted
transcription also in this case).
RETURNS:
np.ndarray : Perturbed audio
'''
# Cloning the original audio
input_ = input__.clone()
# Making our input differentiable
input_.requires_grad = True
# Forward Pass
output, _ = self.model(input_.to(self.device))
# Softmax Activation for computing logits
output = F.log_softmax(output, dim=-1)
if targeted: # Condition for checking if the user wants 'targeted' attack to be performed
# Assert that in targeted attack we have target present before we proceed
assert target != None, "Target should not be 'None' in targeted attack. Please pass a target transcription."
# Encode the target transcription
encoded_transcription = self._encode_transcription(target)
# Convert the target transcription to a PyTorch tensor
target = torch.from_numpy(np.array(encoded_transcription)).to(self.device).long()
# Computing the CTC Loss
output_lengths = torch.tensor([output.shape[1]], dtype=torch.long).to(self.device)
output = output.transpose(0, 1)
target_lengths = torch.tensor([len(encoded_transcription)], dtype=torch.long).to(self.device)
loss = F.ctc_loss(output, target, output_lengths, target_lengths, blank=0, reduction='mean')
# Computing gradient of our input w.r.t loss
loss.backward()
# If 'targeted' then we will minimize our loss to the respective target transcription
sign_grad = -input_.grad.sign()
# Calculating 'sign' of the FGSM attack and multiplying it with our small epsilon step
perturbation = epsilon * sign_grad
# Adding perturbation in the original input to make adversarial example
perturbed_input = input_ + perturbation
# Clamping the audio in original audio range (-1,1)
perturbed_input = torch.clamp(perturbed_input, -1, 1)
# Returning perturbed audio
return perturbed_input.detach().numpy()
else: # Condition for checking if the user wants 'untargeted' attack to be performed
# Using the model's transcription as target in untargeted attack
untarget = list(self.INFER(input_.to(self.device)))
# Encode the target transcription
encoded_transcription = self._encode_transcription(untarget)
# Convert the target transcription to a PyTorch tensor
target = torch.from_numpy(np.array(encoded_transcription)).to(self.device).long()
# Computing CTC Loss
output_length = torch.tensor([output.shape[1]], dtype=torch.long).to(self.device)
output = output.transpose(0, 1)
target_length = torch.tensor([len(encoded_transcription)], dtype=torch.long).to(self.device)
loss = F.ctc_loss(output, target, output_length, target_length, blank=0, reduction='mean')
# Computing gradient of our input w.r.t loss
loss.backward()
# If untargeted then we will maximize our loss
sign_grad = input_.grad.sign()
# Calculating 'sign' of the FGSM attack and multiplying it with our small epsilon step
perturbation = epsilon * sign_grad
# Adding perturbation in the original input to make adversarial example
perturbed_input = input_ + perturbation
# Clamping the audio in original audio range (-1,1)
perturbed_input = torch.clamp(perturbed_input, -1, 1)
# Returning perturbed audio
return perturbed_input.detach().numpy()
def BIM_ATTACK(self, input__: torch.Tensor, target: List[str] = None,
epsilon: float = 0.2, alpha: float = 0.1,
num_iter: int = 10, nested: bool = True,targeted: bool = False, early_stop: bool = False) -> np.ndarray:
'''
Basic Itertive Moment attack is implemented which is simple Fast Gradient
Sign Attack but in loop.
For more information, see the paper: https://arxiv.org/abs/1607.02533
INPUT ARGUMENTS:
input__ : Input audio. Ex: Tensor[0.1,0.3,...] or (samples,)
Type: torch.Tensor
target : Target transcription (needed if the you want targeted
attack) Ex: ["my name is mango."].
Type: List[str]
CAUTION:
Please make sure these characters are also present in the
dictionary of the model also.
epsilon : Maximum allowable noise for our audio.
Type: float
alpha : Step size for noise to be added in each iteration
Type: float
num_iter : Number of iteration of attack
Type: int
nested : if this attack in being run in a for loop with tqdm
Type: bool
targeted : If the attack should be targeted towards your desired
transcription or not.
Type: bool
CAUTION:
Please make to pass your targetted
transcription also in this case).
early_stop : If user wants to stop the attack early if the attack reaches the target transcription before the total number of iterations.
Type: bool
RETURNS:
np.ndarray : Perturbed audio
'''
# Cloning the original given audio
input_ = input__.clone()
# Making our input differentiable
input_.requires_grad = True
# Storing input in variable to add in noise later
original_input = input_.clone()
# Checking if the user is running this code in for loop or not
if nested:
leave = False
else:
leave = True
if targeted: # Condition for checking if the user wants 'targeted' attack to be performed
# Assert that in targeted attack we have target present before we proceed
assert target != None, "Target should not be 'None' in targeted attack. Please pass a target transcription."
# Encode the target transcription
encoded_transcription = self._encode_transcription(target)
for i in tqdm(range(num_iter), colour="red", leave = leave):
# Forward pass
output, _ = self.model(input_.to(self.device))
# Softmax Activation for computing logits
output = F.log_softmax(output, dim=-1)
# Convert the target transcription to a PyTorch tensor
target_ = torch.from_numpy(np.array(encoded_transcription)).to(self.device).long()
# Computing the CTC Loss
output_length = torch.tensor([output.shape[1]], dtype=torch.long).to(self.device)
output = output.transpose(0, 1)
target_length = torch.tensor([len(encoded_transcription)], dtype=torch.long).to(self.device)
loss = F.ctc_loss(output, target_, output_length, target_length, blank=0, reduction='mean')
# Computing gradients of our input w.r.t loss
loss.backward()
# If targeted then we will minimize our loss
sign_grad = -input_.grad.data
# Adding perturbation in our input
perturbed_input = original_input + (alpha * sign_grad.detach().sign())
# Clamping the perturbation in range (-eps, eps)
perturbation = torch.clamp(perturbed_input - original_input, -epsilon, epsilon)
# Clamping the overall perturbated audio in the original audio range (-1, 1)
input_.data = torch.clamp(input_ + perturbation, -1, 1)
if early_stop: # if user have enabled early stopping then do the following tasks or else run all iterations
# Storing model's current inference and target transcription in new variables for computing WER
string1 = list(filter(lambda x: x!= '',self.INFER(input_).split("|")))
string2 = list(reduce(lambda x,y: x+y, target).split("|"))
# Computing WER while also making sure length of both strings is same
# This will also early stop the attack if we reach out target transcription
# before the completion of all iterations because further iterations will further
# increase noise in the original audio leading to bad/low SNR
if len(string1) == len(string2):
if self._wer(string1, string2)[0] == 0:
print("Breaking for loop because targeted Attack is performed successfully !")
return input_.detach().numpy()
elif len(string1) > len(string2):
diff = len(string1) - len(string2)
for i in range(diff):
string2.append("<eps>")
if self._wer(string1, string2)[0] == 0:
print("Breaking for loop because targeted Attack is performed successfully !")
return input_.detach().numpy()
else:
diff = len(string2) - len(string1)
for i in range(diff):
string1.append("<eps>")
if self._wer(string1, string2)[0] == 0:
print("Breaking for loop because targeted Attack is performed successfully !")
return input_.detach().numpy()
# Making gradients of input zero
input_.grad.zero_()
# Returning perturbed audio after the loop ends
return input_.detach().numpy()
else: # Condition for checking if the user wants 'untargeted' attack to be performed
# Using the model's transcription as target in untargeted attack
target = self.INFER(input_.to(self.device))
for i in tqdm(range(num_iter), colour="red", leave = leave):
# Using the model's transcription as target in untargeted attack
untarget = self.INFER(input_.to(self.device))
# Encode the target transcription
encoded_transcription = self._encode_transcription(untarget)
# Forward pass
output, _ = self.model(input_.to(self.device))
# Softmax Activation for computing logits
output = F.log_softmax(output, dim=-1)
# Convert the target transcription to a PyTorch tensor
target_ = torch.from_numpy(np.array(encoded_transcription)).to(self.device).long()
# Computing the CTC Loss
output_length = torch.tensor([output.shape[1]], dtype=torch.long).to(self.device)
output = output.transpose(0, 1)
target_length = torch.tensor([len(encoded_transcription)], dtype=torch.long).to(self.device)
loss = F.ctc_loss(output, target_, output_length, target_length, blank=0, reduction='mean')
# Computing gradients of our input w.r.t loss
loss.backward()
# If untargeted then we will maximize our loss
sign_grad = input_.grad.data
# Adding perturbation in our input
perturbed_input = original_input + (alpha * sign_grad.detach().sign())
# Clamping the perturbation in range (-eps, eps)
perturbation = torch.clamp(perturbed_input - original_input, -epsilon, epsilon)
# Clamping the overall perturbated audio in the original audio range (-1, 1)
input_.data = torch.clamp(input_ + perturbation, -1, 1)
if early_stop: # if user have enabled early stopping then do the following tasks or else run all iterations
# Storing model's current inference and target transcription in new variables for computing WER
string1 = list(self.INFER(input_).split("|"))
string2 = list(target.split("|"))
# Removing empty spaces (if any) that cause error when computing WER
string1 = list(filter(lambda x: x!= '', string1))
string2 = list(filter(lambda x: x!= '', string2))
# Computing WER while also making sure length of both strings is same
# This will also early stop the attack if we reach out target transcription
# before the completion of all iteration because further iteration will further
# increase noise in the original audio leading to bad/low SNR
if len(string1) == len(string2):
if self._wer(string1, string2)[0] == 1:
print("Breaking for loop because untargeted Attack is performed successfully !")
return input_.detach().numpy()
elif len(string1) > len(string2):
diff = len(string1) - len(string2)
for i in range(diff):
string2.append("<eps>")
if self._wer(string1, string2)[0] == 1:
print("Breaking for loop because untargeted Attack is performed successfully !")
return input_.detach().numpy()
else:
diff = len(string2) - len(string1)
for i in range(diff):
string1.append("<eps>")
if self._wer(string1, string2)[0] == 1:
print("Breaking for loop because untargeted Attack is performed successfully !")
return input_.detach().numpy()
# Making gradients of input zero
input_.grad.zero_()
# Returning perturbed audio after the loop ends
return input_.detach().numpy()
def PGD_ATTACK(self, input__: torch.Tensor, target: List[str] = None,
epsilon: float = 0.3, alpha: float = 0.01, num_iter: int = 40,
nested: bool = True,targeted: bool = False, early_stop: bool = False) -> np.ndarray:
'''
Projected Gradient Descent attack is implemented which in simple terms is more
advanced version of BIM. In this attack we project our perturbation back to
some Lp norm and find perturbations in that particular region.
For more information, see the paper: https://arxiv.org/abs/1706.06083
INPUT ARGUMENTS:
input__ : Input audio. Ex: Tensor[0.1,0.3,...] or (samples,)
Type: torch.Tensor
target : Target transcription (needed if the you want targeted
attack) Ex: ["my name is mango."].
Type: List[str]
CAUTION:
Please make sure these characters are also present in the
dictionary of the model also.
epsilon : Noise controlling parameter.
Type: float
alpha : Step size for noise to be added in each iteration
Type: float
num_iter : Number of iteration of attack
Type: int
nested : if this attack in being run in a for loop with tqdm
Type: bool
targeted : If the attack should be targeted towards your desired
transcription or not.
Type: bool
CAUTION:
Please make to pass your targetted
transcription also in this case).
early_stop : If user wants to stop the attack early if the attack reaches the target transcription before the total number of iterations.
Type: bool
RETURNS:
np.ndarray : Perturbed audio
'''
# Cloning the original audio
input_ = input__.clone().to(self.device)
# Making a zero differentiable tensor of same shape as input
delta = torch.zeros_like(input_, requires_grad=True).to(self.device)
# checking if the user is running this code in for loop or not
if nested:
leave = False
else:
leave = True
if targeted: # Condition for checking if the user wants 'targeted' attack to be performed
# Assert that in targeted attack we have target present before we proceed
assert target != None, "Target should not be 'None' in targeted attack. Please pass a target transcription."
# Encode the target transcription
encoded_transcription = self._encode_transcription(target)
# Convert the target transcription to a PyTorch tensor
target_ = torch.from_numpy(np.array(encoded_transcription)).to(self.device).long()
for i in tqdm(range(num_iter), colour = 'red', leave = leave):
# Forward pass
output, _ = self.model(input_ + delta)
# Softmax Activation for computing logits
output = F.log_softmax(output, dim=-1)
# Computing CTC loss
output_length = torch.tensor([output.shape[1]], dtype=torch.long).to(self.device)
output = output.transpose(0, 1)
target_length = torch.tensor([len(encoded_transcription)], dtype=torch.long).to(self.device)
loss = F.ctc_loss(output, target_, output_length, target_length, blank=0, reduction='mean')
# Computing gradients of our input w.r.t loss
loss.backward()
# Update delta with gradient sign
sign = -1 # Negative sign because of targeted attack
delta.data = (delta + alpha * sign * delta.grad.detach().sign())
# Perform projection of delta onto Lp ball
delta.data = delta.data.clamp(-epsilon, epsilon)
if early_stop: # if user have enabled early stopping then do the following tasks or else run all iterations
# Storing model's current inference and target transcription in new variables for computing WER
string1 = list(filter(lambda x: x!= '',self.INFER(input_ + delta).split("|")))
string2 = list(reduce(lambda x,y: x+y, target).split("|"))
# Computing WER while also making sure length of both strings is same
# This will also early stop the attack if we reach out target transcription
# before the completion of all iteration because further iteration will further
# increase noise in the original audio leading to bad/low SNR
if len(string1) == len(string2):
if self._wer(string1, string2)[0] == 0:
print("Breaking for loop because targeted Attack is performed successfully !")
adv_example = input_ + delta
return adv_example.detach().cpu().numpy()
elif len(string1) > len(string2):
diff = len(string1) - len(string2)
for i in range(diff):
string2.append("<eps>")
if self._wer(string1, string2)[0] == 0:
print("Breaking for loop because targeted Attack is performed successfully !")
adv_example = input_ + delta
return adv_example.detach().cpu().numpy()
else:
diff = len(string2) - len(string1)
for i in range(diff):
string1.append("<eps>")
if self._wer(string1, string2)[0] == 0:
print("Breaking for loop because targeted Attack is performed successfully !")
adv_example = input_ + delta
return adv_example.detach().cpu().numpy()
# Zeroing the gradients so that they don't accumulate
delta.grad.zero_()
# Returning perturbed audio after the loop ends
adv_example = input_ + delta
return adv_example.detach().cpu().numpy()
else: # Condition for checking if the user wants 'untargeted' attack to be performed
# We will use the original input's transcription as our target to move away from
target = self.INFER(input_)
for i in tqdm(range(num_iter), colour = 'red', leave = leave):
# We will use the original input's transcription as our target to move away from
untarget = self.INFER(input_)
# Encode the target transcription
encoded_transcription = self._encode_transcription(untarget)
# Convert the target transcription to a PyTorch tensor
target_ = torch.from_numpy(np.array(encoded_transcription)).to(self.device).long()
# Forward pass
output, _ = self.model(input_ + delta)
# Softmax Activation for computing logits
output = F.log_softmax(output, dim=-1)
# Computing CTC loss
output_length = torch.tensor([output.shape[1]], dtype=torch.long).to(self.device)
output = output.transpose(0, 1)
target_length = torch.tensor([len(encoded_transcription)], dtype=torch.long).to(self.device)
loss = F.ctc_loss(output, target_, output_length, target_length, blank=0, reduction='mean')
# Computing gradients of our input w.r.t loss
loss.backward()
# Update delta with gradient sign
sign = 1 # Positive sign because of untargeted attack
delta.data = (delta + alpha * sign * delta.grad.detach().sign())
# Perform projection of delta onto Lp ball
delta.data = delta.data.clamp(-epsilon, epsilon)
if early_stop: # if user have enabled early stopping then do the following tasks or else run all iterations
# Storing model's current inference and target transcription in new variables for computing WER
string1 = list(filter(lambda x: x!= '',self.INFER(input_ + delta).split("|")))
string2 = list(reduce(lambda x,y: x+y, target).split("|"))
# Computing WER while also making sure length of both strings is same
# This will also early stop the attack if we reach out target transcription
# before the completion of all iteration because further iteration will further
# increase noise in the original audio leading to bad/low SNR
if len(string1) == len(string2):
if self._wer(string1, string2)[0] == 1:
print("Breaking for loop because untargeted Attack is performed successfully !")
adv_example = input_ + delta
return adv_example.detach().cpu().numpy()
elif len(string1) > len(string2):
diff = len(string1) - len(string2)
for i in range(diff):
string2.append("<eps>")
if self._wer(string1, string2)[0] == 1:
print("Breaking for loop because untargeted Attack is performed successfully !")
adv_example = input_ + delta
return adv_example.detach().cpu().numpy()
else:
diff = len(string2) - len(string1)
for i in range(diff):
string1.append("<eps>")
if self._wer(string1, string2)[0] == 1:
print("Breaking for loop because untargeted Attack is performed successfully !")
adv_example = input_ + delta
return adv_example.detach().cpu().numpy()
# Zeroing the gradients so that they don't accumulate
delta.grad.zero_()
# Returning perturbed audio after the loop ends
adv_example = input_ + delta
return adv_example.detach().cpu().numpy()
def CW_ATTACK(self, input__: torch.Tensor, target: List[str] = None,
epsilon: float = 0.3, c: float = 1e-4, learning_rate: float = 0.01,
num_iter: int = 1000, decrease_factor_eps: float = 1,
num_iter_decrease_eps: int = 10, optimizer: str = None,
nested: bool = True, early_stop: bool = True, search_eps: bool = False,
targeted: bool = False, internal_call = False) -> np.ndarray:
'''
Implements the Carlini and Wagner attack, the strongest white box
adversarial attack. This attack uses an optimization strategy to find the
adversarial transcription while keeping the perturbation as low as possible.
For more information, see the paper: https://arxiv.org/pdf/1801.01944.pdf
INPUT ARGUMENTS:
input__ : Input audio. Ex: Tensor[0.1,0.3,...] or (samples,)
Type: torch.Tensor
target : Target transcription (needed if the you want targeted
attack) Ex: ["my name is mango."].
Type: List[str]
CAUTION:
Please make sure these characters are also present in the
dictionary of the model also.
epsilon : Noise controlling parameter.
Type: float
c : Regularization term controlling factor.
Type: float
learning_rate : learning_rate of optimizer.
Type: float
num_iter : Number of iteration of attack.
Type: int
decrease_factor_eps : Factor to decrease epsilon during search
Type: float
num_iter_decrease_eps : Number of iterations after which to decrease epsilon
Type: int
optimizer : Name of the optimizer to use for the attack.
Type: str
nested : if this attack in being run in a for loop with tqdm
Type: bool
early_stop : if the user wants to end the attack as soon as the attack
gets the target transcription.
Type: bool
search_eps : if the user wants the attack to search for the epsilon value
on its own provided the initial epsilon value of large.
Type: bool
targeted : If the attack should be targeted towards your desired
transcription or not.
Type: bool
CAUTION:
Please make to pass your targetted
transcription also in this case).
internal_call : If the CW is being called internally by another attack.
Type: bool
RETURNS:
np.ndarray : Perturbed audio
'''
# checking if user accidentally passed wrong arugments or not
if early_stop == True and search_eps == True:
raise Exception("Early stop and Epsilon search arguments, both cannot be true at the same time.")
if epsilon <= 0:
raise Exception("Value of epsilon should be greater than 0")
# Convert the input audio to a PyTorch tensor
input_audio = input__.clone().to(self.device).float()
# Making audio differentiable
input_audio.requires_grad_()
# Cloning the original audio
input_audio_orig = input_audio.clone().to(self.device)
# Define the optimizer
if optimizer == "Adam":
optimizer = torch.optim.Adam([input_audio], lr=learning_rate)
else:
optimizer = torch.optim.SGD([input_audio], lr=learning_rate)
# Setting our inital parameters
successful_attack = False
num_successful_attacks = 0
# Checking if the user wants to run this code in for loop or not
if nested:
leave = False
descrip = None
if internal_call:
descrip = "*"*5+"Attack Stage 1"+"*"*5
else:
leave = True
descrip = None
if targeted:
# Making sure target is given in targeted attack
assert target is not None, "Target should not be 'None' in a targeted attack. Please pass a target transcription."
# Encode the target transcription
encoded_transcription = self._encode_transcription(target)
# Convert the target transcription to a PyTorch tensor
target_tensor = torch.from_numpy(np.array(encoded_transcription)).to(self.device).long()
for i in tqdm(range(num_iter), colour="red", leave = leave, desc = descrip):
# Zero the gradients
optimizer.zero_grad()
# Compute the model’s prediction
output, _ = self.model(input_audio)
# Softmax Activation for computing logits
output = F.log_softmax(output, dim=-1)
# Compute the CTC loss function
output_length = torch.tensor([output.shape[1]], dtype=torch.long).to(self.device)
output = output.transpose(0, 1)
target_length = torch.tensor([len(encoded_transcription)], dtype=torch.long).to(self.device)
loss_classifier = F.ctc_loss(output, target_tensor, output_length, target_length, blank=0, reduction='mean')
# Regularization term to minimize the perturbation
loss_norm = torch.norm(input_audio - input_audio_orig)
# Combine the losses and compute gradients
loss = (c * loss_norm) + ( loss_classifier)
# Computing gradients of our input w.r.t loss
loss.backward()
# Update the input audio with gradients
optimizer.step()
# Calculating perturbation by subtracting the optimized audio from cloned one
perturbation = input_audio - input_audio_orig
# Project the perturbation onto the epsilon ball in range (-eps, eps)
perturbation = torch.clamp(perturbation, -epsilon, epsilon)
# Cliping to audio in range (-1, 1)
input_audio.data = torch.clamp(input_audio_orig + perturbation, -1, 1)
# Storing model's current inference and target transcription in new variables for computing WER
string1 = list(filter(lambda x: x!= '',self.INFER(input_audio).split("|")))
string2 = list(reduce(lambda x,y: x+y, target).split("|"))
if early_stop:
# Computing WER while also making sure length of both strings is same
# This will also early stop the attack if we reach our target transcription
# before the completion of all iteration
if len(string1) == len(string2):
if self._wer(string1, string2)[0] == 0:
print("Breaking for loop because targeted Attack is performed successfully !")
adv_example = input_audio
return adv_example.detach().cpu().numpy()
elif len(string1) > len(string2):
diff = len(string1) - len(string2)
for i in range(diff):
string2.append("<eps>")
if self._wer(string1, string2)[0] == 0:
print("Breaking for loop because targeted Attack is performed successfully !")
adv_example = input_audio
return adv_example.detach().cpu().numpy()
else:
diff = len(string2) - len(string1)
for i in range(diff):
string1.append("<eps>")
if self._wer(string1, string2)[0] == 0:
print("Breaking for loop because targeted Attack is performed successfully !")
adv_example = input_audio
return adv_example.detach().cpu().numpy()
elif search_eps:
# Computing WER while also making sure length of both strings is same
if len(string1) == len(string2):
if self._wer(string1, string2)[0] == 0:
num_successful_attacks += 1
if num_successful_attacks >= num_iter_decrease_eps:
successful_attack = True
epsilon *= decrease_factor_eps
num_successful_attacks = 0
else:
successful_attack = False
elif len(string1) > len(string2):
diff = len(string1) - len(string2)
for i in range(diff):
string2.append("<eps>")
if self._wer(string1, string2)[0] == 0:
num_successful_attacks += 1
if num_successful_attacks >= num_iter_decrease_eps:
successful_attack = True
epsilon *= decrease_factor_eps
num_successful_attacks = 0
else:
successful_attack = False
else:
diff = len(string2) - len(string1)
for i in range(diff):
string1.append("<eps>")
if self._wer(string1, string2)[0] == 0:
num_successful_attacks += 1
if num_successful_attacks >= num_iter_decrease_eps:
successful_attack = True
epsilon *= decrease_factor_eps
num_successful_attacks = 0
else:
successful_attack = False
adv_example = input_audio
return adv_example.detach().cpu().numpy()
else: # If untargeted
# Then we will use the model's transcription as our target
target = self.INFER(input_audio.to(self.device))
for i in tqdm(range(num_iter), colour="red", leave = leave):
# We will use the model's transcription as our target
untarget = self.INFER(input_audio.to(self.device))
# Encode the target transcription
encoded_transcription = self._encode_transcription(untarget)
# Convert the target transcription to a PyTorch tensor
target_tensor = torch.from_numpy(np.array(encoded_transcription)).to(self.device).long()
# Zero the gradients
optimizer.zero_grad()
# Compute the model’s prediction
output, _ = self.model(input_audio)
# Softmax Activation for computing logits
output = F.log_softmax(output, dim=-1)
# Compute the CTC loss function
output_length = torch.tensor([output.shape[1]], dtype=torch.long).to(self.device)
output = output.transpose(0, 1)
target_length = torch.tensor([len(encoded_transcription)], dtype=torch.long).to(self.device)
loss_classifier = -F.ctc_loss(output, target_tensor, output_length, target_length, blank=0, reduction='mean')
# Regularization term to minimize the perturbation
loss_norm = torch.norm(input_audio - input_audio_orig)
# Combine the losses and compute gradients
loss = (c * loss_norm) + ( loss_classifier)
# Computing gradients of our input w.r.t loss
loss.backward()
# Update the input audio with gradients
optimizer.step()
# Calculating perturbation by subtracting the optimized audio from cloned one
perturbation = input_audio - input_audio_orig
# Project the perturbation onto the epsilon ball in range (-eps, eps)
perturbation = torch.clamp(perturbation, -epsilon, epsilon)
# Cliping to audio in range (-1, 1)
input_audio.data = torch.clamp(input_audio_orig + perturbation, -1, 1)
# Storing model's current inference and target transcription in new variables for computing WER
string1 = list(filter(lambda x: x!= '',self.INFER(input_audio).split("|")))
string2 = list(reduce(lambda x,y: x+y, target).split("|"))
if early_stop:
# Computing WER while also making sure length of both strings is same
# This will also early stop the attack if we reach our target transcription
# before the completion of all iteration
if len(string1) == len(string2):
if self._wer(string1, string2)[0] == 1:
print("Breaking for loop because targeted Attack is performed successfully !")
adv_example = input_audio
return adv_example.detach().cpu().numpy()
elif len(string1) > len(string2):
diff = len(string1) - len(string2)
for i in range(diff):
string2.append("<eps>")
if self._wer(string1, string2)[0] == 1:
print("Breaking for loop because targeted Attack is performed successfully !")
adv_example = input_audio
return adv_example.detach().cpu().numpy()
else:
diff = len(string2) - len(string1)
for i in range(diff):
string1.append("<eps>")
if self._wer(string1, string2)[0] == 1:
print("Breaking for loop because targeted Attack is performed successfully !")
adv_example = input_audio
return adv_example.detach().cpu().numpy()
elif search_eps:
# Computing WER while also making sure length of both strings is same
if len(string1) == len(string2):
if self._wer(string1, string2)[0] == 1:
num_successful_attacks += 1
if num_successful_attacks >= num_iter_decrease_eps:
successful_attack = True
epsilon *= decrease_factor_eps
num_successful_attacks = 0
else:
successful_attack = False
elif len(string1) > len(string2):
diff = len(string1) - len(string2)
for i in range(diff):
string2.append("<eps>")
if self._wer(string1, string2)[0] == 1:
num_successful_attacks += 1
if num_successful_attacks >= num_iter_decrease_eps:
successful_attack = True
epsilon *= decrease_factor_eps
num_successful_attacks = 0
else:
successful_attack = False
else:
diff = len(string2) - len(string1)
for i in range(diff):
string1.append("<eps>")
if self._wer(string1, string2)[0] == 1:
num_successful_attacks += 1
if num_successful_attacks >= num_iter_decrease_eps:
successful_attack = True
epsilon *= decrease_factor_eps
num_successful_attacks = 0
else:
successful_attack = False
adv_example = input_audio
return adv_example.detach().cpu().numpy()
def IMPERCEPTIBLE_ATTACK(self, input__: torch.Tensor, target: List[str] = None,
epsilon: float = 0.3, c: float = 1e-4, learning_rate1: float = 0.01,
learning_rate2: float = 0.01, num_iter1: int = 10000, num_iter2: int = 2000,
decrease_factor_eps: float = 1.0, num_iter_decrease_eps: int = 10,
optimizer1: str = None, optimizer2: str = None, nested: bool = True ,
early_stop_cw: bool = True, search_eps_cw: bool = False, alpha: float = 0.5) -> np.ndarray:
'''
Implements the Imperceptible ASR attack, which leverages the strongest white box
adversarial attack which is CW attack while also masking sure the added perturbation
is imperceptible to humans using Psychoacoustic Scale. This attack is performed in two
stages. In first stage we perform simple CW attack and in 2nd stage we make sure our
added perturbations are imperceptible.
For more information, see the paper: https://arxiv.org/abs/1903.10346
INPUT ARGUMENTS:
input__ : Input audio. Ex: Tensor[0.1,0.3,...] or (samples,)
Type: torch.Tensor
target : Target transcription (needed if the you want targeted
attack) Ex: ["my name is mango."]
Type: List[str]