### Clone Flower fastai Example Project Source: https://flower.ai/docs/framework/v1.23.0/fr/_sources/tutorial-quickstart-fastai Clones the fastai quickstart example from GitHub and sets up the directory structure. This is the initial step to get the project code. ```shell git clone --depth=1 https://github.com/adap/flower.git _tmp \ && mv _tmp/examples/quickstart-fastai . \ && rm -rf _tmp && cd quickstart-fastai ``` -------------------------------- ### Getting Started Tutorials Source: https://flower.ai/docs/framework/v1.23.0/zh_Hans/tutorial-series-customize-the-client-pytorch A collection of quickstart tutorials for various machine learning libraries and platforms with Flower. ```APIDOC ## Getting Started Tutorials ### Description These tutorials provide a quick introduction to using Flower with popular machine learning libraries and frameworks. ### Tutorials * **PyTorch Quickstart**: Learn to implement federated learning with PyTorch. * **TensorFlow Quickstart**: Get started with Flower and TensorFlow. * **MLX Quickstart**: A guide for using Flower with MLX. * **🤗 Transformers Quickstart**: Integrate Flower with Hugging Face Transformers. * **JAX Quickstart**: Implement federated learning using JAX. * **Pandas Quickstart**: A quick start guide for using Flower with Pandas. * **fastai Quickstart**: Learn to use Flower with the fastai library. * **PyTorch Lightning Quickstart**: Integrate Flower with PyTorch Lightning. * **scikit-learn Quickstart**: A quick guide for Flower and scikit-learn. * **XGBoost Quickstart**: Implement federated learning with XGBoost. * **Android Quickstart**: Get started with Flower on Android devices. * **iOS Quickstart**: Learn to use Flower on iOS devices. ``` -------------------------------- ### Download compose.yml file Source: https://flower.ai/docs/framework/v1.23.0/fr/_sources/docker/run-quickstart-examples-docker-compose Downloads the compose.yml file from the Flower repository into the example directory. This file is necessary for Docker Compose setup. ```bash $ curl https://raw.githubusercontent.com/adap/flower/refs/tags/v|stable_flwr_version|/framework/docker/complete/compose.yml \ -o compose.yml ``` -------------------------------- ### Run Flower Quickstart Example Source: https://flower.ai/docs/framework/v1.23.0/zh_Hans/docker/tutorial-quickstart-docker-compose This command executes the Flower quickstart example for local deployment. It streams logs and connects to the configured SuperLink. Ensure `pyproject.toml` is correctly set up before running. ```bash flwr run quickstart-compose local-deployment --stream ``` -------------------------------- ### Clone Quickstart PyTorch Example Source: https://flower.ai/docs/framework/v1.23.0/ko/_sources/docker/run-quickstart-examples-docker-compose Clones the Flower repository and extracts the quickstart-pytorch example. This command uses shallow cloning for efficiency and cleans up unnecessary files. ```bash git clone --depth=1 https://github.com/adap/flower.git \ && mv flower/examples/quickstart-pytorch . \ && rm -rf flower && cd quickstart-pytorch ``` -------------------------------- ### Docker Deployment Guide Source: https://flower.ai/docs/framework/v1.23.0/ko/_modules/flwr/client/client Instructions on how to run Flower using Docker, including quickstart examples and advanced configurations for secure connections and persistence. ```APIDOC ## Docker Deployment ### Description This section provides guidance on deploying and running the Flower framework using Docker containers. It covers basic setup, security enhancements, and state persistence. ### Quickstart with Docker 1. **Build the Docker image**: Use the provided Dockerfile to build a custom Flower image. 2. **Run a server container**: Start a server instance in a Docker container. 3. **Run client containers**: Start client instances in separate containers, connecting to the server. ### Enable TLS for Secure Connections - Configure environment variables or Docker Compose files to specify TLS certificates and keys for secure communication between clients and the server. ### Persist the State of the SuperLink - Use Docker volumes to mount persistent storage for the Flower server's state, ensuring data is not lost when containers are restarted. ### Run with Root User Privileges (If Necessary) - Adjust Dockerfile or container run commands to execute Flower components with root privileges if required by specific dependencies, though this is generally discouraged for security reasons. ### Docker Compose - Utilize `docker-compose.yml` files to define and manage multi-container Flower deployments, simplifying the setup of servers, clients, and other necessary services. ``` -------------------------------- ### Monitor ServerApp Logs for Updated Output Source: https://flower.ai/docs/framework/v1.23.0/zh_Hans/_sources/docker/tutorial-quickstart-docker-compose Shows an example of the ServerApp logs after running the updated Flower quickstart example. The output includes the new 'Get weights' line, confirming that the application code modification was successful and deployed. ```text INFO : Starting logstream for run_id `10386255862566726253` INFO : Starting Flower ServerApp WARNING : Option `--insecure` was set. Starting insecure HTTP channel to superlink:9091. 🎊 Successfully installed quickstart-compose to /app/.flwr/apps/flower.quickstart-compose.1.0.0.35361a47. ``` -------------------------------- ### Flower Contribution Guide - Setup Source: https://flower.ai/docs/framework/v1.23.0/ko/_modules/flwr/common/record/arrayrecord This section provides guidance on setting up a development environment for contributing to the Flower framework. It covers installing the development version, configuring virtual environments, and using VSCode Dev Containers. ```bash # Install development version pip install -e ".[dev]" # Example of setting up a virtual environment (conceptual) # python -m venv .venv # source .venv/bin/activate # VSCode Dev Container setup instructions would follow here ``` -------------------------------- ### Create New Flower PyTorch Project Using CLI Source: https://flower.ai/docs/framework/v1.23.0/fr/_sources/docker/tutorial-quickstart-docker Uses the flwr command-line tool to generate a new Flower application project based on PyTorch framework. Requires locally installed flwr CLI. The command creates a project directory with basic setup files; follow up by installing dependencies and reading the README for customization. ```console $ flwr new quickstart-docker --framework PyTorch --username flower ``` -------------------------------- ### Install Local Project Dependencies Source: https://flower.ai/docs/framework/v1.23.0/ko/tutorial-series-get-started-with-flower-pytorch Navigates into the newly created project directory and installs the project and its dependencies using pip. This ensures all required libraries are available for the project. ```bash cd flower-tutorial $ pip install -e . ``` -------------------------------- ### Start Flower Client - Connection Examples Source: https://flower.ai/docs/framework/v1.23.0/zh_Hans/_modules/flwr/compat/client/app Python code examples showing different ways to start a Flower client connection, including insecure connections, TLS with system certificates, and TLS with custom certificates. Each example demonstrates proper function usage with different security configurations. ```python start_client( server_address=localhost:8080, client_fn=client_fn, ) ``` ```python def client_fn(context: Context): return FlowerClient().to_client() start_client( server_address=localhost:8080, client_fn=client_fn, insecure=False, ) ``` ```python from pathlib import Path start_client( server_address=localhost:8080, client_fn=client_fn, root_certificates=Path("/crts/root.pem").read_bytes(), ) ``` -------------------------------- ### Define ClientApp Service with Dockerfile Inline Source: https://flower.ai/docs/framework/v1.23.0/ko/docker/tutorial-quickstart-docker-compose This Docker Compose service defines `superexec-clientapp-3`, which builds a custom Docker image using an inline Dockerfile. The image is based on `flwr/superexec`, installs build essentials, and configures the environment to run as the `app` user. It copies `pyproject.toml`, modifies it to remove simulation dependencies, installs the package, and sets `flower-superexec` as the entrypoint. ```yaml superexec-clientapp-3: build: context: ${PROJECT_DIR:-.} dockerfile_inline: | FROM flwr/superexec:${FLWR_VERSION:-1.23.0} USER root RUN apt-get update \ && apt-get -y --no-install-recommends install \ build-essential \ && rm -rf /var/lib/apt/lists/* USER app WORKDIR /app COPY --chown=app:app pyproject.toml . RUN sed -i 's/.*flwr[simulation].*//' pyproject.toml \ && python -m pip install -U --no-cache-dir . ENTRYPOINT ["flower-superexec"] command: - --insecure - --plugin-type - clientapp - --appio-api-address - supernode-3:9096 deploy: resources: limits: cpus: "2" stop_signal: SIGINT depends_on: - supernode-3 ``` -------------------------------- ### Fastai Server and Client Application Structure Source: https://flower.ai/docs/framework/v1.23.0/fr/_sources/tutorial-quickstart-fastai Outlines the file structure for the fastai Flower example, including the client application, server application, task definitions (model, training, data), and project configuration. ```shell quickstart-fastai ├── fastai_example │ ├── client_app.py # Defines your ClientApp │ ├── server_app.py # Defines your ServerApp │ └── task.py # Defines your model, training and data loading ├── pyproject.toml # Project metadata like dependencies and configs └── README.md ``` -------------------------------- ### Set Flower Version Environment Variable Source: https://flower.ai/docs/framework/v1.23.0/ko/_sources/docker/run-quickstart-examples-docker-compose Exports the FLWR_VERSION environment variable to specify which Flower version to use. Update the value to match your installed version. ```bash export FLWR_VERSION="|stable_flwr_version|" # update with your version ``` -------------------------------- ### Start Flower SuperLink and SuperNodes (CLI) Source: https://flower.ai/docs/framework/v1.23.0/zh_Hans/how-to-upgrade-to-flower-1 Illustrates how to start a SuperLink and SuperNodes from the command line for distributed Flower training. Includes examples for insecure and secure (HTTPS) deployments with SSL certificates. ```Shell # Start a SuperLink $ flower-superlink --insecure # In a new terminal window, start a long-running SuperNode $ flower-supernode \ --insecure \ --superlink 127.0.0.1:9092 \ --clientappio-api-address 127.0.0.1:9094 \ # In another terminal window, start another long-running SuperNode (at least 2 SuperNodes are required) $ flower-supernode \ --insecure \ --superlink 127.0.0.1:9092 \ --clientappio-api-address 127.0.0.1:9095 \ ``` ```Shell # Start a secure SuperLink $ flower-superlink \ --ssl-ca-certfile \ --ssl-certfile \ --ssl-keyfile # In a new terminal window, start a long-running SuperNode $ flower-supernode \ --superlink 127.0.0.1:9092 \ --clientappio-api-address 127.0.0.1:9094 \ --root-certificates \ # In another terminal window, start another long-running SuperNode (at least 2 SuperNodes are required) $ flower-supernode \ --superlink 127.0.0.1:9092 \ --clientappio-api-address 127.0.0.1:9095 \ --root-certificates \ ``` -------------------------------- ### Start Flower Simulation (Python - v1.7) Source: https://flower.ai/docs/framework/v1.23.0/ko/_sources/how-to-upgrade-to-flower-1.13 Shows how to start a Flower simulation using the `start_simulation()` function in Python (deprecated for versions 1.8 and later). It involves passing a dictionary of client resource requirements to the `client_resources` argument. ```python # Flower 1.7 (in `sim.py`, deprecated) if __name__ == "__main__": hist = start_simulation( num_clients=10, client_resources="{"num_cpus": 2, "num_gpus": 0.25}", ... ) ``` -------------------------------- ### Initialize and Start ServerApp with FedAvg Strategy Source: https://flower.ai/docs/framework/v1.23.0/fr/how-to-use-strategies Demonstrates the basic setup of a ServerApp and initiating the FedAvg strategy. The `ServerApp` is instantiated, and its `main` function is decorated. Inside `main`, a `Net` model is loaded, an `ArrayRecord` is created from its state, and the `FedAvg` strategy is initialized. Finally, the `start` method of the strategy is called to begin the federated learning process. ```python from flwr.serverapp.strategy import FedAvg app = ServerApp() @app.main() def main(grid: Grid, context: Context) -> None: """Main entry point for the ServerApp.""" # Load global model global_model = Net() arrays = ArrayRecord(global_model.state_dict()) # Initialize FedAvg strategy with default settings strategy = FedAvg() # Start strategy, run FedAvg for `num_rounds` result = strategy.start( grid=grid, initial_arrays=arrays, ) ``` -------------------------------- ### How-to Guides: Building and Deploying Flower Applications Source: https://flower.ai/docs/framework/v1.23.0/zh_Hans/tutorial-series-customize-the-client-pytorch Guides on building, simulating, and deploying Flower applications, including configuration and advanced features. ```APIDOC ## How-to Guides: Building and Deploying Flower Applications ### Description This section provides practical guidance on various aspects of developing and deploying Flower applications, from installation and configuration to advanced deployment scenarios. ### Building Flower Applications * **Install Flower**: Instructions for installing the Flower framework. * **Configure `pyproject.toml`**: How to configure your project using `pyproject.toml`. * **Configure a `ClientApp`**: Setting up a client application. * **Design Stateful ClientApps**: Creating client applications that maintain state. * **Use Strategies**: Implementing and using different aggregation strategies. * **Implement Strategies**: Customizing and implementing your own strategies. * **Integrate Evaluation Results**: Combining evaluation results from clients. * **Save and Load Model Checkpoints**: Managing model checkpoints during training. * **Use Built-in Mods**: Leveraging pre-built modules for common tasks. * **Use Differential Privacy**: Implementing differential privacy for enhanced privacy. * **Implement FedBN**: Using Federated Batch Normalization. * **Use CLI JSON Output**: Configuring the Command Line Interface for JSON output. * **OpenFL Migration Guide**: Guidance for migrating from OpenFL to Flower. * **Upgrade Guides**: Instructions for upgrading to newer versions of Flower (v1.0, v1.13, Message API). ### Simulating Flower Applications * **Run Simulations**: How to run simulations of federated learning scenarios. ### Deploying Flower Applications * **Run Flower with the Deployment Engine**: Using the Flower Deployment Engine. * **Enable TLS Connections**: Securing communication with TLS. * **Authenticate SuperNodes**: Authenticating SuperNodes for secure operation. * **Configure Logging**: Setting up logging for Flower applications. * **Run Flower on Cloud Platforms**: Deployment guides for GCP, Azure, and Red Hat OpenShift. * **Run Flower on Multiple OpenShift Clusters**: Deploying across multiple clusters. * **Authenticate Accounts via OpenID Connect**: Integrating OpenID Connect for authentication. * **Configure Audit Logging**: Setting up audit logging for security and compliance. * **Run Flower using Docker**: Deploying Flower applications with Docker. * **Quickstart with Docker**: Basic Docker deployment. * **Enable TLS for Secure Connections**: Securing Docker deployments with TLS. * **Persist the State of the SuperLink**: Ensuring state persistence for the SuperLink. * **Set Environment Variables**: Configuring environment variables for Docker containers. * **Run with Root User Privileges**: Considerations for running with root privileges. * **Run ServerApp or ClientApp as a Subprocess**: Running Flower components as subprocesses. * **Pin a Docker Image to a Specific Version**: Using specific Docker image versions. * **Use a Different Flower Version**: Deploying with a different Flower version. * **Quickstart with Docker Compose**: Using Docker Compose for multi-container deployments. * **Run Flower Quickstart Examples with Docker Compose**: Deploying examples with Docker Compose. * **Deploy Flower on Multiple Machines with Docker Compose**: Scaling deployments across machines. * **Run Flower using Helm**: Deploying Flower applications with Helm. * **Deploy SuperLink**: Deploying the SuperLink component. * **Deploy SuperNode**: Deploying the SuperNode component. ``` -------------------------------- ### Create Flower SuperExec Dockerfile Source: https://flower.ai/docs/framework/v1.23.0/fr/how-to-run-flower-on-gcp This Dockerfile sets up the environment for the Flower SuperExec. It starts from a base image, installs dependencies, and configures the entrypoint for the SuperExec application. Dependencies are managed via pyproject.toml. ```docker FROM flwr/superexec:1.23.0 WORKDIR /app COPY pyproject.toml . RUN sed -i 's/.*flwr[simulation].*//' pyproject.toml \ && python -m pip install -U --no-cache-dir . ENTRYPOINT ["flower-superexec"] ``` -------------------------------- ### Flower Source Code Direct Reference Examples Source: https://flower.ai/docs/framework/v1.23.0/zh_Hans/contributor-how-to-build-docker-images Provides examples of how to reference the Flower source code directly from a Git repository or artifact store. These references can be used to install specific versions or branches of Flower for development or testing purposes. ```git # main branch git+https://github.com/adap/flower.git@main#subdirectory=framework ``` ```git # commit hash git+https://github.com/adap/flower.git@4bc1bca3d0576dd2233972d9d91c2c7e8eb03edd#subdirectory=framework ``` ```git # tag git+https://github.com/adap/flower.git@1.23.0#subdirectory=framework ``` ```url https://artifact.flower.ai/py/main/latest/flwr-1.23.0-py3-none-any.whl ``` -------------------------------- ### Run Quickstart Project (Flower CLI) Source: https://flower.ai/docs/framework/v1.23.0/fr/docker/tutorial-quickstart-docker This command initiates the Flower quickstart project in a local deployment mode using the Flower command-line interface. It streams logs for monitoring execution progress. ```bash flwr run . local-deployment --stream ``` -------------------------------- ### Start SuperNode (Bash) Source: https://flower.ai/docs/framework/v1.23.0/ko/_sources/how-to-run-flower-with-deployment-engine Starts a Flower SuperNode with insecure communication enabled, connecting to a specified SuperLink and API address. It also includes node configuration for partition details. ```bash $ flower-supernode \ --insecure \ --superlink 127.0.0.1:9092 \ --clientappio-api-address 127.0.0.1:9094 \ --node-config "partition-id=0 num-partitions=2" ``` ```shell $ flower-supernode \ --insecure \ --superlink 127.0.0.1:9092 \ --clientappio-api-address 127.0.0.1:9095 \ --node-config "partition-id=1 num-partitions=2" ``` -------------------------------- ### Install Google Cloud SDK (gcloud CLI) for Windows Source: https://flower.ai/docs/framework/v1.23.0/fr/how-to-run-flower-on-gcp Provides instructions for installing the Google Cloud SDK on Windows by downloading and running the provided installer executable. This enables interaction with GCP services. ```bash # Windows # Download the Windows installer from the Google Cloud SDK page # https://dl.google.com/dl/cloudsdk/channels/rapid/GoogleCloudSDKInstaller.exe # Run the .exe installer and follow the on-screen instructions ``` -------------------------------- ### Install Flower Framework Project Source: https://flower.ai/docs/framework/v1.23.0/ko/tutorial-quickstart-xgboost Installs the Flower framework project in editable mode from the current directory. This command sets up all dependencies and makes the project available for execution. ```shell $ pip install -e . ``` -------------------------------- ### Create and Run ServerApp with FedAvg Strategy Source: https://flower.ai/docs/framework/v1.23.0/zh_Hans/how-to-use-strategies This snippet demonstrates the basic setup of a ServerApp, loading a global model, initializing the FedAvg strategy with default settings, and starting the federated learning process by executing the strategy's start method. It requires the 'flwr' library. ```python from flwr.serverapp.serverapp import ServerApp from flwr.serverapp.strategy import FedAvg from flwr.common.typing import Grid, Context from flwr.common.record import ArrayRecord from flwr.server.client_proxy import ClientProxy from flwr.server.server import Server from flwr.server.client_manager import ClientManager from flwr.server.handler.server_app import ServerApp from flwr.server.strategy import Strategy from flwr.server.server_app import ServerApp as ServerAppImpl # Assume Net, Grid, Context, ArrayRecord are defined elsewhere # Placeholder for Net, Grid, Context, ArrayRecord for demonstration class Net: def state_dict(self): return { "layer1": [1, 2, 3] } class Grid: pass class Context: pass class ArrayRecord: def __init__(self, data): self.data = data # Create ServerApp instance app = ServerApp() @app.main() def main(grid: Grid, context: Context) -> None: """Main entry point for the ServerApp.""" # Load global model global_model = Net() arrays = ArrayRecord(global_model.state_dict()) # Initialize FedAvg strategy with default settings strategy = FedAvg() # Start strategy, run FedAvg for `num_rounds` result = strategy.start( grid=grid, initial_arrays=arrays, ) ``` -------------------------------- ### Minimal strategy start method execution Source: https://flower.ai/docs/framework/v1.23.0/ko/how-to-use-strategies Demonstrates the minimal required arguments for the strategy's start method, including the Grid and initial model parameters as an ArrayRecord. ```python result = strategy.start( grid=grid, initial_arrays=ArrayRecord(...), ) ``` -------------------------------- ### Understanding the `start` Method Workflow Source: https://flower.ai/docs/framework/v1.23.0/ko/explanation-flower-strategy-abstraction Explains the step-by-step workflow of the `start` method in the `Strategy` base class, detailing the sequence of operations in a federated learning round. ```APIDOC ## Understanding the `start` Method Workflow ### Description The `start` method orchestrates the federated learning process. It sequentially calls various components, including `configure_train`, `aggregate_train`, `configure_evaluate`, and `aggregate_evaluate`, for a specified number of rounds. ### Workflow Steps: 1. **Initial Evaluation**: If `evaluate_fn` is provided, it's called to evaluate the initial model on the ServerApp side. 2. **Configure Training**: `configure_train` is called to generate training messages for client nodes. 3. **Send Training Messages**: Training messages are sent to client nodes. 4. **Client Training**: Client nodes execute their `@app.train()` function and return training replies. 5. **Aggregate Training**: `aggregate_train` is called to aggregate the training replies from the clients. 6. **Configure Evaluation**: `configure_evaluate` is called to generate evaluation messages for client nodes. 7. **Send Evaluation Messages**: Evaluation messages are sent to client nodes. 8. **Client Evaluation**: Client nodes execute their `@app.evaluate()` function and return evaluation replies. 9. **Aggregate Evaluation**: `aggregate_evaluate` is called to aggregate the evaluation replies from the clients. 10. **Server-Side Evaluation**: If `evaluate_fn` is provided, it's called again to evaluate the aggregated model on the ServerApp side. 11. **Repeat Rounds**: Steps 2 through 10 are repeated for the specified `num_rounds`. 12. **Return Result**: The method returns the final `Result`, which includes the final model and the history of metrics. ``` -------------------------------- ### Building SuperExec Docker Image for ServerApps Source: https://flower.ai/docs/framework/v1.23.0/fr/_sources/docker/tutorial-quickstart-docker This Dockerfile creates a custom SuperExec image based on flwr/superexec, installing project dependencies from pyproject.toml while removing unnecessary Flower simulation extras. It sets up the working directory, copies config, modifies dependencies, and installs via pip. Requires pyproject.toml in build context and Docker; outputs a tagged image for running ServerApps or ClientApps. Limitation: Flower is pre-installed, so explicit flwr dependency is stripped. ```dockerfile FROM flwr/superexec:|stable_flwr_version| WORKDIR /app COPY pyproject.toml . RUN sed -i 's/.*flwr\[simulation\].*//' pyproject.toml \ && python -m pip install -U --no-cache-dir . ENTRYPOINT ["flower-superexec"] ``` ```bash docker build -f superexec.Dockerfile -t flwr_superexec:0.0.1 . ``` -------------------------------- ### Instantiate and Start FedAvg Strategy with ServerApp Source: https://flower.ai/docs/framework/v1.23.0/fr/_sources/how-to-use-strategies Demonstrates how to create a ServerApp, initialize a global model, and start the FedAvg strategy with default settings. This snippet shows the basic setup for running a federated learning process using a pre-built strategy. ```python from flwr.serverapp import ServerApp from flwr.serverapp.strategy import FedAvg from flwr.common import ArrayRecord, Grid, Context # Define a placeholder for the neural network class Net: def state_dict(self): # Replace with actual model state dictionary return {} # Create ServerApp app = ServerApp() @app.main() def main(grid: Grid, context: Context) -> None: """Main entry point for the ServerApp.""" # Load global model global_model = Net() arrays = ArrayRecord(global_model.state_dict()) # Initialize FedAvg strategy with default settings strategy = FedAvg() # Start strategy, run FedAvg for `num_rounds` result = strategy.start( grid=grid, initial_arrays=arrays, ) ``` -------------------------------- ### Start ServerApp and ClientApps SuperExec (Docker) Source: https://flower.ai/docs/framework/v1.23.0/ko/docker/tutorial-quickstart-docker Launches Docker containers for both a ServerApp SuperExec and multiple ClientApp SuperExec instances. This command sequence is used to deploy a new version of the Flower application. ```docker docker run --rm \ --network flwr-network \ --name superexec-serverapp \ --detach \ flwr_superexec:0.0.1 \ --insecure \ --plugin-type serverapp \ --appio-api-address superlink:9091 docker run --rm \ --network flwr-network \ --name superexec-clientapp-1 \ --detach \ flwr_superexec:0.0.1 \ --insecure \ --plugin-type clientapp \ --appio-api-address supernode-1:9094 docker run --rm \ --network flwr-network \ --name superexec-clientapp-2 \ --detach \ flwr_superexec:0.0.1 \ --insecure \ --plugin-type clientapp \ --appio-api-address supernode-2:9095 ``` -------------------------------- ### Install and Run Flower Project (Bash) Source: https://flower.ai/docs/framework/v1.23.0/en/tutorial-quickstart-mlx Installs the project in editable mode from the directory containing pyproject.toml. Runs the federated learning simulation with default arguments or overrides like number of rounds and learning rate. Outputs include strategy details, round metrics, and final results; requires Flower CLI installed. ```bash $ pip install -e . ``` ```bash $ flwr run . ``` ```bash $ flwr run . --run-config "num-server-rounds=5 lr=0.05" ``` -------------------------------- ### Initialize and Verify Google Cloud SDK (gcloud) Source: https://flower.ai/docs/framework/v1.23.0/fr/how-to-run-flower-on-gcp Initializes the gcloud CLI after installation and verifies the installation by checking the version. This step is crucial for setting up authentication and configuration. ```bash # Once the package is installed (e.g., using brew), we initialize gcloud as follows: gcloud init # initialize with gcloud init. gcloud version # verify installation ``` -------------------------------- ### Flower ServerApp Main Function (JAX) Source: https://flower.ai/docs/framework/v1.23.0/fr/tutorial-quickstart-jax Defines the main entry point for a Flower ServerApp using JAX. It initializes the Federated Averaging strategy, loads the global model, and starts the federated learning process for a specified number of rounds. The final model weights are then saved to disk. Dependencies include Flower, JAX, NumPy, and strategy/model utilities. ```python import numpy as np from flwr.common import Context, Grid, ArrayRecord, RecordDict from flwr.server.strategy import FedAvg from flwr_example.jax.model import load_model, get_params # Placeholder for ServerApp initialization and strategy class ServerApp: def main(self): def decorator(func): return func return decorator app = ServerApp() @app.main() def main(grid: Grid, context: Context) -> None: """Main entry point for the ServerApp.""" # Read from config num_rounds = context.run_config["num-server-rounds"] input_dim = context.run_config["input-dim"] # Load global model model = load_model((input_dim,)) arrays = ArrayRecord(get_params(model)) # Initialize FedAvg strategy strategy = FedAvg() # Start strategy, run FedAvg for `num_rounds` result = strategy.start( grid=grid, initial_arrays=arrays, num_rounds=num_rounds, ) # Save final model to disk print("\nSaving final model to disk...") ndarrays = result.arrays.to_numpy_ndarrays() np.savez("final_model.npz", *ndarrays) ``` -------------------------------- ### Start Strategy with Client Configuration (Python) Source: https://flower.ai/docs/framework/v1.23.0/fr/_sources/how-to-configure-clients Illustrates how to start a Flower strategy (e.g., FedAvg) and pass a ConfigRecord to its `start` method. This ensures the configuration is sent to the ClientApps as part of the Message. The `server-round` key is automatically added by Flower. ```python from flwr.app import ServerApp, ConfigRecord from flwr.server.strategy import FedAvg # Create ServerApp app = ServerApp() @app.main() def main(grid: Grid, context: Context) -> None: """Main entry point for the ServerApp.""" # ... Read run config, initialize global model, etc # Initialize FedAvg strategy strategy = FedAvg() # Construct the config to be embedded into the Messages that will # be sent to the ClientApps config = ConfigRecord({"lr": 0.1, "optim": "adam-w", "augment": True}) # Start strategy, run FedAvg for `num_rounds` result = strategy.start( grid=grid, initial_arrays=arrays, train_config=config, num_rounds=10, ) ``` -------------------------------- ### Create and Configure ServerApp for Federated Learning Source: https://flower.ai/docs/framework/v1.23.0/fr/_sources/tutorial-quickstart-pytorch This Python code demonstrates the initialization of a ServerApp and its main function. It reads configuration parameters like training fraction, number of rounds, and learning rate from the run configuration. It also loads an initial global model, initializes the FedAvg strategy, and starts the federated training process. Finally, it saves the resulting global model to disk. ```python from flwr.server import ServerApp from flwr.common import Context, Grid, ArrayRecord, ConfigRecord, Message, RecordDict from flwr.strategies import FedAvg import torch # Assume Net is defined elsewhere class Net(torch.nn.Module): def __init__(self, n_classes=10): super().__init__() self.fc1 = torch.nn.Linear(10, 10) def forward(self, x): return self.fc1(x) # Create ServerApp app = ServerApp() @app.main() def main(grid: Grid, context: Context) -> None: """Main entry point for the ServerApp.""" # Read run config fraction_train: float = context.run_config["fraction-train"] num_rounds: int = context.run_config["num-server-rounds"] lr: float = context.run_config["lr"] # Load global model global_model = Net() arrays = ArrayRecord(global_model.state_dict()) # Initialize FedAvg strategy strategy = FedAvg(fraction_train=fraction_train) # Start strategy, run FedAvg for `num_rounds` result = strategy.start( grid=grid, initial_arrays=arrays, train_config=ConfigRecord({"lr": lr}), num_rounds=num_rounds, ) # Save final model to disk print("\nSaving final model to disk...") state_dict = result.arrays.to_torch_state_dict() torch.save(state_dict, "final_model.pt") ``` -------------------------------- ### Python: IidPartitioner Example Source: https://flower.ai/docs/framework/v1.23.0/fr/_sources/tutorial-quickstart-mlx This example shows how to use the `IidPartitioner` from Flower Datasets to generate partitions of the MNIST dataset. ```python partitioner = IidPartitioner(num_partitions=num_partitions) fds = FederatedDataset( dataset="ylecun/mnist", partitioners="{"train": partitioner}", ) partition = fds.load_partition(partition_id) partition_splits = partition.train_test_split(test_size=0.2, seed=42) partition_splits["train"].set_format("numpy") partition_splits["test"].set_format("numpy") train_partition = partition_splits["train"].map( lambda img: {"img": img.reshape(-1, 28 * 28).squeeze().astype(np.float32) / 255.0}, input_columns="image", ) test_partition = partition_splits["test"].map( lambda img: {"img": img.reshape(-1, 28 * 28).squeeze().astype(np.float32) / 255.0}, input_columns="image", ) data = ( train_partition["img"], train_partition["label"].astype(np.uint32), test_partition["img"], test_partition["label"].astype(np.uint32), ) train_images, train_labels, test_images, test_labels = map(mx.array, data) ``` -------------------------------- ### Running SuperNode Containers with Docker Source: https://flower.ai/docs/framework/v1.23.0/fr/_sources/docker/tutorial-quickstart-docker These commands start SuperNode containers for distributed computation in Flower AI, configuring partition IDs, network connections to SuperLink, and API addresses for ClientApp communication. They require Docker, the flwr/supernode image, and a pre-created flwr-network. Inputs include partition settings and ports; outputs are detached containers ready for federation. Limitation: Use unique ports for multiple instances on the same host. ```bash docker run --rm \ -p 9094:9094 \ --network flwr-network \ --name supernode-1 \ --detach \ flwr/supernode:|stable_flwr_version| \ --insecure \ --superlink superlink:9092 \ --node-config "partition-id=0 num-partitions=2" \ --clientappio-api-address 0.0.0.0:9094 \ --isolation process ``` ```bash docker run --rm \ -p 9095:9095 \ --network flwr-network \ --name supernode-2 \ --detach \ flwr/supernode:|stable_flwr_version| \ --insecure \ --superlink superlink:9092 \ --node-config "partition-id=1 num-partitions=2" \ --clientappio-api-address 0.0.0.0:9095 \ --isolation process ``` -------------------------------- ### Initialize and verify gcloud installation Source: https://flower.ai/docs/framework/v1.23.0/fr/_sources/how-to-run-flower-on-gcp Commands to initialize the gcloud CLI and verify its installation. Essential for setting up the environment to interact with GCP. ```bash gcloud init ``` ```bash gcloud version ``` -------------------------------- ### Customized strategy start with configs and rounds Source: https://flower.ai/docs/framework/v1.23.0/ko/how-to-use-strategies Shows how to customize the start method with training and evaluation configurations, and specify the number of rounds for federated learning. ```python train_cfg = ConfigRecord({"lr": 0.1, "optim": "adam"}) eval_cfg = ConfigRecord({"max-steps": 500, "local-checkpoint": True}) result = strategy.start( grid=grid, initial_arrays=ArrayRecord(...), train_config=train_cfg, evaluate_config=eval_cfg, num_rounds=100, ) ``` -------------------------------- ### Define Additional SuperNode Service in Docker Compose Source: https://flower.ai/docs/framework/v1.23.0/ko/docker/tutorial-quickstart-docker-compose This Docker Compose service definition outlines a `supernode-3` which is part of a federated learning setup. It includes configurations for insecure communication, superlink integration, client app API address, and isolation settings. The `partition-id` and `num-partitions` indicate its role in a distributed setup. ```yaml supernode-3: image: flwr/supernode:${FLWR_VERSION:-1.23.0} command: - --insecure - --superlink - superlink:9092 - --clientappio-api-address - 0.0.0.0:9096 - --isolation - process - --node-config - "partition-id=1 num-partitions=2" depends_on: - superlink ``` -------------------------------- ### Clone Flower Docker Compose Repository Source: https://flower.ai/docs/framework/v1.23.0/fr/_sources/docker/tutorial-quickstart-docker-compose Clones the Flower Docker Compose repository to set up the necessary files for deployment. It fetches the latest stable version and moves the 'complete' directory to the current location, then navigates into it. ```bash git clone --depth=1 --branch v|stable_flwr_version| https://github.com/adap/flower.git _tmp \ && mv _tmp/framework/docker/complete . \ && rm -rf _tmp && cd complete ``` -------------------------------- ### Install Google Cloud SDK (gcloud CLI) for macOS Source: https://flower.ai/docs/framework/v1.23.0/fr/how-to-run-flower-on-gcp Installs the Google Cloud SDK for macOS using curl and prompts for on-screen instructions. This is the primary tool for interacting with Google Cloud services. ```bash # macOS curl https://sdk.cloud.google.com | bash # and then follow on-screen prompts # macOS (w/ Homebrew) brew install --cask google-cloud-sdk ``` -------------------------------- ### Flower Simulation Setup (Python) Source: https://flower.ai/docs/framework/v1.23.0/zh_Hans/how-to-upgrade-to-flower-1 Shows how to wrap client and server logic with `ClientApp` and `ServerApp` for Flower simulations. Demonstrates the recommended approach in Flower 1.10 and provides deprecated options. Requires the `flwr` library. ```Python from flwr.app import Context from flwr.clientapp import ClientApp from flwr.server import ServerAppComponents, ServerConfig from flwr.server.strategy import FedAvg from flwr.serverapp import ServerApp from flwr.simulation import start_simulation # Regular Flower client implementation class FlowerClient(): # ... pass # Flower 1.10 and later (recommended) def client_fn(context: Context): return FlowerClient().to_client() app = ClientApp(client_fn=client_fn) def server_fn(context: Context): strategy = FedAvg(...) config = ServerConfig(...) return ServerAppComponents(strategy=strategy, config=config) server_app = ServerApp(server_fn=server_fn) ``` -------------------------------- ### Configure TLS for Additional SuperNode in with-tls.yml Source: https://flower.ai/docs/framework/v1.23.0/ko/docker/tutorial-quickstart-docker-compose This configuration snippet for `with-tls.yml` adds TLS settings for the `supernode-3` service. It specifies the command-line arguments for connecting to the superlink, the client app API address, and importantly, the path to the root certificates (`--root-certificates`) and secrets for mounting the certificate files. ```yaml supernode-3: command: - --superlink - superlink:9092 - --clientappio-api-address - 0.0.0.0:9096 - --isolation - process - --node-config - "partition-id=1 num-partitions=2" - --root-certificates - certificates/superlink-ca.crt secrets: - source: superlink-ca-certfile target: /app/certificates/superlink-ca.crt ``` -------------------------------- ### Example Audit Log Output: SuperNode Pulls Message Source: https://flower.ai/docs/framework/v1.23.0/ko/how-to-configure-audit-logging This example illustrates the audit log output when a SuperNode retrieves messages from the SuperLink. It records the 'started' and 'completed' states for the `FleetServicer.PullMessages` event. ```text INFO : [AUDIT] {"timestamp": "2025-07-14T10:27:02Z", "actor": {"actor_id": "...", "description": "SuperNode", "ip_address": "..."}, "event": {"action": "FleetServicer.PullMessages", "run_id": null, "fab_hash": null}, "status": "started"} INFO : [Fleet.PullMessages] node_id=... INFO : [AUDIT] {"timestamp": "2025-07-14T10:27:02Z", "actor": {"actor_id": "...", "description": "SuperNode", "ip_address": "..."}, "event": {"action": "FleetServicer.PullMessages", "run_id": null, "fab_hash": null}, "status": "completed"} ``` -------------------------------- ### Redirect Python Warnings to Logging Source: https://flower.ai/docs/framework/v1.23.0/zh_Hans/_modules/logging Implements a custom warning handler that logs formatted warnings to the 'py.warnings' logger if no file is provided, otherwise delegates to the original handler. The captureWarnings function toggles this redirection globally. Depends on the warnings and logging modules from the Python standard library. Handles standard warning parameters like message, category, filename, lineno, file, and line. Limitations include global state modification and requires logger setup to avoid missing handlers. ```python _warnings_showwarning = None def _showwarning(message, category, filename, lineno, file=None, line=None): """ Implementation of showwarnings which redirects to logging, which will first check to see if the file parameter is None. If a file is specified, it will delegate to the original warnings implementation of showwarning. Otherwise, it will call warnings.formatwarning and will log the resulting string to a warnings logger named "py.warnings" with level logging.WARNING. """ if file is not None: if _warnings_showwarning is not None: _warnings_showwarning(message, category, filename, lineno, file, line) else: s = warnings.formatwarning(message, category, filename, lineno, line) logger = getLogger("py.warnings") if not logger.handlers: logger.addHandler(NullHandler()) logger.warning("%s", s) def captureWarnings(capture): """ If capture is true, redirect all warnings to the logging package. If capture is False, ensure that warnings are not redirected to logging but to their original destinations. """ global _warnings_showwarning if capture: if _warnings_showwarning is None: _warnings_showwarning = warnings.showwarning warnings.showwarning = _showwarning else: if _warnings_showwarning is not None: warnings.showwarning = _warnings_showwarning _warnings_showwarning = None ``` -------------------------------- ### Configure SuperLink with TLS and State Persistence Source: https://flower.ai/docs/framework/v1.23.0/ko/docker/tutorial-quickstart-docker-compose This snippet modifies the `superlink` service configuration in `with-state.yml` to enable TLS and persist its state. It comments out the insecure and simple database configuration, and uncomment lines to enable isolation, process execution, and crucially, TLS by specifying SSL certificate and key files. It also continues to use a database file for state persistence. ```yaml 1 superlink: 2 # command: 3 # - --insecure 4 # - --isolation 5 # - process 6 # - --database=state/state.db 7 command: 8 - --isolation 9 - process 10 - --ssl-ca-certfile=certificates/ca.crt 11 - --ssl-certfile=certificates/server.pem 12 - --ssl-keyfile=certificates/server.key 13 - --database=state/state.db 14 volumes: 15 - ./state/:/app/state/:rw ``` -------------------------------- ### Server API Source: https://flower.ai/docs/framework/v1.23.0/zh_Hans/tutorial-series-build-a-strategy-from-scratch-pytorch Documentation for starting and configuring Flower servers, including managing clients and implementing various strategies. ```APIDOC ## Server API Documentation This section covers the Flower server functionalities, including starting the server and managing client connections. ### start_server **Description:** Starts a Flower server with the given configuration and strategy. **Method:** `flwr.server.start_server` **Endpoint:** N/A (Server-side function) ### ServerApp **Description:** A class representing a Flower server application, providing the core logic for federated learning orchestration. **Method:** `flwr.server.ServerApp` **Endpoint:** N/A (Server-side class) ### ServerAppComponents **Description:** A data class for holding components of a Flower server application, such as the client manager and strategy. **Method:** `flwr.server.ServerAppComponents` **Endpoint:** N/A (Server-side class) ### ClientManager **Description:** An abstract base class for managing connected Flower clients. **Method:** `flwr.server.ClientManager` **Endpoint:** N/A (Server-side class) ### SimpleClientManager **Description:** A simple implementation of `ClientManager` that keeps track of connected clients. **Method:** `flwr.server.SimpleClientManager` **Endpoint:** N/A (Server-side class) ### Driver **Description:** Interface for driving the Flower server's lifecycle. **Method:** `flwr.server.Driver` **Endpoint:** N/A (Server-side class) ### Grid **Description:** Represents a collection of clients, often used in distributed server setups. **Method:** `flwr.server.Grid` **Endpoint:** N/A (Server-side class) ### History **Description:** Stores the results of a federated learning workload, including metrics and rounds. **Method:** `flwr.server.History` **Endpoint:** N/A (Server-side class) ### LegacyContext **Description:** Context object for legacy server implementations. **Method:** `flwr.server.LegacyContext` **Endpoint:** N/A (Server-side class) ### ServerConfig **Description:** Configuration options for the Flower server. **Method:** `flwr.server.ServerConfig` **Endpoint:** N/A (Server-side class) ``` -------------------------------- ### Instantiate and Start FedAvg Strategy with ServerApp in Python Source: https://flower.ai/docs/framework/v1.23.0/ko/_sources/how-to-use-strategies Demonstrates how to create a ServerApp, load a global model, and initialize and start the FedAvg strategy with default settings. This code snippet shows the basic setup for running federated learning using the FedAvg strategy. ```python from flwr.serverapp import ServerApp from flwr.common import ArrayRecord, Grid, Context # Assume Net is a defined model class # class Net: # def state_dict(self): # pass # Create ServerApp app = ServerApp() @app.main() def main(grid: Grid, context: Context) -> None: """Main entry point for the ServerApp.""" # Load global model global_model = Net() arrays = ArrayRecord(global_model.state_dict()) # Initialize FedAvg strategy with default settings strategy = FedAvg() # Start strategy, run FedAvg for `num_rounds` result = strategy.start( grid=grid, initial_arrays=arrays, ) ``` -------------------------------- ### Flower Server API Source: https://flower.ai/docs/framework/v1.23.0/ko/tutorial-quickstart-mlx Details the server-side components, including starting the server, managing clients, and server configurations. ```APIDOC ## Flower Server API Reference ### `flwr.server` Module This module contains the core components for running a Flower server. #### `start_server(..., **kwargs)` * **Description**: Starts a Flower server instance. * **Method**: POST * **Endpoint**: N/A (server-side function) * **Parameters**: * `config` (ServerConfig) - Server configuration. * `strategy` (Strategy) - The federated learning strategy to use. * `client_manager` (ClientManager) - Manages connected clients. * `extensions` (list) - List of server extensions. #### `ClientManager` Class * **Description**: Abstract base class for managing connected clients. #### `ServerApp` Class * **Description**: Represents a server application that can be configured and run. #### `ServerConfig` Class * **Description**: Configuration settings for the Flower server. ```