flwr-nightly 1.21.0.dev20250902__py3-none-any.whl → 1.21.0.dev20250904__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/constant.py +25 -8
- flwr/cli/new/templates/app/code/server.pytorch_msg_api.py.tpl +0 -8
- flwr/cli/run/run.py +2 -6
- flwr/clientapp/__init__.py +4 -0
- flwr/clientapp/centraldp_mods.py +132 -0
- flwr/common/exception.py +31 -0
- flwr/common/exit/exit_code.py +2 -0
- flwr/server/serverapp/app.py +41 -28
- flwr/serverapp/dp_fixed_clipping.py +352 -0
- flwr/serverapp/strategy/__init__.py +12 -0
- flwr/serverapp/strategy/dp_fixed_clipping.py +352 -0
- flwr/serverapp/strategy/fedadagrad.py +162 -0
- flwr/serverapp/strategy/fedadam.py +181 -0
- flwr/serverapp/strategy/fedopt.py +218 -0
- flwr/serverapp/strategy/fedyogi.py +173 -0
- flwr/serverapp/strategy/result.py +76 -1
- flwr/serverapp/strategy/strategy.py +18 -23
- flwr/serverapp/strategy/strategy_utils.py +14 -1
- {flwr_nightly-1.21.0.dev20250902.dist-info → flwr_nightly-1.21.0.dev20250904.dist-info}/METADATA +1 -1
- {flwr_nightly-1.21.0.dev20250902.dist-info → flwr_nightly-1.21.0.dev20250904.dist-info}/RECORD +22 -14
- {flwr_nightly-1.21.0.dev20250902.dist-info → flwr_nightly-1.21.0.dev20250904.dist-info}/WHEEL +0 -0
- {flwr_nightly-1.21.0.dev20250902.dist-info → flwr_nightly-1.21.0.dev20250904.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,218 @@
|
|
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
|
+
"""Adaptive Federated Optimization (FedOpt) [Reddi et al., 2020] abstract strategy.
|
16
|
+
|
17
|
+
Paper: arxiv.org/abs/2003.00295
|
18
|
+
"""
|
19
|
+
|
20
|
+
from collections.abc import Iterable
|
21
|
+
from logging import INFO
|
22
|
+
from typing import Callable, Optional
|
23
|
+
|
24
|
+
import numpy as np
|
25
|
+
|
26
|
+
from flwr.common import (
|
27
|
+
ArrayRecord,
|
28
|
+
ConfigRecord,
|
29
|
+
Message,
|
30
|
+
MetricRecord,
|
31
|
+
NDArray,
|
32
|
+
RecordDict,
|
33
|
+
log,
|
34
|
+
)
|
35
|
+
from flwr.server import Grid
|
36
|
+
|
37
|
+
from .fedavg import FedAvg
|
38
|
+
from .strategy_utils import AggregationError
|
39
|
+
|
40
|
+
|
41
|
+
# pylint: disable=line-too-long
|
42
|
+
class FedOpt(FedAvg):
|
43
|
+
"""Federated Optim strategy.
|
44
|
+
|
45
|
+
Implementation based on https://arxiv.org/abs/2003.00295v5
|
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
|
+
eta : float, optional
|
81
|
+
Server-side learning rate. Defaults to 1e-1.
|
82
|
+
eta_l : float, optional
|
83
|
+
Client-side learning rate. Defaults to 1e-1.
|
84
|
+
beta_1 : float, optional
|
85
|
+
Momentum parameter. Defaults to 0.0.
|
86
|
+
beta_2 : float, optional
|
87
|
+
Second moment parameter. Defaults to 0.0.
|
88
|
+
tau : float, optional
|
89
|
+
Controls the algorithm's degree of adaptability. Defaults to 1e-3.
|
90
|
+
"""
|
91
|
+
|
92
|
+
# pylint: disable=too-many-arguments,too-many-instance-attributes,too-many-locals, line-too-long
|
93
|
+
def __init__(
|
94
|
+
self,
|
95
|
+
*,
|
96
|
+
fraction_train: float = 1.0,
|
97
|
+
fraction_evaluate: float = 1.0,
|
98
|
+
min_train_nodes: int = 2,
|
99
|
+
min_evaluate_nodes: int = 2,
|
100
|
+
min_available_nodes: int = 2,
|
101
|
+
weighted_by_key: str = "num-examples",
|
102
|
+
arrayrecord_key: str = "arrays",
|
103
|
+
configrecord_key: str = "config",
|
104
|
+
train_metrics_aggr_fn: Optional[
|
105
|
+
Callable[[list[RecordDict], str], MetricRecord]
|
106
|
+
] = None,
|
107
|
+
evaluate_metrics_aggr_fn: Optional[
|
108
|
+
Callable[[list[RecordDict], str], MetricRecord]
|
109
|
+
] = None,
|
110
|
+
eta: float = 1e-1,
|
111
|
+
eta_l: float = 1e-1,
|
112
|
+
beta_1: float = 0.0,
|
113
|
+
beta_2: float = 0.0,
|
114
|
+
tau: float = 1e-3,
|
115
|
+
) -> None:
|
116
|
+
super().__init__(
|
117
|
+
fraction_train=fraction_train,
|
118
|
+
fraction_evaluate=fraction_evaluate,
|
119
|
+
min_train_nodes=min_train_nodes,
|
120
|
+
min_evaluate_nodes=min_evaluate_nodes,
|
121
|
+
min_available_nodes=min_available_nodes,
|
122
|
+
weighted_by_key=weighted_by_key,
|
123
|
+
arrayrecord_key=arrayrecord_key,
|
124
|
+
configrecord_key=configrecord_key,
|
125
|
+
train_metrics_aggr_fn=train_metrics_aggr_fn,
|
126
|
+
evaluate_metrics_aggr_fn=evaluate_metrics_aggr_fn,
|
127
|
+
)
|
128
|
+
self.current_arrays: Optional[dict[str, NDArray]] = None
|
129
|
+
self.eta = eta
|
130
|
+
self.eta_l = eta_l
|
131
|
+
self.tau = tau
|
132
|
+
self.beta_1 = beta_1
|
133
|
+
self.beta_2 = beta_2
|
134
|
+
self.m_t: Optional[dict[str, NDArray]] = None
|
135
|
+
self.v_t: Optional[dict[str, NDArray]] = None
|
136
|
+
|
137
|
+
def summary(self) -> None:
|
138
|
+
"""Log summary configuration of the strategy."""
|
139
|
+
log(INFO, "\t├──> FedOpt settings:")
|
140
|
+
log(
|
141
|
+
INFO,
|
142
|
+
"\t│\t├── eta (%s) | eta_l (%s)",
|
143
|
+
f"{self.eta:.6g}",
|
144
|
+
f"{self.eta_l:.6g}",
|
145
|
+
)
|
146
|
+
log(
|
147
|
+
INFO,
|
148
|
+
"\t│\t├── beta_1 (%s) | beta_2 (%s)",
|
149
|
+
f"{self.beta_1:.6g}",
|
150
|
+
f"{self.beta_2:.6g}",
|
151
|
+
)
|
152
|
+
log(
|
153
|
+
INFO,
|
154
|
+
"\t│\t└── tau (%s)",
|
155
|
+
f"{self.tau:.6g}",
|
156
|
+
)
|
157
|
+
super().summary()
|
158
|
+
|
159
|
+
def configure_train(
|
160
|
+
self, server_round: int, arrays: ArrayRecord, config: ConfigRecord, grid: Grid
|
161
|
+
) -> Iterable[Message]:
|
162
|
+
"""Configure the next round of federated training."""
|
163
|
+
# Keep track of array record being communicated
|
164
|
+
self.current_arrays = {k: array.numpy() for k, array in arrays.items()}
|
165
|
+
return super().configure_train(server_round, arrays, config, grid)
|
166
|
+
|
167
|
+
def _compute_deltat_and_mt(
|
168
|
+
self, aggregated_arrayrecord: ArrayRecord
|
169
|
+
) -> tuple[dict[str, NDArray], dict[str, NDArray], dict[str, NDArray]]:
|
170
|
+
"""Compute delta_t and m_t.
|
171
|
+
|
172
|
+
This is a shared stage during aggregation for FedAdagrad, FedAdam and FedYogi.
|
173
|
+
"""
|
174
|
+
if self.current_arrays is None:
|
175
|
+
reason = (
|
176
|
+
"Current arrays not set. Ensure that `configure_train` has been "
|
177
|
+
"called before aggregation."
|
178
|
+
)
|
179
|
+
raise AggregationError(reason=reason)
|
180
|
+
|
181
|
+
aggregated_ndarrays = {
|
182
|
+
k: array.numpy() for k, array in aggregated_arrayrecord.items()
|
183
|
+
}
|
184
|
+
|
185
|
+
# Check keys in aggregated arrays match those in current arrays
|
186
|
+
if set(aggregated_ndarrays.keys()) != set(self.current_arrays.keys()):
|
187
|
+
reason = (
|
188
|
+
"Keys of the aggregated arrays do not match those of the arrays "
|
189
|
+
"stored at the strategy. `delta_t = aggregated_arrays - "
|
190
|
+
"current_arrays` cannot be computed."
|
191
|
+
)
|
192
|
+
raise AggregationError(reason=reason)
|
193
|
+
|
194
|
+
# Check that the shape of values match
|
195
|
+
# Only shapes that match can compute delta_t (we don't want
|
196
|
+
# broadcasting to happen)
|
197
|
+
for k, x in aggregated_ndarrays.items():
|
198
|
+
if x.shape != self.current_arrays[k].shape:
|
199
|
+
reason = (
|
200
|
+
f"Shape of aggregated array '{k}' does not match "
|
201
|
+
f"shape of the array under the same key stored in the strategy. "
|
202
|
+
f"Cannot compute `delta_t`."
|
203
|
+
)
|
204
|
+
raise AggregationError(reason=reason)
|
205
|
+
|
206
|
+
delta_t = {
|
207
|
+
k: x - self.current_arrays[k] for k, x in aggregated_ndarrays.items()
|
208
|
+
}
|
209
|
+
|
210
|
+
# m_t
|
211
|
+
if not self.m_t:
|
212
|
+
self.m_t = {k: np.zeros_like(v) for k, v in aggregated_ndarrays.items()}
|
213
|
+
self.m_t = {
|
214
|
+
k: self.beta_1 * v + (1 - self.beta_1) * delta_t[k]
|
215
|
+
for k, v in self.m_t.items()
|
216
|
+
}
|
217
|
+
|
218
|
+
return delta_t, self.m_t, aggregated_ndarrays
|
@@ -0,0 +1,173 @@
|
|
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
|
+
"""Adaptive Federated Optimization using Yogi (FedYogi) [Reddi et al., 2020] strategy.
|
16
|
+
|
17
|
+
Paper: arxiv.org/abs/2003.00295
|
18
|
+
"""
|
19
|
+
|
20
|
+
|
21
|
+
from collections import OrderedDict
|
22
|
+
from collections.abc import Iterable
|
23
|
+
from typing import Callable, Optional
|
24
|
+
|
25
|
+
import numpy as np
|
26
|
+
|
27
|
+
from flwr.common import Array, ArrayRecord, Message, MetricRecord, RecordDict
|
28
|
+
|
29
|
+
from .fedopt import FedOpt
|
30
|
+
from .strategy_utils import AggregationError
|
31
|
+
|
32
|
+
|
33
|
+
# pylint: disable=line-too-long
|
34
|
+
class FedYogi(FedOpt):
|
35
|
+
"""FedYogi [Reddi et al., 2020] strategy.
|
36
|
+
|
37
|
+
Implementation based on https://arxiv.org/abs/2003.00295v5
|
38
|
+
|
39
|
+
|
40
|
+
Parameters
|
41
|
+
----------
|
42
|
+
fraction_train : float (default: 1.0)
|
43
|
+
Fraction of nodes used during training. In case `min_train_nodes`
|
44
|
+
is larger than `fraction_train * total_connected_nodes`, `min_train_nodes`
|
45
|
+
will still be sampled.
|
46
|
+
fraction_evaluate : float (default: 1.0)
|
47
|
+
Fraction of nodes used during validation. In case `min_evaluate_nodes`
|
48
|
+
is larger than `fraction_evaluate * total_connected_nodes`,
|
49
|
+
`min_evaluate_nodes` will still be sampled.
|
50
|
+
min_train_nodes : int (default: 2)
|
51
|
+
Minimum number of nodes used during training.
|
52
|
+
min_evaluate_nodes : int (default: 2)
|
53
|
+
Minimum number of nodes used during validation.
|
54
|
+
min_available_nodes : int (default: 2)
|
55
|
+
Minimum number of total nodes in the system.
|
56
|
+
weighted_by_key : str (default: "num-examples")
|
57
|
+
The key within each MetricRecord whose value is used as the weight when
|
58
|
+
computing weighted averages for both ArrayRecords and MetricRecords.
|
59
|
+
arrayrecord_key : str (default: "arrays")
|
60
|
+
Key used to store the ArrayRecord when constructing Messages.
|
61
|
+
configrecord_key : str (default: "config")
|
62
|
+
Key used to store the ConfigRecord when constructing Messages.
|
63
|
+
train_metrics_aggr_fn : Optional[callable] (default: None)
|
64
|
+
Function with signature (list[RecordDict], str) -> MetricRecord,
|
65
|
+
used to aggregate MetricRecords from training round replies.
|
66
|
+
If `None`, defaults to `aggregate_metricrecords`, which performs a weighted
|
67
|
+
average using the provided weight factor key.
|
68
|
+
evaluate_metrics_aggr_fn : Optional[callable] (default: None)
|
69
|
+
Function with signature (list[RecordDict], str) -> MetricRecord,
|
70
|
+
used to aggregate MetricRecords from training round replies.
|
71
|
+
If `None`, defaults to `aggregate_metricrecords`, which performs a weighted
|
72
|
+
average using the provided weight factor key.
|
73
|
+
eta : float, optional
|
74
|
+
Server-side learning rate. Defaults to 1e-2.
|
75
|
+
eta_l : float, optional
|
76
|
+
Client-side learning rate. Defaults to 0.0316.
|
77
|
+
beta_1 : float, optional
|
78
|
+
Momentum parameter. Defaults to 0.9.
|
79
|
+
beta_2 : float, optional
|
80
|
+
Second moment parameter. Defaults to 0.99.
|
81
|
+
tau : float, optional
|
82
|
+
Controls the algorithm's degree of adaptability.
|
83
|
+
Defaults to 1e-3.
|
84
|
+
"""
|
85
|
+
|
86
|
+
# pylint: disable=too-many-arguments, too-many-locals
|
87
|
+
def __init__(
|
88
|
+
self,
|
89
|
+
*,
|
90
|
+
fraction_train: float = 1.0,
|
91
|
+
fraction_evaluate: float = 1.0,
|
92
|
+
min_train_nodes: int = 2,
|
93
|
+
min_evaluate_nodes: int = 2,
|
94
|
+
min_available_nodes: int = 2,
|
95
|
+
weighted_by_key: str = "num-examples",
|
96
|
+
arrayrecord_key: str = "arrays",
|
97
|
+
configrecord_key: str = "config",
|
98
|
+
train_metrics_aggr_fn: Optional[
|
99
|
+
Callable[[list[RecordDict], str], MetricRecord]
|
100
|
+
] = None,
|
101
|
+
evaluate_metrics_aggr_fn: Optional[
|
102
|
+
Callable[[list[RecordDict], str], MetricRecord]
|
103
|
+
] = None,
|
104
|
+
eta: float = 1e-2,
|
105
|
+
eta_l: float = 0.0316,
|
106
|
+
beta_1: float = 0.9,
|
107
|
+
beta_2: float = 0.99,
|
108
|
+
tau: float = 1e-3,
|
109
|
+
) -> None:
|
110
|
+
super().__init__(
|
111
|
+
fraction_train=fraction_train,
|
112
|
+
fraction_evaluate=fraction_evaluate,
|
113
|
+
min_train_nodes=min_train_nodes,
|
114
|
+
min_evaluate_nodes=min_evaluate_nodes,
|
115
|
+
min_available_nodes=min_available_nodes,
|
116
|
+
weighted_by_key=weighted_by_key,
|
117
|
+
arrayrecord_key=arrayrecord_key,
|
118
|
+
configrecord_key=configrecord_key,
|
119
|
+
train_metrics_aggr_fn=train_metrics_aggr_fn,
|
120
|
+
evaluate_metrics_aggr_fn=evaluate_metrics_aggr_fn,
|
121
|
+
eta=eta,
|
122
|
+
eta_l=eta_l,
|
123
|
+
beta_1=beta_1,
|
124
|
+
beta_2=beta_2,
|
125
|
+
tau=tau,
|
126
|
+
)
|
127
|
+
|
128
|
+
def aggregate_train(
|
129
|
+
self,
|
130
|
+
server_round: int,
|
131
|
+
replies: Iterable[Message],
|
132
|
+
) -> tuple[Optional[ArrayRecord], Optional[MetricRecord]]:
|
133
|
+
"""Aggregate ArrayRecords and MetricRecords in the received Messages."""
|
134
|
+
aggregated_arrayrecord, aggregated_metrics = super().aggregate_train(
|
135
|
+
server_round, replies
|
136
|
+
)
|
137
|
+
|
138
|
+
if aggregated_arrayrecord is None:
|
139
|
+
return aggregated_arrayrecord, aggregated_metrics
|
140
|
+
|
141
|
+
if self.current_arrays is None:
|
142
|
+
reason = (
|
143
|
+
"Current arrays not set. Ensure that `configure_train` has been "
|
144
|
+
"called before aggregation."
|
145
|
+
)
|
146
|
+
raise AggregationError(reason=reason)
|
147
|
+
|
148
|
+
# Compute intermediate variables
|
149
|
+
delta_t, m_t, aggregated_ndarrays = self._compute_deltat_and_mt(
|
150
|
+
aggregated_arrayrecord
|
151
|
+
)
|
152
|
+
|
153
|
+
# v_t
|
154
|
+
if not self.v_t:
|
155
|
+
self.v_t = {k: np.zeros_like(v) for k, v in aggregated_ndarrays.items()}
|
156
|
+
self.v_t = {
|
157
|
+
k: v
|
158
|
+
- (1.0 - self.beta_2) * (delta_t[k] ** 2) * np.sign(v - delta_t[k] ** 2)
|
159
|
+
for k, v in self.v_t.items()
|
160
|
+
}
|
161
|
+
|
162
|
+
new_arrays = {
|
163
|
+
k: x + self.eta * m_t[k] / (np.sqrt(self.v_t[k]) + self.tau)
|
164
|
+
for k, x in self.current_arrays.items()
|
165
|
+
}
|
166
|
+
|
167
|
+
# Update current arrays
|
168
|
+
self.current_arrays = new_arrays
|
169
|
+
|
170
|
+
return (
|
171
|
+
ArrayRecord(OrderedDict({k: Array(v) for k, v in new_arrays.items()})),
|
172
|
+
aggregated_metrics,
|
173
|
+
)
|
@@ -15,16 +15,91 @@
|
|
15
15
|
"""Strategy results."""
|
16
16
|
|
17
17
|
|
18
|
+
import pprint
|
18
19
|
from dataclasses import dataclass, field
|
19
20
|
|
20
21
|
from flwr.common import ArrayRecord, MetricRecord
|
22
|
+
from flwr.common.typing import MetricRecordValues
|
21
23
|
|
22
24
|
|
23
25
|
@dataclass
|
24
26
|
class Result:
|
25
|
-
"""Data class carrying records generated during the execution of a strategy.
|
27
|
+
"""Data class carrying records generated during the execution of a strategy.
|
28
|
+
|
29
|
+
This class encapsulates the results of a federated learning strategy execution,
|
30
|
+
including the final global model parameters and metrics collected throughout
|
31
|
+
the federated training and evaluation (both federated and centralized) stages.
|
32
|
+
|
33
|
+
Attributes
|
34
|
+
----------
|
35
|
+
arrays : ArrayRecord
|
36
|
+
The final global model parameters. Contains the
|
37
|
+
aggregated model weights/parameters that resulted from the federated
|
38
|
+
learning process.
|
39
|
+
train_metrics_clientapp : dict[int, MetricRecord]
|
40
|
+
Training metrics collected from ClientApps, indexed by round number.
|
41
|
+
Contains aggregated metrics (e.g., loss, accuracy) from the training
|
42
|
+
phase of each federated learning round.
|
43
|
+
evaluate_metrics_clientapp : dict[int, MetricRecord]
|
44
|
+
Evaluation metrics collected from ClientApps, indexed by round number.
|
45
|
+
Contains aggregated metrics (e.g. validation loss) from the evaluation
|
46
|
+
phase where ClientApps evaluate the global model on their local
|
47
|
+
validation/test data.
|
48
|
+
evaluate_metrics_serverapp : dict[int, MetricRecord]
|
49
|
+
Evaluation metrics generated at the ServerApp, indexed by round number.
|
50
|
+
Contains metrics from centralized evaluation performed by the ServerApp
|
51
|
+
(e.g., when the server evaluates the global model on a held-out dataset).
|
52
|
+
"""
|
26
53
|
|
27
54
|
arrays: ArrayRecord = field(default_factory=ArrayRecord)
|
28
55
|
train_metrics_clientapp: dict[int, MetricRecord] = field(default_factory=dict)
|
29
56
|
evaluate_metrics_clientapp: dict[int, MetricRecord] = field(default_factory=dict)
|
30
57
|
evaluate_metrics_serverapp: dict[int, MetricRecord] = field(default_factory=dict)
|
58
|
+
|
59
|
+
def __repr__(self) -> str:
|
60
|
+
"""Create a representation of the Result instance."""
|
61
|
+
rep = ""
|
62
|
+
arr_size = sum(len(array.data) for array in self.arrays.values()) / (1024**2)
|
63
|
+
rep += "Global Arrays:\n" + f"\tArrayRecord ({arr_size:.3f} MB)\n" + "\n"
|
64
|
+
rep += (
|
65
|
+
"Aggregated ClientApp-side Train Metrics:\n"
|
66
|
+
+ pprint.pformat(stringify_dict(self.train_metrics_clientapp), indent=2)
|
67
|
+
+ "\n\n"
|
68
|
+
)
|
69
|
+
|
70
|
+
rep += (
|
71
|
+
"Aggregated ClientApp-side Evaluate Metrics:\n"
|
72
|
+
+ pprint.pformat(stringify_dict(self.evaluate_metrics_clientapp), indent=2)
|
73
|
+
+ "\n\n"
|
74
|
+
)
|
75
|
+
|
76
|
+
rep += (
|
77
|
+
"ServerApp-side Evaluate Metrics:\n"
|
78
|
+
+ pprint.pformat(stringify_dict(self.evaluate_metrics_serverapp), indent=2)
|
79
|
+
+ "\n"
|
80
|
+
)
|
81
|
+
|
82
|
+
return rep
|
83
|
+
|
84
|
+
|
85
|
+
def format_value(val: MetricRecordValues) -> str:
|
86
|
+
"""Format a value as string, applying scientific notation for floats."""
|
87
|
+
if isinstance(val, float):
|
88
|
+
return f"{val:.4e}"
|
89
|
+
if isinstance(val, int):
|
90
|
+
return str(val)
|
91
|
+
if isinstance(val, list):
|
92
|
+
return str([f"{x:.4e}" if isinstance(x, float) else str(x) for x in val])
|
93
|
+
return str(val)
|
94
|
+
|
95
|
+
|
96
|
+
def stringify_dict(d: dict[int, MetricRecord]) -> dict[int, dict[str, str]]:
|
97
|
+
"""Return a copy results metrics but with values converted to string and formatted
|
98
|
+
accordingtly."""
|
99
|
+
new_metrics_dict = {}
|
100
|
+
for k, inner in d.items():
|
101
|
+
new_inner = {}
|
102
|
+
for ik, iv in inner.items():
|
103
|
+
new_inner[ik] = format_value(iv)
|
104
|
+
new_metrics_dict[k] = new_inner
|
105
|
+
return new_metrics_dict
|
@@ -15,6 +15,7 @@
|
|
15
15
|
"""Flower message-based strategy."""
|
16
16
|
|
17
17
|
|
18
|
+
import io
|
18
19
|
import time
|
19
20
|
from abc import ABC, abstractmethod
|
20
21
|
from collections.abc import Iterable
|
@@ -22,11 +23,10 @@ from logging import INFO
|
|
22
23
|
from typing import Callable, Optional
|
23
24
|
|
24
25
|
from flwr.common import ArrayRecord, ConfigRecord, Message, MetricRecord, log
|
25
|
-
from flwr.common.exit import ExitCode, flwr_exit
|
26
26
|
from flwr.server import Grid
|
27
27
|
|
28
28
|
from .result import Result
|
29
|
-
from .strategy_utils import
|
29
|
+
from .strategy_utils import log_strategy_start_info
|
30
30
|
|
31
31
|
|
32
32
|
class Strategy(ABC):
|
@@ -202,7 +202,7 @@ class Strategy(ABC):
|
|
202
202
|
log(INFO, "[ROUND %s/%s]", current_round, num_rounds)
|
203
203
|
|
204
204
|
# -----------------------------------------------------------------
|
205
|
-
# --- TRAINING
|
205
|
+
# --- TRAINING (CLIENTAPP-SIDE) -----------------------------------
|
206
206
|
# -----------------------------------------------------------------
|
207
207
|
|
208
208
|
# Call strategy to configure training round
|
@@ -218,15 +218,10 @@ class Strategy(ABC):
|
|
218
218
|
)
|
219
219
|
|
220
220
|
# Aggregate train
|
221
|
-
|
222
|
-
|
223
|
-
|
224
|
-
|
225
|
-
)
|
226
|
-
except InconsistentMessageReplies as e:
|
227
|
-
flwr_exit(
|
228
|
-
ExitCode.SERVERAPP_STRATEGY_PRECONDITION_UNMET, message=str(e)
|
229
|
-
)
|
221
|
+
agg_arrays, agg_train_metrics = self.aggregate_train(
|
222
|
+
current_round,
|
223
|
+
train_replies,
|
224
|
+
)
|
230
225
|
|
231
226
|
# Log training metrics and append to history
|
232
227
|
if agg_arrays is not None:
|
@@ -237,7 +232,7 @@ class Strategy(ABC):
|
|
237
232
|
result.train_metrics_clientapp[current_round] = agg_train_metrics
|
238
233
|
|
239
234
|
# -----------------------------------------------------------------
|
240
|
-
# --- EVALUATION (
|
235
|
+
# --- EVALUATION (CLIENTAPP-SIDE) ---------------------------------
|
241
236
|
# -----------------------------------------------------------------
|
242
237
|
|
243
238
|
# Call strategy to configure evaluation round
|
@@ -253,15 +248,10 @@ class Strategy(ABC):
|
|
253
248
|
)
|
254
249
|
|
255
250
|
# Aggregate evaluate
|
256
|
-
|
257
|
-
|
258
|
-
|
259
|
-
|
260
|
-
)
|
261
|
-
except InconsistentMessageReplies as e:
|
262
|
-
flwr_exit(
|
263
|
-
ExitCode.SERVERAPP_STRATEGY_PRECONDITION_UNMET, message=str(e)
|
264
|
-
)
|
251
|
+
agg_evaluate_metrics = self.aggregate_evaluate(
|
252
|
+
current_round,
|
253
|
+
evaluate_replies,
|
254
|
+
)
|
265
255
|
|
266
256
|
# Log training metrics and append to history
|
267
257
|
if agg_evaluate_metrics is not None:
|
@@ -269,7 +259,7 @@ class Strategy(ABC):
|
|
269
259
|
result.evaluate_metrics_clientapp[current_round] = agg_evaluate_metrics
|
270
260
|
|
271
261
|
# -----------------------------------------------------------------
|
272
|
-
# --- EVALUATION (
|
262
|
+
# --- EVALUATION (SERVERAPP-SIDE) ---------------------------------
|
273
263
|
# -----------------------------------------------------------------
|
274
264
|
|
275
265
|
# Centralized evaluation
|
@@ -282,5 +272,10 @@ class Strategy(ABC):
|
|
282
272
|
log(INFO, "")
|
283
273
|
log(INFO, "Strategy execution finished in %.2fs", time.time() - t_start)
|
284
274
|
log(INFO, "")
|
275
|
+
log(INFO, "Final results:")
|
276
|
+
log(INFO, "")
|
277
|
+
for line in io.StringIO(str(result)):
|
278
|
+
log(INFO, "\t%s", line.strip("\n"))
|
279
|
+
log(INFO, "")
|
285
280
|
|
286
281
|
return result
|
@@ -30,13 +30,26 @@ from flwr.common import (
|
|
30
30
|
RecordDict,
|
31
31
|
log,
|
32
32
|
)
|
33
|
+
from flwr.common.exception import AppExitException
|
34
|
+
from flwr.common.exit import ExitCode
|
33
35
|
from flwr.server import Grid
|
34
36
|
|
35
37
|
|
36
|
-
class InconsistentMessageReplies(
|
38
|
+
class InconsistentMessageReplies(AppExitException):
|
37
39
|
"""Exception triggered when replies are inconsistent and therefore aggregation must
|
38
40
|
be skipped."""
|
39
41
|
|
42
|
+
exit_code = ExitCode.SERVERAPP_STRATEGY_PRECONDITION_UNMET
|
43
|
+
|
44
|
+
def __init__(self, reason: str):
|
45
|
+
super().__init__(reason)
|
46
|
+
|
47
|
+
|
48
|
+
class AggregationError(AppExitException):
|
49
|
+
"""Exception triggered when aggregation fails."""
|
50
|
+
|
51
|
+
exit_code = ExitCode.SERVERAPP_STRATEGY_AGGREGATION_ERROR
|
52
|
+
|
40
53
|
def __init__(self, reason: str):
|
41
54
|
super().__init__(reason)
|
42
55
|
|
{flwr_nightly-1.21.0.dev20250902.dist-info → flwr_nightly-1.21.0.dev20250904.dist-info}/METADATA
RENAMED
@@ -1,6 +1,6 @@
|
|
1
1
|
Metadata-Version: 2.3
|
2
2
|
Name: flwr-nightly
|
3
|
-
Version: 1.21.0.
|
3
|
+
Version: 1.21.0.dev20250904
|
4
4
|
Summary: Flower: A Friendly Federated AI Framework
|
5
5
|
License: Apache-2.0
|
6
6
|
Keywords: Artificial Intelligence,Federated AI,Federated Analytics,Federated Evaluation,Federated Learning,Flower,Machine Learning
|