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
flwr/cli/ls.py ADDED
@@ -0,0 +1,327 @@
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 command line interface `ls` command."""
16
+
17
+
18
+ import io
19
+ import json
20
+ from datetime import datetime, timedelta
21
+ from pathlib import Path
22
+ from typing import Annotated, Optional
23
+
24
+ import typer
25
+ from rich.console import Console
26
+ from rich.table import Table
27
+ from rich.text import Text
28
+
29
+ from flwr.cli.config_utils import (
30
+ exit_if_no_address,
31
+ load_and_validate,
32
+ process_loaded_project_config,
33
+ validate_federation_in_project_config,
34
+ )
35
+ from flwr.common.constant import FAB_CONFIG_FILE, CliOutputFormat, SubStatus
36
+ from flwr.common.date import format_timedelta, isoformat8601_utc
37
+ from flwr.common.logger import print_json_error, redirect_output, restore_output
38
+ from flwr.common.serde import run_from_proto
39
+ from flwr.common.typing import Run
40
+ from flwr.proto.exec_pb2 import ( # pylint: disable=E0611
41
+ ListRunsRequest,
42
+ ListRunsResponse,
43
+ )
44
+ from flwr.proto.exec_pb2_grpc import ExecStub
45
+
46
+ from .utils import init_channel, try_obtain_cli_auth_plugin, unauthenticated_exc_handler
47
+
48
+ _RunListType = tuple[int, str, str, str, str, str, str, str, str]
49
+
50
+
51
+ def ls( # pylint: disable=too-many-locals, too-many-branches
52
+ app: Annotated[
53
+ Path,
54
+ typer.Argument(help="Path of the Flower project"),
55
+ ] = Path("."),
56
+ federation: Annotated[
57
+ Optional[str],
58
+ typer.Argument(help="Name of the federation"),
59
+ ] = None,
60
+ runs: Annotated[
61
+ bool,
62
+ typer.Option(
63
+ "--runs",
64
+ help="List all runs",
65
+ ),
66
+ ] = False,
67
+ run_id: Annotated[
68
+ Optional[int],
69
+ typer.Option(
70
+ "--run-id",
71
+ help="Specific run ID to display",
72
+ ),
73
+ ] = None,
74
+ output_format: Annotated[
75
+ str,
76
+ typer.Option(
77
+ "--format",
78
+ case_sensitive=False,
79
+ help="Format output using 'default' view or 'json'",
80
+ ),
81
+ ] = CliOutputFormat.DEFAULT,
82
+ ) -> None:
83
+ """List the details of one provided run ID or all runs in a Flower federation.
84
+
85
+ The following details are displayed:
86
+
87
+ - **Run ID:** Unique identifier for the run.
88
+ - **FAB:** Name of the FAB associated with the run (``{FAB_ID} (v{FAB_VERSION})``).
89
+ - **Status:** Current status of the run (pending, starting, running, finished).
90
+ - **Elapsed:** Time elapsed since the run started (``HH:MM:SS``).
91
+ - **Created At:** Timestamp when the run was created.
92
+ - **Running At:** Timestamp when the run started running.
93
+ - **Finished At:** Timestamp when the run finished.
94
+
95
+ All timestamps follow ISO 8601, UTC and are formatted as ``YYYY-MM-DD HH:MM:SSZ``.
96
+ """
97
+ suppress_output = output_format == CliOutputFormat.JSON
98
+ captured_output = io.StringIO()
99
+ try:
100
+ if suppress_output:
101
+ redirect_output(captured_output)
102
+ # Load and validate federation config
103
+ typer.secho("Loading project configuration... ", fg=typer.colors.BLUE)
104
+
105
+ pyproject_path = app / FAB_CONFIG_FILE if app else None
106
+ config, errors, warnings = load_and_validate(path=pyproject_path)
107
+ config = process_loaded_project_config(config, errors, warnings)
108
+ federation, federation_config = validate_federation_in_project_config(
109
+ federation, config
110
+ )
111
+ exit_if_no_address(federation_config, "ls")
112
+
113
+ try:
114
+ if runs and run_id is not None:
115
+ raise ValueError(
116
+ "The options '--runs' and '--run-id' are mutually exclusive."
117
+ )
118
+ auth_plugin = try_obtain_cli_auth_plugin(app, federation)
119
+ channel = init_channel(app, federation_config, auth_plugin)
120
+ stub = ExecStub(channel)
121
+
122
+ # Display information about a specific run ID
123
+ if run_id is not None:
124
+ typer.echo(f"🔍 Displaying information for run ID {run_id}...")
125
+ restore_output()
126
+ _display_one_run(stub, run_id, output_format)
127
+ # By default, list all runs
128
+ else:
129
+ typer.echo("📄 Listing all runs...")
130
+ restore_output()
131
+ _list_runs(stub, output_format)
132
+
133
+ except ValueError as err:
134
+ if suppress_output:
135
+ redirect_output(captured_output)
136
+ typer.secho(
137
+ f"❌ {err}",
138
+ fg=typer.colors.RED,
139
+ bold=True,
140
+ )
141
+ raise typer.Exit(code=1) from err
142
+ finally:
143
+ channel.close()
144
+ except (typer.Exit, Exception) as err: # pylint: disable=broad-except
145
+ if suppress_output:
146
+ restore_output()
147
+ e_message = captured_output.getvalue()
148
+ print_json_error(e_message, err)
149
+ else:
150
+ typer.secho(
151
+ f"{err}",
152
+ fg=typer.colors.RED,
153
+ bold=True,
154
+ )
155
+ finally:
156
+ if suppress_output:
157
+ restore_output()
158
+ captured_output.close()
159
+
160
+
161
+ def _format_runs(run_dict: dict[int, Run], now_isoformat: str) -> list[_RunListType]:
162
+ """Format runs to a list."""
163
+
164
+ def _format_datetime(dt: Optional[datetime]) -> str:
165
+ return isoformat8601_utc(dt).replace("T", " ") if dt else "N/A"
166
+
167
+ run_list: list[_RunListType] = []
168
+
169
+ # Add rows
170
+ for run in sorted(
171
+ run_dict.values(), key=lambda x: datetime.fromisoformat(x.pending_at)
172
+ ):
173
+ # Combine status and sub-status into a single string
174
+ if run.status.sub_status == "":
175
+ status_text = run.status.status
176
+ else:
177
+ status_text = f"{run.status.status}:{run.status.sub_status}"
178
+
179
+ # Convert isoformat to datetime
180
+ pending_at = datetime.fromisoformat(run.pending_at) if run.pending_at else None
181
+ running_at = datetime.fromisoformat(run.running_at) if run.running_at else None
182
+ finished_at = (
183
+ datetime.fromisoformat(run.finished_at) if run.finished_at else None
184
+ )
185
+
186
+ # Calculate elapsed time
187
+ elapsed_time = timedelta()
188
+ if running_at:
189
+ if finished_at:
190
+ end_time = finished_at
191
+ else:
192
+ end_time = datetime.fromisoformat(now_isoformat)
193
+ elapsed_time = end_time - running_at
194
+
195
+ run_list.append(
196
+ (
197
+ run.run_id,
198
+ run.fab_id,
199
+ run.fab_version,
200
+ run.fab_hash,
201
+ status_text,
202
+ format_timedelta(elapsed_time),
203
+ _format_datetime(pending_at),
204
+ _format_datetime(running_at),
205
+ _format_datetime(finished_at),
206
+ )
207
+ )
208
+ return run_list
209
+
210
+
211
+ def _to_table(run_list: list[_RunListType]) -> Table:
212
+ """Format the provided run list to a rich Table."""
213
+ table = Table(header_style="bold cyan", show_lines=True)
214
+
215
+ # Add columns
216
+ table.add_column(
217
+ Text("Run ID", justify="center"), style="bright_white", overflow="fold"
218
+ )
219
+ table.add_column(Text("FAB", justify="center"), style="dim white")
220
+ table.add_column(Text("Status", justify="center"))
221
+ table.add_column(Text("Elapsed", justify="center"), style="blue")
222
+ table.add_column(Text("Created At", justify="center"), style="dim white")
223
+ table.add_column(Text("Running At", justify="center"), style="dim white")
224
+ table.add_column(Text("Finished At", justify="center"), style="dim white")
225
+
226
+ for row in run_list:
227
+ (
228
+ run_id,
229
+ fab_id,
230
+ fab_version,
231
+ _,
232
+ status_text,
233
+ elapsed,
234
+ created_at,
235
+ running_at,
236
+ finished_at,
237
+ ) = row
238
+ # Style the status based on its value
239
+ sub_status = status_text.rsplit(":", maxsplit=1)[-1]
240
+ if sub_status == SubStatus.COMPLETED:
241
+ status_style = "green"
242
+ elif sub_status == SubStatus.FAILED:
243
+ status_style = "red"
244
+ else:
245
+ status_style = "yellow"
246
+
247
+ formatted_row = (
248
+ f"[bold]{run_id}[/bold]",
249
+ f"{fab_id} (v{fab_version})",
250
+ f"[{status_style}]{status_text}[/{status_style}]",
251
+ elapsed,
252
+ created_at,
253
+ running_at,
254
+ finished_at,
255
+ )
256
+ table.add_row(*formatted_row)
257
+
258
+ return table
259
+
260
+
261
+ def _to_json(run_list: list[_RunListType]) -> str:
262
+ """Format run status list to a JSON formatted string."""
263
+ runs_list = []
264
+ for row in run_list:
265
+ (
266
+ run_id,
267
+ fab_id,
268
+ fab_version,
269
+ fab_hash,
270
+ status_text,
271
+ elapsed,
272
+ created_at,
273
+ running_at,
274
+ finished_at,
275
+ ) = row
276
+ runs_list.append(
277
+ {
278
+ "run-id": run_id,
279
+ "fab-id": fab_id,
280
+ "fab-name": fab_id.split("/")[-1],
281
+ "fab-version": fab_version,
282
+ "fab-hash": fab_hash[:8],
283
+ "status": status_text,
284
+ "elapsed": elapsed,
285
+ "created-at": created_at,
286
+ "running-at": running_at,
287
+ "finished-at": finished_at,
288
+ }
289
+ )
290
+
291
+ return json.dumps({"success": True, "runs": runs_list})
292
+
293
+
294
+ def _list_runs(
295
+ stub: ExecStub,
296
+ output_format: str = CliOutputFormat.DEFAULT,
297
+ ) -> None:
298
+ """List all runs."""
299
+ with unauthenticated_exc_handler():
300
+ res: ListRunsResponse = stub.ListRuns(ListRunsRequest())
301
+ run_dict = {run_id: run_from_proto(proto) for run_id, proto in res.run_dict.items()}
302
+
303
+ formatted_runs = _format_runs(run_dict, res.now)
304
+ if output_format == CliOutputFormat.JSON:
305
+ Console().print_json(_to_json(formatted_runs))
306
+ else:
307
+ Console().print(_to_table(formatted_runs))
308
+
309
+
310
+ def _display_one_run(
311
+ stub: ExecStub,
312
+ run_id: int,
313
+ output_format: str = CliOutputFormat.DEFAULT,
314
+ ) -> None:
315
+ """Display information about a specific run."""
316
+ with unauthenticated_exc_handler():
317
+ res: ListRunsResponse = stub.ListRuns(ListRunsRequest(run_id=run_id))
318
+ if not res.run_dict:
319
+ raise ValueError(f"Run ID {run_id} not found")
320
+
321
+ run_dict = {run_id: run_from_proto(proto) for run_id, proto in res.run_dict.items()}
322
+
323
+ formatted_runs = _format_runs(run_dict, res.now)
324
+ if output_format == CliOutputFormat.JSON:
325
+ Console().print_json(_to_json(formatted_runs))
326
+ else:
327
+ Console().print(_to_table(formatted_runs))
flwr/cli/new/__init__.py CHANGED
@@ -14,6 +14,7 @@
14
14
  # ==============================================================================
15
15
  """Flower command line interface `new` command."""
16
16
 
17
+
17
18
  from .new import new as new
18
19
 
19
20
  __all__ = [
flwr/cli/new/new.py CHANGED
@@ -14,23 +14,44 @@
14
14
  # ==============================================================================
15
15
  """Flower command line interface `new` command."""
16
16
 
17
- import os
17
+
18
+ import re
18
19
  from enum import Enum
20
+ from pathlib import Path
19
21
  from string import Template
20
- from typing import Dict, Optional
22
+ from typing import Annotated, Optional
21
23
 
22
24
  import typer
23
- from typing_extensions import Annotated
24
25
 
25
- from ..utils import prompt_options, prompt_text
26
+ from ..utils import (
27
+ is_valid_project_name,
28
+ prompt_options,
29
+ prompt_text,
30
+ sanitize_project_name,
31
+ )
26
32
 
27
33
 
28
34
  class MlFramework(str, Enum):
29
35
  """Available frameworks."""
30
36
 
31
- NUMPY = "NumPy"
32
37
  PYTORCH = "PyTorch"
33
38
  TENSORFLOW = "TensorFlow"
39
+ SKLEARN = "sklearn"
40
+ HUGGINGFACE = "HuggingFace"
41
+ JAX = "JAX"
42
+ MLX = "MLX"
43
+ NUMPY = "NumPy"
44
+ FLOWERTUNE = "FlowerTune"
45
+ BASELINE = "Flower Baseline"
46
+
47
+
48
+ class LlmChallengeName(str, Enum):
49
+ """Available LLM challenges."""
50
+
51
+ GENERALNLP = "GeneralNLP"
52
+ FINANCE = "Finance"
53
+ MEDICAL = "Medical"
54
+ CODE = "Code"
34
55
 
35
56
 
36
57
  class TemplateNotFound(Exception):
@@ -39,116 +60,239 @@ class TemplateNotFound(Exception):
39
60
 
40
61
  def load_template(name: str) -> str:
41
62
  """Load template from template directory and return as text."""
42
- tpl_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "templates"))
43
- tpl_file_path = os.path.join(tpl_dir, name)
63
+ tpl_dir = (Path(__file__).parent / "templates").absolute()
64
+ tpl_file_path = tpl_dir / name
44
65
 
45
- if not os.path.isfile(tpl_file_path):
66
+ if not tpl_file_path.is_file():
46
67
  raise TemplateNotFound(f"Template '{name}' not found")
47
68
 
48
69
  with open(tpl_file_path, encoding="utf-8") as tpl_file:
49
70
  return tpl_file.read()
50
71
 
51
72
 
52
- def render_template(template: str, data: Dict[str, str]) -> str:
73
+ def render_template(template: str, data: dict[str, str]) -> str:
53
74
  """Render template."""
54
75
  tpl_file = load_template(template)
55
76
  tpl = Template(tpl_file)
56
- result = tpl.substitute(data)
57
- return result
77
+ if ".gitignore" not in template:
78
+ return tpl.substitute(data)
79
+ return tpl.template
58
80
 
59
81
 
60
- def create_file(file_path: str, content: str) -> None:
82
+ def create_file(file_path: Path, content: str) -> None:
61
83
  """Create file including all nessecary directories and write content into file."""
62
- os.makedirs(os.path.dirname(file_path), exist_ok=True)
63
- with open(file_path, "w", encoding="utf-8") as f:
64
- f.write(content)
84
+ file_path.parent.mkdir(exist_ok=True)
85
+ file_path.write_text(content, encoding="utf-8")
65
86
 
66
87
 
67
- def render_and_create(file_path: str, template: str, context: Dict[str, str]) -> None:
88
+ def render_and_create(file_path: Path, template: str, context: dict[str, str]) -> None:
68
89
  """Render template and write to file."""
69
90
  content = render_template(template, context)
70
91
  create_file(file_path, content)
71
92
 
72
93
 
94
+ # pylint: disable=too-many-locals,too-many-branches,too-many-statements
73
95
  def new(
74
- project_name: Annotated[
96
+ app_name: Annotated[
75
97
  Optional[str],
76
- typer.Argument(metavar="project_name", help="The name of the project"),
98
+ typer.Argument(help="The name of the Flower App"),
77
99
  ] = None,
78
100
  framework: Annotated[
79
101
  Optional[MlFramework],
80
102
  typer.Option(case_sensitive=False, help="The ML framework to use"),
81
103
  ] = None,
104
+ username: Annotated[
105
+ Optional[str],
106
+ typer.Option(case_sensitive=False, help="The Flower username of the author"),
107
+ ] = None,
82
108
  ) -> None:
83
- """Create new Flower project."""
84
- print(
85
- typer.style(
86
- f"🔨 Creating Flower project {project_name}...",
87
- fg=typer.colors.GREEN,
88
- bold=True,
109
+ """Create new Flower App."""
110
+ if app_name is None:
111
+ app_name = prompt_text("Please provide the app name")
112
+ if not is_valid_project_name(app_name):
113
+ app_name = prompt_text(
114
+ "Please provide a name that only contains "
115
+ "characters in {'-', a-zA-Z', '0-9'}",
116
+ predicate=is_valid_project_name,
117
+ default=sanitize_project_name(app_name),
89
118
  )
90
- )
91
119
 
92
- if project_name is None:
93
- project_name = prompt_text("Please provide project name")
120
+ # Set project directory path
121
+ package_name = re.sub(r"[-_.]+", "-", app_name).lower()
122
+ import_name = package_name.replace("-", "_")
123
+ project_dir = Path.cwd() / package_name
124
+
125
+ if project_dir.exists():
126
+ if not typer.confirm(
127
+ typer.style(
128
+ f"\n💬 {app_name} already exists, do you want to override it?",
129
+ fg=typer.colors.MAGENTA,
130
+ bold=True,
131
+ )
132
+ ):
133
+ return
134
+
135
+ if username is None:
136
+ username = prompt_text("Please provide your Flower username")
94
137
 
95
138
  if framework is not None:
96
139
  framework_str = str(framework.value)
97
140
  else:
98
- framework_value = prompt_options(
141
+ framework_str = prompt_options(
99
142
  "Please select ML framework by typing in the number",
100
143
  [mlf.value for mlf in MlFramework],
101
144
  )
102
- selected_value = [
103
- name
104
- for name, value in vars(MlFramework).items()
105
- if value == framework_value
106
- ]
107
- framework_str = selected_value[0]
108
145
 
109
- framework_str = framework_str.lower()
146
+ llm_challenge_str = None
147
+ if framework_str == MlFramework.FLOWERTUNE:
148
+ llm_challenge_value = prompt_options(
149
+ "Please select LLM challenge by typing in the number",
150
+ sorted([challenge.value for challenge in LlmChallengeName]),
151
+ )
152
+ llm_challenge_str = llm_challenge_value.lower()
110
153
 
111
- # Set project directory path
112
- cwd = os.getcwd()
113
- pnl = project_name.lower()
114
- project_dir = os.path.join(cwd, pnl)
154
+ if framework_str == MlFramework.BASELINE:
155
+ framework_str = "baseline"
115
156
 
116
- # List of files to render
117
- files = {
118
- "README.md": {"template": "app/README.md.tpl"},
119
- "requirements.txt": {"template": f"app/requirements.{framework_str}.txt.tpl"},
120
- "flower.toml": {"template": "app/flower.toml.tpl"},
121
- "pyproject.toml": {"template": f"app/pyproject.{framework_str}.toml.tpl"},
122
- f"{pnl}/__init__.py": {"template": "app/code/__init__.py.tpl"},
123
- f"{pnl}/server.py": {"template": f"app/code/server.{framework_str}.py.tpl"},
124
- f"{pnl}/client.py": {"template": f"app/code/client.{framework_str}.py.tpl"},
157
+ print(
158
+ typer.style(
159
+ f"\n🔨 Creating Flower App {app_name}...",
160
+ fg=typer.colors.GREEN,
161
+ bold=True,
162
+ )
163
+ )
164
+
165
+ context = {
166
+ "framework_str": framework_str,
167
+ "import_name": import_name.replace("-", "_"),
168
+ "package_name": package_name,
169
+ "project_name": app_name,
170
+ "username": username,
125
171
  }
126
172
 
127
- # In case framework is MlFramework.PYTORCH generate additionally the task.py file
128
- if framework_str == MlFramework.PYTORCH.value.lower():
129
- files[f"{pnl}/task.py"] = {"template": f"app/code/task.{framework_str}.py.tpl"}
173
+ template_name = framework_str.lower()
174
+
175
+ # List of files to render
176
+ if llm_challenge_str:
177
+ files = {
178
+ ".gitignore": {"template": "app/.gitignore.tpl"},
179
+ "pyproject.toml": {"template": f"app/pyproject.{template_name}.toml.tpl"},
180
+ "README.md": {"template": f"app/README.{template_name}.md.tpl"},
181
+ f"{import_name}/__init__.py": {"template": "app/code/__init__.py.tpl"},
182
+ f"{import_name}/server_app.py": {
183
+ "template": "app/code/flwr_tune/server_app.py.tpl"
184
+ },
185
+ f"{import_name}/client_app.py": {
186
+ "template": "app/code/flwr_tune/client_app.py.tpl"
187
+ },
188
+ f"{import_name}/models.py": {
189
+ "template": "app/code/flwr_tune/models.py.tpl"
190
+ },
191
+ f"{import_name}/dataset.py": {
192
+ "template": "app/code/flwr_tune/dataset.py.tpl"
193
+ },
194
+ f"{import_name}/strategy.py": {
195
+ "template": "app/code/flwr_tune/strategy.py.tpl"
196
+ },
197
+ }
198
+
199
+ # Challenge specific context
200
+ fraction_fit = "0.2" if llm_challenge_str == "code" else "0.1"
201
+ if llm_challenge_str == "generalnlp":
202
+ challenge_name = "General NLP"
203
+ num_clients = "20"
204
+ dataset_name = "vicgalle/alpaca-gpt4"
205
+ elif llm_challenge_str == "finance":
206
+ challenge_name = "Finance"
207
+ num_clients = "50"
208
+ dataset_name = "FinGPT/fingpt-sentiment-train"
209
+ elif llm_challenge_str == "medical":
210
+ challenge_name = "Medical"
211
+ num_clients = "20"
212
+ dataset_name = "medalpaca/medical_meadow_medical_flashcards"
213
+ else:
214
+ challenge_name = "Code"
215
+ num_clients = "10"
216
+ dataset_name = "lucasmccabe-lmi/CodeAlpaca-20k"
130
217
 
131
- context = {"project_name": project_name}
218
+ context["llm_challenge_str"] = llm_challenge_str
219
+ context["fraction_fit"] = fraction_fit
220
+ context["challenge_name"] = challenge_name
221
+ context["num_clients"] = num_clients
222
+ context["dataset_name"] = dataset_name
223
+ else:
224
+ files = {
225
+ ".gitignore": {"template": "app/.gitignore.tpl"},
226
+ "README.md": {"template": "app/README.md.tpl"},
227
+ "pyproject.toml": {"template": f"app/pyproject.{template_name}.toml.tpl"},
228
+ f"{import_name}/__init__.py": {"template": "app/code/__init__.py.tpl"},
229
+ f"{import_name}/server_app.py": {
230
+ "template": f"app/code/server.{template_name}.py.tpl"
231
+ },
232
+ f"{import_name}/client_app.py": {
233
+ "template": f"app/code/client.{template_name}.py.tpl"
234
+ },
235
+ }
236
+
237
+ # Depending on the framework, generate task.py file
238
+ frameworks_with_tasks = [
239
+ MlFramework.PYTORCH.value,
240
+ MlFramework.JAX.value,
241
+ MlFramework.HUGGINGFACE.value,
242
+ MlFramework.MLX.value,
243
+ MlFramework.TENSORFLOW.value,
244
+ MlFramework.SKLEARN.value,
245
+ MlFramework.NUMPY.value,
246
+ ]
247
+ if framework_str in frameworks_with_tasks:
248
+ files[f"{import_name}/task.py"] = {
249
+ "template": f"app/code/task.{template_name}.py.tpl"
250
+ }
251
+
252
+ if framework_str == "baseline":
253
+ # Include additional files for baseline template
254
+ for file_name in ["model", "dataset", "strategy", "utils", "__init__"]:
255
+ files[f"{import_name}/{file_name}.py"] = {
256
+ "template": f"app/code/{file_name}.{template_name}.py.tpl"
257
+ }
258
+
259
+ # Replace README.md
260
+ files["README.md"]["template"] = f"app/README.{template_name}.md.tpl"
261
+
262
+ # Add LICENSE
263
+ files["LICENSE"] = {"template": "app/LICENSE.tpl"}
132
264
 
133
265
  for file_path, value in files.items():
134
266
  render_and_create(
135
- file_path=os.path.join(project_dir, file_path),
267
+ file_path=project_dir / file_path,
136
268
  template=value["template"],
137
269
  context=context,
138
270
  )
139
271
 
140
- print(
141
- typer.style(
142
- "🎊 Project creation successful.\n\n"
143
- "Use the following command to run your project:\n",
144
- fg=typer.colors.GREEN,
145
- bold=True,
146
- )
272
+ prompt = typer.style(
273
+ "🎊 Flower App creation successful.\n\n"
274
+ "To run your Flower App, use the following command:\n\n",
275
+ fg=typer.colors.GREEN,
276
+ bold=True,
147
277
  )
148
- print(
149
- typer.style(
150
- f" cd {project_name}\n" + " pip install -e .\n flwr run\n",
151
- fg=typer.colors.BRIGHT_CYAN,
152
- bold=True,
153
- )
278
+
279
+ _add = " huggingface-cli login\n" if llm_challenge_str else ""
280
+ prompt += typer.style(
281
+ _add + f" flwr run {package_name}\n\n",
282
+ fg=typer.colors.BRIGHT_CYAN,
283
+ bold=True,
284
+ )
285
+
286
+ prompt += typer.style(
287
+ "If you haven't installed all dependencies yet, follow these steps:\n\n",
288
+ fg=typer.colors.GREEN,
289
+ bold=True,
154
290
  )
291
+
292
+ prompt += typer.style(
293
+ f" cd {package_name}\n" + " pip install -e .\n" + _add + " flwr run .\n",
294
+ fg=typer.colors.BRIGHT_CYAN,
295
+ bold=True,
296
+ )
297
+
298
+ print(prompt)