flwr-nightly 1.22.0.dev20250915__py3-none-any.whl → 1.22.0.dev20250917__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- flwr/cli/app.py +2 -0
- flwr/cli/new/new.py +2 -2
- flwr/cli/new/templates/app/README.flowertune.md.tpl +1 -1
- flwr/cli/new/templates/app/code/client.baseline.py.tpl +64 -47
- flwr/cli/new/templates/app/code/flwr_tune/client_app.py.tpl +56 -90
- flwr/cli/new/templates/app/code/flwr_tune/models.py.tpl +1 -23
- flwr/cli/new/templates/app/code/flwr_tune/server_app.py.tpl +37 -58
- flwr/cli/new/templates/app/code/flwr_tune/strategy.py.tpl +39 -44
- flwr/cli/new/templates/app/code/model.baseline.py.tpl +0 -14
- flwr/cli/new/templates/app/code/server.baseline.py.tpl +27 -29
- flwr/cli/new/templates/app/pyproject.baseline.toml.tpl +3 -3
- flwr/cli/new/templates/app/pyproject.flowertune.toml.tpl +1 -1
- flwr/cli/pull.py +100 -0
- flwr/cli/utils.py +17 -0
- flwr/common/constant.py +2 -0
- flwr/proto/control_pb2.py +7 -3
- flwr/proto/control_pb2.pyi +24 -0
- flwr/proto/control_pb2_grpc.py +34 -0
- flwr/proto/control_pb2_grpc.pyi +13 -0
- flwr/server/app.py +13 -0
- flwr/serverapp/strategy/__init__.py +8 -0
- flwr/serverapp/strategy/fedavg.py +23 -2
- flwr/serverapp/strategy/fedavgm.py +198 -0
- flwr/serverapp/strategy/fedmedian.py +71 -0
- flwr/serverapp/strategy/fedprox.py +174 -0
- flwr/serverapp/strategy/fedtrimmedavg.py +176 -0
- flwr/serverapp/strategy/strategy_utils_tests.py +20 -1
- flwr/simulation/app.py +1 -1
- flwr/simulation/run_simulation.py +25 -30
- flwr/superlink/artifact_provider/__init__.py +22 -0
- flwr/superlink/artifact_provider/artifact_provider.py +37 -0
- flwr/superlink/servicer/control/control_grpc.py +3 -0
- flwr/superlink/servicer/control/control_servicer.py +59 -2
- {flwr_nightly-1.22.0.dev20250915.dist-info → flwr_nightly-1.22.0.dev20250917.dist-info}/METADATA +6 -16
- {flwr_nightly-1.22.0.dev20250915.dist-info → flwr_nightly-1.22.0.dev20250917.dist-info}/RECORD +37 -30
- {flwr_nightly-1.22.0.dev20250915.dist-info → flwr_nightly-1.22.0.dev20250917.dist-info}/WHEEL +0 -0
- {flwr_nightly-1.22.0.dev20250915.dist-info → flwr_nightly-1.22.0.dev20250917.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,198 @@
|
|
1
|
+
# Copyright 2025 Flower Labs GmbH. All Rights Reserved.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
# ==============================================================================
|
15
|
+
"""Federated Averaging with Momentum (FedAvgM) [Hsu et al., 2019] strategy.
|
16
|
+
|
17
|
+
Paper: arxiv.org/pdf/1909.06335.pdf
|
18
|
+
"""
|
19
|
+
|
20
|
+
|
21
|
+
from collections import OrderedDict
|
22
|
+
from collections.abc import Iterable
|
23
|
+
from logging import INFO
|
24
|
+
from typing import Callable, Optional
|
25
|
+
|
26
|
+
from flwr.common import (
|
27
|
+
Array,
|
28
|
+
ArrayRecord,
|
29
|
+
ConfigRecord,
|
30
|
+
Message,
|
31
|
+
MetricRecord,
|
32
|
+
NDArrays,
|
33
|
+
RecordDict,
|
34
|
+
log,
|
35
|
+
)
|
36
|
+
from flwr.server import Grid
|
37
|
+
|
38
|
+
from ..exception import AggregationError
|
39
|
+
from .fedavg import FedAvg
|
40
|
+
|
41
|
+
|
42
|
+
class FedAvgM(FedAvg):
|
43
|
+
"""Federated Averaging with Momentum strategy.
|
44
|
+
|
45
|
+
Implementation based on https://arxiv.org/abs/1909.06335
|
46
|
+
|
47
|
+
Parameters
|
48
|
+
----------
|
49
|
+
fraction_train : float (default: 1.0)
|
50
|
+
Fraction of nodes used during training. In case `min_train_nodes`
|
51
|
+
is larger than `fraction_train * total_connected_nodes`, `min_train_nodes`
|
52
|
+
will still be sampled.
|
53
|
+
fraction_evaluate : float (default: 1.0)
|
54
|
+
Fraction of nodes used during validation. In case `min_evaluate_nodes`
|
55
|
+
is larger than `fraction_evaluate * total_connected_nodes`,
|
56
|
+
`min_evaluate_nodes` will still be sampled.
|
57
|
+
min_train_nodes : int (default: 2)
|
58
|
+
Minimum number of nodes used during training.
|
59
|
+
min_evaluate_nodes : int (default: 2)
|
60
|
+
Minimum number of nodes used during validation.
|
61
|
+
min_available_nodes : int (default: 2)
|
62
|
+
Minimum number of total nodes in the system.
|
63
|
+
weighted_by_key : str (default: "num-examples")
|
64
|
+
The key within each MetricRecord whose value is used as the weight when
|
65
|
+
computing weighted averages for both ArrayRecords and MetricRecords.
|
66
|
+
arrayrecord_key : str (default: "arrays")
|
67
|
+
Key used to store the ArrayRecord when constructing Messages.
|
68
|
+
configrecord_key : str (default: "config")
|
69
|
+
Key used to store the ConfigRecord when constructing Messages.
|
70
|
+
train_metrics_aggr_fn : Optional[callable] (default: None)
|
71
|
+
Function with signature (list[RecordDict], str) -> MetricRecord,
|
72
|
+
used to aggregate MetricRecords from training round replies.
|
73
|
+
If `None`, defaults to `aggregate_metricrecords`, which performs a weighted
|
74
|
+
average using the provided weight factor key.
|
75
|
+
evaluate_metrics_aggr_fn : Optional[callable] (default: None)
|
76
|
+
Function with signature (list[RecordDict], str) -> MetricRecord,
|
77
|
+
used to aggregate MetricRecords from training round replies.
|
78
|
+
If `None`, defaults to `aggregate_metricrecords`, which performs a weighted
|
79
|
+
average using the provided weight factor key.
|
80
|
+
server_learning_rate: float (default: 1.0)
|
81
|
+
Server-side learning rate used in server-side optimization.
|
82
|
+
server_momentum: float (default: 0.0)
|
83
|
+
Server-side momentum factor used for FedAvgM.
|
84
|
+
"""
|
85
|
+
|
86
|
+
def __init__( # pylint: disable=R0913, R0917
|
87
|
+
self,
|
88
|
+
fraction_train: float = 1.0,
|
89
|
+
fraction_evaluate: float = 1.0,
|
90
|
+
min_train_nodes: int = 2,
|
91
|
+
min_evaluate_nodes: int = 2,
|
92
|
+
min_available_nodes: int = 2,
|
93
|
+
weighted_by_key: str = "num-examples",
|
94
|
+
arrayrecord_key: str = "arrays",
|
95
|
+
configrecord_key: str = "config",
|
96
|
+
train_metrics_aggr_fn: Optional[
|
97
|
+
Callable[[list[RecordDict], str], MetricRecord]
|
98
|
+
] = None,
|
99
|
+
evaluate_metrics_aggr_fn: Optional[
|
100
|
+
Callable[[list[RecordDict], str], MetricRecord]
|
101
|
+
] = None,
|
102
|
+
server_learning_rate: float = 1.0,
|
103
|
+
server_momentum: float = 0.0,
|
104
|
+
) -> None:
|
105
|
+
super().__init__(
|
106
|
+
fraction_train=fraction_train,
|
107
|
+
fraction_evaluate=fraction_evaluate,
|
108
|
+
min_train_nodes=min_train_nodes,
|
109
|
+
min_evaluate_nodes=min_evaluate_nodes,
|
110
|
+
min_available_nodes=min_available_nodes,
|
111
|
+
weighted_by_key=weighted_by_key,
|
112
|
+
arrayrecord_key=arrayrecord_key,
|
113
|
+
configrecord_key=configrecord_key,
|
114
|
+
train_metrics_aggr_fn=train_metrics_aggr_fn,
|
115
|
+
evaluate_metrics_aggr_fn=evaluate_metrics_aggr_fn,
|
116
|
+
)
|
117
|
+
self.server_learning_rate = server_learning_rate
|
118
|
+
self.server_momentum = server_momentum
|
119
|
+
self.server_opt: bool = (self.server_momentum != 0.0) or (
|
120
|
+
self.server_learning_rate != 1.0
|
121
|
+
)
|
122
|
+
self.current_arrays: Optional[ArrayRecord] = None
|
123
|
+
self.momentum_vector: Optional[NDArrays] = None
|
124
|
+
|
125
|
+
def summary(self) -> None:
|
126
|
+
"""Log summary configuration of the strategy."""
|
127
|
+
opt_status = "ON" if self.server_opt else "OFF"
|
128
|
+
log(INFO, "\t├──> FedAvgM settings:")
|
129
|
+
log(INFO, "\t|\t├── Server optimization: %s", opt_status)
|
130
|
+
log(INFO, "\t|\t├── Server learning rate: %s", self.server_learning_rate)
|
131
|
+
log(INFO, "\t|\t└── Server Momentum: %s", self.server_momentum)
|
132
|
+
super().summary()
|
133
|
+
|
134
|
+
def configure_train(
|
135
|
+
self, server_round: int, arrays: ArrayRecord, config: ConfigRecord, grid: Grid
|
136
|
+
) -> Iterable[Message]:
|
137
|
+
"""Configure the next round of federated training."""
|
138
|
+
if self.current_arrays is None:
|
139
|
+
self.current_arrays = arrays
|
140
|
+
return super().configure_train(server_round, arrays, config, grid)
|
141
|
+
|
142
|
+
def aggregate_train(
|
143
|
+
self,
|
144
|
+
server_round: int,
|
145
|
+
replies: Iterable[Message],
|
146
|
+
) -> tuple[Optional[ArrayRecord], Optional[MetricRecord]]:
|
147
|
+
"""Aggregate ArrayRecords and MetricRecords in the received Messages."""
|
148
|
+
# Call FedAvg aggregate_train to perform validation and aggregation
|
149
|
+
aggregated_arrays, aggregated_metrics = super().aggregate_train(
|
150
|
+
server_round, replies
|
151
|
+
)
|
152
|
+
|
153
|
+
# following convention described in
|
154
|
+
# https://pytorch.org/docs/stable/generated/torch.optim.SGD.html
|
155
|
+
if self.server_opt and aggregated_arrays is not None:
|
156
|
+
# The initial parameters should be set in `start()` method already
|
157
|
+
if self.current_arrays is None:
|
158
|
+
raise AggregationError(
|
159
|
+
"No initial parameters set for FedAvgM. "
|
160
|
+
"Ensure that `configure_train` has been called before aggregation."
|
161
|
+
)
|
162
|
+
ndarrays = self.current_arrays.to_numpy_ndarrays()
|
163
|
+
aggregated_ndarrays = aggregated_arrays.to_numpy_ndarrays()
|
164
|
+
|
165
|
+
# Preserve keys for arrays in ArrayRecord
|
166
|
+
array_keys = list(aggregated_arrays.keys())
|
167
|
+
aggregated_arrays.clear()
|
168
|
+
|
169
|
+
# Remember that updates are the opposite of gradients
|
170
|
+
pseudo_gradient = [
|
171
|
+
old - new for new, old in zip(aggregated_ndarrays, ndarrays)
|
172
|
+
]
|
173
|
+
if self.server_momentum > 0.0:
|
174
|
+
if self.momentum_vector is None:
|
175
|
+
# Initialize momentum vector in the first round
|
176
|
+
self.momentum_vector = pseudo_gradient
|
177
|
+
else:
|
178
|
+
self.momentum_vector = [
|
179
|
+
self.server_momentum * mv + pg
|
180
|
+
for mv, pg in zip(self.momentum_vector, pseudo_gradient)
|
181
|
+
]
|
182
|
+
|
183
|
+
# No nesterov for now
|
184
|
+
pseudo_gradient = self.momentum_vector
|
185
|
+
|
186
|
+
# SGD and convert back to ArrayRecord
|
187
|
+
updated_array_list = [
|
188
|
+
Array(old - self.server_learning_rate * pg)
|
189
|
+
for old, pg in zip(ndarrays, pseudo_gradient)
|
190
|
+
]
|
191
|
+
aggregated_arrays = ArrayRecord(
|
192
|
+
OrderedDict(zip(array_keys, updated_array_list))
|
193
|
+
)
|
194
|
+
|
195
|
+
# Update current weights
|
196
|
+
self.current_arrays = aggregated_arrays
|
197
|
+
|
198
|
+
return aggregated_arrays, aggregated_metrics
|
@@ -0,0 +1,71 @@
|
|
1
|
+
# Copyright 2025 Flower Labs GmbH. All Rights Reserved.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
# ==============================================================================
|
15
|
+
"""Federated Median (FedMedian) [Yin et al., 2018] strategy.
|
16
|
+
|
17
|
+
Paper: arxiv.org/pdf/1803.01498v1.pdf
|
18
|
+
"""
|
19
|
+
|
20
|
+
|
21
|
+
from collections.abc import Iterable
|
22
|
+
from typing import Optional, cast
|
23
|
+
|
24
|
+
import numpy as np
|
25
|
+
|
26
|
+
from flwr.common import Array, ArrayRecord, Message, MetricRecord
|
27
|
+
|
28
|
+
from .fedavg import FedAvg
|
29
|
+
|
30
|
+
|
31
|
+
class FedMedian(FedAvg):
|
32
|
+
"""Federated Median (FedMedian) strategy.
|
33
|
+
|
34
|
+
Implementation based on https://arxiv.org/pdf/1803.01498v1
|
35
|
+
"""
|
36
|
+
|
37
|
+
def aggregate_train(
|
38
|
+
self,
|
39
|
+
server_round: int,
|
40
|
+
replies: Iterable[Message],
|
41
|
+
) -> tuple[Optional[ArrayRecord], Optional[MetricRecord]]:
|
42
|
+
"""Aggregate ArrayRecords and MetricRecords in the received Messages."""
|
43
|
+
# Call FedAvg aggregate_train to perform validation and aggregation
|
44
|
+
valid_replies, _ = self._check_and_log_replies(replies, is_train=True)
|
45
|
+
|
46
|
+
if not valid_replies:
|
47
|
+
return None, None
|
48
|
+
|
49
|
+
# Aggregate ArrayRecords using median
|
50
|
+
# Get the key for the only ArrayRecord from the first Message
|
51
|
+
record_key = list(valid_replies[0].content.array_records.keys())[0]
|
52
|
+
# Preserve keys for arrays in ArrayRecord
|
53
|
+
array_keys = list(valid_replies[0].content[record_key].keys())
|
54
|
+
|
55
|
+
# Compute median for each layer and construct ArrayRecord
|
56
|
+
arrays = ArrayRecord()
|
57
|
+
for array_key in array_keys:
|
58
|
+
# Get the corresponding layer from each client
|
59
|
+
layers = [
|
60
|
+
cast(ArrayRecord, msg.content[record_key]).pop(array_key).numpy()
|
61
|
+
for msg in valid_replies
|
62
|
+
]
|
63
|
+
# Compute median and save as Array in ArrayRecord
|
64
|
+
arrays[array_key] = Array(np.median(np.stack(layers), axis=0))
|
65
|
+
|
66
|
+
# Aggregate MetricRecords
|
67
|
+
metrics = self.train_metrics_aggr_fn(
|
68
|
+
[msg.content for msg in valid_replies],
|
69
|
+
self.weighted_by_key,
|
70
|
+
)
|
71
|
+
return arrays, metrics
|
@@ -0,0 +1,174 @@
|
|
1
|
+
# Copyright 2025 Flower Labs GmbH. All Rights Reserved.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
# ==============================================================================
|
15
|
+
"""Federated Optimization (FedProx) [Li et al., 2018] strategy.
|
16
|
+
|
17
|
+
Paper: arxiv.org/abs/1812.06127
|
18
|
+
"""
|
19
|
+
|
20
|
+
|
21
|
+
from collections.abc import Iterable
|
22
|
+
from logging import INFO, WARN
|
23
|
+
from typing import Callable, Optional
|
24
|
+
|
25
|
+
from flwr.common import (
|
26
|
+
ArrayRecord,
|
27
|
+
ConfigRecord,
|
28
|
+
Message,
|
29
|
+
MetricRecord,
|
30
|
+
RecordDict,
|
31
|
+
log,
|
32
|
+
)
|
33
|
+
from flwr.server import Grid
|
34
|
+
|
35
|
+
from .fedavg import FedAvg
|
36
|
+
|
37
|
+
|
38
|
+
class FedProx(FedAvg):
|
39
|
+
r"""Federated Optimization strategy.
|
40
|
+
|
41
|
+
Implementation based on https://arxiv.org/abs/1812.06127
|
42
|
+
|
43
|
+
FedProx extends FedAvg by introducing a proximal term into the client-side
|
44
|
+
optimization objective. The strategy itself behaves identically to FedAvg
|
45
|
+
on the server side, but each client **MUST** add a proximal regularization
|
46
|
+
term to its local loss function during training:
|
47
|
+
|
48
|
+
.. math::
|
49
|
+
\frac{\mu}{2} || w - w^t ||^2
|
50
|
+
|
51
|
+
Where $w^t$ denotes the global parameters and $w$ denotes the local weights
|
52
|
+
being optimized.
|
53
|
+
|
54
|
+
This strategy sends the proximal term inside the ``ConfigRecord`` as part of the
|
55
|
+
``configure_train`` method under key ``"proximal-mu"``. The client can then use this
|
56
|
+
value to add the proximal term to the loss function.
|
57
|
+
|
58
|
+
In PyTorch, for example, the loss would go from:
|
59
|
+
|
60
|
+
.. code:: python
|
61
|
+
loss = criterion(net(inputs), labels)
|
62
|
+
|
63
|
+
To:
|
64
|
+
|
65
|
+
.. code:: python
|
66
|
+
# Get proximal term weight from message
|
67
|
+
mu = msg.content["config"]["proximal-mu"]
|
68
|
+
|
69
|
+
# Compute proximal term
|
70
|
+
proximal_term = 0.0
|
71
|
+
for local_weights, global_weights in zip(net.parameters(), global_params):
|
72
|
+
proximal_term += (local_weights - global_weights).norm(2)
|
73
|
+
|
74
|
+
# Update loss
|
75
|
+
loss = criterion(net(inputs), labels) + (mu / 2) * proximal_term
|
76
|
+
|
77
|
+
With ``global_params`` being a copy of the model parameters, created **after**
|
78
|
+
applying the received global weights but **before** local training begins.
|
79
|
+
|
80
|
+
.. code:: python
|
81
|
+
global_params = copy.deepcopy(net).parameters()
|
82
|
+
|
83
|
+
Parameters
|
84
|
+
----------
|
85
|
+
fraction_train : float (default: 1.0)
|
86
|
+
Fraction of nodes used during training. In case `min_train_nodes`
|
87
|
+
is larger than `fraction_train * total_connected_nodes`, `min_train_nodes`
|
88
|
+
will still be sampled.
|
89
|
+
fraction_evaluate : float (default: 1.0)
|
90
|
+
Fraction of nodes used during validation. In case `min_evaluate_nodes`
|
91
|
+
is larger than `fraction_evaluate * total_connected_nodes`,
|
92
|
+
`min_evaluate_nodes` will still be sampled.
|
93
|
+
min_train_nodes : int (default: 2)
|
94
|
+
Minimum number of nodes used during training.
|
95
|
+
min_evaluate_nodes : int (default: 2)
|
96
|
+
Minimum number of nodes used during validation.
|
97
|
+
min_available_nodes : int (default: 2)
|
98
|
+
Minimum number of total nodes in the system.
|
99
|
+
weighted_by_key : str (default: "num-examples")
|
100
|
+
The key within each MetricRecord whose value is used as the weight when
|
101
|
+
computing weighted averages for both ArrayRecords and MetricRecords.
|
102
|
+
arrayrecord_key : str (default: "arrays")
|
103
|
+
Key used to store the ArrayRecord when constructing Messages.
|
104
|
+
configrecord_key : str (default: "config")
|
105
|
+
Key used to store the ConfigRecord when constructing Messages.
|
106
|
+
train_metrics_aggr_fn : Optional[callable] (default: None)
|
107
|
+
Function with signature (list[RecordDict], str) -> MetricRecord,
|
108
|
+
used to aggregate MetricRecords from training round replies.
|
109
|
+
If `None`, defaults to `aggregate_metricrecords`, which performs a weighted
|
110
|
+
average using the provided weight factor key.
|
111
|
+
evaluate_metrics_aggr_fn : Optional[callable] (default: None)
|
112
|
+
Function with signature (list[RecordDict], str) -> MetricRecord,
|
113
|
+
used to aggregate MetricRecords from training round replies.
|
114
|
+
If `None`, defaults to `aggregate_metricrecords`, which performs a weighted
|
115
|
+
average using the provided weight factor key.
|
116
|
+
proximal_mu : float (default: 0.0)
|
117
|
+
The weight of the proximal term used in the optimization. 0.0 makes
|
118
|
+
this strategy equivalent to FedAvg, and the higher the coefficient, the more
|
119
|
+
regularization will be used (that is, the client parameters will need to be
|
120
|
+
closer to the server parameters during training).
|
121
|
+
"""
|
122
|
+
|
123
|
+
def __init__( # pylint: disable=R0913, R0917
|
124
|
+
self,
|
125
|
+
fraction_train: float = 1.0,
|
126
|
+
fraction_evaluate: float = 1.0,
|
127
|
+
min_train_nodes: int = 2,
|
128
|
+
min_evaluate_nodes: int = 2,
|
129
|
+
min_available_nodes: int = 2,
|
130
|
+
weighted_by_key: str = "num-examples",
|
131
|
+
arrayrecord_key: str = "arrays",
|
132
|
+
configrecord_key: str = "config",
|
133
|
+
train_metrics_aggr_fn: Optional[
|
134
|
+
Callable[[list[RecordDict], str], MetricRecord]
|
135
|
+
] = None,
|
136
|
+
evaluate_metrics_aggr_fn: Optional[
|
137
|
+
Callable[[list[RecordDict], str], MetricRecord]
|
138
|
+
] = None,
|
139
|
+
proximal_mu: float = 0.0,
|
140
|
+
) -> None:
|
141
|
+
super().__init__(
|
142
|
+
fraction_train=fraction_train,
|
143
|
+
fraction_evaluate=fraction_evaluate,
|
144
|
+
min_train_nodes=min_train_nodes,
|
145
|
+
min_evaluate_nodes=min_evaluate_nodes,
|
146
|
+
min_available_nodes=min_available_nodes,
|
147
|
+
weighted_by_key=weighted_by_key,
|
148
|
+
arrayrecord_key=arrayrecord_key,
|
149
|
+
configrecord_key=configrecord_key,
|
150
|
+
train_metrics_aggr_fn=train_metrics_aggr_fn,
|
151
|
+
evaluate_metrics_aggr_fn=evaluate_metrics_aggr_fn,
|
152
|
+
)
|
153
|
+
self.proximal_mu = proximal_mu
|
154
|
+
|
155
|
+
if self.proximal_mu == 0.0:
|
156
|
+
log(
|
157
|
+
WARN,
|
158
|
+
"FedProx initialized with `proximal_mu=0.0`. "
|
159
|
+
"This makes the strategy equivalent to FedAvg.",
|
160
|
+
)
|
161
|
+
|
162
|
+
def summary(self) -> None:
|
163
|
+
"""Log summary configuration of the strategy."""
|
164
|
+
log(INFO, "\t├──> FedProx settings:")
|
165
|
+
log(INFO, "\t|\t└── Proximal mu: %s", self.proximal_mu)
|
166
|
+
super().summary()
|
167
|
+
|
168
|
+
def configure_train(
|
169
|
+
self, server_round: int, arrays: ArrayRecord, config: ConfigRecord, grid: Grid
|
170
|
+
) -> Iterable[Message]:
|
171
|
+
"""Configure the next round of federated training."""
|
172
|
+
# Inject proximal term weight into config
|
173
|
+
config["proximal-mu"] = self.proximal_mu
|
174
|
+
return super().configure_train(server_round, arrays, config, grid)
|
@@ -0,0 +1,176 @@
|
|
1
|
+
# Copyright 2025 Flower Labs GmbH. All Rights Reserved.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
# ==============================================================================
|
15
|
+
"""Federated Averaging with Trimmed Mean [Dong Yin, et al., 2021].
|
16
|
+
|
17
|
+
Paper: arxiv.org/abs/1803.01498
|
18
|
+
"""
|
19
|
+
|
20
|
+
|
21
|
+
from collections.abc import Iterable
|
22
|
+
from logging import INFO
|
23
|
+
from typing import Callable, Optional, cast
|
24
|
+
|
25
|
+
import numpy as np
|
26
|
+
|
27
|
+
from flwr.common import Array, ArrayRecord, Message, MetricRecord, NDArray, RecordDict
|
28
|
+
from flwr.common.logger import log
|
29
|
+
|
30
|
+
from ..exception import AggregationError
|
31
|
+
from .fedavg import FedAvg
|
32
|
+
|
33
|
+
|
34
|
+
class FedTrimmedAvg(FedAvg):
|
35
|
+
"""Federated Averaging with Trimmed Mean [Dong Yin, et al., 2021].
|
36
|
+
|
37
|
+
Implemented based on: https://arxiv.org/abs/1803.01498
|
38
|
+
|
39
|
+
Parameters
|
40
|
+
----------
|
41
|
+
fraction_train : float (default: 1.0)
|
42
|
+
Fraction of nodes used during training. In case `min_train_nodes`
|
43
|
+
is larger than `fraction_train * total_connected_nodes`, `min_train_nodes`
|
44
|
+
will still be sampled.
|
45
|
+
fraction_evaluate : float (default: 1.0)
|
46
|
+
Fraction of nodes used during validation. In case `min_evaluate_nodes`
|
47
|
+
is larger than `fraction_evaluate * total_connected_nodes`,
|
48
|
+
`min_evaluate_nodes` will still be sampled.
|
49
|
+
min_train_nodes : int (default: 2)
|
50
|
+
Minimum number of nodes used during training.
|
51
|
+
min_evaluate_nodes : int (default: 2)
|
52
|
+
Minimum number of nodes used during validation.
|
53
|
+
min_available_nodes : int (default: 2)
|
54
|
+
Minimum number of total nodes in the system.
|
55
|
+
weighted_by_key : str (default: "num-examples")
|
56
|
+
The key within each MetricRecord whose value is used as the weight when
|
57
|
+
computing weighted averages for both ArrayRecords and MetricRecords.
|
58
|
+
arrayrecord_key : str (default: "arrays")
|
59
|
+
Key used to store the ArrayRecord when constructing Messages.
|
60
|
+
configrecord_key : str (default: "config")
|
61
|
+
Key used to store the ConfigRecord when constructing Messages.
|
62
|
+
train_metrics_aggr_fn : Optional[callable] (default: None)
|
63
|
+
Function with signature (list[RecordDict], str) -> MetricRecord,
|
64
|
+
used to aggregate MetricRecords from training round replies.
|
65
|
+
If `None`, defaults to `aggregate_metricrecords`, which performs a weighted
|
66
|
+
average using the provided weight factor key.
|
67
|
+
evaluate_metrics_aggr_fn : Optional[callable] (default: None)
|
68
|
+
Function with signature (list[RecordDict], str) -> MetricRecord,
|
69
|
+
used to aggregate MetricRecords from training round replies.
|
70
|
+
If `None`, defaults to `aggregate_metricrecords`, which performs a weighted
|
71
|
+
average using the provided weight factor key.
|
72
|
+
beta : float (default: 0.2)
|
73
|
+
Fraction to cut off of both tails of the distribution.
|
74
|
+
"""
|
75
|
+
|
76
|
+
def __init__( # pylint: disable=R0913, R0917
|
77
|
+
self,
|
78
|
+
fraction_train: float = 1.0,
|
79
|
+
fraction_evaluate: float = 1.0,
|
80
|
+
min_train_nodes: int = 2,
|
81
|
+
min_evaluate_nodes: int = 2,
|
82
|
+
min_available_nodes: int = 2,
|
83
|
+
weighted_by_key: str = "num-examples",
|
84
|
+
arrayrecord_key: str = "arrays",
|
85
|
+
configrecord_key: str = "config",
|
86
|
+
train_metrics_aggr_fn: Optional[
|
87
|
+
Callable[[list[RecordDict], str], MetricRecord]
|
88
|
+
] = None,
|
89
|
+
evaluate_metrics_aggr_fn: Optional[
|
90
|
+
Callable[[list[RecordDict], str], MetricRecord]
|
91
|
+
] = None,
|
92
|
+
beta: float = 0.2,
|
93
|
+
) -> None:
|
94
|
+
super().__init__(
|
95
|
+
fraction_train=fraction_train,
|
96
|
+
fraction_evaluate=fraction_evaluate,
|
97
|
+
min_train_nodes=min_train_nodes,
|
98
|
+
min_evaluate_nodes=min_evaluate_nodes,
|
99
|
+
min_available_nodes=min_available_nodes,
|
100
|
+
weighted_by_key=weighted_by_key,
|
101
|
+
arrayrecord_key=arrayrecord_key,
|
102
|
+
configrecord_key=configrecord_key,
|
103
|
+
train_metrics_aggr_fn=train_metrics_aggr_fn,
|
104
|
+
evaluate_metrics_aggr_fn=evaluate_metrics_aggr_fn,
|
105
|
+
)
|
106
|
+
self.beta = beta
|
107
|
+
|
108
|
+
def summary(self) -> None:
|
109
|
+
"""Log summary configuration of the strategy."""
|
110
|
+
log(INFO, "\t├──> FedTrimmedAvg settings:")
|
111
|
+
log(INFO, "\t|\t└── beta: %s", self.beta)
|
112
|
+
super().summary()
|
113
|
+
|
114
|
+
def aggregate_train(
|
115
|
+
self,
|
116
|
+
server_round: int,
|
117
|
+
replies: Iterable[Message],
|
118
|
+
) -> tuple[Optional[ArrayRecord], Optional[MetricRecord]]:
|
119
|
+
"""Aggregate ArrayRecords and MetricRecords in the received Messages."""
|
120
|
+
# Call FedAvg aggregate_train to perform validation and aggregation
|
121
|
+
valid_replies, _ = self._check_and_log_replies(replies, is_train=True)
|
122
|
+
|
123
|
+
if not valid_replies:
|
124
|
+
return None, None
|
125
|
+
|
126
|
+
# Aggregate ArrayRecords using trimmed mean
|
127
|
+
# Get the key for the only ArrayRecord from the first Message
|
128
|
+
record_key = list(valid_replies[0].content.array_records.keys())[0]
|
129
|
+
# Preserve keys for arrays in ArrayRecord
|
130
|
+
array_keys = list(valid_replies[0].content[record_key].keys())
|
131
|
+
|
132
|
+
# Compute trimmed mean for each layer and construct ArrayRecord
|
133
|
+
arrays = ArrayRecord()
|
134
|
+
for array_key in array_keys:
|
135
|
+
# Get the corresponding layer from each client
|
136
|
+
layers = [
|
137
|
+
cast(ArrayRecord, msg.content[record_key]).pop(array_key).numpy()
|
138
|
+
for msg in valid_replies
|
139
|
+
]
|
140
|
+
# Compute trimmed mean and save as Array in ArrayRecord
|
141
|
+
try:
|
142
|
+
arrays[array_key] = Array(trim_mean(np.stack(layers), self.beta))
|
143
|
+
except ValueError as e:
|
144
|
+
raise AggregationError(
|
145
|
+
f"Trimmed mean could not be computed. "
|
146
|
+
f"Likely cause: beta={self.beta} is too large."
|
147
|
+
) from e
|
148
|
+
|
149
|
+
# Aggregate MetricRecords
|
150
|
+
metrics = self.train_metrics_aggr_fn(
|
151
|
+
[msg.content for msg in valid_replies],
|
152
|
+
self.weighted_by_key,
|
153
|
+
)
|
154
|
+
return arrays, metrics
|
155
|
+
|
156
|
+
|
157
|
+
def trim_mean(array: NDArray, cut_fraction: float) -> NDArray:
|
158
|
+
"""Compute trimmed mean along axis=0.
|
159
|
+
|
160
|
+
It is based on the scipy implementation:
|
161
|
+
|
162
|
+
https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.trim_mean.html
|
163
|
+
"""
|
164
|
+
axis = 0
|
165
|
+
nobs = array.shape[0]
|
166
|
+
lowercut = int(cut_fraction * nobs)
|
167
|
+
uppercut = nobs - lowercut
|
168
|
+
if lowercut > uppercut:
|
169
|
+
raise ValueError("Fraction too big.")
|
170
|
+
|
171
|
+
atmp = np.partition(array, (lowercut, uppercut - 1), axis)
|
172
|
+
|
173
|
+
slice_list = [slice(None)] * atmp.ndim
|
174
|
+
slice_list[axis] = slice(lowercut, uppercut)
|
175
|
+
result: NDArray = np.mean(atmp[tuple(slice_list)], axis=axis)
|
176
|
+
return result
|
@@ -16,12 +16,20 @@
|
|
16
16
|
|
17
17
|
|
18
18
|
from collections import OrderedDict
|
19
|
+
from unittest.mock import Mock
|
19
20
|
|
20
21
|
import numpy as np
|
21
22
|
import pytest
|
22
23
|
from parameterized import parameterized
|
23
24
|
|
24
|
-
from flwr.common import
|
25
|
+
from flwr.common import (
|
26
|
+
Array,
|
27
|
+
ArrayRecord,
|
28
|
+
ConfigRecord,
|
29
|
+
Message,
|
30
|
+
MetricRecord,
|
31
|
+
RecordDict,
|
32
|
+
)
|
25
33
|
from flwr.serverapp.exception import InconsistentMessageReplies
|
26
34
|
|
27
35
|
from .strategy_utils import (
|
@@ -32,6 +40,17 @@ from .strategy_utils import (
|
|
32
40
|
)
|
33
41
|
|
34
42
|
|
43
|
+
def create_mock_reply(arrays: ArrayRecord, num_examples: float) -> Message:
|
44
|
+
"""Create a mock reply Message with default keys."""
|
45
|
+
message = Mock(spec=Message)
|
46
|
+
message.content = RecordDict(
|
47
|
+
{"arrays": arrays, "metrics": MetricRecord({"num-examples": num_examples})}
|
48
|
+
)
|
49
|
+
message.has_error.side_effect = lambda: False
|
50
|
+
message.has_content.side_effect = lambda: True
|
51
|
+
return message
|
52
|
+
|
53
|
+
|
35
54
|
def test_config_to_str() -> None:
|
36
55
|
"""Test that items of types bytes are masked out."""
|
37
56
|
config = ConfigRecord({"a": 123, "b": [1, 2, 3], "c": b"bytes"})
|
flwr/simulation/app.py
CHANGED
@@ -245,7 +245,7 @@ def run_simulation_process( # pylint: disable=R0913, R0914, R0915, R0917, W0212
|
|
245
245
|
run=run,
|
246
246
|
enable_tf_gpu_growth=enable_tf_gpu_growth,
|
247
247
|
verbose_logging=verbose,
|
248
|
-
|
248
|
+
server_app_context=context,
|
249
249
|
is_app=True,
|
250
250
|
exit_event=EventType.FLWR_SIMULATION_RUN_LEAVE,
|
251
251
|
)
|