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.
- flwr/cli/app.py +16 -2
- flwr/cli/build.py +181 -0
- flwr/cli/cli_user_auth_interceptor.py +90 -0
- flwr/cli/config_utils.py +343 -0
- flwr/cli/example.py +4 -1
- flwr/cli/install.py +253 -0
- flwr/cli/log.py +182 -0
- flwr/{server/superlink/state → cli/login}/__init__.py +4 -10
- flwr/cli/login/login.py +88 -0
- flwr/cli/ls.py +327 -0
- flwr/cli/new/__init__.py +1 -0
- flwr/cli/new/new.py +210 -66
- flwr/cli/new/templates/app/.gitignore.tpl +163 -0
- flwr/cli/new/templates/app/LICENSE.tpl +202 -0
- flwr/cli/new/templates/app/README.baseline.md.tpl +127 -0
- flwr/cli/new/templates/app/README.flowertune.md.tpl +66 -0
- flwr/cli/new/templates/app/README.md.tpl +16 -32
- flwr/cli/new/templates/app/code/__init__.baseline.py.tpl +1 -0
- flwr/cli/new/templates/app/code/__init__.py.tpl +1 -1
- flwr/cli/new/templates/app/code/client.baseline.py.tpl +58 -0
- flwr/cli/new/templates/app/code/client.huggingface.py.tpl +55 -0
- flwr/cli/new/templates/app/code/client.jax.py.tpl +50 -0
- flwr/cli/new/templates/app/code/client.mlx.py.tpl +73 -0
- flwr/cli/new/templates/app/code/client.numpy.py.tpl +7 -7
- flwr/cli/new/templates/app/code/client.pytorch.py.tpl +30 -21
- flwr/cli/new/templates/app/code/client.sklearn.py.tpl +63 -0
- flwr/cli/new/templates/app/code/client.tensorflow.py.tpl +57 -1
- flwr/cli/new/templates/app/code/dataset.baseline.py.tpl +36 -0
- flwr/cli/new/templates/app/code/flwr_tune/__init__.py +15 -0
- flwr/cli/new/templates/app/code/flwr_tune/client_app.py.tpl +126 -0
- flwr/cli/new/templates/app/code/flwr_tune/dataset.py.tpl +87 -0
- flwr/cli/new/templates/app/code/flwr_tune/models.py.tpl +78 -0
- flwr/cli/new/templates/app/code/flwr_tune/server_app.py.tpl +94 -0
- flwr/cli/new/templates/app/code/flwr_tune/strategy.py.tpl +83 -0
- flwr/cli/new/templates/app/code/model.baseline.py.tpl +80 -0
- flwr/cli/new/templates/app/code/server.baseline.py.tpl +46 -0
- flwr/cli/new/templates/app/code/server.huggingface.py.tpl +38 -0
- flwr/cli/new/templates/app/code/server.jax.py.tpl +26 -0
- flwr/cli/new/templates/app/code/server.mlx.py.tpl +31 -0
- flwr/cli/new/templates/app/code/server.numpy.py.tpl +22 -9
- flwr/cli/new/templates/app/code/server.pytorch.py.tpl +21 -18
- flwr/cli/new/templates/app/code/server.sklearn.py.tpl +36 -0
- flwr/cli/new/templates/app/code/server.tensorflow.py.tpl +29 -1
- flwr/cli/new/templates/app/code/strategy.baseline.py.tpl +1 -0
- flwr/cli/new/templates/app/code/task.huggingface.py.tpl +102 -0
- flwr/cli/new/templates/app/code/task.jax.py.tpl +57 -0
- flwr/cli/new/templates/app/code/task.mlx.py.tpl +102 -0
- flwr/cli/new/templates/app/code/task.numpy.py.tpl +7 -0
- flwr/cli/new/templates/app/code/task.pytorch.py.tpl +29 -24
- flwr/cli/new/templates/app/code/task.sklearn.py.tpl +67 -0
- flwr/cli/new/templates/app/code/task.tensorflow.py.tpl +53 -0
- flwr/cli/new/templates/app/code/utils.baseline.py.tpl +1 -0
- flwr/cli/new/templates/app/pyproject.baseline.toml.tpl +138 -0
- flwr/cli/new/templates/app/pyproject.flowertune.toml.tpl +68 -0
- flwr/cli/new/templates/app/pyproject.huggingface.toml.tpl +46 -0
- flwr/cli/new/templates/app/pyproject.jax.toml.tpl +35 -0
- flwr/cli/new/templates/app/pyproject.mlx.toml.tpl +39 -0
- flwr/cli/new/templates/app/pyproject.numpy.toml.tpl +25 -12
- flwr/cli/new/templates/app/pyproject.pytorch.toml.tpl +29 -14
- flwr/cli/new/templates/app/pyproject.sklearn.toml.tpl +35 -0
- flwr/cli/new/templates/app/pyproject.tensorflow.toml.tpl +29 -14
- flwr/cli/run/__init__.py +1 -0
- flwr/cli/run/run.py +212 -34
- flwr/cli/stop.py +130 -0
- flwr/cli/utils.py +240 -5
- flwr/client/__init__.py +3 -2
- flwr/client/app.py +432 -255
- flwr/client/client.py +1 -11
- flwr/client/client_app.py +74 -13
- flwr/client/clientapp/__init__.py +22 -0
- flwr/client/clientapp/app.py +259 -0
- flwr/client/clientapp/clientappio_servicer.py +244 -0
- flwr/client/clientapp/utils.py +115 -0
- flwr/client/dpfedavg_numpy_client.py +7 -8
- flwr/client/grpc_adapter_client/__init__.py +15 -0
- flwr/client/grpc_adapter_client/connection.py +98 -0
- flwr/client/grpc_client/connection.py +21 -7
- flwr/client/grpc_rere_client/__init__.py +1 -1
- flwr/client/grpc_rere_client/client_interceptor.py +176 -0
- flwr/client/grpc_rere_client/connection.py +163 -56
- flwr/client/grpc_rere_client/grpc_adapter.py +167 -0
- flwr/client/heartbeat.py +74 -0
- flwr/client/message_handler/__init__.py +1 -1
- flwr/client/message_handler/message_handler.py +10 -11
- flwr/client/mod/__init__.py +5 -5
- flwr/client/mod/centraldp_mods.py +4 -2
- flwr/client/mod/comms_mods.py +5 -4
- flwr/client/mod/localdp_mod.py +10 -5
- flwr/client/mod/secure_aggregation/__init__.py +1 -1
- flwr/client/mod/secure_aggregation/secaggplus_mod.py +26 -26
- flwr/client/mod/utils.py +2 -4
- flwr/client/nodestate/__init__.py +26 -0
- flwr/client/nodestate/in_memory_nodestate.py +38 -0
- flwr/client/nodestate/nodestate.py +31 -0
- flwr/client/nodestate/nodestate_factory.py +38 -0
- flwr/client/numpy_client.py +8 -31
- flwr/client/rest_client/__init__.py +1 -1
- flwr/client/rest_client/connection.py +199 -176
- flwr/client/run_info_store.py +112 -0
- flwr/client/supernode/__init__.py +24 -0
- flwr/client/supernode/app.py +321 -0
- flwr/client/typing.py +1 -0
- flwr/common/__init__.py +17 -11
- flwr/common/address.py +47 -3
- flwr/common/args.py +153 -0
- flwr/common/auth_plugin/__init__.py +24 -0
- flwr/common/auth_plugin/auth_plugin.py +121 -0
- flwr/common/config.py +243 -0
- flwr/common/constant.py +132 -1
- flwr/common/context.py +32 -2
- flwr/common/date.py +22 -4
- flwr/common/differential_privacy.py +2 -2
- flwr/common/dp.py +2 -4
- flwr/common/exit_handlers.py +3 -3
- flwr/common/grpc.py +164 -5
- flwr/common/logger.py +230 -12
- flwr/common/message.py +191 -106
- flwr/common/object_ref.py +179 -44
- flwr/common/pyproject.py +1 -0
- flwr/common/record/__init__.py +2 -1
- flwr/common/record/configsrecord.py +58 -18
- flwr/common/record/metricsrecord.py +57 -17
- flwr/common/record/parametersrecord.py +88 -20
- flwr/common/record/recordset.py +153 -30
- flwr/common/record/typeddict.py +30 -55
- flwr/common/recordset_compat.py +31 -12
- flwr/common/retry_invoker.py +123 -30
- flwr/common/secure_aggregation/__init__.py +1 -1
- flwr/common/secure_aggregation/crypto/__init__.py +1 -1
- flwr/common/secure_aggregation/crypto/shamir.py +11 -11
- flwr/common/secure_aggregation/crypto/symmetric_encryption.py +68 -4
- flwr/common/secure_aggregation/ndarrays_arithmetic.py +17 -17
- flwr/common/secure_aggregation/quantization.py +8 -8
- flwr/common/secure_aggregation/secaggplus_constants.py +1 -1
- flwr/common/secure_aggregation/secaggplus_utils.py +10 -12
- flwr/common/serde.py +298 -19
- flwr/common/telemetry.py +65 -29
- flwr/common/typing.py +120 -19
- flwr/common/version.py +17 -3
- flwr/proto/clientappio_pb2.py +45 -0
- flwr/proto/clientappio_pb2.pyi +132 -0
- flwr/proto/clientappio_pb2_grpc.py +135 -0
- flwr/proto/clientappio_pb2_grpc.pyi +53 -0
- flwr/proto/exec_pb2.py +62 -0
- flwr/proto/exec_pb2.pyi +212 -0
- flwr/proto/exec_pb2_grpc.py +237 -0
- flwr/proto/exec_pb2_grpc.pyi +93 -0
- flwr/proto/fab_pb2.py +31 -0
- flwr/proto/fab_pb2.pyi +65 -0
- flwr/proto/fab_pb2_grpc.py +4 -0
- flwr/proto/fab_pb2_grpc.pyi +4 -0
- flwr/proto/fleet_pb2.py +42 -23
- flwr/proto/fleet_pb2.pyi +123 -1
- flwr/proto/fleet_pb2_grpc.py +170 -0
- flwr/proto/fleet_pb2_grpc.pyi +61 -0
- flwr/proto/grpcadapter_pb2.py +32 -0
- flwr/proto/grpcadapter_pb2.pyi +43 -0
- flwr/proto/grpcadapter_pb2_grpc.py +66 -0
- flwr/proto/grpcadapter_pb2_grpc.pyi +24 -0
- flwr/proto/log_pb2.py +29 -0
- flwr/proto/log_pb2.pyi +39 -0
- flwr/proto/log_pb2_grpc.py +4 -0
- flwr/proto/log_pb2_grpc.pyi +4 -0
- flwr/proto/message_pb2.py +41 -0
- flwr/proto/message_pb2.pyi +128 -0
- flwr/proto/message_pb2_grpc.py +4 -0
- flwr/proto/message_pb2_grpc.pyi +4 -0
- flwr/proto/node_pb2.py +1 -1
- flwr/proto/recordset_pb2.py +35 -33
- flwr/proto/recordset_pb2.pyi +40 -14
- flwr/proto/run_pb2.py +64 -0
- flwr/proto/run_pb2.pyi +268 -0
- flwr/proto/run_pb2_grpc.py +4 -0
- flwr/proto/run_pb2_grpc.pyi +4 -0
- flwr/proto/serverappio_pb2.py +52 -0
- flwr/proto/{driver_pb2.pyi → serverappio_pb2.pyi} +62 -20
- flwr/proto/serverappio_pb2_grpc.py +410 -0
- flwr/proto/serverappio_pb2_grpc.pyi +160 -0
- flwr/proto/simulationio_pb2.py +38 -0
- flwr/proto/simulationio_pb2.pyi +65 -0
- flwr/proto/simulationio_pb2_grpc.py +239 -0
- flwr/proto/simulationio_pb2_grpc.pyi +94 -0
- flwr/proto/task_pb2.py +7 -8
- flwr/proto/task_pb2.pyi +8 -5
- flwr/proto/transport_pb2.py +8 -8
- flwr/proto/transport_pb2.pyi +9 -6
- flwr/server/__init__.py +2 -10
- flwr/server/app.py +579 -402
- flwr/server/client_manager.py +8 -6
- flwr/server/compat/app.py +6 -62
- flwr/server/compat/app_utils.py +14 -8
- flwr/server/compat/driver_client_proxy.py +25 -58
- flwr/server/compat/legacy_context.py +5 -4
- flwr/server/driver/__init__.py +2 -0
- flwr/server/driver/driver.py +36 -131
- flwr/server/driver/grpc_driver.py +217 -81
- flwr/server/driver/inmemory_driver.py +182 -0
- flwr/server/history.py +28 -29
- flwr/server/run_serverapp.py +15 -126
- flwr/server/server.py +50 -44
- flwr/server/server_app.py +59 -10
- flwr/server/serverapp/__init__.py +22 -0
- flwr/server/serverapp/app.py +256 -0
- flwr/server/serverapp_components.py +52 -0
- flwr/server/strategy/__init__.py +2 -2
- flwr/server/strategy/aggregate.py +37 -23
- flwr/server/strategy/bulyan.py +9 -9
- flwr/server/strategy/dp_adaptive_clipping.py +25 -25
- flwr/server/strategy/dp_fixed_clipping.py +23 -22
- flwr/server/strategy/dpfedavg_adaptive.py +8 -8
- flwr/server/strategy/dpfedavg_fixed.py +13 -12
- flwr/server/strategy/fault_tolerant_fedavg.py +11 -11
- flwr/server/strategy/fedadagrad.py +9 -9
- flwr/server/strategy/fedadam.py +20 -10
- flwr/server/strategy/fedavg.py +16 -16
- flwr/server/strategy/fedavg_android.py +17 -17
- flwr/server/strategy/fedavgm.py +9 -9
- flwr/server/strategy/fedmedian.py +5 -5
- flwr/server/strategy/fedopt.py +6 -6
- flwr/server/strategy/fedprox.py +7 -7
- flwr/server/strategy/fedtrimmedavg.py +8 -8
- flwr/server/strategy/fedxgb_bagging.py +12 -12
- flwr/server/strategy/fedxgb_cyclic.py +10 -10
- flwr/server/strategy/fedxgb_nn_avg.py +6 -6
- flwr/server/strategy/fedyogi.py +9 -9
- flwr/server/strategy/krum.py +9 -9
- flwr/server/strategy/qfedavg.py +16 -16
- flwr/server/strategy/strategy.py +10 -10
- flwr/server/superlink/driver/__init__.py +2 -2
- flwr/server/superlink/driver/serverappio_grpc.py +61 -0
- flwr/server/superlink/driver/serverappio_servicer.py +363 -0
- flwr/server/superlink/ffs/__init__.py +24 -0
- flwr/server/superlink/ffs/disk_ffs.py +108 -0
- flwr/server/superlink/ffs/ffs.py +79 -0
- flwr/server/superlink/ffs/ffs_factory.py +47 -0
- flwr/server/superlink/fleet/__init__.py +1 -1
- flwr/server/superlink/fleet/grpc_adapter/__init__.py +15 -0
- flwr/server/superlink/fleet/grpc_adapter/grpc_adapter_servicer.py +162 -0
- flwr/server/superlink/fleet/grpc_bidi/__init__.py +1 -1
- flwr/server/superlink/fleet/grpc_bidi/flower_service_servicer.py +4 -2
- flwr/server/superlink/fleet/grpc_bidi/grpc_bridge.py +3 -2
- flwr/server/superlink/fleet/grpc_bidi/grpc_client_proxy.py +1 -1
- flwr/server/superlink/fleet/grpc_bidi/grpc_server.py +5 -154
- flwr/server/superlink/fleet/grpc_rere/__init__.py +1 -1
- flwr/server/superlink/fleet/grpc_rere/fleet_servicer.py +120 -13
- flwr/server/superlink/fleet/grpc_rere/server_interceptor.py +228 -0
- flwr/server/superlink/fleet/message_handler/__init__.py +1 -1
- flwr/server/superlink/fleet/message_handler/message_handler.py +153 -9
- flwr/server/superlink/fleet/rest_rere/__init__.py +1 -1
- flwr/server/superlink/fleet/rest_rere/rest_api.py +119 -81
- flwr/server/superlink/fleet/vce/__init__.py +1 -0
- flwr/server/superlink/fleet/vce/backend/__init__.py +4 -4
- flwr/server/superlink/fleet/vce/backend/backend.py +8 -9
- flwr/server/superlink/fleet/vce/backend/raybackend.py +87 -68
- flwr/server/superlink/fleet/vce/vce_api.py +208 -146
- flwr/server/superlink/linkstate/__init__.py +28 -0
- flwr/server/superlink/linkstate/in_memory_linkstate.py +581 -0
- flwr/server/superlink/linkstate/linkstate.py +389 -0
- flwr/server/superlink/{state/state_factory.py → linkstate/linkstate_factory.py} +19 -10
- flwr/server/superlink/linkstate/sqlite_linkstate.py +1236 -0
- flwr/server/superlink/linkstate/utils.py +389 -0
- flwr/server/superlink/simulation/__init__.py +15 -0
- flwr/server/superlink/simulation/simulationio_grpc.py +65 -0
- flwr/server/superlink/simulation/simulationio_servicer.py +186 -0
- flwr/server/superlink/utils.py +65 -0
- flwr/server/typing.py +2 -0
- flwr/server/utils/__init__.py +1 -1
- flwr/server/utils/tensorboard.py +5 -5
- flwr/server/utils/validator.py +31 -11
- flwr/server/workflow/default_workflows.py +70 -26
- flwr/server/workflow/secure_aggregation/secagg_workflow.py +1 -0
- flwr/server/workflow/secure_aggregation/secaggplus_workflow.py +40 -27
- flwr/simulation/__init__.py +12 -5
- flwr/simulation/app.py +247 -315
- flwr/simulation/legacy_app.py +402 -0
- flwr/simulation/ray_transport/__init__.py +1 -1
- flwr/simulation/ray_transport/ray_actor.py +42 -67
- flwr/simulation/ray_transport/ray_client_proxy.py +37 -17
- flwr/simulation/ray_transport/utils.py +1 -0
- flwr/simulation/run_simulation.py +306 -163
- flwr/simulation/simulationio_connection.py +89 -0
- flwr/superexec/__init__.py +15 -0
- flwr/superexec/app.py +59 -0
- flwr/superexec/deployment.py +188 -0
- flwr/superexec/exec_grpc.py +80 -0
- flwr/superexec/exec_servicer.py +231 -0
- flwr/superexec/exec_user_auth_interceptor.py +101 -0
- flwr/superexec/executor.py +96 -0
- flwr/superexec/simulation.py +124 -0
- {flwr_nightly-1.8.0.dev20240314.dist-info → flwr_nightly-1.15.0.dev20250114.dist-info}/METADATA +33 -26
- flwr_nightly-1.15.0.dev20250114.dist-info/RECORD +328 -0
- flwr_nightly-1.15.0.dev20250114.dist-info/entry_points.txt +12 -0
- flwr/cli/flower_toml.py +0 -140
- flwr/cli/new/templates/app/flower.toml.tpl +0 -13
- flwr/cli/new/templates/app/requirements.numpy.txt.tpl +0 -2
- flwr/cli/new/templates/app/requirements.pytorch.txt.tpl +0 -4
- flwr/cli/new/templates/app/requirements.tensorflow.txt.tpl +0 -4
- flwr/client/node_state.py +0 -48
- flwr/client/node_state_tests.py +0 -65
- flwr/proto/driver_pb2.py +0 -44
- flwr/proto/driver_pb2_grpc.py +0 -169
- flwr/proto/driver_pb2_grpc.pyi +0 -66
- flwr/server/superlink/driver/driver_grpc.py +0 -54
- flwr/server/superlink/driver/driver_servicer.py +0 -129
- flwr/server/superlink/state/in_memory_state.py +0 -230
- flwr/server/superlink/state/sqlite_state.py +0 -630
- flwr/server/superlink/state/state.py +0 -154
- flwr_nightly-1.8.0.dev20240314.dist-info/RECORD +0 -211
- flwr_nightly-1.8.0.dev20240314.dist-info/entry_points.txt +0 -9
- {flwr_nightly-1.8.0.dev20240314.dist-info → flwr_nightly-1.15.0.dev20250114.dist-info}/LICENSE +0 -0
- {flwr_nightly-1.8.0.dev20240314.dist-info → flwr_nightly-1.15.0.dev20250114.dist-info}/WHEEL +0 -0
@@ -0,0 +1,36 @@
|
|
1
|
+
"""$project_name: A Flower / $framework_str app."""
|
2
|
+
|
3
|
+
from flwr.common import Context, ndarrays_to_parameters
|
4
|
+
from flwr.server import ServerApp, ServerAppComponents, ServerConfig
|
5
|
+
from flwr.server.strategy import FedAvg
|
6
|
+
from $import_name.task import get_model, get_model_params, set_initial_params
|
7
|
+
|
8
|
+
|
9
|
+
def server_fn(context: Context):
|
10
|
+
# Read from config
|
11
|
+
num_rounds = context.run_config["num-server-rounds"]
|
12
|
+
|
13
|
+
# Create LogisticRegression Model
|
14
|
+
penalty = context.run_config["penalty"]
|
15
|
+
local_epochs = context.run_config["local-epochs"]
|
16
|
+
model = get_model(penalty, local_epochs)
|
17
|
+
|
18
|
+
# Setting initial parameters, akin to model.compile for keras models
|
19
|
+
set_initial_params(model)
|
20
|
+
|
21
|
+
initial_parameters = ndarrays_to_parameters(get_model_params(model))
|
22
|
+
|
23
|
+
# Define strategy
|
24
|
+
strategy = FedAvg(
|
25
|
+
fraction_fit=1.0,
|
26
|
+
fraction_evaluate=1.0,
|
27
|
+
min_available_clients=2,
|
28
|
+
initial_parameters=initial_parameters,
|
29
|
+
)
|
30
|
+
config = ServerConfig(num_rounds=num_rounds)
|
31
|
+
|
32
|
+
return ServerAppComponents(strategy=strategy, config=config)
|
33
|
+
|
34
|
+
|
35
|
+
# Create ServerApp
|
36
|
+
app = ServerApp(server_fn=server_fn)
|
@@ -1 +1,29 @@
|
|
1
|
-
"""$project_name: A Flower /
|
1
|
+
"""$project_name: A Flower / $framework_str app."""
|
2
|
+
|
3
|
+
from flwr.common import Context, ndarrays_to_parameters
|
4
|
+
from flwr.server import ServerApp, ServerAppComponents, ServerConfig
|
5
|
+
from flwr.server.strategy import FedAvg
|
6
|
+
|
7
|
+
from $import_name.task import load_model
|
8
|
+
|
9
|
+
|
10
|
+
def server_fn(context: Context):
|
11
|
+
# Read from config
|
12
|
+
num_rounds = context.run_config["num-server-rounds"]
|
13
|
+
|
14
|
+
# Get parameters to initialize global model
|
15
|
+
parameters = ndarrays_to_parameters(load_model().get_weights())
|
16
|
+
|
17
|
+
# Define strategy
|
18
|
+
strategy = strategy = FedAvg(
|
19
|
+
fraction_fit=1.0,
|
20
|
+
fraction_evaluate=1.0,
|
21
|
+
min_available_clients=2,
|
22
|
+
initial_parameters=parameters,
|
23
|
+
)
|
24
|
+
config = ServerConfig(num_rounds=num_rounds)
|
25
|
+
|
26
|
+
return ServerAppComponents(strategy=strategy, config=config)
|
27
|
+
|
28
|
+
# Create ServerApp
|
29
|
+
app = ServerApp(server_fn=server_fn)
|
@@ -0,0 +1 @@
|
|
1
|
+
"""$project_name: A Flower Baseline."""
|
@@ -0,0 +1,102 @@
|
|
1
|
+
"""$project_name: A Flower / $framework_str app."""
|
2
|
+
|
3
|
+
import warnings
|
4
|
+
from collections import OrderedDict
|
5
|
+
|
6
|
+
import torch
|
7
|
+
import transformers
|
8
|
+
from datasets.utils.logging import disable_progress_bar
|
9
|
+
from evaluate import load as load_metric
|
10
|
+
from flwr_datasets import FederatedDataset
|
11
|
+
from flwr_datasets.partitioner import IidPartitioner
|
12
|
+
from torch.optim import AdamW
|
13
|
+
from torch.utils.data import DataLoader
|
14
|
+
from transformers import AutoTokenizer, DataCollatorWithPadding
|
15
|
+
|
16
|
+
warnings.filterwarnings("ignore", category=UserWarning)
|
17
|
+
warnings.filterwarnings("ignore", category=FutureWarning)
|
18
|
+
disable_progress_bar()
|
19
|
+
transformers.logging.set_verbosity_error()
|
20
|
+
|
21
|
+
|
22
|
+
fds = None # Cache FederatedDataset
|
23
|
+
|
24
|
+
|
25
|
+
def load_data(partition_id: int, num_partitions: int, model_name: str):
|
26
|
+
"""Load IMDB data (training and eval)"""
|
27
|
+
# Only initialize `FederatedDataset` once
|
28
|
+
global fds
|
29
|
+
if fds is None:
|
30
|
+
partitioner = IidPartitioner(num_partitions=num_partitions)
|
31
|
+
fds = FederatedDataset(
|
32
|
+
dataset="stanfordnlp/imdb",
|
33
|
+
partitioners={"train": partitioner},
|
34
|
+
)
|
35
|
+
partition = fds.load_partition(partition_id)
|
36
|
+
# Divide data: 80% train, 20% test
|
37
|
+
partition_train_test = partition.train_test_split(test_size=0.2, seed=42)
|
38
|
+
|
39
|
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
40
|
+
|
41
|
+
def tokenize_function(examples):
|
42
|
+
return tokenizer(
|
43
|
+
examples["text"], truncation=True, add_special_tokens=True, max_length=512
|
44
|
+
)
|
45
|
+
|
46
|
+
partition_train_test = partition_train_test.map(tokenize_function, batched=True)
|
47
|
+
partition_train_test = partition_train_test.remove_columns("text")
|
48
|
+
partition_train_test = partition_train_test.rename_column("label", "labels")
|
49
|
+
|
50
|
+
data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
|
51
|
+
trainloader = DataLoader(
|
52
|
+
partition_train_test["train"],
|
53
|
+
shuffle=True,
|
54
|
+
batch_size=32,
|
55
|
+
collate_fn=data_collator,
|
56
|
+
)
|
57
|
+
|
58
|
+
testloader = DataLoader(
|
59
|
+
partition_train_test["test"], batch_size=32, collate_fn=data_collator
|
60
|
+
)
|
61
|
+
|
62
|
+
return trainloader, testloader
|
63
|
+
|
64
|
+
|
65
|
+
def train(net, trainloader, epochs, device):
|
66
|
+
optimizer = AdamW(net.parameters(), lr=5e-5)
|
67
|
+
net.train()
|
68
|
+
for _ in range(epochs):
|
69
|
+
for batch in trainloader:
|
70
|
+
batch = {k: v.to(device) for k, v in batch.items()}
|
71
|
+
outputs = net(**batch)
|
72
|
+
loss = outputs.loss
|
73
|
+
loss.backward()
|
74
|
+
optimizer.step()
|
75
|
+
optimizer.zero_grad()
|
76
|
+
|
77
|
+
|
78
|
+
def test(net, testloader, device):
|
79
|
+
metric = load_metric("accuracy")
|
80
|
+
loss = 0
|
81
|
+
net.eval()
|
82
|
+
for batch in testloader:
|
83
|
+
batch = {k: v.to(device) for k, v in batch.items()}
|
84
|
+
with torch.no_grad():
|
85
|
+
outputs = net(**batch)
|
86
|
+
logits = outputs.logits
|
87
|
+
loss += outputs.loss.item()
|
88
|
+
predictions = torch.argmax(logits, dim=-1)
|
89
|
+
metric.add_batch(predictions=predictions, references=batch["labels"])
|
90
|
+
loss /= len(testloader.dataset)
|
91
|
+
accuracy = metric.compute()["accuracy"]
|
92
|
+
return loss, accuracy
|
93
|
+
|
94
|
+
|
95
|
+
def get_weights(net):
|
96
|
+
return [val.cpu().numpy() for _, val in net.state_dict().items()]
|
97
|
+
|
98
|
+
|
99
|
+
def set_weights(net, parameters):
|
100
|
+
params_dict = zip(net.state_dict().keys(), parameters)
|
101
|
+
state_dict = OrderedDict({k: torch.tensor(v) for k, v in params_dict})
|
102
|
+
net.load_state_dict(state_dict, strict=True)
|
@@ -0,0 +1,57 @@
|
|
1
|
+
"""$project_name: A Flower / $framework_str app."""
|
2
|
+
|
3
|
+
import jax
|
4
|
+
import jax.numpy as jnp
|
5
|
+
import numpy as np
|
6
|
+
from sklearn.datasets import make_regression
|
7
|
+
from sklearn.model_selection import train_test_split
|
8
|
+
|
9
|
+
key = jax.random.PRNGKey(0)
|
10
|
+
|
11
|
+
|
12
|
+
def load_data():
|
13
|
+
# Load dataset
|
14
|
+
X, y = make_regression(n_features=3, random_state=0)
|
15
|
+
X, X_test, y, y_test = train_test_split(X, y)
|
16
|
+
return X, y, X_test, y_test
|
17
|
+
|
18
|
+
|
19
|
+
def load_model(model_shape):
|
20
|
+
# Extract model parameters
|
21
|
+
params = {"b": jax.random.uniform(key), "w": jax.random.uniform(key, model_shape)}
|
22
|
+
return params
|
23
|
+
|
24
|
+
|
25
|
+
def loss_fn(params, X, y):
|
26
|
+
# Return MSE as loss
|
27
|
+
err = jnp.dot(X, params["w"]) + params["b"] - y
|
28
|
+
return jnp.mean(jnp.square(err))
|
29
|
+
|
30
|
+
|
31
|
+
def train(params, grad_fn, X, y):
|
32
|
+
loss = 1_000_000
|
33
|
+
num_examples = X.shape[0]
|
34
|
+
for epochs in range(50):
|
35
|
+
grads = grad_fn(params, X, y)
|
36
|
+
params = jax.tree.map(lambda p, g: p - 0.05 * g, params, grads)
|
37
|
+
loss = loss_fn(params, X, y)
|
38
|
+
return params, loss, num_examples
|
39
|
+
|
40
|
+
|
41
|
+
def evaluation(params, grad_fn, X_test, y_test):
|
42
|
+
num_examples = X_test.shape[0]
|
43
|
+
err_test = loss_fn(params, X_test, y_test)
|
44
|
+
loss_test = jnp.mean(jnp.square(err_test))
|
45
|
+
return loss_test, num_examples
|
46
|
+
|
47
|
+
|
48
|
+
def get_params(params):
|
49
|
+
parameters = []
|
50
|
+
for _, val in params.items():
|
51
|
+
parameters.append(np.array(val))
|
52
|
+
return parameters
|
53
|
+
|
54
|
+
|
55
|
+
def set_params(local_params, global_params):
|
56
|
+
for key, value in list(zip(local_params.keys(), global_params)):
|
57
|
+
local_params[key] = value
|
@@ -0,0 +1,102 @@
|
|
1
|
+
"""$project_name: A Flower / $framework_str app."""
|
2
|
+
|
3
|
+
import mlx.core as mx
|
4
|
+
import mlx.nn as nn
|
5
|
+
import numpy as np
|
6
|
+
from flwr_datasets import FederatedDataset
|
7
|
+
from flwr_datasets.partitioner import IidPartitioner
|
8
|
+
|
9
|
+
from datasets.utils.logging import disable_progress_bar
|
10
|
+
|
11
|
+
disable_progress_bar()
|
12
|
+
|
13
|
+
|
14
|
+
class MLP(nn.Module):
|
15
|
+
"""A simple MLP."""
|
16
|
+
|
17
|
+
def __init__(
|
18
|
+
self, num_layers: int, input_dim: int, hidden_dim: int, output_dim: int
|
19
|
+
):
|
20
|
+
super().__init__()
|
21
|
+
layer_sizes = [input_dim] + [hidden_dim] * num_layers + [output_dim]
|
22
|
+
self.layers = [
|
23
|
+
nn.Linear(idim, odim)
|
24
|
+
for idim, odim in zip(layer_sizes[:-1], layer_sizes[1:])
|
25
|
+
]
|
26
|
+
|
27
|
+
def __call__(self, x):
|
28
|
+
for l in self.layers[:-1]:
|
29
|
+
x = mx.maximum(l(x), 0.0)
|
30
|
+
return self.layers[-1](x)
|
31
|
+
|
32
|
+
|
33
|
+
def loss_fn(model, X, y):
|
34
|
+
return mx.mean(nn.losses.cross_entropy(model(X), y))
|
35
|
+
|
36
|
+
|
37
|
+
def eval_fn(model, X, y):
|
38
|
+
return mx.mean(mx.argmax(model(X), axis=1) == y)
|
39
|
+
|
40
|
+
|
41
|
+
def batch_iterate(batch_size, X, y):
|
42
|
+
perm = mx.array(np.random.permutation(y.size))
|
43
|
+
for s in range(0, y.size, batch_size):
|
44
|
+
ids = perm[s : s + batch_size]
|
45
|
+
yield X[ids], y[ids]
|
46
|
+
|
47
|
+
|
48
|
+
fds = None # Cache FederatedDataset
|
49
|
+
|
50
|
+
|
51
|
+
def load_data(partition_id: int, num_partitions: int):
|
52
|
+
# Only initialize `FederatedDataset` once
|
53
|
+
global fds
|
54
|
+
if fds is None:
|
55
|
+
partitioner = IidPartitioner(num_partitions=num_partitions)
|
56
|
+
fds = FederatedDataset(
|
57
|
+
dataset="ylecun/mnist",
|
58
|
+
partitioners={"train": partitioner},
|
59
|
+
trust_remote_code=True,
|
60
|
+
)
|
61
|
+
partition = fds.load_partition(partition_id)
|
62
|
+
partition_splits = partition.train_test_split(test_size=0.2, seed=42)
|
63
|
+
|
64
|
+
partition_splits["train"].set_format("numpy")
|
65
|
+
partition_splits["test"].set_format("numpy")
|
66
|
+
|
67
|
+
train_partition = partition_splits["train"].map(
|
68
|
+
lambda img: {
|
69
|
+
"img": img.reshape(-1, 28 * 28).squeeze().astype(np.float32) / 255.0
|
70
|
+
},
|
71
|
+
input_columns="image",
|
72
|
+
)
|
73
|
+
test_partition = partition_splits["test"].map(
|
74
|
+
lambda img: {
|
75
|
+
"img": img.reshape(-1, 28 * 28).squeeze().astype(np.float32) / 255.0
|
76
|
+
},
|
77
|
+
input_columns="image",
|
78
|
+
)
|
79
|
+
|
80
|
+
data = (
|
81
|
+
train_partition["img"],
|
82
|
+
train_partition["label"].astype(np.uint32),
|
83
|
+
test_partition["img"],
|
84
|
+
test_partition["label"].astype(np.uint32),
|
85
|
+
)
|
86
|
+
|
87
|
+
train_images, train_labels, test_images, test_labels = map(mx.array, data)
|
88
|
+
return train_images, train_labels, test_images, test_labels
|
89
|
+
|
90
|
+
|
91
|
+
def get_params(model):
|
92
|
+
layers = model.parameters()["layers"]
|
93
|
+
return [np.array(val) for layer in layers for _, val in layer.items()]
|
94
|
+
|
95
|
+
|
96
|
+
def set_params(model, parameters):
|
97
|
+
new_params = {}
|
98
|
+
new_params["layers"] = [
|
99
|
+
{"weight": mx.array(parameters[i]), "bias": mx.array(parameters[i + 1])}
|
100
|
+
for i in range(0, len(parameters), 2)
|
101
|
+
]
|
102
|
+
model.update(new_params)
|
@@ -1,16 +1,14 @@
|
|
1
|
-
"""$project_name: A Flower /
|
1
|
+
"""$project_name: A Flower / $framework_str app."""
|
2
2
|
|
3
3
|
from collections import OrderedDict
|
4
4
|
|
5
5
|
import torch
|
6
6
|
import torch.nn as nn
|
7
7
|
import torch.nn.functional as F
|
8
|
+
from flwr_datasets import FederatedDataset
|
9
|
+
from flwr_datasets.partitioner import IidPartitioner
|
8
10
|
from torch.utils.data import DataLoader
|
9
|
-
from torchvision.datasets import CIFAR10
|
10
11
|
from torchvision.transforms import Compose, Normalize, ToTensor
|
11
|
-
from flwr_datasets import FederatedDataset
|
12
|
-
|
13
|
-
DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
14
12
|
|
15
13
|
|
16
14
|
class Net(nn.Module):
|
@@ -34,12 +32,22 @@ class Net(nn.Module):
|
|
34
32
|
return self.fc3(x)
|
35
33
|
|
36
34
|
|
37
|
-
|
35
|
+
fds = None # Cache FederatedDataset
|
36
|
+
|
37
|
+
|
38
|
+
def load_data(partition_id: int, num_partitions: int):
|
38
39
|
"""Load partition CIFAR10 data."""
|
39
|
-
|
40
|
+
# Only initialize `FederatedDataset` once
|
41
|
+
global fds
|
42
|
+
if fds is None:
|
43
|
+
partitioner = IidPartitioner(num_partitions=num_partitions)
|
44
|
+
fds = FederatedDataset(
|
45
|
+
dataset="uoft-cs/cifar10",
|
46
|
+
partitioners={"train": partitioner},
|
47
|
+
)
|
40
48
|
partition = fds.load_partition(partition_id)
|
41
49
|
# Divide data on each node: 80% train, 20% test
|
42
|
-
partition_train_test = partition.train_test_split(test_size=0.2)
|
50
|
+
partition_train_test = partition.train_test_split(test_size=0.2, seed=42)
|
43
51
|
pytorch_transforms = Compose(
|
44
52
|
[ToTensor(), Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]
|
45
53
|
)
|
@@ -55,44 +63,41 @@ def load_data(partition_id, num_partitions):
|
|
55
63
|
return trainloader, testloader
|
56
64
|
|
57
65
|
|
58
|
-
def train(net, trainloader,
|
66
|
+
def train(net, trainloader, epochs, device):
|
59
67
|
"""Train the model on the training set."""
|
60
68
|
net.to(device) # move model to GPU if available
|
61
69
|
criterion = torch.nn.CrossEntropyLoss().to(device)
|
62
|
-
optimizer = torch.optim.
|
70
|
+
optimizer = torch.optim.Adam(net.parameters(), lr=0.01)
|
63
71
|
net.train()
|
72
|
+
running_loss = 0.0
|
64
73
|
for _ in range(epochs):
|
65
74
|
for batch in trainloader:
|
66
75
|
images = batch["img"]
|
67
76
|
labels = batch["label"]
|
68
77
|
optimizer.zero_grad()
|
69
|
-
criterion(net(images.to(
|
78
|
+
loss = criterion(net(images.to(device)), labels.to(device))
|
79
|
+
loss.backward()
|
70
80
|
optimizer.step()
|
81
|
+
running_loss += loss.item()
|
71
82
|
|
72
|
-
|
73
|
-
|
74
|
-
|
75
|
-
results = {
|
76
|
-
"train_loss": train_loss,
|
77
|
-
"train_accuracy": train_acc,
|
78
|
-
"val_loss": val_loss,
|
79
|
-
"val_accuracy": val_acc,
|
80
|
-
}
|
81
|
-
return results
|
83
|
+
avg_trainloss = running_loss / len(trainloader)
|
84
|
+
return avg_trainloss
|
82
85
|
|
83
86
|
|
84
|
-
def test(net, testloader):
|
87
|
+
def test(net, testloader, device):
|
85
88
|
"""Validate the model on the test set."""
|
89
|
+
net.to(device)
|
86
90
|
criterion = torch.nn.CrossEntropyLoss()
|
87
91
|
correct, loss = 0, 0.0
|
88
92
|
with torch.no_grad():
|
89
93
|
for batch in testloader:
|
90
|
-
images = batch["img"].to(
|
91
|
-
labels = batch["label"].to(
|
94
|
+
images = batch["img"].to(device)
|
95
|
+
labels = batch["label"].to(device)
|
92
96
|
outputs = net(images)
|
93
97
|
loss += criterion(outputs, labels).item()
|
94
98
|
correct += (torch.max(outputs.data, 1)[1] == labels).sum().item()
|
95
99
|
accuracy = correct / len(testloader.dataset)
|
100
|
+
loss = loss / len(testloader)
|
96
101
|
return loss, accuracy
|
97
102
|
|
98
103
|
|
@@ -0,0 +1,67 @@
|
|
1
|
+
"""$project_name: A Flower / $framework_str app."""
|
2
|
+
|
3
|
+
import numpy as np
|
4
|
+
from flwr_datasets import FederatedDataset
|
5
|
+
from flwr_datasets.partitioner import IidPartitioner
|
6
|
+
from sklearn.linear_model import LogisticRegression
|
7
|
+
|
8
|
+
fds = None # Cache FederatedDataset
|
9
|
+
|
10
|
+
|
11
|
+
def load_data(partition_id: int, num_partitions: int):
|
12
|
+
"""Load partition MNIST data."""
|
13
|
+
# Only initialize `FederatedDataset` once
|
14
|
+
global fds
|
15
|
+
if fds is None:
|
16
|
+
partitioner = IidPartitioner(num_partitions=num_partitions)
|
17
|
+
fds = FederatedDataset(
|
18
|
+
dataset="mnist",
|
19
|
+
partitioners={"train": partitioner},
|
20
|
+
)
|
21
|
+
|
22
|
+
dataset = fds.load_partition(partition_id, "train").with_format("numpy")
|
23
|
+
|
24
|
+
X, y = dataset["image"].reshape((len(dataset), -1)), dataset["label"]
|
25
|
+
|
26
|
+
# Split the on edge data: 80% train, 20% test
|
27
|
+
X_train, X_test = X[: int(0.8 * len(X))], X[int(0.8 * len(X)) :]
|
28
|
+
y_train, y_test = y[: int(0.8 * len(y))], y[int(0.8 * len(y)) :]
|
29
|
+
|
30
|
+
return X_train, X_test, y_train, y_test
|
31
|
+
|
32
|
+
|
33
|
+
def get_model(penalty: str, local_epochs: int):
|
34
|
+
|
35
|
+
return LogisticRegression(
|
36
|
+
penalty=penalty,
|
37
|
+
max_iter=local_epochs,
|
38
|
+
warm_start=True,
|
39
|
+
)
|
40
|
+
|
41
|
+
|
42
|
+
def get_model_params(model):
|
43
|
+
if model.fit_intercept:
|
44
|
+
params = [
|
45
|
+
model.coef_,
|
46
|
+
model.intercept_,
|
47
|
+
]
|
48
|
+
else:
|
49
|
+
params = [model.coef_]
|
50
|
+
return params
|
51
|
+
|
52
|
+
|
53
|
+
def set_model_params(model, params):
|
54
|
+
model.coef_ = params[0]
|
55
|
+
if model.fit_intercept:
|
56
|
+
model.intercept_ = params[1]
|
57
|
+
return model
|
58
|
+
|
59
|
+
|
60
|
+
def set_initial_params(model):
|
61
|
+
n_classes = 10 # MNIST has 10 classes
|
62
|
+
n_features = 784 # Number of features in dataset
|
63
|
+
model.classes_ = np.array([i for i in range(10)])
|
64
|
+
|
65
|
+
model.coef_ = np.zeros((n_classes, n_features))
|
66
|
+
if model.fit_intercept:
|
67
|
+
model.intercept_ = np.zeros((n_classes,))
|
@@ -0,0 +1,53 @@
|
|
1
|
+
"""$project_name: A Flower / $framework_str app."""
|
2
|
+
|
3
|
+
import os
|
4
|
+
|
5
|
+
import keras
|
6
|
+
from keras import layers
|
7
|
+
from flwr_datasets import FederatedDataset
|
8
|
+
from flwr_datasets.partitioner import IidPartitioner
|
9
|
+
|
10
|
+
|
11
|
+
# Make TensorFlow log less verbose
|
12
|
+
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
|
13
|
+
|
14
|
+
|
15
|
+
def load_model():
|
16
|
+
# Define a simple CNN for CIFAR-10 and set Adam optimizer
|
17
|
+
model = keras.Sequential(
|
18
|
+
[
|
19
|
+
keras.Input(shape=(32, 32, 3)),
|
20
|
+
layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
|
21
|
+
layers.MaxPooling2D(pool_size=(2, 2)),
|
22
|
+
layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
|
23
|
+
layers.MaxPooling2D(pool_size=(2, 2)),
|
24
|
+
layers.Flatten(),
|
25
|
+
layers.Dropout(0.5),
|
26
|
+
layers.Dense(10, activation="softmax"),
|
27
|
+
]
|
28
|
+
)
|
29
|
+
model.compile("adam", "sparse_categorical_crossentropy", metrics=["accuracy"])
|
30
|
+
return model
|
31
|
+
|
32
|
+
|
33
|
+
fds = None # Cache FederatedDataset
|
34
|
+
|
35
|
+
|
36
|
+
def load_data(partition_id, num_partitions):
|
37
|
+
# Download and partition dataset
|
38
|
+
# Only initialize `FederatedDataset` once
|
39
|
+
global fds
|
40
|
+
if fds is None:
|
41
|
+
partitioner = IidPartitioner(num_partitions=num_partitions)
|
42
|
+
fds = FederatedDataset(
|
43
|
+
dataset="uoft-cs/cifar10",
|
44
|
+
partitioners={"train": partitioner},
|
45
|
+
)
|
46
|
+
partition = fds.load_partition(partition_id, "train")
|
47
|
+
partition.set_format("numpy")
|
48
|
+
|
49
|
+
# Divide data on each node: 80% train, 20% test
|
50
|
+
partition = partition.train_test_split(test_size=0.2)
|
51
|
+
x_train, y_train = partition["train"]["img"] / 255.0, partition["train"]["label"]
|
52
|
+
x_test, y_test = partition["test"]["img"] / 255.0, partition["test"]["label"]
|
53
|
+
return x_train, y_train, x_test, y_test
|
@@ -0,0 +1 @@
|
|
1
|
+
"""$project_name: A Flower Baseline."""
|