forked from pliang279/LG-FedAvg
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Update.py
366 lines (267 loc) · 12.4 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
import torch
from torch import nn
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm
import math
import pdb
import copy
from torch.optim import Optimizer
class DatasetSplit(Dataset):
def __init__(self, dataset, idxs):
self.dataset = dataset
self.idxs = list(idxs)
def __len__(self):
return len(self.idxs)
def __getitem__(self, item):
image, label = self.dataset[self.idxs[item]]
return image, label
class LocalUpdate(object):
def __init__(self, args, dataset=None, idxs=None, pretrain=False):
self.args = args
self.loss_func = nn.CrossEntropyLoss()
self.selected_clients = []
self.ldr_train = DataLoader(DatasetSplit(dataset, idxs), batch_size=self.args.local_bs, shuffle=True)
self.pretrain = pretrain
def train(self, net, body_lr, head_lr, idx=-1, local_eps=None):
net.train()
# train and update
# For ablation study
"""
body_params = []
head_params = []
for name, p in net.named_parameters():
if 'features.0' in name or 'features.1' in name: # active
body_params.append(p)
else: # deactive
head_params.append(p)
"""
body_params = [p for name, p in net.named_parameters() if 'linear' not in name]
head_params = [p for name, p in net.named_parameters() if 'linear' in name]
optimizer = torch.optim.SGD([{'params': body_params, 'lr': body_lr},
{'params': head_params, 'lr': head_lr}],
momentum=self.args.momentum,
weight_decay=self.args.wd)
epoch_loss = []
if local_eps is None:
if self.pretrain:
local_eps = self.args.local_ep_pretrain
else:
local_eps = self.args.local_ep
for iter in range(local_eps):
batch_loss = []
for batch_idx, (images, labels) in enumerate(self.ldr_train):
images, labels = images.to(self.args.device), labels.to(self.args.device)
net.zero_grad()
logits = net(images)
loss = self.loss_func(logits, labels)
loss.backward()
optimizer.step()
batch_loss.append(loss.item())
epoch_loss.append(sum(batch_loss)/len(batch_loss))
return net.state_dict(), sum(epoch_loss) / len(epoch_loss)
class LocalUpdatePerFedAvg(object):
def __init__(self, args, dataset=None, idxs=None, pretrain=False):
self.args = args
self.loss_func = nn.CrossEntropyLoss()
self.selected_clients = []
self.ldr_train = DataLoader(DatasetSplit(dataset, idxs), batch_size=self.args.local_bs, shuffle=True)
self.pretrain = pretrain
def train(self, net, lr, beta=0.001, momentum=0.9):
net.train()
# train and update
optimizer = torch.optim.SGD(net.parameters(), lr=lr, momentum=momentum)
epoch_loss = []
for local_ep in range(self.args.local_ep):
batch_loss = []
if len(self.ldr_train) / self.args.local_ep == 0:
num_iter = int(len(self.ldr_train) / self.args.local_ep)
else:
num_iter = int(len(self.ldr_train) / self.args.local_ep) + 1
train_loader_iter = iter(self.ldr_train)
for batch_idx in range(num_iter):
temp_net = copy.deepcopy(list(net.parameters()))
# Step 1
for g in optimizer.param_groups:
g['lr'] = lr
try:
images, labels = next(train_loader_iter)
except:
train_loader_iter = iter(self.ldr_train)
images, labels = next(train_loader_iter)
images, labels = images.to(self.args.device), labels.to(self.args.device)
net.zero_grad()
logits = net(images)
loss = self.loss_func(logits, labels)
loss.backward()
optimizer.step()
# Step 2
for g in optimizer.param_groups:
g['lr'] = beta
try:
images, labels = next(train_loader_iter)
except:
train_loader_iter = iter(self.ldr_train)
images, labels = next(train_loader_iter)
images, labels = images.to(self.args.device), labels.to(self.args.device)
net.zero_grad()
logits = net(images)
loss = self.loss_func(logits, labels)
loss.backward()
# restore the model parameters to the one before first update
for old_p, new_p in zip(net.parameters(), temp_net):
old_p.data = new_p.data.clone()
optimizer.step()
batch_loss.append(loss.item())
epoch_loss.append(sum(batch_loss)/len(batch_loss))
return net.state_dict(), sum(epoch_loss) / len(epoch_loss)
def one_sgd_step(self, net, lr, beta=0.001, momentum=0.9):
net.train()
# train and update
optimizer = torch.optim.SGD(net.parameters(), lr=lr, momentum=momentum)
test_loader_iter = iter(self.ldr_train)
# Step 1
for g in optimizer.param_groups:
g['lr'] = lr
try:
images, labels = next(train_loader_iter)
except:
train_loader_iter = iter(self.ldr_train)
images, labels = next(train_loader_iter)
images, labels = images.to(self.args.device), labels.to(self.args.device)
net.zero_grad()
logits = net(images)
loss = self.loss_func(logits, labels)
loss.backward()
optimizer.step()
# Step 2
for g in optimizer.param_groups:
g['lr'] = beta
try:
images, labels = next(train_loader_iter)
except:
train_loader_iter = iter(self.ldr_train)
images, labels = next(train_loader_iter)
images, labels = images.to(self.args.device), labels.to(self.args.device)
net.zero_grad()
logits = net(images)
loss = self.loss_func(logits, labels)
loss.backward()
optimizer.step()
return net.state_dict()
class LocalUpdateFedRep(object):
def __init__(self, args, dataset=None, idxs=None, pretrain=False):
self.args = args
self.loss_func = nn.CrossEntropyLoss()
self.selected_clients = []
self.ldr_train = DataLoader(DatasetSplit(dataset, idxs), batch_size=self.args.local_bs, shuffle=True)
self.pretrain = pretrain
def train(self, net, lr):
net.train()
# train and update
body_params = [p for name, p in net.named_parameters() if 'linear' not in name]
head_params = [p for name, p in net.named_parameters() if 'linear' in name]
optimizer = torch.optim.SGD([{'params': body_params, 'lr': 0.0, 'name': "body"},
{'params': head_params, 'lr': lr, "name": "head"}],
momentum=self.args.momentum,
weight_decay=self.args.wd)
local_eps = self.args.local_ep
for iter in range(local_eps):
for batch_idx, (images, labels) in enumerate(self.ldr_train):
images, labels = images.to(self.args.device), labels.to(self.args.device)
net.zero_grad()
logits = net(images)
loss = self.loss_func(logits, labels)
loss.backward()
optimizer.step()
for g in optimizer.param_groups:
if g['name'] == "body":
g['lr'] = lr
elif g['name'] == 'head':
g['lr'] = 0.0
for batch_idx, (images, labels) in enumerate(self.ldr_train):
images, labels = images.to(self.args.device), labels.to(self.args.device)
net.zero_grad()
logits = net(images)
loss = self.loss_func(logits, labels)
loss.backward()
optimizer.step()
return net.state_dict()
class LocalUpdateFedProx(object):
def __init__(self, args, dataset=None, idxs=None, pretrain=False):
self.args = args
self.loss_func = nn.CrossEntropyLoss()
self.selected_clients = []
self.ldr_train = DataLoader(DatasetSplit(dataset, idxs), batch_size=self.args.local_bs, shuffle=True)
self.pretrain = pretrain
def train(self, net, body_lr, head_lr):
net.train()
g_net = copy.deepcopy(net)
body_params = [p for name, p in net.named_parameters() if 'linear' not in name]
head_params = [p for name, p in net.named_parameters() if 'linear' in name]
optimizer = torch.optim.SGD([{'params': body_params, 'lr': body_lr},
{'params': head_params, 'lr': head_lr}],
momentum=self.args.momentum,
weight_decay=self.args.wd)
epoch_loss = []
for iter in range(self.args.local_ep):
batch_loss = []
for batch_idx, (images, labels) in enumerate(self.ldr_train):
images, labels = images.to(self.args.device), labels.to(self.args.device)
net.zero_grad()
logits = net(images)
loss = self.loss_func(logits, labels)
# for fedprox
fed_prox_reg = 0.0
for l_param, g_param in zip(net.parameters(), g_net.parameters()):
fed_prox_reg += (self.args.mu / 2 * torch.norm((l_param - g_param)) ** 2)
loss += fed_prox_reg
loss.backward()
optimizer.step()
batch_loss.append(loss.item())
epoch_loss.append(sum(batch_loss)/len(batch_loss))
return net.state_dict(), sum(epoch_loss) / len(epoch_loss)
class LocalUpdateDitto(object):
def __init__(self, args, dataset=None, idxs=None):
self.args = args
self.loss_func = nn.CrossEntropyLoss()
self.selected_clients = []
self.ldr_train = DataLoader(DatasetSplit(dataset, idxs), batch_size=self.args.local_bs, shuffle=True)
def train(self, net, w_ditto=None, lam=0, idx=-1, lr=0.1, last=False, momentum=0.9):
net.train()
# train and update
bias_p=[]
weight_p=[]
for name, p in net.named_parameters():
if 'bias' in name:
bias_p += [p]
else:
weight_p += [p]
optimizer = torch.optim.SGD(net.parameters(), lr=lr, momentum=momentum)
local_eps = self.args.local_ep
args = self.args
epoch_loss=[]
num_updates = 0
for iter in range(local_eps):
done=False
batch_loss = []
for batch_idx, (images, labels) in enumerate(self.ldr_train):
w_0 = copy.deepcopy(net.state_dict())
images, labels = images.to(self.args.device), labels.to(self.args.device)
log_probs = net(images)
loss = self.loss_func(log_probs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if w_ditto is not None:
w_net = copy.deepcopy(net.state_dict())
for key in w_net.keys():
w_net[key] = w_net[key] - args.lr*lam*(w_0[key] - w_ditto[key])
net.load_state_dict(w_net)
optimizer.zero_grad()
num_updates += 1
batch_loss.append(loss.item())
epoch_loss.append(sum(batch_loss)/len(batch_loss))
return net.state_dict(), sum(epoch_loss) / len(epoch_loss)