-
Notifications
You must be signed in to change notification settings - Fork 70
/
badnet.py
executable file
·276 lines (229 loc) · 10.5 KB
/
badnet.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
'''
Badnets: Identifying vulnerabilities in the machine learning model supply chain.
this script is for badnet attack
@article{gu2017badnets,
title={Badnets: Identifying vulnerabilities in the machine learning model supply chain},
author={Gu, Tianyu and Dolan-Gavitt, Brendan and Garg, Siddharth},
journal={arXiv preprint arXiv:1708.06733},
year={2017}
}
basic structure:
1. config args, save_path, fix random seed
2. set the clean train data and clean test data
3. set the attack img transform and label transform
4. set the backdoor attack data and backdoor test data
5. set the device, model, criterion, optimizer, training schedule.
6. save the attack result for defense
'''
import os
import sys
import yaml
sys.path = ["./"] + sys.path
import argparse
import numpy as np
import torch
import logging
from utils.backdoor_generate_poison_index import generate_poison_index_from_label_transform
from utils.aggregate_block.bd_attack_generate import bd_attack_img_trans_generate, bd_attack_label_trans_generate
from copy import deepcopy
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.save_load_attack import save_attack_result
from attack.prototype import NormalCase
from utils.trainer_cls import BackdoorModelTrainer
from utils.bd_dataset_v2 import prepro_cls_DatasetBD_v2, dataset_wrapper_with_transform
def add_common_attack_args(parser):
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('--pratio', type=float,
help='the poison rate '
)
return parser
class BadNet(NormalCase):
r"""Badnets: Identifying vulnerabilities in the machine learning model supply chain.
basic structure:
1. config args, save_path, fix random seed
2. set the clean train data and clean test data
3. set the attack img transform and label transform
4. set the backdoor attack data and backdoor test data
5. set the device, model, criterion, optimizer, training schedule.
6. attack or use the model to do finetune with 5% clean data
7. save the attack result for defense
.. code-block:: python
attack = BadNet()
attack.attack()
.. Note::
@article{gu2017badnets,
title={Badnets: Identifying vulnerabilities in the machine learning model supply chain},
author={Gu, Tianyu and Dolan-Gavitt, Brendan and Garg, Siddharth},
journal={arXiv preprint arXiv:1708.06733},
year={2017}}
Args:
attack (string): name of attack, use to match the transform and set the saving prefix of path.
attack_target (Int): target class No. in all2one attack
attack_label_trans (str): which type of label modification in backdoor attack
pratio (float): the poison rate
bd_yaml_path (string): path for yaml file provide additional default attributes
patch_mask_path (string): path for patch mask
**kwargs (optional): Additional attributes.
"""
def __init__(self):
super(BadNet).__init__()
def set_bd_args(cls, parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
parser = add_common_attack_args(parser)
parser.add_argument("--patch_mask_path", type=str)
parser.add_argument('--bd_yaml_path', type=str, default='./config/attack/badnet/default.yaml',
help='path for yaml file provide additional default attributes')
return parser
def add_bd_yaml_to_args(self, args):
with open(args.bd_yaml_path, 'r') as f:
mix_defaults = yaml.safe_load(f)
mix_defaults.update({k: v for k, v in args.__dict__.items() if v is not None})
args.__dict__ = mix_defaults
def stage1_non_training_data_prepare(self):
logging.info(f"stage1 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()
train_bd_img_transform, test_bd_img_transform = bd_attack_img_trans_generate(args)
### get the backdoor transform on label
bd_label_transform = bd_attack_label_trans_generate(args)
### 4. set the backdoor attack data and backdoor test data
train_poison_index = generate_poison_index_from_label_transform(
clean_train_dataset_targets,
label_transform=bd_label_transform,
train=True,
pratio=args.pratio if 'pratio' in args.__dict__ else None,
p_num=args.p_num if 'p_num' in args.__dict__ else None,
)
logging.debug(f"poison train idx is saved")
torch.save(train_poison_index,
args.save_path + '/train_poison_index_list.pickle',
)
### generate train dataset for backdoor attack
bd_train_dataset = prepro_cls_DatasetBD_v2(
deepcopy(train_dataset_without_transform),
poison_indicator=train_poison_index,
bd_image_pre_transform=train_bd_img_transform,
bd_label_pre_transform=bd_label_transform,
save_folder_path=f"{args.save_path}/bd_train_dataset",
)
bd_train_dataset_with_transform = dataset_wrapper_with_transform(
bd_train_dataset,
train_img_transform,
train_label_transform,
)
### decide which img to poison in ASR Test
test_poison_index = generate_poison_index_from_label_transform(
clean_test_dataset_targets,
label_transform=bd_label_transform,
train=False,
)
### generate test dataset for ASR
bd_test_dataset = prepro_cls_DatasetBD_v2(
deepcopy(test_dataset_without_transform),
poison_indicator=test_poison_index,
bd_image_pre_transform=test_bd_img_transform,
bd_label_pre_transform=bd_label_transform,
save_folder_path=f"{args.save_path}/bd_test_dataset",
)
bd_test_dataset.subset(
np.where(test_poison_index == 1)[0]
)
bd_test_dataset_with_transform = dataset_wrapper_with_transform(
bd_test_dataset,
test_img_transform,
test_label_transform,
)
self.stage1_results = clean_train_dataset_with_transform, \
clean_test_dataset_with_transform, \
bd_train_dataset_with_transform, \
bd_test_dataset_with_transform
def stage2_training(self):
logging.info(f"stage2 start")
assert 'args' in self.__dict__
args = self.args
clean_train_dataset_with_transform, \
clean_test_dataset_with_transform, \
bd_train_dataset_with_transform, \
bd_test_dataset_with_transform = self.stage1_results
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]
)
trainer = BackdoorModelTrainer(
self.net,
)
criterion = argparser_criterion(args)
optimizer, scheduler = argparser_opt_scheduler(self.net, args)
from torch.utils.data.dataloader import DataLoader
trainer.train_with_test_each_epoch_on_mix(
DataLoader(bd_train_dataset_with_transform, batch_size=args.batch_size, shuffle=True, drop_last=True,
pin_memory=args.pin_memory, num_workers=args.num_workers, ),
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, ),
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, ),
args.epochs,
criterion=criterion,
optimizer=optimizer,
scheduler=scheduler,
device=self.device,
frequency_save=args.frequency_save,
save_folder_path=args.save_path,
save_prefix='attack',
amp=args.amp,
prefetch=args.prefetch,
prefetch_transform_attr_name="ori_image_transform_in_loading", # since we use the preprocess_bd_dataset
non_blocking=args.non_blocking,
)
save_attack_result(
model_name=args.model,
num_classes=args.num_classes,
model=trainer.model.cpu().state_dict(),
data_path=args.dataset_path,
img_size=args.img_size,
clean_data=args.dataset,
bd_train=bd_train_dataset_with_transform,
bd_test=bd_test_dataset_with_transform,
save_path=args.save_path,
)
if __name__ == '__main__':
attack = BadNet()
parser = argparse.ArgumentParser(description=sys.argv[0])
parser = attack.set_args(parser)
parser = attack.set_bd_args(parser)
args = parser.parse_args()
logging.debug("Be careful that we need to give the bd yaml higher priority. So, we put the add bd yaml first.")
attack.add_bd_yaml_to_args(args)
attack.add_yaml_to_args(args)
args = attack.process_args(args)
attack.prepare(args)
attack.stage1_non_training_data_prepare()
attack.stage2_training()