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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,19 @@ jobs:
- run: pip install -e ".[dev]"
- run: pytest tests/ -q

causal-lm:
name: causal LM (CPU)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip
# Exercise real PEFT training on a tiny local model without Hub downloads or GPUs.
- run: pip install -e ".[lm,dev]"
- run: pytest tests/test_causal_lm.py -q

docs:
name: docs build
runs-on: ubuntu-latest
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ makes a rigorous setup the default and *checks* for the common pitfalls.
Hugging Face image-classification id also works by name.
- **Models:** built-in `LeNet` / `ConvNet` / `MLP`, torchvision architectures such as
`ResNet18` and `MobileNetV3`, and Hub models written as `hf:<id>`.
- **Finance causal LMs:** pretrained models with 4-bit LoRA training on Flower,
response-only loss, text poisoning, membership probes, and adapter defenses.
See the [causal-LM guide](docs/causal-lm.md) for supported combinations and GPU setup.

## Install (isolated conda env)

Expand All @@ -73,6 +76,7 @@ conda activate fltest
pip install -e ".[dev]" # core (reference + Flower) + test tooling
pip install -e ".[nvflare]" # optional NVFlare backend (needs Python <=3.11)
pip install -e ".[hf]" # optional Hugging Face models and text datasets
pip install -e ".[lm]" # optional Finance causal-LM training and attacks
```

CPU is the default and is deterministic; `device: mps` (Apple Silicon) or `device: cuda`
Expand Down
17 changes: 12 additions & 5 deletions docs/attacks.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ 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.
For classification, `backdoor` and `dlg` operate on pixels; `label_flip`, `sign_flip`,
`gaussian`, and `model_replacement` operate on labels or updates. The Finance causal-LM
task adds text `label_flip` and `backdoor` poisoning and response-loss membership probes.
See [Causal language models](causal-lm.md#text-attacks-and-adapter-defenses) for its
supported parameters, combinations, and `finance_attacks_smoke.yaml` example.

## Catalog

Expand All @@ -30,7 +32,8 @@ work on labels or updates, so they apply to either modality.

**`label_flip`** — wraps the attacker's loader and relabels each batch
(`y → (y+shift) % num_classes`, or a fixed `{src: dst}` mapping). A classic robustness
attack; weak alone (one of the "naive" attacks the project flags).
attack; weak alone (one of the "naive" attacks the project flags). For Finance causal
LMs, it instead reverses sentiment polarity or applies a string-to-string mapping.

**`gaussian`** — adds zero-mean Gaussian noise to the attacker's update
(`u' = u + N(0, sigma²)`). Naive Byzantine attack; useful as a baseline.
Expand Down Expand Up @@ -64,12 +67,14 @@ 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 |

**`backdoor`** — the attacker stamps a bright patch on a fraction (`infection_rate`) of its
**`backdoor`** — for image classification, 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
fraction of a triggered test set predicted as the target — and records it as a metric. This
is the headline robustness signal; pair it with a robust-aggregation defense to see ASR drop
(see [Defenses](defenses.md)).
For Finance causal LMs, a text `trigger` is appended to training inputs and responses
are changed to the chosen sentiment label; ASR uses triggered held-out inputs.

**`membership_inference`** — asks whether a given record was in a client's training data,
which is the canonical privacy attack the proposal cites and the one Pitfall-1 says
Expand All @@ -80,6 +85,8 @@ are the held-out test set. It records `membership_inference_auc`, where 0.5 mean
leakage and 1.0 means members and non-members separate perfectly, alongside
`membership_loss_gap`. No shadow model is needed, and because it reads only losses it
applies to text as readily as to images.
For Finance causal LMs, members are restricted to source records actually consumed
in successful optimizer steps through the current round, and scores use only response tokens.

For example, `examples/configs/membership_inference.yaml` runs the same overfitted setup
twice. Undefended it reaches AUC 0.67, and clipping with Gaussian noise takes it to 0.50,
Expand Down
152 changes: 152 additions & 0 deletions docs/causal-lm.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
# Finance causal-LM runs

Install the optional language-model dependencies in the same environment on every
Ray node. The `lm` extra adds Transformers, PEFT, Accelerate, SentencePiece, and Linux bitsandbytes.

```bash
pip install -e ".[lm,dev]"
```

`examples/configs/finance_smoke.yaml` runs two clients for two rounds with
`HuggingFaceTB/SmolLM2-135M-Instruct`, 4-bit NF4 loading, FP16 computation, and LoRA.
Each round performs two local optimizer steps with batches of two examples. It uses
up to 32 training examples per client and 16 held-out evaluation examples.
`finance_learning_check.yaml` increases training to five rounds of ten local steps,
using the same holdout seed and pinned model and dataset revisions.
`finance_mistral_memory_check.yaml` runs one Mistral-7B client for one optimizer
step at batch size 16 with a sequence limit of 512 and four evaluation examples.
`finance_mistral_smoke.yaml` tests two Mistral clients for two rounds on the GPU
cluster. `finance_mistral_round_timing.yaml` times one round with ten sampled clients
from fifty IID partitions, each taking ten local steps with batches of sixteen.

For the two-node SPHERE reservation, start Ray on `a` and `b` from identical FLTest
environments. Each machine needs an installed copy of this branch at the same absolute
path and access to the specified Hugging Face model revision. Set `HF_HOME` and the
config's cache directories on storage with enough free space before larger runs.
Select a writable directory on each machine for Ray's temporary files.

```bash
# On a, using its dedicated experiment LAN address
ray start --head --node-ip-address=10.0.1.1 --port=6379 \
--num-cpus=24 --num-gpus=1 --include-dashboard=false \
--object-store-memory=4000000000 --disable-usage-stats

# On b
ray start --address=10.0.1.1:6379 --node-ip-address=10.0.1.2 \
--num-cpus=24 --num-gpus=1 --object-store-memory=4000000000 \
--disable-usage-stats

# On a
export FLTEST_RAY_ADDRESS=10.0.1.1:6379
fltest run examples/configs/finance_smoke.yaml
```

`task: causal_lm` selects the Finance implementation for `framework: flwr`.
`lm` holds precision, quantization, LoRA rank and alpha, sequence length, local steps,
gradient checkpointing, holdout fraction, and checkpoint directory. For a CPU FP32
development run, set `device: cpu`, `lm.precision: fp32`, `lm.quantization: null`,
`total_gpus: 0`, and `client_resources.num_gpus: 0`.

The loader groups inputs by Unicode-normalized, case-folded text with whitespace
collapsed, then hashes the group with the run seed to choose the holdout. Every copy
of an input stays on the same side of the split, including conflicting labels.
The remaining examples are shuffled and divided into balanced IID shards.
The original nine Finance sentiment labels are retained. The prompt uses the model's
chat template with an explicit request to reply using only the sentiment label.
Only response and EOS tokens contribute to training and held-out loss.
Long prompts are truncated from the left to keep the complete response in the sequence.

`clients_per_round` samples stable partition IDs from a seed and round number.
`client_resources` specifies the CPU and GPU share per worker. The server waits for
all selected clients and rejects incomplete rounds or incompatible adapter tensors.
FedAvg weights each update by the number of distinct examples that client used in
its local steps. Model discovery never allocates a client model.

The JSON report includes round 0 and every trained round. `accuracy` is the fraction
of greedy generated sentiment labels matching the target. A bare label or an explicit
first-sentence assertion such as "The sentiment of this tweet is negative." is accepted.
Ambiguous text and unrelated quoted labels receive no predicted label. `exact_match`
retains the strict score for the entire normalized response. `label_parse_rate` records
the fraction with a recognized label, and each round includes raw responses and targets.
`loss` is mean response cross-entropy, weighted by supervised token count.
`train_loss` records client training loss. `zero_shot_gap` is trained accuracy minus
round-0 accuracy. The small holdout is intended for pipeline verification.
LM runs require `loss_fn: CrossEntropyLoss` and `client_epochs: 1`; the number of
local optimizer steps is controlled by `lm.local_steps`.

The report also records model, tokenizer, and dataset revisions, the dataset fingerprint,
holdout group digest, selected client IDs, hosts, sample counts, and GPU memory figures.
`extras.checkpoint` points to an adapter plus tokenizer and run metadata. The final
directory appears atomically after saving succeeds, with a unique name for each attempt.
An LM run that fails writes its error to the report and exits with a nonzero status.

Run `ray stop` on both nodes after the experiment finishes. Stop background Ray
processes before switching to a different Python environment.

## Text attacks and adapter defenses

`finance_attacks_smoke.yaml` checks text attacks and each supported adapter defense
through `fltest run`. It uses SmolLM2-135M, five IID client shards, two local steps,
and sixteen held-out examples. Most runs select two clients per round; robust
aggregation runs select five so Krum and trimming have enough submissions. These
are integration checks. Their small sample counts do not establish attack efficacy
or a defense's effectiveness.

```bash
FLTEST_RAY_ADDRESS=10.0.1.1:6379 fltest run examples/configs/finance_attacks_smoke.yaml
```

`label_flip` changes the supervised Finance response for `target_clients`. Its default
mapping reverses positive and negative polarity while preserving intensity and leaving
neutral unchanged. An explicit `mapping: {positive: negative, negative: positive}`
changes only the named labels. Finance mappings use strings from the nine labels;
the classification task retains its numeric label rotation.
The existing `sign_flip` and `gaussian` update attacks can also operate on the LoRA arrays.

`backdoor` requires a nonempty `trigger` string and a sentiment `target_label`.
It appends the trigger to the input of a deterministic fraction of the attacker's
training records and trains their response toward the target. `infection_rate` is a
probability per source record, selected from the seed, client, round, and source ID;
it does not round down to zero in a one-example batch. Training preserves the clean
source records. Each client's `poisoned_samples` counts distinct modified records consumed
in successful optimizer steps; the round-level value averages client counts.
At round 0 and after each round, `attack_success_rate`
measures target-label generation on triggered held-out records, excluding examples
whose clean label is already the target. `backdoor_evaluation_samples` is its denominator.

`membership_inference` takes `target_client` and `max_samples`. It scores per-record
mean response cross-entropy on the current global model, excluding prompt and padding
tokens. Members are the target client's distinct source records used in successful
optimizer steps through the current round. Allocated records that have never trained
the model are excluded. Nonmembers come from the held-out split. Reports include
the actual probe counts, `membership_inference_auc`, and `membership_loss_gap`.
At round 0, or before the target has trained, the member count is zero and no AUC
is reported. Probes select source IDs in sorted order up to `max_samples` per set.
This implementation requires unpoisoned training records when membership inference
is enabled. It measures leakage through the global model; secure aggregation does
not remove that observation channel.

Each client's `trained_sample_ids` list uses original row indices from the pinned
dataset revision. IDs survive splitting, shuffling, truncation, poisoning, and
transport from Ray workers; client weights count distinct consumed IDs. The report
retains those lists by round so sampled participation and member sets are auditable.

Supported defenses are `norm_clip`, `gradient_noise`, `median`, `trimmed_mean`, `krum`,
`fldetector`, `secure_aggregation`, and `mpc_aggregation`. They operate only on LoRA
arrays. Gradient noise is seeded separately for each client and round; it provides
no privacy accountant or claimed differential-privacy budget. Krum requires more
than `2*f+2` participating clients, and trimming requires more than `2*trim`.
The same checks apply after any server-side filtering. FLDetector retains its
existing history-based detection logic and needs enough rounds to build that history.

Float secure aggregation uses the actual selected partition IDs, requires every
selected client to succeed, and follows optional client clipping/noise. It cannot
be combined with server-side filtering or robust aggregation. Fixed-point MPC
records quantization error, overflow, and dropout diagnostics against plain FedAvg
on the same adapter updates. These secure-aggregation implementations simulate
masking and ring arithmetic; they do not implement cryptographic key exchange.
Choose one aggregation defense per run. Configuration validation rejects unsupported
LM attacks, metrics, and incompatible defense combinations before loading a model.

Medical and Stack Overflow data/tasks, DoRA, and the reference LM backend remain
outside the current Finance implementation.
7 changes: 4 additions & 3 deletions docs/defenses.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,10 @@ run in separate Ray workers.
entries carry counters rather than learned information, so they pass through unmasked.

Both defenses also assume the participant set is fixed for the round — masks cancel only
across exactly the set that produced them. FLTest's backends use full participation, and
`secure_aggregation` records `secagg_participant_mismatch` if a round ever aggregates a
different number of updates rather than letting the residue pass silently.
across exactly the set that produced them. The Finance causal-LM Flower path passes
the selected partition IDs to every worker and rejects incomplete rounds.
`secure_aggregation` records `secagg_participant_mismatch` when the observed count
differs from the expected participant set.

**`secure_aggregation`** — float masking, no quantization. The client uploads
`x_i + m_i / n_i`; FedAvg's `sum_i (n_i / N) * x_i` then cancels the masks exactly. This is
Expand Down
5 changes: 5 additions & 0 deletions docs/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,14 @@ The core install pulls PyTorch (CPU/MPS wheels on macOS, CPU/CUDA on Linux), Flo
```bash
pip install -e ".[nvflare]" # NVFlare backend (requires Python <= 3.11)
pip install -e ".[hf]" # Hugging Face models via `model_name: hf:<id>`
pip install -e ".[lm]" # Finance causal-LM training, LoRA, and text attacks
pip install -e ".[docs]" # this documentation site (mkdocs-material)
```

The `lm` extra requires PyTorch 2.4 or later. The Finance GPU configurations use Linux
CUDA, FP16 computation, and bitsandbytes 4-bit loading. CPU FP32 development runs
disable quantization. See [Causal language models](causal-lm.md) for setup and examples.

!!! warning "Intel Macs cap PyTorch at 2.2.2"
PyTorch ships no macOS x86_64 wheel past 2.2.2, so an Intel Mac cannot install a newer
one. transformers 5 requires torch 2.5 or later and disables PyTorch below it, printing
Expand Down
82 changes: 82 additions & 0 deletions examples/configs/finance_attacks_smoke.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# Integration checks only: tiny training/evaluation sets do not measure attack efficacy.
# Run from the head of an existing two-GPU Ray cluster.
name: finance_attacks_smoke
task: causal_lm
dataset: hf:flwrlabs/fingpt-sentiment-train
model_name: hf:HuggingFaceTB/SmolLM2-135M-Instruct
device: cuda
total_cpus: 8
total_gpus: 2
num_clients: 5
dataset_partitions: 5
clients_per_round: 2
num_rounds: 2
client_batch_size: 2
client_lr: 0.00005
optimizer: AdamW
server_batch_size: 4
max_test_data_size: 16
client_resources: {num_cpus: 2, num_gpus: 1}
lm:
model_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac
tokenizer_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac
dataset_revision: d01aba2a91252c687bc35e4da659ab73ac70ea27
precision: fp16
quantization: 4bit
lora_r: 32
lora_alpha: 64
seq_len: 256
local_steps: 2
gradient_checkpointing: true
holdout_fraction: 0.1
max_train_samples_per_client: 32
checkpoint_dir: reports/adapters
metrics: [accuracy, loss]
runs:
- {framework: flwr, name: clean}
- framework: flwr
name: label_flip_clip
attacks: [{name: label_flip, target_clients: [3]}]
defenses: [{name: norm_clip, params: {clip_norm: 1.0}}]
- framework: flwr
name: backdoor
attacks:
- &text_backdoor
name: backdoor
target_clients: [3]
params: {trigger: "cf_trigger", target_label: positive, infection_rate: 0.5}
- framework: flwr
name: backdoor_median
clients_per_round: 5
attacks: [*text_backdoor]
defenses: [{name: median}]
- framework: flwr
name: backdoor_trimmed_mean
clients_per_round: 5
attacks: [*text_backdoor]
defenses: [{name: trimmed_mean, params: {trim: 1}}]
- framework: flwr
name: backdoor_krum
clients_per_round: 5
attacks: [*text_backdoor]
defenses: [{name: krum, params: {num_byzantine: 1}}]
- framework: flwr
name: membership
attacks: [&membership {name: membership_inference, params: {target_client: 3, max_samples: 8}}]
- framework: flwr
name: membership_noise
attacks: [*membership]
defenses: [{name: gradient_noise, params: {clip_norm: 1.0, sigma: 0.001}}]
- framework: flwr
name: membership_secure_aggregation
attacks: [*membership]
defenses: [{name: secure_aggregation, params: {mask_scale: 1.0}}]
- framework: flwr
name: fixed_point_aggregation
defenses: [{name: mpc_aggregation, params: {quant_bits: 16, modulus: 4294967296}}]
- framework: flwr
name: fldetector
clients_per_round: 5
num_rounds: 4
attacks: [{name: label_flip, target_clients: [3]}]
defenses: [{name: fldetector, params: {window_size: 1, start_round: 2}}]
36 changes: 36 additions & 0 deletions examples/configs/finance_learning_check.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Five-round learning check on the same 16-example holdout as finance_smoke.yaml.
name: finance_learning_check
task: causal_lm
dataset: hf:flwrlabs/fingpt-sentiment-train
model_name: hf:HuggingFaceTB/SmolLM2-135M-Instruct
seed: 786
device: cuda
total_cpus: 8
total_gpus: 2
num_clients: 2
dataset_partitions: 2
clients_per_round: 2
num_rounds: 5
client_batch_size: 2
client_lr: 0.00005
optimizer: AdamW
server_batch_size: 4
max_test_data_size: 16
client_resources: {num_cpus: 2, num_gpus: 1}
lm:
model_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac
tokenizer_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac
dataset_revision: d01aba2a91252c687bc35e4da659ab73ac70ea27
precision: fp16
quantization: 4bit
lora_r: 32
lora_alpha: 64
seq_len: 256
local_steps: 10
gradient_checkpointing: true
holdout_fraction: 0.1
max_train_samples_per_client: 32
checkpoint_dir: reports/adapters
metrics: [accuracy, loss]
runs:
- {framework: flwr, name: clean}
Loading
Loading