-
Notifications
You must be signed in to change notification settings - Fork 1
/
nodes.py
1557 lines (1348 loc) · 55.1 KB
/
nodes.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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
fl_sim.nodes
=============
:class:`Node` s are the core of the simulation framework.
:class:`Node` has two subclasses: :class:`Server` and :class:`Client`.
The :class:`Server` class is the base class for all servers,
which acts as the coordinator of the training process, as well as maintainer of status variables.
The :class:`Client` class is the base class for all clients.
.. contents::
:depth: 2
:local:
:backlinks: top
.. currentmodule:: fl_sim.nodes
Base Node class
---------------
.. autosummary::
:toctree: generated/
Node
Server classes
--------------
.. autosummary::
:toctree: generated/
Server
ServerConfig
Client classes
--------------
.. autosummary::
:toctree: generated/
Client
ClientConfig
"""
import json
import os
import types
import warnings
from abc import ABC, abstractmethod
from collections import defaultdict
from copy import deepcopy
from itertools import repeat
from numbers import Number
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Union
import numpy as np
import torch
import torch.nn as nn
import yaml
from bib_lookup import CitationMixin
from torch import Tensor
from torch.nn.parameter import Parameter
from torch.optim import SGD
from torch.optim.lr_scheduler import LambdaLR
from torch.utils.data import DataLoader
from torch_ecg.cfg import CFG
from torch_ecg.utils import ReprMixin, add_docstring, get_kwargs
from tqdm.auto import tqdm
from .data_processing.fed_dataset import FedDataset
from .models import reset_parameters
from .optimizers import get_optimizer
from .utils.loggers import LoggerManager
from .utils.misc import default_dict_to_dict, get_scheduler, set_seed
from .utils.torch_compat import torch_norm
__all__ = [
"Server",
"Client",
"ServerConfig",
"ClientConfig",
"ClientMessage",
]
class ServerConfig(ReprMixin):
"""Configs for the Server.
Parameters
----------
algorithm : str
The algorithm name.
num_iters : int
The number of (outer) iterations.
num_clients : int
The number of clients.
clients_sample_ratio : float
The ratio of clients to sample for each iteration.
log_dir : str or pathlib.Path, optional
The log directory.
If not specified, will use the default log directory.
If not absolute, will be relative to the default log directory.
txt_logger : bool, default True
Whether to use txt logger.
json_logger : bool, default True
Whether to use json logger.
eval_every : int, default 1
The number of iterations to evaluate the model.
visiable_gpus : Sequence[int], optional
Visable GPU IDs for allocating devices for clients.
Defaults to use all GPUs if available.
extra_observes : List[str], optional
Extra attributes to observe during training.
seed : int, default 0
The random seed.
tag : str, optional
The tag of the experiment.
verbose : int, default 1
The verbosity level.
gpu_proportion : float, default 0.2
The proportion of clients to use GPU.
Used to similate the system heterogeneity of the clients.
Not used in the current version, reserved for future use.
**kwargs : dict, optional
The other arguments,
will be set as attributes of the class.
"""
__name__ = "ServerConfig"
def __init__(
self,
algorithm: str,
num_iters: int,
num_clients: int,
clients_sample_ratio: float,
log_dir: Optional[Union[str, Path]] = None,
txt_logger: bool = True,
json_logger: bool = True,
eval_every: int = 1,
visiable_gpus: Optional[Sequence[int]] = None,
extra_observes: Optional[List[str]] = None,
seed: int = 0,
tag: Optional[str] = None,
verbose: int = 1,
gpu_proportion: float = 0.2,
**kwargs: Any,
) -> None:
self.algorithm = algorithm
self.num_iters = num_iters
self.num_clients = num_clients
self.clients_sample_ratio = clients_sample_ratio
self.log_dir = log_dir
self.txt_logger = txt_logger
self.json_logger = json_logger
self.eval_every = eval_every
self.visiable_gpus = visiable_gpus
default_gpus = list(range(torch.cuda.device_count()))
if self.visiable_gpus is None:
self.visiable_gpus = default_gpus
if not set(self.visiable_gpus).issubset(set(default_gpus)):
warnings.warn(f"GPU(s) {set(self.visiable_gpus) - set(default_gpus)} " "are not available.")
self.visiable_gpus = [item for item in self.visiable_gpus if item in default_gpus]
self.extra_observes = extra_observes or []
self.seed = seed
self.tag = tag
self.verbose = verbose
self.gpu_proportion = gpu_proportion
for k, v in kwargs.items():
setattr(self, k, v)
set_seed(self.seed)
def extra_repr_keys(self) -> List[str]:
return super().extra_repr_keys() + list(self.__dict__)
class ClientConfig(ReprMixin):
"""Configs for the Client.
Parameters
----------
algorithm : str
The algorithm name.
optimizer : str
The name of the optimizer to solve the local (inner) problem.
batch_size : int
The batch size.
num_epochs : int
The number of epochs.
lr : float
The learning rate.
scheduler : dict, optional
The scheduler config.
None for no scheduler, using constant learning rate.
extra_observes : List[str], optional
Extra attributes to observe during training,
which would be recorded in evaluated metrics,
sent to the server, and written to the log file.
verbose : int, default 1
The verbosity level.
latency : float, default 0.0
The latency of the client.
Not used in the current version, reserved for future use.
**kwargs : dict, optional
The other arguments,
will be set as attributes of the class.
"""
__name__ = "ClientConfig"
def __init__(
self,
algorithm: str,
optimizer: str,
batch_size: int,
num_epochs: int,
lr: float,
scheduler: Optional[dict] = None,
extra_observes: Optional[List[str]] = None,
verbose: int = 1,
latency: float = 0.0,
**kwargs: Any,
) -> None:
self.algorithm = algorithm
self.optimizer = optimizer
self.batch_size = batch_size
self.num_epochs = num_epochs
self.lr = lr
self.scheduler = scheduler or {"name": "none"}
self.extra_observes = extra_observes or []
self.verbose = verbose
self.latency = latency
for k, v in kwargs.items():
setattr(self, k, v)
def extra_repr_keys(self) -> List[str]:
return super().extra_repr_keys() + list(self.__dict__)
class Node(ReprMixin, ABC):
"""An abstract base class for the server and client nodes."""
__name__ = "Node"
@abstractmethod
def communicate(self, target: "Node") -> None:
"""Communicate with the target node.
The current node communicates model parameters, gradients, etc. to `target` node.
For example, a client node communicates its local model parameters to server node via
.. code-block:: python
target._received_messages.append(
ClientMessage(
{
"client_id": self.client_id,
"parameters": self.get_detached_model_parameters(),
"train_samples": self.config.num_epochs * self.config.num_steps * self.config.batch_size,
"metrics": self._metrics,
}
)
)
For a server node, global model parameters are communicated to clients via
.. code-block:: python
target._received_messages = {"parameters": self.get_detached_model_parameters()}
"""
raise NotImplementedError
@abstractmethod
def update(self) -> None:
"""Update model parameters, gradients, etc.
according to `self._reveived_messages`.
"""
raise NotImplementedError
def _post_init(self) -> None:
"""Check if all required field in the config are set."""
assert all(
[hasattr(self.config, k) for k in self.required_config_fields]
), f"missing required config fields: {list(set(self.required_config_fields) - set(self.config.__dict__))}"
@property
@abstractmethod
def required_config_fields(self) -> List[str]:
"""The list of required fields in the config."""
raise NotImplementedError
@property
@abstractmethod
def is_convergent(self) -> bool:
"""Whether the training process on the node is convergent."""
raise NotImplementedError
def get_detached_model_parameters(self) -> List[Tensor]:
"""Get the detached model parameters."""
return [p.detach().clone() for p in self.model.parameters()]
def compute_gradients(
self,
at: Optional[Sequence[Tensor]] = None,
dataloader: Optional[DataLoader] = None,
) -> List[Tensor]:
"""Compute the gradients of the model on the node.
The gradients are computed on the model parameters `at` or the current model parameters,
as the average of the gradients on the mini-batches from `dataloader` or `self.train_loader`.
Parameters
----------
at : list of torch.Tensor, optional
The model parameters to compute the gradients.
None for the current model parameters.
dataloader : torch.utils.data.DataLoader, optional
The dataloader to compute the gradients.
None for `self.train_loader`.
"""
prev_training = self.model.training
prev_model_state_dict = self.model.state_dict()
if at is not None:
self.set_parameters(at)
if dataloader is None:
assert hasattr(self, "train_loader") and self.train_loader is not None, "train_loader is not set"
dataloader = self.train_loader
assert len(dataloader) > 0, "empty dataloader"
self.model.train()
self.optimizer.zero_grad()
total_samples = len(dataloader.dataset)
for X, y in dataloader:
X, y = X.to(self.device), y.to(self.device)
y_pred = self.model(X)
loss = self.criterion(y_pred, y) * len(X) / total_samples
# gradients are accumulated after each backward pass
# one should **NOT** call `optimizer.zero_grad()` before the backward pass
# and should **NOT** call `optimizer.step()` after the backward pass
# since the model parameters should not be updated
# otherwise, the result is not the gradients **at** ``at``
loss.backward()
mini_batch_grads = [p.grad.detach().clone() for p in self.model.parameters()]
# set the model state back and clear the gradients
self.model.load_state_dict(prev_model_state_dict)
self.optimizer.zero_grad()
self.model.train(prev_training)
# garbage collection
del prev_model_state_dict
return mini_batch_grads
def get_gradients(
self,
norm: Optional[Union[str, int, float]] = None,
model: Optional[torch.nn.Module] = None,
) -> Union[float, List[Tensor]]:
"""Get the gradients or norm of the gradients
of the model on the node.
Parameters
----------
norm : str or int or float, optional
The norm of the gradients to compute.
None for the raw gradients (list of tensors).
Refer to :func:`torch.linalg.norm` for more details.
model : torch.nn.Module, optional
The model to get the gradients,
default to `self.model`.
Returns
-------
float or List[torch.Tensor]
The gradients or norm of the gradients.
"""
if model is None:
model = self.model
grads = []
for param in model.parameters():
if param.grad is None:
grads.append(torch.zeros_like(param.data))
else:
grads.append(param.grad.data)
if norm is not None:
if len(grads) == 0:
grads = 0.0
warnings.warn("No gradients available. Set to 0.0 by default.", RuntimeWarning)
else:
grads = torch_norm(torch.cat([grad.view(-1) for grad in grads]), norm).item()
return grads
@staticmethod
def get_norm(
tensor: Union[
Number,
Tensor,
np.ndarray,
Parameter,
types.GeneratorType,
Sequence[Union[np.ndarray, Tensor, Parameter, types.GeneratorType]],
],
norm: Union[str, int, float] = "fro",
) -> float:
"""Get the norm of a tensor.
Parameters
----------
tensor : torch.Tensor or np.ndarray or torch.nn.parameter.Parameter or generator or list
The tensor (array, parameter, etc.) to compute the norm.
norm : str or int or float, default "fro"
The norm to compute.
Refer to :func:`torch.linalg.norm` for more details.
Returns
-------
float
The norm of the tensor.
"""
if tensor is None:
return float("nan")
if isinstance(tensor, Number):
return tensor
if isinstance(tensor, Tensor):
tensor = [tensor]
elif isinstance(tensor, np.ndarray):
tensor = [torch.from_numpy(tensor)]
elif isinstance(tensor, Parameter):
tensor = [tensor.data]
elif isinstance(tensor, (list, tuple)):
tensor = [torch.from_numpy(t) if isinstance(t, np.ndarray) else t.detach().clone() for t in tensor]
elif isinstance(tensor, types.GeneratorType):
return Node.get_norm(list(tensor), norm)
else:
raise TypeError(f"Unsupported type: {type(tensor)}")
return torch_norm(torch.cat([t.view(-1) for t in tensor]), norm).item()
def set_parameters(self, params: Iterable[Parameter], model: Optional[torch.nn.Module] = None) -> None:
"""Set the parameters of the model on the node.
Parameters
----------
params : Iterable[torch.nn.parameter.Parameter]
The parameters to set.
model : torch.nn.Module, optional
The model to set the parameters,
default to `self.model`.
Returns
-------
None
"""
if model is None:
model = self.model
for node_param, param in zip(model.parameters(), params):
node_param.data = param.data.detach().clone().to(self.device)
@staticmethod
def aggregate_results_from_json_log(d: Union[dict, str, Path], part: str = "val", metric: str = "acc") -> np.ndarray:
"""Aggregate the federated results from json log.
Parameters
----------
d : dict or str or pathlib.Path
The dict of the json/yaml log,
or the path to the json/yaml log file.
part : str, default "train"
The part of the log to aggregate.
metric : str, default "acc"
The metric to aggregate.
Returns
-------
numpy.ndarray
The aggregated results (curve).
NOTE
----
The parameter `d` should be a dict similar to the following structure:
.. dropdown::
:animate: fade-in-slide-down
.. code-block:: json
{
"train": {
"client0": [
{
"epoch": 1,
"step": 1,
"time": "2020-01-01 00:00:00",
"loss": 0.1,
"acc": 0.2,
"top3_acc": 0.3,
"top5_acc": 0.4,
"num_samples": 100
}
]
},
"val": {
"client0": [
{
"epoch": 1,
"step": 1,
"time": "2020-01-01 00:00:00",
"loss": 0.1,
"acc": 0.2,
"top3_acc": 0.3,
"top5_acc": 0.4,
"num_samples": 100
}
]
}
}
"""
if isinstance(d, (str, Path)):
d = Path(d)
if d.suffix == ".json":
d = json.loads(d.read_text())
elif d.suffix in [".yaml", ".yml"]:
d = yaml.safe_load(d.read_text())
else:
raise ValueError(f"unsupported file type: {d.suffix}")
epochs = list(sorted(np.unique([item["epoch"] for _, v in d[part].items() for item in v])))
metric_curve = [[] for _ in range(len(epochs))]
num_samples = [0 for _ in range(len(epochs))]
for _, v in tqdm(
d[part].items(),
mininterval=1,
desc="Aggregating results",
total=len(d[part]),
unit="client",
leave=False,
disable=int(os.environ.get("FLSIM_VERBOSE", "1")) < 1,
):
for item in v:
idx = epochs.index(item["epoch"])
metric_curve[idx].append(item[metric] * item["num_samples"])
num_samples[idx] += item["num_samples"]
return np.array([sum(v) / num_samples[i] for i, v in enumerate(metric_curve)])
class Server(Node, CitationMixin):
"""The class to simulate the server node.
The server node is responsible for communicating with clients,
and perform the aggregation of the local model parameters (and/or gradients),
and update the global model parameters.
Parameters
----------
model : torch.nn.Module
The model to be trained (optimized).
dataset : FedDataset
The dataset to be used for training.
config : ServerConfig
The configs for the server.
client_config : ClientConfig
The configs for the clients.
lazy : bool, default False
Whether to use lazy initialization
for the client nodes. This is useful
when one wants to do centralized training
for verification.
TODO
----
1. Run clients training in parallel.
2. Use the attribute `_is_convergent` to control the termination of the training.
This perhaps can be achieved by comparing part of the items in `self._cached_models`
"""
__name__ = "Server"
def __init__(
self,
model: nn.Module,
dataset: FedDataset,
config: ServerConfig,
client_config: ClientConfig,
lazy: bool = False,
) -> None:
self.model = model
self.dataset = dataset
self.criterion = deepcopy(dataset.criterion)
assert isinstance(config, self.config_cls["server"]), (
f"(server) config should be an instance of " f"{self.config_cls['server']}, but got {type(config)}."
)
self.config = config
if not hasattr(self.config, "verbose"):
self.config.verbose = get_kwargs(ServerConfig)["verbose"]
warnings.warn(
"The `verbose` attribute is not found in the config, " f"set it to the default value {self.config.verbose}.",
RuntimeWarning,
)
if self.config.num_clients is None:
self.config.num_clients = self.dataset.DEFAULT_TRAIN_CLIENTS_NUM
self.device = torch.device("cpu")
assert isinstance(client_config, self.config_cls["client"]), (
f"client_config should be an instance of " f"{self.config_cls['client']}, but got {type(client_config)}."
)
self._client_config = client_config
if not hasattr(self._client_config, "verbose"):
# self._client_config.verbose = get_kwargs(ClientConfig)["verbose"]
self._client_config.verbose = self.config.verbose # set to server's verbose
warnings.warn(
"The `verbose` attribute is not found in the client_config, "
f"set it to the default value {self._client_config.verbose}.",
RuntimeWarning,
)
logger_config = dict(
log_dir=self.config.log_dir,
log_suffix=self.config.tag,
txt_logger=self.config.txt_logger,
json_logger=self.config.json_logger,
algorithm=self.config.algorithm,
model=self.model.__class__.__name__,
dataset=self.dataset.__class__.__name__,
verbose=self.config.verbose,
)
self._logger_manager = LoggerManager.from_config(logger_config)
# set batch_size, in case of centralized training
setattr(self.config, "batch_size", client_config.batch_size)
# echo the configs to stdout and txt log file
self._logger_manager.log_message(f"Server Configs:\n{str(self.config)}")
self._logger_manager.log_message(f"Client Configs:\n{str(self._client_config)}")
self._received_messages = []
self._num_communications = 0
self.n_iter = 0
self._metrics = {} # aggregated metrics
self._cached_metrics = [] # container for caching aggregated metrics
self._is_convergent = False # status variable for convergence
# flag for completing the experiment
# which will be checked before calling
# `self.train`, `self.train_centralized`, `self.train_federated`
self._complete_experiment = False
self._clients = None
if not lazy:
self._setup_clients(self.dataset, self._client_config)
self._post_init()
# checks that the client has all the required attributes in config.extra_observes
for attr in self.config.extra_observes:
assert hasattr(self, attr), f"{self.__name__} should have attribute {attr} for extra observes."
def _setup_clients(
self,
dataset: Optional[FedDataset] = None,
client_config: Optional[ClientConfig] = None,
force: bool = False,
) -> None:
"""Setup the clients.
Parameters
----------
dataset : FedDataset, optional
The dataset to be used for training the local models,
defaults to `self.dataset`.
client_config : ClientConfig, optional
The configs for the clients,
defaults to `self._client_config`.
force : bool, default False
Whether to force setup the clients.
If set to True, the clients will be setup
even if they have been setup before.
Returns
-------
None
"""
if self._clients is not None and not force:
return
elif force:
# reset the clients
del self._clients
self._logger_manager.log_message("Setup clients...")
dataset = dataset or self.dataset
client_config = client_config or self._client_config
self._clients = [
self.client_cls(client_id, device, deepcopy(self.model), dataset, client_config)
for client_id, device in tqdm(
zip(range(self.config.num_clients), self._allocate_devices()),
desc="Allocating devices",
total=self.config.num_clients,
unit="client",
mininterval=1,
leave=False,
)
]
def _allocate_devices(self) -> List[torch.device]:
"""Allocate devices for clients, can be used in :meth:`_setup_clients`."""
self._logger_manager.log_message("Allocate devices...")
# num_gpus = torch.cuda.device_count()
num_gpus = len(self.config.visiable_gpus)
if num_gpus == 0:
return list(repeat(torch.device("cpu"), self.config.num_clients))
return [torch.device(f"cuda:{self.config.visiable_gpus[i%num_gpus]}") for i in range(self.config.num_clients)]
def _sample_clients(
self,
subset: Optional[Sequence[int]] = None,
clients_sample_ratio: Optional[float] = None,
clients_sample_num: Optional[int] = None,
) -> List[int]:
"""Sample clients for each iteration.
Parameters
----------
subset : Sequence[int], optional
The subset of clients to be sampled from,
defaults to `None`, which means all clients.
clients_sample_ratio : float, optional
The ratio of clients to be sampled,
defaults to `None`, which means `self.config.clients_sample_ratio`.
clients_sample_num : int, optional
The number of clients to be sampled.
If not `None`, will override `clients_sample_ratio`.
Returns
-------
List[int]
The list of selected client ids.
"""
if subset is None:
subset = range(self.config.num_clients)
if clients_sample_ratio is None:
clients_sample_ratio = self.config.clients_sample_ratio
if clients_sample_num is not None:
k = min(len(subset), max(1, clients_sample_num))
else:
k = min(len(subset), max(1, round(clients_sample_ratio * len(subset))))
# return random.sample(subset, k=k)
# random.sample does not support numpy array input
return np.random.choice(subset, k, replace=False).tolist()
def _communicate(self, target: "Client") -> None:
"""Broadcast to target client, and maintain state variables."""
self.communicate(target)
self._num_communications += 1
def _update(self) -> None:
"""Server update, and clear cached messages from clients of the previous iteration."""
self._logger_manager.log_message("Server update...")
if len(self._received_messages) == 0:
warnings.warn(
"No message received from the clients, unable to update server model.",
RuntimeWarning,
)
return
assert all([isinstance(m, ClientMessage) for m in self._received_messages]), (
"received messages must be of type `ClientMessage`, "
f"but got {[type(m) for m in self._received_messages if not isinstance(m, ClientMessage)]}"
)
self.update()
# free the memory of the received messages
del self._received_messages
self._received_messages = [] # clear messages received in the previous iteration
self._logger_manager.log_message("Server update finished...")
def train(self, mode: str = "federated", extra_configs: Optional[dict] = None) -> None:
"""The main training loop.
Parameters
----------
mode : {"federated", "centralized", "local"}, optional
The mode of training, by default "federated", case-insensitive.
extra_configs : dict, optional
The extra configs for the training `mode`.
Returns
-------
None
"""
if self._complete_experiment:
# reset before training if a previous experiment is completed
self._reset(reset_clients=(mode.lower() != "centralized"))
self._complete_experiment = False
if mode.lower() == "federated":
self.train_federated(extra_configs)
elif mode.lower() == "centralized":
self.train_centralized(extra_configs)
elif mode.lower() == "local":
self.train_local(extra_configs)
else:
raise ValueError(f"mode {mode} is not supported")
self._complete_experiment = True
def train_centralized(self, extra_configs: Optional[dict] = None) -> None:
"""Centralized training, conducted only on the server node.
This is used as a baseline for comparison.
Parameters
----------
extra_configs : dict, optional
The extra configs for centralized training.
Returns
-------
None
"""
if self._complete_experiment:
# reset before training if a previous experiment is completed
# no need to reset clients for centralized training
self._reset(reset_clients=False)
self._logger_manager.log_message("Training centralized...")
extra_configs = CFG(extra_configs or {})
batch_size = extra_configs.get("batch_size", self.config.batch_size)
train_loader, val_loader = self.dataset.get_dataloader(batch_size, batch_size, None)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.model.train()
self.model.to(device)
criterion = deepcopy(self.dataset.criterion)
lr = extra_configs.get("lr", 1e-2)
optimizer = extra_configs.get("optimizer", SGD(self.model.parameters(), lr))
scheduler = extra_configs.get("scheduler", LambdaLR(optimizer, lambda epoch: 1 / (0.01 * epoch + 1)))
self._complete_experiment = False
epoch_losses = []
self.n_iter, global_step = 0, 0
for self.n_iter in range(self.config.num_iters):
with tqdm(
total=len(train_loader.dataset),
desc=f"Epoch {self.n_iter+1}/{self.config.num_iters}",
unit="sample",
mininterval=1 if torch.cuda.is_available() else 10,
) as pbar:
epoch_loss = []
batch_losses = []
for data, target in train_loader:
data, target = data.to(device), target.to(device)
output = self.model(data)
loss = criterion(output, target)
optimizer.zero_grad()
loss.backward()
batch_losses.append(loss.item())
optimizer.step()
global_step += 1
if self.config.verbose >= 2:
pbar.set_postfix(
**{
"loss (batch)": loss.item(),
"lr": scheduler.get_last_lr()[0],
}
)
pbar.update(data.shape[0])
# free memory
del data, target, output, loss
epoch_loss.append(sum(batch_losses) / len(batch_losses))
if (self.n_iter + 1) % self.config.eval_every == 0:
self._logger_manager.log_message("Evaluating...")
metrics = self.evaluate_centralized(val_loader)
self._logger_manager.log_metrics(
None,
metrics,
step=global_step,
epoch=self.n_iter + 1,
part="val",
)
metrics = self.evaluate_centralized(train_loader)
self._logger_manager.log_metrics(
None,
metrics,
step=global_step,
epoch=self.n_iter + 1,
part="train",
)
scheduler.step()
self.model.to(self.device) # move to the original device
self._logger_manager.log_message("Centralized training finished...")
self._logger_manager.flush()
# self._logger_manager.reset()
self._complete_experiment = True
def train_federated(self, extra_configs: Optional[dict] = None) -> None:
"""Federated (distributed) training,
conducted on the clients and the server.
Parameters
----------
extra_configs : dict, optional
The extra configs for federated training.
Returns
-------
None
TODO
----
Run clients training in parallel.
"""
if self._clients is None:
self._clients = self._setup_clients(self.dataset, self._client_config)
if self._complete_experiment:
# reset before training if a previous experiment is completed
self._reset()
self._complete_experiment = False
self._logger_manager.log_message("Training federated...")
self.n_iter = 0
with tqdm(
range(self.config.num_iters),
total=self.config.num_iters,
desc=f"{self.config.algorithm} training",
unit="iter",
mininterval=1, # usually useless since a full iteration takes a very long time
) as outer_pbar:
for self.n_iter in outer_pbar:
selected_clients = self._sample_clients()
with tqdm(
total=len(selected_clients),
desc=f"Iter {self.n_iter+1}/{self.config.num_iters}",
unit="client",
mininterval=max(1, len(selected_clients) // 50),
disable=self.config.verbose < 1,
leave=False,
) as pbar:
for client_id in selected_clients:
client = self._clients[client_id]
# server communicates with client
# typically broadcasting the global model to the client
self._communicate(client)
if self.n_iter > 0 and (self.n_iter + 1) % self.config.eval_every == 0:
for part in self.dataset.data_parts:
# NOTE: one should execute `client.evaluate`
# before `client._update`,
# otherwise the evaluation would be done
# on the ``personalized`` (locally fine-tuned) model.
metrics = client.evaluate(part)
self._logger_manager.log_metrics(
client_id,
metrics,
step=self.n_iter,
epoch=self.n_iter,
part=part,
)
# client trains the model
# and perhaps updates other local variables
client._update()
# client communicates with server
# typically sending the local model
# and evaluated local metrics to the server
# and perhaps other local variables (e.g. gradients, etc.)
client._communicate(self)
pbar.update(1)
if self.n_iter > 0 and (self.n_iter + 1) % self.config.eval_every == 0:
# server aggregates the metrics from clients
self.aggregate_client_metrics()
# server updates the global model
# and perhaps other global variables
self._update()
self._logger_manager.log_message("Federated training finished...")
self._logger_manager.flush()
self._complete_experiment = True
def train_local(self, extra_configs: Optional[dict] = None) -> None:
"""Local training, conducted on the clients,
without any communication with the server. Used for comparison.
Parameters
----------
extra_configs : dict, optional
The extra configs for local training.
Returns
-------
None
"""
if self._clients is None:
self._clients = self._setup_clients(self.dataset, self._client_config)
if self._complete_experiment: