-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathdefense.py
195 lines (165 loc) · 8.13 KB
/
defense.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
import time
start_time = time.time()
import multiprocessing as mp
mp.set_start_method('fork')
import ctypes as c
import argparse
import os
import numpy as np
import pandas as pd
from PIL import Image
import image_generators
import task_utils
task_utils.start_time = start_time
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--input_dir', required=True, type=str, \
help='Input directory with images.')
parser.add_argument('--output_file', required=True, type=str, \
help='Output directory with images.')
parser.add_argument('--train_batch_size', default=24, type=int, \
help='How many images process at one time.')
parser.add_argument('--num_samples', default=-1, type=int, \
help='Number of samples, -1 for all samples')
args = parser.parse_args()
input_dir_abs = os.path.abspath(args.input_dir)
images_info = image_generators.get_names_and_labels(\
args.input_dir, mode='test')
print('Total images:', len(images_info))
eps = 8.
if args.num_samples < 0:
num_samples = len(images_info)
else:
num_samples = args.num_samples
use_avg_pred = True
step_size = eps
noise_size = eps*0.2
grad_aug_scale = 0.02
print('Loading images')
# each image_data element: filename, img, lbl
image_data = image_generators.load_images_into_batches(\
images_info, args.train_batch_size, \
max_samples=num_samples, to_buffer=True)
print('Generating placeholders')
placeholders = {}
for i, data in enumerate(image_data):
imgmat_size = (len(data[0]), 299, 299, 3)
lblmat_size = (len(data[0]), 1000)
data_min = task_utils.get_raw_array(init=np.clip(task_utils.get_array(data[1], imgmat_size)-eps, 0, None))
data_max = task_utils.get_raw_array(init=np.clip(task_utils.get_array(data[1], imgmat_size)+eps, None, 255))
data_actual = data[1]
grad_mat = task_utils.get_raw_array(dims=imgmat_size)
lbl_mat = task_utils.get_raw_array(dims=lblmat_size)
# data, min, max, grad, lbl, pseudo-label matrix
placeholders[i] = (\
data[0], \
data_actual, \
data_min, \
data_max, \
grad_mat, \
data[2], \
lbl_mat)
print('Preparing functions')
# each tuple is a sequence of pairs followed by two floats
# the pairs describe which network to use and the rand_repeat for accumulating gradients
# the two floats are the step size and noise size of that FGSM step
source_models = ['incresv2ensadv','inceptionv3adv', 'inceptionv3ens3adv', 'inceptionv3ens4adv']
dist_pairs = [('inceptionv3ens3adv', 'inceptionv3ens4adv'), \
('inceptionv3ens3adv', 'incresv2ensadv'), \
('inceptionv3ens4adv', 'incresv2ensadv'), \
('inceptionv3adv', 'incresv2ensadv'), \
('inceptionv3ens3adv', 'inceptionv3adv'), \
('inceptionv3ens4adv', 'inceptionv3adv'), \
]
step_size = 1.
noise_size = 0.4
grad_aug_scale = 0.01
pred_aug_scale = 0.01
plan = [\
(('RST', 'def'), \
# ((source_models, dist_pairs), \
((('inceptionv3ens3adv','inceptionv3ens4adv'), 1), step_size, noise_size), \
((('inceptionv3ens3adv','inceptionv3ens4adv'), 1), step_size, noise_size), \
((('inceptionv3ens4adv','incresv2ensadv'), 1), (('inceptionv3ens3adv','incresv2ensadv'), 1), step_size, noise_size), \
((('inceptionv3ens3adv','inceptionv3ens4adv'), 1), step_size, noise_size), \
((('inceptionv3ens4adv','incresv2ensadv'), 1), (('inceptionv3ens3adv','incresv2ensadv'), 1), step_size, noise_size), \
((('inceptionv3ens3adv','inceptionv3ens4adv'), 1), step_size, noise_size), \
((('inceptionv3ens4adv','inceptionv3adv'), 1), (('inceptionv3ens3adv','incresv2ensadv'), 1), step_size, noise_size)), \
]
task_list = []
phase_info = {}
next_task = {}
for i_phase, phase in enumerate(plan):
last_task_in_batch = {}
if phase[0][0] == 'RST':
task = ('phase {0} restore from {1}'.format(i_phase, phase[0][1]), \
(), 7, (phase[0][1],))
task_list.append(task)
phase_info[i_phase] = (len(task_list)-1, set(), set())
else:
task = ('phase {0} load {1}'.format(i_phase, phase[0]), (), 5+1*(i_phase==0), \
(phase[0][0], phase[0][1]))
task_list.append(task)
# id of loading task, all tasks other than load, first tasks after load
phase_info[i_phase] = (len(task_list)-1, set(), set())
for phid, (fname_list, imgs, imgs_min, imgs_max, grads, lbls, lbls_mat) in placeholders.items():
for i_pl, pl in enumerate(phase[1:]):
if pl[-1]>1e-5:
task = ('phase {0} batch {1} step {2}, noise {3:.2f}'.format(i_phase, phid, i_pl, pl[-1]), \
(fname_list,imgs,None,grads,imgs_min,imgs_max,lbls_mat),4,\
(pl[-1],))
task_list.append(task)
# COPIED
if phid not in last_task_in_batch:
phase_info[i_phase][2].add(len(task_list)-1)
else:
next_task[last_task_in_batch[phid]] = len(task_list)-1
last_task_in_batch[phid] = len(task_list)-1
phase_info[i_phase][1].add(len(task_list)-1)
for j_stp, stp in enumerate(pl[:-2]):
task = ('phase {0} batch {1} step {2}, grad {3} repeat {4}'.format(i_phase, phid, i_pl, stp[0], stp[1]), \
(fname_list,imgs,None,grads,imgs_min,imgs_max,lbls_mat),0,\
(None, stp[0], grad_aug_scale, stp[1]))
task_list.append(task)
# COPIED
if phid not in last_task_in_batch:
phase_info[i_phase][2].add(len(task_list)-1)
else:
next_task[last_task_in_batch[phid]] = len(task_list)-1
last_task_in_batch[phid] = len(task_list)-1
phase_info[i_phase][1].add(len(task_list)-1)
task = ('phase {0} batch {1} step {2}, FGSM step, step size {3:.2f}'.format(i_phase, phid, i_pl, pl[-2]), \
(fname_list,imgs,None,grads,imgs_min,imgs_max,lbls_mat),1,\
(pl[-2],))
task_list.append(task)
# COPIED
if phid not in last_task_in_batch:
phase_info[i_phase][2].add(len(task_list)-1)
else:
next_task[last_task_in_batch[phid]] = len(task_list)-1
last_task_in_batch[phid] = len(task_list)-1
phase_info[i_phase][1].add(len(task_list)-1)
task = ('phase {0} batch {1}, final pred'.format(i_phase, phid), \
(fname_list,imgs,None,grads,imgs_min,imgs_max,lbls_mat),3,(pred_aug_scale,))
task_list.append(task)
# COPIED
if phid not in last_task_in_batch:
phase_info[i_phase][2].add(len(task_list)-1)
else:
next_task[last_task_in_batch[phid]] = len(task_list)-1
last_task_in_batch[phid] = len(task_list)-1
phase_info[i_phase][1].add(len(task_list)-1)
print('Preparation finished', time.time()-start_time)
print(len(task_list), 'tasks')
task_utils.run_tasks(task_list, phase_info, next_task, \
verbose=False, cpu_worker=1, is_defense=True)
with open(args.output_file, 'w') as f:
for phid, (fnames, _, _, _, _, _, lbls_mat) in placeholders.items():
batch_preds = task_utils.get_array(lbls_mat, (len(fnames),1000)).argmax(axis=1)
for img, pred in zip(fnames, batch_preds):
_ = f.write('{0},{1}\n'.format(os.path.split(img)[1], pred+1))
print('Time:', time.time()-start_time)
print('\n'.join(str(u) for u in plan))
print()
if __name__ == '__main__':
main()