-
Notifications
You must be signed in to change notification settings - Fork 4
/
client.py
420 lines (327 loc) · 13.4 KB
/
client.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
import os
from copy import deepcopy
import torch.nn.functional as F
from utils.torch_utils import *
class Client(object):
r"""Implements one clients
Attributes
----------
learners_ensemble
n_learners
train_iterator
val_iterator
test_iterator
train_loader
n_train_samples
n_test_samples
samples_weights
local_steps
logger
tune_locally:
Methods
----------
__init__
step
write_logs
update_sample_weights
update_learners_weights
"""
def __init__(
self,
learners_ensemble,
train_iterator,
val_iterator,
test_iterator,
logger,
local_steps,
save_path,
tune_locally=False
):
self.learners_ensemble = learners_ensemble
self.n_learners = len(self.learners_ensemble)
self.tune_locally = tune_locally
if self.tune_locally:
self.tuned_learners_ensemble = deepcopy(self.learners_ensemble)
else:
self.tuned_learners_ensemble = None
self.binary_classification_flag = self.learners_ensemble.is_binary_classification
self.train_iterator = train_iterator
self.val_iterator = val_iterator
self.test_iterator = test_iterator
self.train_loader = iter(self.train_iterator)
self.n_train_samples = len(self.train_iterator.dataset)
self.n_test_samples = len(self.test_iterator.dataset)
self.samples_weights = torch.ones(self.n_learners, self.n_train_samples) / self.n_learners
self.local_steps = local_steps
self.counter = 0
self.logger = logger
os.makedirs(save_path, exist_ok=True)
self.save_path = os.path.join(save_path, 'params.pt')
# self.clear_models()
def get_next_batch(self):
try:
batch = next(self.train_loader)
except StopIteration:
self.train_loader = iter(self.train_iterator)
batch = next(self.train_loader)
return batch
def step(self, single_batch_flag=False, *args, **kwargs):
"""
perform on step for the client
:param single_batch_flag: if true, the client only uses one batch to perform the update
:return
clients_updates: ()
"""
# self.reload_models()
self.counter += 1
self.update_sample_weights() # update q(x)
self.update_learners_weights() # update pi, mu and Var
if single_batch_flag:
batch = self.get_next_batch()
client_updates = \
self.learners_ensemble.fit_batch(
batch=batch,
weights=self.samples_weights
)
else:
client_updates = \
self.learners_ensemble.fit_epochs(
iterator=self.train_iterator,
n_epochs=self.local_steps,
weights=self.samples_weights
)
# TODO: add flag arguments to use `free_gradients`
self.learners_ensemble.free_gradients()
# self.clear_models()
return client_updates
def clear_models(self):
self.learners_ensemble.save_models(self.save_path)
self.learners_ensemble.free_memory()
self.learners_ensemble.free_gradients()
torch.cuda.empty_cache()
def reload_models(self):
self.learners_ensemble.load_models(self.save_path)
def write_logs(self):
if self.tune_locally:
self.update_tuned_learners()
if self.tune_locally:
train_loss, train_acc = self.tuned_learners_ensemble.evaluate_iterator(self.val_iterator)
test_loss, test_acc = self.tuned_learners_ensemble.evaluate_iterator(self.test_iterator)
else:
train_loss, train_acc = self.learners_ensemble.evaluate_iterator(self.val_iterator)
test_loss, test_acc = self.learners_ensemble.evaluate_iterator(self.test_iterator)
self.logger.add_scalar("Train/Loss", train_loss, self.counter)
self.logger.add_scalar("Train/Metric", train_acc, self.counter)
self.logger.add_scalar("Test/Loss", test_loss, self.counter)
self.logger.add_scalar("Test/Metric", test_acc, self.counter)
return train_loss, train_acc, test_loss, test_acc
def update_sample_weights(self):
pass
def update_learners_weights(self):
pass
def update_tuned_learners(self):
if not self.tune_locally:
return
for learner_id, learner in enumerate(self.tuned_learners_ensemble):
copy_model(source=self.learners_ensemble[learner_id].model, target=learner.model)
learner.fit_epochs(self.train_iterator, self.local_steps, weights=self.samples_weights[learner_id])
class MixtureClient(Client):
def update_sample_weights(self):
all_losses = self.learners_ensemble.gather_losses(self.val_iterator)
self.samples_weights = F.softmax((torch.log(torch.Tensor(self.learners_ensemble.learners_weights)) - all_losses.T), dim=1).T
def update_learners_weights(self):
self.learners_ensemble.learners_weights = self.samples_weights.mean(dim=1)
# class GMixtureClient(Client):
# def update_sample_weights(self):
# self.samples_weights = self.learners_ensemble.calc_samples_weights(self.val_iterator)
#
# def update_learners_weights(self): # calculate pi, mu and Var
# self.learners_ensemble.m_step(self.samples_weights, self.val_iterator)
class ACGMixtureClient(Client):
def __init__(self, learners_ensemble, train_iterator, val_iterator, test_iterator, logger, local_steps, save_path,
tune_locally=False):
super().__init__(learners_ensemble, train_iterator, val_iterator, test_iterator, logger, local_steps, save_path,
tune_locally)
self.learners_ensemble.initialize_gmm(iterator=train_iterator)
def update_sample_weights(self):
self.samples_weights = self.learners_ensemble.calc_samples_weights(self.val_iterator)
def update_learners_weights(self): # calculate pi, mu and Var
self.learners_ensemble.m_step(self.samples_weights, self.val_iterator)
"""
" Only update gmm
"""
def step(self, single_batch_flag=False, n_iter=1, *args, **kwargs):
self.counter += 1
# self.learners_ensemble.initialize_gmm(iterator=self.train_iterator)
"""
" EM step
"""
for _ in range(n_iter):
self.update_sample_weights() # update q(x)
self.update_learners_weights() # update pi, mu and Var
sum_samples_weights = self.samples_weights.sum(dim=1)
if single_batch_flag:
batch = self.get_next_batch()
client_updates = \
self.learners_ensemble.fit_batch(
batch=batch,
weights=sum_samples_weights
)
else:
client_updates = \
self.learners_ensemble.fit_epochs(
iterator=self.train_iterator,
n_epochs=self.local_steps,
weights=sum_samples_weights
)
self.learners_ensemble.free_gradients()
# self.clear_models()
return client_updates
def unseen_step(self, single_batch_flag=False, n_iter=1, *args, **kwargs):
self.counter += 1
"""
" EM step
"""
for _ in range(n_iter):
self.update_sample_weights() # update q(x)
def gmm_step(self, single_batch_flag=False, n_iter=1, *args, **kwargs):
"""
perform on step for the client
:param single_batch_flag: if true, the client only uses one batch to perform the update
:return
clients_updates: ()
"""
# self.reload_models()
self.counter += 1
# self.learners_ensemble.initialize_gmm(iterator=self.train_iterator)
"""
" EM step
"""
for _ in range(n_iter):
self.update_sample_weights() # update q(x)
self.update_learners_weights() # update pi, mu and Var
# sum_samples_weights = self.samples_weights.sum(dim=1)
# if single_batch_flag:
# batch = self.get_next_batch()
# client_updates = \
# self.learners_ensemble.fit_batch(
# batch=batch,
# weights=sum_samples_weights
# )
# else:
# client_updates = \
# self.learners_ensemble.fit_epochs(
# iterator=self.train_iterator,
# n_epochs=self.local_steps,
# weights=sum_samples_weights
# )
# self.learners_ensemble.free_gradients()
# self.clear_models()
# return client_updates
return
def ac_step(self):
self.learners_ensemble.freeze_classifier()
ac_client_update = \
self.learners_ensemble.fit_ac_epochs(
iterator=self.train_iterator,
n_epochs=self.local_steps
)
self.learners_ensemble.unfreeze_classifier()
return ac_client_update
def write_logs(self):
if self.tune_locally:
self.update_tuned_learners()
if self.tune_locally:
train_loss, train_acc = self.tuned_learners_ensemble.evaluate_iterator(self.val_iterator)
test_loss, test_acc = self.tuned_learners_ensemble.evaluate_iterator(self.test_iterator)
else:
train_loss, train_acc = self.learners_ensemble.evaluate_iterator(self.val_iterator)
test_loss, test_acc = self.learners_ensemble.evaluate_iterator(self.test_iterator)
# train_recon, train_nll = self.learners_ensemble.evaluate_ac_iterator(self.val_iterator)
# test_recon, test_nll = self.learners_ensemble.evaluate_ac_iterator(self.test_iterator)
train_recon = 0
train_nll = 0
test_recon = 0
test_nll = 0
#not used
self.logger.add_scalar("Train/Loss", train_loss, self.counter)
self.logger.add_scalar("Train/Metric", train_acc, self.counter)
self.logger.add_scalar("Test/Loss", test_loss, self.counter)
self.logger.add_scalar("Test/Metric", test_acc, self.counter)
self.logger.add_scalar("Train/Recon_Loss", train_recon, self.counter)
self.logger.add_scalar("Train/NLL", train_nll, self.counter)
self.logger.add_scalar("Test/Recon_Loss", test_recon, self.counter)
self.logger.add_scalar("Test/NLL", test_nll, self.counter)
return train_loss, train_acc, test_loss, test_acc, train_recon, train_nll, test_recon, test_nll
class AgnosticFLClient(Client):
def __init__(
self,
learners_ensemble,
train_iterator,
val_iterator,
test_iterator,
logger,
local_steps,
tune_locally=False
):
super(AgnosticFLClient, self).__init__(
learners_ensemble=learners_ensemble,
train_iterator=train_iterator,
val_iterator=val_iterator,
test_iterator=test_iterator,
logger=logger,
local_steps=local_steps,
tune_locally=tune_locally
)
assert self.n_learners == 1, "AgnosticFLClient only supports single learner."
def step(self, *args, **kwargs):
self.counter += 1
batch = self.get_next_batch()
losses = self.learners_ensemble.compute_gradients_and_loss(batch)
return losses
class FFLClient(Client):
r"""
Implements client for q-FedAvg from
`FAIR RESOURCE ALLOCATION IN FEDERATED LEARNING`__(https://arxiv.org/pdf/1905.10497.pdf)
"""
def __init__(
self,
learners_ensemble,
train_iterator,
val_iterator,
test_iterator,
logger,
local_steps,
q=1,
tune_locally=False
):
super(FFLClient, self).__init__(
learners_ensemble=learners_ensemble,
train_iterator=train_iterator,
val_iterator=val_iterator,
test_iterator=test_iterator,
logger=logger,
local_steps=local_steps,
tune_locally=tune_locally
)
assert self.n_learners == 1, "AgnosticFLClient only supports single learner."
self.q = q
def step(self, lr, *args, **kwargs):
hs = 0
for learner in self.learners_ensemble:
initial_state_dict = self.learners_ensemble[0].model.state_dict()
learner.fit_epochs(iterator=self.train_iterator, n_epochs=self.local_steps)
client_loss, _ = learner.evaluate_iterator(self.train_iterator)
client_loss = torch.tensor(client_loss)
client_loss += 1e-10
# assign the difference to param.grad for each param in learner.parameters()
differentiate_learner(
target=learner,
reference_state_dict=initial_state_dict,
coeff=torch.pow(client_loss, self.q) / lr
)
hs = self.q * torch.pow(client_loss, self.q - 1) * torch.pow(torch.linalg.norm(learner.get_grad_tensor()),
2)
hs /= torch.pow(torch.pow(client_loss, self.q), 2)
hs += torch.pow(client_loss, self.q) / lr
return hs / len(self.learners_ensemble)