-
Notifications
You must be signed in to change notification settings - Fork 2
/
cifar100_train.py
351 lines (298 loc) · 20.5 KB
/
cifar100_train.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
import utils.csv_record as csv_record
import torch
import torch.nn as nn
import main
import test
import copy
import config
from cifar100_trigger import cifar100_trigger
def Cifar100Train(helper, start_epoch, local_model, target_model, is_poison, agent_name_keys, noise_trigger,
intinal_trigger):
epochs_submit_update_dict = dict()
epochs_change_update_dict = dict()
num_samples_dict = dict()
current_number_of_adversaries = 0
for temp_name in agent_name_keys:
if temp_name in helper.params['adversary_list']:
current_number_of_adversaries += 1
poisonupdate_dict = dict()
poisonloss_dict = dict()
user_grads = []
server_update = dict()
models = copy.deepcopy(local_model)
models.copy_params(target_model.state_dict())
IsTrigger = False
tuned_trigger = noise_trigger
for model_id in range(helper.params['no_models']):
epochs_local_update_list = []
last_local_model = dict()
client_grad = []
for name, data in target_model.state_dict().items():
last_local_model[name] = target_model.state_dict()[name].clone()
agent_name_key = agent_name_keys[model_id]
model = local_model
normalmodel = copy.deepcopy(local_model)
model.copy_params(target_model.state_dict())
normalmodel.copy_params(target_model.state_dict())
optimizer = torch.optim.SGD(model.parameters(), lr=helper.params['lr'],
momentum=helper.params['momentum'],
weight_decay=helper.params['decay'])
normalOptimizer = torch.optim.SGD(normalmodel.parameters(), lr=helper.params['lr'],
momentum=helper.params['momentum'],
weight_decay=helper.params['decay'])
model.train()
normalmodel.train()
adversarial_index = -1
localmodel_poison_epochs = helper.params['poison_epochs']
if is_poison and agent_name_key in helper.params['adversary_list']:
for temp_index in range(0, len(helper.params['adversary_list'])):
if int(agent_name_key) == helper.params['adversary_list'][temp_index]:
adversarial_index = temp_index
localmodel_poison_epochs = helper.params[str(temp_index) + '_poison_epochs']
main.logger.info(
f'poison local model {agent_name_key} index {adversarial_index} ')
break
if len(helper.params['adversary_list']) == 1:
adversarial_index = -1
for epoch in range(start_epoch, start_epoch + helper.params['aggr_epoch_interval']):
target_params_variables = dict()
for name, param in target_model.named_parameters():
target_params_variables[name] = last_local_model[name].clone().detach().requires_grad_(False)
if is_poison and agent_name_key in helper.params['adversary_list'] and (epoch in localmodel_poison_epochs):
main.logger.info('poison_now')
if not IsTrigger:
tuned_trigger = cifar100_trigger(helper, local_model, target_model, noise_trigger, intinal_trigger)
IsTrigger = True
poison_lr = helper.params['poison_lr']
internal_epoch_num = helper.params['internal_poison_epochs']
step_lr = helper.params['poison_step_lr']
main.logger.info('normally training')
_, data_iterator = helper.train_data[agent_name_key]
normalData_size = 0
for batch_id, batch in enumerate(data_iterator):
normalOptimizer.zero_grad()
normalData, normalTargets = helper.get_batch(data_iterator, batch, evaluation=False)
normalData_size += len(normalData)
normaloutput = normalmodel(normalData)
loss = nn.functional.cross_entropy(normaloutput, normalTargets)
loss.backward()
normalOptimizer.step()
normal_params_variables = dict()
for name, param in normalmodel.named_parameters():
normal_params_variables[name] = normalmodel.state_dict()[name].clone().detach().requires_grad_(
False)
normalmodel_updates_dict = dict()
for name, data in normalmodel.state_dict().items():
normalmodel_updates_dict[name] = torch.zeros_like(data)
normalmodel_updates_dict[name] = (data - last_local_model[name])
main.logger.info('save normal model, normally training ending')
poison_optimizer = torch.optim.SGD(model.parameters(), lr=poison_lr,
momentum=helper.params['momentum'],
weight_decay=helper.params['decay'])
scheduler = torch.optim.lr_scheduler.MultiStepLR(poison_optimizer,
milestones=[0.2 * internal_epoch_num,
0.8 * internal_epoch_num], gamma=0.1)
temp_local_epoch = (epoch - 1) * internal_epoch_num
for internal_epoch in range(1, internal_epoch_num + 1):
temp_local_epoch += 1
_, data_iterator = helper.train_data[agent_name_key]
poison_data_count = 0
total_loss = 0.
correct = 0
dataset_size = 0
dis2global_list = []
for batch_id, batch in enumerate(data_iterator):
data, targets, poison_num = helper.get_poison_batch(batch, tuned_trigger,
adversarial_index=adversarial_index,
evaluation=False)
poison_optimizer.zero_grad()
dataset_size += len(data)
poison_data_count += poison_num
output = model(data)
class_loss = nn.functional.cross_entropy(output, targets)
loss = class_loss
if helper.params['attack_methods'] == 'CerP':
malDistance_Loss = helper.model_dist_norm_var(model, normal_params_variables)
sum_cs = 0
otheradnum = 0
if poisonupdate_dict:
for otherAd in helper.params['adversary_list']:
if otherAd == agent_name_key:
continue
else:
if otherAd in poisonupdate_dict.keys():
otheradnum += 1
otherAd_variables = dict()
for name, data in poisonupdate_dict[otherAd].items():
otherAd_variables[name] = poisonupdate_dict[otherAd][
name].clone().detach().requires_grad_(False)
sum_cs += helper.model_cosine_similarity(model, otherAd_variables)
loss = class_loss + helper.params['alpha_loss'] * malDistance_Loss + \
helper.params['beta_loss'] * sum_cs
poisonloss_dict[agent_name_key] = loss
loss.backward()
if helper.params['aggregation_methods'] == config.AGGR_BULYAN or \
helper.params['aggregation_methods'] == config.AGGR_MKRUM or \
helper.params['aggregation_methods'] == config.AGGR_FOOLSGOLD:
for i, (name, params) in enumerate(model.named_parameters()):
if params.requires_grad:
if internal_epoch == 1 and batch_id == 0:
client_grad.append(params.grad.clone())
else:
client_grad[i] += params.grad.clone()
poison_optimizer.step()
total_loss += loss.data
pred = output.data.max(1)[1]
correct += pred.eq(targets.data.view_as(pred)).cpu().sum().item()
if step_lr:
scheduler.step()
main.logger.info(f'Current lr: {scheduler.get_lr()}')
acc = 100.0 * (float(correct) / float(dataset_size))
total_l = total_loss / dataset_size
main.logger.info(
'___PoisonTrain {} , epoch {:3d}, local model {}, internal_epoch {:3d}, Average loss: {:.4f}, '
'Accuracy: {}/{} ({:.4f}%), train_poison_data_count: {}'.format(model.name, epoch,
agent_name_key,
internal_epoch,
total_l, correct, dataset_size,
acc, poison_data_count))
csv_record.train_result.append(
[agent_name_key, temp_local_epoch,
epoch, internal_epoch, total_l.item(), acc, correct, dataset_size])
if helper.params['vis_train']:
model.train_vis(main.vis, temp_local_epoch,
acc, loss=total_l, eid=helper.params['environment_name'], is_poisoned=True,
name=str(agent_name_key))
num_samples_dict[agent_name_key] = dataset_size
if helper.params["batch_track_distance"]:
main.logger.info(
f'MODEL {model_id}. P-norm is {helper.model_global_norm(model):.4f}. '
f'Distance to the global model: {dis2global_list}. ')
# internal epoch finish
main.logger.info(f'Global model norm: {helper.model_global_norm(target_model)}.')
main.logger.info(f'Norm before scaling: {helper.model_global_norm(model)}. '
f'Distance: {helper.model_dist_norm(model, target_params_variables)}')
if helper.params['one-shot']:
main.logger.info(f'will scale.')
epoch_loss, epoch_acc, epoch_corret, epoch_total = test.Mytest(helper=helper, epoch=epoch,
model=model, is_poison=False,
visualize=False,
agent_name_key=agent_name_key)
csv_record.test_result.append(
[agent_name_key, epoch, epoch_loss, epoch_acc, epoch_corret, epoch_total])
epoch_loss, epoch_acc, epoch_corret, epoch_total = test.Mytest_poison(helper=helper,
epoch=epoch,
model=model,
noise_trigger=tuned_trigger,
is_poison=True,
visualize=False,
agent_name_key=agent_name_key)
csv_record.posiontest_result.append(
[agent_name_key, epoch, epoch_loss, epoch_acc, epoch_corret, epoch_total])
clip_rate = helper.params['scale_weights_poison']
main.logger.info(f"Scaling by {clip_rate}")
if helper.params['aggregation_methods'] == config.AGGR_FOOLSGOLD or \
helper.params['aggregation_methods'] == config.AGGR_BULYAN or \
helper.params['aggregation_methods'] == config.AGGR_MKRUM:
client_gradss = [i * clip_rate for i in client_grad]
client_grad = client_gradss
else:
for key, value in model.state_dict().items():
target_value = last_local_model[key]
new_value = target_value + (value - target_value) * clip_rate
model.state_dict()[key].copy_(new_value)
distance = helper.model_dist_norm(model, target_params_variables)
main.logger.info(
f'Scaled Norm after poisoning: '
f'{helper.model_global_norm(model)}, distance: {distance}')
csv_record.scale_temp_one_row.append(epoch)
csv_record.scale_temp_one_row.append(round(distance, 4))
distance = helper.model_dist_norm(model, target_params_variables)
main.logger.info(f"Total norm for {current_number_of_adversaries} "
f"adversaries is: {helper.model_global_norm(model)}. distance: {distance}")
else:
temp_local_epoch = (epoch - 1) * helper.params['internal_epochs']
for internal_epoch in range(1, helper.params['internal_epochs'] + 1):
temp_local_epoch += 1
_, data_iterator = helper.train_data[agent_name_key]
total_loss = 0.
correct = 0
dataset_size = 0
dis2global_list = []
old_gradient = {}
for batch_id, batch in enumerate(data_iterator):
optimizer.zero_grad()
data, targets = helper.get_batch(data_iterator, batch, evaluation=False)
dataset_size += len(data)
output = model(data)
loss = nn.functional.cross_entropy(output, targets)
loss.backward()
if helper.params['aggregation_methods'] == config.AGGR_BULYAN or \
helper.params['aggregation_methods'] == config.AGGR_MKRUM or \
helper.params['aggregation_methods'] == config.AGGR_FOOLSGOLD:
for i, (name, params) in enumerate(model.named_parameters()):
if params.requires_grad:
if internal_epoch == 1 and batch_id == 0:
client_grad.append(params.grad.clone())
else:
client_grad[i] += params.grad.clone()
optimizer.step()
total_loss += loss.data
pred = output.data.max(1)[1]
correct += pred.eq(targets.data.view_as(pred)).cpu().sum().item()
acc = 100.0 * (float(correct) / float(dataset_size))
total_l = total_loss / dataset_size
main.logger.info(
'___Train {}, epoch {:3d}, local model {}, internal_epoch {:3d}, Average loss: {:.4f}, '
'Accuracy: {}/{} ({:.4f}%)'.format(model.name, epoch, agent_name_key, internal_epoch,
total_l, correct, dataset_size,
acc))
csv_record.train_result.append([agent_name_key, temp_local_epoch,
epoch, internal_epoch, total_l.item(), acc, correct, dataset_size])
if helper.params['vis_train']:
model.train_vis(main.vis, temp_local_epoch,
acc, loss=total_l, eid=helper.params['environment_name'], is_poisoned=False,
name=str(agent_name_key))
num_samples_dict[agent_name_key] = dataset_size
if helper.params["batch_track_distance"]:
main.logger.info(
f'MODEL {model_id}. P-norm is {helper.model_global_norm(model):.4f}. '
f'Distance to the global model: {dis2global_list}. ')
epoch_loss, epoch_acc, epoch_corret, epoch_total = test.Mytest(helper=helper, epoch=epoch,
model=model, is_poison=False,
visualize=True,
agent_name_key=agent_name_key)
csv_record.test_result.append([agent_name_key, epoch, epoch_loss, epoch_acc, epoch_corret, epoch_total,
helper.model_dist_norm(model, target_params_variables)])
if is_poison:
if agent_name_key in helper.params['adversary_list'] and (epoch in localmodel_poison_epochs):
epoch_loss, epoch_acc, epoch_corret, epoch_total = test.Mytest_poison(helper=helper,
epoch=epoch,
model=model,
noise_trigger=tuned_trigger,
is_poison=True,
visualize=True,
agent_name_key=agent_name_key)
csv_record.posiontest_result.append(
[agent_name_key, epoch, epoch_loss, epoch_acc, epoch_corret, epoch_total,
helper.model_dist_norm(model, target_params_variables)])
Ad_model_dict = dict()
for name, data in model.state_dict().items():
Ad_model_dict[name] = model.state_dict()[name].clone().detach().requires_grad_(False)
poisonupdate_dict[agent_name_key] = Ad_model_dict
local_model_update_dict = dict()
for name, data in model.state_dict().items():
local_model_update_dict[name] = torch.zeros_like(data)
local_model_update_dict[name] = (data - last_local_model[name])
last_local_model[name] = copy.deepcopy(data)
if helper.params['aggregation_methods'] == config.AGGR_FOOLSGOLD or \
helper.params['aggregation_methods'] == config.AGGR_BULYAN or \
helper.params['aggregation_methods'] == config.AGGR_MEDIAN or \
helper.params['aggregation_methods'] == config.AGGR_MKRUM:
epochs_local_update_list.append(client_grad)
else:
epochs_local_update_list.append(local_model_update_dict)
epochs_change_update_dict[agent_name_key] = epochs_local_update_list
for name, params in epochs_change_update_dict.items():
epochs_submit_update_dict[name] = epochs_change_update_dict[name]
return epochs_submit_update_dict, num_samples_dict, user_grads, server_update, tuned_trigger