From 28be1555ade47dc924f9372ccce3c4ca0289da88 Mon Sep 17 00:00:00 2001 From: Abdullah Soomro Date: Thu, 17 Sep 2026 11:44:32 -0400 Subject: [PATCH] feat: add online FLDetector defense --- CHANGELOG.md | 12 ++ docs/defenses.md | 24 ++++ fltest/core/wiring.py | 7 +- fltest/defenses/__init__.py | 1 + fltest/defenses/fldetector.py | 222 +++++++++++++++++++++++++++++ fltest/frameworks/flower/server.py | 3 + pyproject.toml | 2 +- tests/test_fldetector.py | 132 +++++++++++++++++ tests/test_registry_and_fuzzer.py | 2 +- 9 files changed, 402 insertions(+), 3 deletions(-) create mode 100644 fltest/defenses/fldetector.py create mode 100644 tests/test_fldetector.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 4535c7d..162b34a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/docs/defenses.md b/docs/defenses.md index 01c1ef0..82279bf 100644 --- a/docs/defenses.md +++ b/docs/defenses.md @@ -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 @@ -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 diff --git a/fltest/core/wiring.py b/fltest/core/wiring.py index ff87d68..e4565e7 100644 --- a/fltest/core/wiring.py +++ b/fltest/core/wiring.py @@ -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: diff --git a/fltest/defenses/__init__.py b/fltest/defenses/__init__.py index 67e362e..9bcb67c 100644 --- a/fltest/defenses/__init__.py +++ b/fltest/defenses/__init__.py @@ -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(): diff --git a/fltest/defenses/fldetector.py b/fltest/defenses/fldetector.py new file mode 100644 index 0000000..c44b83a --- /dev/null +++ b/fltest/defenses/fldetector.py @@ -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() diff --git a/fltest/frameworks/flower/server.py b/fltest/frameworks/flower/server.py index a6443a5..7d90a84 100644 --- a/fltest/frameworks/flower/server.py +++ b/fltest/frameworks/flower/server.py @@ -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 @@ -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) @@ -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) diff --git a/pyproject.toml b/pyproject.toml index 62b5436..a4af511 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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" diff --git a/tests/test_fldetector.py b/tests/test_fldetector.py new file mode 100644 index 0000000..3421a5b --- /dev/null +++ b/tests/test_fldetector.py @@ -0,0 +1,132 @@ +"""Online FLDetector's hook contract and aggregation composition.""" + +import numpy as np +import pytest + +from fltest.core import ClientSubmission, HookContext +from fltest.core.config import DefenseSpec, RunSpec +from fltest.core.wiring import build_hook_runner +from fltest.defenses.fldetector import FLDetectorDefense, _hessian_product, _suspected_ids + + +def _spec(**kwargs): + return RunSpec(**{"run_id": "det", "run_name": "det", "framework": "reference", **kwargs}) + + +def _round_context(spec, round_number, model, gradients): + submissions = tuple( + ClientSubmission(cid, (np.array([model - gradient], dtype=np.float32),), 1) + for cid, gradient in gradients.items() + ) + return HookContext( + cfg=spec, round=round_number, + global_state=[np.array([model], dtype=np.float32)], + client_submissions=submissions, + updates_and_weights=[(list(item.update), item.num_samples) for item in submissions], + ) + + +def test_hessian_product_uses_gradient_curvature(): + s = np.array([2.0, 1.0]) + y = np.array([4.0, 2.0]) + assert np.allclose(_hessian_product([(s, y)], np.array([3.0, -1.0])), [6.0, -2.0]) + assert np.array_equal( + _hessian_product([(np.zeros(2), np.zeros(2))], np.array([3.0, -1.0])), + np.zeros(2), + ) + + +def test_gap_statistics_separates_obvious_high_score_cluster(): + scores = {0: 0.01, 1: 0.011, 2: 0.012, 3: 0.91, 4: 0.93} + assert _suspected_ids(scores, max_clusters=3, samples=20, seed=1) == {3, 4} + assert _suspected_ids({cid: 0.2 for cid in scores}, 3, 20, 1) == set() + + +def test_fldetector_filters_current_round_then_excludes_future_training(): + spec = _spec(num_clients=5) + detector = FLDetectorDefense(window_size=1, start_round=3, max_clusters=3) + detector.before_simulation(HookContext(cfg=spec)) + for rnd, model in ((1, 0.0), (2, -1.0), (3, -2.0)): + gradients = {0: 1.0, 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04} + if rnd == 3: + gradients[4] = 10.0 + ctx = _round_context(spec, rnd, model, gradients) + detector.before_aggregate(ctx) + if rnd < 3: + assert len(ctx.updates_and_weights) == 5 + else: + assert detector.excluded_clients == {4} + assert len(ctx.updates_and_weights) == 4 + assert ctx.metrics["fldetector_detected_clients"] == [4] + ctx.new_global_state = [np.array([model - 1.0], dtype=np.float32)] + detector.after_aggregate(ctx) + + next_round = HookContext(cfg=spec, selected_clients=tuple(range(5))) + detector.before_round(next_round) + assert next_round.selected_clients == (0, 1, 2, 3) + + +def test_fldetector_requires_identity_and_unmodified_alignment(): + spec = _spec() + detector = FLDetectorDefense() + ctx = _round_context(spec, 1, 0.0, {0: 1.0, 1: 1.1}) + ctx.client_submissions = (ClientSubmission(None, ctx.client_submissions[0].update, 1), + ctx.client_submissions[1]) + with pytest.raises(ValueError, match="unique, stable client IDs"): + detector.before_aggregate(ctx) + + ctx = _round_context(spec, 1, 0.0, {0: 1.0, 1: 1.1}) + ctx.updates_and_weights.reverse() + with pytest.raises(ValueError, match="aligned"): + detector.before_aggregate(ctx) + + +def test_fldetector_must_run_before_optional_robust_aggregator(): + spec = _spec(defenses=[DefenseSpec(name="median"), DefenseSpec(name="fldetector")]) + with pytest.raises(ValueError, match="must precede"): + build_hook_runner(spec, load_env_hooks=False) + + spec.defenses.reverse() + runner = build_hook_runner(spec, load_env_hooks=False) + handlers = runner._registry["before_aggregate"] + assert [type(handler.__self__).__name__ for handler in handlers] == [ + "FLDetectorDefense", "MedianDefense", + ] + + +def test_flower_aggregation_uses_fldetector_filter_and_keeps_hook_metrics(): + from types import SimpleNamespace + + from flwr.common import Code, ndarrays_to_parameters, parameters_to_ndarrays + + from fltest.core import HookRunner + from fltest.frameworks.flower.server import HookedFedAvg + + spec = _spec(framework="flwr", num_clients=5) + runner = HookRunner() + detector = FLDetectorDefense(window_size=1, start_round=3, max_clusters=3) + detector.attach(runner) + strategy = HookedFedAvg( + hook_runner=runner, spec=spec, history={}, + initial_parameters=ndarrays_to_parameters([np.array([0.0], dtype=np.float32)]), + ) + + for rnd, model in ((1, 0.0), (2, -1.0), (3, -2.0)): + gradients = [1.0, 1.01, 1.02, 1.03, 1.04 if rnd < 3 else 10.0] + results = [( + SimpleNamespace(), + SimpleNamespace( + status=SimpleNamespace(code=Code.OK), + parameters=ndarrays_to_parameters([ + np.array([model - gradient], dtype=np.float32) + ]), + num_examples=1, + metrics={"cid": cid}, + ), + ) for cid, gradient in enumerate(gradients)] + aggregated, _ = strategy.aggregate_fit(rnd, results, []) + if rnd == 3: + assert np.allclose(parameters_to_ndarrays(aggregated)[0], [model - 1.015]) + assert strategy._last_server_metrics["fldetector_detected_clients"] == [4] + # Keep the synthetic model trajectory controlled for the next prediction. + strategy._global_state = [np.array([model - 1.0], dtype=np.float32)] diff --git a/tests/test_registry_and_fuzzer.py b/tests/test_registry_and_fuzzer.py index 6b63245..3312cf8 100644 --- a/tests/test_registry_and_fuzzer.py +++ b/tests/test_registry_and_fuzzer.py @@ -16,7 +16,7 @@ def test_registries_populated(): "label_flip", "sign_flip", "gaussian", "backdoor", "dlg", "membership_inference", "model_replacement", } <= set(ATTACKS.names()) - assert {"gradient_noise", "norm_clip", "krum", "trimmed_mean", "median"} <= set(DEFENSES.names()) + assert {"gradient_noise", "norm_clip", "krum", "trimmed_mean", "median", "fldetector"} <= set(DEFENSES.names()) assert {"accuracy", "loss", "per_client"} <= set(METRICS.names())