forked from ZFancy/SFAT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
update.py
400 lines (337 loc) · 17.2 KB
/
update.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
import copy
import torch
import numpy as np
import torch.nn.functional as F
import attack_generator as attack
from torch import nn
from torch.utils.data import DataLoader, Dataset
def TRADES_loss(adv_logits, natural_logits, target, beta):
batch_size = len(target)
criterion_kl = nn.KLDivLoss(size_average=False).cuda()
loss_natural = nn.CrossEntropyLoss(reduction='mean')(natural_logits, target)
loss_robust = (1.0 / batch_size) * criterion_kl(F.log_softmax(adv_logits, dim=1),
F.softmax(natural_logits, dim=1))
loss = loss_natural + beta * loss_robust
return loss
def MART_loss(adv_logits, natural_logits, target, beta):
kl = nn.KLDivLoss(reduction='none')
batch_size = len(target)
adv_probs = F.softmax(adv_logits, dim=1)
tmp1 = torch.argsort(adv_probs, dim=1)[:, -2:]
new_y = torch.where(tmp1[:, -1] == target, tmp1[:, -2], tmp1[:, -1])
loss_adv = F.cross_entropy(adv_logits, target) + F.nll_loss(torch.log(1.0001 - adv_probs + 1e-12), new_y)
nat_probs = F.softmax(natural_logits, dim=1)
true_probs = torch.gather(nat_probs, 1, (target.unsqueeze(1)).long()).squeeze()
loss_robust = (1.0 / batch_size) * torch.sum(
torch.sum(kl(torch.log(adv_probs + 1e-12), nat_probs), dim=1) * (1.0000001 - true_probs))
loss = loss_adv + float(beta) * loss_robust
return loss
class DatasetSplit(Dataset):
"""An abstract Dataset class wrapped around Pytorch Dataset class.
"""
def __init__(self, dataset, idxs):
self.dataset = dataset
self.idxs = [int(i) for i in idxs]
def __len__(self):
return len(self.idxs)
def __getitem__(self, item):
image, label = self.dataset[self.idxs[item]]
return torch.tensor(image), torch.tensor(label)
class LocalUpdate(object):
def __init__(self, args, dataset, idxs, logger, alg, anchor, anchor_mu, local_rank, aysn=False, method='AT'):
self.args = args
self.logger = logger
self.trainloader, self.testloader = self.train_test(
dataset, list(idxs))
self.device = 'cuda' if args.gpu else 'cpu'
self.criterion = nn.CrossEntropyLoss(reduction="mean").to(self.device)
self.alg = alg
self.anchor = anchor
self.anchor_mu = anchor_mu
self.local_rank = local_rank
self.asyn = aysn
self.method = method
def train_test(self, dataset, idxs):
"""
Returns train and test dataloaders for a given dataset
and user indexes.
"""
# split indexes for train, validation, and test (80, 10, 10)
idxs_train = idxs[:int(1.0*len(idxs))]
idxs_test = idxs[int(0.9*len(idxs)):]
trainloader = DataLoader(DatasetSplit(dataset, idxs_train),
batch_size=self.args.local_bs, shuffle=True)
testloader = DataLoader(DatasetSplit(dataset, idxs_test),
batch_size=int(len(idxs_test)/10), shuffle=False)
return trainloader, testloader
def update_weights(self, model, global_round):
# Set mode to train model
model.train()
epoch_loss = []
# Set optimizer for the local updates
if self.args.optimizer == 'sgd':
optimizer = torch.optim.SGD(model.parameters(), lr=self.args.lr,
momentum=self.args.momentum)
elif self.args.optimizer == 'adam':
optimizer = torch.optim.Adam(model.parameters(), lr=self.args.lr,
weight_decay=1e-4)
for iter in range(self.args.local_ep):
batch_loss = []
for batch_idx, (images, labels) in enumerate(self.trainloader):
images, labels = images.to(self.device), labels.to(self.device)
model.zero_grad()
log_probs = model(images)
loss = self.criterion(log_probs, labels)
loss.backward()
optimizer.step()
if self.args.verbose and (batch_idx % 10 == 0):
print('| Global Round : {} | Local Epoch : {} | [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
global_round, iter, batch_idx * len(images),
len(self.trainloader.dataset),
100. * batch_idx / len(self.trainloader), loss.item()))
self.logger.add_scalar('loss', loss.item())
batch_loss.append(loss.item())
epoch_loss.append(sum(batch_loss)/len(batch_loss))
return model.state_dict(), sum(epoch_loss) / len(epoch_loss)
def update_weights_at(self, model, global_round):
epoch_loss = []
index = 0.0
index_pgd =0
# Set optimizer for the local updates
if self.args.optimizer == 'sgd':
optimizer = torch.optim.SGD(model.parameters(), lr=self.args.lr,
momentum=self.args.momentum)
elif self.args.optimizer == 'adam':
optimizer = torch.optim.Adam(model.parameters(), lr=self.args.lr,
weight_decay=1e-4)
timestep = 0
max_local_train = self.args.local_ep
tau = 0
if self.args.dataset == 'cifar-10':
eps = 8/255
sts = 2/255
if self.args.dataset == 'svhn':
eps = 4/255
sts = 1/255
if self.args.dataset == 'cifar-100':
eps = 8/255
sts = 2/255
total, correct = 0.0, 0.0
lop = self.args.local_ep
for iter in range(lop):
batch_loss = []
index = 0.0
index_pgd = 0
for batch_idx, (images, labels) in enumerate(self.trainloader):
images, labels = images.to(self.device), labels.to(self.device)
if self.method == 'AT':
x_adv, ka = attack.PGD(model,images,labels,eps,sts,self.args.num_steps,loss_fn="cent",category="Madry",rand_init=True)
elif self.method == 'TRADES':
x_adv, ka = attack.PGD(model,images,labels,eps,sts,self.args.num_steps,loss_fn="kl",category="trades",rand_init=True)
elif self.method == 'MART':
x_adv, ka = attack.PGD(model,images,labels,eps,sts,self.args.num_steps,loss_fn="cent",category="trades",rand_init=True)
elif self.method == 'ST':
x_adv, ka = images, 0
model.train()
model.zero_grad()
log_probs = model(x_adv)
_, pred_labels = torch.max(log_probs, 1)
pred_labels = pred_labels.view(-1)
correct += torch.sum(torch.eq(pred_labels, labels)).item()
total += len(labels)
if self.method == 'AT':
loss = self.criterion(log_probs, labels)
elif self.method == 'TRADES':
nat_probs = model(images)
loss = TRADES_loss(log_probs, nat_probs, labels, beta=6.0)
elif self.method == 'MART':
nat_probs = model(images)
loss = MART_loss(log_probs, nat_probs, labels, beta=6.0)
elif self.method == 'ST':
loss = self.criterion(log_probs, labels)
ka -= loss.sum().item()
index_pgd += sum(ka)
ka = -(loss.sum().item())*len(x_adv)
if self.alg == 'FedProx' and global_round > 0:
proximal_term = 0
for w, w_t in zip(model.parameters(), self.anchor.parameters()) :
# update the proximal term
#proximal_term += torch.sum(torch.abs((w-w_t)**2))
proximal_term += (w-w_t).norm(2)
loss = loss + (self.anchor_mu/2)*proximal_term
loss.backward()
optimizer.step()
if self.method == 'ST':
index += ka
else:
index = index + ka
if self.args.verbose and (batch_idx % 10 == 0):
print('| Global Round : {} | Local Epoch : {} | [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
global_round, iter, batch_idx * len(images),
len(self.trainloader.dataset),
100. * batch_idx / len(self.trainloader), loss.item()))
self.logger.add_scalar('loss', loss.item())
batch_loss.append(loss.item())
epoch_loss.append(sum(batch_loss)/len(batch_loss))
if timestep == 0 and len(self.local_rank) >= 1 and self.asyn == True and global_round>0:
selfrank = index / len(self.trainloader)
ipx_sorted = np.sort(self.local_rank)
ipx_idx = int(self.args.num_users * self.args.frac)
ipx_value = ipx_sorted[int(ipx_idx*(1-min(1,global_round/(0.15*self.args.epochs))))]
if selfrank < ipx_value and max_local_train == self.args.local_ep:
print(1)
max_local_train = int(self.args.es*max_local_train)
timestep = timestep+1
if timestep > max_local_train and len(self.local_rank) >= 1 and self.asyn == True and max_local_train != self.args.local_ep:
break
return model.state_dict(), sum(epoch_loss) / len(epoch_loss), index / len(self.trainloader), correct/total, index_pgd/ len(self.trainloader)
def update_weights_scaffold(self, model, c_global_model, c_local_model, global_round):
model.train()
epoch_loss = []
index = 0.0
index_pgd = 0
# Set optimizer for the local updates
if self.args.optimizer == 'sgd':
optimizer = torch.optim.SGD(model.parameters(), lr=self.args.lr,
momentum=self.args.momentum)
elif self.args.optimizer == 'adam':
optimizer = torch.optim.Adam(model.parameters(), lr=self.args.lr,
weight_decay=1e-4)
c_global_para = copy.deepcopy(c_global_model.state_dict())
global_model_para = copy.deepcopy(model.state_dict())
cnt = 0
c_local_para = copy.deepcopy(c_local_model.state_dict())
local_lr = 1e-4
timestep = 0
max_local_train = self.args.local_ep
tau = 0
if self.args.dataset == 'cifar-10':
eps = 8/255
sts = 2/255
if self.args.dataset == 'svhn':
eps = 4/255
sts = 1/255
if self.args.dataset == 'cifar-100':
eps = 8/255
sts = 2/255
total, correct = 0.0, 0.0
for iter in range(self.args.local_ep):
batch_loss = []
index = 0.0
index_pgd = 0
for batch_idx, (images, labels) in enumerate(self.trainloader):
images, labels = images.to(self.device), labels.to(self.device)
if self.method == 'AT':
x_adv, ka = attack.PGD(model,images,labels,eps,sts,self.args.num_steps,loss_fn="cent",category="Madry",rand_init=True)
elif self.method == 'TRADES':
x_adv, ka = attack.PGD(model,images,labels,eps,sts,self.args.num_steps,loss_fn="kl",category="trades",rand_init=True)
elif self.method == 'MART':
x_adv, ka = attack.PGD(model,images,labels,eps,sts,self.args.num_steps,loss_fn="cent",category="trades",rand_init=True)
elif self.method == 'ST':
x_adv, ka = images, 0
model.train()
model.zero_grad()
log_probs = model(x_adv)
_, pred_labels = torch.max(log_probs, 1)
pred_labels = pred_labels.view(-1)
correct += torch.sum(torch.eq(pred_labels, labels)).item()
total += len(labels)
if self.method == 'AT':
loss = self.criterion(log_probs, labels)
elif self.method == 'TRADES':
nat_probs = model(images)
loss = TRADES_loss(log_probs, nat_probs, labels, 6.0)
elif self.method == 'MART':
nat_probs = model(images)
loss = MART_loss(log_probs, nat_probs, labels, 6.0)
elif self.method == 'ST':
loss = self.criterion(log_probs, labels)
ka -= loss.sum().item()
index_pgd += sum(ka)
ka = -(loss.sum().item())*len(x_adv)
if self.alg == 'FedProx' and global_round > 0:
proximal_term = 0
for w, w_t in zip(model.parameters(), self.anchor.parameters()) :
# update the proximal term
#proximal_term += torch.sum(torch.abs((w-w_t)**2))
proximal_term += (w-w_t).norm(2)
loss = loss + (self.anchor_mu/2)*proximal_term
loss.backward()
optimizer.step()
if self.method == 'ST':
index += ka
else:
index = index + ka
if self.args.verbose and (batch_idx % 10 == 0):
print('| Global Round : {} | Local Epoch : {} | [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
global_round, iter, batch_idx * len(images),
len(self.trainloader.dataset),
100. * batch_idx / len(self.trainloader), loss.item()))
self.logger.add_scalar('loss', loss.item())
batch_loss.append(loss.item())
net_para = copy.deepcopy(model.state_dict())
for key in net_para:
net_para[key] = net_para[key] - local_lr * (c_global_para[key] - c_local_para[key])
model.load_state_dict(net_para)
cnt += 1
epoch_loss.append(sum(batch_loss)/len(batch_loss))
if timestep == 0 and len(self.local_rank) >= 1 and self.asyn == True and global_round>0:
selfrank = index / len(self.trainloader)
ipx_sorted = np.sort(self.local_rank)
ipx_idx = int(self.args.num_users * self.args.frac)
ipx_value = ipx_sorted[int(ipx_idx*(1-min(1,global_round/(0.15*self.args.epochs))))]
if selfrank < ipx_value and max_local_train == self.args.local_ep:
print(1)
max_local_train = int(self.args.es*max_local_train)
timestep = timestep+1
if timestep > max_local_train and len(self.local_rank) >= 1 and self.asyn == True and max_local_train != self.args.local_ep:
break
c_new_para = copy.deepcopy(c_local_model.state_dict())
c_delta_para = copy.deepcopy(c_local_model.state_dict())
net_para = copy.deepcopy(model.state_dict())
for key in net_para:
c_new_para[key] = c_new_para[key] - c_global_para[key] + (
global_model_para[key] - net_para[key]) / (cnt * local_lr)
c_delta_para[key] = c_new_para[key] - c_local_para[key]
c_local_model.load_state_dict(c_new_para)
return model.state_dict(), sum(epoch_loss) / len(epoch_loss), index / len(self.trainloader), correct/total, c_local_model, c_delta_para, index_pgd/ len(self.trainloader)
def inference(self, model):
""" Returns the inference accuracy and loss.
"""
model.eval()
loss, total, correct = 0.0, 0.0, 0.0
for batch_idx, (images, labels) in enumerate(self.testloader):
images, labels = images.to(self.device), labels.to(self.device)
# Inference
outputs = model(images)
batch_loss = self.criterion(outputs, labels)
loss += batch_loss.item()
# Prediction
_, pred_labels = torch.max(outputs, 1)
pred_labels = pred_labels.view(-1)
correct += torch.sum(torch.eq(pred_labels, labels)).item()
total += len(labels)
accuracy = correct/total
return accuracy, loss
def test_inference(args, model, test_dataset):
""" Returns the test accuracy and loss.
"""
model.eval()
loss, total, correct = 0.0, 0.0, 0.0
device = 'cuda' if args.gpu else 'cpu'
criterion = nn.NLLLoss().to(device)
testloader = DataLoader(test_dataset, batch_size=128,
shuffle=False)
for batch_idx, (images, labels) in enumerate(testloader):
images, labels = images.to(device), labels.to(device)
# Inference
outputs = model(images)
batch_loss = criterion(outputs, labels)
loss += batch_loss.item()
# Prediction
_, pred_labels = torch.max(outputs, 1)
pred_labels = pred_labels.view(-1)
correct += torch.sum(torch.eq(pred_labels, labels)).item()
total += len(labels)
accuracy = correct/total
return accuracy, loss