-
Notifications
You must be signed in to change notification settings - Fork 0
/
experiments.py
356 lines (295 loc) · 15.7 KB
/
experiments.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
import main
import models
import mosaic_mnist
import torch
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import os
import shutil
import numpy as np
import argparse
def init(subfolder=''):
os.makedirs(os.path.join('trained_models', subfolder), exist_ok=True)
######################## EXPERIMENT 1 ########################
# Train a regular model on consistent Mosaic MNIST, train an #
# adversarial model based on it, then compare the two's #
# performances on all three versions of Mosaic MNIST #
##############################################################
def experiment1(**kwargs):
init('exp1+bg')
log_path = 'trained_models/exp1+bg'
ckpt_path = log_path + '/checkpoint.pth.tar'
vgg_path = log_path + '/vgg13.pth.tar'
vgg_adv_path = log_path + '/vgg13_adv.pth.tar'
BATCH_SIZE = 16
# Train task model, pretrain adversary
args = None
if not os.path.exists(vgg_path):
args = main.parser.parse_args(['dat',
'--dataset', 'mosaic_mnist',
'--arch', 'vgg13_adv',
#'--no-gpu',
'--precision', 'half',
'--epochs', '0',
'--pretrain-epochs', '2',
'--adv-pretrain-epochs', '2',
'--batch-size', str(BATCH_SIZE),
'--lr', '0.01',
'--adv-lr', '0.01',
'--momentum', '0.',
'--adv-momentum', '0.',
'--log-path', log_path,
#'--no-tensorboard'
])
args = main.reformat_args(args)
print('> Training VGG13 model')
BATCH_SIZE = main.main_reduce_batch(args) # Pretrain, return biggest working batch size
shutil.move(ckpt_path, vgg_path)
else:
print('Trained VGG13 model found! Skipping VGG13 training.')
# Interpret args for training/testing
args = main.parser.parse_args(['dat',
'--dataset', 'mosaic_mnist',
'--arch', 'vgg13_adv',
#'--no-gpu',
'--precision', 'half',
'--epochs', '10',
'--pretrain-epochs', '0',
'--adv-pretrain-epochs', '0',
'--batch-size', str(BATCH_SIZE),
'--lr', '0.001',
'--adv-lr', '0.01',
'--momentum', '0.',
'--adv-momentum', '0.',
'--log-path', log_path,
'--load-from', vgg_path,
#'--no-tensorboard'
])
args = main.reformat_args(args)
for kw in kwargs: # Manual arg setting from command line
kwargs[kw] = type(getattr(args, kw))(kwargs[kw]) # Convert to appropriate type
setattr(args, kw, kwargs[kw])
# These might have changed
log_path = args.log_path
ckpt_path = log_path + '/checkpoint.pth.tar'
vgg_adv_path = log_path + '/vgg13_adv.pth.tar'
# Train adversarial model
if not os.path.exists(vgg_adv_path):
print('> Training adversarial VGG13 model')
BATCH_SIZE = main.main_reduce_batch(args) # Train, return batch size
shutil.move(ckpt_path, vgg_adv_path)
else:
print('Trained Adversarial VGG13 model found! Skipping adversarial VGG13 training.')
# Test both models on Mosaic MNIST variants
if not os.path.exists(log_path + '/results.np'):
# Load saved models
vgg_save = torch.load(vgg_path)
vgg_model = models.vgg13_adv()
vgg_model.load_state_dict(vgg_save['state_dict'])
vgg_model = torch.nn.DataParallel(vgg_model.cuda()).half()
vgg_adv_save = torch.load(vgg_adv_path)
vgg_adv_model = models.vgg13_adv()
vgg_adv_model.load_state_dict(vgg_adv_save['state_dict'])
vgg_adv_model = torch.nn.DataParallel(vgg_adv_model.cuda()).half()
# Load test sets
print('> Loading test sets')
tf = transforms.Compose([
transforms.ToTensor(),
mosaic_mnist.grayscale2color])
dataloaders = dict()
for name in ['consistent', 'inconsistent', 'malicious']:
dset = mosaic_mnist.MnistMosaicDataset(name+'_test+bg', tf, True) #TODO: +bg
dataloaders[name] = DataLoader(dset, batch_size=BATCH_SIZE, shuffle=False, num_workers=4)
# Test models on sets
results = {'vgg13': {}, 'vgg13_adv': {}}
criterion = torch.nn.CrossEntropyLoss()
args = main.parser.parse_args(['dat', '--precision', 'half'])
#args = main.parser.parse_args(['dat'])
for name in ['consistent', 'inconsistent', 'malicious']:
print('Testing VGG13 model on ' + name + ' Mosaic MNIST...')
results['vgg13'][name] = main.validate(dataloaders[name], vgg_model, criterion, args)
for name in ['consistent', 'inconsistent', 'malicious']:
print('Testing Adversarial VGG13 model on ' + name + ' Mosaic MNIST...')
results['vgg13_adv'][name] = main.validate(dataloaders[name], vgg_adv_model, criterion, args)
# Save results
with open(log_path + '/results.np', 'wb') as f:
np.save(f, results)
else: # Results already exist
print('Results file found! Skipping testing of networks.')
with open(log_path + '/results.np', 'rb') as f:
results = np.load(f).item()
# Print results
print('\n\nRESULTS:\n')
print('%-11s| %-13s| %-13s| %-13s' % ('Model', 'Consistent', 'Inconsistent', 'Malicious'))
print('-'*11 + ('+' + '-'*14)*3)
print('%-11s| %-13.2f| %-13.2f| %-13.2f' % ('vgg13', results['vgg13']['consistent'], results['vgg13']['inconsistent'], results['vgg13']['malicious']))
print('%-11s| %-13.2f| %-13.2f| %-13.2f' % ('vgg13_adv', results['vgg13_adv']['consistent'], results['vgg13_adv']['inconsistent'], results['vgg13_adv']['malicious']))
def experiment2(**kwargs):
init('exp2')
log_path = 'trained_models/exp2'
ckpt_path = log_path + '/checkpoint.pth.tar'
vgg_path = log_path + '/vgg13.pth.tar'
vgg_adv_path = log_path + '/vgg13_adv.pth.tar'
BATCH_SIZE = 16
args = None
if not os.path.exists(vgg_path):
args = main.parser.parse_args(['/z/dat/ImageNet_2012',
'--dataset', 'imagenet',
'--arch', 'vgg13_adv',
'--precision', 'half',
'--pretrained', 'task',
'--epochs', '0',
'--pretrain-epochs', '0',
'--adv-pretrain-epochs', '1',
'--batch-size', str(BATCH_SIZE),
'--lr', '0.01',
'--adv-lr', '0.01',
'--momentum', '0.',
'--adv-momentum', '0.',
'--log-path', log_path,
])
args = main.reformat_args(args)
print('> Training VGG13 model')
BATCH_SIZE = main.main_reduce_batch(args) # Pretrain, return biggest working batch size
shutil.move(ckpt_path, vgg_path)
else:
print('Trained VGG13 model found! Skipping VGG13 training.')
# Interpret args for training/testing
args = main.parser.parse_args(['/z/dat/ImageNet_2012',
'--dataset', 'imagenet',
'--arch', 'vgg13_adv',
'--precision', 'half',
'--epochs', '10',
'--pretrain-epochs', '0',
'--adv-pretrain-epochs', '0',
'--batch-size', str(BATCH_SIZE),
'--lr', '0.001',
'--adv-lr', '0.01',
'--momentum', '0.',
'--adv-momentum', '0.',
'--log-path', log_path,
'--load-from', vgg_path,
])
args = main.reformat_args(args)
for kw in kwargs: # Manual arg setting from command line
kwargs[kw] = type(getattr(args, kw))(kwargs[kw]) # Convert to appropriate type
setattr(args, kw, kwargs[kw])
# These might have changed
log_path = args.log_path
ckpt_path = log_path + '/checkpoint.pth.tar'
vgg_adv_path = log_path + '/vgg13_adv.pth.tar'
# Train adversarial model
if not os.path.exists(vgg_adv_path):
print('> Training adversarial VGG13 model')
BATCH_SIZE = main.main_reduce_batch(args) # Train, return batch size
shutil.move(ckpt_path, vgg_adv_path)
else:
print('Trained Adversarial VGG13 model found! Skipping adversarial VGG13 training.')
# Test both models on Mosaic MNIST variants
if not os.path.exists(log_path + '/results.np'):
# Load saved models
vgg_save = torch.load(vgg_path)
vgg_model = models.vgg13_adv()
vgg_model.load_state_dict(vgg_save['state_dict'])
vgg_model = torch.nn.DataParallel(vgg_model.cuda()).half()
vgg_adv_save = torch.load(vgg_adv_path)
vgg_adv_model = models.vgg13_adv()
vgg_adv_model.load_state_dict(vgg_adv_save['state_dict'])
vgg_adv_model = torch.nn.DataParallel(vgg_adv_model.cuda()).half()
dataloader = main.make_dataloader(args, training=False)
acc1_vgg = main.validate(dataloader, vgg_model, torch.nn.CrossEntropyLoss(), args)
acc1_vgg_adv = main.validate(dataloader, vgg_adv_model, torch.nn.CrossEntropyLoss(), args)
# Save results
with open(log_path + '/results.np', 'wb') as f:
np.save(f, {'acc1_vgg': acc1_vgg, 'acc1_vgg_adv': acc1_vgg_adv})
else:
print('Results found! Skipping testing.')
with open(log_path + '/results.np', 'wb') as f:
results = np.load(f)
acc1_vgg = results['acc1_vgg']
acc1_vgg_adv = results['acc1_vgg_adv']
print('Results:')
print('VGG13 Acc@1: {}%'.format(acc1_vgg*100.))
print('VGG13 Adv. Acc@1: {}%'.format(acc1_vgg_adv*100.))
def experiment3(**kwargs):
init('exp3')
log_path = 'trained_models/exp3'
ckpt_path = log_path + '/checkpoint.pth.tar'
pretrained_path = log_path + '/pretrained.pth.tar'
trained_path = log_path + '/trained.pth.tar'
BATCH_SIZE = 16
args = main.parser.parse_args(['dat',
'--dataset', 'mosaic_mnist',
'--arch', 'twolayer_adv',
'--precision', 'half',
'--pretrained', 'none',
'--epochs', '0',
'--pretrain-epochs', '5',
'--adv-pretrain-epochs', '5',
'--batch-size', str(BATCH_SIZE),
'--lr', '0.001',
'--adv-lr', '0.01',
'--momentum', '0.',
'--adv-momentum', '0.',
'--log-path', log_path,
])
for kw in kwargs:
kwargs[kw] = type(getattr(args, kw))(kwargs[kw])
setattr(args, kw, kwargs[kw])
args = main.reformat_args(args)
print('> Pretraining two-layer model')
BATCH_SIZE = main.main_reduce_batch(args)
shutil.move(ckpt_path, pretrained_path)
args.load_path = pretrained_path
args.epochs = 10
args.pretrain_epochs = 0
args.adv_pretrain_epochs = 0
print('> Training two-layer model')
BATCH_SIZE = main.main_reduce_batch(args)
shutil.move(ckpt_path, trained_path)
pretrained_save = torch.load(pretrained_path)
pretrained_model = models.twolayer_adv()
pretrained_model.load_state_dict(pretrained_save['state_dict'])
pretrained_model = torch.nn.DataParallel(pretrained_model.cuda()).half()
trained_save = torch.load(trained_path)
trained_model = models.twolayer_adv()
trained_model.load_state_dict(trained_save['state_dict'])
trained_model = torch.nn.DataParallel(trained_model.cuda()).half()
# Load test sets
print('> Loading test sets')
tf = transforms.Compose([
transforms.ToTensor(),
mosaic_mnist.grayscale2color])
dataloaders = dict()
for name in ['consistent', 'inconsistent', 'malicious']:
dset = mosaic_mnist.MnistMosaicDataset(name+'_test', tf, True)
dataloaders[name] = DataLoader(dset, batch_size=BATCH_SIZE, shuffle=False, num_workers=4)
# Test models on sets
results = {'pretrained': {}, 'trained': {}}
criterion = torch.nn.CrossEntropyLoss()
args = main.parser.parse_args(['dat', '--precision', 'half'])
#args = main.parser.parse_args(['dat'])
for name in ['consistent', 'inconsistent', 'malicious']:
print('Testing pretrained model on ' + name + ' Mosaic MNIST...')
results['pretrained'][name] = main.validate(dataloaders[name], pretrained_model, criterion, args)
for name in ['consistent', 'inconsistent', 'malicious']:
print('Testing trained model on ' + name + ' Mosaic MNIST...')
results['trained'][name] = main.validate(dataloaders[name], trained_model, criterion, args)
with open(log_path + '/results.np', 'wb') as f:
np.save(f, results)
print('RESULTS:')
print('%10s %-12s %-12s %-12s' % ('Model', 'Consistent', 'Inconsistent', 'Malicious'))
for model in ['pretrained', 'trained']:
print('%10s: %-12.2f %-12.2f %-12.2f' % (model, results[model]['consistent'], results[model]['inconsistent'], results[model]['malicious']))
parser = argparse.ArgumentParser(description='Paper Experiments for ARTB in CNNs')
parser.add_argument('exps', default='1', metavar='N')
parser.add_argument('kwargs', nargs='*', metavar='**kwargs')
if __name__ == '__main__':
args = parser.parse_args()
experiments = {'1': experiment1, '2': experiment2, '3': experiment3} #TODO: Add others as they come
for exp in args.exps:
print('+-----------------------+')
print('| RUNNING: Experiment {} |'.format(exp))
print('+-----------------------+')
kwargs = dict(zip(args.kwargs[0::2], args.kwargs[1::2]))
experiments[exp](**kwargs)