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
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,18 @@ 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.

## 0.9.0

**Online FLDetector defense.** Added a hook-based detector for the reference and Flower
backends. It compares each client's current model delta against a history-based L-BFGS
prediction, averages normalized inconsistency over a configurable window, and uses gap
statistics plus two-cluster k-means to identify suspicious clients. Detected submissions
are filtered before aggregation; `before_round` excludes those clients in later rounds.
This online variant does not restart training from the initial model as in the paper.
When paired with Krum, trimmed mean, or median, list `fldetector` first so filtering
precedes the aggregation rule. Flower now carries server-side aggregation-hook metrics
into round history.

## 0.8.0

**Before-round client selection.** The `before_round` hook now receives all eligible
Expand Down
24 changes: 24 additions & 0 deletions docs/defenses.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Two flavors compose through the same hooks:
| `krum` | robust aggregation (select) | `before_aggregate` | `num_byzantine` (1) |
| `trimmed_mean` | robust aggregation (coordinate trim) | `before_aggregate` | `trim` (1) |
| `median` | robust aggregation (coordinate median) | `before_aggregate` | — |
| `fldetector` | history-based client filtering | `before_round`, `before_aggregate`, `after_aggregate` | `window_size` (10), `start_round` (50), `max_clusters` (10), `gap_samples` (20) |

## How each works

Expand All @@ -43,6 +44,29 @@ across clients, then averages the rest.
**`median`** — coordinate-wise median across client updates. Simple and strong against a
Byzantine minority.

**`fldetector`** — compares each client's model delta with a limited-memory BFGS
prediction from earlier rounds. It scores inconsistencies over `window_size` rounds and
uses gap statistics and two-cluster k-means to identify the high-score group. Identified
clients are removed from the current aggregation and excluded from later rounds. This is
an *online* variant: unlike the [FLDetector paper](https://doi.org/10.1145/3534678.3539231),
it does not restart training after detection. It requires unique stable client IDs and
full client participation until detection; custom Flower clients must report their `cid`.
The default `start_round=50` follows the paper's warm-up choice, so shorter experiments
should lower it. At least `window_size + 2` rounds are needed to form the history.

To combine detection with a robust rule, place it first:

```yaml
defenses:
- {name: fldetector, params: {window_size: 10, start_round: 50}}
- {name: median}
```

`fldetector_scores`, `fldetector_detected_clients`, and
`fldetector_detected_count` are recorded in the detection round's metrics. The detector
fails explicitly if submission IDs are missing or an earlier hook changes the update
list's alignment. It is not available on NVFlare.

!!! note "Backend support"
Client-side and robust-aggregation defenses run on the **reference** and **Flower**
backends. **NVFlare** runs clients in separate processes, so it does not apply
Expand Down
7 changes: 6 additions & 1 deletion fltest/core/wiring.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,12 @@ def build_hook_runner(spec: RunSpec, load_env_hooks: bool = True) -> HookRunner:
for atk in spec.attacks:
ATTACKS.get(atk.name)(target_clients=atk.target_clients, **atk.params).attach(runner)

for dfn in spec.defenses:
for index, dfn in enumerate(spec.defenses):
if dfn.name == "fldetector" and any(
prior.name in ("krum", "trimmed_mean", "median")
for prior in spec.defenses[:index]
):
raise ValueError("fldetector must precede the robust aggregator in defenses")
DEFENSES.get(dfn.name)(**dfn.params).attach(runner)

if load_env_hooks:
Expand Down
1 change: 1 addition & 0 deletions fltest/defenses/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"krum": "fltest.defenses.krum",
"trimmed_mean": "fltest.defenses.trimmed_mean",
"median": "fltest.defenses.median",
"fldetector": "fltest.defenses.fldetector",
}

for _name, _module in BUILTIN_DEFENSES.items():
Expand Down
222 changes: 222 additions & 0 deletions fltest/defenses/fldetector.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
"""Online FLDetector: history-based detection before aggregation.

This keeps the paper's prediction, score window, and gap-statistic decision, but
filters a detected client immediately and in later rounds instead of restarting
training from the initial model. FLTest submissions contain model weights, so the
gradient-like vector used here is ``global_weights - client_weights``.
"""

from __future__ import annotations

from collections import deque

import numpy as np

from fltest.core.hook_context import HookContext
from fltest.core.registry import register_defense
from fltest.defenses.base import PPFLBaseClass


def _flatten(arrays) -> np.ndarray:
return np.concatenate([np.asarray(a, dtype=np.float64).ravel() for a in arrays])


def _hessian_product(pairs, vector: np.ndarray) -> np.ndarray:
"""Apply a limited-memory BFGS Hessian (not its inverse) to a vector."""
usable = [
(s, y) for s, y in pairs
if np.dot(s, s) > 1e-12 and np.dot(y, s) > 1e-12
and np.isfinite(s).all() and np.isfinite(y).all()
]
if not usable:
return np.zeros_like(vector)
s_last, y_last = usable[-1]
scale = float(np.dot(y_last, s_last) / np.dot(s_last, s_last))
terms = []

def apply(value):
out = scale * value
for bs, sbs, y, ys in terms:
out = out - bs * (np.dot(bs, value) / sbs) + y * (np.dot(y, value) / ys)
return out

for s, y in usable:
ys = float(np.dot(y, s))
if ys <= 1e-12 or not np.isfinite(ys):
continue
bs = apply(s)
sbs = float(np.dot(s, bs))
if sbs <= 1e-12 or not np.isfinite(sbs):
continue
terms.append((bs, sbs, y, ys))
return apply(vector)


def _cluster_costs(values: np.ndarray, max_clusters: int):
"""Exact one-dimensional k-means costs and split points."""
values = np.sort(np.asarray(values, dtype=np.float64))
n = len(values)
sums = np.r_[0.0, np.cumsum(values)]
squares = np.r_[0.0, np.cumsum(values * values)]
cost = np.full((max_clusters + 1, n + 1), np.inf)
split = np.zeros((max_clusters + 1, n + 1), dtype=int)
cost[0, 0] = 0.0
for k in range(1, max_clusters + 1):
for end in range(k, n + 1):
starts = np.arange(k - 1, end)
count = end - starts
total = sums[end] - sums[starts]
sse = squares[end] - squares[starts] - total * total / count
candidates = cost[k - 1, starts] + np.maximum(sse, 0.0)
best = int(np.argmin(candidates))
cost[k, end] = candidates[best]
split[k, end] = starts[best]
return cost[:, n], split


def _suspected_ids(scores: dict[int, float], max_clusters: int, samples: int, seed: int):
if len(scores) < 3:
return set()
ids = sorted(scores)
values = np.array([scores[cid] for cid in ids], dtype=np.float64)
spread = float(np.ptp(values))
if not np.isfinite(spread) or spread <= 1e-12:
return set()
values = (values - values.min()) / spread
limit = min(max_clusters, len(values) - 1)
observed, _ = _cluster_costs(values, limit + 1)
rng = np.random.default_rng(seed)
references = np.array([
_cluster_costs(rng.uniform(size=len(values)), limit + 1)[0][1:]
for _ in range(samples)
])
eps = np.finfo(float).tiny
ref_logs = np.log(np.maximum(references, eps))
gaps = ref_logs.mean(axis=0) - np.log(np.maximum(observed[1:], eps))
deviation = np.sqrt(1.0 + 1.0 / samples) * ref_logs.std(axis=0, ddof=1)
chosen = next(
(k for k in range(1, limit + 1)
if gaps[k - 1] >= gaps[k] - deviation[k]),
limit + 1,
)
if chosen == 1:
return set()
_, two_split = _cluster_costs(values, 2)
boundary = two_split[2, len(values)]
sorted_ids = sorted(ids, key=lambda cid: scores[cid])
return set(sorted_ids[boundary:])


@register_defense("fldetector")
class FLDetectorDefense(PPFLBaseClass):
"""Detect clients with repeatedly inconsistent updates, then exclude them.

Must precede an optional robust aggregator in the defense list. Requires
identified submissions from the reference or Flower backend.
"""

HOOKS = ("before_simulation", "before_round", "before_aggregate", "after_aggregate")

def __init__(self, window_size=10, start_round=50, max_clusters=10, gap_samples=20, **params):
super().__init__(**params)
if window_size < 1 or start_round < 1 or max_clusters < 2 or gap_samples < 2:
raise ValueError("Invalid FLDetector window, start round, cluster, or sample count")
self.window_size = int(window_size)
self.start_round = int(start_round)
self.max_clusters = int(max_clusters)
self.gap_samples = int(gap_samples)
self._reset()

def _reset(self):
self.excluded_clients: set[int] = set()
self._previous_updates: dict[int, np.ndarray] = {}
self._previous_model: np.ndarray | None = None
self._previous_gradient: np.ndarray | None = None
self._pairs = deque(maxlen=self.window_size)
self._distances = deque(maxlen=self.window_size)
self._current_model: np.ndarray | None = None

def before_simulation(self, ctx: HookContext) -> None:
self._reset()

def before_round(self, ctx: HookContext) -> None:
if not self.excluded_clients:
return
selected = ctx.selected_clients
if selected is None:
selected = range(ctx.cfg.num_clients)
ctx.selected_clients = tuple(cid for cid in selected if cid not in self.excluded_clients)
if not ctx.selected_clients:
raise ValueError("FLDetector excluded every available client")

def before_aggregate(self, ctx: HookContext) -> None:
submissions = ctx.client_submissions
uw = ctx.updates_and_weights
if not submissions or uw is None or ctx.global_state is None:
raise ValueError("FLDetector requires identified submissions and a global model")
if len(submissions) != len(uw) or any(
len(record.update) != len(update)
or any(a is not b for a, b in zip(record.update, update))
for record, (update, _) in zip(submissions, uw)
):
raise ValueError("FLDetector requires submissions aligned with aggregation inputs")
ids = [record.client_id for record in submissions]
if any(cid is None for cid in ids) or len(set(ids)) != len(ids):
raise ValueError("FLDetector requires unique, stable client IDs")

model = _flatten(ctx.global_state)
updates = {record.client_id: model - _flatten(record.update) for record in submissions}
distances = {}
if self._previous_model is not None and self._pairs:
hvp = _hessian_product(self._pairs, model - self._previous_model)
distances = {
cid: float(np.linalg.norm(update - self._previous_updates[cid] - hvp))
for cid, update in updates.items() if cid in self._previous_updates
}
total = sum(distances.values())
if total > 0:
distances = {cid: value / total for cid, value in distances.items()}
else:
distances = {cid: 0.0 for cid in distances}
self._distances.append(distances)

if (not self.excluded_clients and ctx.round is not None
and ctx.round >= self.start_round and len(self._pairs) >= self.window_size
and len(self._distances) >= self.window_size):
common = set(updates).intersection(*(set(row) for row in self._distances))
scores = {
cid: float(np.mean([row[cid] for row in self._distances]))
for cid in common
}
detected = _suspected_ids(
scores, self.max_clusters, self.gap_samples,
int(ctx.cfg.seed) + int(ctx.round),
)
self.excluded_clients.update(detected)
ctx.record(
fldetector_scores=scores,
fldetector_detected_clients=sorted(detected),
fldetector_detected_count=len(detected),
)

self._previous_updates = {cid: value.copy() for cid, value in updates.items()}
self._current_model = model.copy()
if self.excluded_clients:
ctx.updates_and_weights = [
pair for cid, pair in zip(ids, uw) if cid not in self.excluded_clients
]
if not ctx.updates_and_weights:
raise ValueError("FLDetector filtered every received update")

def after_aggregate(self, ctx: HookContext) -> None:
current = self._current_model
if current is None or ctx.new_global_state is None:
return
gradient = current - _flatten(ctx.new_global_state)
if self._previous_model is not None and self._previous_gradient is not None:
self._pairs.append((
current - self._previous_model,
gradient - self._previous_gradient,
))
self._previous_model = current.copy()
self._previous_gradient = gradient.copy()
3 changes: 3 additions & 0 deletions fltest/frameworks/flower/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ def __init__(self, hook_runner: HookRunner, spec: RunSpec, history: Dict, **kwar
self._spec = spec
self._history = history
self._last_fit_metrics: Dict[str, float] = {}
self._last_server_metrics: Dict = {}
self._client_id_by_proxy: Dict[str, int] = {}
self._global_state = (
parameters_to_ndarrays(initial_parameters) if initial_parameters is not None else None
Expand Down Expand Up @@ -117,6 +118,7 @@ def aggregate_fit(self, server_round, results, failures):
ctx.new_global_state = aggregated
self._global_state = aggregated
self._hooks.run("after_aggregate", ctx)
self._last_server_metrics = dict(ctx.metrics)

# Surface client-side hook metrics (e.g. DLG reconstruction) by averaging numerics.
acc: Dict[str, List[float]] = defaultdict(list)
Expand Down Expand Up @@ -154,6 +156,7 @@ def evaluate_fn(server_round, parameters, config):
strat_metrics = getattr(evaluate_fn, "_strategy", None)
if strat_metrics is not None:
ctx.metrics.update(strat_metrics._last_fit_metrics)
ctx.metrics.update(strat_metrics._last_server_metrics)
hook_runner.run("after_round", ctx)
if server_round > 0:
history[server_round] = dict(ctx.metrics)
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "fltest"
version = "0.8.0"
version = "0.9.0"
description = "FLTest: a testbed for evaluating privacy and robustness of Privacy-Preserving Federated Learning (PPFL)."
readme = "README.md"
requires-python = ">=3.10,<3.13"
Expand Down
Loading
Loading