{"id":9756,"library":"flwr","title":"Flower: A Friendly Federated AI Framework","description":"Flower (flwr) is an open-source framework for building federated learning systems. It enables collaborative training of machine learning models across decentralized datasets without exchanging raw data. Currently at version 1.29.0, Flower maintains a rapid release cadence, often releasing minor versions monthly with new features and improvements.","status":"active","version":"1.29.0","language":"en","source_language":"en","source_url":"https://github.com/flwrlabs/flower","tags":["federated learning","machine learning","distributed computing","AI","privacy-preserving AI","deep learning"],"install":[{"cmd":"pip install flwr","lang":"bash","label":"Base Installation"},{"cmd":"pip install 'flwr[torch]'","lang":"bash","label":"With PyTorch Backend"},{"cmd":"pip install 'flwr[tensorflow]'","lang":"bash","label":"With TensorFlow Backend"},{"cmd":"pip install 'flwr[jax]'","lang":"bash","label":"With JAX Backend"}],"dependencies":[{"reason":"Required for PyTorch-based federated learning applications.","package":"torch","optional":true},{"reason":"Required for TensorFlow-based federated learning applications.","package":"tensorflow","optional":true},{"reason":"Required for JAX-based federated learning applications.","package":"jax","optional":true},{"reason":"Used for data serialization and RPC communication. Typically installed as a core dependency.","package":"protobuf","optional":false},{"reason":"Used for gRPC communication between clients and server. Typically installed as a core dependency.","package":"grpcio","optional":false}],"imports":[{"symbol":"start_server","correct":"from flwr.server import start_server"},{"symbol":"start_client","correct":"from flwr.client import start_client"},{"note":"Used for running federated learning simulations locally without needing separate client processes.","symbol":"start_simulation","correct":"from flwr.simulation import start_simulation"},{"symbol":"Client","correct":"from flwr.client import Client"},{"note":"A convenient base class for clients that exchange NumPy arrays, simplifying client implementation.","symbol":"NumPyClient","correct":"from flwr.client import NumPyClient"},{"note":"Base class for implementing custom federated learning strategies.","symbol":"Strategy","correct":"from flwr.server.strategy import Strategy"},{"note":"The most commonly used federated averaging strategy, provided out-of-the-box.","symbol":"FedAvg","correct":"from flwr.server.strategy import FedAvg"},{"note":"Flower migrated from `NDArrays` (NumPy array list) to a more flexible `Message` API starting from v1.21.0. While `NDArrays` still exists for backward compatibility, `Message` is the recommended and future-proof way to exchange data and configure steps.","wrong":"from flwr.common import NDArrays","symbol":"Message","correct":"from flwr.common import Message"}],"quickstart":{"code":"import flwr as fw\nimport numpy as np\nfrom collections import OrderedDict\n\n# 1. Define a Flower Client (inheriting from NumPyClient)\nclass CifarClient(fw.client.NumPyClient):\n    def __init__(self):\n        # In a real scenario, you'd load your actual ML model here\n        # For this quickstart, we'll use a dummy model with NumPy arrays.\n        self.model = {\n            \"layer1\": np.random.rand(10, 10).astype(np.float32),\n            \"layer2\": np.random.rand(10, 1).astype(np.float32)\n        }\n\n    def get_parameters(self, config):\n        \"\"\"Return model parameters as a list of NumPy arrays.\"\"\"\n        return [v for v in self.model.values()]\n\n    def set_parameters(self, parameters):\n        \"\"\"Set model parameters from a list of NumPy arrays.\"\"\"\n        params_dict = zip(self.model.keys(), parameters)\n        self.model = OrderedDict({k: v for k, v in params_dict})\n\n    def fit(self, parameters, config):\n        \"\"\"Simulate training and return updated parameters, number of examples, and metrics.\"\"\"\n        self.set_parameters(parameters)\n        # Simulate training: update weights slightly\n        new_weights = {k: v + np.random.rand(*v.shape).astype(np.float32) * 0.1 for k, v in self.model.items()}\n        self.model = OrderedDict(new_weights)\n        num_examples = 100\n        metrics = {\"accuracy\": float(np.random.rand())}\n        return self.get_parameters({}), num_examples, metrics\n\n    def evaluate(self, parameters, config):\n        \"\"\"Simulate evaluation and return loss, number of examples, and metrics.\"\"\"\n        self.set_parameters(parameters)\n        # Simulate evaluation\n        loss = float(np.random.rand() * 0.5 + 0.5) # Loss between 0.5 and 1.0\n        accuracy = float(np.random.rand() * 0.2 + 0.7) # Accuracy between 0.7 and 0.9\n        num_examples = 50\n        return loss, num_examples, {\"accuracy\": accuracy}\n\n# 2. Define a Flower Server Strategy\n# FedAvg (Federated Averaging) is a common choice.\nstrategy = fw.server.strategy.FedAvg(\n    fraction_fit=1.0,         # Sample 100% of available clients for training\n    fraction_evaluate=1.0,    # Sample 100% of available clients for evaluation\n    min_fit_clients=2,        # Wait for at least 2 clients to participate in fit\n    min_evaluate_clients=2,   # Wait for at least 2 clients to participate in evaluate\n    min_available_clients=2,  # Total number of clients that need to be connected\n)\n\n# 3. Define the client factory function for the simulation\ndef client_fn(cid: str):\n    \"\"\"Returns a Flower Client for a given client ID.\"\"\"\n    print(f\"Creating client {cid}...\")\n    return CifarClient().to_client()\n\n# 4. Start the Flower Simulation\nprint(\"Starting Flower simulation with 2 clients for 3 rounds...\")\nfw.simulation.start_simulation(\n    client_fn=client_fn,\n    num_clients=2,\n    config=fw.server.ServerConfig(num_rounds=3),\n    strategy=strategy,\n)\nprint(\"Simulation finished.\")","lang":"python","description":"This quickstart demonstrates how to set up a basic federated learning simulation using Flower. It defines a `NumPyClient` subclass with dummy model logic for parameter exchange, training, and evaluation. It then configures a `FedAvg` strategy and launches a local simulation using `flwr.simulation.start_simulation`, which manages multiple clients and the server within a single process for easy testing."},"warnings":[{"fix":"Review the official documentation on `flwr.common.Message` and the updated `flwr.server.strategy.Strategy` interface. Client implementations should primarily use `NumPyClient` (which handles `Message` conversion internally) or directly work with `Message` objects. Custom strategies must implement methods compatible with the new Message API.","message":"Flower has migrated its internal communication and strategy APIs from using raw `NDArrays` (lists of NumPy arrays) to a more flexible `Message` API. Older code that directly manipulated `NDArrays` for parameter exchange or implemented custom strategies without the `Message` API will need significant updates.","severity":"breaking","affected_versions":">=1.21.0, >=1.22.0"},{"fix":"Install Flower with the relevant extras, e.g., `pip install 'flwr[torch]'`, `pip install 'flwr[tensorflow]'`, or `pip install 'flwr[jax]'`. Ensure that the versions of the ML framework packages are compatible with your `flwr` version and Python environment.","message":"Flower's base installation (`pip install flwr`) does not include machine learning framework dependencies. If you intend to use PyTorch, TensorFlow, or JAX, you must install Flower with the appropriate optional dependencies, otherwise you will encounter `ModuleNotFoundError`.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Always use a virtual environment and ensure it's configured with a Python version within the `flwr`'s supported range. For example, `conda create -n flwr_env python=3.10` or `pyenv install 3.11.x` followed by `pyenv local 3.11.x`.","message":"Flower requires Python version `>=3.10` and `<4.0`. Using an incompatible Python interpreter (e.g., Python 3.9 or Python 4.0+) will lead to installation failures, runtime errors, or unexpected behavior.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Consult the latest `flwr` documentation for current CLI usage, configuration options, and examples for launching servers and simulations. Update any legacy scripts that rely on older CLI syntax or configuration file formats.","message":"The `flwr` CLI has undergone several changes, including the introduction of centralized configuration via a `pyproject.toml` or `flwr.json` file. Old command-line arguments and script patterns for starting servers or simulations might no longer work as expected.","severity":"breaking","affected_versions":">=1.26.0"}],"env_vars":null,"last_verified":"2026-04-17T00:00:00.000Z","next_check":"2026-07-16T00:00:00.000Z","problems":[{"fix":"Change your import statements from `import flower` to `import flwr` and ensure you installed it using `pip install flwr`.","cause":"The Python package name for Flower is `flwr`, not `flower`.","error":"ModuleNotFoundError: No module named 'flower'"},{"fix":"For common use cases, subclass `flwr.client.NumPyClient` and override its methods (`get_parameters`, `set_parameters`, `fit`, `evaluate`). If implementing a custom client directly from `flwr.client.Client`, ensure all abstract methods are correctly implemented according to the latest API.","cause":"You are attempting to use methods of a `flwr.client.Client` object (or a custom client) that are either not implemented, misspelled, or do not conform to the expected API for parameter exchange and federated operations.","error":"AttributeError: 'Client' object has no attribute 'get_parameters' (or 'fit', 'evaluate', etc.)"},{"fix":"Explicitly cast all NumPy arrays to the required `dtype` (e.g., `np.float32`) before returning them from client methods like `get_parameters`, `fit`, or `evaluate`. For example: `[v.astype(np.float32) for v in self.model.values()]`.","cause":"A mismatch in the data types of NumPy arrays (e.g., `float32` vs `float64`) being exchanged between clients and the server, often due to how different ML frameworks (PyTorch, TensorFlow) handle default data types.","error":"ValueError: incompatible buffer format, expected 'float32', got 'float64'"},{"fix":"Verify that the Flower server is running and listening on the specified `server_address` (e.g., `127.0.0.1:8080`). Check network connectivity, ensure no firewall is blocking the port, and confirm the port is not already in use by another application. For local testing, ensure the client and server use the exact same address and port.","cause":"The client failed to connect to the Flower server. This could be due to the server not running, an incorrect server address/port, network issues, or a firewall blocking the connection.","error":"grpc._channel._MultiThreadedRendezvous: <_MultiThreadedRendezvous of RPC that terminated with status StatusCode.UNAVAILABLE (or similar connection errors)>"},{"fix":"Consult the `flwr` documentation for the latest API. For parameter exchange, use `flwr.common.Message` or rely on `NumPyClient` which abstracts this. If a symbol was moved, search the documentation or `flwr` source code for its new location.","cause":"Attempting to import a symbol (e.g., `NDArrays`, `Parameters`) that has been removed or deprecated in favor of the new `Message` API, or has been moved to a different module.","error":"ImportError: cannot import name 'xyz' from 'flwr.common'"}]}