flwr-nightly 1.22.0.dev20250917__py3-none-any.whl → 1.22.0.dev20250919__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/new/new.py +2 -0
- flwr/cli/new/templates/app/code/client.xgboost.py.tpl +110 -0
- flwr/cli/new/templates/app/code/server.xgboost.py.tpl +56 -0
- flwr/cli/new/templates/app/code/task.xgboost.py.tpl +67 -0
- flwr/cli/new/templates/app/pyproject.xgboost.toml.tpl +61 -0
- flwr/clientapp/mod/__init__.py +2 -1
- flwr/clientapp/mod/centraldp_mods.py +155 -39
- flwr/clientapp/typing.py +22 -0
- flwr/common/constant.py +1 -0
- flwr/common/exit/exit_code.py +4 -0
- flwr/common/record/typeddict.py +12 -0
- flwr/serverapp/strategy/__init__.py +12 -0
- flwr/serverapp/strategy/dp_adaptive_clipping.py +335 -0
- flwr/serverapp/strategy/dp_fixed_clipping.py +71 -49
- flwr/serverapp/strategy/fedadagrad.py +0 -3
- flwr/serverapp/strategy/fedadam.py +0 -3
- flwr/serverapp/strategy/fedavgm.py +3 -3
- flwr/serverapp/strategy/fedprox.py +1 -1
- flwr/serverapp/strategy/fedtrimmedavg.py +1 -1
- flwr/serverapp/strategy/fedxgb_cyclic.py +220 -0
- flwr/serverapp/strategy/fedyogi.py +0 -3
- flwr/serverapp/strategy/krum.py +230 -0
- flwr/serverapp/strategy/qfedavg.py +252 -0
- flwr/supercore/cli/flower_superexec.py +26 -1
- flwr/supercore/constant.py +19 -0
- flwr/supercore/superexec/plugin/exec_plugin.py +11 -1
- flwr/supercore/superexec/run_superexec.py +16 -2
- {flwr_nightly-1.22.0.dev20250917.dist-info → flwr_nightly-1.22.0.dev20250919.dist-info}/METADATA +1 -1
- {flwr_nightly-1.22.0.dev20250917.dist-info → flwr_nightly-1.22.0.dev20250919.dist-info}/RECORD +31 -23
- flwr/serverapp/dp_fixed_clipping.py +0 -352
- flwr/serverapp/strategy/strategy_utils_tests.py +0 -323
- {flwr_nightly-1.22.0.dev20250917.dist-info → flwr_nightly-1.22.0.dev20250919.dist-info}/WHEEL +0 -0
- {flwr_nightly-1.22.0.dev20250917.dist-info → flwr_nightly-1.22.0.dev20250919.dist-info}/entry_points.txt +0 -0
@@ -1,352 +0,0 @@
|
|
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
|
-
"""Message-based Central differential privacy with fixed clipping.
|
16
|
-
|
17
|
-
Papers: https://arxiv.org/abs/1712.07557, https://arxiv.org/abs/1710.06963
|
18
|
-
"""
|
19
|
-
|
20
|
-
from abc import ABC
|
21
|
-
from collections import OrderedDict
|
22
|
-
from collections.abc import Iterable
|
23
|
-
from logging import INFO, WARNING
|
24
|
-
from typing import Optional
|
25
|
-
|
26
|
-
from flwr.common import Array, ArrayRecord, ConfigRecord, Message, MetricRecord, log
|
27
|
-
from flwr.common.differential_privacy import (
|
28
|
-
add_gaussian_noise_inplace,
|
29
|
-
compute_clip_model_update,
|
30
|
-
compute_stdv,
|
31
|
-
)
|
32
|
-
from flwr.common.differential_privacy_constants import (
|
33
|
-
CLIENTS_DISCREPANCY_WARNING,
|
34
|
-
KEY_CLIPPING_NORM,
|
35
|
-
)
|
36
|
-
from flwr.server import Grid
|
37
|
-
|
38
|
-
from .strategy import Strategy
|
39
|
-
|
40
|
-
|
41
|
-
class DifferentialPrivacyFixedClippingBase(Strategy, ABC):
|
42
|
-
"""Base class for DP strategies with fixed clipping.
|
43
|
-
|
44
|
-
This class contains common functionality shared between server-side and
|
45
|
-
client-side fixed clipping implementations.
|
46
|
-
|
47
|
-
Parameters
|
48
|
-
----------
|
49
|
-
strategy : Strategy
|
50
|
-
The strategy to which DP functionalities will be added by this wrapper.
|
51
|
-
noise_multiplier : float
|
52
|
-
The noise multiplier for the Gaussian mechanism for model updates.
|
53
|
-
A value of 1.0 or higher is recommended for strong privacy.
|
54
|
-
clipping_norm : float
|
55
|
-
The value of the clipping norm.
|
56
|
-
num_sampled_clients : int
|
57
|
-
The number of clients that are sampled on each round.
|
58
|
-
"""
|
59
|
-
|
60
|
-
# pylint: disable=too-many-arguments,too-many-instance-attributes
|
61
|
-
def __init__(
|
62
|
-
self,
|
63
|
-
strategy: Strategy,
|
64
|
-
noise_multiplier: float,
|
65
|
-
clipping_norm: float,
|
66
|
-
num_sampled_clients: int,
|
67
|
-
) -> None:
|
68
|
-
super().__init__()
|
69
|
-
|
70
|
-
self.strategy = strategy
|
71
|
-
|
72
|
-
if noise_multiplier < 0:
|
73
|
-
raise ValueError("The noise multiplier should be a non-negative value.")
|
74
|
-
|
75
|
-
if clipping_norm <= 0:
|
76
|
-
raise ValueError("The clipping norm should be a positive value.")
|
77
|
-
|
78
|
-
if num_sampled_clients <= 0:
|
79
|
-
raise ValueError(
|
80
|
-
"The number of sampled clients should be a positive value."
|
81
|
-
)
|
82
|
-
|
83
|
-
self.noise_multiplier = noise_multiplier
|
84
|
-
self.clipping_norm = clipping_norm
|
85
|
-
self.num_sampled_clients = num_sampled_clients
|
86
|
-
|
87
|
-
def _validate_replies(self, replies: Iterable[Message]) -> bool:
|
88
|
-
"""Validate replies and log errors/warnings.
|
89
|
-
|
90
|
-
Returns
|
91
|
-
-------
|
92
|
-
bool
|
93
|
-
True if replies are valid for aggregation, False otherwise.
|
94
|
-
"""
|
95
|
-
num_errors = 0
|
96
|
-
num_replies_with_content = 0
|
97
|
-
for msg in replies:
|
98
|
-
if msg.has_error():
|
99
|
-
log(
|
100
|
-
INFO,
|
101
|
-
"Received error in reply from node %d: %s",
|
102
|
-
msg.metadata.src_node_id,
|
103
|
-
msg.error,
|
104
|
-
)
|
105
|
-
num_errors += 1
|
106
|
-
else:
|
107
|
-
num_replies_with_content += 1
|
108
|
-
|
109
|
-
# Errors are not allowed
|
110
|
-
if num_errors:
|
111
|
-
log(
|
112
|
-
INFO,
|
113
|
-
"aggregate_train: Some clients reported errors. Skipping aggregation.",
|
114
|
-
)
|
115
|
-
return False
|
116
|
-
|
117
|
-
log(
|
118
|
-
INFO,
|
119
|
-
"aggregate_train: Received %s results and %s failures",
|
120
|
-
num_replies_with_content,
|
121
|
-
num_errors,
|
122
|
-
)
|
123
|
-
|
124
|
-
if num_replies_with_content != self.num_sampled_clients:
|
125
|
-
log(
|
126
|
-
WARNING,
|
127
|
-
CLIENTS_DISCREPANCY_WARNING,
|
128
|
-
num_replies_with_content,
|
129
|
-
self.num_sampled_clients,
|
130
|
-
)
|
131
|
-
|
132
|
-
return True
|
133
|
-
|
134
|
-
def _add_noise_to_aggregated_arrays(
|
135
|
-
self, aggregated_arrays: ArrayRecord
|
136
|
-
) -> ArrayRecord:
|
137
|
-
"""Add Gaussian noise to aggregated arrays.
|
138
|
-
|
139
|
-
Parameters
|
140
|
-
----------
|
141
|
-
aggregated_arrays : ArrayRecord
|
142
|
-
The aggregated arrays to add noise to.
|
143
|
-
|
144
|
-
Returns
|
145
|
-
-------
|
146
|
-
ArrayRecord
|
147
|
-
The aggregated arrays with noise added.
|
148
|
-
"""
|
149
|
-
aggregated_ndarrays = aggregated_arrays.to_numpy_ndarrays()
|
150
|
-
stdv = compute_stdv(
|
151
|
-
self.noise_multiplier, self.clipping_norm, self.num_sampled_clients
|
152
|
-
)
|
153
|
-
add_gaussian_noise_inplace(aggregated_ndarrays, stdv)
|
154
|
-
|
155
|
-
log(
|
156
|
-
INFO,
|
157
|
-
"aggregate_fit: central DP noise with %.4f stdev added",
|
158
|
-
stdv,
|
159
|
-
)
|
160
|
-
|
161
|
-
return ArrayRecord(
|
162
|
-
OrderedDict(
|
163
|
-
{
|
164
|
-
k: Array(v)
|
165
|
-
for k, v in zip(aggregated_arrays.keys(), aggregated_ndarrays)
|
166
|
-
}
|
167
|
-
)
|
168
|
-
)
|
169
|
-
|
170
|
-
def configure_evaluate(
|
171
|
-
self, server_round: int, arrays: ArrayRecord, config: ConfigRecord, grid: Grid
|
172
|
-
) -> Iterable[Message]:
|
173
|
-
"""Configure the next round of federated evaluation."""
|
174
|
-
return self.strategy.configure_evaluate(server_round, arrays, config, grid)
|
175
|
-
|
176
|
-
def aggregate_evaluate(
|
177
|
-
self,
|
178
|
-
server_round: int,
|
179
|
-
replies: Iterable[Message],
|
180
|
-
) -> Optional[MetricRecord]:
|
181
|
-
"""Aggregate MetricRecords in the received Messages."""
|
182
|
-
return self.strategy.aggregate_evaluate(server_round, replies)
|
183
|
-
|
184
|
-
def summary(self) -> None:
|
185
|
-
"""Log summary configuration of the strategy."""
|
186
|
-
self.strategy.summary()
|
187
|
-
|
188
|
-
|
189
|
-
class DifferentialPrivacyServerSideFixedClipping(DifferentialPrivacyFixedClippingBase):
|
190
|
-
"""Strategy wrapper for central DP with server-side fixed clipping.
|
191
|
-
|
192
|
-
Parameters
|
193
|
-
----------
|
194
|
-
strategy : Strategy
|
195
|
-
The strategy to which DP functionalities will be added by this wrapper.
|
196
|
-
noise_multiplier : float
|
197
|
-
The noise multiplier for the Gaussian mechanism for model updates.
|
198
|
-
A value of 1.0 or higher is recommended for strong privacy.
|
199
|
-
clipping_norm : float
|
200
|
-
The value of the clipping norm.
|
201
|
-
num_sampled_clients : int
|
202
|
-
The number of clients that are sampled on each round.
|
203
|
-
|
204
|
-
Examples
|
205
|
-
--------
|
206
|
-
Create a strategy::
|
207
|
-
|
208
|
-
strategy = fl.serverapp.FedAvg( ... )
|
209
|
-
|
210
|
-
Wrap the strategy with the `DifferentialPrivacyServerSideFixedClipping` wrapper::
|
211
|
-
|
212
|
-
dp_strategy = DifferentialPrivacyServerSideFixedClipping(
|
213
|
-
strategy, cfg.noise_multiplier, cfg.clipping_norm, cfg.num_sampled_clients
|
214
|
-
)
|
215
|
-
"""
|
216
|
-
|
217
|
-
def __init__(
|
218
|
-
self,
|
219
|
-
strategy: Strategy,
|
220
|
-
noise_multiplier: float,
|
221
|
-
clipping_norm: float,
|
222
|
-
num_sampled_clients: int,
|
223
|
-
) -> None:
|
224
|
-
super().__init__(strategy, noise_multiplier, clipping_norm, num_sampled_clients)
|
225
|
-
self.current_arrays: ArrayRecord = ArrayRecord()
|
226
|
-
|
227
|
-
def __repr__(self) -> str:
|
228
|
-
"""Compute a string representation of the strategy."""
|
229
|
-
return "Differential Privacy Strategy Wrapper (Server-Side Fixed Clipping)"
|
230
|
-
|
231
|
-
def configure_train(
|
232
|
-
self, server_round: int, arrays: ArrayRecord, config: ConfigRecord, grid: Grid
|
233
|
-
) -> Iterable[Message]:
|
234
|
-
"""Configure the next round of training."""
|
235
|
-
self.current_arrays = arrays
|
236
|
-
return self.strategy.configure_train(server_round, arrays, config, grid)
|
237
|
-
|
238
|
-
def aggregate_train(
|
239
|
-
self,
|
240
|
-
server_round: int,
|
241
|
-
replies: Iterable[Message],
|
242
|
-
) -> tuple[Optional[ArrayRecord], Optional[MetricRecord]]:
|
243
|
-
"""Aggregate ArrayRecords and MetricRecords in the received Messages."""
|
244
|
-
if not self._validate_replies(replies):
|
245
|
-
return None, None
|
246
|
-
|
247
|
-
# Clip arrays in replies
|
248
|
-
current_ndarrays = self.current_arrays.to_numpy_ndarrays()
|
249
|
-
for reply in replies:
|
250
|
-
for arr_name, record in reply.content.array_records.items():
|
251
|
-
# Clip
|
252
|
-
reply_ndarrays = record.to_numpy_ndarrays()
|
253
|
-
compute_clip_model_update(
|
254
|
-
param1=reply_ndarrays,
|
255
|
-
param2=current_ndarrays,
|
256
|
-
clipping_norm=self.clipping_norm,
|
257
|
-
)
|
258
|
-
# Replace content while preserving keys
|
259
|
-
reply.content[arr_name] = ArrayRecord(
|
260
|
-
OrderedDict(
|
261
|
-
{k: Array(v) for k, v in zip(record.keys(), reply_ndarrays)}
|
262
|
-
)
|
263
|
-
)
|
264
|
-
log(
|
265
|
-
INFO,
|
266
|
-
"aggregate_fit: parameters are clipped by value: %.4f.",
|
267
|
-
self.clipping_norm,
|
268
|
-
)
|
269
|
-
|
270
|
-
# Pass the new parameters for aggregation
|
271
|
-
aggregated_arrays, aggregated_metrics = self.strategy.aggregate_train(
|
272
|
-
server_round, replies
|
273
|
-
)
|
274
|
-
|
275
|
-
# Add Gaussian noise to the aggregated arrays
|
276
|
-
if aggregated_arrays:
|
277
|
-
aggregated_arrays = self._add_noise_to_aggregated_arrays(aggregated_arrays)
|
278
|
-
|
279
|
-
return aggregated_arrays, aggregated_metrics
|
280
|
-
|
281
|
-
|
282
|
-
class DifferentialPrivacyClientSideFixedClipping(DifferentialPrivacyFixedClippingBase):
|
283
|
-
"""Strategy wrapper for central DP with client-side fixed clipping.
|
284
|
-
|
285
|
-
Use `fixedclipping_mod` modifier at the client side.
|
286
|
-
|
287
|
-
In comparison to `DifferentialPrivacyServerSideFixedClipping`,
|
288
|
-
which performs clipping on the server-side,
|
289
|
-
`DifferentialPrivacyClientSideFixedClipping` expects clipping to happen
|
290
|
-
on the client-side, usually by using the built-in `fixedclipping_mod`.
|
291
|
-
|
292
|
-
Parameters
|
293
|
-
----------
|
294
|
-
strategy : Strategy
|
295
|
-
The strategy to which DP functionalities will be added by this wrapper.
|
296
|
-
noise_multiplier : float
|
297
|
-
The noise multiplier for the Gaussian mechanism for model updates.
|
298
|
-
A value of 1.0 or higher is recommended for strong privacy.
|
299
|
-
clipping_norm : float
|
300
|
-
The value of the clipping norm.
|
301
|
-
num_sampled_clients : int
|
302
|
-
The number of clients that are sampled on each round.
|
303
|
-
|
304
|
-
Examples
|
305
|
-
--------
|
306
|
-
Create a strategy::
|
307
|
-
|
308
|
-
strategy = fl.serverapp.FedAvg(...)
|
309
|
-
|
310
|
-
Wrap the strategy with the `DifferentialPrivacyClientSideFixedClipping` wrapper::
|
311
|
-
|
312
|
-
dp_strategy = DifferentialPrivacyClientSideFixedClipping(
|
313
|
-
strategy, cfg.noise_multiplier, cfg.clipping_norm, cfg.num_sampled_clients
|
314
|
-
)
|
315
|
-
|
316
|
-
On the client, add the `fixedclipping_mod` to the client-side mods::
|
317
|
-
|
318
|
-
app = fl.client.ClientApp(mods=[fixedclipping_mod])
|
319
|
-
"""
|
320
|
-
|
321
|
-
def __repr__(self) -> str:
|
322
|
-
"""Compute a string representation of the strategy."""
|
323
|
-
return "Differential Privacy Strategy Wrapper (Client-Side Fixed Clipping)"
|
324
|
-
|
325
|
-
def configure_train(
|
326
|
-
self, server_round: int, arrays: ArrayRecord, config: ConfigRecord, grid: Grid
|
327
|
-
) -> Iterable[Message]:
|
328
|
-
"""Configure the next round of training."""
|
329
|
-
# Inject clipping norm in config
|
330
|
-
config[KEY_CLIPPING_NORM] = self.clipping_norm
|
331
|
-
# Call parent method
|
332
|
-
return self.strategy.configure_train(server_round, arrays, config, grid)
|
333
|
-
|
334
|
-
def aggregate_train(
|
335
|
-
self,
|
336
|
-
server_round: int,
|
337
|
-
replies: Iterable[Message],
|
338
|
-
) -> tuple[Optional[ArrayRecord], Optional[MetricRecord]]:
|
339
|
-
"""Aggregate ArrayRecords and MetricRecords in the received Messages."""
|
340
|
-
if not self._validate_replies(replies):
|
341
|
-
return None, None
|
342
|
-
|
343
|
-
# Aggregate
|
344
|
-
aggregated_arrays, aggregated_metrics = self.strategy.aggregate_train(
|
345
|
-
server_round, replies
|
346
|
-
)
|
347
|
-
|
348
|
-
# Add Gaussian noise to the aggregated arrays
|
349
|
-
if aggregated_arrays:
|
350
|
-
aggregated_arrays = self._add_noise_to_aggregated_arrays(aggregated_arrays)
|
351
|
-
|
352
|
-
return aggregated_arrays, aggregated_metrics
|
@@ -1,323 +0,0 @@
|
|
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
|
-
"""Tests for message-based strategy utilities."""
|
16
|
-
|
17
|
-
|
18
|
-
from collections import OrderedDict
|
19
|
-
from unittest.mock import Mock
|
20
|
-
|
21
|
-
import numpy as np
|
22
|
-
import pytest
|
23
|
-
from parameterized import parameterized
|
24
|
-
|
25
|
-
from flwr.common import (
|
26
|
-
Array,
|
27
|
-
ArrayRecord,
|
28
|
-
ConfigRecord,
|
29
|
-
Message,
|
30
|
-
MetricRecord,
|
31
|
-
RecordDict,
|
32
|
-
)
|
33
|
-
from flwr.serverapp.exception import InconsistentMessageReplies
|
34
|
-
|
35
|
-
from .strategy_utils import (
|
36
|
-
aggregate_arrayrecords,
|
37
|
-
aggregate_metricrecords,
|
38
|
-
config_to_str,
|
39
|
-
validate_message_reply_consistency,
|
40
|
-
)
|
41
|
-
|
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
|
-
|
54
|
-
def test_config_to_str() -> None:
|
55
|
-
"""Test that items of types bytes are masked out."""
|
56
|
-
config = ConfigRecord({"a": 123, "b": [1, 2, 3], "c": b"bytes"})
|
57
|
-
expected_str = "{'a': 123, 'b': [1, 2, 3], 'c': <bytes>}"
|
58
|
-
assert config_to_str(config) == expected_str
|
59
|
-
|
60
|
-
|
61
|
-
def test_arrayrecords_aggregation() -> None:
|
62
|
-
"""Test aggregation of ArrayRecords."""
|
63
|
-
num_replies = 3
|
64
|
-
num_arrays = 4
|
65
|
-
weights = [0.25, 0.4, 0.35]
|
66
|
-
np_arrays = [
|
67
|
-
[np.random.randn(7, 3) for _ in range(num_arrays)] for _ in range(num_replies)
|
68
|
-
]
|
69
|
-
|
70
|
-
avg_list = [
|
71
|
-
np.average([lst[i] for lst in np_arrays], axis=0, weights=weights)
|
72
|
-
for i in range(num_arrays)
|
73
|
-
]
|
74
|
-
|
75
|
-
# Construct RecordDicts (mimicing replies)
|
76
|
-
records = [
|
77
|
-
RecordDict(
|
78
|
-
{
|
79
|
-
"arrays": ArrayRecord(np_arrays[i]),
|
80
|
-
"metrics": MetricRecord({"weight": weights[i]}),
|
81
|
-
}
|
82
|
-
)
|
83
|
-
for i in range(num_replies)
|
84
|
-
]
|
85
|
-
# Execute aggregate
|
86
|
-
aggrd = aggregate_arrayrecords(records, weighting_metric_name="weight")
|
87
|
-
|
88
|
-
# Assert consistency
|
89
|
-
assert all(np.allclose(a, b) for a, b in zip(aggrd.to_numpy_ndarrays(), avg_list))
|
90
|
-
assert aggrd.object_id == ArrayRecord(avg_list).object_id
|
91
|
-
|
92
|
-
|
93
|
-
def test_arrayrecords_aggregation_with_ndim_zero() -> None:
|
94
|
-
"""Test aggregation of ArrayRecords with 0-dim arrays."""
|
95
|
-
num_replies = 3
|
96
|
-
weights = [0.25, 0.4, 0.35]
|
97
|
-
np_arrays = [np.array(np.random.randn()) for _ in range(num_replies)]
|
98
|
-
|
99
|
-
# For 0-dimensional arrays, we just compute the weighted average directly
|
100
|
-
avg_list = [np.average(np_arrays, axis=0, weights=weights)]
|
101
|
-
|
102
|
-
# Construct RecordDicts (mimicing replies)
|
103
|
-
records = [
|
104
|
-
RecordDict(
|
105
|
-
{
|
106
|
-
"arrays": ArrayRecord([np_arrays[i]]),
|
107
|
-
"metrics": MetricRecord({"weight": weights[i]}),
|
108
|
-
}
|
109
|
-
)
|
110
|
-
for i in range(num_replies)
|
111
|
-
]
|
112
|
-
# Execute aggregate
|
113
|
-
aggrd = aggregate_arrayrecords(records, weighting_metric_name="weight")
|
114
|
-
|
115
|
-
# Assert consistency
|
116
|
-
assert np.isclose(aggrd.to_numpy_ndarrays()[0], avg_list[0])
|
117
|
-
assert aggrd.object_id == ArrayRecord([np.array(avg_list[0])]).object_id
|
118
|
-
|
119
|
-
|
120
|
-
def test_metricrecords_aggregation() -> None:
|
121
|
-
"""Test aggregation of MetricRecords."""
|
122
|
-
num_replies = 3
|
123
|
-
weights = [0.25, 0.4, 0.35]
|
124
|
-
metric_records = [
|
125
|
-
MetricRecord({"a": 1, "b": 2.0, "c": np.random.randn(3).tolist()})
|
126
|
-
for _ in range(num_replies)
|
127
|
-
]
|
128
|
-
|
129
|
-
# Compute expected aggregated MetricRecord.
|
130
|
-
# For ease, we convert everything into numpy arrays, then aggregate
|
131
|
-
as_np_entries = [
|
132
|
-
{
|
133
|
-
k: np.array(v) if isinstance(v, (int, float, list)) else v
|
134
|
-
for k, v in record.items()
|
135
|
-
}
|
136
|
-
for record in metric_records
|
137
|
-
]
|
138
|
-
avg_list = [
|
139
|
-
np.average(
|
140
|
-
[list(entries.values())[i] for entries in as_np_entries],
|
141
|
-
axis=0,
|
142
|
-
weights=weights,
|
143
|
-
).tolist()
|
144
|
-
for i in range(len(as_np_entries[0]))
|
145
|
-
]
|
146
|
-
expected_record = MetricRecord(dict(zip(as_np_entries[0].keys(), avg_list)))
|
147
|
-
expected_record["a"] = float(expected_record["a"]) # type: ignore
|
148
|
-
expected_record["b"] = float(expected_record["b"]) # type: ignore
|
149
|
-
|
150
|
-
# Construct RecordDicts (mimicing replies)
|
151
|
-
# Inject weighting factor
|
152
|
-
records = [
|
153
|
-
RecordDict(
|
154
|
-
{
|
155
|
-
"metrics": MetricRecord(
|
156
|
-
record.__dict__["_data"] | {"weight": weights[i]}
|
157
|
-
),
|
158
|
-
}
|
159
|
-
)
|
160
|
-
for i, record in enumerate(metric_records)
|
161
|
-
]
|
162
|
-
|
163
|
-
# Execute aggregate
|
164
|
-
aggrd = aggregate_metricrecords(records, weighting_metric_name="weight")
|
165
|
-
# Assert
|
166
|
-
assert expected_record.object_id == aggrd.object_id
|
167
|
-
|
168
|
-
|
169
|
-
@parameterized.expand( # type: ignore
|
170
|
-
[
|
171
|
-
(
|
172
|
-
True,
|
173
|
-
RecordDict(
|
174
|
-
{
|
175
|
-
"global-model": ArrayRecord([np.random.randn(7, 3)]),
|
176
|
-
"metrics": MetricRecord({"weight": 0.123}),
|
177
|
-
}
|
178
|
-
),
|
179
|
-
), # Compliant
|
180
|
-
(
|
181
|
-
False,
|
182
|
-
RecordDict(
|
183
|
-
{
|
184
|
-
"global-model": ArrayRecord([np.random.randn(7, 3)]),
|
185
|
-
"metrics": MetricRecord({"weight": [0.123]}),
|
186
|
-
}
|
187
|
-
),
|
188
|
-
), # Weighting key is not a scalar (BAD)
|
189
|
-
(
|
190
|
-
False,
|
191
|
-
RecordDict(
|
192
|
-
{
|
193
|
-
"global-model": ArrayRecord([np.random.randn(7, 3)]),
|
194
|
-
"metrics": MetricRecord({"loss": 0.01}),
|
195
|
-
}
|
196
|
-
),
|
197
|
-
), # No weighting key in MetricRecord (BAD)
|
198
|
-
(
|
199
|
-
False,
|
200
|
-
RecordDict({"global-model": ArrayRecord([np.random.randn(7, 3)])}),
|
201
|
-
), # No MetricsRecord (BAD)
|
202
|
-
(
|
203
|
-
False,
|
204
|
-
RecordDict(
|
205
|
-
{
|
206
|
-
"global-model": ArrayRecord([np.random.randn(7, 3)]),
|
207
|
-
"another-model": ArrayRecord([np.random.randn(7, 3)]),
|
208
|
-
}
|
209
|
-
),
|
210
|
-
), # Two ArrayRecords (BAD)
|
211
|
-
(
|
212
|
-
False,
|
213
|
-
RecordDict(
|
214
|
-
{
|
215
|
-
"global-model": ArrayRecord([np.random.randn(7, 3)]),
|
216
|
-
"metrics": MetricRecord({"weight": 0.123}),
|
217
|
-
"more-metrics": MetricRecord({"loss": 0.321}),
|
218
|
-
}
|
219
|
-
),
|
220
|
-
), # Two MetricRecords (BAD)
|
221
|
-
]
|
222
|
-
)
|
223
|
-
def test_consistency_of_replies_with_matching_keys(
|
224
|
-
is_valid: bool, recorddict: RecordDict
|
225
|
-
) -> None:
|
226
|
-
"""Test consistency in replies."""
|
227
|
-
# Create dummy records
|
228
|
-
records = [recorddict for _ in range(3)]
|
229
|
-
|
230
|
-
if not is_valid:
|
231
|
-
# Should raise InconsistentMessageReplies exception
|
232
|
-
with pytest.raises(InconsistentMessageReplies):
|
233
|
-
validate_message_reply_consistency(
|
234
|
-
records, weighted_by_key="weight", check_arrayrecord=True
|
235
|
-
)
|
236
|
-
else:
|
237
|
-
# Should not raise an exception
|
238
|
-
validate_message_reply_consistency(
|
239
|
-
records, weighted_by_key="weight", check_arrayrecord=True
|
240
|
-
)
|
241
|
-
|
242
|
-
|
243
|
-
@parameterized.expand( # type: ignore
|
244
|
-
[
|
245
|
-
(
|
246
|
-
[
|
247
|
-
RecordDict(
|
248
|
-
{
|
249
|
-
"global-model": ArrayRecord([np.random.randn(7, 3)]),
|
250
|
-
"metrics": MetricRecord({"weight": 0.123}),
|
251
|
-
}
|
252
|
-
),
|
253
|
-
RecordDict(
|
254
|
-
{
|
255
|
-
"model": ArrayRecord([np.random.randn(7, 3)]),
|
256
|
-
"metrics": MetricRecord({"weight": 0.123}),
|
257
|
-
}
|
258
|
-
),
|
259
|
-
],
|
260
|
-
), # top-level keys don't match for ArrayRecords
|
261
|
-
(
|
262
|
-
[
|
263
|
-
RecordDict(
|
264
|
-
{
|
265
|
-
"global-model": ArrayRecord(
|
266
|
-
OrderedDict({"a": Array(np.random.randn(7, 3))})
|
267
|
-
),
|
268
|
-
"metrics": MetricRecord({"weight": 0.123}),
|
269
|
-
}
|
270
|
-
),
|
271
|
-
RecordDict(
|
272
|
-
{
|
273
|
-
"global-model": ArrayRecord(
|
274
|
-
OrderedDict({"b": Array(np.random.randn(7, 3))})
|
275
|
-
),
|
276
|
-
"metrics": MetricRecord({"weight": 0.123}),
|
277
|
-
}
|
278
|
-
),
|
279
|
-
],
|
280
|
-
), # top-level keys match for ArrayRecords but not those for Arrays
|
281
|
-
(
|
282
|
-
[
|
283
|
-
RecordDict(
|
284
|
-
{
|
285
|
-
"global-model": ArrayRecord([np.random.randn(7, 3)]),
|
286
|
-
"metrics": MetricRecord({"weight": 0.123}),
|
287
|
-
}
|
288
|
-
),
|
289
|
-
RecordDict(
|
290
|
-
{
|
291
|
-
"global-model": ArrayRecord([np.random.randn(7, 3)]),
|
292
|
-
"my-metrics": MetricRecord({"weight": 0.123}),
|
293
|
-
}
|
294
|
-
),
|
295
|
-
],
|
296
|
-
), # top-level keys don't match for MetricRecords
|
297
|
-
(
|
298
|
-
[
|
299
|
-
RecordDict(
|
300
|
-
{
|
301
|
-
"global-model": ArrayRecord([np.random.randn(7, 3)]),
|
302
|
-
"metrics": MetricRecord({"weight": 0.123}),
|
303
|
-
}
|
304
|
-
),
|
305
|
-
RecordDict(
|
306
|
-
{
|
307
|
-
"global-model": ArrayRecord([np.random.randn(7, 3)]),
|
308
|
-
"my-metrics": MetricRecord({"my-weights": 0.123}),
|
309
|
-
}
|
310
|
-
),
|
311
|
-
],
|
312
|
-
), # top-level keys match for MetricRecords but not inner ones
|
313
|
-
]
|
314
|
-
)
|
315
|
-
def test_consistency_of_replies_with_different_keys(
|
316
|
-
list_records: list[RecordDict],
|
317
|
-
) -> None:
|
318
|
-
"""Test consistency in replies when records don't have matching keys."""
|
319
|
-
# All test cases expect InconsistentMessageReplies exception to be raised
|
320
|
-
with pytest.raises(InconsistentMessageReplies):
|
321
|
-
validate_message_reply_consistency(
|
322
|
-
list_records, weighted_by_key="weight", check_arrayrecord=True
|
323
|
-
)
|
{flwr_nightly-1.22.0.dev20250917.dist-info → flwr_nightly-1.22.0.dev20250919.dist-info}/WHEEL
RENAMED
File without changes
|
File without changes
|