From 85d3323b437ba18ee32998b9d7fc5742ad86ac2f Mon Sep 17 00:00:00 2001 From: Ali Anwar Date: Wed, 28 Oct 2026 15:25:10 -0500 Subject: [PATCH 1/2] feat: run Flower clients on a multi-node Ray cluster Setting FLTEST_RAY_ADDRESS makes the Flower backend join an existing Ray cluster instead of starting a private single-machine Ray, so the simulated clients spread over every node. Without the variable nothing changes. Two things had to change. Ray refuses num_cpus/num_gpus when it connects to an existing cluster, so the backend passes only the address. And prepared shards were memory-mapped from the local Hugging Face cache; a memory-mapped table pickles as a file path, so clients scheduled on other nodes failed with FileNotFoundError and the run stalled with every client actor idle. On a cluster the shards are now kept in memory (separate cache key). Adds tests/test_multinode_ray.py and docs/multi-node.md. Verified on an 8-node, 128-vCPU Ray cluster on SPHERE: defense_robust.yaml reproduces the single-machine result (accuracy 0.8965, ASR 0.0270 vs 0.8945, 0.0346). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 19 ++++++++++ README.md | 3 ++ docs/multi-node.md | 57 +++++++++++++++++++++++++++++ fltest/data/datasets.py | 29 +++++++++++++-- fltest/frameworks/flower/adapter.py | 32 ++++++++++++---- mkdocs.yml | 1 + tests/test_multinode_ray.py | 51 ++++++++++++++++++++++++++ 7 files changed, 181 insertions(+), 11 deletions(-) create mode 100644 docs/multi-node.md create mode 100644 tests/test_multinode_ray.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 29e397e..025252f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,25 @@ versioning](https://semver.org). The patch number changes for a fix and the mino for new capability that leaves existing configs working. The major number changes when the configuration schema or the plugin API breaks. +## Unreleased + +**Multi-node clusters.** The Flower backend can now run its clients on an existing multi-node +Ray cluster. Set `FLTEST_RAY_ADDRESS` to the head node's address, and Flower joins that +cluster instead of starting a private single-machine Ray. Without the variable, behaviour is +unchanged. `docs/multi-node.md` covers cluster setup. + +Two changes make this work. Ray refuses `num_cpus`/`num_gpus` when it connects to an existing +cluster, so the backend passes only the address. The other change is to the data. Prepared +shards were memory-mapped from the local Hugging Face cache, and a memory-mapped table +pickles as a file path. Clients scheduled on other nodes therefore failed with +`FileNotFoundError` on a cache file that existed only on the driver, and the run stalled with +every client actor idle. On a cluster the shards are now kept in memory and travel by value, +under a separate cache key. `tests/test_multinode_ray.py` covers both decisions. + +Verified on an 8-node, 128-vCPU Ray cluster on the SPHERE testbed. There, +`examples/configs/defense_robust.yaml` reproduces the single-machine result, with accuracy +0.8965 and attack success 0.0270, against 0.8945 and 0.0346 on one machine. + ## 0.11.0 **Detection quality.** Added the `detection` metric listener. A detector's accuracy column diff --git a/README.md b/README.md index 149fe11..5d6edfd 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,9 @@ pytest tests/ -q See `docs/ARCHITECTURE.md` for the design and `examples/configs/` for runnable configs. +To spread the Flower backend's clients over a multi-node Ray cluster, set +`FLTEST_RAY_ADDRESS`; see [multi-node clusters](docs/multi-node.md). + ## Notes & limitations - **NVFlare** accepts built-in models only, since it rebuilds the model from its class diff --git a/docs/multi-node.md b/docs/multi-node.md new file mode 100644 index 0000000..3a695ee --- /dev/null +++ b/docs/multi-node.md @@ -0,0 +1,57 @@ +# Running on a multi-node cluster + +By default every backend simulates all federated clients on the machine that runs `fltest`. +The Flower backend can instead spread its clients over a multi-node +[Ray](https://docs.ray.io) cluster, so a run with hundreds of clients uses every node's CPUs. +The reference and NVFlare backends always run on one machine. + +## 1. Prepare identical nodes + +Install FLTest on every node **at the same path, with the same Python environment**. Ray +workers import `fltest` and the client hooks from the driver's `sys.path`, so the virtual +environment and the repository must sit at the same location everywhere. For example, +`~/FLTest/.venv` on each node. + +## 2. Start a Ray cluster + +Use the `ray` binary from that environment. On the head node: + +```bash +ray start --head --node-ip-address= --port=6379 --num-cpus= --disable-usage-stats +``` + +Then on every other node: + +```bash +ray start --address=:6379 --node-ip-address= --num-cpus= --disable-usage-stats +``` + +`ray status` on the head should list every node and the total CPUs. + +## 3. Run FLTest against the cluster + +On the head node, point FLTest at the cluster and run any config whose runs use +`framework: flwr`: + +```bash +export FLTEST_RAY_ADDRESS=:6379 +fltest run my_config.yaml +``` + +With `FLTEST_RAY_ADDRESS` set, two things change: + +- **Flower joins the cluster.** It connects to it instead of starting a private Ray sized by + `total_cpus`/`total_gpus`, so those two settings are ignored and the cluster's resources + apply. Each client still requests one CPU. +- **Data shards are kept in memory.** Prepared shards are held in memory rather than + memory-mapped from the local Hugging Face cache, so they reach clients on other nodes. A + memory-mapped table pickles as a file path that exists only on the driver node. These + in-memory shards are cached under their own key, separate from single-machine runs. + +Unset the variable to go back to single-machine runs. + +## When it pays off + +Flower starts one client worker per cluster CPU and ships each client's shard to its node. +For a handful of clients that overhead dominates, and a single machine is faster. The cluster +helps when there are many clients, or each client trains for many steps. diff --git a/fltest/data/datasets.py b/fltest/data/datasets.py index 2589371..d0d25a8 100644 --- a/fltest/data/datasets.py +++ b/fltest/data/datasets.py @@ -12,6 +12,7 @@ from __future__ import annotations +import os from collections import Counter from dataclasses import dataclass, field from typing import Dict, List, Optional @@ -199,7 +200,8 @@ def encode(batch): ) keep = {"input_ids", "attention_mask", "label"} - split = split.map(encode, input_columns=spec.column, batched=True) + split = split.map(encode, input_columns=spec.column, batched=True, + keep_in_memory=_shards_in_memory()) return split.remove_columns([c for c in split.column_names if c not in keep]) @@ -251,7 +253,10 @@ def prepare(split): split = _tokenize_split(split, spec, tokenizer_id) else: transform = _TRANSFORMS[spec.transform] - split = split.map(lambda img: {"img": transform(img)}, input_columns=spec.column) + # On a Ray cluster the shards are pickled to other nodes. A memory-mapped table pickles + # as a path into this machine's Hugging Face cache, which other nodes do not have. + split = split.map(lambda img: {"img": transform(img)}, input_columns=spec.column, + keep_in_memory=_shards_in_memory()) return split.with_format("torch") return { @@ -260,6 +265,23 @@ def prepare(split): } +def _shards_in_memory() -> bool: + """Keep prepared shards in memory when clients run on a multi-node Ray cluster. + + ``FLTEST_RAY_ADDRESS`` is the switch the Flower backend uses to join such a cluster. + """ + return bool(os.environ.get("FLTEST_RAY_ADDRESS")) + + +def _cache_key(dataset_name: str, num_clients: int, partitioner: str, tokenizer_id: str, + part_kwargs: Dict) -> str: + """Cache key for prepared shards. In-memory shards get their own key, so a cluster run never + reuses memory-mapped shards cached by a single-machine run, and the reverse.""" + kw = "_".join(f"{k}{v}" for k, v in sorted(part_kwargs.items())) + key = f"{dataset_name}_{num_clients}_{partitioner}_{tokenizer_id}_{kw}" + return key + "_inmem" if _shards_in_memory() else key + + def get_cached_federated_dataset( dataset_name: str, num_clients: int, @@ -274,8 +296,7 @@ def get_cached_federated_dataset( different token ids from the same text. """ cache = Index(cache_path) - kw = "_".join(f"{k}{v}" for k, v in sorted(part_kwargs.items())) - key = f"{dataset_name}_{num_clients}_{partitioner}_{tokenizer_id}_{kw}" + key = _cache_key(dataset_name, num_clients, partitioner, tokenizer_id, part_kwargs) if key not in cache: cache[key] = get_federated_dataset( dataset_name, num_clients, partitioner, tokenizer_id=tokenizer_id, **part_kwargs diff --git a/fltest/frameworks/flower/adapter.py b/fltest/frameworks/flower/adapter.py index 755b58e..8ef3b9a 100644 --- a/fltest/frameworks/flower/adapter.py +++ b/fltest/frameworks/flower/adapter.py @@ -7,7 +7,8 @@ from __future__ import annotations -from typing import Any, Dict +import os +from typing import Any, Dict, Optional from flwr.simulation import run_simulation @@ -22,6 +23,28 @@ from fltest.frameworks.flower.server import get_server_app +RAY_ADDRESS_ENV = "FLTEST_RAY_ADDRESS" + + +def ray_cluster_address() -> Optional[str]: + """Address of an existing Ray cluster to run Flower clients on, or None for a local one. + + Set ``FLTEST_RAY_ADDRESS`` (for example ``10.0.0.1:6379``) to spread the simulated clients + over every node of a running Ray cluster instead of the machine running ``fltest``. + """ + return os.environ.get(RAY_ADDRESS_ENV) or None + + +def ray_backend_config(total_cpus: int, total_gpus: int, num_clients: int) -> Dict[str, Any]: + """Flower's Ray backend settings: a private local Ray sized by the spec, or, when + ``FLTEST_RAY_ADDRESS`` is set, a connection to that cluster. Ray refuses resource + arguments when it joins an existing cluster, since the cluster already declares them.""" + per_client_gpu = (total_gpus / num_clients) if total_gpus else 0.0 + address = ray_cluster_address() + init_args = {"address": address} if address else {"num_cpus": total_cpus, "num_gpus": total_gpus} + return {"client_resources": {"num_cpus": 1, "num_gpus": per_client_gpu}, "init_args": init_args} + + @register_framework("flwr") @register_framework("flower") class FlowerAdapter(FrameworkAdapter): @@ -55,12 +78,7 @@ def run_simulation(self, spec: RunSpec, data: Dict[str, Any], hook_runner: HookR driver_runner.run("on_data_distribute", ctx_data) c2loader = ctx_data.dist_dict if ctx_data.dist_dict is not None else c2loader - num_gpus = spec.total_gpus - per_client_gpu = (num_gpus / spec.num_clients) if num_gpus else 0.0 - backend_config = { - "client_resources": {"num_cpus": 1, "num_gpus": per_client_gpu}, - "init_args": {"num_cpus": spec.total_cpus, "num_gpus": num_gpus}, - } + backend_config = ray_backend_config(spec.total_cpus, spec.total_gpus, spec.num_clients) state_holder: Dict[str, Any] = {} server_app = get_server_app(spec, driver_runner, history, test_loader, state_holder) diff --git a/mkdocs.yml b/mkdocs.yml index 4dbe52e..1de1cbe 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -48,6 +48,7 @@ nav: - Configuring runs: - Configuration reference: configuration.md - Config fuzzing: fuzzing.md + - Multi-node clusters: multi-node.md - Components: - Datasets: datasets.md - Attacks: attacks.md diff --git a/tests/test_multinode_ray.py b/tests/test_multinode_ray.py new file mode 100644 index 0000000..b29849b --- /dev/null +++ b/tests/test_multinode_ray.py @@ -0,0 +1,51 @@ +"""Running Flower clients on a multi-node Ray cluster (FLTEST_RAY_ADDRESS). + +Two things must change when the clients leave the driver's machine: Flower joins the existing +cluster instead of starting a private one, and the prepared data shards travel by value, +because a memory-mapped Hugging Face table pickles as a path that only exists on the driver. +These checks need no network and no running cluster. +""" + +import pytest + +from fltest.data import datasets +from fltest.frameworks.flower.adapter import RAY_ADDRESS_ENV, ray_backend_config + + +@pytest.fixture +def no_cluster(monkeypatch): + monkeypatch.delenv(RAY_ADDRESS_ENV, raising=False) + + +@pytest.fixture +def cluster(monkeypatch): + monkeypatch.setenv(RAY_ADDRESS_ENV, "10.0.0.1:6379") + + +def test_local_ray_is_sized_by_the_spec(no_cluster): + cfg = ray_backend_config(total_cpus=8, total_gpus=2, num_clients=4) + assert cfg["init_args"] == {"num_cpus": 8, "num_gpus": 2} + assert cfg["client_resources"] == {"num_cpus": 1, "num_gpus": 0.5} + + +def test_cluster_address_replaces_local_resources(cluster): + cfg = ray_backend_config(total_cpus=8, total_gpus=0, num_clients=4) + # Ray rejects num_cpus/num_gpus when it connects to an existing cluster. + assert cfg["init_args"] == {"address": "10.0.0.1:6379"} + assert cfg["client_resources"] == {"num_cpus": 1, "num_gpus": 0.0} + + +def test_empty_address_means_local(monkeypatch): + monkeypatch.setenv(RAY_ADDRESS_ENV, "") + assert "address" not in ray_backend_config(4, 0, 2)["init_args"] + + +def test_shards_stay_memory_mapped_locally(no_cluster): + assert datasets._shards_in_memory() is False + assert datasets._cache_key("mnist", 10, "iid", "", {}) == "mnist_10_iid__" + + +def test_cluster_shards_are_in_memory_with_their_own_cache_key(cluster): + assert datasets._shards_in_memory() is True + key = datasets._cache_key("mnist", 10, "dirichlet", "", {"alpha": 0.5}) + assert key == "mnist_10_dirichlet__alpha0.5_inmem" From c15cfb9645f11fe6ae2f0ac8dbd1a5f4ff401384 Mon Sep 17 00:00:00 2001 From: Ali Anwar Date: Wed, 28 Oct 2026 20:32:00 -0500 Subject: [PATCH 2/2] fix: store each client's shard in the Ray cluster once Flower pickles the client app with every message to a client, and the app held every client's loader. On a cluster the shards travel by value, so each message carried the whole federation's data: about 800 MB with 120 CIFAR-10 clients, which filled the head node's disk while spilling Ray objects. Each client's loader now goes into the object store once, and the client app holds only the references. Co-Authored-By: Claude Opus 5.5 --- docs/multi-node.md | 7 ++++++- fltest/frameworks/flower/adapter.py | 19 +++++++++++++++++++ fltest/frameworks/flower/client.py | 8 +++++++- tests/test_multinode_ray.py | 29 ++++++++++++++++++++++++----- 4 files changed, 56 insertions(+), 7 deletions(-) diff --git a/docs/multi-node.md b/docs/multi-node.md index 3a695ee..ddd0897 100644 --- a/docs/multi-node.md +++ b/docs/multi-node.md @@ -38,7 +38,7 @@ export FLTEST_RAY_ADDRESS=:6379 fltest run my_config.yaml ``` -With `FLTEST_RAY_ADDRESS` set, two things change: +With `FLTEST_RAY_ADDRESS` set, three things change: - **Flower joins the cluster.** It connects to it instead of starting a private Ray sized by `total_cpus`/`total_gpus`, so those two settings are ignored and the cluster's resources @@ -47,6 +47,11 @@ With `FLTEST_RAY_ADDRESS` set, two things change: memory-mapped from the local Hugging Face cache, so they reach clients on other nodes. A memory-mapped table pickles as a file path that exists only on the driver node. These in-memory shards are cached under their own key, separate from single-machine runs. +- **Each shard is stored in the cluster once.** Before the run starts, each client's shard is + put into Ray's object store, and a client fetches only its own. Flower sends the client app + with every message to a client, so an app that held the shards would carry every client's + data each time. With 120 CIFAR-10 clients that is about 800 MB per message, which fills the + head node's disk. Unset the variable to go back to single-machine runs. diff --git a/fltest/frameworks/flower/adapter.py b/fltest/frameworks/flower/adapter.py index 8ef3b9a..9409cc1 100644 --- a/fltest/frameworks/flower/adapter.py +++ b/fltest/frameworks/flower/adapter.py @@ -8,6 +8,7 @@ from __future__ import annotations import os +import sys from typing import Any, Dict, Optional from flwr.simulation import run_simulation @@ -45,6 +46,22 @@ def ray_backend_config(total_cpus: int, total_gpus: int, num_clients: int) -> Di return {"client_resources": {"num_cpus": 1, "num_gpus": per_client_gpu}, "init_args": init_args} +def share_with_cluster(c2loader: Dict[int, Any], backend_config: Dict[str, Any]) -> Dict[int, Any]: + """Put each client's loader into the cluster's object store once and return the references. + + The client app is pickled with every message Flower sends to a client, so a client app that + held the loaders themselves would ship every client's data with every call. Ray is started + here the way Flower starts it, which makes Flower reuse this connection; Flower shuts Ray down + at the end of the run, which frees the stored loaders. + """ + import ray + + if not ray.is_initialized(): + ray.init(runtime_env={"env_vars": {"PYTHONPATH": ":".join(sys.path)}}, + **backend_config["init_args"]) + return {cid: ray.put(loader) for cid, loader in c2loader.items()} + + @register_framework("flwr") @register_framework("flower") class FlowerAdapter(FrameworkAdapter): @@ -79,6 +96,8 @@ def run_simulation(self, spec: RunSpec, data: Dict[str, Any], hook_runner: HookR c2loader = ctx_data.dist_dict if ctx_data.dist_dict is not None else c2loader backend_config = ray_backend_config(spec.total_cpus, spec.total_gpus, spec.num_clients) + if ray_cluster_address(): + c2loader = share_with_cluster(c2loader, backend_config) state_holder: Dict[str, Any] = {} server_app = get_server_app(spec, driver_runner, history, test_loader, state_holder) diff --git a/fltest/frameworks/flower/client.py b/fltest/frameworks/flower/client.py index 0b998f2..b056785 100644 --- a/fltest/frameworks/flower/client.py +++ b/fltest/frameworks/flower/client.py @@ -9,6 +9,7 @@ from __future__ import annotations +import ray from flwr.client import ClientApp, NumPyClient from fltest.core import HookContext @@ -70,12 +71,17 @@ def evaluate(self, parameters, config): return float(loss), len(self.trainloader), {"accuracy": float(acc)} +def client_loader(entry): + """A client's loader, fetched from the object store when it was shared with a cluster.""" + return ray.get(entry) if isinstance(entry, ray.ObjectRef) else entry + + def get_client_app(spec: RunSpec, c2loader) -> ClientApp: """Build the Flower ClientApp; hooks are reconstructed per-worker from ``spec``.""" def client_fn(context): runner = build_hook_runner(spec) # rebuilt in-worker from the picklable spec partition_id = context.node_config["partition-id"] - return FlowerClient(c2loader[partition_id], spec, partition_id, runner).to_client() + return FlowerClient(client_loader(c2loader[partition_id]), spec, partition_id, runner).to_client() return ClientApp(client_fn=client_fn) diff --git a/tests/test_multinode_ray.py b/tests/test_multinode_ray.py index b29849b..7d53a65 100644 --- a/tests/test_multinode_ray.py +++ b/tests/test_multinode_ray.py @@ -1,15 +1,17 @@ """Running Flower clients on a multi-node Ray cluster (FLTEST_RAY_ADDRESS). -Two things must change when the clients leave the driver's machine: Flower joins the existing -cluster instead of starting a private one, and the prepared data shards travel by value, -because a memory-mapped Hugging Face table pickles as a path that only exists on the driver. -These checks need no network and no running cluster. +Three things must change when the clients leave the driver's machine: Flower joins the existing +cluster instead of starting a private one, the prepared data shards travel by value, because a +memory-mapped Hugging Face table pickles as a path that only exists on the driver, and each +client's shard goes into the object store once, so a message to a client does not carry every +client's data. These checks need no network and no running cluster. """ import pytest from fltest.data import datasets -from fltest.frameworks.flower.adapter import RAY_ADDRESS_ENV, ray_backend_config +from fltest.frameworks.flower.adapter import RAY_ADDRESS_ENV, ray_backend_config, share_with_cluster +from fltest.frameworks.flower.client import client_loader @pytest.fixture @@ -49,3 +51,20 @@ def test_cluster_shards_are_in_memory_with_their_own_cache_key(cluster): assert datasets._shards_in_memory() is True key = datasets._cache_key("mnist", 10, "dirichlet", "", {"alpha": 0.5}) assert key == "mnist_10_dirichlet__alpha0.5_inmem" + + +def test_local_loaders_are_used_directly(): + loader = [1, 2, 3] + assert client_loader(loader) is loader + + +def test_shared_loaders_are_fetched_per_client(): + import ray + + ray.init(num_cpus=1, include_dashboard=False) + try: + refs = share_with_cluster({0: [1, 2], 1: [3]}, {"init_args": {}}) + assert all(isinstance(r, ray.ObjectRef) for r in refs.values()) + assert client_loader(refs[1]) == [3] + finally: + ray.shutdown()