-
Notifications
You must be signed in to change notification settings - Fork 1
/
FL_train.py
430 lines (349 loc) · 21.6 KB
/
FL_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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
from args import args
import torch
import torch.nn as nn
import models
from utils import *
from AGRs import *
from Attacks import *
import copy
import numpy as np
import torch.optim as optim
from torch.optim.lr_scheduler import CosineAnnealingLR
from collections import defaultdict
import collections
#####################################FRL#########################################
def FRL_train(tr_loaders, te_loader):
print ("#########Federated Learning using Rankings############")
args.conv_type = 'MaskConv'
args.conv_init = 'signed_constant'
args.bn_type="NonAffineNoStatsBN"
n_attackers = int(args.nClients * args.at_fractions)
sss = "fraction of maliciou clients: %.2f | total number of malicious clients: %d"%(args.at_fractions,
n_attackers)
print (sss)
with (args.run_base_dir / "output.txt").open("a") as f:
f.write("\n"+str(sss))
criterion = nn.CrossEntropyLoss().to(args.device)
FLmodel = getattr(models, args.model)().to(args.device)
initial_scores={}
for n, m in FLmodel.named_modules():
if hasattr(m, "scores"):
initial_scores[str(n)]=m.scores.detach().clone().flatten().sort()[0]
e=0
t_best_acc=0
while e <= args.FL_global_epochs:
torch.cuda.empty_cache()
round_users = np.random.choice(args.nClients, args.round_nclients, replace=False)
round_malicious = round_users[round_users < n_attackers]
round_benign = round_users[round_users >= n_attackers]
while len(round_malicious)>=args.round_nclients/2:
round_users = np.random.choice(args.nClients, args.round_nclients, replace=False)
round_malicious = round_users[round_users < n_attackers]
round_benign = round_users[round_users >= n_attackers]
user_updates=collections.defaultdict(list)
########################################benign Client Learning#########################################
for kk in round_benign:
mp = copy.deepcopy(FLmodel)
optimizer = optim.SGD([p for p in mp.parameters() if p.requires_grad], lr=args.lr*(args.lrdc**e), momentum=args.momentum, weight_decay=args.wd)
scheduler = CosineAnnealingLR(optimizer, T_max=args.local_epochs)
for epoch in range(args.local_epochs):
train_loss, train_acc = train(tr_loaders[kk], mp, criterion, optimizer, args.device)
scheduler.step()
for n, m in mp.named_modules():
if hasattr(m, "scores"):
rank=Find_rank(m.scores.detach().clone())
user_updates[str(n)]=rank[None,:] if len(user_updates[str(n)]) == 0 else torch.cat((user_updates[str(n)], rank[None,:]), 0)
del rank
del optimizer, mp, scheduler
########################################malicious Client Learning######################################
if len(round_malicious):
sum_args_sorts_mal={}
for kk in np.random.choice(n_attackers, min(n_attackers, args.rand_mal_clients), replace=False):
torch.cuda.empty_cache()
mp = copy.deepcopy(FLmodel)
optimizer = optim.SGD([p for p in mp.parameters() if p.requires_grad], lr=args.lr*(args.lrdc**e), momentum=args.momentum, weight_decay=args.wd)
scheduler = CosineAnnealingLR(optimizer, T_max=args.local_epochs)
for epoch in range(args.local_epochs):
train_loss, train_acc = train(tr_loaders[kk], mp, criterion, optimizer, args.device)
scheduler.step()
for n, m in mp.named_modules():
if hasattr(m, "scores"):
rank=Find_rank(m.scores.detach().clone())
rank_arg=torch.sort(rank)[1]
if str(n) in sum_args_sorts_mal:
sum_args_sorts_mal[str(n)]+=rank_arg
else:
sum_args_sorts_mal[str(n)]=rank_arg
del rank, rank_arg
del optimizer, mp, scheduler
for n, m in FLmodel.named_modules():
if hasattr(m, "scores"):
rank_mal_agr=torch.sort(sum_args_sorts_mal[str(n)], descending=True)[1]
for kk in round_malicious:
user_updates[str(n)]=rank_mal_agr[None,:] if len(user_updates[str(n)]) == 0 else torch.cat((user_updates[str(n)], rank_mal_agr[None,:]), 0)
del sum_args_sorts_mal
########################################Server AGR#########################################
FRL_Vote(FLmodel, user_updates, initial_scores)
del user_updates
if (e+1)%1==0:
t_loss, t_acc = test(te_loader, FLmodel, criterion, args.device)
if t_acc>t_best_acc:
t_best_acc=t_acc
sss='e %d | malicious users: %d | test acc %.4f test loss %.6f best test_acc %.4f' % (e, len(round_malicious), t_acc, t_loss, t_best_acc)
print (sss)
with (args.run_base_dir / "output.txt").open("a") as f:
f.write("\n"+str(sss))
e+=1
#####################################FedAVG#########################################
def FedAVG(tr_loaders, te_loader):
print ("#########Federated Learning using FedAVG############")
args.conv_type = 'StandardConv'
args.bn_type="NonAffineNoStatsBN"
n_attackers = int(args.nClients * args.at_fractions)
sss = "fraction of maliciou clients: %.2f | total number of malicious clients: %d"%(args.at_fractions,
n_attackers)
print (sss)
with (args.run_base_dir / "output.txt").open("a") as f:
f.write("\n"+str(sss))
criterion = nn.CrossEntropyLoss().to(args.device)
FLmodel = getattr(models, args.model)().to(args.device)
model_received = []
for i, (name, param) in enumerate(FLmodel.state_dict().items()):
model_received = param.view(-1).data.type(torch.cuda.FloatTensor) if len(model_received) == 0 else torch.cat((model_received, param.view(-1).data.type(torch.cuda.FloatTensor)))
e=0
t_best_acc=0
while e <= args.FL_global_epochs:
torch.cuda.empty_cache()
round_users = np.random.choice(args.nClients, args.round_nclients, replace=False)
round_malicious = round_users[round_users < n_attackers]
round_benign = round_users[round_users >= n_attackers]
while len(round_malicious)>=args.round_nclients/2:
round_users = np.random.choice(args.nClients, args.round_nclients, replace=False)
round_malicious = round_users[round_users < n_attackers]
round_benign = round_users[round_users >= n_attackers]
user_updates = []
########################################benign Client Learning#########################################
for kk in round_benign:
mp = copy.deepcopy(FLmodel)
optimizer = optim.SGD([p for p in mp.parameters() if p.requires_grad], lr=args.lr*(args.lrdc**e), momentum=args.momentum, weight_decay=args.wd)
scheduler = CosineAnnealingLR(optimizer, T_max=args.local_epochs)
for epoch in range(args.local_epochs):
train_loss, train_acc = train(tr_loaders[kk], mp, criterion, optimizer, args.device)
scheduler.step()
params = []
for i, (name, param) in enumerate(mp.state_dict().items()):
params = param.view(-1).data.type(torch.cuda.FloatTensor) if len(params) == 0 else torch.cat((params, param.view(-1).data.type(torch.cuda.FloatTensor)))
update = (params - model_received)
user_updates = update[None,:] if len(user_updates) == 0 else torch.cat((user_updates, update[None,:]), 0)
del optimizer, mp, scheduler
########################################malicious Client Learning######################################
for kk in round_malicious:
scale=100000
mal_update = scale * model_received
user_updates = mal_update[None,:] if len(user_updates) == 0 else torch.cat((user_updates, mal_update[None,:]), 0)
########################################Server AGR#########################################
agg_update = torch.mean(user_updates, dim=0)
del user_updates
model_received = model_received + agg_update
FLmodel = getattr(models, args.model)().to(args.device)
start_idx=0
state_dict = {}
previous_name = 'none'
for i, (name, param) in enumerate(FLmodel.state_dict().items()):
start_idx = 0 if i == 0 else start_idx + len(FLmodel.state_dict()[previous_name].data.view(-1))
start_end = start_idx + len(FLmodel.state_dict()[name].data.view(-1))
params = model_received[start_idx:start_end].reshape(FLmodel.state_dict()[name].data.shape)
state_dict[name] = params
previous_name = name
FLmodel.load_state_dict(state_dict)
if (e+1)%1==0:
t_loss, t_acc = test(te_loader, FLmodel, criterion, args.device)
if t_acc>t_best_acc:
t_best_acc=t_acc
sss='e %d | malicious users: %d | test acc %.4f test loss %.6f best test_acc %.4f' % (e, len(round_malicious), t_acc, t_loss, t_best_acc)
print (sss)
with (args.run_base_dir / "output.txt").open("a") as f:
f.write("\n"+str(sss))
if math.isnan(t_loss) or t_loss > 10000:
print('val loss %f... exit: The global model is totally destroyed by the adversary' % t_loss)
break
e+=1
#######################################Trimmed-Mean######################################
def Tr_Mean(tr_loaders, te_loader):
print ("#########Federated Learning using Trimmed Mean############")
args.conv_type = 'StandardConv'
args.bn_type="NonAffineNoStatsBN"
n_attackers = int(args.nClients * args.at_fractions)
sss = "fraction of maliciou clients: %.2f | total number of malicious clients: %d"%(args.at_fractions,
n_attackers)
print (sss)
with (args.run_base_dir / "output.txt").open("a") as f:
f.write("\n"+str(sss))
criterion = nn.CrossEntropyLoss().to(args.device)
FLmodel = getattr(models, args.model)().to(args.device)
model_received = []
for i, (name, param) in enumerate(FLmodel.state_dict().items()):
model_received = param.view(-1).data.type(torch.cuda.FloatTensor) if len(model_received) == 0 else torch.cat((model_received, param.view(-1).data.type(torch.cuda.FloatTensor)))
e=0
t_best_acc=0
while e <= args.FL_global_epochs:
torch.cuda.empty_cache()
round_users = np.random.choice(args.nClients, args.round_nclients, replace=False)
round_malicious = round_users[round_users < n_attackers]
round_benign = round_users[round_users >= n_attackers]
while len(round_malicious)>=args.round_nclients/2:
round_users = np.random.choice(args.nClients, args.round_nclients, replace=False)
round_malicious = round_users[round_users < n_attackers]
round_benign = round_users[round_users >= n_attackers]
user_updates = []
########################################benign Client Learning#########################################
for kk in round_benign:
mp = copy.deepcopy(FLmodel)
optimizer = optim.SGD([p for p in mp.parameters() if p.requires_grad], lr=args.lr*(args.lrdc**e), momentum=args.momentum, weight_decay=args.wd)
scheduler = CosineAnnealingLR(optimizer, T_max=args.local_epochs)
for epoch in range(args.local_epochs):
train_loss, train_acc = train(tr_loaders[kk], mp, criterion, optimizer, args.device)
scheduler.step()
params = []
for i, (name, param) in enumerate(mp.state_dict().items()):
params = param.view(-1).data.type(torch.cuda.FloatTensor) if len(params) == 0 else torch.cat((params, param.view(-1).data.type(torch.cuda.FloatTensor)))
update = (params - model_received)
user_updates = update[None,:] if len(user_updates) == 0 else torch.cat((user_updates, update[None,:]), 0)
del optimizer, mp, scheduler
########################################malicious Client Learning######################################
if len(round_malicious):
mal_updates = []
for kk in np.random.choice(n_attackers, min(n_attackers, args.rand_mal_clients), replace=False):
mp = copy.deepcopy(FLmodel)
optimizer = optim.SGD([p for p in mp.parameters() if p.requires_grad], lr=args.lr*(args.lrdc**e), momentum=args.momentum, weight_decay=args.wd)
scheduler = CosineAnnealingLR(optimizer, T_max=args.local_epochs)
for epoch in range(args.local_epochs):
train_loss, train_acc = train(tr_loaders[kk], mp, criterion, optimizer, args.device)
scheduler.step()
params = []
for i, (name, param) in enumerate(mp.state_dict().items()):
params = param.view(-1).data.type(torch.cuda.FloatTensor) if len(params) == 0 else torch.cat((params, param.view(-1).data.type(torch.cuda.FloatTensor)))
update = (params - model_received)
mal_updates = update[None,:] if len(mal_updates) == 0 else torch.cat((mal_updates, update[None,:]), 0)
del optimizer, mp, scheduler
mal_update = our_attack_trmean(mal_updates, len(round_malicious), dev_type='std', threshold=5.0)
del mal_updates
for kk in round_malicious:
user_updates = mal_update[None,:] if len(user_updates) == 0 else torch.cat((user_updates, mal_update[None,:]), 0)
########################################Server AGR#########################################
agg_update = tr_mean(user_updates, len(round_malicious))
del user_updates
model_received = model_received + agg_update
FLmodel = getattr(models, args.model)().to(args.device)
start_idx=0
state_dict = {}
previous_name = 'none'
for i, (name, param) in enumerate(FLmodel.state_dict().items()):
start_idx = 0 if i == 0 else start_idx + len(FLmodel.state_dict()[previous_name].data.view(-1))
start_end = start_idx + len(FLmodel.state_dict()[name].data.view(-1))
params = model_received[start_idx:start_end].reshape(FLmodel.state_dict()[name].data.shape)
state_dict[name] = params
previous_name = name
FLmodel.load_state_dict(state_dict)
if (e+1)%1==0:
t_loss, t_acc = test(te_loader, FLmodel, criterion, args.device)
if math.isnan(t_loss) or t_loss > 10000:
print('val loss %f... exit: The global model is totally destroyed by the adversary' % val_loss)
break
if t_acc>t_best_acc:
t_best_acc=t_acc
sss='e %d | malicious users: %d | test acc %.4f test loss %.6f best test_acc %.4f' % (e, len(round_malicious), t_acc, t_loss, t_best_acc)
print (sss)
with (args.run_base_dir / "output.txt").open("a") as f:
f.write("\n"+str(sss))
e+=1
############################Multi-Krum#########################################
def Mkrum(tr_loaders, te_loader):
print ("#########Federated Learning using Multi-Krum############")
args.conv_type = 'StandardConv'
args.bn_type="NonAffineNoStatsBN"
n_attackers = int(args.nClients * args.at_fractions)
sss = "fraction of maliciou clients: %.2f | total number of malicious clients: %d"%(args.at_fractions,
n_attackers)
print (sss)
with (args.run_base_dir / "output.txt").open("a") as f:
f.write("\n"+str(sss))
criterion = nn.CrossEntropyLoss().to(args.device)
FLmodel = getattr(models, args.model)().to(args.device)
model_received = []
for i, (name, param) in enumerate(FLmodel.state_dict().items()):
model_received = param.view(-1).data.type(torch.cuda.FloatTensor) if len(model_received) == 0 else torch.cat((model_received, param.view(-1).data.type(torch.cuda.FloatTensor)))
e=0
t_best_acc=0
while e <= args.FL_global_epochs:
torch.cuda.empty_cache()
round_users = np.random.choice(args.nClients, args.round_nclients, replace=False)
round_malicious = round_users[round_users < n_attackers]
round_benign = round_users[round_users >= n_attackers]
while len(round_malicious)>=args.round_nclients/2:
round_users = np.random.choice(args.nClients, args.round_nclients, replace=False)
round_malicious = round_users[round_users < n_attackers]
round_benign = round_users[round_users >= n_attackers]
user_updates = []
########################################benign Client Learning#########################################
for kk in round_benign:
mp = copy.deepcopy(FLmodel)
optimizer = optim.SGD([p for p in mp.parameters() if p.requires_grad], lr=args.lr*(args.lrdc**e), momentum=args.momentum, weight_decay=args.wd)
scheduler = CosineAnnealingLR(optimizer, T_max=args.local_epochs)
for epoch in range(args.local_epochs):
train_loss, train_acc = train(tr_loaders[kk], mp, criterion, optimizer, args.device)
scheduler.step()
params = []
for i, (name, param) in enumerate(mp.state_dict().items()):
params = param.view(-1).data.type(torch.cuda.FloatTensor) if len(params) == 0 else torch.cat((params, param.view(-1).data.type(torch.cuda.FloatTensor)))
update = (params - model_received)
user_updates = update[None,:] if len(user_updates) == 0 else torch.cat((user_updates, update[None,:]), 0)
del optimizer, mp, scheduler
########################################malicious Client Learning######################################
if len(round_malicious):
mal_updates = []
for kk in np.random.choice(n_attackers, min(n_attackers, args.rand_mal_clients), replace=False):
mp = copy.deepcopy(FLmodel)
optimizer = optim.SGD([p for p in mp.parameters() if p.requires_grad], lr=args.lr*(args.lrdc**e), momentum=args.momentum, weight_decay=args.wd)
scheduler = CosineAnnealingLR(optimizer, T_max=args.local_epochs)
for epoch in range(args.local_epochs):
train_loss, train_acc = train(tr_loaders[kk], mp, criterion, optimizer, args.device)
scheduler.step()
params = []
for i, (name, param) in enumerate(mp.state_dict().items()):
params = param.view(-1).data.type(torch.cuda.FloatTensor) if len(params) == 0 else torch.cat((params, param.view(-1).data.type(torch.cuda.FloatTensor)))
update = (params - model_received)
mal_updates = update[None,:] if len(mal_updates) == 0 else torch.cat((mal_updates, update[None,:]), 0)
del optimizer, mp, scheduler
mal_agg_update = torch.mean(mal_updates, 0)
mal_update = our_attack_mkrum(mal_updates, mal_agg_update, len(round_malicious), dev_type='std', threshold=5.0, threshold_diff=1e-5)
del mal_updates
for kk in round_malicious:
user_updates = mal_update[None,:] if len(user_updates) == 0 else torch.cat((user_updates, mal_update[None,:]), 0)
########################################Server AGR#########################################
agg_update, krum_candidate = multi_krum(user_updates, len(round_malicious), multi_k=True)
del user_updates
model_received = model_received + agg_update
FLmodel = getattr(models, args.model)().to(args.device)
start_idx=0
state_dict = {}
previous_name = 'none'
for i, (name, param) in enumerate(FLmodel.state_dict().items()):
start_idx = 0 if i == 0 else start_idx + len(FLmodel.state_dict()[previous_name].data.view(-1))
start_end = start_idx + len(FLmodel.state_dict()[name].data.view(-1))
params = model_received[start_idx:start_end].reshape(FLmodel.state_dict()[name].data.shape)
state_dict[name] = params
previous_name = name
FLmodel.load_state_dict(state_dict)
if (e+1)%1==0:
t_loss, t_acc = test(te_loader, FLmodel, criterion, args.device)
if math.isnan(t_loss) or t_loss > 10000:
print('val loss %f... exit: The global model is totally destroyed by the adversary' % val_loss)
break
if t_acc>t_best_acc:
t_best_acc=t_acc
sss='e %d | malicious users: %d | test acc %.4f test loss %.6f best test_acc %.4f' % (e, len(round_malicious), t_acc, t_loss, t_best_acc)
print (sss)
with (args.run_base_dir / "output.txt").open("a") as f:
f.write("\n"+str(sss))
e+=1