Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
62 changes: 62 additions & 0 deletions docs/multi-node.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# 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=<head-ip> --port=6379 --num-cpus=<cores> --disable-usage-stats
```

Then on every other node:

```bash
ray start --address=<head-ip>:6379 --node-ip-address=<this-node-ip> --num-cpus=<cores> --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=<head-ip>:6379
fltest run my_config.yaml
```

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
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.
- **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.

## 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.
29 changes: 25 additions & 4 deletions fltest/data/datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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])


Expand Down Expand Up @@ -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 {
Expand All @@ -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,
Expand All @@ -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
Expand Down
51 changes: 44 additions & 7 deletions fltest/frameworks/flower/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@

from __future__ import annotations

from typing import Any, Dict
import os
import sys
from typing import Any, Dict, Optional

from flwr.simulation import run_simulation

Expand All @@ -22,6 +24,44 @@
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}


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):
Expand Down Expand Up @@ -55,12 +95,9 @@ 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)
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)
Expand Down
8 changes: 7 additions & 1 deletion fltest/frameworks/flower/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from __future__ import annotations

import ray
from flwr.client import ClientApp, NumPyClient

from fltest.core import HookContext
Expand Down Expand Up @@ -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)
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
70 changes: 70 additions & 0 deletions tests/test_multinode_ray.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
"""Running Flower clients on a multi-node Ray cluster (FLTEST_RAY_ADDRESS).

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, share_with_cluster
from fltest.frameworks.flower.client import client_loader


@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"


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()
Loading