diff --git a/README.md b/README.md index 149fe11..c9b1796 100644 --- a/README.md +++ b/README.md @@ -43,8 +43,11 @@ makes a rigorous setup the default and *checks* for the common pitfalls. share one `HookContext`. A plugin written once runs across every backend, and several plugins compose on a single run. - **Attacks:** `label_flip`, `sign_flip`, `gaussian`, `backdoor` and `model_replacement` - (with attack-success-rate), `dlg` (gradient-inversion privacy attack), and - `membership_inference` (loss-threshold privacy attack, scored as AUC each round). + (with attack-success-rate), `little_is_enough` (Byzantine attack sized to the honest + clients' own variance, so robust aggregation keeps selecting it) and its backdoor variants + `little_is_enough_backdoor` and `little_is_enough_cropped_backdoor`, `dlg` + (gradient-inversion privacy attack), and `membership_inference` (loss-threshold privacy + attack, scored as AUC each round). - **Defenses (PPFL):** `gradient_noise` (DP-style clip+noise), `norm_clip`, robust aggregation `krum` / `trimmed_mean` / `median`, and secure aggregation `secure_aggregation` (float pairwise masking) / `mpc_aggregation` (fixed point in a @@ -93,6 +96,7 @@ fltest run examples/configs/exhaustive_eval.yaml fltest run examples/configs/membership_inference.yaml fltest run examples/configs/dlg.yaml # gradient inversion fltest run examples/configs/model_replacement.yaml # boosted backdoor, reference + Flower +fltest run examples/configs/little_is_enough.yaml # Byzantine attack vs Krum, each robust rule, FLDetector fltest run examples/configs/secure_agg.yaml # DLG vs no defense / DP noise / masking fltest run examples/configs/mpc_aggregation.yaml # what the finite ring costs: quantization, overflow, dropouts diff --git a/docs/attacks.md b/docs/attacks.md index 3bb52ca..ad042ed 100644 --- a/docs/attacks.md +++ b/docs/attacks.md @@ -10,9 +10,10 @@ attacks: Multiple attacks compose. `target_clients` restricts which clients are adversarial. -`backdoor` and `dlg` operate on pixels, so they apply only to image datasets and raise a -clear error on a text run. `label_flip`, `sign_flip`, `gaussian`, and `model_replacement` -work on labels or updates, so they apply to either modality. +`backdoor`, `little_is_enough_backdoor`, `little_is_enough_cropped_backdoor`, and `dlg` +operate on pixels, so they apply only +to image datasets and raise a clear error on a text run. `label_flip`, `sign_flip`, `gaussian`, `model_replacement`, and +`little_is_enough` work on labels or updates, so they apply to either modality. ## Catalog @@ -22,6 +23,9 @@ work on labels or updates, so they apply to either modality. | `gaussian` | model poisoning (naive) | `after_client_train` | `sigma` (0.1) | | `sign_flip` | model poisoning | `after_client_train` | `scale` (1.0) | | `model_replacement` | model poisoning (targeted) | `after_client_train` | `scale` (automatic), `target_round` | +| `little_is_enough` | model poisoning (Byzantine, evasive) | `before_aggregate` | `z` (automatic), `target_clients` (required) | +| `little_is_enough_cropped_backdoor` | model poisoning (targeted, evasive) | `on_data_distribute`, `before_aggregate`, `after_round` | `z` (automatic), `target_label` (0), `patch_size` (5), `target_clients` (required) | +| `little_is_enough_backdoor` | model poisoning (targeted, evasive) | `on_data_distribute`, `before_aggregate`, `after_round` | `z` (automatic), `alpha` (1.0), `epochs` (5), `samples` (1000), `target_label` (0), `patch_size` (5), `target_clients` (required) | | `backdoor` | data poisoning (targeted) | `before_client_train`, `after_round` | `target_label` (0), `infection_rate` (0.3), `patch_size` (4), `patch_value` (1.0) | | `dlg` | privacy (gradient inversion) | `before_client_train` (+ `before_aggregate` in shared_update mode) | `target_client`, `target_round`, `num_images`, `iters`, `source` | | `membership_inference` | privacy (inference) | `on_data_distribute`, `after_round` | `target_client` (0), `max_samples` (512) | @@ -64,6 +68,147 @@ model only in round 3, at an automatic scale of 4.0. Replacement takes attack su | Flower | backdoor only | 0.2724 | 0.8867 | | Flower | model replacement | 0.9892 | 0.8506 | +**`little_is_enough`** — a Byzantine attack that measures the honest population before +perturbing it, from Baruch et al., [*A Little Is Enough: Circumventing Defenses For +Distributed Learning*](https://proceedings.neurips.cc/paper/2019/hash/ec1c59141046cd1866bbbcdfb6ae31d4-Abstract.html). +`gaussian` and `sign_flip` perturb an update without reference to the honest ones, so a +perturbation big enough to matter is also an outlier — exactly what `krum`, `median` and +`trimmed_mean` filter. This attack instead sets every attacker's update to the benign mean +shifted by a fraction of the benign standard deviation, per coordinate: + +``` +u' = mu - z * sigma +``` + +With `n` participants and `m` attackers, `s = floor(n/2 + 1) - m` honest workers are needed +to complete a majority, and the default `z` is the largest value with +`Phi(z) < (n - m - s) / (n - m)` — the most an attacker can move while still sitting inside +the range a majority of honest workers occupy. The attack runs at `before_aggregate`, where +FLTest exposes every submission, and rewrites only the attackers' entries; attacks attach +before defenses, so a robust aggregator in the same config still sees the crafted updates. +`target_clients` is required, because the crafted update is built from the *other* clients' +submissions. NVFlare does not emit `before_aggregate` and cannot run this attack. + +**Reading the outcome.** Accuracy alone is a poor success signal for an untargeted Byzantine +attack, so the attack scores itself at `after_aggregate`. It records the `z` it asked for, +`little_is_enough_drift` (how far the aggregate actually landed from the benign mean, in +benign standard deviations) and `little_is_enough_absorption` (`drift / z` — the share of the +requested shift the defense conceded). The anchor for reading absorption is plain FedAvg, +which concedes exactly the attackers' share of the round's total sample weight — `m/n` when +every client holds an equal shard, and their data share otherwise. A defense scoring above +its own FedAvg line is doing worse than no defense at all. + +Measured over one aggregation round on a controlled population of ten clients, four of them +adversarial, so the numbers isolate what each rule concedes rather than how training then +unfolds (the `rules-*` runs in `little_is_enough.yaml` are the trained version): + +| Aggregation | `z = 1.0` | `z = 1.5` | `z = 3.0` | +|-------------|----------:|----------:|----------:| +| FedAvg (no defense), 4 of 10 attackers | 0.40 | 0.40 | 0.40 | +| `krum` | 1.00 | 1.00 | 0.00 | +| `median` | 0.85 | 0.69 | 0.36 | +| `trimmed_mean`, `trim: 2` | 0.63 | 0.57 | 0.46 | + +Krum concedes everything while it accepts the craft, because it returns one selected update +and that update is the attacker's — strictly worse than averaging. It drops to zero the +moment `z` puts the craft outside the honest spread. The coordinate-wise rules never fully +accept or reject: they concede a share that *falls* as `z` grows, because pushing an already +extreme value further does not move a median. + +The `rules-*` runs in `little_is_enough.yaml` train at `z = 1.5` for four rounds. Over the +same five seeds: + +| Run | Accuracy | Absorption | +|-----|---------:|-----------:| +| no attack, FedAvg | 0.8283 ± 0.0142 | – | +| attack, FedAvg (no defense) | 0.7939 ± 0.0225 | 0.4000 ± 0.0000 | +| attack, `krum` | 0.7582 ± 0.0332 | 1.0000 ± 0.0000 | +| attack, `median` | 0.7783 ± 0.0243 | 0.6892 ± 0.0019 | +| attack, `trimmed_mean`, `trim: 2` | 0.7873 ± 0.0225 | 0.5616 ± 0.0017 | + +**Every robust rule here concedes more than plain averaging does.** Against this attack the +protection ordering runs backwards: no defense (0.40) is the most resistant, then +`trimmed_mean` (0.56), then `median` (0.69), and `krum` (1.00) hands over the whole model. + +Note how differently the two columns behave. Absorption is reproducible to the fourth decimal +across seeds; accuracy varies by ±0.02 to ±0.03, which is wider than the gaps between the +rows. So the absorption ordering is a result, and the matching accuracy ordering is not — it +may well be coincidence at this scale. Krum's accuracy spread is the widest of all (±0.0332), +which is Krum itself rather than the attack: even when it defends successfully it keeps one +update and discards nine, so the round's model is whichever client it happened to pick. + +The runnable sweep puts four attackers among ten clients behind Krum for eight rounds, over +five seeds (786, 101, 202, 303, 404): + +| Run | `z` | Accuracy | Absorption | Krum's pick | +|-----|----:|---------:|-----------:|-------------| +| no attack | – | 0.8559 ± 0.0222 | – | an honest client | +| `little_is_enough` (automatic) | 0.4307 | 0.8775 ± 0.0161 | 1.00 | the attacker | +| `little_is_enough` | 1.5 | 0.8473 ± 0.0244 | 1.00 | the attacker | +| `little_is_enough` | 3.0 | 0.8303 ± 0.0691 | 0.03 | an honest client | +| `gaussian`, `sigma: 0.5` | – | 0.8303 ± 0.0691 | – | an honest client | + +**Evasion is reliable here; damage is not.** Absorption is 1.00 at both `z = 0.43` and +`z = 1.5` in every seed — Krum takes the crafted update whole, every round, deterministically. +That is the attack working exactly as the paper describes, and it is the result to quote. + +Accuracy is a different story. At `z = 1.5` the attack costs 0.9 points against a baseline +whose own seed-to-seed spread is ±0.022, so at this scale getting past Krum buys the attacker +nothing measurable. Do not read the middle row as damage. An earlier single-seed run of this +same config showed a 4.6-point drop at `z = 1.5`; four more seeds showed that was the seed, +not the attack. + +Two findings do survive the seeds. The automatic `z` of 0.43 makes accuracy *rise*, in four +of five seeds: the craft sits so close to the benign mean that Krum selecting it beats Krum's +usual pick of one client's noisy update, so the attacker is invisible and actively unhelpful +to itself. And at `z = 3.0` the craft has left the honest spread, Krum rejects it (absorption +0.03), and the run becomes identical to the filtered `gaussian` baseline — not similar, +identical, in all five seeds, because both are filtered and Krum falls back to the same +honest client. + +The lesson for using this attack is that accuracy is too noisy to evaluate it at this scale. +Score it with `little_is_enough_absorption`, which is deterministic and separates "the defense +filtered me" from "the defense took the bait." + +The automatic `z` is small whenever attackers are a small fraction of the round: it is 0 +below roughly `n/2` attackers and reaches the paper's headline 1.43 only at 24 attackers out +of 50. Treat it as the stealth ceiling, not as a recommended strength, and sweep `z` +(`attack_strength` in [metamorphic testing](metamorphic-testing.md)) to find where a defense +actually breaks. + +**`little_is_enough_backdoor`** — the same paper's backdoor variant (Section 3.4, +Algorithm 4), and the version of "A Little Is Enough" the FLDetector paper evaluates. It +spends the `z`-deviation budget on a goal instead of a fixed shift: starting from the +benign mean `mu`, the attacker trains on `samples` of its own images with the upper-left +`patch_size` x `patch_size` pixels set to maximal intensity and relabelled `target_label`, +for `epochs` passes, then clamps every parameter into `mu ± z·sigma` and submits the result +from every attacker. The defaults are the paper's pattern experiment: 1000 images, a 5x5 +trigger, label 0, five passes. It records `attack_success_rate` every round, the share of +triggered test images (true label other than the target) sent to `target_label`. + +`alpha` weights the paper's Equation 3, `alpha·l_backdoor + (1 - alpha)·l_delta`. Equation +4's `l_delta` measures each parameter's distance from `mu` in units of `z·sigma`, and +honest clients agree so closely that this term's curvature, `1/(z·sigma)^2`, makes plain SGD +diverge; it is minimised exactly with a proximal step instead. Summed over every parameter +it also outweighs the backdoor loss so heavily that the optimum stays at `mu`: on MNIST with +the MLP, `alpha = 0.2` leaves the crafted update identical to the benign mean. The default +`alpha = 1` lets the clamp alone keep the update inside the honest range, which is the +clamp's job, and the backdoor then builds up round after round. Median over 30 rounds at 28% +attackers reaches ASR 0.49 at `z = 0.74` while clean accuracy stays at 0.91; at the paper's +`z = 0.2` it reaches only 0.03 in that time. + +**`little_is_enough_cropped_backdoor`** — the same attack as the FLDetector paper describes +running it: each malicious update "computed following the Scaling Attack", which the +attacker then "crops" into range. Every round, each attacker trains its own model from the +global model on its own images plus a trigger-stamped duplicate of each, labelled +`target_label` (the Scaling attack's augmentation, scaling factor 1), with the run's +`client_epochs`, `client_lr`, and `client_batch_size`. It then clamps every parameter into +the honest `mu ± z·sigma`. `little_is_enough_backdoor` trains one update from the honest +mean and gives it to every attacker; this one gives each attacker its own, anchored to its +own poisoned training. That is the difference a consistency detector such as `fldetector` +reads. Trigger, target label, and `attack_success_rate` are as for +`little_is_enough_backdoor`. + **`backdoor`** — the attacker stamps a bright patch on a fraction (`infection_rate`) of its images and relabels them to `target_label`; the global model learns *trigger ⇒ target_label*. At each round end it measures **attack success rate (ASR)** — the @@ -121,6 +266,14 @@ dataset: cifar10 attacks: [{name: dlg, params: {target_client: 0, target_round: 1, iters: 300, source: gradient}}] ``` -Runnable: `examples/configs/attack_label_flip.yaml`, `model_replacement.yaml`, `dlg.yaml`. +```yaml +# Byzantine attack sized to the honest spread; sweep z to find where the defense breaks +defenses: [{name: krum, params: {num_byzantine: 4}}] +attacks: [{name: little_is_enough, params: {z: 1.5}, target_clients: [0, 1, 2, 3]}] +``` + +Runnable: `examples/configs/attack_label_flip.yaml`, `model_replacement.yaml`, +`little_is_enough.yaml` (strength sweep against Krum, the same attack against each +aggregation rule, and against FLDetector), `dlg.yaml`. To add your own attack, see **[Port your attacks & defenses](extending.md)**. diff --git a/docs/installation.md b/docs/installation.md index 98b285a..46901b2 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -49,11 +49,11 @@ pip install -e ".[docs]" # this documentation site (mkdocs-material) ```bash fltest list # Frameworks: ['flare', 'flower', 'flwr', 'nvflare', 'reference'] -# Attacks: ['backdoor', 'dlg', 'gaussian', 'label_flip', 'membership_inference', 'model_replacement', 'sign_flip'] +# Attacks: ['backdoor', 'dlg', 'gaussian', 'label_flip', 'little_is_enough', 'little_is_enough_backdoor', 'little_is_enough_cropped_backdoor', 'membership_inference', 'model_replacement', 'sign_flip'] # Defenses: ['fldetector', 'gradient_noise', 'krum', 'median', 'mpc_aggregation', 'norm_clip', 'secure_aggregation', 'trimmed_mean'] # Metrics: ['accuracy', 'loss', 'per_client'] -pytest tests/ -q # 110 passing +pytest tests/ -q # 130 passing ``` `fltest list` and `fltest pitfalls` return immediately, because neither needs to load a diff --git a/docs/metrics.md b/docs/metrics.md index c8edb5e..cdbb51b 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -19,13 +19,16 @@ The test subset size is `max_test_data_size`. These three appear in `final` for | Metric | Produced by | Meaning | |--------|-------------|---------| -| `attack_success_rate` | `backdoor` attack | fraction of a *triggered* test set predicted as the target label (excludes samples already of the target) | +| `attack_success_rate` | `backdoor`, `little_is_enough_backdoor`, `little_is_enough_cropped_backdoor` attacks | fraction of a *triggered* test set predicted as the target label (excludes samples already of the target) | | `reconstruction_mse` | `dlg` attack | pixel MSE between the reconstructed and true victim image (lower = better reconstruction = worse privacy) | | `reconstruction_psnr` | `dlg` attack | peak signal-to-noise ratio of the reconstruction (higher = better reconstruction) | | `label_recovery` | `dlg` attack | fraction of victim labels correctly recovered | | `membership_inference_auc` | `membership_inference` attack | probability that a random training sample looks more member-like than a random held-out one; 0.5 is no leakage, 1.0 is perfect separation | | `membership_loss_gap` | `membership_inference` attack | mean held-out loss minus mean training loss, which is the overfitting gap the attack exploits | | `model_replacement_scale` | `model_replacement` attack | factor applied to the malicious client's delta from the current global model | +| `little_is_enough_z` | `little_is_enough` attack | standard deviations the crafted update sits from the benign mean; large enough to hurt and small enough to stay selected is the whole attack | +| `little_is_enough_drift` | `little_is_enough` attack | how far the round's aggregate actually landed from the benign mean, in benign standard deviations — the shift the attack really achieved | +| `little_is_enough_absorption` | `little_is_enough` attack | `drift / z`: the fraction of the requested shift the defense conceded. 0 means fully filtered, 1 means the crafted update was taken wholesale. Plain FedAvg concedes the attackers' share of total sample weight (`m/n` for equal shards), so anything above that line is a defense doing worse than no defense | | `per_client_acc_mean` / `per_client_acc_min` | `per_client` listener | personalized accuracy of the final global model on each client's own data — `min` exposes representation disparity (project Pitfall-3) | Add `per_client` to `metrics:` to enable personalized evaluation. Attack metrics appear @@ -76,10 +79,17 @@ the comparison is measured. | `detection_f1` | harmonic mean of the two | | `detection_false_positives` | honest clients the defense wrongly flagged | | `detection_missed` | malicious clients the defense never flagged | +| `detection_accuracy` | DACC in the FLDetector paper: the share of all `num_clients` classified correctly, counting an unflagged client as classified benign | +| `detection_fpr` | share of honest clients flagged as malicious | +| `detection_fnr` | share of malicious clients left unflagged (`1 - detection_recall`) | + +The last three are the FLDetector paper's own detection metrics, so a run can be read +against its Table 2 directly. Ground truth is the union of `target_clients` over the attacks that make a client -malicious, which are `backdoor`, `label_flip`, `sign_flip`, `gaussian`, and -`model_replacement`. `dlg` and `membership_inference` are deliberately excluded, because an +malicious, which are `backdoor`, `label_flip`, `sign_flip`, `gaussian`, +`model_replacement`, `little_is_enough`, `little_is_enough_backdoor`, and +`little_is_enough_cropped_backdoor`. `dlg` and `membership_inference` are deliberately excluded, because an honest-but-curious server names a *victim* rather than an adversary, and counting one would mark an honest client as a detection the defense owed you. diff --git a/examples/configs/little_is_enough.yaml b/examples/configs/little_is_enough.yaml new file mode 100644 index 0000000..d83bf97 --- /dev/null +++ b/examples/configs/little_is_enough.yaml @@ -0,0 +1,65 @@ +# Does FLDetector stop "A Little Is Enough", as its paper claims? +# +# Zhang et al., FLDetector (KDD 2022) define ALIE as the Scaling Attack's backdoor update +# cropped into the honest clients' own range, and report on MNIST with Median aggregation +# and 28 of 100 clients malicious: +# +# ALIE without FLDetector 97.8 accuracy / 100.0 ASR +# ALIE with FLDetector 97.9 accuracy / 0.3 ASR (their Table 3) +# detection of ALIE FNR 0.00, every attacker caught (their Table 2) +# +# Three runs, one attack: the clean baseline, the attack undefended, and the attack with +# FLDetector in front of Median. FLDetector uses the paper's own defaults (detect from +# iteration 50, window 10, 10 clusters, 20 gap samples), so only the defense differs +# between the last two runs. +# +# Compare `asr` against the paper's ASR column and `detection_fnr` against Table 2. +# +# Why non-IID matters here, measured rather than assumed. The attack clamps its poisoned +# model into mu +/- z*sigma, where sigma is how much honest clients disagree per weight. +# Clipping a trained backdoor into that band leaves almost nothing of it: a single clipped +# update scores 0.02 ASR on an MLP and 0.0000 on LeNet with IID data, where honest convnet +# clients agree to within 1e-5 per weight. The attack only works by accumulating that +# residue over many rounds. Dirichlet(0.5) widens LeNet's band about 40x, which takes one +# clipped round from 0.0000 to 0.1536 ASR -- so this is the setting where it has a chance. +# +# About an hour on CPU. +# +# fltest run examples/configs/little_is_enough.yaml +name: little_is_enough +device: cpu +dataset: mnist +model_name: LeNet +data_distribution: dirichlet +dirichlet_alpha: 0.5 +num_clients: 100 +num_rounds: 120 +client_lr: 0.05 +client_epochs: 1 +metrics: [accuracy, loss, detection] + +runs: + - framework: reference + name: no-attack + defenses: [{name: median}] + attacks: [] + + - framework: reference + name: alie-median + defenses: [{name: median}] + attacks: + - name: little_is_enough_cropped_backdoor + params: {z: 0.74, target_label: 0, patch_size: 5} + target_clients: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, + 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27] + + - framework: reference + name: alie-fldetector-median + defenses: + - {name: fldetector, params: {start_round: 50, window_size: 10, max_clusters: 10, gap_samples: 20}} + - {name: median} + attacks: + - name: little_is_enough_cropped_backdoor + params: {z: 0.74, target_label: 0, patch_size: 5} + target_clients: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, + 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27] diff --git a/fltest/attacks/__init__.py b/fltest/attacks/__init__.py index aef9ece..c932471 100644 --- a/fltest/attacks/__init__.py +++ b/fltest/attacks/__init__.py @@ -18,6 +18,9 @@ "dlg": "fltest.attacks.dlg", "membership_inference": "fltest.attacks.membership_inference", "model_replacement": "fltest.attacks.model_replacement", + "little_is_enough": "fltest.attacks.little_is_enough", + "little_is_enough_backdoor": "fltest.attacks.little_is_enough_backdoor", + "little_is_enough_cropped_backdoor": "fltest.attacks.little_is_enough_backdoor", } for _name, _module in BUILTIN_ATTACKS.items(): diff --git a/fltest/attacks/little_is_enough.py b/fltest/attacks/little_is_enough.py new file mode 100644 index 0000000..dd0ff18 --- /dev/null +++ b/fltest/attacks/little_is_enough.py @@ -0,0 +1,181 @@ +"""A Little Is Enough: a Byzantine attack sized to the honest population's own spread. + +Baruch, Baruch and Goldberg, *A Little Is Enough: Circumventing Defenses For Distributed +Learning* (NeurIPS 2019). + +``gaussian`` and ``sign_flip`` perturb an update without reference to what the honest +updates look like, so any perturbation large enough to matter is also an outlier — which is +exactly the signal ``krum``, ``median`` and ``trimmed_mean`` key on. This attack measures +the benign population first and moves only as far as that population's own variance allows, +per coordinate: + +``u' = mu - z * sigma`` + +With ``n`` participants and ``m`` attackers, ``s = floor(n/2 + 1) - m`` benign workers are +needed to complete a majority. A value ``z`` deviations out is covered by the +``(n - m) * (1 - Phi(z))`` honest workers lying further out still, so staying hidden needs +``(n - m) * (1 - Phi(z)) >= s``, i.e. ``Phi(z) <= (n - m - s) / (n - m)``; the default ``z`` +is the largest value satisfying it. The crafted update therefore still falls inside the range +a majority of honest workers occupy: a distance-based rule keeps accepting it while the +aggregate drifts a little every round. Set ``z`` explicitly to sweep attack strength. + +``sigma`` is the population standard deviation (NumPy's default). Reimplementations built on +``torch.std`` use the sample form, which is larger by ``sqrt(k / (k - 1))`` over ``k`` benign +clients, so the same ``z`` is a slightly wider step there than here. + +Threat model: the paper's *full-knowledge* attacker, which sees the round's benign updates. +The attack runs at ``before_aggregate``, where FLTest exposes every submission, and rewrites +only the attackers' entries. Attacks attach before defenses, so a robust aggregator in the +same config still sees the crafted updates. NVFlare does not emit ``before_aggregate`` and +cannot run this attack. +""" + +from __future__ import annotations + +from statistics import NormalDist +from typing import List, Optional, Set + +import numpy as np + +from fltest.attacks.base import ThreatModelBaseClass +from fltest.core.hook_context import ClientSubmission, HookContext +from fltest.core.registry import register_attack + + +@register_attack("little_is_enough") +class LittleIsEnoughAttack(ThreatModelBaseClass): + """Replace the attackers' updates with a perturbation of the benign mean.""" + + HOOKS = ("before_aggregate", "after_aggregate") + + def __init__(self, z: Optional[float] = None, **params): + super().__init__(**params) + if z is not None and z < 0: + raise ValueError("little_is_enough z must not be negative") + if not self.target_clients: + raise ValueError( + "little_is_enough needs target_clients: it crafts the attackers' updates " + "from the benign ones, so the adversarial clients must be named" + ) + self.z = z + self._asked = None # benign statistics of the round, for scoring the aggregate + + def _attacker_positions(self, ctx: HookContext, count: int) -> Set[int]: + """Positions in ``updates_and_weights`` held by the adversarial clients.""" + submissions = ctx.client_submissions + if submissions is not None and len(submissions) == count: + ids = [s.client_id for s in submissions] + if all(cid is not None for cid in ids): + return {pos for pos, cid in enumerate(ids) if self.targets(cid)} + # Backends that do not identify submissions keep FLTest's positional convention. + return {pos for pos in range(count) if self.targets(pos)} + + def _perturbation(self, num_participants: int, num_attackers: int) -> float: + if self.z is not None: + return float(self.z) + s = num_participants // 2 + 1 - num_attackers + benign = num_participants - num_attackers + ratio = (benign - s) / benign + # Below 0.5 no perturbation keeps the majority, and 1.0 would be unbounded. + return NormalDist().inv_cdf(min(max(ratio, 0.5), 1.0 - 1e-9)) + + @staticmethod + def _layer_statistics(uw, benign: List[int], num_layers: int): + """Per layer: a benign reference array, and the benign mean and deviation. + + Mean and deviation are None for a layer that is not floating point. Integer buffers + (BatchNorm's num_batches_tracked and friends) carry no gradient signal, and + perturbing one only truncates on the cast back. + """ + stats = [] + for layer in range(num_layers): + arrays = [np.asarray(uw[pos][0][layer]) for pos in benign] + reference = arrays[0] + if not np.issubdtype(reference.dtype, np.floating): + stats.append((reference, None, None)) + continue + stacked = np.stack([a.astype(np.float64) for a in arrays]) + stats.append((reference, stacked.mean(axis=0), stacked.std(axis=0))) + return stats + + def _craft(self, ctx: HookContext, stats, z: float) -> List[np.ndarray]: + """Algorithm 3: the benign mean moved ``z`` deviations, coordinate by coordinate.""" + return [ + reference.copy() if mean is None + else (mean - z * deviation).astype(reference.dtype, copy=False) + for reference, mean, deviation in stats + ] + + def _craft_each(self, ctx: HookContext, stats, z: float, attackers) -> dict: + """Each attacker's submission, by position. By default every attacker sends one craft.""" + crafted = self._craft(ctx, stats, z) + return {pos: crafted for pos in attackers} + + def before_aggregate(self, ctx: HookContext) -> None: + uw = ctx.updates_and_weights + if not uw or len(uw) < 2: + return + attackers = self._attacker_positions(ctx, len(uw)) + benign = [pos for pos in range(len(uw)) if pos not in attackers] + # A round may select no attacker, or leave no honest update to measure. + if not attackers or not benign: + return + + num_layers = len(uw[benign[0]][0]) + if any(len(uw[pos][0]) != num_layers for pos in range(len(uw))): + raise ValueError("little_is_enough requires updates of matching length") + + z = self._perturbation(len(uw), len(attackers)) + stats = self._layer_statistics(uw, benign, num_layers) + crafted = self._craft_each(ctx, stats, z, sorted(attackers)) + float_layers = [layer for layer, (_, mean, _) in enumerate(stats) if mean is not None] + self._asked = ( + (float_layers, + np.concatenate([stats[layer][1].ravel() for layer in float_layers]), + np.concatenate([stats[layer][2].ravel() for layer in float_layers]), z) + if float_layers else None + ) + + # The submission records describe what the server received, so they have to carry + # the crafted arrays too — a detection defense reads them, and FLDetector rejects a + # round whose records and aggregation inputs have drifted apart. + records = list(ctx.client_submissions or ()) + aligned = len(records) == len(uw) + for pos in attackers: + submitted = list(crafted[pos]) + uw[pos] = (submitted, uw[pos][1]) + if aligned: + records[pos] = ClientSubmission( + records[pos].client_id, tuple(submitted), records[pos].num_samples + ) + if aligned: + ctx.client_submissions = tuple(records) + ctx.record(little_is_enough_z=z) + + def after_aggregate(self, ctx: HookContext) -> None: + """Score the round: how far the aggregate actually moved, in benign sigmas. + + The attacker asked the aggregate to sit ``z`` standard deviations below the honest + mean. Reading back where it landed says what the defense conceded — near ``z`` means + the crafted update was absorbed, near 0 means it was filtered out. + """ + asked, self._asked = self._asked, None + if asked is None or ctx.new_global_state is None: + return + layers, mean, deviation, z = asked + if max(layers) >= len(ctx.new_global_state): + return + aggregate = np.concatenate( + [np.asarray(ctx.new_global_state[layer]).astype(np.float64).ravel() + for layer in layers] + ) + if aggregate.shape != mean.shape: + return + # Coordinates the honest clients all agree on carry no scale to measure against. + movable = deviation > 0 + if not movable.any(): + return + drift = float(np.mean((mean[movable] - aggregate[movable]) / deviation[movable])) + ctx.record(little_is_enough_drift=drift) + if z > 0: + ctx.record(little_is_enough_absorption=drift / z) diff --git a/fltest/attacks/little_is_enough_backdoor.py b/fltest/attacks/little_is_enough_backdoor.py new file mode 100644 index 0000000..0e90d3e --- /dev/null +++ b/fltest/attacks/little_is_enough_backdoor.py @@ -0,0 +1,288 @@ +"""A Little Is Enough, backdoor variant: a trigger planted inside the honest spread. + +Baruch, Baruch and Goldberg, *A Little Is Enough: Circumventing Defenses For Distributed +Learning* (NeurIPS 2019), Section 3.4 and Algorithm 4. The convergence attack in +``little_is_enough`` moves every parameter a fixed ``z`` deviations; this one spends the +same budget on a goal. Starting from the benign mean ``mu``, the attacker trains on images +stamped with a trigger and relabelled to ``target_label``, then clamps every parameter back +into ``mu +/- z * sigma``: + +``p_mal = max(mu - z * sigma, min(v, mu + z * sigma))`` + +so the crafted update stays inside the range a distance-based defense accepts, while the +parameters inside that range are chosen to carry the backdoor. Every attacker submits it. + +The defaults follow the paper's pattern experiment (Section 4.2): each round the attacker +samples ``samples`` of its own images, sets the upper-left ``patch_size`` x ``patch_size`` +pixels to maximal intensity, labels them ``target_label`` and trains for ``epochs`` passes. +The FLDetector paper (Zhang et al., KDD 2022) evaluates this attack with the same trigger +and target label 0. + +``alpha`` weights the paper's Equation 3, ``alpha * l_backdoor + (1 - alpha) * l_delta``, +where Equation 4's ``l_delta`` sums each parameter's squared distance from ``mu`` in units +of ``max(z * sigma, 1e-5)``. That term is stiff: its curvature is ``1 / (z * sigma)^2``, +and honest clients agree so closely that plain SGD on it diverges at any usable learning +rate, so it is minimised exactly with a proximal step after each gradient step. Summed +over every parameter it also outweighs the batch-mean backdoor loss so heavily that the +optimum barely leaves ``mu``, and the backdoor never forms. The default ``alpha = 1`` +therefore leaves "stay close to mu" to the clamp, which is exactly what the clamp is for; +set ``alpha < 1`` to reproduce Equation 3 as written. + +``attack_success_rate`` is recorded every round: the share of test images, their true +label not already ``target_label``, that the global model sends to ``target_label`` once +the trigger is stamped on. Threat model and backend support are those of +``little_is_enough``: a full-knowledge attacker acting at ``before_aggregate``, on the +reference and Flower backends. +""" + +from __future__ import annotations + +from typing import List, Optional + +import numpy as np +import torch +from torch.utils.data import DataLoader + +from fltest.attacks.little_is_enough import LittleIsEnoughAttack +from fltest.core.hook_context import HookContext +from fltest.core.registry import register_attack +from fltest.data.models import LOSS_FUNCTIONS, OPTIMIZERS, get_model +from fltest.data.utils import load_ndarrays_into, state_dict_to_ndarrays + + +def _stamp(images: torch.Tensor, size: int, value: float) -> torch.Tensor: + """Set the upper-left ``size`` x ``size`` pixels of each image to ``value``.""" + out = images.clone() + out[..., :size, :size] = value + return out + + +@register_attack("little_is_enough_backdoor") +class LittleIsEnoughBackdoorAttack(LittleIsEnoughAttack): + """Train a backdoor from the benign mean, then clamp it into ``mu +/- z * sigma``.""" + + HOOKS = ("on_data_distribute", "before_aggregate", "after_round") + + def __init__(self, z: Optional[float] = None, alpha: float = 1.0, epochs: int = 5, + samples: int = 1000, target_label: int = 0, patch_size: int = 5, + patch_value: float = 1.0, **params): + super().__init__(z=z, **params) + if not 0.0 < alpha <= 1.0: + raise ValueError("little_is_enough_backdoor alpha must be in (0, 1]") + if epochs < 1 or samples < 1 or patch_size < 1: + raise ValueError("little_is_enough_backdoor epochs, samples and patch_size must be positive") + self.alpha = float(alpha) + self.epochs = int(epochs) + self.samples = int(samples) + self.target_label = int(target_label) + self.patch_size = int(patch_size) + self.patch_value = float(patch_value) + self._pool = None # the attackers' own images, pooled + self._net = None # scratch model the backdoor is trained in, built once + + def on_data_distribute(self, ctx: HookContext) -> None: + """Pool the attackers' training images; the backdoor is trained on these.""" + images = [] + for cid, loader in sorted((ctx.dist_dict or {}).items()): + if not self.targets(cid): + continue + dataset = getattr(loader, "dataset", None) + # A sequential read draws nothing from the global RNG, so honest clients shuffle + # exactly as they would in a run without this attack. + batches = DataLoader(dataset, batch_size=512) if dataset is not None else loader + for batch in batches: + if "img" not in batch: + raise ValueError( + "little_is_enough_backdoor stamps a trigger onto pixels, so it needs " + "an image dataset. Use little_is_enough on text." + ) + images.append(torch.as_tensor(batch["img"])) + self._pool = torch.cat(images) if images else None + + def _network(self, spec): + if self._net is None: + # Building a model draws its initial weights from the global RNG. Fork it so the + # attacker's scratch model leaves the honest clients' randomness untouched. + with torch.random.fork_rng(devices=[]): + self._net = get_model( + spec.model_name, spec.model_cache_path, channels=spec.channels, + num_classes=spec.num_classes, deterministic=False, + ) + return self._net.to(spec.device) + + def _craft(self, ctx: HookContext, stats, z: float) -> List[np.ndarray]: + """Algorithm 4: train from the benign mean on the backdoor, then clamp.""" + if self._pool is None: + raise ValueError( + "little_is_enough_backdoor has no attacker images to train on. It reads them at " + "on_data_distribute, which the reference and Flower backends emit." + ) + spec, device = ctx.cfg, ctx.cfg.device + net = self._network(spec) + start = [reference if mean is None else mean for reference, mean, _ in stats] + load_ndarrays_into(net, start) + + position = {name: i for i, name in enumerate(net.state_dict())} + anchors = [] + if self.alpha < 1.0: + for name, param in net.named_parameters(): + _, mean, deviation = stats[position[name]] + anchors.append(( + param, + torch.as_tensor(mean, dtype=param.dtype, device=device), + torch.as_tensor(np.maximum(z * deviation, 1e-5), dtype=param.dtype, device=device), + )) + + generator = torch.Generator().manual_seed(int(spec.seed) + int(ctx.round or 0)) + pick = torch.randperm(len(self._pool), generator=generator)[: self.samples] + images = _stamp(self._pool[pick], self.patch_size, self.patch_value) + labels = torch.full((len(pick),), self.target_label, dtype=torch.long) + + lr = spec.client_lr + optimizer = OPTIMIZERS[spec.optimizer](net.parameters(), lr=lr) + criterion = LOSS_FUNCTIONS[spec.loss_fn]() + net.train() + for _ in range(self.epochs): + order = torch.randperm(len(labels), generator=generator) + for first in range(0, len(order), spec.client_batch_size): + batch = order[first:first + spec.client_batch_size] + optimizer.zero_grad() + loss = self.alpha * criterion(net(images[batch].to(device)), labels[batch].to(device)) + loss.backward() + optimizer.step() + with torch.no_grad(): + # Proximal step for (1 - alpha) * l_delta: its exact minimiser from here, + # which stays stable however small z * sigma is. + for param, anchor, scale in anchors: + c = 2.0 * lr * (1.0 - self.alpha) / scale ** 2 + param.copy_((param + c * anchor) / (1.0 + c)) + + return LittleIsEnoughCroppedBackdoorAttack._crop( + state_dict_to_ndarrays(net.state_dict()), stats, z) + + @torch.no_grad() + def after_round(self, ctx: HookContext) -> None: + self._score_backdoor(ctx) + + def _score_backdoor(self, ctx: HookContext) -> None: + if ctx.global_state is None or ctx.test_data is None or ctx.cfg is None: + return + spec = ctx.cfg + model = ctx.model + if model is None: + model = self._network(spec) + load_ndarrays_into(model, ctx.global_state) + model.eval() + hit, total = 0, 0 + for batch in ctx.test_data: + if "img" not in batch: + return + labels = batch["label"].to(spec.device) + keep = labels != self.target_label + if not keep.any(): + continue + images = _stamp(batch["img"].to(spec.device)[keep], self.patch_size, self.patch_value) + hit += int((model(images).argmax(dim=1) == self.target_label).sum().item()) + total += int(keep.sum().item()) + if total: + ctx.record(attack_success_rate=hit / total) + + +@register_attack("little_is_enough_cropped_backdoor") +class LittleIsEnoughCroppedBackdoorAttack(LittleIsEnoughBackdoorAttack): + """Each attacker trains its own Scaling-attack backdoor, then crops it into range. + + The FLDetector paper (Zhang et al., KDD 2022) evaluates "A Little Is Enough" this way: + the malicious updates "are first computed following the Scaling Attack", and then "the + attacker crops the model updates to be in certain ranges". Here that is, per attacker + and per round: start from the global model, train on the attacker's own images plus a + trigger-stamped duplicate of each, labelled ``target_label`` (the Scaling attack's + augmentation, with the paper's scaling factor of 1), then clamp every parameter into + the honest ``mu +/- z * sigma``. + + ``little_is_enough_backdoor`` follows Algorithm 4 of the ALIE paper instead: one update, + trained from the honest mean ``mu`` and shared by every attacker. The two differ in + what the malicious update is anchored to, which is what a consistency detector such as + FLDetector reads. Local training uses the run's own ``client_epochs``, ``client_lr``, + ``client_batch_size`` and ``optimizer``, as an honest client's does. + """ + + def __init__(self, z: Optional[float] = None, target_label: int = 0, patch_size: int = 5, + patch_value: float = 1.0, **params): + super().__init__(z=z, target_label=target_label, patch_size=patch_size, + patch_value=patch_value, **params) + self._shards = {} # attacker client id -> (images, labels) + + def on_data_distribute(self, ctx: HookContext) -> None: + """Keep each attacker's own images and labels; every attacker trains on its own.""" + self._shards = {} + for cid, loader in sorted((ctx.dist_dict or {}).items()): + if not self.targets(cid): + continue + dataset = getattr(loader, "dataset", None) + batches = DataLoader(dataset, batch_size=512) if dataset is not None else loader + images, labels = [], [] + for batch in batches: + if "img" not in batch: + raise ValueError( + "little_is_enough_cropped_backdoor stamps a trigger onto pixels, so it " + "needs an image dataset. Use little_is_enough on text." + ) + images.append(torch.as_tensor(batch["img"])) + labels.append(torch.as_tensor(batch["label"])) + if images: + self._shards[cid] = (torch.cat(images), torch.cat(labels)) + + def _craft_each(self, ctx: HookContext, stats, z: float, attackers) -> dict: + if ctx.global_state is None: + raise ValueError("little_is_enough_cropped_backdoor needs the round's global model") + records = ctx.client_submissions + aligned = records is not None and len(records) == len(ctx.updates_and_weights) + crafted = {} + for pos in attackers: + cid = records[pos].client_id if aligned and records[pos].client_id is not None else pos + if cid not in self._shards: + raise ValueError( + f"little_is_enough_cropped_backdoor has no training data for attacker {cid}. " + "It reads it at on_data_distribute, which the reference and Flower backends emit." + ) + crafted[pos] = self._crop(self._poisoned_training(ctx, cid), stats, z) + return crafted + + def _poisoned_training(self, ctx: HookContext, cid: int) -> List[np.ndarray]: + """The Scaling attack's local update: own data plus stamped duplicates, from the global model.""" + spec, device = ctx.cfg, ctx.cfg.device + net = self._network(spec) + load_ndarrays_into(net, ctx.global_state) + images, labels = self._shards[cid] + images = torch.cat([images, _stamp(images, self.patch_size, self.patch_value)]) + labels = torch.cat([labels, torch.full_like(labels, self.target_label)]) + + generator = torch.Generator().manual_seed( + int(spec.seed) * 100_003 + int(ctx.round or 0) * 1_009 + int(cid)) + optimizer = OPTIMIZERS[spec.optimizer](net.parameters(), lr=spec.client_lr) + criterion = LOSS_FUNCTIONS[spec.loss_fn]() + net.train() + for _ in range(spec.client_epochs): + order = torch.randperm(len(labels), generator=generator) + for first in range(0, len(order), spec.client_batch_size): + batch = order[first:first + spec.client_batch_size] + optimizer.zero_grad() + criterion(net(images[batch].to(device)), labels[batch].to(device)).backward() + optimizer.step() + return state_dict_to_ndarrays(net.state_dict()) + + @staticmethod + def _crop(trained: List[np.ndarray], stats, z: float) -> List[np.ndarray]: + """Clamp each floating-point layer into the honest ``mu +/- z * sigma``.""" + cropped = [] + for (reference, mean, deviation), value in zip(stats, trained): + if mean is None: + cropped.append(reference.copy()) + continue + bound = z * deviation + cropped.append( + np.clip(value.astype(np.float64), mean - bound, mean + bound) + .astype(reference.dtype, copy=False) + ) + return cropped diff --git a/fltest/core/config.py b/fltest/core/config.py index 18b15ae..e65112c 100644 --- a/fltest/core/config.py +++ b/fltest/core/config.py @@ -94,6 +94,7 @@ class TestingSpec(BaseModel): "dirichlet_alpha", "classes_per_partition", "optimizer", + "partition_seed", ) @@ -106,6 +107,12 @@ class RunSpec(BaseModel): # reproducibility / hardware seed: int = 786 + #: Draw for the random partitioners (dirichlet, pathological), separate from ``seed`` + #: so that repeating a run under new training noise and repeating it on a new client + #: split are different questions. Holding one fixed while varying the other is the + #: only way to tell a result that depends on the data split from one that does not. + #: Defaults to the partitioners' own 42, so existing results stay reproducible. + partition_seed: int = 42 device: str = "cpu" deterministic: bool = True total_cpus: int = 4 @@ -163,9 +170,10 @@ def tokenizer_id(self) -> str: def partitioner_kwargs(self) -> Dict[str, Any]: if self.data_distribution == "dirichlet": - return {"alpha": self.dirichlet_alpha} + return {"alpha": self.dirichlet_alpha, "seed": self.partition_seed} if self.data_distribution == "pathological": - return {"classes_per_partition": self.classes_per_partition} + return {"classes_per_partition": self.classes_per_partition, + "seed": self.partition_seed} return {} def aggregation(self) -> str: @@ -203,6 +211,7 @@ def summary(self) -> Dict[str, Any]: "client_batch_size": self.client_batch_size, "optimizer": self.optimizer, "seed": self.seed, + "partition_seed": self.partition_seed, "attacks": [ {"name": a.name, "params": a.params, "target_clients": a.target_clients} for a in self.attacks @@ -219,6 +228,7 @@ class TestConfig(BaseModel): name: str = "fltest_run" seed: int = 786 + partition_seed: ScalarOrList = 42 device: str = "cpu" deterministic: bool = True total_cpus: int = 4 diff --git a/fltest/data/datasets.py b/fltest/data/datasets.py index 2589371..ba928e5 100644 --- a/fltest/data/datasets.py +++ b/fltest/data/datasets.py @@ -26,7 +26,7 @@ NaturalIdPartitioner, PathologicalPartitioner, ) -from torch.utils.data import DataLoader +from torch.utils.data import DataLoader, Dataset from torchvision import transforms from fltest.data.utils import seed_everything @@ -96,13 +96,13 @@ class DatasetSpec: # A lower Dirichlet alpha means more label skew across clients. PARTITIONERS = { "iid": lambda n, label_column="label", **kw: IidPartitioner(num_partitions=n), - "dirichlet": lambda n, label_column="label", alpha=0.5, **kw: DirichletPartitioner( - num_partitions=n, partition_by=label_column, alpha=alpha + "dirichlet": lambda n, label_column="label", alpha=0.5, seed=42, **kw: DirichletPartitioner( + num_partitions=n, partition_by=label_column, alpha=alpha, seed=seed ), - "pathological": lambda n, label_column="label", classes_per_partition=2, **kw: ( + "pathological": lambda n, label_column="label", classes_per_partition=2, seed=42, **kw: ( PathologicalPartitioner( num_partitions=n, partition_by=label_column, - num_classes_per_partition=classes_per_partition, + num_classes_per_partition=classes_per_partition, seed=seed, ) ), "natural": lambda n, label_column="label", partition_by="", **kw: NaturalIdPartitioner( @@ -283,6 +283,42 @@ def get_cached_federated_dataset( return cache[key] +class _InMemoryShard(Dataset): + """A prepared split's columns, converted to tensors once. + + ``prepare`` stores transformed images as nested lists, and the torch format rebuilds + them element by element on every read. Across a run that is most of the wall-clock + time, and a GPU cannot help with it. The conversion here goes through the same torch + formatter, just once for the whole split, so every column comes out with the dtype and + shape a batch read gives, and batches, shuffling and results are unchanged. + """ + + def __init__(self, columns: Dict[str, torch.Tensor]): + self.columns = columns + self._length = len(next(iter(columns.values()))) + + @classmethod + def from_split(cls, split): + """The split in memory, or None when a column is ragged and cannot be stacked.""" + if len(split) == 0: + return None + columns = split.with_format("torch")[:] + if not columns or not all(isinstance(v, torch.Tensor) for v in columns.values()): + return None + return cls(dict(columns)) + + def __len__(self): + return self._length + + def __getitem__(self, index): + return {name: column[index] for name, column in self.columns.items()} + + +def _in_memory(split): + """Serve ``split`` from memory when it stacks into tensors, else read it as before.""" + return _InMemoryShard.from_split(split) or split + + def build_dataloaders( dataset_dict: Dict, num_clients: int, @@ -303,7 +339,7 @@ def worker_init_fn(worker_id): c2loader = { cid: DataLoader( - dataset_dict["c2data"][cid], + _in_memory(dataset_dict["c2data"][cid]), batch_size=client_batch_size, shuffle=True, num_workers=0, @@ -314,7 +350,7 @@ def worker_init_fn(worker_id): test_split = dataset_dict["test_data"] n_test = min(max_test_size, len(test_split)) test_loader = DataLoader( - test_split.select(range(n_test)), + _in_memory(test_split.select(range(n_test))), batch_size=server_batch_size, shuffle=False, num_workers=0, diff --git a/fltest/metrics/detection.py b/fltest/metrics/detection.py index 16758c6..7ef1493 100644 --- a/fltest/metrics/detection.py +++ b/fltest/metrics/detection.py @@ -24,6 +24,7 @@ #: from this set is server-side, and its targets are victims rather than adversaries. MALICIOUS_CLIENT_ATTACKS = { "backdoor", "label_flip", "sign_flip", "gaussian", "model_replacement", + "little_is_enough", "little_is_enough_backdoor", "little_is_enough_cropped_backdoor", } #: Metrics a detector records to announce what it flagged. @@ -79,12 +80,20 @@ def after_simulation(self, ctx: HookContext) -> None: precision = hits / len(flagged) if flagged else 0.0 recall = hits / len(truth) if truth else 0.0 f1 = (2 * precision * recall / (precision + recall)) if (precision + recall) else 0.0 + false_positives, missed = len(flagged - truth), len(truth - flagged) + # The FLDetector paper's own three, over every client in the federation: an + # unflagged client counts as classified benign. + clients = max(int(ctx.cfg.num_clients), len(truth | flagged)) + honest = clients - len(truth) ctx.record( detection_precision=precision, detection_recall=recall, detection_f1=f1, - detection_false_positives=float(len(flagged - truth)), - detection_missed=float(len(truth - flagged)), + detection_false_positives=float(false_positives), + detection_missed=float(missed), + detection_accuracy=(clients - false_positives - missed) / clients, + detection_fpr=false_positives / honest if honest else 0.0, + detection_fnr=missed / len(truth) if truth else 0.0, ) ctx.extras["detection"] = { "malicious_clients": sorted(truth), diff --git a/fltest/testing/report.py b/fltest/testing/report.py index a325f50..7faadee 100644 --- a/fltest/testing/report.py +++ b/fltest/testing/report.py @@ -133,6 +133,9 @@ def print_outcomes(title: str, outcomes: List[TestOutcome]) -> bool: "detection_f1": "det-f1", "detection_false_positives": "det-fp", "detection_missed": "det-miss", + "detection_accuracy": "dacc", + "detection_fpr": "fpr", + "detection_fnr": "fnr", } #: What each shortened column means, printed under the table for the metrics in play. A @@ -165,6 +168,9 @@ def print_outcomes(title: str, outcomes: List[TestOutcome]) -> bool: "detection_f1": "harmonic mean of detection precision and recall", "detection_false_positives": "honest clients the defense wrongly flagged", "detection_missed": "malicious clients the defense never flagged", + "detection_accuracy": "FLDetector paper's DACC, the share of all clients classified correctly as benign or malicious", + "detection_fpr": "share of honest clients flagged as malicious", + "detection_fnr": "share of malicious clients left unflagged", } #: Width the fixed-settings block wraps at, independent of how wide the table is. diff --git a/tests/test_attacks_defenses.py b/tests/test_attacks_defenses.py index 3869bf7..f2e6fc1 100644 --- a/tests/test_attacks_defenses.py +++ b/tests/test_attacks_defenses.py @@ -1,6 +1,7 @@ """Unit tests for attacks/defenses operating on the canonical ndarray update.""" import numpy as np +import pytest import torch from fltest.core.hook_context import HookContext @@ -109,6 +110,353 @@ def test_model_replacement_reaches_target_under_equal_weight_fedavg(): assert np.allclose(aggregated[0], target[0]) +# --- little is enough ------------------------------------------------------------------ + +def _lie_round(values, attackers, num_clients=None, **kw): + """Run the attack over one scalar-layer submission per client.""" + from fltest.attacks.little_is_enough import LittleIsEnoughAttack + + uw = [([np.full((2,), v, dtype=np.float32)], 10) for v in values] + ctx = HookContext( + cfg=_spec(num_clients=num_clients or len(values)), round=1, updates_and_weights=uw, + ) + LittleIsEnoughAttack(target_clients=attackers, **kw).before_aggregate(ctx) + return ctx + + +def test_little_is_enough_z_is_the_largest_step_that_stays_covered(): + """The property z is defined by: enough honest workers must lie further out than the craft. + + Checked against the criterion itself rather than against a remembered constant, so the + test still means something if the derivation is ever revisited. + """ + from statistics import NormalDist + + n, m = 50, 24 + s = n // 2 + 1 - m # honest workers needed to complete a majority alongside the attackers + z = _lie_round([1.0] * n, attackers=list(range(m))).metrics["little_is_enough_z"] + + def honest_further_out(step): + return (n - m) * (1 - NormalDist().cdf(step)) + + assert honest_further_out(z) >= s - 1e-9 # this step is still covered + assert honest_further_out(z + 0.01) < s # any larger step is not + assert z == pytest.approx(1.426, abs=0.001) # regression guard on the value itself + + +def test_little_is_enough_crafts_the_benign_mean_shifted_by_z_sigma(): + # Benign 1, 2, 3; the attackers' own 9.0 must not enter the statistics. + ctx = _lie_round([1.0, 2.0, 3.0, 9.0, 9.0], attackers=[3, 4], z=1.5) + + expected = 2.0 - 1.5 * float(np.std([1.0, 2.0, 3.0])) + for pos in (3, 4): + update, num_samples = ctx.updates_and_weights[pos] + assert np.allclose(update[0], expected) + assert update[0].dtype == np.float32 + assert num_samples == 10 # sample weight survives, only the update is replaced + for pos, benign in enumerate([1.0, 2.0, 3.0]): + assert np.allclose(ctx.updates_and_weights[pos][0][0], benign) + assert ctx.metrics["little_is_enough_z"] == 1.5 + + +def test_little_is_enough_survives_krum_where_a_naive_outlier_does_not(): + """The point of the attack: stay inside the honest spread, so the filter keeps it.""" + from fltest.attacks.little_is_enough import LittleIsEnoughAttack + from fltest.defenses.krum import KrumDefense + + rng = np.random.default_rng(0) + num_clients, num_attackers, dim = 10, 4, 50 + honest = [ + [(np.ones(dim) + rng.normal(0, 0.1, dim)).astype(np.float32)] + for _ in range(num_clients) + ] + attackers = list(range(num_clients - num_attackers, num_clients)) + + crafted_round = HookContext( + cfg=_spec(num_clients=num_clients), round=1, + updates_and_weights=[(u, 1) for u in honest], + ) + LittleIsEnoughAttack(target_clients=attackers).before_aggregate(crafted_round) + crafted = crafted_round.updates_and_weights[attackers[0]][0][0] + + KrumDefense(num_byzantine=num_attackers).before_aggregate(crafted_round) + assert np.allclose(crafted_round.updates_and_weights[0][0][0], crafted) + + # Same clients, same defense, but perturbed without regard for the honest spread. + naive = [(list(u), 1) for u in honest] + for pos in attackers: + naive[pos] = ([(honest[pos][0] + rng.normal(0, 5.0, dim)).astype(np.float32)], 1) + naive_round = HookContext( + cfg=_spec(num_clients=num_clients), round=1, updates_and_weights=naive, + ) + KrumDefense(num_byzantine=num_attackers).before_aggregate(naive_round) + selected = naive_round.updates_and_weights[0][0][0] + assert not any(np.allclose(selected, naive[pos][0][0]) for pos in attackers) + + +def test_little_is_enough_identifies_attackers_by_client_id(): + """Client selection makes position and identity diverge; identity must win.""" + from fltest.attacks.little_is_enough import LittleIsEnoughAttack + from fltest.core.hook_context import ClientSubmission + + updates = [[np.full((2,), v, dtype=np.float32)] for v in (1.0, 2.0, 3.0)] + selected = (5, 7, 9) # round selected clients 5, 7 and 9, in that order + ctx = HookContext( + cfg=_spec(num_clients=10), round=1, + updates_and_weights=[(u, 10) for u in updates], + client_submissions=tuple( + ClientSubmission(cid, tuple(u), 10) for cid, u in zip(selected, updates) + ), + ) + LittleIsEnoughAttack(target_clients=[7], z=0.0).before_aggregate(ctx) + + # Client 7 sits at position 1; with z=0 it submits the mean of clients 5 and 9. + assert np.allclose(ctx.updates_and_weights[1][0][0], 2.0) + assert np.allclose(ctx.updates_and_weights[0][0][0], 1.0) + assert np.allclose(ctx.updates_and_weights[2][0][0], 3.0) + + +def _lie_scored_round(defense, z, num_clients=10, num_attackers=4, dim=400): + """Craft, aggregate as the backend would, then let the attack score the outcome.""" + from fltest.attacks.little_is_enough import LittleIsEnoughAttack + from fltest.data.utils import aggregate_ndarrays + + rng = np.random.default_rng(0) + honest = [ + [(np.ones(dim) + rng.normal(0, 0.1, dim)).astype(np.float32)] + for _ in range(num_clients) + ] + attackers = list(range(num_clients - num_attackers, num_clients)) + ctx = HookContext( + cfg=_spec(num_clients=num_clients), round=1, + updates_and_weights=[(list(u), 1) for u in honest], + ) + attack = LittleIsEnoughAttack(target_clients=attackers, z=z) + attack.before_aggregate(ctx) + if defense is not None: + defense.before_aggregate(ctx) + ctx.new_global_state = aggregate_ndarrays(ctx.updates_and_weights) + attack.after_aggregate(ctx) + return ctx + + +def test_little_is_enough_absorption_under_plain_fedavg_is_the_attacker_fraction(): + """Averaging concedes exactly m/n of the requested shift, which anchors the metric.""" + ctx = _lie_scored_round(defense=None, z=1.5) + assert ctx.metrics["little_is_enough_absorption"] == pytest.approx(0.4, abs=0.01) + assert ctx.metrics["little_is_enough_drift"] == pytest.approx(0.6, abs=0.02) + + +def test_little_is_enough_absorption_reads_out_whether_krum_took_the_craft(): + from fltest.defenses.krum import KrumDefense + + taken = _lie_scored_round(defense=KrumDefense(num_byzantine=4), z=1.5) + # Krum returns a single selected update, so absorption is all or nothing. + assert taken.metrics["little_is_enough_absorption"] == pytest.approx(1.0, abs=0.01) + + filtered = _lie_scored_round(defense=KrumDefense(num_byzantine=4), z=3.0) + assert filtered.metrics["little_is_enough_absorption"] == pytest.approx(0.0, abs=0.01) + + +def test_little_is_enough_scores_nothing_when_no_attacker_participates(): + from fltest.attacks.little_is_enough import LittleIsEnoughAttack + + ctx = _lie_round([1.0, 2.0, 3.0], attackers=[7], num_clients=10) + ctx.new_global_state = [np.full((2,), 2.0, dtype=np.float32)] + LittleIsEnoughAttack(target_clients=[7]).after_aggregate(ctx) + assert "little_is_enough_drift" not in ctx.metrics + + +def test_little_is_enough_keeps_submission_records_aligned(): + """FLDetector reads the records and rejects a round that has drifted from them.""" + from fltest.attacks.little_is_enough import LittleIsEnoughAttack + from fltest.core.hook_context import ClientSubmission + + updates = [[np.full((2,), v, dtype=np.float32)] for v in (1.0, 2.0, 3.0)] + ctx = HookContext( + cfg=_spec(num_clients=3), round=1, + updates_and_weights=[(u, 10) for u in updates], + client_submissions=tuple( + ClientSubmission(cid, tuple(u), 10) for cid, u in enumerate(updates) + ), + ) + LittleIsEnoughAttack(target_clients=[2], z=1.0).before_aggregate(ctx) + + for record, (update, _) in zip(ctx.client_submissions, ctx.updates_and_weights): + assert len(record.update) == len(update) + assert all(a is b for a, b in zip(record.update, update)) + assert [r.client_id for r in ctx.client_submissions] == [0, 1, 2] + assert not np.allclose(ctx.client_submissions[2].update[0], 3.0) # record shows the craft + + +def test_little_is_enough_is_quiet_when_no_attacker_participates(): + ctx = _lie_round([1.0, 2.0, 3.0], attackers=[7], num_clients=10) + for pos, benign in enumerate([1.0, 2.0, 3.0]): + assert np.allclose(ctx.updates_and_weights[pos][0][0], benign) + assert "little_is_enough_z" not in ctx.metrics + + +def test_little_is_enough_leaves_integer_buffers_intact(): + from fltest.attacks.little_is_enough import LittleIsEnoughAttack + + updates, weights = _updates_with_an_integer_buffer(num_clients=3) + ctx = HookContext(cfg=_spec(num_clients=3), round=1, + updates_and_weights=list(zip(updates, weights))) + LittleIsEnoughAttack(target_clients=[2], z=1.0).before_aggregate(ctx) + + crafted = ctx.updates_and_weights[2][0] + assert crafted[1] == 7 and crafted[1].dtype == np.int64 + assert crafted[0].dtype == np.float32 + + +def test_little_is_enough_requires_named_attackers(): + from fltest.attacks.little_is_enough import LittleIsEnoughAttack + + with pytest.raises(ValueError, match="target_clients"): + LittleIsEnoughAttack() + + +# --- little is enough, backdoor variant ------------------------------------------------ + +def _lie_backdoor(z, alpha=1.0, sigma=0.01, attackers=(3, 4), num_clients=5, cropped=False, + **kw): + """Honest MLP updates spread by ``sigma``, and an attack that has seen its own data.""" + from fltest.attacks.little_is_enough_backdoor import ( + LittleIsEnoughBackdoorAttack, + LittleIsEnoughCroppedBackdoorAttack, + ) + from fltest.data.models import get_model + from fltest.data.utils import state_dict_to_ndarrays + + torch.manual_seed(0) + base = state_dict_to_ndarrays(get_model("MLP", "", channels=1, deterministic=False).state_dict()) + rng = np.random.default_rng(0) + uw = [([(w + rng.normal(0, sigma, w.shape)).astype(np.float32) for w in base], 10) + for _ in range(num_clients)] + loaders = {cid: [{"img": torch.randn(32, 1, 32, 32), "label": torch.randint(0, 10, (32,))}] + for cid in range(num_clients)} + spec = _spec(model_name="MLP", channels=1, client_lr=0.05, client_batch_size=32, + optimizer="SGD", seed=1) + if cropped: + attack = LittleIsEnoughCroppedBackdoorAttack(target_clients=list(attackers), z=z, **kw) + else: + attack = LittleIsEnoughBackdoorAttack( + target_clients=list(attackers), z=z, alpha=alpha, samples=64, **kw) + attack.on_data_distribute(HookContext(cfg=spec, dist_dict=loaders)) + ctx = HookContext(cfg=spec, round=1, updates_and_weights=[(list(u), n) for u, n in uw], + global_state=base) + attack.before_aggregate(ctx) + return ctx, uw, spec + + +def test_little_is_enough_backdoor_stays_inside_the_honest_spread(): + ctx, uw, _ = _lie_backdoor(z=0.5) + honest = [uw[pos][0] for pos in (0, 1, 2)] + crafted = ctx.updates_and_weights[3][0] + moved = False + for layer, value in enumerate(crafted): + stacked = np.stack([h[layer].astype(np.float64) for h in honest]) + mean, bound = stacked.mean(axis=0), 0.5 * stacked.std(axis=0) + assert np.all(value >= mean - bound - 1e-6) and np.all(value <= mean + bound + 1e-6) + moved |= not np.allclose(value, mean, atol=1e-6) + assert np.array_equal(value, ctx.updates_and_weights[4][0][layer]) # every attacker alike + assert moved # the clamp bounds the craft, it does not erase it + for pos in (0, 1, 2): + assert all(np.array_equal(a, b) for a, b in zip(ctx.updates_and_weights[pos][0], uw[pos][0])) + + +def test_little_is_enough_backdoor_crafts_a_working_trigger(): + """With the clamp opened wide, what was trained is what is sent: a model with the trigger.""" + from fltest.attacks.little_is_enough_backdoor import _stamp + from fltest.data.models import get_model + from fltest.data.utils import load_ndarrays_into + + ctx, _, _ = _lie_backdoor(z=1e6, target_label=3) + model = get_model("MLP", "", channels=1, deterministic=False) + load_ndarrays_into(model, ctx.updates_and_weights[3][0]) + with torch.no_grad(): + predictions = model(_stamp(torch.randn(64, 1, 32, 32), 5, 1.0)).argmax(dim=1) + assert (predictions == 3).float().mean() > 0.9 + + +def test_cropped_backdoor_gives_each_attacker_its_own_update_inside_the_spread(): + """The FLDetector paper's variant: per-attacker poisoned training, then a crop.""" + ctx, uw, _ = _lie_backdoor(z=0.5, cropped=True) + honest = [uw[pos][0] for pos in (0, 1, 2)] + first, second = ctx.updates_and_weights[3][0], ctx.updates_and_weights[4][0] + assert not all(np.array_equal(a, b) for a, b in zip(first, second)) + for crafted in (first, second): + for layer, value in enumerate(crafted): + stacked = np.stack([h[layer].astype(np.float64) for h in honest]) + mean, bound = stacked.mean(axis=0), 0.5 * stacked.std(axis=0) + assert np.all(value >= mean - bound - 1e-6) and np.all(value <= mean + bound + 1e-6) + for pos in (0, 1, 2): + assert all(np.array_equal(a, b) for a, b in zip(ctx.updates_and_weights[pos][0], uw[pos][0])) + + +def test_cropped_backdoor_trains_the_trigger_into_each_attackers_model(): + from fltest.attacks.little_is_enough_backdoor import _stamp + from fltest.data.models import get_model + from fltest.data.utils import load_ndarrays_into + + ctx, _, spec = _lie_backdoor(z=1e6, cropped=True, target_label=3) + for pos in (3, 4): + model = get_model("MLP", "", channels=1, deterministic=False) + load_ndarrays_into(model, ctx.updates_and_weights[pos][0]) + with torch.no_grad(): + predictions = model(_stamp(torch.randn(64, 1, 32, 32), 5, 1.0)).argmax(dim=1) + assert (predictions == 3).float().mean() > 0.9 + + +def test_little_is_enough_backdoor_penalty_stays_finite_when_honest_clients_agree(): + """Equation 4 divides by z * sigma; a near-zero spread must not blow up the training.""" + ctx, _, _ = _lie_backdoor(z=0.2, alpha=0.2, sigma=1e-7) + assert all(np.isfinite(layer).all() for layer in ctx.updates_and_weights[3][0]) + + +def test_little_is_enough_backdoor_leaves_the_global_rng_alone(): + """Honest clients must shuffle as they would without the attacker in the run.""" + from fltest.attacks.little_is_enough_backdoor import LittleIsEnoughBackdoorAttack + + rng = np.random.default_rng(0) + shapes = [(128, 1024), (128,), (10, 128), (10,)] # the MLP's layers, built without torch + uw = [([rng.normal(0, 0.1, s).astype(np.float32) for s in shapes], 10) for _ in range(4)] + loaders = {3: [{"img": torch.zeros(8, 1, 32, 32), "label": torch.zeros(8, dtype=torch.long)}]} + spec = _spec(model_name="MLP", channels=1, client_lr=0.05, client_batch_size=4, + optimizer="SGD", seed=1) + + torch.manual_seed(5) + expected = torch.rand(3) + torch.manual_seed(5) + attack = LittleIsEnoughBackdoorAttack(target_clients=[3], z=0.5, samples=8, epochs=1) + attack.on_data_distribute(HookContext(cfg=spec, dist_dict=loaders)) + attack.before_aggregate(HookContext(cfg=spec, round=1, updates_and_weights=uw)) + assert torch.equal(torch.rand(3), expected) + + +def test_little_is_enough_backdoor_scores_attack_success_rate(): + from fltest.attacks.little_is_enough_backdoor import LittleIsEnoughBackdoorAttack + + class AlwaysTarget(torch.nn.Module): + def forward(self, x): + return torch.nn.functional.one_hot(torch.full((len(x),), 2), 10).float() + + test_data = [{"img": torch.zeros(4, 1, 32, 32), "label": torch.tensor([2, 0, 1, 3])}] + ctx = HookContext(cfg=_spec(), round=1, global_state=[np.zeros(1)], model=AlwaysTarget(), + test_data=test_data) + LittleIsEnoughBackdoorAttack(target_clients=[0], target_label=2).after_round(ctx) + assert ctx.metrics["attack_success_rate"] == 1.0 # the sample already labelled 2 is excluded + + +def test_little_is_enough_backdoor_needs_images(): + from fltest.attacks.little_is_enough_backdoor import LittleIsEnoughBackdoorAttack + + text = {0: [{"input_ids": torch.zeros(2, 4, dtype=torch.long), "label": torch.zeros(2)}]} + with pytest.raises(ValueError, match="image dataset"): + LittleIsEnoughBackdoorAttack(target_clients=[0]).on_data_distribute( + HookContext(cfg=_spec(), dist_dict=text)) + + def test_gradient_noise_clips_delta_norm(): from fltest.defenses.gradient_noise import GradientNoiseDefense diff --git a/tests/test_datasets_and_models.py b/tests/test_datasets_and_models.py index 5c27e75..e74b794 100644 --- a/tests/test_datasets_and_models.py +++ b/tests/test_datasets_and_models.py @@ -5,6 +5,7 @@ from fltest.data.datasets import ( DATASET_CONFIG, + build_dataloaders, dataset_meta, get_federated_dataset, list_partitioners, @@ -82,3 +83,44 @@ def test_every_dataset_id_is_namespaced(): def test_a_bare_unknown_dataset_says_what_is_wrong(): with pytest.raises(ValueError, match="must be written as 'namespace/name'"): resolve_dataset("not_a_builtin") + + +def _prepared_split(n, width=4): + """A split shaped like ``prepare``'s output: nested-list images and int labels.""" + from datasets import Dataset + + images = torch.arange(n * width * width, dtype=torch.float32).reshape(n, 1, width, width) + return Dataset.from_dict( + {"img": images.tolist(), "label": [i % 3 for i in range(n)]} + ).with_format("torch") + + +def test_client_loaders_serve_the_same_batches_from_memory(): + from torch.utils.data import DataLoader + + from fltest.data.utils import seed_everything + + shards = {cid: _prepared_split(10 + cid) for cid in range(2)} + loaders = build_dataloaders( + {"c2data": shards, "test_data": _prepared_split(7)}, 2, 4, 3, 5, seed=1) + for cid, shard in shards.items(): + seed_everything(1) + expected = [b for _ in range(2) for b in DataLoader(shard, batch_size=4, shuffle=True)] + seed_everything(1) + served = [b for _ in range(2) for b in loaders["c2loader"][cid]] + assert len(served) == len(expected) + for got, want in zip(served, expected): + assert got.keys() == want.keys() + for key in want: + assert got[key].dtype == want[key].dtype + assert torch.equal(got[key], want[key]) + assert sum(len(b["label"]) for b in loaders["test_loader"]) == 5 + + +def test_a_ragged_split_is_read_as_before(): + from datasets import Dataset + + from fltest.data.datasets import _in_memory + + ragged = Dataset.from_dict({"img": [[1.0], [1.0, 2.0]], "label": [0, 1]}).with_format("torch") + assert _in_memory(ragged) is ragged diff --git a/tests/test_detection_metric.py b/tests/test_detection_metric.py index 1300f7c..9ec6967 100644 --- a/tests/test_detection_metric.py +++ b/tests/test_detection_metric.py @@ -69,3 +69,19 @@ def test_an_attack_targeting_everyone_has_no_honest_client_to_score_against(): ctx = _ctx([{"name": "sign_flip"}], [0, 1]) DetectionQualityListener().after_simulation(ctx) assert ctx.metrics == {} + + +def test_little_is_enough_names_its_attackers_as_ground_truth(): + ctx = _ctx([{"name": "little_is_enough", "target_clients": [0, 1]}], [0, 1]) + DetectionQualityListener().after_simulation(ctx) + assert ctx.metrics["detection_precision"] == 1.0 + assert ctx.metrics["detection_recall"] == 1.0 + + +def test_fldetector_paper_metrics_count_every_client(): + """DACC, FPR and FNR as the FLDetector paper defines them, over all eight clients.""" + ctx = _ctx(SIGN_FLIP_01, [0, 5]) + DetectionQualityListener().after_simulation(ctx) + assert ctx.metrics["detection_accuracy"] == 6 / 8 # client 1 missed, client 5 accused + assert ctx.metrics["detection_fpr"] == 1 / 6 + assert ctx.metrics["detection_fnr"] == 1 / 2