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.
Files changed (33) hide show
  1. flwr/cli/new/new.py +2 -0
  2. flwr/cli/new/templates/app/code/client.xgboost.py.tpl +110 -0
  3. flwr/cli/new/templates/app/code/server.xgboost.py.tpl +56 -0
  4. flwr/cli/new/templates/app/code/task.xgboost.py.tpl +67 -0
  5. flwr/cli/new/templates/app/pyproject.xgboost.toml.tpl +61 -0
  6. flwr/clientapp/mod/__init__.py +2 -1
  7. flwr/clientapp/mod/centraldp_mods.py +155 -39
  8. flwr/clientapp/typing.py +22 -0
  9. flwr/common/constant.py +1 -0
  10. flwr/common/exit/exit_code.py +4 -0
  11. flwr/common/record/typeddict.py +12 -0
  12. flwr/serverapp/strategy/__init__.py +12 -0
  13. flwr/serverapp/strategy/dp_adaptive_clipping.py +335 -0
  14. flwr/serverapp/strategy/dp_fixed_clipping.py +71 -49
  15. flwr/serverapp/strategy/fedadagrad.py +0 -3
  16. flwr/serverapp/strategy/fedadam.py +0 -3
  17. flwr/serverapp/strategy/fedavgm.py +3 -3
  18. flwr/serverapp/strategy/fedprox.py +1 -1
  19. flwr/serverapp/strategy/fedtrimmedavg.py +1 -1
  20. flwr/serverapp/strategy/fedxgb_cyclic.py +220 -0
  21. flwr/serverapp/strategy/fedyogi.py +0 -3
  22. flwr/serverapp/strategy/krum.py +230 -0
  23. flwr/serverapp/strategy/qfedavg.py +252 -0
  24. flwr/supercore/cli/flower_superexec.py +26 -1
  25. flwr/supercore/constant.py +19 -0
  26. flwr/supercore/superexec/plugin/exec_plugin.py +11 -1
  27. flwr/supercore/superexec/run_superexec.py +16 -2
  28. {flwr_nightly-1.22.0.dev20250917.dist-info → flwr_nightly-1.22.0.dev20250919.dist-info}/METADATA +1 -1
  29. {flwr_nightly-1.22.0.dev20250917.dist-info → flwr_nightly-1.22.0.dev20250919.dist-info}/RECORD +31 -23
  30. flwr/serverapp/dp_fixed_clipping.py +0 -352
  31. flwr/serverapp/strategy/strategy_utils_tests.py +0 -323
  32. {flwr_nightly-1.22.0.dev20250917.dist-info → flwr_nightly-1.22.0.dev20250919.dist-info}/WHEEL +0 -0
  33. {flwr_nightly-1.22.0.dev20250917.dist-info → flwr_nightly-1.22.0.dev20250919.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,220 @@
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
+ """Flower message-based FedXgbCyclic strategy."""
16
+
17
+
18
+ from collections.abc import Iterable
19
+ from logging import INFO
20
+ from typing import Callable, Optional, cast
21
+
22
+ from flwr.common import (
23
+ ArrayRecord,
24
+ ConfigRecord,
25
+ Message,
26
+ MessageType,
27
+ MetricRecord,
28
+ RecordDict,
29
+ log,
30
+ )
31
+ from flwr.server import Grid
32
+
33
+ from .fedavg import FedAvg
34
+ from .strategy_utils import sample_nodes
35
+
36
+
37
+ # pylint: disable=line-too-long
38
+ class FedXgbCyclic(FedAvg):
39
+ """Configurable FedXgbCyclic strategy implementation.
40
+
41
+ Parameters
42
+ ----------
43
+ fraction_train : float (default: 1.0)
44
+ Fraction of nodes used during training. In case `min_train_nodes`
45
+ is larger than `fraction_train * total_connected_nodes`, `min_train_nodes`
46
+ will still be sampled.
47
+ fraction_evaluate : float (default: 1.0)
48
+ Fraction of nodes used during validation. In case `min_evaluate_nodes`
49
+ is larger than `fraction_evaluate * total_connected_nodes`,
50
+ `min_evaluate_nodes` will still be sampled.
51
+ min_available_nodes : int (default: 2)
52
+ Minimum number of total nodes in the system.
53
+ weighted_by_key : str (default: "num-examples")
54
+ The key within each MetricRecord whose value is used as the weight when
55
+ computing weighted averages for both ArrayRecords and MetricRecords.
56
+ arrayrecord_key : str (default: "arrays")
57
+ Key used to store the ArrayRecord when constructing Messages.
58
+ configrecord_key : str (default: "config")
59
+ Key used to store the ConfigRecord when constructing Messages.
60
+ train_metrics_aggr_fn : Optional[callable] (default: None)
61
+ Function with signature (list[RecordDict], str) -> MetricRecord,
62
+ used to aggregate MetricRecords from training round replies.
63
+ If `None`, defaults to `aggregate_metricrecords`, which performs a weighted
64
+ average using the provided weight factor key.
65
+ evaluate_metrics_aggr_fn : Optional[callable] (default: None)
66
+ Function with signature (list[RecordDict], str) -> MetricRecord,
67
+ used to aggregate MetricRecords from training round replies.
68
+ If `None`, defaults to `aggregate_metricrecords`, which performs a weighted
69
+ average using the provided weight factor key.
70
+ """
71
+
72
+ # pylint: disable=too-many-arguments,too-many-positional-arguments
73
+ def __init__(
74
+ self,
75
+ fraction_train: float = 1.0,
76
+ fraction_evaluate: float = 1.0,
77
+ min_available_nodes: int = 2,
78
+ weighted_by_key: str = "num-examples",
79
+ arrayrecord_key: str = "arrays",
80
+ configrecord_key: str = "config",
81
+ train_metrics_aggr_fn: Optional[
82
+ Callable[[list[RecordDict], str], MetricRecord]
83
+ ] = None,
84
+ evaluate_metrics_aggr_fn: Optional[
85
+ Callable[[list[RecordDict], str], MetricRecord]
86
+ ] = None,
87
+ ) -> None:
88
+ super().__init__(
89
+ fraction_train=fraction_train,
90
+ fraction_evaluate=fraction_evaluate,
91
+ min_train_nodes=2,
92
+ min_evaluate_nodes=2,
93
+ min_available_nodes=min_available_nodes,
94
+ weighted_by_key=weighted_by_key,
95
+ arrayrecord_key=arrayrecord_key,
96
+ configrecord_key=configrecord_key,
97
+ train_metrics_aggr_fn=train_metrics_aggr_fn,
98
+ evaluate_metrics_aggr_fn=evaluate_metrics_aggr_fn,
99
+ )
100
+
101
+ self.registered_nodes: dict[int, int] = {}
102
+
103
+ if fraction_train not in (0.0, 1.0):
104
+ raise ValueError(
105
+ "fraction_train can only be set to 1.0 or 0.0 for FedXgbCyclic."
106
+ )
107
+ if fraction_evaluate not in (0.0, 1.0):
108
+ raise ValueError(
109
+ "fraction_evaluate can only be set to 1.0 or 0.0 for FedXgbCyclic."
110
+ )
111
+
112
+ def _reorder_nodes(self, node_ids: list[int]) -> list[int]:
113
+ """Re-order node ids based on registered nodes.
114
+
115
+ Each node ID is assigned a persistent index in `self.registered_nodes`
116
+ the first time it appears. The input list is then reordered according
117
+ to these stored indices, and the result is compacted into ascending
118
+ order (1..N) for the current call.
119
+ """
120
+ # Assign new indices to unknown nodes
121
+ next_index = max(self.registered_nodes.values(), default=0) + 1
122
+ for nid in node_ids:
123
+ if nid not in self.registered_nodes:
124
+ self.registered_nodes[nid] = next_index
125
+ next_index += 1
126
+
127
+ # Sort node_ids by their stored indices
128
+ sorted_by_index = sorted(node_ids, key=lambda x: self.registered_nodes[x])
129
+
130
+ # Compact re-map of indices just for this output list
131
+ unique_indices = sorted(self.registered_nodes[nid] for nid in sorted_by_index)
132
+ remap = {old: new for new, old in enumerate(unique_indices, start=1)}
133
+
134
+ # Build the result list ordered by compact indices
135
+ result_list = [
136
+ nid
137
+ for _, nid in sorted(
138
+ (remap[self.registered_nodes[nid]], nid) for nid in sorted_by_index
139
+ )
140
+ ]
141
+ return result_list
142
+
143
+ def _make_sampling(
144
+ self, grid: Grid, server_round: int, configure_type: str
145
+ ) -> list[int]:
146
+ """Sample nodes using the Grid."""
147
+ # Sample nodes
148
+ num_nodes = int(len(list(grid.get_node_ids())) * self.fraction_train)
149
+ sample_size = max(num_nodes, self.min_train_nodes)
150
+ node_ids, _ = sample_nodes(grid, self.min_available_nodes, sample_size)
151
+
152
+ # Re-order node_ids
153
+ node_ids = self._reorder_nodes(node_ids)
154
+
155
+ # Sample the clients sequentially given server_round
156
+ sampled_idx = (server_round - 1) % len(node_ids)
157
+ sampled_node_id = [node_ids[sampled_idx]]
158
+
159
+ log(
160
+ INFO,
161
+ f"{configure_type}: Sampled %s nodes (out of %s)",
162
+ len(sampled_node_id),
163
+ len(node_ids),
164
+ )
165
+ return sampled_node_id
166
+
167
+ def configure_train(
168
+ self, server_round: int, arrays: ArrayRecord, config: ConfigRecord, grid: Grid
169
+ ) -> Iterable[Message]:
170
+ """Configure the next round of federated training."""
171
+ # Sample one node
172
+ sampled_node_id = self._make_sampling(grid, server_round, "configure_train")
173
+
174
+ # Always inject current server round
175
+ config["server-round"] = server_round
176
+
177
+ # Construct messages
178
+ record = RecordDict(
179
+ {self.arrayrecord_key: arrays, self.configrecord_key: config}
180
+ )
181
+ return self._construct_messages(record, sampled_node_id, MessageType.TRAIN)
182
+
183
+ def aggregate_train(
184
+ self,
185
+ server_round: int,
186
+ replies: Iterable[Message],
187
+ ) -> tuple[Optional[ArrayRecord], Optional[MetricRecord]]:
188
+ """Aggregate ArrayRecords and MetricRecords in the received Messages."""
189
+ valid_replies, _ = self._check_and_log_replies(replies, is_train=True)
190
+
191
+ arrays, metrics = None, None
192
+ if valid_replies:
193
+ reply_contents = [msg.content for msg in valid_replies]
194
+ array_record_key = next(iter(reply_contents[0].array_records.keys()))
195
+
196
+ # Fetch the client model from current round as global model
197
+ arrays = cast(ArrayRecord, reply_contents[0][array_record_key])
198
+
199
+ # Aggregate MetricRecords
200
+ metrics = self.train_metrics_aggr_fn(
201
+ reply_contents,
202
+ self.weighted_by_key,
203
+ )
204
+ return arrays, metrics
205
+
206
+ def configure_evaluate(
207
+ self, server_round: int, arrays: ArrayRecord, config: ConfigRecord, grid: Grid
208
+ ) -> Iterable[Message]:
209
+ """Configure the next round of federated evaluation."""
210
+ # Sample one node
211
+ sampled_node_id = self._make_sampling(grid, server_round, "configure_evaluate")
212
+
213
+ # Always inject current server round
214
+ config["server-round"] = server_round
215
+
216
+ # Construct messages
217
+ record = RecordDict(
218
+ {self.arrayrecord_key: arrays, self.configrecord_key: config}
219
+ )
220
+ return self._construct_messages(record, sampled_node_id, MessageType.EVALUATE)
@@ -164,9 +164,6 @@ class FedYogi(FedOpt):
164
164
  for k, x in self.current_arrays.items()
165
165
  }
166
166
 
167
- # Update current arrays
168
- self.current_arrays = new_arrays
169
-
170
167
  return (
171
168
  ArrayRecord(OrderedDict({k: Array(v) for k, v in new_arrays.items()})),
172
169
  aggregated_metrics,
@@ -0,0 +1,230 @@
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
+ """Machine Learning with Adversaries: Byzantine Tolerant Gradient Descent.
16
+
17
+ [Blanchard et al., 2017].
18
+
19
+ Paper: proceedings.neurips.cc/paper/2017/file/f4b9ec30ad9f68f89b29639786cb62ef-Paper.pdf
20
+ """
21
+
22
+
23
+ from collections.abc import Iterable
24
+ from logging import INFO
25
+ from typing import Callable, Optional
26
+
27
+ import numpy as np
28
+
29
+ from flwr.common import ArrayRecord, Message, MetricRecord, NDArray, RecordDict, log
30
+
31
+ from .fedavg import FedAvg
32
+ from .strategy_utils import aggregate_arrayrecords
33
+
34
+
35
+ # pylint: disable=too-many-instance-attributes
36
+ class Krum(FedAvg):
37
+ """Krum [Blanchard et al., 2017] strategy.
38
+
39
+ Implementation based on https://arxiv.org/abs/1703.02757
40
+
41
+ Parameters
42
+ ----------
43
+ fraction_train : float (default: 1.0)
44
+ Fraction of nodes used during training. In case `min_train_nodes`
45
+ is larger than `fraction_train * total_connected_nodes`, `min_train_nodes`
46
+ will still be sampled.
47
+ fraction_evaluate : float (default: 1.0)
48
+ Fraction of nodes used during validation. In case `min_evaluate_nodes`
49
+ is larger than `fraction_evaluate * total_connected_nodes`,
50
+ `min_evaluate_nodes` will still be sampled.
51
+ min_train_nodes : int (default: 2)
52
+ Minimum number of nodes used during training.
53
+ min_evaluate_nodes : int (default: 2)
54
+ Minimum number of nodes used during validation.
55
+ min_available_nodes : int (default: 2)
56
+ Minimum number of total nodes in the system.
57
+ num_malicious_nodes : int (default: 0)
58
+ Number of malicious nodes in the system. Defaults to 0.
59
+ num_nodes_to_keep : int (default: 0)
60
+ Number of nodes to keep before averaging (MultiKrum). Defaults to 0, in
61
+ that case classical Krum is applied.
62
+ weighted_by_key : str (default: "num-examples")
63
+ The key within each MetricRecord whose value is used as the weight when
64
+ computing weighted averages for both ArrayRecords and MetricRecords.
65
+ arrayrecord_key : str (default: "arrays")
66
+ Key used to store the ArrayRecord when constructing Messages.
67
+ configrecord_key : str (default: "config")
68
+ Key used to store the ConfigRecord when constructing Messages.
69
+ train_metrics_aggr_fn : Optional[callable] (default: None)
70
+ Function with signature (list[RecordDict], str) -> MetricRecord,
71
+ used to aggregate MetricRecords from training round replies.
72
+ If `None`, defaults to `aggregate_metricrecords`, which performs a weighted
73
+ average using the provided weight factor key.
74
+ evaluate_metrics_aggr_fn : Optional[callable] (default: None)
75
+ Function with signature (list[RecordDict], str) -> MetricRecord,
76
+ used to aggregate MetricRecords from training round replies.
77
+ If `None`, defaults to `aggregate_metricrecords`, which performs a weighted
78
+ average using the provided weight factor key.
79
+ """
80
+
81
+ # pylint: disable=too-many-arguments,too-many-positional-arguments
82
+ def __init__(
83
+ self,
84
+ fraction_train: float = 1.0,
85
+ fraction_evaluate: float = 1.0,
86
+ min_train_nodes: int = 2,
87
+ min_evaluate_nodes: int = 2,
88
+ min_available_nodes: int = 2,
89
+ num_malicious_nodes: int = 0,
90
+ num_nodes_to_keep: int = 0,
91
+ weighted_by_key: str = "num-examples",
92
+ arrayrecord_key: str = "arrays",
93
+ configrecord_key: str = "config",
94
+ train_metrics_aggr_fn: Optional[
95
+ Callable[[list[RecordDict], str], MetricRecord]
96
+ ] = None,
97
+ evaluate_metrics_aggr_fn: Optional[
98
+ Callable[[list[RecordDict], str], MetricRecord]
99
+ ] = None,
100
+ ) -> None:
101
+ super().__init__(
102
+ fraction_train=fraction_train,
103
+ fraction_evaluate=fraction_evaluate,
104
+ min_train_nodes=min_train_nodes,
105
+ min_evaluate_nodes=min_evaluate_nodes,
106
+ min_available_nodes=min_available_nodes,
107
+ weighted_by_key=weighted_by_key,
108
+ arrayrecord_key=arrayrecord_key,
109
+ configrecord_key=configrecord_key,
110
+ train_metrics_aggr_fn=train_metrics_aggr_fn,
111
+ evaluate_metrics_aggr_fn=evaluate_metrics_aggr_fn,
112
+ )
113
+ self.num_malicious_nodes = num_malicious_nodes
114
+ self.num_nodes_to_keep = num_nodes_to_keep
115
+
116
+ def summary(self) -> None:
117
+ """Log summary configuration of the strategy."""
118
+ log(INFO, "\t├──> Krum settings:")
119
+ log(INFO, "\t│\t├── Number of malicious nodes: %d", self.num_malicious_nodes)
120
+ log(INFO, "\t│\t└── Number of nodes to keep: %d", self.num_nodes_to_keep)
121
+ super().summary()
122
+
123
+ def _compute_distances(self, records: list[ArrayRecord]) -> NDArray:
124
+ """Compute distances between ArrayRecords.
125
+
126
+ Parameters
127
+ ----------
128
+ records : list[ArrayRecord]
129
+ A list of ArrayRecords (arrays received in replies)
130
+
131
+ Returns
132
+ -------
133
+ NDArray
134
+ A 2D array representing the distance matrix of squared distances
135
+ between input ArrayRecords
136
+ """
137
+ flat_w = np.array(
138
+ [
139
+ np.concatenate(rec.to_numpy_ndarrays(), axis=None).ravel()
140
+ for rec in records
141
+ ]
142
+ )
143
+ distance_matrix = np.zeros((len(records), len(records)))
144
+ for i, flat_w_i in enumerate(flat_w):
145
+ for j, flat_w_j in enumerate(flat_w):
146
+ delta = flat_w_i - flat_w_j
147
+ norm = np.linalg.norm(delta)
148
+ distance_matrix[i, j] = norm**2
149
+ return distance_matrix
150
+
151
+ def _krum(self, replies: list[RecordDict]) -> list[RecordDict]:
152
+ """Select the set of RecordDicts to aggregate using the Krum or MultiKrum
153
+ algorithm.
154
+
155
+ For each node, computes the sum of squared distances to its n-f-2 closest
156
+ parameter vectors, where n is the number of nodes and f is the number of
157
+ malicious nodes. The node(s) with the lowest score(s) are selected for
158
+ aggregation.
159
+
160
+ Parameters
161
+ ----------
162
+ replies : list[RecordDict]
163
+ List of RecordDicts, each containing an ArrayRecord representing model
164
+ parameters from a client.
165
+
166
+ Returns
167
+ -------
168
+ list[RecordDict]
169
+ List of RecordDicts selected for aggregation. If `num_nodes_to_keep` > 0,
170
+ returns the top `num_nodes_to_keep` RecordDicts (MultiKrum); otherwise,
171
+ returns the single RecordDict with the lowest score (Krum).
172
+ """
173
+ # Construct list of ArrayRecord objects from replies
174
+ # Recall aggregate_train first ensures replies only contain one ArrayRecord
175
+ array_records = [list(reply.array_records.values())[0] for reply in replies]
176
+ distance_matrix = self._compute_distances(array_records)
177
+
178
+ # For each node, take the n-f-2 closest parameters vectors
179
+ num_closest = max(1, len(array_records) - self.num_malicious_nodes - 2)
180
+ closest_indices = []
181
+ for distance in distance_matrix:
182
+ closest_indices.append(
183
+ np.argsort(distance)[1 : num_closest + 1].tolist() # noqa: E203
184
+ )
185
+
186
+ # Compute the score for each node, that is the sum of the distances
187
+ # of the n-f-2 closest parameters vectors
188
+ scores = [
189
+ np.sum(distance_matrix[i, closest_indices[i]])
190
+ for i in range(len(distance_matrix))
191
+ ]
192
+
193
+ # Return RecordDicts that should be aggregated
194
+ if self.num_nodes_to_keep > 0:
195
+ # Choose to_keep nodes and return their average (MultiKrum)
196
+ best_indices = np.argsort(scores)[::-1][
197
+ len(scores) - self.num_nodes_to_keep :
198
+ ] # noqa: E203
199
+ return [replies[i] for i in best_indices]
200
+
201
+ # Return the RecordDict with the ArrayRecord that minimize the score (Krum)
202
+ return [replies[np.argmin(scores)]]
203
+
204
+ def aggregate_train(
205
+ self,
206
+ server_round: int,
207
+ replies: Iterable[Message],
208
+ ) -> tuple[Optional[ArrayRecord], Optional[MetricRecord]]:
209
+ """Aggregate ArrayRecords and MetricRecords in the received Messages."""
210
+ valid_replies, _ = self._check_and_log_replies(replies, is_train=True)
211
+
212
+ arrays, metrics = None, None
213
+ if valid_replies:
214
+ reply_contents = [msg.content for msg in valid_replies]
215
+
216
+ # Krum
217
+ replies_to_aggregate = self._krum(reply_contents)
218
+
219
+ # Aggregate ArrayRecords
220
+ arrays = aggregate_arrayrecords(
221
+ replies_to_aggregate,
222
+ self.weighted_by_key,
223
+ )
224
+
225
+ # Aggregate MetricRecords
226
+ metrics = self.train_metrics_aggr_fn(
227
+ replies_to_aggregate,
228
+ self.weighted_by_key,
229
+ )
230
+ return arrays, metrics