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
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,9 @@ jobs:
with:
python-version: "3.11"
cache: pip
# Exercise real PEFT training on a tiny local model without Hub downloads or GPUs.
# Exercise real adapter and full-model training without Hub downloads or GPUs.
- run: pip install -e ".[lm,dev]"
- run: pytest tests/test_causal_lm.py -q
- run: pytest tests/test_causal_lm.py tests/test_stackoverflow.py tests/test_medical.py -q

docs:
name: docs build
Expand Down
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@ makes a rigorous setup the default and *checks* for the common pitfalls.
- **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.
- **Stack Overflow next-token models:** full-model fine-tuning on user-partitioned
Parquet data, held-out-user accuracy and perplexity, target-word backdoors, and
user-level membership probes. See the [Stack Overflow guide](docs/stackoverflow.md).
- **Medical causal LMs:** flashcard instruction tuning with micro-batched 4-bit
LoRA, held-out response loss, PubMedQA subset evaluation, fixed-answer backdoors
and per-sample membership probes. See the [Medical guide](docs/medical.md).

## Install (isolated conda env)

Expand All @@ -76,7 +82,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
pip install -e ".[lm]" # optional causal-LM applications and attacks
```

CPU is the default and is deterministic; `device: mps` (Apple Silicon) or `device: cuda`
Expand Down
6 changes: 4 additions & 2 deletions docs/causal-lm.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,5 +148,7 @@ 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.
The [Stack Overflow application](stackoverflow.md) adds user-partitioned Parquet data,
full-model training, and next-token evaluation. The [Medical application](medical.md)
adds micro-batched flashcard training and PubMedQA subset evaluation. Optional DoRA
and the reference LM backend remain follow-up work.
4 changes: 2 additions & 2 deletions docs/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ 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 ".[lm]" # causal-LM applications, LoRA, and text attacks
pip install -e ".[docs]" # this documentation site (mkdocs-material)
```

Expand Down Expand Up @@ -56,7 +56,7 @@ fltest list
# Frameworks: ['flare', 'flower', 'flwr', 'nvflare', 'reference']
# Attacks: ['backdoor', 'dlg', 'gaussian', 'label_flip', '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']
# Metrics: ['accuracy', 'detection', 'loss', 'next_token_accuracy', 'per_client', 'perplexity', 'pubmedqa_accuracy']

pytest tests/ -q # 110 passing
```
Expand Down
138 changes: 138 additions & 0 deletions docs/medical.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
# Medical instruction-tuning application

This Flower application trains LoRA adapters on
`hf:flwrlabs/medical-meadow-medical-flashcards`. It measures response-only held-out
flashcard loss and generated decisions on a separate PubMedQA test subset, starting
with a round-0 baseline. Training and attacks exchange only adapter parameters.

Install `pip install -e ".[lm,dev]"` on both nodes and use the Ray setup in the
[causal-LM guide](causal-lm.md). The driver downloads the data; every worker needs
the model and tokenizer cached locally. Start with `medical_smoke.yaml` and
SmolLM2-135M-Instruct, then `medical_qwen_memory_check.yaml` before
`medical_qwen_smoke.yaml` with Qwen2.5-7B-Instruct. All are short integration checks.

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

## Data and response loss

The loader pins dataset, model and tokenizer revisions. It hashes normalized
flashcard questions into train/held-out groups, preventing duplicate questions
from crossing the holdout. Seeded shuffling followed by round-robin assignment
produces IID shards whose sizes differ by at most one before per-client caps.
Stable sample IDs are row indices in the pinned source training split.
Records with empty questions or answers are excluded before splitting, with their
original row IDs recorded in metadata; malformed non-string fields raise an error.

Following [FlowerTune's medical formatter](https://github.com/flwrlabs/flower/blob/5d659b1bd0f805c76fe180e7ed5ef43242b7fa9f/examples/flowertune-llm-medical/flowertune_medical/dataset.py),
the question becomes the Alpaca instruction and the constant instruction column
is discarded. Answer case and Unicode are preserved. Only response tokens and EOS
contribute to loss; prompt and padding labels are -100. Responses exceeding
`seq_len - 2` tokens are right-truncated, leaving one prompt token and EOS; otherwise
the prompt is left-truncated to fit the complete response. Reports count prompt
and response truncation separately. Increase the sequence limit when these counts
are unacceptable for the intended experiment.

```yaml
task: causal_lm
dataset: hf:flwrlabs/medical-meadow-medical-flashcards
model_name: hf:Qwen/Qwen2.5-7B-Instruct
client_batch_size: 16
lm:
precision: fp16
quantization: 4bit
micro_batch_size: 4
grad_accum_steps: 4
gradient_checkpointing: true
attn_implementation: sdpa
medical:
pubmedqa_revision: 13a7d15476092370cbabb6475390e7e69b74d2f2
pubmedqa_max_samples: 128
pubmedqa_max_prompt_tokens: 1024
max_new_tokens: 128
```

`micro_batch_size * grad_accum_steps` must equal `client_batch_size`, which remains
the effective batch size. Each `lm.local_steps` step consumes one effective batch,
weights micro-batch losses by supervised token count, clips gradients once, and
performs one optimizer update. A short final batch uses its actual example/token
counts. FP16 overflow retries the entire effective batch with a lower loss scale;
only successful updates contribute membership IDs. Defaults preserve existing
Finance and Stack Overflow run identities and unsplit training.

On Turing, use FP16 and gradient checkpointing. Qwen configurations explicitly use
`attn_implementation: sdpa`: the initial eager-attention round-0 check produced
nonfinite outputs, while SDPA produced finite loss on the same input. This uses
[PyTorch's attention dispatch](https://qwen.readthedocs.io/en/v2.5/inference/chat.html)
without requiring the external FlashAttention-2 package. The default remains
`eager` for existing configurations. Reserve one GPU
per Qwen client. Check VRAM at the intended batch/sequence settings before longer
runs; Ray GPU fractions do not limit memory. If 7B does not fit, explicitly change
to Qwen2.5-1.5B-Instruct, pin its revision and report that deviation. Stop Ray on
both nodes after each working session.

## PubMedQA and the zero-shot baseline

The evaluator reads the official Parquet conversion of `bigbio/pubmed_qa`,
`pubmed_qa_labeled_fold0_source`, test split (500 records). It executes no remote
dataset loading script. The Parquet commit, file SHA256, selected physical row IDs,
seed, prompt cap and number of truncated prompts are included in reports. This
benchmark is used only for evaluation, separately from the flashcard holdout.

The prompt and boolean cleanup follow
[FlowerTune's medical evaluator](https://github.com/flwrlabs/flower/tree/5d659b1bd0f805c76fe180e7ed5ef43242b7fa9f/benchmarks/flowertune-llm/evaluation/medical),
including its literal `question`/`answer` markers and exact-output fallback for
`maybe`. The generation budget is the longest tokenized candidate label, independent
of the gold answer. This avoids upstream's dependence on the first gold label in
a batch. Prompts exceeding the explicit cap retain their final tokens. Subsetting,
truncation and this budget choice are recorded deviations; these scores are not
full leaderboard results. Use all 500 records and review truncation before formal
comparisons. The other three medical leaderboard benchmarks are not implemented.

`accuracy` aliases `pubmedqa_accuracy`. `loss` is token-weighted CE on held-out
flashcard responses, so the two metrics use different datasets. Reports retain
individual PubMedQA predictions, `pubmedqa_evaluation_samples`,
`evaluated_response_tokens`, `zero_shot_gap` and `zero_shot_loss_reduction`.
The latter two compare each trained round to round 0. Short smoke runs establish
the pipeline; longer clean runs must establish a learning signal before interpreting
attack damage or defense utility costs.

## Attacks and defenses

`medical_attacks_smoke.yaml` exercises fixed-answer backdoors, clipping, median,
trimmed mean, Krum, per-sample membership inference with three noise levels, secure
aggregation and fixed-point MPC. Krum's smoke selects five clients to satisfy
`n > 2*f + 2` for `f=1`; this differs from the planned four-client medical rounds.
FLDetector and label flipping are rejected for this application. Mathematical
aggregation bounds still apply to every selected cohort.

```yaml
attacks:
- name: backdoor
target_clients: [3]
params:
trigger: cf_trigger
target_answer: benchmark response
infection_rate: 0.3
```

Backdoors append a trigger to the question and replace the training answer. The
encoder refuses to truncate away the trigger or any of the fixed target answer.
Held-out ASR measures exact normalized generated-answer matches, excluding clean
answers already equal to the target. Prefix matches do not count. `max_new_tokens`
controls this generation and must cover the full target plus EOS; it does not set
the PubMedQA label budget. Clean records and their stable IDs are preserved.

Membership inference uses `target_client` and `max_samples`. Members are only
flashcards used in successful optimizer steps by the target client through the
current round. Nonmembers come from the held-out flashcards, with scores based on
per-record response loss. AUC is absent before any target records train. Poisoning
and membership inference use separate runs. Clipping, noise and aggregation hooks
operate on the adapter vector; secure aggregation and MPC simulate masking and
arithmetic rather than implementing cryptographic deployment protocols.

The deployment plan's full configuration is 20 IID clients with four selected per
round, effective batch 16, sequence length 512 and ten local optimizer steps.
Repeated seeds, the full grid, long clean learning checks, reference-backend parity,
and the remaining leaderboard benchmarks require further experiments.
12 changes: 12 additions & 0 deletions docs/metrics.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,20 @@
# Metrics — what FLTest measures

For the [Stack Overflow application](stackoverflow.md), `next_token_accuracy` reports
correct predictions over supervised next tokens, including EOS and excluding padding.
`perplexity` is the exponential of token-weighted held-out cross-entropy. These metrics
are produced at round 0 and every trained round; `accuracy` is an alias for next-token
accuracy in this task. Reports also contain metrics grouped by held-out user.

Every run produces a `RunResult` with per-round `history` and a `final` dict (last round).
These metrics are what differential and metamorphic tests read.

For the [Medical application](medical.md), `pubmedqa_accuracy` is generated decision
accuracy on a pinned PubMedQA test subset; `accuracy` aliases it. Medical `loss`
instead measures token-weighted response-only cross-entropy on held-out flashcards.
Both datasets remain fixed through round 0 and all trained rounds. Reports include
the accuracy gap and loss reduction relative to the zero-shot baseline.

## Always measured (every backend, every round)

Computed by evaluating the **global model on the central test set** after each round:
Expand Down
133 changes: 133 additions & 0 deletions docs/stackoverflow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# Stack Overflow next-token application

This Flower application uses `dataset: stackoverflow` and `task: causal_lm`. Each
training user is a client. It fully fine-tunes a pretrained model without adapters
or quantization, and evaluates on separate held-out users.

Start with `stackoverflow_smoke.yaml` and SmolLM2-135M-Instruct. Use
`stackoverflow_360m_memory_check.yaml` and `stackoverflow_360m_smoke.yaml` for
SmolLM2-360M. `stackoverflow_attacks_smoke.yaml` checks target-word poisoning,
user membership inference, noise, and aggregation simulations.
`stackoverflow_1k_packing_check.yaml` tests one round with eight selected users from
the 1,000-user cohort, requesting four clients per GPU after the memory check.

## Export the data on the driver

Install `pip install -e ".[lm,dev]"`. The loader accepts Parquet with `user_id` and
`text` columns. The exporter supports original TFF SQLite and Google's compact
FedJAX mirror of the TFF data, without installing TensorFlow or JAX.
Sources: [TFF Stack Overflow](https://www.tensorflow.org/federated/api_docs/python/tff/simulation/datasets/stackoverflow/load_data)
and [Google's mirror](https://github.com/google/fedjax/blob/main/fedjax/datasets/stackoverflow.py).
The underlying data is CC BY-SA 3.0; the export retains source and license metadata.

```bash
mkdir -p data/stackoverflow/source
curl -fL --retry 3 \
https://storage.googleapis.com/gresearch/fedjax/stackoverflow/stackoverflow_train.sqlite \
-o data/stackoverflow/source/stackoverflow_train.sqlite
curl -fL --retry 3 \
https://storage.googleapis.com/gresearch/fedjax/stackoverflow/stackoverflow_held_out.sqlite \
-o data/stackoverflow/source/stackoverflow_held_out.sqlite

python -m fltest.data.export_stackoverflow \
--train-sqlite data/stackoverflow/source/stackoverflow_train.sqlite \
--heldout-sqlite data/stackoverflow/source/stackoverflow_held_out.sqlite \
--output-dir data/stackoverflow/so_1k \
--train-users 1000 --heldout-users 200 --max-sentences 1000 --seed 786
```

The compact raw files occupy about 6.2 GB; check available space first. Users are
sampled deterministically and each export caps nonempty records per user. The
exporter refuses an existing output directory, then atomically publishes
`train.parquet`, `heldout.parquet`, and `export_manifest.json`. The manifest records
source/export SHA256 hashes, user IDs, record counts, sampling settings, and
attribution. For 10,000 training users, set `--train-users 10000` and a new directory.
For original TFF SQLite, use `--source-format tff` and pass the same database to
both input arguments; its `train` and `heldout` splits are read separately.
Keep all raw and exported data under the gitignored `data/` directory.

## Training and evaluation

```yaml
dataset: stackoverflow
task: causal_lm
data_distribution: by_user
lm:
method: full
quantization: null
precision: fp16
stackoverflow:
train_path: data/stackoverflow/so_1k/train.parquet
heldout_path: data/stackoverflow/so_1k/heldout.parquet
partition_by: user_id
max_heldout_users: 200
metrics: [next_token_accuracy, perplexity, loss]
```

`num_clients` selects training users with a fixed seed; `dataset_partitions` must
match it. The loader checks user separation across the entire exports, including
unselected users. `max_train_samples_per_client` caps each user's records. The
evaluation cap samples records round-robin across selected held-out users. Workers
receive prepared Python records through Ray; Parquet files are needed only on the driver.

Records are right-truncated to `seq_len`, reserving BOS and EOS. If no BOS exists,
EOS supplies the initial context. All subsequent text tokens and EOS contribute
to shifted next-token loss; padding labels are -100. There is no instruction
template or response-only mask. Metrics use the model's subword tokenizer.

Full training keeps FP32 master parameters with FP16 autocast and loss scaling on
CUDA. It uses the existing LM optimizer-step, gradient-checkpointing, client-sampling,
and resource controls. Unique model parameters travel as FP32 arrays, preserving
tied embeddings. The server validates full-model manifests and frees decoded wire
copies instead of retaining two models per submitted client.
Partition identities are discovered concurrently and cached, avoiding one serial
driver-polling wait per user when only a subset of a large cohort is selected.

`accuracy` and `next_token_accuracy` report correct predictions over supervised
tokens. `loss` is token-weighted cross-entropy; `perplexity` is its exponential.
Reports include round 0, trained rounds, metrics grouped by held-out user, the
accuracy learning gap, and `zero_shot_loss_reduction`. They retain file hashes,
client-to-user mappings, and actual trained IDs. IDs are physical Parquet row
indices, with held-out IDs offset by all training rows. Final checkpoints contain
the full model, tokenizer, and run metadata.

Start Ray as described in [Causal language models](causal-lm.md), then run:

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

Smoke configurations reserve one GPU per client. Measure the 360M memory check
before reducing GPU shares: Ray fractions schedule workers without enforcing VRAM
limits. Full-model messages and defense state require substantially more host RAM
and spill space than adapters. Stop Ray on both nodes after working.

Median, trimmed mean, and Krum process bounded coordinate blocks rather than
stacking complete models. Fixed-point MPC accumulates received shares without
retaining every encoded model. FLDetector retains its full gradient/history algorithm;
it rejects full-model configurations whose conservative state estimate exceeds
75% of driver RAM. Reduce participation/history or use larger-memory hardware for
those configurations. Its small-cohort smoke is not a memory guarantee for 64 clients.
The packing example uses SGD, batch size 16, and sequence length 128. Re-measure
memory before using Adam/AdamW, longer sequences, or different batches.

## Text attacks

`backdoor` takes `trigger`, `target_word`, and `infection_rate`. Poisoned records
replace the final whitespace-delimited word with the trigger followed by the target
word. The entire resulting sequence is supervised. Trigger and answer survive
truncation; source IDs and clean loader records are preserved. Held-out ASR inserts
the trigger at the final word's position and checks for the complete generated
target word. A prefix such as `hackedness` does not count for target `hacked`.
Records whose clean final word is already the target are excluded. Round 0 provides
the untrained attack baseline.

`membership_inference` uses `unit: user`, `max_users`, and `max_samples`. Members
are users whose clients actually trained through the current round. Probes include
only records used in successful optimizer steps; nonmembers are held-out users.
Every probed user receives the same number of records, bounded by availability and
`max_samples`. Scores average per-record mean token losses within each user. AUC
compares user scores. Reports include member/nonmember user and record counts,
probes per user, AUC, and loss gap. `target_clients` restricts the member cohort.
Label flipping is unsupported for this unlabeled task. Small smoke sets establish
integration; longer training and larger cohorts are needed for attack/defense results.
Loading
Loading