flwr-nightly 1.21.0.dev20250901__py3-none-any.whl → 1.21.0.dev20250903__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/constant.py +25 -8
  2. flwr/cli/new/templates/app/code/server.pytorch_msg_api.py.tpl +0 -8
  3. flwr/cli/run/run.py +2 -6
  4. flwr/clientapp/__init__.py +4 -0
  5. flwr/clientapp/centraldp_mods.py +132 -0
  6. flwr/common/exception.py +31 -0
  7. flwr/common/exit/__init__.py +4 -0
  8. flwr/common/exit/exit.py +4 -0
  9. flwr/common/exit/exit_code.py +7 -0
  10. flwr/common/exit/exit_handler.py +62 -0
  11. flwr/common/{exit_handlers.py → exit/signal_handler.py} +20 -37
  12. flwr/common/grpc.py +0 -11
  13. flwr/common/inflatable_utils.py +1 -1
  14. flwr/compat/server/app.py +2 -2
  15. flwr/server/app.py +12 -3
  16. flwr/server/serverapp/app.py +41 -28
  17. flwr/serverapp/dp_fixed_clipping.py +352 -0
  18. flwr/serverapp/strategy/__init__.py +6 -0
  19. flwr/serverapp/strategy/dp_fixed_clipping.py +352 -0
  20. flwr/serverapp/strategy/result.py +76 -2
  21. flwr/serverapp/strategy/strategy.py +15 -20
  22. flwr/serverapp/strategy/strategy_utils.py +5 -1
  23. flwr/supercore/cli/flower_superexec.py +3 -0
  24. flwr/supercore/grpc_health/__init__.py +3 -0
  25. flwr/supercore/grpc_health/health_server.py +53 -0
  26. flwr/supercore/grpc_health/simple_health_servicer.py +2 -2
  27. flwr/supercore/superexec/run_superexec.py +15 -3
  28. flwr/supernode/cli/flower_supernode.py +3 -0
  29. flwr/supernode/start_client_internal.py +15 -4
  30. {flwr_nightly-1.21.0.dev20250901.dist-info → flwr_nightly-1.21.0.dev20250903.dist-info}/METADATA +1 -1
  31. {flwr_nightly-1.21.0.dev20250901.dist-info → flwr_nightly-1.21.0.dev20250903.dist-info}/RECORD +33 -27
  32. {flwr_nightly-1.21.0.dev20250901.dist-info → flwr_nightly-1.21.0.dev20250903.dist-info}/WHEEL +0 -0
  33. {flwr_nightly-1.21.0.dev20250901.dist-info → flwr_nightly-1.21.0.dev20250903.dist-info}/entry_points.txt +0 -0
@@ -37,7 +37,8 @@ from flwr.common.constant import (
37
37
  Status,
38
38
  SubStatus,
39
39
  )
40
- from flwr.common.exit import ExitCode, flwr_exit
40
+ from flwr.common.exception import AppExitException
41
+ from flwr.common.exit import ExitCode, add_exit_handler, flwr_exit
41
42
  from flwr.common.heartbeat import HeartbeatSender, get_grpc_app_heartbeat_fn
42
43
  from flwr.common.logger import (
43
44
  log,
@@ -133,12 +134,34 @@ def run_serverapp( # pylint: disable=R0913, R0914, R0915, R0917, W0212
133
134
  # Resolve directory where FABs are installed
134
135
  flwr_dir_ = get_flwr_dir(flwr_dir)
135
136
  log_uploader = None
136
- success = True
137
137
  hash_run_id = None
138
138
  run_status = None
139
139
  heartbeat_sender = None
140
140
  grid = None
141
141
  context = None
142
+ exit_code = ExitCode.SUCCESS
143
+
144
+ def on_exit() -> None:
145
+ # Stop heartbeat sender
146
+ if heartbeat_sender:
147
+ heartbeat_sender.stop()
148
+
149
+ # Stop log uploader for this run and upload final logs
150
+ if log_uploader:
151
+ stop_log_uploader(log_queue, log_uploader)
152
+
153
+ # Update run status
154
+ if run_status and grid:
155
+ run_status_proto = run_status_to_proto(run_status)
156
+ grid._stub.UpdateRunStatus(
157
+ UpdateRunStatusRequest(run_id=run.run_id, run_status=run_status_proto)
158
+ )
159
+
160
+ # Close the Grpc connection
161
+ if grid:
162
+ grid.close()
163
+
164
+ add_exit_handler(on_exit)
142
165
 
143
166
  try:
144
167
  # Initialize the GrpcGrid
@@ -229,43 +252,33 @@ def run_serverapp( # pylint: disable=R0913, R0914, R0915, R0917, W0212
229
252
  _ = grid._stub.PushAppOutputs(out_req)
230
253
 
231
254
  run_status = RunStatus(Status.FINISHED, SubStatus.COMPLETED, "")
255
+
256
+ # Raised when the run is already stopped by the user
232
257
  except RunNotRunningException:
233
258
  log(INFO, "")
234
259
  log(INFO, "Run ID %s stopped.", run.run_id)
235
260
  log(INFO, "")
236
261
  run_status = None
237
- success = False
262
+ # No need to update the exit code since this is expected behavior
238
263
 
239
264
  except Exception as ex: # pylint: disable=broad-exception-caught
240
265
  exc_entity = "ServerApp"
241
266
  log(ERROR, "%s raised an exception", exc_entity, exc_info=ex)
242
267
  run_status = RunStatus(Status.FINISHED, SubStatus.FAILED, str(ex))
243
- success = False
244
268
 
245
- finally:
246
- # Stop heartbeat sender
247
- if heartbeat_sender:
248
- heartbeat_sender.stop()
249
-
250
- # Stop log uploader for this run and upload final logs
251
- if log_uploader:
252
- stop_log_uploader(log_queue, log_uploader)
253
-
254
- # Update run status
255
- if run_status and grid:
256
- run_status_proto = run_status_to_proto(run_status)
257
- grid._stub.UpdateRunStatus(
258
- UpdateRunStatusRequest(run_id=run.run_id, run_status=run_status_proto)
259
- )
260
-
261
- # Close the Grpc connection
262
- if grid:
263
- grid.close()
264
-
265
- event(
266
- EventType.FLWR_SERVERAPP_RUN_LEAVE,
267
- event_details={"run-id-hash": hash_run_id, "success": success},
268
- )
269
+ # Set exit code
270
+ exit_code = ExitCode.SERVERAPP_EXCEPTION # General exit code
271
+ if isinstance(ex, AppExitException):
272
+ exit_code = ex.exit_code
273
+
274
+ flwr_exit(
275
+ code=exit_code,
276
+ event_type=EventType.FLWR_SERVERAPP_RUN_LEAVE,
277
+ event_details={
278
+ "run-id-hash": hash_run_id,
279
+ "success": exit_code == ExitCode.SUCCESS,
280
+ },
281
+ )
269
282
 
270
283
 
271
284
  def _parse_args_run_flwr_serverapp() -> argparse.ArgumentParser:
@@ -0,0 +1,352 @@
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
@@ -15,11 +15,17 @@
15
15
  """ServerApp strategies."""
16
16
 
17
17
 
18
+ from .dp_fixed_clipping import (
19
+ DifferentialPrivacyClientSideFixedClipping,
20
+ DifferentialPrivacyServerSideFixedClipping,
21
+ )
18
22
  from .fedavg import FedAvg
19
23
  from .result import Result
20
24
  from .strategy import Strategy
21
25
 
22
26
  __all__ = [
27
+ "DifferentialPrivacyClientSideFixedClipping",
28
+ "DifferentialPrivacyServerSideFixedClipping",
23
29
  "FedAvg",
24
30
  "Result",
25
31
  "Strategy",