-
Notifications
You must be signed in to change notification settings - Fork 70
/
lira.py
executable file
·1042 lines (842 loc) · 38.3 KB
/
lira.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
'''
LIRA: Learnable, Imperceptible and Robust Backdoor Attacks
This is the code for LIRA attack
github link : https://github.com/sunbelbd/invisible_backdoor_attacks
@inproceedings{Doan2021lira,
title = {LIRA: Learnable, Imperceptible and Robust Backdoor Attacks},
author = {Khoa D. Doan and Yingjie Lao and Weijie Zhao and Ping Li},
booktitle = {Proceedings of the IEEE International Conference on Computer Vision},
year = {2021}
}
Please note that
1. The original code was implemented in Paddlepaddle,
and we replaced all the functionality of Paddlepaddle with the equivalent API of Pytorch.
2. Since this is a training-controllable attack,
the concepts of poisoning rate and poisoned data may not apply.
So, this attack remains incompatible with the whole framework for the time being
(because we require data to be saved during the saving process).
In the future, we will update this version to make it fully integrated into the framework.
3. For fairness issue, we apply the same total training epochs as all other attack methods. But for LIRA, it may not be the best choice.
The original LICENSE of the script is put at the bottom of this file.
'''
import argparse
import logging
import os
import random
import sys
import torch
from copy import deepcopy
from functools import partial
sys.path = ["./"] + sys.path
import numpy as np
from torch import nn, optim
from torchvision import transforms
from torch.utils.data import DataLoader
from torch.utils.data.dataloader import DataLoader
from utils.aggregate_block.dataset_and_transform_generate import get_dataset_denormalization, dataset_and_transform_generate
from utils.trainer_cls import Metric_Aggregator, all_acc, test_given_dataloader_on_mix
from utils.trainer_cls import plot_loss, plot_acc_like_metric, given_dataloader_test
from utils.aggregate_block.model_trainer_generate import generate_cls_model
from utils.aggregate_block.train_settings_generate import argparser_opt_scheduler, argparser_criterion
from utils.bd_dataset_v2 import prepro_cls_DatasetBD_v2, dataset_wrapper_with_transform
from utils.save_load_attack import save_attack_result
from attack.badnet import BadNet
loss_fn = nn.CrossEntropyLoss()
class Autoencoder(nn.Module):
def __init__(self, channels=3):
super(Autoencoder, self).__init__()
self.encoder = nn.Sequential(
nn.Conv2d(channels, 16, (4, 4), stride=(2, 2), padding=1),
nn.BatchNorm2d(16),
nn.ReLU(),
nn.Conv2d(16, 32, (4, 4), stride=(2, 2), padding=1),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.Conv2d(32, 64, (4, 4), stride=(2, 2), padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Conv2d(64, 128, (4, 4), stride=(2, 2), padding=1),
nn.BatchNorm2d(128),
nn.ReLU()
)
self.decoder = nn.Sequential(
nn.ConvTranspose2d(128, 64, (4, 4), stride=(2, 2), padding=(1, 1)),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.ConvTranspose2d(64, 32, (4, 4), stride=(2, 2), padding=(1, 1)),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.ConvTranspose2d(32, 16, (4, 4), stride=(2, 2), padding=(1, 1)),
nn.BatchNorm2d(16),
nn.ReLU(),
nn.ConvTranspose2d(16, channels, (4, 4), stride=(2, 2), padding=(1, 1)),
nn.Tanh()
)
def forward(self, x):
x = self.encoder(x)
x = self.decoder(x)
return x
def double_conv(in_channels, out_channels):
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, (3, 3), padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(),
nn.Conv2d(out_channels, out_channels, (3, 3), padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU()
)
class UNet(nn.Module):
def __init__(self, out_channel):
super().__init__()
self.dconv_down1 = double_conv(3, 64)
self.dconv_down2 = double_conv(64, 128)
self.dconv_down3 = double_conv(128, 256)
self.dconv_down4 = double_conv(256, 512)
self.maxpool = nn.AvgPool2d(2)
self.upsample = nn.Upsample(scale_factor=2, mode='bilinear',
align_corners=True)
self.dconv_up3 = double_conv(256 + 512, 256)
self.dconv_up2 = double_conv(128 + 256, 128)
self.dconv_up1 = double_conv(128 + 64, 64)
self.conv_last = nn.Sequential(
nn.Conv2d(64, out_channel, (1, 1)),
nn.BatchNorm2d(out_channel),
)
self.out_layer = nn.Tanh()
def forward(self, x):
conv1 = self.dconv_down1(x)
x = self.maxpool(conv1)
conv2 = self.dconv_down2(x)
x = self.maxpool(conv2)
conv3 = self.dconv_down3(x)
x = self.maxpool(conv3)
x = self.dconv_down4(x)
x = self.upsample(x)
x = torch.concat([x, conv3], 1)
x = self.dconv_up3(x)
x = self.upsample(x)
x = torch.concat([x, conv2], 1)
x = self.dconv_up2(x)
x = self.upsample(x)
x = torch.concat([x, conv1], 1)
x = self.dconv_up1(x)
out = self.conv_last(x)
out = self.out_layer(out)
return out
def all2one_target_transform(x, attack_target=1):
return torch.ones_like(x) * attack_target
def all2all_target_transform(x, num_classes):
return (x + 1) % num_classes
def create_models(args):
if args.attack_model == 'autoencoder':
logging.debug("use autoencoder as atk model")
atkmodel = Autoencoder(args.input_channel)
# Copy of attack model
tgtmodel = Autoencoder(args.input_channel)
else:
logging.debug("use unet as atk model")
atkmodel = UNet(args.input_channel)
# Copy of attack model
tgtmodel = UNet(args.input_channel)
# Classifier
create_net = partial(generate_cls_model,
model_name=args.model,
num_classes=args.num_classes,
image_size=args.img_size,
)
clsmodel = create_net()
tgtmodel.to(device)
atkmodel.to(device)
clsmodel.to(device)
# Optimizer
tgtoptimizer = torch.optim.Adam(tgtmodel.parameters(), lr=args.lr_atk)
return atkmodel, tgtmodel, tgtoptimizer, clsmodel, create_net
def hp_test(args, atkmodel, scratchmodel, target_transform,
train_loader, test_loader, epoch, trainepoch, clip_image,
testoptimizer=None, log_prefix='Internal', epochs_per_test=5):
# default phase 2 parameters to phase 1
if args.test_alpha is None:
args.test_alpha = args.alpha
if args.test_eps is None:
args.test_eps = args.eps
test_loss = 0
correct = 0
correct_transform = 0
test_transform_loss = 0
atkmodel.eval()
if testoptimizer is None:
scratchmodel.cuda()
testoptimizer = torch.optim.SGD(params=scratchmodel.parameters(), lr=args.lr)
for cepoch in range(trainepoch):
scratchmodel.train()
for batch_idx, (data, target) in enumerate(train_loader):
scratchmodel.cuda()
atkmodel.cuda()
data, target = data.cuda(), target.cuda()
with torch.cuda.amp.autocast(enabled=args.amp):
with torch.no_grad():
noise = atkmodel(data) * args.test_eps
atkdata = clip_image(data + noise)
atkoutput = scratchmodel(atkdata)
output = scratchmodel(data)
loss_clean = loss_fn(output, target)
loss_poison = loss_fn(atkoutput, target_transform(target))
loss = args.alpha * loss_clean + (1 - args.test_alpha) * loss_poison
scaler.scale(loss).backward()
scaler.step(testoptimizer)
scaler.update()
testoptimizer.zero_grad()
if cepoch % epochs_per_test == 0 or cepoch == trainepoch - 1:
scratchmodel.eval()
with torch.no_grad():
for data, target in test_loader:
scratchmodel.cuda()
atkmodel.cuda()
data, target = data.cuda(), target.cuda()
output = scratchmodel(data)
cross_entropy = torch.nn.CrossEntropyLoss(reduction="sum")
test_loss += cross_entropy(output, target).item() # sum up batch loss
correct += (torch.max(output, -1)[1]).eq(target).sum().item()
noise = atkmodel(data) * args.test_eps
atkdata = clip_image(data + noise)
atkoutput = scratchmodel(atkdata)
test_transform_loss += cross_entropy(
atkoutput, target_transform(target)).item() # sum up batch loss
correct_transform += (torch.max(atkoutput, -1)[1]).eq(target_transform(target)).sum().item()
test_loss /= len(test_loader.dataset)
test_transform_loss /= len(test_loader.dataset)
correct /= len(test_loader.dataset)
correct_transform /= len(test_loader.dataset)
logging.debug(
'\n{}-Test set [{}]: Loss: clean {:.4f} poison {:.4f}, Accuracy: clean {:.2f} poison {:.2f}'.format(
log_prefix, cepoch,
test_loss, test_transform_loss,
correct, correct_transform
))
return correct, correct_transform
def train(args, atkmodel, tgtmodel, clsmodel, tgtoptimizer, clsoptimizer, target_transform,
train_loader, epoch, train_epoch, create_net, clip_image, post_transforms=None):
clsmodel.train()
atkmodel.eval()
tgtmodel.train()
losslist = []
for batch_idx, (data, target) in enumerate(train_loader):
tgtmodel.cuda()
clsmodel.cuda()
atkmodel.cuda()
data, target = data.cuda(), target.cuda()
with torch.cuda.amp.autocast(enabled=args.amp):
if post_transforms is not None:
data = post_transforms(data)
########################################
#### Update Transformation Function ####
########################################
noise = tgtmodel(data) * args.eps
atkdata = clip_image(data + noise)
# Calculate loss
atkoutput = clsmodel(atkdata)
loss_poison = loss_fn(atkoutput, target_transform(target))
loss1 = loss_poison
losslist.append(loss1.item())
scaler.scale(loss1).backward()
scaler.step(tgtoptimizer)
scaler.update()
tgtoptimizer.zero_grad()
###############################
#### Update the classifier ####
###############################
with torch.cuda.amp.autocast(enabled=args.amp):
noise = atkmodel(data) * args.eps
atkdata = clip_image(data + noise)
output = clsmodel(data)
atkoutput = clsmodel(atkdata)
loss_clean = loss_fn(output, target)
loss_poison = loss_fn(atkoutput, target_transform(target))
loss2 = loss_clean * args.alpha + (1 - args.alpha) * loss_poison
scaler.scale(loss2).backward()
scaler.step(clsoptimizer)
scaler.update()
clsoptimizer.zero_grad()
atkloss = sum(losslist) / len(losslist)
return atkloss
def get_target_transform(args):
"""DONE
"""
if args.attack_label_trans == 'all2one':
target_transform = lambda x: all2one_target_transform(x, args.attack_target)
elif args.attack_label_trans == 'all2all':
target_transform = lambda x: all2all_target_transform(x, args.num_classes)
else:
raise Exception(f'Invalid mode {args.mode}')
return target_transform
# done
def get_train_test_loaders(args):
train_loader = get_dataloader(args, True)
test_loader = get_dataloader(args, False)
if args.dataset in ['tiny-imagenet', 'tiny-imagenet32', 'tiny']:
xmin, xmax = -2.1179039478302, 2.640000104904175
def clip_image(x):
return torch.clip(x, xmin, xmax)
elif args.dataset == 'cifar10':
xmin, xmax = -1.9895, 2.1309
def clip_image(x):
return torch.clip(x, xmin, xmax)
elif args.dataset == 'cifar100':
xmin, xmax = -1.8974, 2.0243
def clip_image(x):
return torch.clip(x, xmin, xmax)
elif args.dataset == 'mnist':
def clip_image(x):
return torch.clip(x, -1.0, 1.0)
elif args.dataset == 'gtsrb':
def clip_image(x):
return torch.clip(x, 0.0, 1.0)
else:
raise Exception(f'Invalid dataset: {args.dataset}')
return train_loader, test_loader, clip_image
class ToNumpy:
def __call__(self, x):
x = np.array(x)
if len(x.shape) == 2:
x = np.expand_dims(x, axis=2)
return x
class ProbTransform(torch.nn.Module):
def __init__(self, f, p=1):
super().__init__()
self.f = f
self.p = p
def forward(self, x): # , **kwargs):
if random.random() < self.p:
return self.f(x)
else:
return x
class PostTensorTransform(torch.nn.Module):
def __init__(self, opt):
super(PostTensorTransform, self).__init__()
self.random_crop = transforms.RandomCrop((opt.input_height, opt.input_width), padding=opt.random_crop)
self.random_rotation = transforms.RandomRotation(opt.random_rotation)
if opt.dataset == "cifar10":
self.random_horizontal_flip = transforms.RandomHorizontalFlip(p=0.5)
def forward(self, x):
for module in self.children():
x = module(x)
return x
# my done
def get_dataloader(opt, train=True, min_width=0):
train_dataset_without_transform, \
train_img_transform, \
train_label_transform, \
test_dataset_without_transform, \
test_img_transform, \
test_label_transform = dataset_and_transform_generate(opt)
logging.debug("dataset_and_transform_generate done")
clean_train_dataset_with_transform = dataset_wrapper_with_transform(
train_dataset_without_transform,
test_img_transform, # since later we have post_transform which contains randomcrop etc
train_label_transform
)
clean_test_dataset_with_transform = dataset_wrapper_with_transform(
test_dataset_without_transform,
test_img_transform,
test_label_transform,
)
if train:
dataloader = torch.utils.data.DataLoader(
clean_train_dataset_with_transform, batch_size=opt.batch_size, num_workers=opt.num_workers, shuffle=True)
else:
dataloader = torch.utils.data.DataLoader(
clean_test_dataset_with_transform, batch_size=opt.batch_size, num_workers=opt.num_workers, shuffle=False)
return dataloader
def get_model(args):
create_net = partial(generate_cls_model,
model_name=args.model,
num_classes=args.num_classes,
image_size=args.img_size,
)
netC = create_net()
netC.to(device)
optimizerC, schedulerC = argparser_opt_scheduler(netC, args)
logging.info(f'atk stage1, Optimizer: {optimizerC}, scheduler: {schedulerC}')
return netC, optimizerC, schedulerC
def final_test(clean_test_dataloader, bd_test_dataloader, args, test_model_path, atkmodel, netC, target_transform,
train_loader, test_loader,
trainepoch, writer, alpha=0.5, optimizerC=None,
schedulerC=None, log_prefix='Internal', epochs_per_test=1, data_transforms=None, start_epoch=1,
clip_image=None, criterion=None):
atkmodel.cuda()
netC.cuda()
clean_accs, poison_accs = [], []
atkmodel.eval()
if optimizerC is None:
logging.debug('No optimizer, creating default SGD...')
optimizerC = optim.SGD(netC.parameters(), lr=args.finetune_lr)
if schedulerC is None:
logging.debug('No scheduler, creating default 100,200,300,400...')
schedulerC = optim.lr_scheduler.MultiStepLR(optimizerC, [100, 200, 300, 400], args.finetune_lr)
clean_test_loss_list = []
bd_test_loss_list = []
test_acc_list = []
test_asr_list = []
test_ra_list = []
train_loss_list = []
agg = Metric_Aggregator()
for cepoch in range(start_epoch, trainepoch + 1):
netC.train()
batch_loss_list = []
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.cuda(), target.cuda()
netC.cuda()
atkmodel.cuda()
with torch.cuda.amp.autocast(enabled=args.amp):
if data_transforms is not None:
data = data_transforms(data)
output = netC(data)
loss_clean = loss_fn(output, target)
if alpha < 1:
with torch.no_grad():
noise = atkmodel(data) * args.test_eps
if clip_image is None:
atkdata = torch.clip(data + noise, 0, 1)
else:
atkdata = clip_image(data + noise)
atkoutput = netC(atkdata)
loss_poison = loss_fn(atkoutput, target_transform(target))
else:
loss_poison = torch.tensor(0.0)
loss = alpha * loss_clean + (1 - alpha) * loss_poison
scaler.scale(loss).backward()
scaler.step(optimizerC)
scaler.update()
optimizerC.zero_grad()
batch_loss_list.append(loss.item())
one_epoch_loss = sum(batch_loss_list) / len(batch_loss_list)
schedulerC.step()
# test
clean_metrics, \
clean_test_epoch_predict_list, \
clean_test_epoch_label_list, \
= given_dataloader_test(
model=netC,
test_dataloader=clean_test_dataloader,
criterion=criterion,
non_blocking=args.non_blocking,
device=device,
verbose=1,
)
clean_test_loss_avg_over_batch = clean_metrics["test_loss_avg_over_batch"]
test_acc = clean_metrics["test_acc"]
bd_metrics, \
bd_test_epoch_predict_list, \
bd_test_epoch_label_list, \
bd_test_epoch_original_index_list, \
bd_test_epoch_poison_indicator_list, \
bd_test_epoch_original_targets_list = test_given_dataloader_on_mix(
model=netC,
test_dataloader=bd_test_dataloader,
criterion=criterion,
non_blocking=args.non_blocking,
device=device,
verbose=1,
)
bd_test_loss_avg_over_batch = bd_metrics["test_loss_avg_over_batch"]
test_asr = all_acc(bd_test_epoch_predict_list, bd_test_epoch_label_list)
test_ra = all_acc(bd_test_epoch_predict_list, bd_test_epoch_original_targets_list)
agg(
{
"epoch": cepoch,
"train_epoch_loss_avg_over_batch": one_epoch_loss,
"clean_test_loss_avg_over_batch": clean_test_loss_avg_over_batch,
"bd_test_loss_avg_over_batch": bd_test_loss_avg_over_batch,
"test_acc": test_acc,
"test_asr": test_asr,
"test_ra": test_ra,
}
)
clean_test_loss_list.append(clean_test_loss_avg_over_batch)
bd_test_loss_list.append(bd_test_loss_avg_over_batch)
test_acc_list.append(test_acc)
test_asr_list.append(test_asr)
test_ra_list.append(test_ra)
plot_loss(
train_loss_list,
clean_test_loss_list,
bd_test_loss_list,
args.save_path,
"loss_metric_plots_atk_stg2",
)
plot_acc_like_metric(
[], [], [],
test_acc_list,
test_asr_list,
test_ra_list,
args.save_path,
"loss_metric_plots_atk_stg2",
)
agg.to_dataframe().to_csv(f"{args.save_path}/attack_df_atk_stg2.csv")
agg.summary().to_csv(f"{args.save_path}/attack_df_summary_atk_stg2.csv")
return clean_accs, poison_accs
def main(args, clean_test_dataset_with_transform, criterion):
clean_test_dataloader = DataLoader(clean_test_dataset_with_transform, batch_size=args.batch_size, shuffle=False,
drop_last=False,
pin_memory=args.pin_memory, num_workers=args.num_workers, )
clean_test_loss_list = []
bd_test_loss_list = []
test_acc_list = []
test_asr_list = []
test_ra_list = []
train_loss_list = []
agg = Metric_Aggregator()
if args.verbose >= 1:
logging.debug('========== ARGS ==========')
logging.debug(args)
train_loader, test_loader, clip_image = get_train_test_loaders(args)
post_transforms = PostTensorTransform(args)
logging.debug('========== DATA ==========')
logging.debug('Loaders: Train {} examples/{} iters, Test {} examples/{} iters'.format(
len(train_loader.dataset), len(train_loader), len(test_loader.dataset), len(test_loader)))
atkmodel, tgtmodel, tgtoptimizer, clsmodel, create_net = create_models(args)
if args.verbose >= 2:
logging.debug('========== MODELS ==========')
logging.debug(atkmodel)
logging.debug(clsmodel)
target_transform = get_target_transform(args)
trainlosses = []
start_epoch = 1
# Initialize the tgtmodel
tgtmodel.load_state_dict(atkmodel.state_dict(), )
logging.debug('============================')
logging.debug('============================')
logging.debug('BEGIN TRAINING >>>>>>')
clsmodel.cuda()
clsoptimizer = torch.optim.SGD(params=clsmodel.parameters(), lr=args.lr, momentum=0.9)
if "," in args.device:
logging.info("data parallel in main")
atkmodel = torch.nn.DataParallel(
atkmodel,
device_ids=[int(i) for i in args.device[5:].split(",")] # eg. "cuda:2,3,7" -> [2,3,7]
)
tgtmodel = torch.nn.DataParallel(
tgtmodel,
device_ids=[int(i) for i in args.device[5:].split(",")] # eg. "cuda:2,3,7" -> [2,3,7]
)
clsmodel = torch.nn.DataParallel(
clsmodel,
device_ids=[int(i) for i in args.device[5:].split(",")] # eg. "cuda:2,3,7" -> [2,3,7]
)
for epoch in range(start_epoch, args.both_train_epochs + 1):
for i in range(args.train_epoch):
logging.debug(f'===== EPOCH: {epoch}/{args.both_train_epochs + 1} CLS {i + 1}/{args.train_epoch} =====')
if not args.avoid_clsmodel_reinitialization:
clsmodel.cuda()
clsoptimizer = torch.optim.SGD(params=clsmodel.parameters(), lr=args.lr)
trainloss = train(args, atkmodel, tgtmodel, clsmodel, tgtoptimizer, clsoptimizer, target_transform,
train_loader,
epoch, i, create_net, clip_image,
post_transforms=post_transforms)
trainlosses.append(trainloss)
atkmodel.load_state_dict(tgtmodel.state_dict())
if args.avoid_clsmodel_reinitialization:
scratchmodel = create_net()
if "," in args.device:
scratchmodel = torch.nn.DataParallel(
scratchmodel,
device_ids=[int(i) for i in args.device[5:].split(",")] # eg. "cuda:2,3,7" -> [2,3,7]
)
scratchmodel.load_state_dict(clsmodel.state_dict()) # transfer from cls to scratch for testing
else:
clsmodel = create_net()
# test
clsmodel.eval()
clsmodel.to(device, non_blocking=args.non_blocking)
atkmodel.eval()
atkmodel.to(device, non_blocking=args.non_blocking)
bd_test_dataset = prepro_cls_DatasetBD_v2(
clean_test_dataset_with_transform.wrapped_dataset.dataset,
save_folder_path=f"{args.save_path}/bd_test_dataset_stage_one"
)
for trans_t in deepcopy(
clean_test_dataset_with_transform.wrap_img_transform.transforms):
if isinstance(trans_t, transforms.Normalize):
denormalizer = get_dataset_denormalization(trans_t)
logging.info(f"{denormalizer}")
clean_test_dataset_with_transform.wrapped_dataset.getitem_all = True
for batch_idx, (x, labels, original_index, poison_indicator, original_targets) in enumerate(
clean_test_dataloader):
with torch.no_grad():
x = x.to(device, non_blocking=args.non_blocking)
noise = atkmodel(x) * args.test_eps
atkdata = clip_image(x + noise)
atktarget = target_transform(labels)
position_changed = (labels - atktarget != 0)
atkdata = atkdata[position_changed]
targets1 = labels.detach().clone().cpu()[position_changed]
y_poison_batch = atktarget.detach().clone().cpu()[position_changed]
for idx_in_batch, t_img in enumerate(atkdata.detach().clone().cpu()):
if int(y_poison_batch[idx_in_batch]) == int(targets1[idx_in_batch]):
print("find bug")
bd_test_dataset.set_one_bd_sample(
selected_index=int(
batch_idx * int(args.batch_size) + torch.where(position_changed.detach().clone().cpu())[0][
idx_in_batch]),
# manually calculate the original index, since we do not shuffle the dataloader
img=denormalizer(t_img),
bd_label=int(y_poison_batch[idx_in_batch]),
label=int(targets1[idx_in_batch]),
)
bd_test_dataset.subset(
np.where(bd_test_dataset.poison_indicator == 1)[0]
)
bd_test_dataset_with_transform = dataset_wrapper_with_transform(
bd_test_dataset,
clean_test_dataset_with_transform.wrap_img_transform,
)
# generate bd test dataloader
bd_test_dataloader = DataLoader(bd_test_dataset_with_transform, batch_size=args.batch_size, shuffle=False,
drop_last=False,
pin_memory=args.pin_memory, num_workers=args.num_workers, )
### My test code start
clean_metrics, \
clean_test_epoch_predict_list, \
clean_test_epoch_label_list, \
= given_dataloader_test(
model=clsmodel,
test_dataloader=clean_test_dataloader,
criterion=criterion,
non_blocking=args.non_blocking,
device=device,
verbose=1,
)
clean_test_loss_avg_over_batch = clean_metrics["test_loss_avg_over_batch"]
test_acc = clean_metrics["test_acc"]
bd_metrics, \
bd_test_epoch_predict_list, \
bd_test_epoch_label_list, \
bd_test_epoch_original_index_list, \
bd_test_epoch_poison_indicator_list, \
bd_test_epoch_original_targets_list = test_given_dataloader_on_mix(
model=clsmodel,
test_dataloader=bd_test_dataloader,
criterion=criterion,
non_blocking=args.non_blocking,
device=device,
verbose=1,
)
bd_test_loss_avg_over_batch = bd_metrics["test_loss_avg_over_batch"]
test_asr = all_acc(bd_test_epoch_predict_list, bd_test_epoch_label_list)
test_ra = all_acc(bd_test_epoch_predict_list, bd_test_epoch_original_targets_list)
agg(
{
"epoch": epoch,
"train_epoch_loss_avg_over_batch": trainloss,
"clean_test_loss_avg_over_batch": clean_test_loss_avg_over_batch,
"bd_test_loss_avg_over_batch": bd_test_loss_avg_over_batch,
"test_acc": test_acc,
"test_asr": test_asr,
"test_ra": test_ra,
}
)
clean_test_loss_list.append(clean_test_loss_avg_over_batch)
bd_test_loss_list.append(bd_test_loss_avg_over_batch)
test_acc_list.append(test_acc)
test_asr_list.append(test_asr)
test_ra_list.append(test_ra)
plot_loss(
train_loss_list,
clean_test_loss_list,
bd_test_loss_list,
args.save_path,
"loss_metric_plots_atk_stg1",
)
plot_acc_like_metric(
[], [], [],
test_acc_list,
test_asr_list,
test_ra_list,
args.save_path,
"loss_metric_plots_atk_stg1",
)
agg.to_dataframe().to_csv(f"{args.save_path}/attack_df_atk_stg1.csv")
agg.summary().to_csv(f"{args.save_path}/attack_df_summary_atk_stg1.csv")
### My test code end
return clsmodel, atkmodel, bd_test_dataloader
def main2(args, pre_clsmodel, pre_atkmodel, clean_test_dataloader, bd_test_dataloader, criterion):
args_for_finetune = deepcopy(args)
args_for_finetune.__dict__ = {k[9:]: v for k, v in args_for_finetune.__dict__.items() if k.startswith("finetune_")}
if args.test_alpha is None:
logging.debug(f'Defaulting test_alpha to train alpha of {args.alpha}')
args.test_alpha = args.alpha
if args.finetune_lr is None:
logging.debug(f'Defaulting test_lr to train lr {args.lr}')
args.finetune_lr = args.lr
if args.test_eps is None:
logging.debug(f'Defaulting test_eps to train eps {args.test_eps}')
args.test_eps = args.eps
logging.debug('====> ARGS')
logging.debug(args)
torch.device("cuda" if torch.cuda.is_available() else "cpu")
train_loader, test_loader, clip_image = get_train_test_loaders(args)
atkmodel, tgtmodel, tgtoptimizer, _, create_net = create_models(args)
netC, optimizerC, schedulerC = get_model(args)
if "," in args.device:
logging.info("data parallel in main2")
netC = torch.nn.DataParallel(
netC,
device_ids=[int(i) for i in args.device[5:].split(",")] # eg. "cuda:2,3,7" -> [2,3,7]
)
atkmodel = torch.nn.DataParallel(
atkmodel,
device_ids=[int(i) for i in args.device[5:].split(",")] # eg. "cuda:2,3,7" -> [2,3,7]
)
netC.load_state_dict(pre_clsmodel.state_dict())
target_transform = get_target_transform(args)
atkmodel.load_state_dict(pre_atkmodel.state_dict())
netC.to(device)
optimizerC, schedulerC = argparser_opt_scheduler(netC, args_for_finetune)
logging.debug(netC)
logging.info(f"atk stage2, optimizerC: {optimizerC}, schedulerC: {schedulerC}")
data_transforms = PostTensorTransform(args)
logging.debug('====> Post tensor transform')
logging.debug(data_transforms)
clean_accs, poison_accs = final_test(clean_test_dataloader, bd_test_dataloader,
args, None, atkmodel, netC, target_transform,
train_loader, test_loader,
trainepoch=int(args.epochs - args.both_train_epochs),
writer=None, log_prefix='POISON', alpha=args.test_alpha, epochs_per_test=1,
optimizerC=optimizerC, schedulerC=schedulerC, data_transforms=data_transforms,
clip_image=clip_image, criterion=criterion)
class LIRA(BadNet):
def __init__(self):
super(LIRA, self).__init__()
def set_bd_args(cls, parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
parser.add_argument('--attack', type=str, )
parser.add_argument('--attack_target', type=int,
help='target class in all2one attack')
parser.add_argument('--attack_label_trans', type=str,
help='which type of label modification in backdoor attack'
)
parser.add_argument('--bd_yaml_path', type=str, default='./config/attack/lira/default.yaml',
help='path for yaml file provide additional default attributes')
parser.add_argument("--random_crop", type=int, )
parser.add_argument("--random_rotation", type=int, )
parser.add_argument('--attack_model', type=str, ) # default='autoencoder')
parser.add_argument('--lr_atk', type=float, ) # default=0.0001, help='learning rate for attack model')
parser.add_argument('--eps', type=float, ) # default=0.3, help='epsilon for data poisoning')
parser.add_argument('--test_eps', type=float) # default=None,
parser.add_argument('--alpha', type=float, ) # default=0.5)
parser.add_argument('--test_alpha', type=float) # default=None,
parser.add_argument('--fix_generator_epoch', type=int, ) # default=1, help='training epochs for victim model')
# parser.add_argument('--finetune_epochs', type=int) # default=500,
parser.add_argument('--finetune_lr', type=float) # default=None,
# parser.add_argument('--steplr_gamma', ) # default='30,60,90,150')
# parser.add_argument('--steplr_milestones', type=float) # default=0.05,
parser.add_argument('--finetune_steplr_gamma', )
parser.add_argument('--finetune_steplr_milestones', )
parser.add_argument('--finetune_optimizer', ) # default='sgd')
parser.add_argument("--both_train_epochs", type=int, )
################### its original
parser.add_argument('--train_epoch', type=int, default=1, help='training epochs for victim model')
parser.add_argument('--epochs_per_external_eval', type=int, default=50)
parser.add_argument('--best_threshold', type=float, default=0.1)
parser.add_argument('--verbose', type=int, default=1, help='verbosity')
parser.add_argument('--avoid_clsmodel_reinitialization', action='store_true',
default=True, help='whether test the poisoned model from scratch')
parser.add_argument('--test_n_size', default=10)
parser.add_argument('--test_use_train_best', default=False, action='store_true')
parser.add_argument('--test_use_train_last', default=True, action='store_true')
return parser
def stage1_non_training_data_prepare(self):
pass
def stage2_training(self):
logging.info(f"stage2 start")
assert 'args' in self.__dict__
args = self.args
train_dataset_without_transform, \
train_img_transform, \
train_label_transform, \
test_dataset_without_transform, \
test_img_transform, \
test_label_transform, \
clean_train_dataset_with_transform, \
clean_train_dataset_targets, \
clean_test_dataset_with_transform, \
clean_test_dataset_targets \
= self.benign_prepare()
clean_test_dataset = prepro_cls_DatasetBD_v2(
test_dataset_without_transform
)
clean_test_dataset_with_transform = dataset_wrapper_with_transform(clean_test_dataset, test_img_transform)
clean_test_dataloader = DataLoader(clean_test_dataset_with_transform, batch_size=args.batch_size, shuffle=False,
drop_last=False,
pin_memory=args.pin_memory, num_workers=args.num_workers, )
self.net = generate_cls_model(
model_name=args.model,
num_classes=args.num_classes,
image_size=args.img_size[0],
)
self.device = torch.device(
(
f"cuda:{[int(i) for i in args.device[5:].split(',')][0]}" if "," in args.device else args.device
# since DataParallel only allow .to("cuda")
) if torch.cuda.is_available() else "cpu"
)
if "," in args.device:
self.net = torch.nn.DataParallel(
self.net,
device_ids=[int(i) for i in args.device[5:].split(",")] # eg. "cuda:2,3,7" -> [2,3,7]
)
criterion = argparser_criterion(args)
global device
device = torch.device(
(
f"cuda:{[int(i) for i in args.device[5:].split(',')][0]}" if "," in args.device else args.device
# since DataParallel only allow .to("cuda")
) if torch.cuda.is_available() else "cpu"
)
global scaler
scaler = torch.cuda.amp.GradScaler(enabled=args.amp)
clsmodel, atkmodel, bd_test_dataloader = main(args, clean_test_dataset_with_transform, criterion)
main2(args, clsmodel, atkmodel, clean_test_dataloader, bd_test_dataloader, criterion)
###
save_attack_result(
model_name=args.model,
num_classes=args.num_classes,
model=clsmodel.cpu().state_dict(),
data_path=args.dataset_path,
img_size=args.img_size,
clean_data=args.dataset,
bd_train=None,