flwr 1.23.0__py3-none-any.whl → 1.25.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- flwr/__init__.py +16 -5
- flwr/app/error.py +2 -2
- flwr/app/exception.py +3 -3
- flwr/cli/app.py +19 -0
- flwr/cli/{new/templates → app_cmd}/__init__.py +9 -1
- flwr/cli/app_cmd/publish.py +285 -0
- flwr/cli/app_cmd/review.py +262 -0
- flwr/cli/auth_plugin/auth_plugin.py +4 -5
- flwr/cli/auth_plugin/noop_auth_plugin.py +54 -11
- flwr/cli/auth_plugin/oidc_cli_plugin.py +32 -9
- flwr/cli/build.py +60 -18
- flwr/cli/cli_account_auth_interceptor.py +24 -7
- flwr/cli/config_utils.py +101 -13
- flwr/cli/{new/templates/app/code/flwr_tune → federation}/__init__.py +10 -1
- flwr/cli/federation/ls.py +140 -0
- flwr/cli/federation/show.py +318 -0
- flwr/cli/install.py +91 -13
- flwr/cli/log.py +52 -9
- flwr/cli/login/login.py +7 -4
- flwr/cli/ls.py +211 -130
- flwr/cli/new/new.py +123 -331
- flwr/cli/pull.py +10 -5
- flwr/cli/run/run.py +71 -29
- flwr/cli/run_utils.py +148 -0
- flwr/cli/stop.py +26 -8
- flwr/cli/supernode/ls.py +25 -12
- flwr/cli/supernode/register.py +9 -4
- flwr/cli/supernode/unregister.py +5 -3
- flwr/cli/utils.py +239 -16
- flwr/client/__init__.py +1 -1
- flwr/client/dpfedavg_numpy_client.py +4 -1
- flwr/client/grpc_adapter_client/connection.py +8 -9
- flwr/client/grpc_rere_client/connection.py +16 -14
- flwr/client/grpc_rere_client/grpc_adapter.py +6 -2
- flwr/client/grpc_rere_client/node_auth_client_interceptor.py +2 -1
- flwr/client/message_handler/message_handler.py +2 -2
- flwr/client/mod/secure_aggregation/secaggplus_mod.py +3 -3
- flwr/client/numpy_client.py +1 -1
- flwr/client/rest_client/connection.py +18 -18
- flwr/client/run_info_store.py +4 -5
- flwr/client/typing.py +1 -1
- flwr/clientapp/client_app.py +9 -10
- flwr/clientapp/mod/centraldp_mods.py +16 -17
- flwr/clientapp/mod/localdp_mod.py +8 -9
- flwr/clientapp/typing.py +1 -1
- flwr/clientapp/utils.py +3 -3
- flwr/common/address.py +1 -2
- flwr/common/args.py +3 -4
- flwr/common/config.py +13 -16
- flwr/common/constant.py +5 -2
- flwr/common/differential_privacy.py +3 -4
- flwr/common/event_log_plugin/event_log_plugin.py +3 -4
- flwr/common/exit/exit.py +15 -2
- flwr/common/exit/exit_code.py +19 -0
- flwr/common/exit/exit_handler.py +6 -2
- flwr/common/exit/signal_handler.py +5 -5
- flwr/common/grpc.py +6 -6
- flwr/common/inflatable_protobuf_utils.py +1 -1
- flwr/common/inflatable_utils.py +38 -21
- flwr/common/logger.py +19 -19
- flwr/common/message.py +4 -4
- flwr/common/object_ref.py +7 -7
- flwr/common/record/array.py +3 -3
- flwr/common/record/arrayrecord.py +18 -30
- flwr/common/record/configrecord.py +3 -3
- flwr/common/record/recorddict.py +5 -5
- flwr/common/record/typeddict.py +9 -2
- flwr/common/recorddict_compat.py +7 -10
- flwr/common/retry_invoker.py +20 -20
- flwr/common/secure_aggregation/ndarrays_arithmetic.py +3 -3
- flwr/common/serde.py +11 -4
- flwr/common/serde_utils.py +2 -2
- flwr/common/telemetry.py +9 -5
- flwr/common/typing.py +58 -37
- flwr/compat/client/app.py +38 -37
- flwr/compat/client/grpc_client/connection.py +11 -11
- flwr/compat/server/app.py +5 -6
- flwr/proto/appio_pb2.py +13 -3
- flwr/proto/appio_pb2.pyi +134 -65
- flwr/proto/appio_pb2_grpc.py +20 -0
- flwr/proto/appio_pb2_grpc.pyi +27 -0
- flwr/proto/clientappio_pb2.py +17 -7
- flwr/proto/clientappio_pb2.pyi +15 -0
- flwr/proto/clientappio_pb2_grpc.py +206 -40
- flwr/proto/clientappio_pb2_grpc.pyi +168 -53
- flwr/proto/control_pb2.py +71 -52
- flwr/proto/control_pb2.pyi +277 -111
- flwr/proto/control_pb2_grpc.py +249 -40
- flwr/proto/control_pb2_grpc.pyi +185 -52
- flwr/proto/error_pb2.py +13 -3
- flwr/proto/error_pb2.pyi +24 -6
- flwr/proto/error_pb2_grpc.py +20 -0
- flwr/proto/error_pb2_grpc.pyi +27 -0
- flwr/proto/fab_pb2.py +14 -4
- flwr/proto/fab_pb2.pyi +59 -31
- flwr/proto/fab_pb2_grpc.py +20 -0
- flwr/proto/fab_pb2_grpc.pyi +27 -0
- flwr/proto/federation_pb2.py +38 -0
- flwr/proto/federation_pb2.pyi +56 -0
- flwr/proto/federation_pb2_grpc.py +24 -0
- flwr/proto/federation_pb2_grpc.pyi +31 -0
- flwr/proto/fleet_pb2.py +24 -14
- flwr/proto/fleet_pb2.pyi +141 -61
- flwr/proto/fleet_pb2_grpc.py +189 -48
- flwr/proto/fleet_pb2_grpc.pyi +175 -61
- flwr/proto/grpcadapter_pb2.py +14 -4
- flwr/proto/grpcadapter_pb2.pyi +38 -16
- flwr/proto/grpcadapter_pb2_grpc.py +35 -4
- flwr/proto/grpcadapter_pb2_grpc.pyi +38 -7
- flwr/proto/heartbeat_pb2.py +17 -7
- flwr/proto/heartbeat_pb2.pyi +51 -22
- flwr/proto/heartbeat_pb2_grpc.py +20 -0
- flwr/proto/heartbeat_pb2_grpc.pyi +27 -0
- flwr/proto/log_pb2.py +13 -3
- flwr/proto/log_pb2.pyi +34 -11
- flwr/proto/log_pb2_grpc.py +20 -0
- flwr/proto/log_pb2_grpc.pyi +27 -0
- flwr/proto/message_pb2.py +15 -5
- flwr/proto/message_pb2.pyi +154 -86
- flwr/proto/message_pb2_grpc.py +20 -0
- flwr/proto/message_pb2_grpc.pyi +27 -0
- flwr/proto/node_pb2.py +15 -5
- flwr/proto/node_pb2.pyi +50 -25
- flwr/proto/node_pb2_grpc.py +20 -0
- flwr/proto/node_pb2_grpc.pyi +27 -0
- flwr/proto/recorddict_pb2.py +13 -3
- flwr/proto/recorddict_pb2.pyi +184 -107
- flwr/proto/recorddict_pb2_grpc.py +20 -0
- flwr/proto/recorddict_pb2_grpc.pyi +27 -0
- flwr/proto/run_pb2.py +40 -31
- flwr/proto/run_pb2.pyi +158 -84
- flwr/proto/run_pb2_grpc.py +20 -0
- flwr/proto/run_pb2_grpc.pyi +27 -0
- flwr/proto/serverappio_pb2.py +13 -3
- flwr/proto/serverappio_pb2.pyi +32 -8
- flwr/proto/serverappio_pb2_grpc.py +246 -65
- flwr/proto/serverappio_pb2_grpc.pyi +221 -85
- flwr/proto/simulationio_pb2.py +16 -8
- flwr/proto/simulationio_pb2.pyi +15 -0
- flwr/proto/simulationio_pb2_grpc.py +162 -41
- flwr/proto/simulationio_pb2_grpc.pyi +149 -55
- flwr/proto/transport_pb2.py +20 -10
- flwr/proto/transport_pb2.pyi +249 -160
- flwr/proto/transport_pb2_grpc.py +35 -4
- flwr/proto/transport_pb2_grpc.pyi +38 -8
- flwr/server/app.py +39 -17
- flwr/server/client_manager.py +4 -5
- flwr/server/client_proxy.py +10 -11
- flwr/server/compat/app.py +4 -5
- flwr/server/compat/app_utils.py +2 -1
- flwr/server/compat/grid_client_proxy.py +10 -12
- flwr/server/compat/legacy_context.py +3 -4
- flwr/server/fleet_event_log_interceptor.py +2 -1
- flwr/server/grid/grid.py +2 -3
- flwr/server/grid/grpc_grid.py +10 -8
- flwr/server/grid/inmemory_grid.py +4 -4
- flwr/server/run_serverapp.py +2 -3
- flwr/server/server.py +34 -39
- flwr/server/server_app.py +7 -8
- flwr/server/server_config.py +1 -2
- flwr/server/serverapp/app.py +34 -28
- flwr/server/serverapp_components.py +4 -5
- flwr/server/strategy/aggregate.py +9 -8
- flwr/server/strategy/bulyan.py +13 -11
- flwr/server/strategy/dp_adaptive_clipping.py +16 -20
- flwr/server/strategy/dp_fixed_clipping.py +12 -17
- flwr/server/strategy/dpfedavg_adaptive.py +3 -4
- flwr/server/strategy/dpfedavg_fixed.py +6 -10
- flwr/server/strategy/fault_tolerant_fedavg.py +14 -13
- flwr/server/strategy/fedadagrad.py +18 -14
- flwr/server/strategy/fedadam.py +16 -14
- flwr/server/strategy/fedavg.py +16 -17
- flwr/server/strategy/fedavg_android.py +15 -15
- flwr/server/strategy/fedavgm.py +21 -18
- flwr/server/strategy/fedmedian.py +2 -3
- flwr/server/strategy/fedopt.py +11 -10
- flwr/server/strategy/fedprox.py +10 -9
- flwr/server/strategy/fedtrimmedavg.py +12 -11
- flwr/server/strategy/fedxgb_bagging.py +13 -11
- flwr/server/strategy/fedxgb_cyclic.py +6 -6
- flwr/server/strategy/fedxgb_nn_avg.py +4 -4
- flwr/server/strategy/fedyogi.py +16 -14
- flwr/server/strategy/krum.py +12 -11
- flwr/server/strategy/qfedavg.py +16 -15
- flwr/server/strategy/strategy.py +6 -9
- flwr/server/superlink/fleet/grpc_adapter/grpc_adapter_servicer.py +2 -1
- flwr/server/superlink/fleet/grpc_bidi/flower_service_servicer.py +1 -2
- flwr/server/superlink/fleet/grpc_bidi/grpc_bridge.py +3 -4
- flwr/server/superlink/fleet/grpc_bidi/grpc_client_proxy.py +10 -12
- flwr/server/superlink/fleet/grpc_bidi/grpc_server.py +1 -3
- flwr/server/superlink/fleet/grpc_rere/fleet_servicer.py +4 -4
- flwr/server/superlink/fleet/grpc_rere/node_auth_server_interceptor.py +3 -2
- flwr/server/superlink/fleet/message_handler/message_handler.py +75 -30
- flwr/server/superlink/fleet/rest_rere/rest_api.py +2 -2
- flwr/server/superlink/fleet/vce/backend/backend.py +1 -1
- flwr/server/superlink/fleet/vce/backend/raybackend.py +5 -5
- flwr/server/superlink/fleet/vce/vce_api.py +15 -9
- flwr/server/superlink/linkstate/in_memory_linkstate.py +148 -149
- flwr/server/superlink/linkstate/linkstate.py +91 -43
- flwr/server/superlink/linkstate/linkstate_factory.py +22 -5
- flwr/server/superlink/linkstate/sqlite_linkstate.py +502 -436
- flwr/server/superlink/linkstate/utils.py +6 -6
- flwr/server/superlink/serverappio/serverappio_grpc.py +1 -2
- flwr/server/superlink/serverappio/serverappio_servicer.py +26 -21
- flwr/server/superlink/simulation/simulationio_grpc.py +1 -2
- flwr/server/superlink/simulation/simulationio_servicer.py +18 -13
- flwr/server/superlink/utils.py +4 -6
- flwr/server/typing.py +1 -1
- flwr/server/utils/tensorboard.py +15 -8
- flwr/server/workflow/default_workflows.py +5 -5
- flwr/server/workflow/secure_aggregation/secagg_workflow.py +2 -4
- flwr/server/workflow/secure_aggregation/secaggplus_workflow.py +8 -8
- flwr/serverapp/strategy/bulyan.py +16 -15
- flwr/serverapp/strategy/dp_adaptive_clipping.py +12 -11
- flwr/serverapp/strategy/dp_fixed_clipping.py +11 -14
- flwr/serverapp/strategy/fedadagrad.py +10 -11
- flwr/serverapp/strategy/fedadam.py +10 -11
- flwr/serverapp/strategy/fedavg.py +9 -10
- flwr/serverapp/strategy/fedavgm.py +17 -16
- flwr/serverapp/strategy/fedmedian.py +2 -2
- flwr/serverapp/strategy/fedopt.py +10 -11
- flwr/serverapp/strategy/fedprox.py +7 -8
- flwr/serverapp/strategy/fedtrimmedavg.py +9 -9
- flwr/serverapp/strategy/fedxgb_bagging.py +3 -3
- flwr/serverapp/strategy/fedxgb_cyclic.py +9 -9
- flwr/serverapp/strategy/fedyogi.py +9 -11
- flwr/serverapp/strategy/krum.py +7 -7
- flwr/serverapp/strategy/multikrum.py +9 -9
- flwr/serverapp/strategy/qfedavg.py +17 -16
- flwr/serverapp/strategy/strategy.py +6 -9
- flwr/serverapp/strategy/strategy_utils.py +7 -8
- flwr/simulation/app.py +46 -42
- flwr/simulation/legacy_app.py +12 -12
- flwr/simulation/ray_transport/ray_actor.py +10 -11
- flwr/simulation/ray_transport/ray_client_proxy.py +11 -12
- flwr/simulation/run_simulation.py +43 -43
- flwr/simulation/simulationio_connection.py +4 -4
- flwr/supercore/cli/flower_superexec.py +3 -4
- flwr/supercore/constant.py +34 -1
- flwr/supercore/corestate/corestate.py +24 -3
- flwr/supercore/corestate/in_memory_corestate.py +138 -0
- flwr/supercore/corestate/sqlite_corestate.py +157 -0
- flwr/supercore/ffs/disk_ffs.py +1 -2
- flwr/supercore/ffs/ffs.py +1 -2
- flwr/supercore/ffs/ffs_factory.py +1 -2
- flwr/{common → supercore}/heartbeat.py +20 -25
- flwr/supercore/object_store/in_memory_object_store.py +1 -2
- flwr/supercore/object_store/object_store.py +1 -2
- flwr/supercore/object_store/object_store_factory.py +1 -2
- flwr/supercore/object_store/sqlite_object_store.py +8 -7
- flwr/supercore/primitives/asymmetric.py +1 -1
- flwr/supercore/primitives/asymmetric_ed25519.py +11 -1
- flwr/supercore/sqlite_mixin.py +37 -34
- flwr/supercore/superexec/plugin/base_exec_plugin.py +1 -2
- flwr/supercore/superexec/plugin/exec_plugin.py +3 -3
- flwr/supercore/superexec/run_superexec.py +9 -13
- flwr/supercore/utils.py +190 -0
- flwr/superlink/artifact_provider/artifact_provider.py +1 -2
- flwr/superlink/auth_plugin/auth_plugin.py +6 -9
- flwr/superlink/auth_plugin/noop_auth_plugin.py +6 -9
- flwr/{cli/new/templates/app → superlink/federation}/__init__.py +10 -1
- flwr/superlink/federation/federation_manager.py +64 -0
- flwr/superlink/federation/noop_federation_manager.py +71 -0
- flwr/superlink/servicer/control/control_account_auth_interceptor.py +22 -13
- flwr/superlink/servicer/control/control_event_log_interceptor.py +7 -7
- flwr/superlink/servicer/control/control_grpc.py +7 -6
- flwr/superlink/servicer/control/control_license_interceptor.py +3 -3
- flwr/superlink/servicer/control/control_servicer.py +190 -23
- flwr/supernode/cli/flower_supernode.py +58 -3
- flwr/supernode/nodestate/in_memory_nodestate.py +121 -49
- flwr/supernode/nodestate/nodestate.py +52 -8
- flwr/supernode/nodestate/nodestate_factory.py +7 -4
- flwr/supernode/runtime/run_clientapp.py +41 -22
- flwr/supernode/servicer/clientappio/clientappio_servicer.py +46 -10
- flwr/supernode/start_client_internal.py +165 -46
- {flwr-1.23.0.dist-info → flwr-1.25.0.dist-info}/METADATA +9 -11
- flwr-1.25.0.dist-info/RECORD +393 -0
- flwr/cli/new/templates/app/.gitignore.tpl +0 -163
- flwr/cli/new/templates/app/LICENSE.tpl +0 -202
- flwr/cli/new/templates/app/README.baseline.md.tpl +0 -127
- flwr/cli/new/templates/app/README.flowertune.md.tpl +0 -68
- flwr/cli/new/templates/app/README.md.tpl +0 -37
- flwr/cli/new/templates/app/code/__init__.baseline.py.tpl +0 -1
- flwr/cli/new/templates/app/code/__init__.py +0 -15
- flwr/cli/new/templates/app/code/__init__.py.tpl +0 -1
- flwr/cli/new/templates/app/code/__init__.pytorch_legacy_api.py.tpl +0 -1
- flwr/cli/new/templates/app/code/client.baseline.py.tpl +0 -75
- flwr/cli/new/templates/app/code/client.huggingface.py.tpl +0 -93
- flwr/cli/new/templates/app/code/client.jax.py.tpl +0 -71
- flwr/cli/new/templates/app/code/client.mlx.py.tpl +0 -102
- flwr/cli/new/templates/app/code/client.numpy.py.tpl +0 -46
- flwr/cli/new/templates/app/code/client.pytorch.py.tpl +0 -80
- flwr/cli/new/templates/app/code/client.pytorch_legacy_api.py.tpl +0 -55
- flwr/cli/new/templates/app/code/client.sklearn.py.tpl +0 -108
- flwr/cli/new/templates/app/code/client.tensorflow.py.tpl +0 -82
- flwr/cli/new/templates/app/code/client.xgboost.py.tpl +0 -110
- flwr/cli/new/templates/app/code/dataset.baseline.py.tpl +0 -36
- flwr/cli/new/templates/app/code/flwr_tune/client_app.py.tpl +0 -92
- flwr/cli/new/templates/app/code/flwr_tune/dataset.py.tpl +0 -87
- flwr/cli/new/templates/app/code/flwr_tune/models.py.tpl +0 -56
- flwr/cli/new/templates/app/code/flwr_tune/server_app.py.tpl +0 -73
- flwr/cli/new/templates/app/code/flwr_tune/strategy.py.tpl +0 -78
- flwr/cli/new/templates/app/code/model.baseline.py.tpl +0 -66
- flwr/cli/new/templates/app/code/server.baseline.py.tpl +0 -43
- flwr/cli/new/templates/app/code/server.huggingface.py.tpl +0 -42
- flwr/cli/new/templates/app/code/server.jax.py.tpl +0 -39
- flwr/cli/new/templates/app/code/server.mlx.py.tpl +0 -41
- flwr/cli/new/templates/app/code/server.numpy.py.tpl +0 -38
- flwr/cli/new/templates/app/code/server.pytorch.py.tpl +0 -41
- flwr/cli/new/templates/app/code/server.pytorch_legacy_api.py.tpl +0 -31
- flwr/cli/new/templates/app/code/server.sklearn.py.tpl +0 -44
- flwr/cli/new/templates/app/code/server.tensorflow.py.tpl +0 -38
- flwr/cli/new/templates/app/code/server.xgboost.py.tpl +0 -56
- flwr/cli/new/templates/app/code/strategy.baseline.py.tpl +0 -1
- flwr/cli/new/templates/app/code/task.huggingface.py.tpl +0 -98
- flwr/cli/new/templates/app/code/task.jax.py.tpl +0 -57
- flwr/cli/new/templates/app/code/task.mlx.py.tpl +0 -102
- flwr/cli/new/templates/app/code/task.numpy.py.tpl +0 -7
- flwr/cli/new/templates/app/code/task.pytorch.py.tpl +0 -98
- flwr/cli/new/templates/app/code/task.pytorch_legacy_api.py.tpl +0 -111
- flwr/cli/new/templates/app/code/task.sklearn.py.tpl +0 -67
- flwr/cli/new/templates/app/code/task.tensorflow.py.tpl +0 -52
- flwr/cli/new/templates/app/code/task.xgboost.py.tpl +0 -67
- flwr/cli/new/templates/app/code/utils.baseline.py.tpl +0 -1
- flwr/cli/new/templates/app/pyproject.baseline.toml.tpl +0 -146
- flwr/cli/new/templates/app/pyproject.flowertune.toml.tpl +0 -80
- flwr/cli/new/templates/app/pyproject.huggingface.toml.tpl +0 -65
- flwr/cli/new/templates/app/pyproject.jax.toml.tpl +0 -52
- flwr/cli/new/templates/app/pyproject.mlx.toml.tpl +0 -56
- flwr/cli/new/templates/app/pyproject.numpy.toml.tpl +0 -49
- flwr/cli/new/templates/app/pyproject.pytorch.toml.tpl +0 -53
- flwr/cli/new/templates/app/pyproject.pytorch_legacy_api.toml.tpl +0 -53
- flwr/cli/new/templates/app/pyproject.sklearn.toml.tpl +0 -52
- flwr/cli/new/templates/app/pyproject.tensorflow.toml.tpl +0 -53
- flwr/cli/new/templates/app/pyproject.xgboost.toml.tpl +0 -61
- flwr/supercore/object_store/utils.py +0 -43
- flwr-1.23.0.dist-info/RECORD +0 -439
- {flwr-1.23.0.dist-info → flwr-1.25.0.dist-info}/WHEEL +0 -0
- {flwr-1.23.0.dist-info → flwr-1.25.0.dist-info}/entry_points.txt +0 -0
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
"""$project_name: A Flower / FlowerTune app."""
|
|
2
|
-
|
|
3
|
-
import os
|
|
4
|
-
import warnings
|
|
5
|
-
|
|
6
|
-
from flwr.app import ArrayRecord, Context, Message, MetricRecord, RecordDict
|
|
7
|
-
from flwr.clientapp import ClientApp
|
|
8
|
-
from flwr.common.config import unflatten_dict
|
|
9
|
-
from omegaconf import DictConfig
|
|
10
|
-
from peft import get_peft_model_state_dict, set_peft_model_state_dict
|
|
11
|
-
from transformers import TrainingArguments
|
|
12
|
-
from trl import SFTTrainer
|
|
13
|
-
|
|
14
|
-
from $import_name.dataset import (
|
|
15
|
-
get_tokenizer_and_data_collator_and_propt_formatting,
|
|
16
|
-
load_data,
|
|
17
|
-
replace_keys,
|
|
18
|
-
)
|
|
19
|
-
from $import_name.models import cosine_annealing, get_model
|
|
20
|
-
|
|
21
|
-
# Avoid warnings
|
|
22
|
-
os.environ["TOKENIZERS_PARALLELISM"] = "true"
|
|
23
|
-
os.environ["RAY_DISABLE_DOCKER_CPU_WARNING"] = "1"
|
|
24
|
-
warnings.filterwarnings("ignore", category=UserWarning)
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
# Avoid warnings
|
|
28
|
-
os.environ["TOKENIZERS_PARALLELISM"] = "true"
|
|
29
|
-
os.environ["RAY_DISABLE_DOCKER_CPU_WARNING"] = "1"
|
|
30
|
-
warnings.filterwarnings("ignore", category=UserWarning)
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
# Flower ClientApp
|
|
34
|
-
app = ClientApp()
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
@app.train()
|
|
38
|
-
def train(msg: Message, context: Context):
|
|
39
|
-
"""Train the model on local data."""
|
|
40
|
-
# Parse config
|
|
41
|
-
partition_id = context.node_config["partition-id"]
|
|
42
|
-
num_partitions = context.node_config["num-partitions"]
|
|
43
|
-
num_rounds = context.run_config["num-server-rounds"]
|
|
44
|
-
cfg = DictConfig(replace_keys(unflatten_dict(context.run_config)))
|
|
45
|
-
training_arguments = TrainingArguments(**cfg.train.training_arguments)
|
|
46
|
-
|
|
47
|
-
# Let's get the client partition
|
|
48
|
-
trainset = load_data(partition_id, num_partitions, cfg.static.dataset.name)
|
|
49
|
-
(
|
|
50
|
-
tokenizer,
|
|
51
|
-
data_collator,
|
|
52
|
-
formatting_prompts_func,
|
|
53
|
-
) = get_tokenizer_and_data_collator_and_propt_formatting(cfg.model.name)
|
|
54
|
-
|
|
55
|
-
# Load the model and initialize it with the received weights
|
|
56
|
-
model = get_model(cfg.model)
|
|
57
|
-
set_peft_model_state_dict(model, msg.content["arrays"].to_torch_state_dict())
|
|
58
|
-
|
|
59
|
-
# Set learning rate for current round
|
|
60
|
-
new_lr = cosine_annealing(
|
|
61
|
-
msg.content["config"]["server-round"],
|
|
62
|
-
num_rounds,
|
|
63
|
-
cfg.train.learning_rate_max,
|
|
64
|
-
cfg.train.learning_rate_min,
|
|
65
|
-
)
|
|
66
|
-
|
|
67
|
-
training_arguments.learning_rate = new_lr
|
|
68
|
-
training_arguments.output_dir = msg.content["config"]["save_path"]
|
|
69
|
-
|
|
70
|
-
# Construct trainer
|
|
71
|
-
trainer = SFTTrainer(
|
|
72
|
-
model=model,
|
|
73
|
-
tokenizer=tokenizer,
|
|
74
|
-
args=training_arguments,
|
|
75
|
-
max_seq_length=cfg.train.seq_length,
|
|
76
|
-
train_dataset=trainset,
|
|
77
|
-
formatting_func=formatting_prompts_func,
|
|
78
|
-
data_collator=data_collator,
|
|
79
|
-
)
|
|
80
|
-
|
|
81
|
-
# Do local training
|
|
82
|
-
results = trainer.train()
|
|
83
|
-
|
|
84
|
-
# Construct and return reply Message
|
|
85
|
-
model_record = ArrayRecord(get_peft_model_state_dict(model))
|
|
86
|
-
metrics = {
|
|
87
|
-
"train_loss": results.training_loss,
|
|
88
|
-
"num-examples": len(trainset),
|
|
89
|
-
}
|
|
90
|
-
metric_record = MetricRecord(metrics)
|
|
91
|
-
content = RecordDict({"arrays": model_record, "metrics": metric_record})
|
|
92
|
-
return Message(content=content, reply_to=msg)
|
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
"""$project_name: A Flower / FlowerTune app."""
|
|
2
|
-
|
|
3
|
-
from flwr_datasets import FederatedDataset
|
|
4
|
-
from flwr_datasets.partitioner import IidPartitioner
|
|
5
|
-
from transformers import AutoTokenizer
|
|
6
|
-
from trl import DataCollatorForCompletionOnlyLM
|
|
7
|
-
|
|
8
|
-
FDS = None # Cache FederatedDataset
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
def formatting_prompts_func(example):
|
|
12
|
-
"""Construct prompts."""
|
|
13
|
-
output_texts = []
|
|
14
|
-
# Constructing a standard Alpaca
|
|
15
|
-
# (https://github.com/tatsu-lab/stanford_alpaca#data-release) prompt
|
|
16
|
-
mssg = (
|
|
17
|
-
"Below is an instruction that describes a task. "
|
|
18
|
-
"Write a response that appropriately completes the request."
|
|
19
|
-
)
|
|
20
|
-
for i in range(len(example["instruction"])):
|
|
21
|
-
text = (
|
|
22
|
-
f"{mssg}\n### Instruction:\n{example['instruction'][i]}\n"
|
|
23
|
-
f"### Response: {example['response'][i]}"
|
|
24
|
-
)
|
|
25
|
-
output_texts.append(text)
|
|
26
|
-
return output_texts
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
def get_tokenizer_and_data_collator_and_propt_formatting(model_name: str):
|
|
30
|
-
"""Get tokenizer, data_collator and prompt formatting."""
|
|
31
|
-
tokenizer = AutoTokenizer.from_pretrained(
|
|
32
|
-
model_name, use_fast=True, padding_side="right"
|
|
33
|
-
)
|
|
34
|
-
tokenizer.pad_token = tokenizer.eos_token
|
|
35
|
-
response_template_with_context = "\n### Response:" # alpaca response tag
|
|
36
|
-
response_template_ids = tokenizer.encode(
|
|
37
|
-
response_template_with_context, add_special_tokens=False
|
|
38
|
-
)[2:]
|
|
39
|
-
data_collator = DataCollatorForCompletionOnlyLM(
|
|
40
|
-
response_template_ids, tokenizer=tokenizer
|
|
41
|
-
)
|
|
42
|
-
|
|
43
|
-
return tokenizer, data_collator, formatting_prompts_func
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
def formatting(dataset):
|
|
47
|
-
"""Format dataset."""
|
|
48
|
-
dataset["instruction"] = dataset["instruction"] + " " + dataset["input"]
|
|
49
|
-
return dataset
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
def reformat(dataset, llm_task):
|
|
53
|
-
"""Reformat datasets."""
|
|
54
|
-
dataset = dataset.rename_column("output", "response")
|
|
55
|
-
if llm_task in ["finance", "code"]:
|
|
56
|
-
dataset = dataset.map(formatting, remove_columns=["input"])
|
|
57
|
-
if llm_task == "medical":
|
|
58
|
-
dataset = dataset.remove_columns(["instruction"])
|
|
59
|
-
dataset = dataset.rename_column("input", "instruction")
|
|
60
|
-
return dataset
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
def load_data(partition_id: int, num_partitions: int, dataset_name: str):
|
|
64
|
-
"""Load partition data."""
|
|
65
|
-
# Only initialize `FederatedDataset` once
|
|
66
|
-
global FDS
|
|
67
|
-
if FDS is None:
|
|
68
|
-
partitioner = IidPartitioner(num_partitions=num_partitions)
|
|
69
|
-
FDS = FederatedDataset(
|
|
70
|
-
dataset=dataset_name,
|
|
71
|
-
partitioners={"train": partitioner},
|
|
72
|
-
)
|
|
73
|
-
client_trainset = FDS.load_partition(partition_id, "train")
|
|
74
|
-
client_trainset = reformat(client_trainset, llm_task="$llm_challenge_str")
|
|
75
|
-
return client_trainset
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
def replace_keys(input_dict, match="-", target="_"):
|
|
79
|
-
"""Recursively replace match string with target string in dictionary keys."""
|
|
80
|
-
new_dict = {}
|
|
81
|
-
for key, value in input_dict.items():
|
|
82
|
-
new_key = key.replace(match, target)
|
|
83
|
-
if isinstance(value, dict):
|
|
84
|
-
new_dict[new_key] = replace_keys(value, match, target)
|
|
85
|
-
else:
|
|
86
|
-
new_dict[new_key] = value
|
|
87
|
-
return new_dict
|
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
"""$project_name: A Flower / FlowerTune app."""
|
|
2
|
-
|
|
3
|
-
import math
|
|
4
|
-
|
|
5
|
-
import torch
|
|
6
|
-
from omegaconf import DictConfig
|
|
7
|
-
from peft import LoraConfig, get_peft_model
|
|
8
|
-
from peft.utils import prepare_model_for_kbit_training
|
|
9
|
-
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
def cosine_annealing(
|
|
13
|
-
current_round: int,
|
|
14
|
-
total_round: int,
|
|
15
|
-
lrate_max: float = 0.001,
|
|
16
|
-
lrate_min: float = 0.0,
|
|
17
|
-
) -> float:
|
|
18
|
-
"""Implement cosine annealing learning rate schedule."""
|
|
19
|
-
cos_inner = math.pi * current_round / total_round
|
|
20
|
-
return lrate_min + 0.5 * (lrate_max - lrate_min) * (1 + math.cos(cos_inner))
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
def get_model(model_cfg: DictConfig):
|
|
24
|
-
"""Load model with appropriate quantization config and other optimizations.
|
|
25
|
-
"""
|
|
26
|
-
if model_cfg.quantization == 4:
|
|
27
|
-
quantization_config = BitsAndBytesConfig(load_in_4bit=True)
|
|
28
|
-
elif model_cfg.quantization == 8:
|
|
29
|
-
quantization_config = BitsAndBytesConfig(load_in_8bit=True)
|
|
30
|
-
else:
|
|
31
|
-
raise ValueError(
|
|
32
|
-
f"Use 4-bit or 8-bit quantization. You passed: {model_cfg.quantization}/"
|
|
33
|
-
)
|
|
34
|
-
|
|
35
|
-
model = AutoModelForCausalLM.from_pretrained(
|
|
36
|
-
model_cfg.name,
|
|
37
|
-
quantization_config=quantization_config,
|
|
38
|
-
torch_dtype=torch.bfloat16,
|
|
39
|
-
low_cpu_mem_usage=True,
|
|
40
|
-
)
|
|
41
|
-
|
|
42
|
-
model = prepare_model_for_kbit_training(
|
|
43
|
-
model, use_gradient_checkpointing=model_cfg.gradient_checkpointing
|
|
44
|
-
)
|
|
45
|
-
|
|
46
|
-
peft_config = LoraConfig(
|
|
47
|
-
r=model_cfg.lora.peft_lora_r,
|
|
48
|
-
lora_alpha=model_cfg.lora.peft_lora_alpha,
|
|
49
|
-
lora_dropout=0.075,
|
|
50
|
-
task_type="CAUSAL_LM",
|
|
51
|
-
)
|
|
52
|
-
|
|
53
|
-
if model_cfg.gradient_checkpointing:
|
|
54
|
-
model.config.use_cache = False
|
|
55
|
-
|
|
56
|
-
return get_peft_model(model, peft_config)
|
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
"""$project_name: A Flower / FlowerTune app."""
|
|
2
|
-
|
|
3
|
-
import os
|
|
4
|
-
from datetime import datetime
|
|
5
|
-
|
|
6
|
-
from flwr.app import ArrayRecord, ConfigRecord, Context, MetricRecord
|
|
7
|
-
from flwr.common.config import unflatten_dict
|
|
8
|
-
from flwr.serverapp import Grid, ServerApp
|
|
9
|
-
from omegaconf import DictConfig
|
|
10
|
-
from peft import get_peft_model_state_dict, set_peft_model_state_dict
|
|
11
|
-
|
|
12
|
-
from $import_name.dataset import replace_keys
|
|
13
|
-
from $import_name.models import get_model
|
|
14
|
-
from $import_name.strategy import FlowerTuneLlm
|
|
15
|
-
|
|
16
|
-
# Create ServerApp
|
|
17
|
-
app = ServerApp()
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
@app.main()
|
|
21
|
-
def main(grid: Grid, context: Context) -> None:
|
|
22
|
-
"""Main entry point for the ServerApp."""
|
|
23
|
-
# Create output directory given current timestamp
|
|
24
|
-
current_time = datetime.now()
|
|
25
|
-
folder_name = current_time.strftime("%Y-%m-%d_%H-%M-%S")
|
|
26
|
-
save_path = os.path.join(os.getcwd(), f"results/{folder_name}")
|
|
27
|
-
os.makedirs(save_path, exist_ok=True)
|
|
28
|
-
|
|
29
|
-
# Read from config
|
|
30
|
-
num_rounds = context.run_config["num-server-rounds"]
|
|
31
|
-
cfg = DictConfig(replace_keys(unflatten_dict(context.run_config)))
|
|
32
|
-
|
|
33
|
-
# Get initial model weights
|
|
34
|
-
init_model = get_model(cfg.model)
|
|
35
|
-
arrays = ArrayRecord(get_peft_model_state_dict(init_model))
|
|
36
|
-
|
|
37
|
-
# Define strategy
|
|
38
|
-
strategy = FlowerTuneLlm(
|
|
39
|
-
fraction_train=cfg.strategy.fraction_train,
|
|
40
|
-
fraction_evaluate=cfg.strategy.fraction_evaluate,
|
|
41
|
-
)
|
|
42
|
-
|
|
43
|
-
# Start strategy, run FedAvg for `num_rounds`
|
|
44
|
-
strategy.start(
|
|
45
|
-
grid=grid,
|
|
46
|
-
initial_arrays=arrays,
|
|
47
|
-
train_config=ConfigRecord({"save_path": save_path}),
|
|
48
|
-
num_rounds=num_rounds,
|
|
49
|
-
evaluate_fn=get_evaluate_fn(
|
|
50
|
-
cfg.model, cfg.train.save_every_round, num_rounds, save_path
|
|
51
|
-
),
|
|
52
|
-
)
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
# Get function that will be executed by the strategy
|
|
56
|
-
# Here we use it to save global model checkpoints
|
|
57
|
-
def get_evaluate_fn(model_cfg, save_every_round, total_round, save_path):
|
|
58
|
-
"""Return an evaluation function for saving global model."""
|
|
59
|
-
|
|
60
|
-
def evaluate(server_round: int, arrays: ArrayRecord) -> MetricRecord:
|
|
61
|
-
# Save model
|
|
62
|
-
if server_round != 0 and (
|
|
63
|
-
server_round == total_round or server_round % save_every_round == 0
|
|
64
|
-
):
|
|
65
|
-
# Init model
|
|
66
|
-
model = get_model(model_cfg)
|
|
67
|
-
set_peft_model_state_dict(model, arrays.to_torch_state_dict())
|
|
68
|
-
|
|
69
|
-
model.save_pretrained(f"{save_path}/peft_{server_round}")
|
|
70
|
-
|
|
71
|
-
return MetricRecord()
|
|
72
|
-
|
|
73
|
-
return evaluate
|
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
"""$project_name: A Flower / FlowerTune app."""
|
|
2
|
-
|
|
3
|
-
from collections.abc import Iterable
|
|
4
|
-
from logging import INFO, WARN
|
|
5
|
-
from typing import Optional
|
|
6
|
-
|
|
7
|
-
from flwr.app import ArrayRecord, ConfigRecord, Message, MetricRecord
|
|
8
|
-
from flwr.common import log
|
|
9
|
-
from flwr.serverapp import Grid
|
|
10
|
-
from flwr.serverapp.strategy import FedAvg
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
class FlowerTuneLlm(FedAvg):
|
|
14
|
-
"""Customised FedAvg strategy implementation.
|
|
15
|
-
|
|
16
|
-
This class behaves just like FedAvg but also tracks the communication
|
|
17
|
-
costs associated with `train` over FL rounds.
|
|
18
|
-
"""
|
|
19
|
-
def __init__(self, **kwargs):
|
|
20
|
-
super().__init__(**kwargs)
|
|
21
|
-
self.comm_tracker = CommunicationTracker()
|
|
22
|
-
|
|
23
|
-
def configure_train(
|
|
24
|
-
self, server_round: int, arrays: ArrayRecord, config: ConfigRecord, grid: Grid
|
|
25
|
-
) -> Iterable[Message]:
|
|
26
|
-
"""Configure the next round of training."""
|
|
27
|
-
messages = super().configure_train(server_round, arrays, config, grid)
|
|
28
|
-
|
|
29
|
-
# Track communication costs
|
|
30
|
-
self.comm_tracker.track(messages)
|
|
31
|
-
|
|
32
|
-
return messages
|
|
33
|
-
|
|
34
|
-
def aggregate_train(
|
|
35
|
-
self,
|
|
36
|
-
server_round: int,
|
|
37
|
-
replies: Iterable[Message],
|
|
38
|
-
) -> tuple[Optional[ArrayRecord], Optional[MetricRecord]]:
|
|
39
|
-
"""Aggregate ArrayRecords and MetricRecords in the received Messages."""
|
|
40
|
-
# Track communication costs
|
|
41
|
-
self.comm_tracker.track(replies)
|
|
42
|
-
|
|
43
|
-
arrays, metrics = super().aggregate_train(server_round, replies)
|
|
44
|
-
|
|
45
|
-
return arrays, metrics
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
class CommunicationTracker:
|
|
49
|
-
"""Communication costs tracker over FL rounds."""
|
|
50
|
-
def __init__(self):
|
|
51
|
-
self.curr_comm_cost = 0.0
|
|
52
|
-
|
|
53
|
-
def track(self, messages: Iterable[Message]):
|
|
54
|
-
comm_cost = (
|
|
55
|
-
sum(
|
|
56
|
-
record.count_bytes()
|
|
57
|
-
for msg in messages
|
|
58
|
-
if msg.has_content()
|
|
59
|
-
for record in msg.content.array_records.values()
|
|
60
|
-
)
|
|
61
|
-
/ 1024**2
|
|
62
|
-
)
|
|
63
|
-
|
|
64
|
-
self.curr_comm_cost += comm_cost
|
|
65
|
-
log(
|
|
66
|
-
INFO,
|
|
67
|
-
"Communication budget: used %.2f MB (+%.2f MB this round) / 200,000 MB",
|
|
68
|
-
self.curr_comm_cost,
|
|
69
|
-
comm_cost,
|
|
70
|
-
)
|
|
71
|
-
|
|
72
|
-
if self.curr_comm_cost > 2e5:
|
|
73
|
-
log(
|
|
74
|
-
WARN,
|
|
75
|
-
"The accumulated communication cost has exceeded 200,000 MB. "
|
|
76
|
-
"Please consider reducing it if you plan to participate "
|
|
77
|
-
"FlowerTune LLM Leaderboard.",
|
|
78
|
-
)
|
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
"""$project_name: A Flower Baseline."""
|
|
2
|
-
|
|
3
|
-
import torch
|
|
4
|
-
import torch.nn.functional as F
|
|
5
|
-
from torch import nn
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
class Net(nn.Module):
|
|
9
|
-
"""Model (simple CNN adapted from 'PyTorch: A 60 Minute Blitz')."""
|
|
10
|
-
|
|
11
|
-
def __init__(self):
|
|
12
|
-
super().__init__()
|
|
13
|
-
self.conv1 = nn.Conv2d(3, 6, 5)
|
|
14
|
-
self.pool = nn.MaxPool2d(2, 2)
|
|
15
|
-
self.conv2 = nn.Conv2d(6, 16, 5)
|
|
16
|
-
self.fc1 = nn.Linear(16 * 5 * 5, 120)
|
|
17
|
-
self.fc2 = nn.Linear(120, 84)
|
|
18
|
-
self.fc3 = nn.Linear(84, 10)
|
|
19
|
-
|
|
20
|
-
def forward(self, x):
|
|
21
|
-
"""Do forward."""
|
|
22
|
-
x = self.pool(F.relu(self.conv1(x)))
|
|
23
|
-
x = self.pool(F.relu(self.conv2(x)))
|
|
24
|
-
x = x.view(-1, 16 * 5 * 5)
|
|
25
|
-
x = F.relu(self.fc1(x))
|
|
26
|
-
x = F.relu(self.fc2(x))
|
|
27
|
-
return self.fc3(x)
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
def train(net, trainloader, epochs, device):
|
|
31
|
-
"""Train the model on the training set."""
|
|
32
|
-
net.to(device) # move model to GPU if available
|
|
33
|
-
criterion = torch.nn.CrossEntropyLoss()
|
|
34
|
-
criterion.to(device)
|
|
35
|
-
optimizer = torch.optim.SGD(net.parameters(), lr=0.1, momentum=0.9)
|
|
36
|
-
net.train()
|
|
37
|
-
running_loss = 0.0
|
|
38
|
-
for _ in range(epochs):
|
|
39
|
-
for batch in trainloader:
|
|
40
|
-
images = batch["img"]
|
|
41
|
-
labels = batch["label"]
|
|
42
|
-
optimizer.zero_grad()
|
|
43
|
-
loss = criterion(net(images.to(device)), labels.to(device))
|
|
44
|
-
loss.backward()
|
|
45
|
-
optimizer.step()
|
|
46
|
-
running_loss += loss.item()
|
|
47
|
-
|
|
48
|
-
avg_trainloss = running_loss / len(trainloader)
|
|
49
|
-
return avg_trainloss
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
def test(net, testloader, device):
|
|
53
|
-
"""Validate the model on the test set."""
|
|
54
|
-
net.to(device)
|
|
55
|
-
criterion = torch.nn.CrossEntropyLoss()
|
|
56
|
-
correct, loss = 0, 0.0
|
|
57
|
-
with torch.no_grad():
|
|
58
|
-
for batch in testloader:
|
|
59
|
-
images = batch["img"].to(device)
|
|
60
|
-
labels = batch["label"].to(device)
|
|
61
|
-
outputs = net(images)
|
|
62
|
-
loss += criterion(outputs, labels).item()
|
|
63
|
-
correct += (torch.max(outputs.data, 1)[1] == labels).sum().item()
|
|
64
|
-
accuracy = correct / len(testloader.dataset)
|
|
65
|
-
loss = loss / len(testloader)
|
|
66
|
-
return loss, accuracy
|
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
"""$project_name: A Flower Baseline."""
|
|
2
|
-
|
|
3
|
-
import torch
|
|
4
|
-
from flwr.app import ArrayRecord, Context
|
|
5
|
-
from flwr.serverapp import Grid, ServerApp
|
|
6
|
-
from flwr.serverapp.strategy import FedAvg
|
|
7
|
-
|
|
8
|
-
from $import_name.model import Net
|
|
9
|
-
|
|
10
|
-
# Create ServerApp
|
|
11
|
-
app = ServerApp()
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
@app.main()
|
|
15
|
-
def main(grid: Grid, context: Context) -> None:
|
|
16
|
-
"""Main entry point for the ServerApp."""
|
|
17
|
-
|
|
18
|
-
# Read from config
|
|
19
|
-
num_rounds = context.run_config["num-server-rounds"]
|
|
20
|
-
fraction_train = context.run_config["fraction-train"]
|
|
21
|
-
|
|
22
|
-
# Load global model
|
|
23
|
-
global_model = Net()
|
|
24
|
-
arrays = ArrayRecord(global_model.state_dict())
|
|
25
|
-
|
|
26
|
-
# Initialize FedAvg strategy
|
|
27
|
-
strategy = FedAvg(
|
|
28
|
-
fraction_train=fraction_train,
|
|
29
|
-
fraction_evaluate=1.0,
|
|
30
|
-
min_available_nodes=2,
|
|
31
|
-
)
|
|
32
|
-
|
|
33
|
-
# Start strategy, run FedAvg for `num_rounds`
|
|
34
|
-
result = strategy.start(
|
|
35
|
-
grid=grid,
|
|
36
|
-
initial_arrays=arrays,
|
|
37
|
-
num_rounds=num_rounds,
|
|
38
|
-
)
|
|
39
|
-
|
|
40
|
-
# Save final model to disk
|
|
41
|
-
print("\nSaving final model to disk...")
|
|
42
|
-
state_dict = result.arrays.to_torch_state_dict()
|
|
43
|
-
torch.save(state_dict, "final_model.pt")
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
"""$project_name: A Flower / $framework_str app."""
|
|
2
|
-
|
|
3
|
-
import torch
|
|
4
|
-
from flwr.app import ArrayRecord, Context
|
|
5
|
-
from flwr.serverapp import Grid, ServerApp
|
|
6
|
-
from flwr.serverapp.strategy import FedAvg
|
|
7
|
-
from transformers import AutoModelForSequenceClassification
|
|
8
|
-
|
|
9
|
-
# Create ServerApp
|
|
10
|
-
app = ServerApp()
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
@app.main()
|
|
14
|
-
def main(grid: Grid, context: Context) -> None:
|
|
15
|
-
"""Main entry point for the ServerApp."""
|
|
16
|
-
|
|
17
|
-
# Read from config
|
|
18
|
-
num_rounds = context.run_config["num-server-rounds"]
|
|
19
|
-
fraction_train = context.run_config["fraction-train"]
|
|
20
|
-
|
|
21
|
-
# Initialize global model
|
|
22
|
-
model_name = context.run_config["model-name"]
|
|
23
|
-
num_labels = context.run_config["num-labels"]
|
|
24
|
-
net = AutoModelForSequenceClassification.from_pretrained(
|
|
25
|
-
model_name, num_labels=num_labels
|
|
26
|
-
)
|
|
27
|
-
arrays = ArrayRecord(net.state_dict())
|
|
28
|
-
|
|
29
|
-
# Initialize FedAvg strategy
|
|
30
|
-
strategy = FedAvg(fraction_train=fraction_train)
|
|
31
|
-
|
|
32
|
-
# Start strategy, run FedAvg for `num_rounds`
|
|
33
|
-
result = strategy.start(
|
|
34
|
-
grid=grid,
|
|
35
|
-
initial_arrays=arrays,
|
|
36
|
-
num_rounds=num_rounds,
|
|
37
|
-
)
|
|
38
|
-
|
|
39
|
-
# Save final model to disk
|
|
40
|
-
print("\nSaving final model to disk...")
|
|
41
|
-
state_dict = result.arrays.to_torch_state_dict()
|
|
42
|
-
torch.save(state_dict, "final_model.pt")
|
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
"""$project_name: A Flower / $framework_str app."""
|
|
2
|
-
|
|
3
|
-
import numpy as np
|
|
4
|
-
from flwr.app import ArrayRecord, Context
|
|
5
|
-
from flwr.serverapp import Grid, ServerApp
|
|
6
|
-
from flwr.serverapp.strategy import FedAvg
|
|
7
|
-
|
|
8
|
-
from $import_name.task import get_params, load_model
|
|
9
|
-
|
|
10
|
-
# Create ServerApp
|
|
11
|
-
app = ServerApp()
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
@app.main()
|
|
15
|
-
def main(grid: Grid, context: Context) -> None:
|
|
16
|
-
"""Main entry point for the ServerApp."""
|
|
17
|
-
|
|
18
|
-
# Read from config
|
|
19
|
-
num_rounds = context.run_config["num-server-rounds"]
|
|
20
|
-
input_dim = context.run_config["input-dim"]
|
|
21
|
-
|
|
22
|
-
# Load global model
|
|
23
|
-
model = load_model((input_dim,))
|
|
24
|
-
arrays = ArrayRecord(get_params(model))
|
|
25
|
-
|
|
26
|
-
# Initialize FedAvg strategy
|
|
27
|
-
strategy = FedAvg()
|
|
28
|
-
|
|
29
|
-
# Start strategy, run FedAvg for `num_rounds`
|
|
30
|
-
result = strategy.start(
|
|
31
|
-
grid=grid,
|
|
32
|
-
initial_arrays=arrays,
|
|
33
|
-
num_rounds=num_rounds,
|
|
34
|
-
)
|
|
35
|
-
|
|
36
|
-
# Save final model to disk
|
|
37
|
-
print("\nSaving final model to disk...")
|
|
38
|
-
ndarrays = result.arrays.to_numpy_ndarrays()
|
|
39
|
-
np.savez("final_model.npz", *ndarrays)
|
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
"""$project_name: A Flower / $framework_str app."""
|
|
2
|
-
|
|
3
|
-
from flwr.app import ArrayRecord, Context
|
|
4
|
-
from flwr.serverapp import Grid, ServerApp
|
|
5
|
-
from flwr.serverapp.strategy import FedAvg
|
|
6
|
-
|
|
7
|
-
from $import_name.task import MLP, get_params, set_params
|
|
8
|
-
|
|
9
|
-
# Create ServerApp
|
|
10
|
-
app = ServerApp()
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
@app.main()
|
|
14
|
-
def main(grid: Grid, context: Context) -> None:
|
|
15
|
-
"""Main entry point for the ServerApp."""
|
|
16
|
-
# Read from config
|
|
17
|
-
num_rounds = context.run_config["num-server-rounds"]
|
|
18
|
-
num_layers = context.run_config["num-layers"]
|
|
19
|
-
input_dim = context.run_config["input-dim"]
|
|
20
|
-
hidden_dim = context.run_config["hidden-dim"]
|
|
21
|
-
|
|
22
|
-
# Initialize global model
|
|
23
|
-
model = MLP(num_layers, input_dim, hidden_dim, output_dim=10)
|
|
24
|
-
params = get_params(model)
|
|
25
|
-
arrays = ArrayRecord(params)
|
|
26
|
-
|
|
27
|
-
# Initialize FedAvg strategy
|
|
28
|
-
strategy = FedAvg()
|
|
29
|
-
|
|
30
|
-
# Start strategy, run FedAvg for `num_rounds`
|
|
31
|
-
result = strategy.start(
|
|
32
|
-
grid=grid,
|
|
33
|
-
initial_arrays=arrays,
|
|
34
|
-
num_rounds=num_rounds,
|
|
35
|
-
)
|
|
36
|
-
|
|
37
|
-
# Save final model to disk
|
|
38
|
-
print("\nSaving final model to disk...")
|
|
39
|
-
ndarrays = result.arrays.to_numpy_ndarrays()
|
|
40
|
-
set_params(model, ndarrays)
|
|
41
|
-
model.save_weights("final_model.npz")
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
"""$project_name: A Flower / $framework_str app."""
|
|
2
|
-
|
|
3
|
-
import numpy as np
|
|
4
|
-
from flwr.app import ArrayRecord, Context
|
|
5
|
-
from flwr.serverapp import Grid, ServerApp
|
|
6
|
-
from flwr.serverapp.strategy import FedAvg
|
|
7
|
-
|
|
8
|
-
from $import_name.task import get_dummy_model
|
|
9
|
-
|
|
10
|
-
# Create ServerApp
|
|
11
|
-
app = ServerApp()
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
@app.main()
|
|
15
|
-
def main(grid: Grid, context: Context) -> None:
|
|
16
|
-
"""Main entry point for the ServerApp."""
|
|
17
|
-
|
|
18
|
-
# Read run config
|
|
19
|
-
num_rounds: int = context.run_config["num-server-rounds"]
|
|
20
|
-
|
|
21
|
-
# Load global model
|
|
22
|
-
model = get_dummy_model()
|
|
23
|
-
arrays = ArrayRecord(model)
|
|
24
|
-
|
|
25
|
-
# Initialize FedAvg strategy
|
|
26
|
-
strategy = FedAvg()
|
|
27
|
-
|
|
28
|
-
# Start strategy, run FedAvg for `num_rounds`
|
|
29
|
-
result = strategy.start(
|
|
30
|
-
grid=grid,
|
|
31
|
-
initial_arrays=arrays,
|
|
32
|
-
num_rounds=num_rounds,
|
|
33
|
-
)
|
|
34
|
-
|
|
35
|
-
# Save final model to disk
|
|
36
|
-
print("\nSaving final model to disk...")
|
|
37
|
-
ndarrays = result.arrays.to_numpy_ndarrays()
|
|
38
|
-
np.savez("final_model", *ndarrays)
|