flwr-nightly 1.8.0.dev20240315__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.dev20240315.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.dev20240315.dist-info/RECORD +0 -211
  309. flwr_nightly-1.8.0.dev20240315.dist-info/entry_points.txt +0 -9
  310. {flwr_nightly-1.8.0.dev20240315.dist-info → flwr_nightly-1.15.0.dev20250114.dist-info}/LICENSE +0 -0
  311. {flwr_nightly-1.8.0.dev20240315.dist-info → flwr_nightly-1.15.0.dev20250114.dist-info}/WHEEL +0 -0
@@ -16,12 +16,11 @@
16
16
 
17
17
 
18
18
  from abc import ABC
19
- from typing import Callable, Dict, Tuple
19
+ from typing import Callable
20
20
 
21
21
  from flwr.client.client import Client
22
22
  from flwr.common import (
23
23
  Config,
24
- Context,
25
24
  NDArrays,
26
25
  Scalar,
27
26
  ndarrays_to_parameters,
@@ -70,9 +69,7 @@ Example
70
69
  class NumPyClient(ABC):
71
70
  """Abstract base class for Flower clients using NumPy."""
72
71
 
73
- context: Context
74
-
75
- def get_properties(self, config: Config) -> Dict[str, Scalar]:
72
+ def get_properties(self, config: Config) -> dict[str, Scalar]:
76
73
  """Return a client's set of properties.
77
74
 
78
75
  Parameters
@@ -92,7 +89,7 @@ class NumPyClient(ABC):
92
89
  _ = (self, config)
93
90
  return {}
94
91
 
95
- def get_parameters(self, config: Dict[str, Scalar]) -> NDArrays:
92
+ def get_parameters(self, config: dict[str, Scalar]) -> NDArrays:
96
93
  """Return the current local model parameters.
97
94
 
98
95
  Parameters
@@ -111,8 +108,8 @@ class NumPyClient(ABC):
111
108
  return []
112
109
 
113
110
  def fit(
114
- self, parameters: NDArrays, config: Dict[str, Scalar]
115
- ) -> Tuple[NDArrays, int, Dict[str, Scalar]]:
111
+ self, parameters: NDArrays, config: dict[str, Scalar]
112
+ ) -> tuple[NDArrays, int, dict[str, Scalar]]:
116
113
  """Train the provided parameters using the locally held dataset.
117
114
 
118
115
  Parameters
@@ -140,8 +137,8 @@ class NumPyClient(ABC):
140
137
  return [], 0, {}
141
138
 
142
139
  def evaluate(
143
- self, parameters: NDArrays, config: Dict[str, Scalar]
144
- ) -> Tuple[float, int, Dict[str, Scalar]]:
140
+ self, parameters: NDArrays, config: dict[str, Scalar]
141
+ ) -> tuple[float, int, dict[str, Scalar]]:
145
142
  """Evaluate the provided parameters using the locally held dataset.
146
143
 
147
144
  Parameters
@@ -174,14 +171,6 @@ class NumPyClient(ABC):
174
171
  _ = (self, parameters, config)
175
172
  return 0.0, 0, {}
176
173
 
177
- def get_context(self) -> Context:
178
- """Get the run context from this client."""
179
- return self.context
180
-
181
- def set_context(self, context: Context) -> None:
182
- """Apply a run context to this client."""
183
- self.context = context
184
-
185
174
  def to_client(self) -> Client:
186
175
  """Convert to object to Client type and return it."""
187
176
  return _wrap_numpy_client(client=self)
@@ -278,21 +267,9 @@ def _evaluate(self: Client, ins: EvaluateIns) -> EvaluateRes:
278
267
  )
279
268
 
280
269
 
281
- def _get_context(self: Client) -> Context:
282
- """Return context of underlying NumPyClient."""
283
- return self.numpy_client.get_context() # type: ignore
284
-
285
-
286
- def _set_context(self: Client, context: Context) -> None:
287
- """Apply context to underlying NumPyClient."""
288
- self.numpy_client.set_context(context) # type: ignore
289
-
290
-
291
270
  def _wrap_numpy_client(client: NumPyClient) -> Client:
292
- member_dict: Dict[str, Callable] = { # type: ignore
271
+ member_dict: dict[str, Callable] = { # type: ignore
293
272
  "__init__": _constructor,
294
- "get_context": _get_context,
295
- "set_context": _set_context,
296
273
  }
297
274
 
298
275
  # Add wrapper type methods (if overridden)
@@ -1,4 +1,4 @@
1
- # Copyright 2020 Flower Labs GmbH. All Rights Reserved.
1
+ # Copyright 2023 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.
@@ -1,4 +1,4 @@
1
- # Copyright 2020 Flower Labs GmbH. All Rights Reserved.
1
+ # Copyright 2023 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.
@@ -15,31 +15,48 @@
15
15
  """Contextmanager for a REST request-response channel to the Flower server."""
16
16
 
17
17
 
18
+ import random
18
19
  import sys
20
+ import threading
21
+ from collections.abc import Iterator
19
22
  from contextlib import contextmanager
20
23
  from copy import copy
21
24
  from logging import ERROR, INFO, WARN
22
- from typing import Callable, Dict, Iterator, Optional, Tuple, Union, cast
25
+ from typing import Callable, Optional, TypeVar, Union
23
26
 
27
+ from cryptography.hazmat.primitives.asymmetric import ec
28
+ from google.protobuf.message import Message as GrpcMessage
29
+
30
+ from flwr.client.heartbeat import start_ping_loop
24
31
  from flwr.client.message_handler.message_handler import validate_out_message
25
- from flwr.client.message_handler.task_handler import get_task_ins, validate_task_ins
26
32
  from flwr.common import GRPC_MAX_MESSAGE_LENGTH
27
- from flwr.common.constant import MISSING_EXTRA_REST
33
+ from flwr.common.constant import (
34
+ MISSING_EXTRA_REST,
35
+ PING_BASE_MULTIPLIER,
36
+ PING_CALL_TIMEOUT,
37
+ PING_DEFAULT_INTERVAL,
38
+ PING_RANDOM_RANGE,
39
+ )
28
40
  from flwr.common.logger import log
29
41
  from flwr.common.message import Message, Metadata
30
42
  from flwr.common.retry_invoker import RetryInvoker
31
- from flwr.common.serde import message_from_taskins, message_to_taskres
43
+ from flwr.common.serde import message_from_proto, message_to_proto, run_from_proto
44
+ from flwr.common.typing import Fab, Run
45
+ from flwr.proto.fab_pb2 import GetFabRequest, GetFabResponse # pylint: disable=E0611
32
46
  from flwr.proto.fleet_pb2 import ( # pylint: disable=E0611
33
47
  CreateNodeRequest,
34
48
  CreateNodeResponse,
35
49
  DeleteNodeRequest,
36
- PullTaskInsRequest,
37
- PullTaskInsResponse,
38
- PushTaskResRequest,
39
- PushTaskResResponse,
50
+ DeleteNodeResponse,
51
+ PingRequest,
52
+ PingResponse,
53
+ PullMessagesRequest,
54
+ PullMessagesResponse,
55
+ PushMessagesRequest,
56
+ PushMessagesResponse,
40
57
  )
41
58
  from flwr.proto.node_pb2 import Node # pylint: disable=E0611
42
- from flwr.proto.task_pb2 import TaskIns # pylint: disable=E0611
59
+ from flwr.proto.run_pb2 import GetRunRequest, GetRunResponse # pylint: disable=E0611
43
60
 
44
61
  try:
45
62
  import requests
@@ -47,19 +64,21 @@ except ModuleNotFoundError:
47
64
  sys.exit(MISSING_EXTRA_REST)
48
65
 
49
66
 
50
- KEY_NODE = "node"
51
- KEY_METADATA = "in_message_metadata"
52
-
53
-
54
67
  PATH_CREATE_NODE: str = "api/v0/fleet/create-node"
55
68
  PATH_DELETE_NODE: str = "api/v0/fleet/delete-node"
56
69
  PATH_PULL_TASK_INS: str = "api/v0/fleet/pull-task-ins"
70
+ PATH_PULL_MESSAGES: str = "/api/v0/fleet/pull-messages"
57
71
  PATH_PUSH_TASK_RES: str = "api/v0/fleet/push-task-res"
72
+ PATH_PUSH_MESSAGES: str = "/api/v0/fleet/push-messages"
73
+ PATH_PING: str = "api/v0/fleet/ping"
74
+ PATH_GET_RUN: str = "/api/v0/fleet/get-run"
75
+ PATH_GET_FAB: str = "/api/v0/fleet/get-fab"
76
+
77
+ T = TypeVar("T", bound=GrpcMessage)
58
78
 
59
79
 
60
80
  @contextmanager
61
- # pylint: disable-next=too-many-statements
62
- def http_request_response(
81
+ def http_request_response( # pylint: disable=R0913,R0914,R0915,R0917
63
82
  server_address: str,
64
83
  insecure: bool, # pylint: disable=unused-argument
65
84
  retry_invoker: RetryInvoker,
@@ -67,12 +86,17 @@ def http_request_response(
67
86
  root_certificates: Optional[
68
87
  Union[bytes, str]
69
88
  ] = None, # pylint: disable=unused-argument
89
+ authentication_keys: Optional[ # pylint: disable=unused-argument
90
+ tuple[ec.EllipticCurvePrivateKey, ec.EllipticCurvePublicKey]
91
+ ] = None,
70
92
  ) -> Iterator[
71
- Tuple[
93
+ tuple[
72
94
  Callable[[], Optional[Message]],
73
95
  Callable[[Message], None],
96
+ Optional[Callable[[], Optional[int]]],
74
97
  Optional[Callable[[], None]],
75
- Optional[Callable[[], None]],
98
+ Optional[Callable[[int], Run]],
99
+ Optional[Callable[[str, int], Fab]],
76
100
  ]
77
101
  ]:
78
102
  """Primitives for request/response-based interaction with a server.
@@ -98,10 +122,16 @@ def http_request_response(
98
122
  Path of the root certificate. If provided, a secure
99
123
  connection using the certificates will be established to an SSL-enabled
100
124
  Flower server. Bytes won't work for the REST API.
125
+ authentication_keys : Optional[Tuple[PrivateKey, PublicKey]] (default: None)
126
+ Client authentication is not supported for this transport type.
101
127
 
102
128
  Returns
103
129
  -------
104
- receive, send : Callable, Callable
130
+ receive : Callable
131
+ send : Callable
132
+ create_node : Optional[Callable]
133
+ delete_node : Optional[Callable]
134
+ get_run : Optional[Callable]
105
135
  """
106
136
  log(
107
137
  WARN,
@@ -126,233 +156,226 @@ def http_request_response(
126
156
  "For the REST API, the root certificates "
127
157
  "must be provided as a string path to the client.",
128
158
  )
159
+ if authentication_keys is not None:
160
+ log(ERROR, "Client authentication is not supported for this transport type.")
129
161
 
130
- # Necessary state to validate messages to be sent
131
- state: Dict[str, Optional[Metadata]] = {KEY_METADATA: None}
132
-
133
- # Enable create_node and delete_node to store node
134
- node_store: Dict[str, Optional[Node]] = {KEY_NODE: None}
162
+ # Shared variables for inner functions
163
+ metadata: Optional[Metadata] = None
164
+ node: Optional[Node] = None
165
+ ping_thread: Optional[threading.Thread] = None
166
+ ping_stop_event = threading.Event()
135
167
 
136
168
  ###########################################################################
137
- # receive/send functions
169
+ # ping/create_node/delete_node/receive/send/get_run functions
138
170
  ###########################################################################
139
171
 
140
- def create_node() -> None:
141
- """Set create_node."""
142
- create_node_req_proto = CreateNodeRequest()
143
- create_node_req_bytes: bytes = create_node_req_proto.SerializeToString()
144
-
145
- res = retry_invoker.invoke(
146
- requests.post,
147
- url=f"{base_url}/{PATH_CREATE_NODE}",
148
- headers={
149
- "Accept": "application/protobuf",
150
- "Content-Type": "application/protobuf",
151
- },
152
- data=create_node_req_bytes,
153
- verify=verify,
154
- timeout=None,
155
- )
172
+ def _request(
173
+ req: GrpcMessage, res_type: type[T], api_path: str, retry: bool = True
174
+ ) -> Optional[T]:
175
+ # Serialize the request
176
+ req_bytes = req.SerializeToString()
177
+
178
+ # Send the request
179
+ def post() -> requests.Response:
180
+ return requests.post(
181
+ f"{base_url}/{api_path}",
182
+ data=req_bytes,
183
+ headers={
184
+ "Accept": "application/protobuf",
185
+ "Content-Type": "application/protobuf",
186
+ },
187
+ verify=verify,
188
+ timeout=None,
189
+ )
190
+
191
+ if retry:
192
+ res: requests.Response = retry_invoker.invoke(post)
193
+ else:
194
+ res = post()
156
195
 
157
196
  # Check status code and headers
158
197
  if res.status_code != 200:
159
- return
198
+ return None
160
199
  if "content-type" not in res.headers:
161
200
  log(
162
201
  WARN,
163
202
  "[Node] POST /%s: missing header `Content-Type`",
164
- PATH_PULL_TASK_INS,
203
+ api_path,
165
204
  )
166
- return
205
+ return None
167
206
  if res.headers["content-type"] != "application/protobuf":
168
207
  log(
169
208
  WARN,
170
209
  "[Node] POST /%s: header `Content-Type` has wrong value",
171
- PATH_PULL_TASK_INS,
210
+ api_path,
172
211
  )
173
- return
212
+ return None
174
213
 
175
214
  # Deserialize ProtoBuf from bytes
176
- create_node_response_proto = CreateNodeResponse()
177
- create_node_response_proto.ParseFromString(res.content)
178
- # pylint: disable-next=no-member
179
- node_store[KEY_NODE] = create_node_response_proto.node
215
+ grpc_res = res_type()
216
+ grpc_res.ParseFromString(res.content)
217
+ return grpc_res
218
+
219
+ def ping() -> None:
220
+ # Get Node
221
+ if node is None:
222
+ log(ERROR, "Node instance missing")
223
+ return
224
+
225
+ # Construct the ping request
226
+ req = PingRequest(node=node, ping_interval=PING_DEFAULT_INTERVAL)
227
+
228
+ # Send the request
229
+ res = _request(req, PingResponse, PATH_PING, retry=False)
230
+ if res is None:
231
+ return
232
+
233
+ # Check if success
234
+ if not res.success:
235
+ raise RuntimeError("Ping failed unexpectedly.")
236
+
237
+ # Wait
238
+ rd = random.uniform(*PING_RANDOM_RANGE)
239
+ next_interval: float = PING_DEFAULT_INTERVAL - PING_CALL_TIMEOUT
240
+ next_interval *= PING_BASE_MULTIPLIER + rd
241
+ if not ping_stop_event.is_set():
242
+ ping_stop_event.wait(next_interval)
243
+
244
+ def create_node() -> Optional[int]:
245
+ """Set create_node."""
246
+ req = CreateNodeRequest(ping_interval=PING_DEFAULT_INTERVAL)
247
+
248
+ # Send the request
249
+ res = _request(req, CreateNodeResponse, PATH_CREATE_NODE)
250
+ if res is None:
251
+ return None
252
+
253
+ # Remember the node and the ping-loop thread
254
+ nonlocal node, ping_thread
255
+ node = res.node
256
+ ping_thread = start_ping_loop(ping, ping_stop_event)
257
+ return node.node_id
180
258
 
181
259
  def delete_node() -> None:
182
260
  """Set delete_node."""
183
- if node_store[KEY_NODE] is None:
261
+ nonlocal node
262
+ if node is None:
184
263
  log(ERROR, "Node instance missing")
185
264
  return
186
- node: Node = cast(Node, node_store[KEY_NODE])
187
- delete_node_req_proto = DeleteNodeRequest(node=node)
188
- delete_node_req_req_bytes: bytes = delete_node_req_proto.SerializeToString()
189
- res = retry_invoker.invoke(
190
- requests.post,
191
- url=f"{base_url}/{PATH_DELETE_NODE}",
192
- headers={
193
- "Accept": "application/protobuf",
194
- "Content-Type": "application/protobuf",
195
- },
196
- data=delete_node_req_req_bytes,
197
- verify=verify,
198
- timeout=None,
199
- )
200
265
 
201
- # Check status code and headers
202
- if res.status_code != 200:
203
- return
204
- if "content-type" not in res.headers:
205
- log(
206
- WARN,
207
- "[Node] POST /%s: missing header `Content-Type`",
208
- PATH_PULL_TASK_INS,
209
- )
266
+ # Stop the ping-loop thread
267
+ ping_stop_event.set()
268
+ if ping_thread is not None:
269
+ ping_thread.join()
270
+
271
+ # Send DeleteNode request
272
+ req = DeleteNodeRequest(node=node)
273
+
274
+ # Send the request
275
+ res = _request(req, DeleteNodeResponse, PATH_DELETE_NODE)
276
+ if res is None:
210
277
  return
211
- if res.headers["content-type"] != "application/protobuf":
212
- log(
213
- WARN,
214
- "[Node] POST /%s: header `Content-Type` has wrong value",
215
- PATH_PULL_TASK_INS,
216
- )
278
+
279
+ # Cleanup
280
+ node = None
217
281
 
218
282
  def receive() -> Optional[Message]:
219
283
  """Receive next task from server."""
220
284
  # Get Node
221
- if node_store[KEY_NODE] is None:
285
+ if node is None:
222
286
  log(ERROR, "Node instance missing")
223
287
  return None
224
- node: Node = cast(Node, node_store[KEY_NODE])
225
-
226
- # Request instructions (task) from server
227
- pull_task_ins_req_proto = PullTaskInsRequest(node=node)
228
- pull_task_ins_req_bytes: bytes = pull_task_ins_req_proto.SerializeToString()
229
-
230
- # Request instructions (task) from server
231
- res = retry_invoker.invoke(
232
- requests.post,
233
- url=f"{base_url}/{PATH_PULL_TASK_INS}",
234
- headers={
235
- "Accept": "application/protobuf",
236
- "Content-Type": "application/protobuf",
237
- },
238
- data=pull_task_ins_req_bytes,
239
- verify=verify,
240
- timeout=None,
241
- )
242
288
 
243
- # Check status code and headers
244
- if res.status_code != 200:
245
- return None
246
- if "content-type" not in res.headers:
247
- log(
248
- WARN,
249
- "[Node] POST /%s: missing header `Content-Type`",
250
- PATH_PULL_TASK_INS,
251
- )
252
- return None
253
- if res.headers["content-type"] != "application/protobuf":
254
- log(
255
- WARN,
256
- "[Node] POST /%s: header `Content-Type` has wrong value",
257
- PATH_PULL_TASK_INS,
258
- )
259
- return None
289
+ # Request instructions (message) from server
290
+ req = PullMessagesRequest(node=node)
260
291
 
261
- # Deserialize ProtoBuf from bytes
262
- pull_task_ins_response_proto = PullTaskInsResponse()
263
- pull_task_ins_response_proto.ParseFromString(res.content)
292
+ # Send the request
293
+ res = _request(req, PullMessagesResponse, PATH_PULL_MESSAGES)
294
+ if res is None:
295
+ return None
264
296
 
265
- # Get the current TaskIns
266
- task_ins: Optional[TaskIns] = get_task_ins(pull_task_ins_response_proto)
297
+ # Get the current Messages
298
+ message_proto = None if len(res.messages_list) == 0 else res.messages_list[0]
267
299
 
268
- # Discard the current TaskIns if not valid
269
- if task_ins is not None and not (
270
- task_ins.task.consumer.node_id == node.node_id
271
- and validate_task_ins(task_ins)
300
+ # Discard the current message if not valid
301
+ if message_proto is not None and not (
302
+ message_proto.metadata.dst_node_id == node.node_id
272
303
  ):
273
- task_ins = None
304
+ message_proto = None
274
305
 
275
306
  # Return the Message if available
307
+ nonlocal metadata
276
308
  message = None
277
- state[KEY_METADATA] = None
278
- if task_ins is not None:
279
- message = message_from_taskins(task_ins)
280
- state[KEY_METADATA] = copy(message.metadata)
309
+ if message_proto is not None:
310
+ message = message_from_proto(message_proto)
311
+ metadata = copy(message.metadata)
281
312
  log(INFO, "[Node] POST /%s: success", PATH_PULL_TASK_INS)
282
313
  return message
283
314
 
284
315
  def send(message: Message) -> None:
285
316
  """Send task result back to server."""
286
317
  # Get Node
287
- if node_store[KEY_NODE] is None:
318
+ if node is None:
288
319
  log(ERROR, "Node instance missing")
289
320
  return
290
321
 
291
322
  # Get incoming message
292
- in_metadata = state[KEY_METADATA]
293
- if in_metadata is None:
323
+ nonlocal metadata
324
+ if metadata is None:
294
325
  log(ERROR, "No current message")
295
326
  return
296
327
 
297
328
  # Validate out message
298
- if not validate_out_message(message, in_metadata):
329
+ if not validate_out_message(message, metadata):
299
330
  log(ERROR, "Invalid out message")
300
331
  return
301
-
302
- # Construct TaskRes
303
- task_res = message_to_taskres(message)
332
+ metadata = None
304
333
 
305
334
  # Serialize ProtoBuf to bytes
306
- push_task_res_request_proto = PushTaskResRequest(task_res_list=[task_res])
307
- push_task_res_request_bytes: bytes = (
308
- push_task_res_request_proto.SerializeToString()
309
- )
310
-
311
- # Send ClientMessage to server
312
- res = retry_invoker.invoke(
313
- requests.post,
314
- url=f"{base_url}/{PATH_PUSH_TASK_RES}",
315
- headers={
316
- "Accept": "application/protobuf",
317
- "Content-Type": "application/protobuf",
318
- },
319
- data=push_task_res_request_bytes,
320
- verify=verify,
321
- timeout=None,
322
- )
335
+ message_proto = message_to_proto(message=message)
323
336
 
324
- state[KEY_METADATA] = None
337
+ # Serialize ProtoBuf to bytes
338
+ req = PushMessagesRequest(node=node, messages_list=[message_proto])
325
339
 
326
- # Check status code and headers
327
- if res.status_code != 200:
328
- return
329
- if "content-type" not in res.headers:
330
- log(
331
- WARN,
332
- "[Node] POST /%s: missing header `Content-Type`",
333
- PATH_PUSH_TASK_RES,
334
- )
335
- return
336
- if res.headers["content-type"] != "application/protobuf":
337
- log(
338
- WARN,
339
- "[Node] POST /%s: header `Content-Type` has wrong value",
340
- PATH_PUSH_TASK_RES,
341
- )
340
+ # Send the request
341
+ res = _request(req, PushMessagesResponse, PATH_PUSH_MESSAGES)
342
+ if res is None:
342
343
  return
343
344
 
344
- # Deserialize ProtoBuf from bytes
345
- push_task_res_response_proto = PushTaskResResponse()
346
- push_task_res_response_proto.ParseFromString(res.content)
347
345
  log(
348
346
  INFO,
349
347
  "[Node] POST /%s: success, created result %s",
350
348
  PATH_PUSH_TASK_RES,
351
- push_task_res_response_proto.results, # pylint: disable=no-member
349
+ res.results, # pylint: disable=no-member
350
+ )
351
+
352
+ def get_run(run_id: int) -> Run:
353
+ # Construct the request
354
+ req = GetRunRequest(node=node, run_id=run_id)
355
+
356
+ # Send the request
357
+ res = _request(req, GetRunResponse, PATH_GET_RUN)
358
+ if res is None:
359
+ return Run.create_empty(run_id)
360
+
361
+ return run_from_proto(res.run)
362
+
363
+ def get_fab(fab_hash: str, run_id: int) -> Fab:
364
+ # Construct the request
365
+ req = GetFabRequest(node=node, hash_str=fab_hash, run_id=run_id)
366
+
367
+ # Send the request
368
+ res = _request(req, GetFabResponse, PATH_GET_FAB)
369
+ if res is None:
370
+ return Fab("", b"")
371
+
372
+ return Fab(
373
+ res.fab.hash_str,
374
+ res.fab.content,
352
375
  )
353
376
 
354
377
  try:
355
378
  # Yield methods
356
- yield (receive, send, create_node, delete_node)
379
+ yield (receive, send, create_node, delete_node, get_run, get_fab)
357
380
  except Exception as exc: # pylint: disable=broad-except
358
381
  log(ERROR, exc)