flwr 1.19.0__py3-none-any.whl → 1.21.0__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 (167) hide show
  1. flwr/__init__.py +4 -1
  2. flwr/app/__init__.py +28 -0
  3. flwr/app/exception.py +31 -0
  4. flwr/cli/auth_plugin/oidc_cli_plugin.py +4 -4
  5. flwr/cli/build.py +15 -5
  6. flwr/cli/cli_user_auth_interceptor.py +1 -1
  7. flwr/cli/config_utils.py +3 -3
  8. flwr/cli/constant.py +25 -8
  9. flwr/cli/log.py +9 -9
  10. flwr/cli/login/login.py +3 -3
  11. flwr/cli/ls.py +5 -5
  12. flwr/cli/new/new.py +23 -4
  13. flwr/cli/new/templates/app/README.flowertune.md.tpl +2 -0
  14. flwr/cli/new/templates/app/README.md.tpl +5 -0
  15. flwr/cli/new/templates/app/code/__init__.pytorch_msg_api.py.tpl +1 -0
  16. flwr/cli/new/templates/app/code/client.pytorch_msg_api.py.tpl +80 -0
  17. flwr/cli/new/templates/app/code/server.pytorch_msg_api.py.tpl +41 -0
  18. flwr/cli/new/templates/app/code/task.pytorch_msg_api.py.tpl +98 -0
  19. flwr/cli/new/templates/app/pyproject.baseline.toml.tpl +14 -3
  20. flwr/cli/new/templates/app/pyproject.flowertune.toml.tpl +13 -1
  21. flwr/cli/new/templates/app/pyproject.huggingface.toml.tpl +21 -2
  22. flwr/cli/new/templates/app/pyproject.jax.toml.tpl +18 -1
  23. flwr/cli/new/templates/app/pyproject.mlx.toml.tpl +19 -2
  24. flwr/cli/new/templates/app/pyproject.numpy.toml.tpl +18 -1
  25. flwr/cli/new/templates/app/pyproject.pytorch.toml.tpl +20 -3
  26. flwr/cli/new/templates/app/pyproject.pytorch_msg_api.toml.tpl +53 -0
  27. flwr/cli/new/templates/app/pyproject.sklearn.toml.tpl +18 -1
  28. flwr/cli/new/templates/app/pyproject.tensorflow.toml.tpl +18 -1
  29. flwr/cli/run/run.py +53 -50
  30. flwr/cli/stop.py +7 -4
  31. flwr/cli/utils.py +29 -11
  32. flwr/client/grpc_adapter_client/connection.py +11 -4
  33. flwr/client/grpc_rere_client/connection.py +93 -129
  34. flwr/client/rest_client/connection.py +134 -164
  35. flwr/clientapp/__init__.py +10 -0
  36. flwr/clientapp/mod/__init__.py +26 -0
  37. flwr/clientapp/mod/centraldp_mods.py +132 -0
  38. flwr/common/args.py +20 -6
  39. flwr/common/auth_plugin/__init__.py +4 -4
  40. flwr/common/auth_plugin/auth_plugin.py +7 -7
  41. flwr/common/constant.py +26 -5
  42. flwr/common/event_log_plugin/event_log_plugin.py +1 -1
  43. flwr/common/exit/__init__.py +4 -0
  44. flwr/common/exit/exit.py +8 -1
  45. flwr/common/exit/exit_code.py +42 -8
  46. flwr/common/exit/exit_handler.py +62 -0
  47. flwr/common/{exit_handlers.py → exit/signal_handler.py} +20 -37
  48. flwr/common/grpc.py +1 -1
  49. flwr/common/{inflatable_grpc_utils.py → inflatable_protobuf_utils.py} +52 -10
  50. flwr/common/inflatable_utils.py +191 -24
  51. flwr/common/logger.py +1 -1
  52. flwr/common/record/array.py +101 -22
  53. flwr/common/record/arraychunk.py +59 -0
  54. flwr/common/retry_invoker.py +30 -11
  55. flwr/common/serde.py +0 -28
  56. flwr/common/telemetry.py +4 -0
  57. flwr/compat/client/app.py +14 -31
  58. flwr/compat/server/app.py +2 -2
  59. flwr/proto/appio_pb2.py +51 -0
  60. flwr/proto/appio_pb2.pyi +195 -0
  61. flwr/proto/appio_pb2_grpc.py +4 -0
  62. flwr/proto/appio_pb2_grpc.pyi +4 -0
  63. flwr/proto/clientappio_pb2.py +4 -19
  64. flwr/proto/clientappio_pb2.pyi +0 -125
  65. flwr/proto/clientappio_pb2_grpc.py +269 -29
  66. flwr/proto/clientappio_pb2_grpc.pyi +114 -21
  67. flwr/proto/control_pb2.py +62 -0
  68. flwr/proto/{exec_pb2_grpc.py → control_pb2_grpc.py} +54 -54
  69. flwr/proto/{exec_pb2_grpc.pyi → control_pb2_grpc.pyi} +28 -28
  70. flwr/proto/fleet_pb2.py +12 -20
  71. flwr/proto/fleet_pb2.pyi +6 -36
  72. flwr/proto/serverappio_pb2.py +8 -31
  73. flwr/proto/serverappio_pb2.pyi +0 -152
  74. flwr/proto/serverappio_pb2_grpc.py +107 -38
  75. flwr/proto/serverappio_pb2_grpc.pyi +47 -20
  76. flwr/proto/simulationio_pb2.py +4 -11
  77. flwr/proto/simulationio_pb2.pyi +0 -58
  78. flwr/proto/simulationio_pb2_grpc.py +129 -27
  79. flwr/proto/simulationio_pb2_grpc.pyi +52 -13
  80. flwr/server/app.py +130 -153
  81. flwr/server/fleet_event_log_interceptor.py +4 -0
  82. flwr/server/grid/grpc_grid.py +94 -54
  83. flwr/server/grid/inmemory_grid.py +1 -0
  84. flwr/server/serverapp/app.py +165 -144
  85. flwr/server/superlink/fleet/grpc_adapter/grpc_adapter_servicer.py +8 -0
  86. flwr/server/superlink/fleet/grpc_rere/fleet_servicer.py +1 -1
  87. flwr/server/superlink/fleet/grpc_rere/server_interceptor.py +2 -5
  88. flwr/server/superlink/fleet/message_handler/message_handler.py +10 -16
  89. flwr/server/superlink/fleet/rest_rere/rest_api.py +1 -2
  90. flwr/server/superlink/fleet/vce/backend/raybackend.py +3 -1
  91. flwr/server/superlink/fleet/vce/vce_api.py +6 -6
  92. flwr/server/superlink/linkstate/in_memory_linkstate.py +34 -0
  93. flwr/server/superlink/linkstate/linkstate.py +2 -1
  94. flwr/server/superlink/linkstate/sqlite_linkstate.py +45 -0
  95. flwr/server/superlink/serverappio/serverappio_grpc.py +2 -2
  96. flwr/server/superlink/serverappio/serverappio_servicer.py +95 -48
  97. flwr/server/superlink/simulation/simulationio_grpc.py +1 -1
  98. flwr/server/superlink/simulation/simulationio_servicer.py +98 -22
  99. flwr/server/superlink/utils.py +0 -35
  100. flwr/serverapp/__init__.py +12 -0
  101. flwr/serverapp/dp_fixed_clipping.py +352 -0
  102. flwr/serverapp/exception.py +38 -0
  103. flwr/serverapp/strategy/__init__.py +38 -0
  104. flwr/serverapp/strategy/dp_fixed_clipping.py +352 -0
  105. flwr/serverapp/strategy/fedadagrad.py +162 -0
  106. flwr/serverapp/strategy/fedadam.py +181 -0
  107. flwr/serverapp/strategy/fedavg.py +295 -0
  108. flwr/serverapp/strategy/fedopt.py +218 -0
  109. flwr/serverapp/strategy/fedyogi.py +173 -0
  110. flwr/serverapp/strategy/result.py +105 -0
  111. flwr/serverapp/strategy/strategy.py +285 -0
  112. flwr/serverapp/strategy/strategy_utils.py +251 -0
  113. flwr/serverapp/strategy/strategy_utils_tests.py +304 -0
  114. flwr/simulation/app.py +159 -154
  115. flwr/simulation/run_simulation.py +17 -0
  116. flwr/supercore/app_utils.py +58 -0
  117. flwr/supercore/cli/__init__.py +22 -0
  118. flwr/supercore/cli/flower_superexec.py +141 -0
  119. flwr/supercore/corestate/__init__.py +22 -0
  120. flwr/supercore/corestate/corestate.py +81 -0
  121. flwr/{server/superlink → supercore}/ffs/disk_ffs.py +1 -1
  122. flwr/supercore/grpc_health/__init__.py +25 -0
  123. flwr/supercore/grpc_health/health_server.py +53 -0
  124. flwr/supercore/grpc_health/simple_health_servicer.py +38 -0
  125. flwr/supercore/license_plugin/__init__.py +22 -0
  126. flwr/supercore/license_plugin/license_plugin.py +26 -0
  127. flwr/supercore/object_store/in_memory_object_store.py +31 -31
  128. flwr/supercore/object_store/object_store.py +20 -42
  129. flwr/supercore/object_store/utils.py +43 -0
  130. flwr/{superexec → supercore/superexec}/__init__.py +1 -1
  131. flwr/supercore/superexec/plugin/__init__.py +28 -0
  132. flwr/supercore/superexec/plugin/base_exec_plugin.py +53 -0
  133. flwr/supercore/superexec/plugin/clientapp_exec_plugin.py +28 -0
  134. flwr/supercore/superexec/plugin/exec_plugin.py +71 -0
  135. flwr/supercore/superexec/plugin/serverapp_exec_plugin.py +28 -0
  136. flwr/supercore/superexec/plugin/simulation_exec_plugin.py +28 -0
  137. flwr/supercore/superexec/run_superexec.py +185 -0
  138. flwr/supercore/utils.py +32 -0
  139. flwr/superlink/servicer/__init__.py +15 -0
  140. flwr/superlink/servicer/control/__init__.py +22 -0
  141. flwr/{superexec/exec_event_log_interceptor.py → superlink/servicer/control/control_event_log_interceptor.py} +9 -5
  142. flwr/{superexec/exec_grpc.py → superlink/servicer/control/control_grpc.py} +39 -28
  143. flwr/superlink/servicer/control/control_license_interceptor.py +82 -0
  144. flwr/{superexec/exec_servicer.py → superlink/servicer/control/control_servicer.py} +79 -31
  145. flwr/{superexec/exec_user_auth_interceptor.py → superlink/servicer/control/control_user_auth_interceptor.py} +18 -10
  146. flwr/supernode/cli/flower_supernode.py +3 -7
  147. flwr/supernode/cli/flwr_clientapp.py +20 -16
  148. flwr/supernode/nodestate/in_memory_nodestate.py +13 -4
  149. flwr/supernode/nodestate/nodestate.py +3 -44
  150. flwr/supernode/runtime/run_clientapp.py +129 -115
  151. flwr/supernode/servicer/clientappio/__init__.py +1 -3
  152. flwr/supernode/servicer/clientappio/clientappio_servicer.py +217 -165
  153. flwr/supernode/start_client_internal.py +205 -148
  154. {flwr-1.19.0.dist-info → flwr-1.21.0.dist-info}/METADATA +5 -3
  155. {flwr-1.19.0.dist-info → flwr-1.21.0.dist-info}/RECORD +161 -117
  156. {flwr-1.19.0.dist-info → flwr-1.21.0.dist-info}/entry_points.txt +1 -0
  157. flwr/common/inflatable_rest_utils.py +0 -99
  158. flwr/proto/exec_pb2.py +0 -62
  159. flwr/superexec/app.py +0 -45
  160. flwr/superexec/deployment.py +0 -192
  161. flwr/superexec/executor.py +0 -100
  162. flwr/superexec/simulation.py +0 -130
  163. /flwr/proto/{exec_pb2.pyi → control_pb2.pyi} +0 -0
  164. /flwr/{server/superlink → supercore}/ffs/__init__.py +0 -0
  165. /flwr/{server/superlink → supercore}/ffs/ffs.py +0 -0
  166. /flwr/{server/superlink → supercore}/ffs/ffs_factory.py +0 -0
  167. {flwr-1.19.0.dist-info → flwr-1.21.0.dist-info}/WHEEL +0 -0
@@ -34,6 +34,16 @@ from flwr.common.serde import (
34
34
  )
35
35
  from flwr.common.typing import Fab, RunStatus
36
36
  from flwr.proto import simulationio_pb2_grpc
37
+ from flwr.proto.appio_pb2 import ( # pylint: disable=E0611
38
+ ListAppsToLaunchRequest,
39
+ ListAppsToLaunchResponse,
40
+ PullAppInputsRequest,
41
+ PullAppInputsResponse,
42
+ PushAppOutputsRequest,
43
+ PushAppOutputsResponse,
44
+ RequestTokenRequest,
45
+ RequestTokenResponse,
46
+ )
37
47
  from flwr.proto.heartbeat_pb2 import ( # pylint: disable=E0611
38
48
  SendAppHeartbeatRequest,
39
49
  SendAppHeartbeatResponse,
@@ -45,20 +55,16 @@ from flwr.proto.log_pb2 import ( # pylint: disable=E0611
45
55
  from flwr.proto.run_pb2 import ( # pylint: disable=E0611
46
56
  GetFederationOptionsRequest,
47
57
  GetFederationOptionsResponse,
58
+ GetRunRequest,
59
+ GetRunResponse,
48
60
  GetRunStatusRequest,
49
61
  GetRunStatusResponse,
50
62
  UpdateRunStatusRequest,
51
63
  UpdateRunStatusResponse,
52
64
  )
53
- from flwr.proto.simulationio_pb2 import ( # pylint: disable=E0611
54
- PullSimulationInputsRequest,
55
- PullSimulationInputsResponse,
56
- PushSimulationOutputsRequest,
57
- PushSimulationOutputsResponse,
58
- )
59
- from flwr.server.superlink.ffs.ffs_factory import FfsFactory
60
65
  from flwr.server.superlink.linkstate import LinkStateFactory
61
66
  from flwr.server.superlink.utils import abort_if
67
+ from flwr.supercore.ffs import FfsFactory
62
68
 
63
69
 
64
70
  class SimulationIoServicer(simulationio_pb2_grpc.SimulationIoServicer):
@@ -71,23 +77,73 @@ class SimulationIoServicer(simulationio_pb2_grpc.SimulationIoServicer):
71
77
  self.ffs_factory = ffs_factory
72
78
  self.lock = threading.RLock()
73
79
 
74
- def PullSimulationInputs(
75
- self, request: PullSimulationInputsRequest, context: ServicerContext
76
- ) -> PullSimulationInputsResponse:
80
+ def ListAppsToLaunch(
81
+ self,
82
+ request: ListAppsToLaunchRequest,
83
+ context: grpc.ServicerContext,
84
+ ) -> ListAppsToLaunchResponse:
85
+ """Get run IDs with pending messages."""
86
+ log(DEBUG, "SimulationIoServicer.ListAppsToLaunch")
87
+
88
+ # Initialize state connection
89
+ state = self.state_factory.state()
90
+
91
+ # Get IDs of runs in pending status
92
+ run_ids = state.get_run_ids(flwr_aid=None)
93
+ pending_run_ids = []
94
+ for run_id, status in state.get_run_status(run_ids).items():
95
+ if status.status == Status.PENDING:
96
+ pending_run_ids.append(run_id)
97
+
98
+ # Return run IDs
99
+ return ListAppsToLaunchResponse(run_ids=pending_run_ids)
100
+
101
+ def RequestToken(
102
+ self, request: RequestTokenRequest, context: grpc.ServicerContext
103
+ ) -> RequestTokenResponse:
104
+ """Request token."""
105
+ log(DEBUG, "SimulationIoServicer.RequestToken")
106
+
107
+ # Initialize state connection
108
+ state = self.state_factory.state()
109
+
110
+ # Attempt to create a token for the provided run ID
111
+ token = state.create_token(request.run_id)
112
+
113
+ # Return the token
114
+ return RequestTokenResponse(token=token or "")
115
+
116
+ def GetRun(
117
+ self, request: GetRunRequest, context: grpc.ServicerContext
118
+ ) -> GetRunResponse:
119
+ """Get run information."""
120
+ log(DEBUG, "SimulationIoServicer.GetRun")
121
+
122
+ # Init state
123
+ state = self.state_factory.state()
124
+
125
+ # Retrieve run information
126
+ run = state.get_run(request.run_id)
127
+
128
+ if run is None:
129
+ return GetRunResponse()
130
+
131
+ return GetRunResponse(run=run_to_proto(run))
132
+
133
+ def PullAppInputs(
134
+ self, request: PullAppInputsRequest, context: ServicerContext
135
+ ) -> PullAppInputsResponse:
77
136
  """Pull SimultionIo process inputs."""
78
137
  log(DEBUG, "SimultionIoServicer.SimultionIoInputs")
79
138
  # Init access to LinkState and Ffs
80
139
  state = self.state_factory.state()
81
140
  ffs = self.ffs_factory.ffs()
82
141
 
142
+ # Validate the token
143
+ run_id = self._verify_token(request.token, context)
144
+
83
145
  # Lock access to LinkState, preventing obtaining the same pending run_id
84
146
  with self.lock:
85
- # Attempt getting the run_id of a pending run
86
- run_id = state.get_pending_run_id()
87
- # If there's no pending run, return an empty response
88
- if run_id is None:
89
- return PullSimulationInputsResponse()
90
-
91
147
  # Retrieve Context, Run and Fab for the run_id
92
148
  serverapp_ctxt = state.get_serverapp_context(run_id)
93
149
  run = state.get_run(run_id)
@@ -99,7 +155,7 @@ class SimulationIoServicer(simulationio_pb2_grpc.SimulationIoServicer):
99
155
  # Update run status to STARTING
100
156
  if state.update_run_status(run_id, RunStatus(Status.STARTING, "", "")):
101
157
  log(INFO, "Starting run %d", run_id)
102
- return PullSimulationInputsResponse(
158
+ return PullAppInputsResponse(
103
159
  context=context_to_proto(serverapp_ctxt),
104
160
  run=run_to_proto(run),
105
161
  fab=fab_to_proto(fab),
@@ -109,11 +165,16 @@ class SimulationIoServicer(simulationio_pb2_grpc.SimulationIoServicer):
109
165
  # or if the status cannot be updated to STARTING
110
166
  raise RuntimeError(f"Failed to start run {run_id}")
111
167
 
112
- def PushSimulationOutputs(
113
- self, request: PushSimulationOutputsRequest, context: ServicerContext
114
- ) -> PushSimulationOutputsResponse:
168
+ def PushAppOutputs(
169
+ self, request: PushAppOutputsRequest, context: ServicerContext
170
+ ) -> PushAppOutputsResponse:
115
171
  """Push Simulation process outputs."""
116
- log(DEBUG, "SimultionIoServicer.PushSimulationOutputs")
172
+ log(DEBUG, "SimultionIoServicer.PushAppOutputs")
173
+
174
+ # Validate the token
175
+ run_id = self._verify_token(request.token, context)
176
+
177
+ # Init access to LinkState
117
178
  state = self.state_factory.state()
118
179
 
119
180
  # Abort if the run is not running
@@ -126,7 +187,10 @@ class SimulationIoServicer(simulationio_pb2_grpc.SimulationIoServicer):
126
187
  )
127
188
 
128
189
  state.set_serverapp_context(request.run_id, context_from_proto(request.context))
129
- return PushSimulationOutputsResponse()
190
+
191
+ # Remove the token
192
+ state.delete_token(run_id)
193
+ return PushAppOutputsResponse()
130
194
 
131
195
  def UpdateRunStatus(
132
196
  self, request: UpdateRunStatusRequest, context: grpc.ServicerContext
@@ -208,3 +272,15 @@ class SimulationIoServicer(simulationio_pb2_grpc.SimulationIoServicer):
208
272
  )
209
273
 
210
274
  return SendAppHeartbeatResponse(success=success)
275
+
276
+ def _verify_token(self, token: str, context: grpc.ServicerContext) -> int:
277
+ """Verify the token and return the associated run ID."""
278
+ state = self.state_factory.state()
279
+ run_id = state.get_run_id_by_token(token)
280
+ if run_id is None or not state.verify_token(run_id, token):
281
+ context.abort(
282
+ grpc.StatusCode.PERMISSION_DENIED,
283
+ "Invalid token.",
284
+ )
285
+ raise RuntimeError("This line should never be reached.")
286
+ return run_id
@@ -20,11 +20,7 @@ from typing import Optional, Union
20
20
  import grpc
21
21
 
22
22
  from flwr.common.constant import Status, SubStatus
23
- from flwr.common.inflatable import iterate_object_tree
24
23
  from flwr.common.typing import RunStatus
25
- from flwr.proto.fleet_pb2 import PushMessagesRequest # pylint: disable=E0611
26
- from flwr.proto.message_pb2 import ObjectIDs # pylint: disable=E0611
27
- from flwr.proto.serverappio_pb2 import PushInsMessagesRequest # pylint: disable=E0611
28
24
  from flwr.server.superlink.linkstate import LinkState
29
25
  from flwr.supercore.object_store import ObjectStore
30
26
 
@@ -74,34 +70,3 @@ def abort_if(
74
70
  """Abort context if status of the provided `run_id` is in `abort_status_list`."""
75
71
  msg = check_abort(run_id, abort_status_list, state, store)
76
72
  abort_grpc_context(msg, context)
77
-
78
-
79
- def store_mapping_and_register_objects(
80
- store: ObjectStore, request: Union[PushInsMessagesRequest, PushMessagesRequest]
81
- ) -> dict[str, ObjectIDs]:
82
- """Store Message object to descendants mapping and preregister objects."""
83
- if not request.messages_list:
84
- return {}
85
-
86
- objects_to_push: dict[str, ObjectIDs] = {}
87
-
88
- # Get run_id from the first message in the list
89
- # All messages of a request should in the same run
90
- run_id = request.messages_list[0].metadata.run_id
91
-
92
- for object_tree in request.message_object_trees:
93
- all_object_ids = [obj.object_id for obj in iterate_object_tree(object_tree)]
94
- msg_object_id, descendant_ids = all_object_ids[-1], all_object_ids[:-1]
95
- # Store mapping
96
- store.set_message_descendant_ids(
97
- msg_object_id=msg_object_id, descendant_ids=descendant_ids
98
- )
99
-
100
- # Preregister
101
- object_ids_just_registered = store.preregister(run_id, object_tree)
102
- # Keep track of objects that need to be pushed
103
- objects_to_push[msg_object_id] = ObjectIDs(
104
- object_ids=object_ids_just_registered
105
- )
106
-
107
- return objects_to_push
@@ -13,3 +13,15 @@
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
15
  """Public Flower ServerApp APIs."""
16
+
17
+
18
+ from flwr.server.grid import Grid
19
+ from flwr.server.server_app import ServerApp
20
+
21
+ from . import strategy
22
+
23
+ __all__ = [
24
+ "Grid",
25
+ "ServerApp",
26
+ "strategy",
27
+ ]
@@ -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
@@ -0,0 +1,38 @@
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 ServerApp exceptions."""
16
+
17
+
18
+ from flwr.app.exception import AppExitException
19
+ from flwr.common.exit import ExitCode
20
+
21
+
22
+ class InconsistentMessageReplies(AppExitException):
23
+ """Exception triggered when replies are inconsistent and therefore aggregation must
24
+ be skipped."""
25
+
26
+ exit_code = ExitCode.SERVERAPP_STRATEGY_PRECONDITION_UNMET
27
+
28
+ def __init__(self, reason: str):
29
+ super().__init__(reason)
30
+
31
+
32
+ class AggregationError(AppExitException):
33
+ """Exception triggered when aggregation fails."""
34
+
35
+ exit_code = ExitCode.SERVERAPP_STRATEGY_AGGREGATION_ERROR
36
+
37
+ def __init__(self, reason: str):
38
+ super().__init__(reason)
@@ -0,0 +1,38 @@
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
+ """ServerApp strategies."""
16
+
17
+
18
+ from .dp_fixed_clipping import (
19
+ DifferentialPrivacyClientSideFixedClipping,
20
+ DifferentialPrivacyServerSideFixedClipping,
21
+ )
22
+ from .fedadagrad import FedAdagrad
23
+ from .fedadam import FedAdam
24
+ from .fedavg import FedAvg
25
+ from .fedyogi import FedYogi
26
+ from .result import Result
27
+ from .strategy import Strategy
28
+
29
+ __all__ = [
30
+ "DifferentialPrivacyClientSideFixedClipping",
31
+ "DifferentialPrivacyServerSideFixedClipping",
32
+ "FedAdagrad",
33
+ "FedAdam",
34
+ "FedAvg",
35
+ "FedYogi",
36
+ "Result",
37
+ "Strategy",
38
+ ]