flwr-nightly 1.8.0.dev20240314__py3-none-any.whl → 1.15.0.dev20250114__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (311) hide show
  1. flwr/cli/app.py +16 -2
  2. flwr/cli/build.py +181 -0
  3. flwr/cli/cli_user_auth_interceptor.py +90 -0
  4. flwr/cli/config_utils.py +343 -0
  5. flwr/cli/example.py +4 -1
  6. flwr/cli/install.py +253 -0
  7. flwr/cli/log.py +182 -0
  8. flwr/{server/superlink/state → cli/login}/__init__.py +4 -10
  9. flwr/cli/login/login.py +88 -0
  10. flwr/cli/ls.py +327 -0
  11. flwr/cli/new/__init__.py +1 -0
  12. flwr/cli/new/new.py +210 -66
  13. flwr/cli/new/templates/app/.gitignore.tpl +163 -0
  14. flwr/cli/new/templates/app/LICENSE.tpl +202 -0
  15. flwr/cli/new/templates/app/README.baseline.md.tpl +127 -0
  16. flwr/cli/new/templates/app/README.flowertune.md.tpl +66 -0
  17. flwr/cli/new/templates/app/README.md.tpl +16 -32
  18. flwr/cli/new/templates/app/code/__init__.baseline.py.tpl +1 -0
  19. flwr/cli/new/templates/app/code/__init__.py.tpl +1 -1
  20. flwr/cli/new/templates/app/code/client.baseline.py.tpl +58 -0
  21. flwr/cli/new/templates/app/code/client.huggingface.py.tpl +55 -0
  22. flwr/cli/new/templates/app/code/client.jax.py.tpl +50 -0
  23. flwr/cli/new/templates/app/code/client.mlx.py.tpl +73 -0
  24. flwr/cli/new/templates/app/code/client.numpy.py.tpl +7 -7
  25. flwr/cli/new/templates/app/code/client.pytorch.py.tpl +30 -21
  26. flwr/cli/new/templates/app/code/client.sklearn.py.tpl +63 -0
  27. flwr/cli/new/templates/app/code/client.tensorflow.py.tpl +57 -1
  28. flwr/cli/new/templates/app/code/dataset.baseline.py.tpl +36 -0
  29. flwr/cli/new/templates/app/code/flwr_tune/__init__.py +15 -0
  30. flwr/cli/new/templates/app/code/flwr_tune/client_app.py.tpl +126 -0
  31. flwr/cli/new/templates/app/code/flwr_tune/dataset.py.tpl +87 -0
  32. flwr/cli/new/templates/app/code/flwr_tune/models.py.tpl +78 -0
  33. flwr/cli/new/templates/app/code/flwr_tune/server_app.py.tpl +94 -0
  34. flwr/cli/new/templates/app/code/flwr_tune/strategy.py.tpl +83 -0
  35. flwr/cli/new/templates/app/code/model.baseline.py.tpl +80 -0
  36. flwr/cli/new/templates/app/code/server.baseline.py.tpl +46 -0
  37. flwr/cli/new/templates/app/code/server.huggingface.py.tpl +38 -0
  38. flwr/cli/new/templates/app/code/server.jax.py.tpl +26 -0
  39. flwr/cli/new/templates/app/code/server.mlx.py.tpl +31 -0
  40. flwr/cli/new/templates/app/code/server.numpy.py.tpl +22 -9
  41. flwr/cli/new/templates/app/code/server.pytorch.py.tpl +21 -18
  42. flwr/cli/new/templates/app/code/server.sklearn.py.tpl +36 -0
  43. flwr/cli/new/templates/app/code/server.tensorflow.py.tpl +29 -1
  44. flwr/cli/new/templates/app/code/strategy.baseline.py.tpl +1 -0
  45. flwr/cli/new/templates/app/code/task.huggingface.py.tpl +102 -0
  46. flwr/cli/new/templates/app/code/task.jax.py.tpl +57 -0
  47. flwr/cli/new/templates/app/code/task.mlx.py.tpl +102 -0
  48. flwr/cli/new/templates/app/code/task.numpy.py.tpl +7 -0
  49. flwr/cli/new/templates/app/code/task.pytorch.py.tpl +29 -24
  50. flwr/cli/new/templates/app/code/task.sklearn.py.tpl +67 -0
  51. flwr/cli/new/templates/app/code/task.tensorflow.py.tpl +53 -0
  52. flwr/cli/new/templates/app/code/utils.baseline.py.tpl +1 -0
  53. flwr/cli/new/templates/app/pyproject.baseline.toml.tpl +138 -0
  54. flwr/cli/new/templates/app/pyproject.flowertune.toml.tpl +68 -0
  55. flwr/cli/new/templates/app/pyproject.huggingface.toml.tpl +46 -0
  56. flwr/cli/new/templates/app/pyproject.jax.toml.tpl +35 -0
  57. flwr/cli/new/templates/app/pyproject.mlx.toml.tpl +39 -0
  58. flwr/cli/new/templates/app/pyproject.numpy.toml.tpl +25 -12
  59. flwr/cli/new/templates/app/pyproject.pytorch.toml.tpl +29 -14
  60. flwr/cli/new/templates/app/pyproject.sklearn.toml.tpl +35 -0
  61. flwr/cli/new/templates/app/pyproject.tensorflow.toml.tpl +29 -14
  62. flwr/cli/run/__init__.py +1 -0
  63. flwr/cli/run/run.py +212 -34
  64. flwr/cli/stop.py +130 -0
  65. flwr/cli/utils.py +240 -5
  66. flwr/client/__init__.py +3 -2
  67. flwr/client/app.py +432 -255
  68. flwr/client/client.py +1 -11
  69. flwr/client/client_app.py +74 -13
  70. flwr/client/clientapp/__init__.py +22 -0
  71. flwr/client/clientapp/app.py +259 -0
  72. flwr/client/clientapp/clientappio_servicer.py +244 -0
  73. flwr/client/clientapp/utils.py +115 -0
  74. flwr/client/dpfedavg_numpy_client.py +7 -8
  75. flwr/client/grpc_adapter_client/__init__.py +15 -0
  76. flwr/client/grpc_adapter_client/connection.py +98 -0
  77. flwr/client/grpc_client/connection.py +21 -7
  78. flwr/client/grpc_rere_client/__init__.py +1 -1
  79. flwr/client/grpc_rere_client/client_interceptor.py +176 -0
  80. flwr/client/grpc_rere_client/connection.py +163 -56
  81. flwr/client/grpc_rere_client/grpc_adapter.py +167 -0
  82. flwr/client/heartbeat.py +74 -0
  83. flwr/client/message_handler/__init__.py +1 -1
  84. flwr/client/message_handler/message_handler.py +10 -11
  85. flwr/client/mod/__init__.py +5 -5
  86. flwr/client/mod/centraldp_mods.py +4 -2
  87. flwr/client/mod/comms_mods.py +5 -4
  88. flwr/client/mod/localdp_mod.py +10 -5
  89. flwr/client/mod/secure_aggregation/__init__.py +1 -1
  90. flwr/client/mod/secure_aggregation/secaggplus_mod.py +26 -26
  91. flwr/client/mod/utils.py +2 -4
  92. flwr/client/nodestate/__init__.py +26 -0
  93. flwr/client/nodestate/in_memory_nodestate.py +38 -0
  94. flwr/client/nodestate/nodestate.py +31 -0
  95. flwr/client/nodestate/nodestate_factory.py +38 -0
  96. flwr/client/numpy_client.py +8 -31
  97. flwr/client/rest_client/__init__.py +1 -1
  98. flwr/client/rest_client/connection.py +199 -176
  99. flwr/client/run_info_store.py +112 -0
  100. flwr/client/supernode/__init__.py +24 -0
  101. flwr/client/supernode/app.py +321 -0
  102. flwr/client/typing.py +1 -0
  103. flwr/common/__init__.py +17 -11
  104. flwr/common/address.py +47 -3
  105. flwr/common/args.py +153 -0
  106. flwr/common/auth_plugin/__init__.py +24 -0
  107. flwr/common/auth_plugin/auth_plugin.py +121 -0
  108. flwr/common/config.py +243 -0
  109. flwr/common/constant.py +132 -1
  110. flwr/common/context.py +32 -2
  111. flwr/common/date.py +22 -4
  112. flwr/common/differential_privacy.py +2 -2
  113. flwr/common/dp.py +2 -4
  114. flwr/common/exit_handlers.py +3 -3
  115. flwr/common/grpc.py +164 -5
  116. flwr/common/logger.py +230 -12
  117. flwr/common/message.py +191 -106
  118. flwr/common/object_ref.py +179 -44
  119. flwr/common/pyproject.py +1 -0
  120. flwr/common/record/__init__.py +2 -1
  121. flwr/common/record/configsrecord.py +58 -18
  122. flwr/common/record/metricsrecord.py +57 -17
  123. flwr/common/record/parametersrecord.py +88 -20
  124. flwr/common/record/recordset.py +153 -30
  125. flwr/common/record/typeddict.py +30 -55
  126. flwr/common/recordset_compat.py +31 -12
  127. flwr/common/retry_invoker.py +123 -30
  128. flwr/common/secure_aggregation/__init__.py +1 -1
  129. flwr/common/secure_aggregation/crypto/__init__.py +1 -1
  130. flwr/common/secure_aggregation/crypto/shamir.py +11 -11
  131. flwr/common/secure_aggregation/crypto/symmetric_encryption.py +68 -4
  132. flwr/common/secure_aggregation/ndarrays_arithmetic.py +17 -17
  133. flwr/common/secure_aggregation/quantization.py +8 -8
  134. flwr/common/secure_aggregation/secaggplus_constants.py +1 -1
  135. flwr/common/secure_aggregation/secaggplus_utils.py +10 -12
  136. flwr/common/serde.py +298 -19
  137. flwr/common/telemetry.py +65 -29
  138. flwr/common/typing.py +120 -19
  139. flwr/common/version.py +17 -3
  140. flwr/proto/clientappio_pb2.py +45 -0
  141. flwr/proto/clientappio_pb2.pyi +132 -0
  142. flwr/proto/clientappio_pb2_grpc.py +135 -0
  143. flwr/proto/clientappio_pb2_grpc.pyi +53 -0
  144. flwr/proto/exec_pb2.py +62 -0
  145. flwr/proto/exec_pb2.pyi +212 -0
  146. flwr/proto/exec_pb2_grpc.py +237 -0
  147. flwr/proto/exec_pb2_grpc.pyi +93 -0
  148. flwr/proto/fab_pb2.py +31 -0
  149. flwr/proto/fab_pb2.pyi +65 -0
  150. flwr/proto/fab_pb2_grpc.py +4 -0
  151. flwr/proto/fab_pb2_grpc.pyi +4 -0
  152. flwr/proto/fleet_pb2.py +42 -23
  153. flwr/proto/fleet_pb2.pyi +123 -1
  154. flwr/proto/fleet_pb2_grpc.py +170 -0
  155. flwr/proto/fleet_pb2_grpc.pyi +61 -0
  156. flwr/proto/grpcadapter_pb2.py +32 -0
  157. flwr/proto/grpcadapter_pb2.pyi +43 -0
  158. flwr/proto/grpcadapter_pb2_grpc.py +66 -0
  159. flwr/proto/grpcadapter_pb2_grpc.pyi +24 -0
  160. flwr/proto/log_pb2.py +29 -0
  161. flwr/proto/log_pb2.pyi +39 -0
  162. flwr/proto/log_pb2_grpc.py +4 -0
  163. flwr/proto/log_pb2_grpc.pyi +4 -0
  164. flwr/proto/message_pb2.py +41 -0
  165. flwr/proto/message_pb2.pyi +128 -0
  166. flwr/proto/message_pb2_grpc.py +4 -0
  167. flwr/proto/message_pb2_grpc.pyi +4 -0
  168. flwr/proto/node_pb2.py +1 -1
  169. flwr/proto/recordset_pb2.py +35 -33
  170. flwr/proto/recordset_pb2.pyi +40 -14
  171. flwr/proto/run_pb2.py +64 -0
  172. flwr/proto/run_pb2.pyi +268 -0
  173. flwr/proto/run_pb2_grpc.py +4 -0
  174. flwr/proto/run_pb2_grpc.pyi +4 -0
  175. flwr/proto/serverappio_pb2.py +52 -0
  176. flwr/proto/{driver_pb2.pyi → serverappio_pb2.pyi} +62 -20
  177. flwr/proto/serverappio_pb2_grpc.py +410 -0
  178. flwr/proto/serverappio_pb2_grpc.pyi +160 -0
  179. flwr/proto/simulationio_pb2.py +38 -0
  180. flwr/proto/simulationio_pb2.pyi +65 -0
  181. flwr/proto/simulationio_pb2_grpc.py +239 -0
  182. flwr/proto/simulationio_pb2_grpc.pyi +94 -0
  183. flwr/proto/task_pb2.py +7 -8
  184. flwr/proto/task_pb2.pyi +8 -5
  185. flwr/proto/transport_pb2.py +8 -8
  186. flwr/proto/transport_pb2.pyi +9 -6
  187. flwr/server/__init__.py +2 -10
  188. flwr/server/app.py +579 -402
  189. flwr/server/client_manager.py +8 -6
  190. flwr/server/compat/app.py +6 -62
  191. flwr/server/compat/app_utils.py +14 -8
  192. flwr/server/compat/driver_client_proxy.py +25 -58
  193. flwr/server/compat/legacy_context.py +5 -4
  194. flwr/server/driver/__init__.py +2 -0
  195. flwr/server/driver/driver.py +36 -131
  196. flwr/server/driver/grpc_driver.py +217 -81
  197. flwr/server/driver/inmemory_driver.py +182 -0
  198. flwr/server/history.py +28 -29
  199. flwr/server/run_serverapp.py +15 -126
  200. flwr/server/server.py +50 -44
  201. flwr/server/server_app.py +59 -10
  202. flwr/server/serverapp/__init__.py +22 -0
  203. flwr/server/serverapp/app.py +256 -0
  204. flwr/server/serverapp_components.py +52 -0
  205. flwr/server/strategy/__init__.py +2 -2
  206. flwr/server/strategy/aggregate.py +37 -23
  207. flwr/server/strategy/bulyan.py +9 -9
  208. flwr/server/strategy/dp_adaptive_clipping.py +25 -25
  209. flwr/server/strategy/dp_fixed_clipping.py +23 -22
  210. flwr/server/strategy/dpfedavg_adaptive.py +8 -8
  211. flwr/server/strategy/dpfedavg_fixed.py +13 -12
  212. flwr/server/strategy/fault_tolerant_fedavg.py +11 -11
  213. flwr/server/strategy/fedadagrad.py +9 -9
  214. flwr/server/strategy/fedadam.py +20 -10
  215. flwr/server/strategy/fedavg.py +16 -16
  216. flwr/server/strategy/fedavg_android.py +17 -17
  217. flwr/server/strategy/fedavgm.py +9 -9
  218. flwr/server/strategy/fedmedian.py +5 -5
  219. flwr/server/strategy/fedopt.py +6 -6
  220. flwr/server/strategy/fedprox.py +7 -7
  221. flwr/server/strategy/fedtrimmedavg.py +8 -8
  222. flwr/server/strategy/fedxgb_bagging.py +12 -12
  223. flwr/server/strategy/fedxgb_cyclic.py +10 -10
  224. flwr/server/strategy/fedxgb_nn_avg.py +6 -6
  225. flwr/server/strategy/fedyogi.py +9 -9
  226. flwr/server/strategy/krum.py +9 -9
  227. flwr/server/strategy/qfedavg.py +16 -16
  228. flwr/server/strategy/strategy.py +10 -10
  229. flwr/server/superlink/driver/__init__.py +2 -2
  230. flwr/server/superlink/driver/serverappio_grpc.py +61 -0
  231. flwr/server/superlink/driver/serverappio_servicer.py +363 -0
  232. flwr/server/superlink/ffs/__init__.py +24 -0
  233. flwr/server/superlink/ffs/disk_ffs.py +108 -0
  234. flwr/server/superlink/ffs/ffs.py +79 -0
  235. flwr/server/superlink/ffs/ffs_factory.py +47 -0
  236. flwr/server/superlink/fleet/__init__.py +1 -1
  237. flwr/server/superlink/fleet/grpc_adapter/__init__.py +15 -0
  238. flwr/server/superlink/fleet/grpc_adapter/grpc_adapter_servicer.py +162 -0
  239. flwr/server/superlink/fleet/grpc_bidi/__init__.py +1 -1
  240. flwr/server/superlink/fleet/grpc_bidi/flower_service_servicer.py +4 -2
  241. flwr/server/superlink/fleet/grpc_bidi/grpc_bridge.py +3 -2
  242. flwr/server/superlink/fleet/grpc_bidi/grpc_client_proxy.py +1 -1
  243. flwr/server/superlink/fleet/grpc_bidi/grpc_server.py +5 -154
  244. flwr/server/superlink/fleet/grpc_rere/__init__.py +1 -1
  245. flwr/server/superlink/fleet/grpc_rere/fleet_servicer.py +120 -13
  246. flwr/server/superlink/fleet/grpc_rere/server_interceptor.py +228 -0
  247. flwr/server/superlink/fleet/message_handler/__init__.py +1 -1
  248. flwr/server/superlink/fleet/message_handler/message_handler.py +153 -9
  249. flwr/server/superlink/fleet/rest_rere/__init__.py +1 -1
  250. flwr/server/superlink/fleet/rest_rere/rest_api.py +119 -81
  251. flwr/server/superlink/fleet/vce/__init__.py +1 -0
  252. flwr/server/superlink/fleet/vce/backend/__init__.py +4 -4
  253. flwr/server/superlink/fleet/vce/backend/backend.py +8 -9
  254. flwr/server/superlink/fleet/vce/backend/raybackend.py +87 -68
  255. flwr/server/superlink/fleet/vce/vce_api.py +208 -146
  256. flwr/server/superlink/linkstate/__init__.py +28 -0
  257. flwr/server/superlink/linkstate/in_memory_linkstate.py +581 -0
  258. flwr/server/superlink/linkstate/linkstate.py +389 -0
  259. flwr/server/superlink/{state/state_factory.py → linkstate/linkstate_factory.py} +19 -10
  260. flwr/server/superlink/linkstate/sqlite_linkstate.py +1236 -0
  261. flwr/server/superlink/linkstate/utils.py +389 -0
  262. flwr/server/superlink/simulation/__init__.py +15 -0
  263. flwr/server/superlink/simulation/simulationio_grpc.py +65 -0
  264. flwr/server/superlink/simulation/simulationio_servicer.py +186 -0
  265. flwr/server/superlink/utils.py +65 -0
  266. flwr/server/typing.py +2 -0
  267. flwr/server/utils/__init__.py +1 -1
  268. flwr/server/utils/tensorboard.py +5 -5
  269. flwr/server/utils/validator.py +31 -11
  270. flwr/server/workflow/default_workflows.py +70 -26
  271. flwr/server/workflow/secure_aggregation/secagg_workflow.py +1 -0
  272. flwr/server/workflow/secure_aggregation/secaggplus_workflow.py +40 -27
  273. flwr/simulation/__init__.py +12 -5
  274. flwr/simulation/app.py +247 -315
  275. flwr/simulation/legacy_app.py +402 -0
  276. flwr/simulation/ray_transport/__init__.py +1 -1
  277. flwr/simulation/ray_transport/ray_actor.py +42 -67
  278. flwr/simulation/ray_transport/ray_client_proxy.py +37 -17
  279. flwr/simulation/ray_transport/utils.py +1 -0
  280. flwr/simulation/run_simulation.py +306 -163
  281. flwr/simulation/simulationio_connection.py +89 -0
  282. flwr/superexec/__init__.py +15 -0
  283. flwr/superexec/app.py +59 -0
  284. flwr/superexec/deployment.py +188 -0
  285. flwr/superexec/exec_grpc.py +80 -0
  286. flwr/superexec/exec_servicer.py +231 -0
  287. flwr/superexec/exec_user_auth_interceptor.py +101 -0
  288. flwr/superexec/executor.py +96 -0
  289. flwr/superexec/simulation.py +124 -0
  290. {flwr_nightly-1.8.0.dev20240314.dist-info → flwr_nightly-1.15.0.dev20250114.dist-info}/METADATA +33 -26
  291. flwr_nightly-1.15.0.dev20250114.dist-info/RECORD +328 -0
  292. flwr_nightly-1.15.0.dev20250114.dist-info/entry_points.txt +12 -0
  293. flwr/cli/flower_toml.py +0 -140
  294. flwr/cli/new/templates/app/flower.toml.tpl +0 -13
  295. flwr/cli/new/templates/app/requirements.numpy.txt.tpl +0 -2
  296. flwr/cli/new/templates/app/requirements.pytorch.txt.tpl +0 -4
  297. flwr/cli/new/templates/app/requirements.tensorflow.txt.tpl +0 -4
  298. flwr/client/node_state.py +0 -48
  299. flwr/client/node_state_tests.py +0 -65
  300. flwr/proto/driver_pb2.py +0 -44
  301. flwr/proto/driver_pb2_grpc.py +0 -169
  302. flwr/proto/driver_pb2_grpc.pyi +0 -66
  303. flwr/server/superlink/driver/driver_grpc.py +0 -54
  304. flwr/server/superlink/driver/driver_servicer.py +0 -129
  305. flwr/server/superlink/state/in_memory_state.py +0 -230
  306. flwr/server/superlink/state/sqlite_state.py +0 -630
  307. flwr/server/superlink/state/state.py +0 -154
  308. flwr_nightly-1.8.0.dev20240314.dist-info/RECORD +0 -211
  309. flwr_nightly-1.8.0.dev20240314.dist-info/entry_points.txt +0 -9
  310. {flwr_nightly-1.8.0.dev20240314.dist-info → flwr_nightly-1.15.0.dev20250114.dist-info}/LICENSE +0 -0
  311. {flwr_nightly-1.8.0.dev20240314.dist-info → flwr_nightly-1.15.0.dev20250114.dist-info}/WHEEL +0 -0
@@ -1,4 +1,4 @@
1
- # Copyright 2023 Flower Labs GmbH. All Rights Reserved.
1
+ # Copyright 2024 Flower Labs GmbH. All Rights Reserved.
2
2
  #
3
3
  # Licensed under the Apache License, Version 2.0 (the "License");
4
4
  # you may not use this file except in compliance with the License.
@@ -12,20 +12,27 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
- """Flower driver service client."""
15
+ """Flower gRPC Driver."""
16
16
 
17
17
 
18
- from logging import DEBUG, ERROR, WARNING
19
- from typing import Optional
18
+ import time
19
+ import warnings
20
+ from collections.abc import Iterable
21
+ from logging import DEBUG, WARNING
22
+ from typing import Optional, cast
20
23
 
21
24
  import grpc
22
25
 
23
- from flwr.common import EventType, event
26
+ from flwr.common import DEFAULT_TTL, Message, Metadata, RecordSet
27
+ from flwr.common.constant import SERVERAPPIO_API_DEFAULT_CLIENT_ADDRESS
24
28
  from flwr.common.grpc import create_channel
25
29
  from flwr.common.logger import log
26
- from flwr.proto.driver_pb2 import ( # pylint: disable=E0611
27
- CreateRunRequest,
28
- CreateRunResponse,
30
+ from flwr.common.retry_invoker import _make_simple_grpc_retry_invoker, _wrap_stub
31
+ from flwr.common.serde import message_from_taskres, message_to_taskins, run_from_proto
32
+ from flwr.common.typing import Run
33
+ from flwr.proto.node_pb2 import Node # pylint: disable=E0611
34
+ from flwr.proto.run_pb2 import GetRunRequest, GetRunResponse # pylint: disable=E0611
35
+ from flwr.proto.serverappio_pb2 import ( # pylint: disable=E0611
29
36
  GetNodesRequest,
30
37
  GetNodesResponse,
31
38
  PullTaskResRequest,
@@ -33,97 +40,226 @@ from flwr.proto.driver_pb2 import ( # pylint: disable=E0611
33
40
  PushTaskInsRequest,
34
41
  PushTaskInsResponse,
35
42
  )
36
- from flwr.proto.driver_pb2_grpc import DriverStub # pylint: disable=E0611
43
+ from flwr.proto.serverappio_pb2_grpc import ServerAppIoStub # pylint: disable=E0611
44
+ from flwr.proto.task_pb2 import TaskIns # pylint: disable=E0611
37
45
 
38
- DEFAULT_SERVER_ADDRESS_DRIVER = "[::]:9091"
46
+ from .driver import Driver
39
47
 
40
48
  ERROR_MESSAGE_DRIVER_NOT_CONNECTED = """
41
49
  [Driver] Error: Not connected.
42
50
 
43
- Call `connect()` on the `GrpcDriver` instance before calling any of the other
44
- `GrpcDriver` methods.
51
+ Call `connect()` on the `GrpcDriverStub` instance before calling any of the other
52
+ `GrpcDriverStub` methods.
45
53
  """
46
54
 
47
55
 
48
- class GrpcDriver:
49
- """`GrpcDriver` provides access to the gRPC Driver API/service."""
56
+ class GrpcDriver(Driver):
57
+ """`GrpcDriver` provides an interface to the ServerAppIo API.
50
58
 
51
- def __init__(
59
+ Parameters
60
+ ----------
61
+ serverappio_service_address : str (default: "[::]:9091")
62
+ The address (URL, IPv6, IPv4) of the SuperLink ServerAppIo API service.
63
+ root_certificates : Optional[bytes] (default: None)
64
+ The PEM-encoded root certificates as a byte string.
65
+ If provided, a secure connection using the certificates will be
66
+ established to an SSL-enabled Flower server.
67
+ """
68
+
69
+ def __init__( # pylint: disable=too-many-arguments
52
70
  self,
53
- driver_service_address: str = DEFAULT_SERVER_ADDRESS_DRIVER,
71
+ serverappio_service_address: str = SERVERAPPIO_API_DEFAULT_CLIENT_ADDRESS,
54
72
  root_certificates: Optional[bytes] = None,
55
73
  ) -> None:
56
- self.driver_service_address = driver_service_address
57
- self.root_certificates = root_certificates
58
- self.channel: Optional[grpc.Channel] = None
59
- self.stub: Optional[DriverStub] = None
60
-
61
- def connect(self) -> None:
62
- """Connect to the Driver API."""
63
- event(EventType.DRIVER_CONNECT)
64
- if self.channel is not None or self.stub is not None:
74
+ self._addr = serverappio_service_address
75
+ self._cert = root_certificates
76
+ self._run: Optional[Run] = None
77
+ self._grpc_stub: Optional[ServerAppIoStub] = None
78
+ self._channel: Optional[grpc.Channel] = None
79
+ self.node = Node(node_id=0, anonymous=True)
80
+ self._retry_invoker = _make_simple_grpc_retry_invoker()
81
+
82
+ @property
83
+ def _is_connected(self) -> bool:
84
+ """Check if connected to the ServerAppIo API server."""
85
+ return self._channel is not None
86
+
87
+ def _connect(self) -> None:
88
+ """Connect to the ServerAppIo API.
89
+
90
+ This will not call GetRun.
91
+ """
92
+ if self._is_connected:
65
93
  log(WARNING, "Already connected")
66
94
  return
67
- self.channel = create_channel(
68
- server_address=self.driver_service_address,
69
- insecure=(self.root_certificates is None),
70
- root_certificates=self.root_certificates,
95
+ self._channel = create_channel(
96
+ server_address=self._addr,
97
+ insecure=(self._cert is None),
98
+ root_certificates=self._cert,
71
99
  )
72
- self.stub = DriverStub(self.channel)
73
- log(DEBUG, "[Driver] Connected to %s", self.driver_service_address)
100
+ self._grpc_stub = ServerAppIoStub(self._channel)
101
+ _wrap_stub(self._grpc_stub, self._retry_invoker)
102
+ log(DEBUG, "[Driver] Connected to %s", self._addr)
74
103
 
75
- def disconnect(self) -> None:
76
- """Disconnect from the Driver API."""
77
- event(EventType.DRIVER_DISCONNECT)
78
- if self.channel is None or self.stub is None:
104
+ def _disconnect(self) -> None:
105
+ """Disconnect from the ServerAppIo API."""
106
+ if not self._is_connected:
79
107
  log(DEBUG, "Already disconnected")
80
108
  return
81
- channel = self.channel
82
- self.channel = None
83
- self.stub = None
109
+ channel: grpc.Channel = self._channel
110
+ self._channel = None
111
+ self._grpc_stub = None
84
112
  channel.close()
85
113
  log(DEBUG, "[Driver] Disconnected")
86
114
 
87
- def create_run(self, req: CreateRunRequest) -> CreateRunResponse:
88
- """Request for run ID."""
89
- # Check if channel is open
90
- if self.stub is None:
91
- log(ERROR, ERROR_MESSAGE_DRIVER_NOT_CONNECTED)
92
- raise ConnectionError("`GrpcDriver` instance not connected")
93
-
94
- # Call Driver API
95
- res: CreateRunResponse = self.stub.CreateRun(request=req)
96
- return res
97
-
98
- def get_nodes(self, req: GetNodesRequest) -> GetNodesResponse:
99
- """Get client IDs."""
100
- # Check if channel is open
101
- if self.stub is None:
102
- log(ERROR, ERROR_MESSAGE_DRIVER_NOT_CONNECTED)
103
- raise ConnectionError("`GrpcDriver` instance not connected")
104
-
105
- # Call gRPC Driver API
106
- res: GetNodesResponse = self.stub.GetNodes(request=req)
107
- return res
108
-
109
- def push_task_ins(self, req: PushTaskInsRequest) -> PushTaskInsResponse:
110
- """Schedule tasks."""
111
- # Check if channel is open
112
- if self.stub is None:
113
- log(ERROR, ERROR_MESSAGE_DRIVER_NOT_CONNECTED)
114
- raise ConnectionError("`GrpcDriver` instance not connected")
115
-
116
- # Call gRPC Driver API
117
- res: PushTaskInsResponse = self.stub.PushTaskIns(request=req)
118
- return res
119
-
120
- def pull_task_res(self, req: PullTaskResRequest) -> PullTaskResResponse:
121
- """Get task results."""
122
- # Check if channel is open
123
- if self.stub is None:
124
- log(ERROR, ERROR_MESSAGE_DRIVER_NOT_CONNECTED)
125
- raise ConnectionError("`GrpcDriver` instance not connected")
126
-
127
- # Call Driver API
128
- res: PullTaskResResponse = self.stub.PullTaskRes(request=req)
129
- return res
115
+ def set_run(self, run_id: int) -> None:
116
+ """Set the run."""
117
+ # Get the run info
118
+ req = GetRunRequest(run_id=run_id)
119
+ res: GetRunResponse = self._stub.GetRun(req)
120
+ if not res.HasField("run"):
121
+ raise RuntimeError(f"Cannot find the run with ID: {run_id}")
122
+ self._run = run_from_proto(res.run)
123
+
124
+ @property
125
+ def run(self) -> Run:
126
+ """Run information."""
127
+ return Run(**vars(self._run))
128
+
129
+ @property
130
+ def _stub(self) -> ServerAppIoStub:
131
+ """ServerAppIo stub."""
132
+ if not self._is_connected:
133
+ self._connect()
134
+ return cast(ServerAppIoStub, self._grpc_stub)
135
+
136
+ def _check_message(self, message: Message) -> None:
137
+ # Check if the message is valid
138
+ if not (
139
+ # Assume self._run being initialized
140
+ message.metadata.run_id == cast(Run, self._run).run_id
141
+ and message.metadata.src_node_id == self.node.node_id
142
+ and message.metadata.message_id == ""
143
+ and message.metadata.reply_to_message == ""
144
+ and message.metadata.ttl > 0
145
+ ):
146
+ raise ValueError(f"Invalid message: {message}")
147
+
148
+ def create_message( # pylint: disable=too-many-arguments,R0917
149
+ self,
150
+ content: RecordSet,
151
+ message_type: str,
152
+ dst_node_id: int,
153
+ group_id: str,
154
+ ttl: Optional[float] = None,
155
+ ) -> Message:
156
+ """Create a new message with specified parameters.
157
+
158
+ This method constructs a new `Message` with given content and metadata.
159
+ The `run_id` and `src_node_id` will be set automatically.
160
+ """
161
+ if ttl:
162
+ warnings.warn(
163
+ "A custom TTL was set, but note that the SuperLink does not enforce "
164
+ "the TTL yet. The SuperLink will start enforcing the TTL in a future "
165
+ "version of Flower.",
166
+ stacklevel=2,
167
+ )
168
+
169
+ ttl_ = DEFAULT_TTL if ttl is None else ttl
170
+ metadata = Metadata(
171
+ run_id=cast(Run, self._run).run_id,
172
+ message_id="", # Will be set by the server
173
+ src_node_id=self.node.node_id,
174
+ dst_node_id=dst_node_id,
175
+ reply_to_message="",
176
+ group_id=group_id,
177
+ ttl=ttl_,
178
+ message_type=message_type,
179
+ )
180
+ return Message(metadata=metadata, content=content)
181
+
182
+ def get_node_ids(self) -> list[int]:
183
+ """Get node IDs."""
184
+ # Call GrpcDriverStub method
185
+ res: GetNodesResponse = self._stub.GetNodes(
186
+ GetNodesRequest(run_id=cast(Run, self._run).run_id)
187
+ )
188
+ return [node.node_id for node in res.nodes]
189
+
190
+ def push_messages(self, messages: Iterable[Message]) -> Iterable[str]:
191
+ """Push messages to specified node IDs.
192
+
193
+ This method takes an iterable of messages and sends each message
194
+ to the node specified in `dst_node_id`.
195
+ """
196
+ # Construct TaskIns
197
+ task_ins_list: list[TaskIns] = []
198
+ for msg in messages:
199
+ # Check message
200
+ self._check_message(msg)
201
+ # Convert Message to TaskIns
202
+ taskins = message_to_taskins(msg)
203
+ # Add to list
204
+ task_ins_list.append(taskins)
205
+ # Call GrpcDriverStub method
206
+ res: PushTaskInsResponse = self._stub.PushTaskIns(
207
+ PushTaskInsRequest(
208
+ task_ins_list=task_ins_list, run_id=cast(Run, self._run).run_id
209
+ )
210
+ )
211
+ return list(res.task_ids)
212
+
213
+ def pull_messages(self, message_ids: Iterable[str]) -> Iterable[Message]:
214
+ """Pull messages based on message IDs.
215
+
216
+ This method is used to collect messages from the SuperLink that correspond to a
217
+ set of given message IDs.
218
+ """
219
+ # Pull TaskRes
220
+ res: PullTaskResResponse = self._stub.PullTaskRes(
221
+ PullTaskResRequest(
222
+ node=self.node, task_ids=message_ids, run_id=cast(Run, self._run).run_id
223
+ )
224
+ )
225
+ # Convert TaskRes to Message
226
+ msgs = [message_from_taskres(taskres) for taskres in res.task_res_list]
227
+ return msgs
228
+
229
+ def send_and_receive(
230
+ self,
231
+ messages: Iterable[Message],
232
+ *,
233
+ timeout: Optional[float] = None,
234
+ ) -> Iterable[Message]:
235
+ """Push messages to specified node IDs and pull the reply messages.
236
+
237
+ This method sends a list of messages to their destination node IDs and then
238
+ waits for the replies. It continues to pull replies until either all replies are
239
+ received or the specified timeout duration is exceeded.
240
+ """
241
+ # Push messages
242
+ msg_ids = set(self.push_messages(messages))
243
+
244
+ # Pull messages
245
+ end_time = time.time() + (timeout if timeout is not None else 0.0)
246
+ ret: list[Message] = []
247
+ while timeout is None or time.time() < end_time:
248
+ res_msgs = self.pull_messages(msg_ids)
249
+ ret.extend(res_msgs)
250
+ msg_ids.difference_update(
251
+ {msg.metadata.reply_to_message for msg in res_msgs}
252
+ )
253
+ if len(msg_ids) == 0:
254
+ break
255
+ # Sleep
256
+ time.sleep(3)
257
+ return ret
258
+
259
+ def close(self) -> None:
260
+ """Disconnect from the SuperLink if connected."""
261
+ # Check if `connect` was called before
262
+ if not self._is_connected:
263
+ return
264
+ # Disconnect
265
+ self._disconnect()
@@ -0,0 +1,182 @@
1
+ # Copyright 2024 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 in-memory Driver."""
16
+
17
+
18
+ import time
19
+ import warnings
20
+ from collections.abc import Iterable
21
+ from typing import Optional, cast
22
+ from uuid import UUID
23
+
24
+ from flwr.common import DEFAULT_TTL, Message, Metadata, RecordSet
25
+ from flwr.common.serde import message_from_taskres, message_to_taskins
26
+ from flwr.common.typing import Run
27
+ from flwr.proto.node_pb2 import Node # pylint: disable=E0611
28
+ from flwr.server.superlink.linkstate import LinkStateFactory
29
+
30
+ from .driver import Driver
31
+
32
+
33
+ class InMemoryDriver(Driver):
34
+ """`InMemoryDriver` class provides an interface to the ServerAppIo API.
35
+
36
+ Parameters
37
+ ----------
38
+ state_factory : StateFactory
39
+ A StateFactory embedding a state that this driver can interface with.
40
+ pull_interval : float (default=0.1)
41
+ Sleep duration between calls to `pull_messages`.
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ state_factory: LinkStateFactory,
47
+ pull_interval: float = 0.1,
48
+ ) -> None:
49
+ self._run: Optional[Run] = None
50
+ self.state = state_factory.state()
51
+ self.pull_interval = pull_interval
52
+ self.node = Node(node_id=0, anonymous=True)
53
+
54
+ def _check_message(self, message: Message) -> None:
55
+ # Check if the message is valid
56
+ if not (
57
+ message.metadata.run_id == cast(Run, self._run).run_id
58
+ and message.metadata.src_node_id == self.node.node_id
59
+ and message.metadata.message_id == ""
60
+ and message.metadata.reply_to_message == ""
61
+ and message.metadata.ttl > 0
62
+ ):
63
+ raise ValueError(f"Invalid message: {message}")
64
+
65
+ def set_run(self, run_id: int) -> None:
66
+ """Initialize the run."""
67
+ run = self.state.get_run(run_id)
68
+ if run is None:
69
+ raise RuntimeError(f"Cannot find the run with ID: {run_id}")
70
+ self._run = run
71
+
72
+ @property
73
+ def run(self) -> Run:
74
+ """Run ID."""
75
+ return Run(**vars(cast(Run, self._run)))
76
+
77
+ def create_message( # pylint: disable=too-many-arguments,R0917
78
+ self,
79
+ content: RecordSet,
80
+ message_type: str,
81
+ dst_node_id: int,
82
+ group_id: str,
83
+ ttl: Optional[float] = None,
84
+ ) -> Message:
85
+ """Create a new message with specified parameters.
86
+
87
+ This method constructs a new `Message` with given content and metadata.
88
+ The `run_id` and `src_node_id` will be set automatically.
89
+ """
90
+ if ttl:
91
+ warnings.warn(
92
+ "A custom TTL was set, but note that the SuperLink does not enforce "
93
+ "the TTL yet. The SuperLink will start enforcing the TTL in a future "
94
+ "version of Flower.",
95
+ stacklevel=2,
96
+ )
97
+ ttl_ = DEFAULT_TTL if ttl is None else ttl
98
+
99
+ metadata = Metadata(
100
+ run_id=cast(Run, self._run).run_id,
101
+ message_id="", # Will be set by the server
102
+ src_node_id=self.node.node_id,
103
+ dst_node_id=dst_node_id,
104
+ reply_to_message="",
105
+ group_id=group_id,
106
+ ttl=ttl_,
107
+ message_type=message_type,
108
+ )
109
+ return Message(metadata=metadata, content=content)
110
+
111
+ def get_node_ids(self) -> list[int]:
112
+ """Get node IDs."""
113
+ return list(self.state.get_nodes(cast(Run, self._run).run_id))
114
+
115
+ def push_messages(self, messages: Iterable[Message]) -> Iterable[str]:
116
+ """Push messages to specified node IDs.
117
+
118
+ This method takes an iterable of messages and sends each message
119
+ to the node specified in `dst_node_id`.
120
+ """
121
+ task_ids: list[str] = []
122
+ for msg in messages:
123
+ # Check message
124
+ self._check_message(msg)
125
+ # Convert Message to TaskIns
126
+ taskins = message_to_taskins(msg)
127
+ # Store in state
128
+ taskins.task.pushed_at = time.time()
129
+ task_id = self.state.store_task_ins(taskins)
130
+ if task_id:
131
+ task_ids.append(str(task_id))
132
+
133
+ return task_ids
134
+
135
+ def pull_messages(self, message_ids: Iterable[str]) -> Iterable[Message]:
136
+ """Pull messages based on message IDs.
137
+
138
+ This method is used to collect messages from the SuperLink that correspond to a
139
+ set of given message IDs.
140
+ """
141
+ msg_ids = {UUID(msg_id) for msg_id in message_ids}
142
+ # Pull TaskRes
143
+ task_res_list = self.state.get_task_res(task_ids=msg_ids)
144
+ # Delete tasks in state
145
+ # Delete the TaskIns/TaskRes pairs if TaskRes is found
146
+ task_ins_ids_to_delete = {
147
+ UUID(task_res.task.ancestry[0]) for task_res in task_res_list
148
+ }
149
+ self.state.delete_tasks(task_ins_ids=task_ins_ids_to_delete)
150
+ # Convert TaskRes to Message
151
+ msgs = [message_from_taskres(taskres) for taskres in task_res_list]
152
+ return msgs
153
+
154
+ def send_and_receive(
155
+ self,
156
+ messages: Iterable[Message],
157
+ *,
158
+ timeout: Optional[float] = None,
159
+ ) -> Iterable[Message]:
160
+ """Push messages to specified node IDs and pull the reply messages.
161
+
162
+ This method sends a list of messages to their destination node IDs and then
163
+ waits for the replies. It continues to pull replies until either all replies are
164
+ received or the specified timeout duration is exceeded.
165
+ """
166
+ # Push messages
167
+ msg_ids = set(self.push_messages(messages))
168
+
169
+ # Pull messages
170
+ end_time = time.time() + (timeout if timeout is not None else 0.0)
171
+ ret: list[Message] = []
172
+ while timeout is None or time.time() < end_time:
173
+ res_msgs = self.pull_messages(msg_ids)
174
+ ret.extend(res_msgs)
175
+ msg_ids.difference_update(
176
+ {msg.metadata.reply_to_message for msg in res_msgs}
177
+ )
178
+ if len(msg_ids) == 0:
179
+ break
180
+ # Sleep
181
+ time.sleep(self.pull_interval)
182
+ return ret
flwr/server/history.py CHANGED
@@ -17,7 +17,6 @@
17
17
 
18
18
  import pprint
19
19
  from functools import reduce
20
- from typing import Dict, List, Tuple
21
20
 
22
21
  from flwr.common.typing import Scalar
23
22
 
@@ -26,11 +25,11 @@ class History:
26
25
  """History class for training and/or evaluation metrics collection."""
27
26
 
28
27
  def __init__(self) -> None:
29
- self.losses_distributed: List[Tuple[int, float]] = []
30
- self.losses_centralized: List[Tuple[int, float]] = []
31
- self.metrics_distributed_fit: Dict[str, List[Tuple[int, Scalar]]] = {}
32
- self.metrics_distributed: Dict[str, List[Tuple[int, Scalar]]] = {}
33
- self.metrics_centralized: Dict[str, List[Tuple[int, Scalar]]] = {}
28
+ self.losses_distributed: list[tuple[int, float]] = []
29
+ self.losses_centralized: list[tuple[int, float]] = []
30
+ self.metrics_distributed_fit: dict[str, list[tuple[int, Scalar]]] = {}
31
+ self.metrics_distributed: dict[str, list[tuple[int, Scalar]]] = {}
32
+ self.metrics_centralized: dict[str, list[tuple[int, Scalar]]] = {}
34
33
 
35
34
  def add_loss_distributed(self, server_round: int, loss: float) -> None:
36
35
  """Add one loss entry (from distributed evaluation)."""
@@ -41,7 +40,7 @@ class History:
41
40
  self.losses_centralized.append((server_round, loss))
42
41
 
43
42
  def add_metrics_distributed_fit(
44
- self, server_round: int, metrics: Dict[str, Scalar]
43
+ self, server_round: int, metrics: dict[str, Scalar]
45
44
  ) -> None:
46
45
  """Add metrics entries (from distributed fit)."""
47
46
  for key in metrics:
@@ -52,7 +51,7 @@ class History:
52
51
  self.metrics_distributed_fit[key].append((server_round, metrics[key]))
53
52
 
54
53
  def add_metrics_distributed(
55
- self, server_round: int, metrics: Dict[str, Scalar]
54
+ self, server_round: int, metrics: dict[str, Scalar]
56
55
  ) -> None:
57
56
  """Add metrics entries (from distributed evaluation)."""
58
57
  for key in metrics:
@@ -63,7 +62,7 @@ class History:
63
62
  self.metrics_distributed[key].append((server_round, metrics[key]))
64
63
 
65
64
  def add_metrics_centralized(
66
- self, server_round: int, metrics: Dict[str, Scalar]
65
+ self, server_round: int, metrics: dict[str, Scalar]
67
66
  ) -> None:
68
67
  """Add metrics entries (from centralized evaluation)."""
69
68
  for key in metrics:
@@ -91,32 +90,32 @@ class History:
91
90
  """
92
91
  rep = ""
93
92
  if self.losses_distributed:
94
- rep += "History (loss, distributed):\n" + pprint.pformat(
95
- reduce(
96
- lambda a, b: a + b,
97
- [
98
- f"\tround {server_round}: {loss}\n"
99
- for server_round, loss in self.losses_distributed
100
- ],
101
- )
93
+ rep += "History (loss, distributed):\n" + reduce(
94
+ lambda a, b: a + b,
95
+ [
96
+ f"\tround {server_round}: {loss}\n"
97
+ for server_round, loss in self.losses_distributed
98
+ ],
102
99
  )
103
100
  if self.losses_centralized:
104
- rep += "History (loss, centralized):\n" + pprint.pformat(
105
- reduce(
106
- lambda a, b: a + b,
107
- [
108
- f"\tround {server_round}: {loss}\n"
109
- for server_round, loss in self.losses_centralized
110
- ],
111
- )
101
+ rep += "History (loss, centralized):\n" + reduce(
102
+ lambda a, b: a + b,
103
+ [
104
+ f"\tround {server_round}: {loss}\n"
105
+ for server_round, loss in self.losses_centralized
106
+ ],
112
107
  )
113
108
  if self.metrics_distributed_fit:
114
- rep += "History (metrics, distributed, fit):\n" + pprint.pformat(
115
- self.metrics_distributed_fit
109
+ rep += (
110
+ "History (metrics, distributed, fit):\n"
111
+ + pprint.pformat(self.metrics_distributed_fit)
112
+ + "\n"
116
113
  )
117
114
  if self.metrics_distributed:
118
- rep += "History (metrics, distributed, evaluate):\n" + pprint.pformat(
119
- self.metrics_distributed
115
+ rep += (
116
+ "History (metrics, distributed, evaluate):\n"
117
+ + pprint.pformat(self.metrics_distributed)
118
+ + "\n"
120
119
  )
121
120
  if self.metrics_centralized:
122
121
  rep += "History (metrics, centralized):\n" + pprint.pformat(