flwr-nightly 1.8.0.dev20240315__py3-none-any.whl → 1.15.0.dev20250115__py3-none-any.whl

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