-
Notifications
You must be signed in to change notification settings - Fork 0
/
adversarial_training_main.py
248 lines (179 loc) · 9.24 KB
/
adversarial_training_main.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
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torchvision as tv
from time import time
from VAECNN import *
from fast_gradient_sign_untargeted import FastGradientSignUntargeted
from utils import makedirs, create_logger, tensor2cuda, numpy2cuda, evaluate, save_model
from argument import parser, print_args
KL_WEIGHT=0.01
class Trainer():
def __init__(self, args, logger, attack):
self.args = args
self.logger = logger
self.attack = attack
def standard_train(self, model, tr_loader, va_loader=None):
self.train(model, tr_loader, va_loader, False)
def adversarial_train(self, model, tr_loader, va_loader=None):
self.train(model, tr_loader, va_loader, True)
def train(self, model, tr_loader, va_loader=None, adv_train=False):
args = self.args
logger = self.logger
opt = torch.optim.SGD(model.parameters(), args.learning_rate,
weight_decay=args.weight_decay,
momentum=args.momentum)
scheduler = torch.optim.lr_scheduler.MultiStepLR(opt,
milestones=[40000, 60000],
gamma=0.1)
_iter = 0
begin_time = time()
for epoch in range(1, args.max_epoch+1):
for data, label in tr_loader:
data, label = tensor2cuda(data), tensor2cuda(label)
if adv_train:
# When training, the adversarial example is created from a random
# close point to the original data point. If in evaluation mode,
# just start from the original data point.
adv_data = self.attack.perturb(data, label, 'mean', True)
output, kl_loss = model(adv_data, _eval=False)
else:
output, kl_loss= model(data, _eval=False)
loss = F.cross_entropy(output, label) + kl_loss * KL_WEIGHT
opt.zero_grad()
loss.backward()
opt.step()
if _iter % args.n_eval_step == 0:
t1 = time()
if adv_train:
with torch.no_grad():
stand_output, _ = model(data, _eval=True)
pred = torch.max(stand_output, dim=1)[1]
# print(pred)
std_acc = evaluate(pred.cpu().numpy(), label.cpu().numpy()) * 100
pred = torch.max(output, dim=1)[1]
# print(pred)
adv_acc = evaluate(pred.cpu().numpy(), label.cpu().numpy()) * 100
else:
adv_data = self.attack.perturb(data, label, 'mean', False)
with torch.no_grad():
adv_output, _ = model(adv_data, _eval=True)
pred = torch.max(adv_output, dim=1)[1]
# print(label)
# print(pred)
adv_acc = evaluate(pred.cpu().numpy(), label.cpu().numpy()) * 100
pred = torch.max(output, dim=1)[1]
# print(pred)
std_acc = evaluate(pred.cpu().numpy(), label.cpu().numpy()) * 100
t2 = time()
logger.info(f'epoch: {epoch}, iter: {_iter}, lr={opt.param_groups[0]["lr"]}, '
f'spent {time()-begin_time:.2f} s, tr_loss: {loss.item():.3f}')
logger.info(f'standard acc: {std_acc:.3f}%, robustness acc: {adv_acc:.3f}%')
begin_time = time()
if _iter % args.n_store_image_step == 0:
tv.utils.save_image(torch.cat([data.cpu(), adv_data.cpu()], dim=0),
os.path.join(args.log_folder, f'images_{_iter}.jpg'),
nrow=16)
if _iter % args.n_checkpoint_step == 0:
file_name = os.path.join(args.model_folder, f'checkpoint_{_iter}.pth')
save_model(model, file_name)
_iter += 1
# scheduler depends on training interation
scheduler.step()
if va_loader is not None:
t1 = time()
va_acc, va_adv_acc = self.test(model, va_loader, True, False)
va_acc, va_adv_acc = va_acc * 100.0, va_adv_acc * 100.0
t2 = time()
logger.info('\n'+'='*20 +f' evaluation at epoch: {epoch} iteration: {_iter} ' \
+'='*20)
logger.info(f'test acc: {va_acc:.3f}%, test adv acc: {va_adv_acc:.3f}%, spent: {t2-t1:.3f} s')
logger.info('='*28+' end of evaluation '+'='*28+'\n')
def test(self, model, loader, adv_test=False, use_pseudo_label=False):
# adv_test is False, return adv_acc as -1
total_acc = 0.0
num = 0
total_adv_acc = 0.0
with torch.no_grad():
for data, label in loader:
data, label = tensor2cuda(data), tensor2cuda(label)
output, _ = model(data, _eval=True)
pred = torch.max(output, dim=1)[1]
te_acc = evaluate(pred.cpu().numpy(), label.cpu().numpy(), 'sum')
total_acc += te_acc
num += output.shape[0]
if adv_test:
# use predicted label as target label
with torch.enable_grad():
adv_data = self.attack.perturb(data,
pred if use_pseudo_label else label,
'mean',
False)
adv_output, _ = model(adv_data, _eval=True)
adv_pred = torch.max(adv_output, dim=1)[1]
adv_acc = evaluate(adv_pred.cpu().numpy(), label.cpu().numpy(), 'sum')
total_adv_acc += adv_acc
else:
total_adv_acc = -num
return total_acc / num , total_adv_acc / num
def main(args):
save_folder = '%s_%s' % (args.dataset, args.affix)
log_folder = os.path.join(args.log_root, save_folder)
model_folder = os.path.join(args.model_root, save_folder)
makedirs(log_folder)
makedirs(model_folder)
setattr(args, 'log_folder', log_folder)
setattr(args, 'model_folder', model_folder)
logger = create_logger(log_folder, args.todo, 'info')
print_args(args, logger)
# model = WideResNet(depth=34, num_classes=10, widen_factor=10, dropRate=0.0)
if args.model_name == 'VAEResNet18FirstLayerChanged':
model = VAECNNFirstLayerChanged(BasicBlock, [2,2,2,2])
else:
model = VAEResNet18()
attack = FastGradientSignUntargeted(model,
args.epsilon,
args.alpha,
min_val=0,
max_val=1,
max_iters=args.k,
_type=args.perturbation_type)
if torch.cuda.is_available():
model.cuda()
trainer = Trainer(args, logger, attack)
if args.todo == 'train':
transform_train = tv.transforms.Compose([
tv.transforms.RandomCrop(32, padding=4, fill=0, padding_mode='constant'),
tv.transforms.RandomHorizontalFlip(),
tv.transforms.ToTensor(),
])
tr_dataset = tv.datasets.CIFAR10(args.data_root,
train=True,
transform=transform_train,
download=True)
tr_loader = DataLoader(tr_dataset, batch_size=args.batch_size, shuffle=True, num_workers=4)
# evaluation during training
te_dataset = tv.datasets.CIFAR10(args.data_root,
train=False,
transform=tv.transforms.ToTensor(),
download=True)
te_loader = DataLoader(te_dataset, batch_size=args.batch_size, shuffle=False, num_workers=4)
trainer.train(model, tr_loader, te_loader, args.adv_train)
elif args.todo == 'test':
te_dataset = tv.datasets.CIFAR10(args.data_root,
train=False,
transform=tv.transforms.ToTensor(),
download=True)
te_loader = DataLoader(te_dataset, batch_size=args.batch_size, shuffle=False, num_workers=4)
checkpoint = torch.load(args.load_checkpoint)
model.load_state_dict(checkpoint)
std_acc, adv_acc = trainer.test(model, te_loader, adv_test=True, use_pseudo_label=False)
print(f"std acc: {std_acc * 100:.3f}%, adv_acc: {adv_acc * 100:.3f}%")
else:
raise NotImplementedError
if __name__ == '__main__':
args = parser()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
main(args)