From dbce3393af279b31a0e7388efc343b05fbeef9af Mon Sep 17 00:00:00 2001 From: Muhammad Abdullah Soomro Date: Sun, 29 Nov 2026 16:50:33 -0500 Subject: [PATCH] feat: add Stack Overflow and Medical causal-LM applications --- .github/workflows/ci.yml | 4 +- README.md | 8 +- docs/causal-lm.md | 6 +- docs/installation.md | 4 +- docs/medical.md | 138 ++++++ docs/metrics.md | 12 + docs/stackoverflow.md | 133 ++++++ examples/configs/medical_attacks_smoke.yaml | 151 ++++++ .../configs/medical_qwen_memory_check.yaml | 49 ++ examples/configs/medical_qwen_smoke.yaml | 49 ++ examples/configs/medical_smoke.yaml | 48 ++ .../stackoverflow_1k_packing_check.yaml | 38 ++ .../stackoverflow_360m_memory_check.yaml | 37 ++ .../configs/stackoverflow_360m_smoke.yaml | 36 ++ .../configs/stackoverflow_attacks_smoke.yaml | 89 ++++ examples/configs/stackoverflow_smoke.yaml | 38 ++ fltest/attacks/causal_lm.py | 10 +- fltest/attacks/data_poison_backdoor.py | 31 +- fltest/attacks/medical.py | 67 +++ fltest/attacks/membership_inference.py | 50 ++ fltest/attacks/stackoverflow.py | 75 +++ fltest/core/config.py | 112 ++++- fltest/core/orchestrator.py | 11 +- fltest/data/causal_lm.py | 120 ++++- fltest/data/export_stackoverflow.py | 154 ++++++ fltest/data/medical.py | 221 +++++++++ fltest/data/stackoverflow.py | 170 +++++++ fltest/defenses/_robust.py | 28 ++ fltest/defenses/fldetector.py | 17 + fltest/defenses/krum.py | 13 +- fltest/defenses/median.py | 5 +- fltest/defenses/mpc_aggregation.py | 13 +- fltest/defenses/trimmed_mean.py | 13 +- fltest/frameworks/flower/adapter.py | 8 +- fltest/frameworks/flower/client.py | 23 +- fltest/frameworks/flower/server.py | 77 ++- fltest/metrics/__init__.py | 3 + fltest/metrics/causal_lm.py | 19 + fltest/testing/report.py | 6 + mkdocs.yml | 2 + pyproject.toml | 2 + tests/test_medical.py | 325 +++++++++++++ tests/test_stackoverflow.py | 452 ++++++++++++++++++ 43 files changed, 2757 insertions(+), 110 deletions(-) create mode 100644 docs/medical.md create mode 100644 docs/stackoverflow.md create mode 100644 examples/configs/medical_attacks_smoke.yaml create mode 100644 examples/configs/medical_qwen_memory_check.yaml create mode 100644 examples/configs/medical_qwen_smoke.yaml create mode 100644 examples/configs/medical_smoke.yaml create mode 100644 examples/configs/stackoverflow_1k_packing_check.yaml create mode 100644 examples/configs/stackoverflow_360m_memory_check.yaml create mode 100644 examples/configs/stackoverflow_360m_smoke.yaml create mode 100644 examples/configs/stackoverflow_attacks_smoke.yaml create mode 100644 examples/configs/stackoverflow_smoke.yaml create mode 100644 fltest/attacks/medical.py create mode 100644 fltest/attacks/stackoverflow.py create mode 100644 fltest/data/export_stackoverflow.py create mode 100644 fltest/data/medical.py create mode 100644 fltest/data/stackoverflow.py create mode 100644 fltest/metrics/causal_lm.py create mode 100644 tests/test_medical.py create mode 100644 tests/test_stackoverflow.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d11d45d..64c03e8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/README.md b/README.md index 2fbed46..e307197 100644 --- a/README.md +++ b/README.md @@ -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) @@ -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` diff --git a/docs/causal-lm.md b/docs/causal-lm.md index 7446338..870ea28 100644 --- a/docs/causal-lm.md +++ b/docs/causal-lm.md @@ -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. diff --git a/docs/installation.md b/docs/installation.md index 918b2c5..da5eccc 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -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:` -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) ``` @@ -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 ``` diff --git a/docs/medical.md b/docs/medical.md new file mode 100644 index 0000000..397c31c --- /dev/null +++ b/docs/medical.md @@ -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. diff --git a/docs/metrics.md b/docs/metrics.md index c8edb5e..0b83360 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -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: diff --git a/docs/stackoverflow.md b/docs/stackoverflow.md new file mode 100644 index 0000000..5d5e0f3 --- /dev/null +++ b/docs/stackoverflow.md @@ -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. diff --git a/examples/configs/medical_attacks_smoke.yaml b/examples/configs/medical_attacks_smoke.yaml new file mode 100644 index 0000000..592cb97 --- /dev/null +++ b/examples/configs/medical_attacks_smoke.yaml @@ -0,0 +1,151 @@ +# Integration smoke only; start the existing two-node GPU Ray cluster first. +name: medical_attacks_smoke +task: causal_lm +dataset: hf:flwrlabs/medical-meadow-medical-flashcards +model_name: hf:HuggingFaceTB/SmolLM2-135M-Instruct +seed: 786 +device: cuda +total_cpus: 8 +total_gpus: 2 +num_clients: 5 +dataset_partitions: 5 +clients_per_round: 2 +num_rounds: 2 +client_batch_size: 4 +client_lr: 5.0e-05 +optimizer: AdamW +server_batch_size: 2 +max_test_data_size: 8 +client_resources: + num_cpus: 2 + num_gpus: 1 +lm: + model_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac + tokenizer_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac + dataset_revision: bc33733afea65239aed2149aa79ea77742d28cc2 + 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 + micro_batch_size: 1 + grad_accum_steps: 4 + medical: + pubmedqa_revision: 13a7d15476092370cbabb6475390e7e69b74d2f2 + pubmedqa_max_samples: 8 + pubmedqa_max_prompt_tokens: 1024 + max_new_tokens: 32 +metrics: +- pubmedqa_accuracy +- loss +runs: +- framework: flwr + name: fixed_answer + clients_per_round: 2 + attacks: + - &id001 + name: backdoor + target_clients: + - 3 + params: + trigger: cf_trigger + target_answer: benchmark response + infection_rate: 1.0 + defenses: [] +- framework: flwr + name: fixed_answer_clip + clients_per_round: 2 + attacks: + - *id001 + defenses: + - name: norm_clip + params: + clip_norm: 1.0 +- framework: flwr + name: fixed_answer_median + clients_per_round: 4 + attacks: + - *id001 + defenses: + - name: median +- framework: flwr + name: fixed_answer_trimmed_mean + clients_per_round: 4 + attacks: + - *id001 + defenses: + - name: trimmed_mean + params: + trim: 1 +- framework: flwr + name: fixed_answer_krum + clients_per_round: 5 + attacks: + - *id001 + defenses: + - name: krum + params: + num_byzantine: 1 +- framework: flwr + name: membership + clients_per_round: 2 + attacks: + - &id002 + name: membership_inference + params: + target_client: 3 + max_samples: 4 + defenses: [] +- framework: flwr + name: membership_noise_0.0001 + clients_per_round: 2 + attacks: + - *id002 + defenses: + - name: gradient_noise + params: + clip_norm: 1.0 + sigma: 0.0001 +- framework: flwr + name: membership_noise_0.001 + clients_per_round: 2 + attacks: + - *id002 + defenses: + - name: gradient_noise + params: + clip_norm: 1.0 + sigma: 0.001 +- framework: flwr + name: membership_noise_0.01 + clients_per_round: 2 + attacks: + - *id002 + defenses: + - name: gradient_noise + params: + clip_norm: 1.0 + sigma: 0.01 +- framework: flwr + name: membership_secure_aggregation + clients_per_round: 2 + attacks: + - *id002 + defenses: + - name: secure_aggregation + params: + mask_scale: 1.0 +- framework: flwr + name: fixed_point_aggregation + clients_per_round: 2 + attacks: [] + defenses: + - name: mpc_aggregation + params: + quant_bits: 16 + modulus: 4294967296 diff --git a/examples/configs/medical_qwen_memory_check.yaml b/examples/configs/medical_qwen_memory_check.yaml new file mode 100644 index 0000000..b515e8c --- /dev/null +++ b/examples/configs/medical_qwen_memory_check.yaml @@ -0,0 +1,49 @@ +# Integration smoke only; start the existing two-node GPU Ray cluster first. +name: medical_qwen_memory_check +task: causal_lm +dataset: hf:flwrlabs/medical-meadow-medical-flashcards +model_name: hf:Qwen/Qwen2.5-7B-Instruct +seed: 786 +device: cuda +total_cpus: 6 +total_gpus: 1 +num_clients: 1 +dataset_partitions: 1 +clients_per_round: 1 +num_rounds: 1 +client_batch_size: 16 +client_lr: 5.0e-05 +optimizer: AdamW +server_batch_size: 1 +max_test_data_size: 4 +client_resources: + num_cpus: 6 + num_gpus: 1 +lm: + attn_implementation: sdpa + model_revision: a09a35458c702b33eeacc393d103063234e8bc28 + tokenizer_revision: a09a35458c702b33eeacc393d103063234e8bc28 + dataset_revision: bc33733afea65239aed2149aa79ea77742d28cc2 + precision: fp16 + quantization: 4bit + lora_r: 32 + lora_alpha: 64 + seq_len: 512 + local_steps: 1 + gradient_checkpointing: true + holdout_fraction: 0.1 + max_train_samples_per_client: 32 + checkpoint_dir: reports/adapters + micro_batch_size: 4 + grad_accum_steps: 4 + medical: + pubmedqa_revision: 13a7d15476092370cbabb6475390e7e69b74d2f2 + pubmedqa_max_samples: 4 + pubmedqa_max_prompt_tokens: 1024 + max_new_tokens: 32 +metrics: +- pubmedqa_accuracy +- loss +runs: +- framework: flwr + name: clean diff --git a/examples/configs/medical_qwen_smoke.yaml b/examples/configs/medical_qwen_smoke.yaml new file mode 100644 index 0000000..39e1eb8 --- /dev/null +++ b/examples/configs/medical_qwen_smoke.yaml @@ -0,0 +1,49 @@ +# Integration smoke only; start the existing two-node GPU Ray cluster first. +name: medical_qwen_smoke +task: causal_lm +dataset: hf:flwrlabs/medical-meadow-medical-flashcards +model_name: hf:Qwen/Qwen2.5-7B-Instruct +seed: 786 +device: cuda +total_cpus: 12 +total_gpus: 2 +num_clients: 2 +dataset_partitions: 2 +clients_per_round: 2 +num_rounds: 2 +client_batch_size: 16 +client_lr: 5.0e-05 +optimizer: AdamW +server_batch_size: 1 +max_test_data_size: 8 +client_resources: + num_cpus: 6 + num_gpus: 1 +lm: + attn_implementation: sdpa + model_revision: a09a35458c702b33eeacc393d103063234e8bc28 + tokenizer_revision: a09a35458c702b33eeacc393d103063234e8bc28 + dataset_revision: bc33733afea65239aed2149aa79ea77742d28cc2 + precision: fp16 + quantization: 4bit + lora_r: 32 + lora_alpha: 64 + seq_len: 512 + local_steps: 2 + gradient_checkpointing: true + holdout_fraction: 0.1 + max_train_samples_per_client: 32 + checkpoint_dir: reports/adapters + micro_batch_size: 4 + grad_accum_steps: 4 + medical: + pubmedqa_revision: 13a7d15476092370cbabb6475390e7e69b74d2f2 + pubmedqa_max_samples: 8 + pubmedqa_max_prompt_tokens: 1024 + max_new_tokens: 32 +metrics: +- pubmedqa_accuracy +- loss +runs: +- framework: flwr + name: clean diff --git a/examples/configs/medical_smoke.yaml b/examples/configs/medical_smoke.yaml new file mode 100644 index 0000000..fb10504 --- /dev/null +++ b/examples/configs/medical_smoke.yaml @@ -0,0 +1,48 @@ +# Integration smoke only; start the existing two-node GPU Ray cluster first. +name: medical_smoke +task: causal_lm +dataset: hf:flwrlabs/medical-meadow-medical-flashcards +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: 2 +client_batch_size: 4 +client_lr: 5.0e-05 +optimizer: AdamW +server_batch_size: 2 +max_test_data_size: 8 +client_resources: + num_cpus: 2 + num_gpus: 1 +lm: + model_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac + tokenizer_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac + dataset_revision: bc33733afea65239aed2149aa79ea77742d28cc2 + 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 + micro_batch_size: 1 + grad_accum_steps: 4 + medical: + pubmedqa_revision: 13a7d15476092370cbabb6475390e7e69b74d2f2 + pubmedqa_max_samples: 8 + pubmedqa_max_prompt_tokens: 1024 + max_new_tokens: 32 +metrics: +- pubmedqa_accuracy +- loss +runs: +- framework: flwr + name: clean diff --git a/examples/configs/stackoverflow_1k_packing_check.yaml b/examples/configs/stackoverflow_1k_packing_check.yaml new file mode 100644 index 0000000..465a621 --- /dev/null +++ b/examples/configs/stackoverflow_1k_packing_check.yaml @@ -0,0 +1,38 @@ +# One bounded round: 1,000 users, 8 selected, four concurrent clients per GPU. +# Run the single-client memory check before relying on the fractional GPU share. +name: stackoverflow_1k_packing_check +task: causal_lm +dataset: stackoverflow +data_distribution: by_user +model_name: hf:HuggingFaceTB/SmolLM2-360M +device: cuda +total_cpus: 16 +total_gpus: 2 +num_clients: 1000 +dataset_partitions: 1000 +clients_per_round: 8 +num_rounds: 1 +client_batch_size: 16 +client_lr: 0.001 +optimizer: SGD +server_batch_size: 2 +max_test_data_size: 8 +client_resources: {num_cpus: 2, num_gpus: 0.25} +lm: + model_revision: f8027fd0eaeea54caa13c31d31b9fdc459c38b49 + tokenizer_revision: f8027fd0eaeea54caa13c31d31b9fdc459c38b49 + method: full + precision: fp16 + quantization: null + seq_len: 128 + local_steps: 1 + gradient_checkpointing: true + max_train_samples_per_client: 32 + checkpoint_dir: reports/models + stackoverflow: + train_path: data/stackoverflow/so_1k/train.parquet + heldout_path: data/stackoverflow/so_1k/heldout.parquet + max_heldout_users: 2 +metrics: [next_token_accuracy, perplexity, loss] +runs: + - {framework: flwr, name: clean} diff --git a/examples/configs/stackoverflow_360m_memory_check.yaml b/examples/configs/stackoverflow_360m_memory_check.yaml new file mode 100644 index 0000000..1efda82 --- /dev/null +++ b/examples/configs/stackoverflow_360m_memory_check.yaml @@ -0,0 +1,37 @@ +# Measure whole-job GPU memory before scheduling multiple full-model clients per GPU. +name: stackoverflow_360m_memory_check +task: causal_lm +dataset: stackoverflow +data_distribution: by_user +model_name: hf:HuggingFaceTB/SmolLM2-360M +device: cuda +total_cpus: 4 +total_gpus: 1 +num_clients: 1 +dataset_partitions: 1 +clients_per_round: 1 +num_rounds: 1 +client_batch_size: 16 +client_lr: 0.001 +optimizer: SGD +server_batch_size: 2 +max_test_data_size: 8 +client_resources: {num_cpus: 2, num_gpus: 1} +lm: + model_revision: f8027fd0eaeea54caa13c31d31b9fdc459c38b49 + tokenizer_revision: f8027fd0eaeea54caa13c31d31b9fdc459c38b49 + method: full + precision: fp16 + quantization: null + seq_len: 128 + local_steps: 1 + gradient_checkpointing: true + max_train_samples_per_client: 32 + checkpoint_dir: reports/models + stackoverflow: + train_path: data/stackoverflow/so_1k/train.parquet + heldout_path: data/stackoverflow/so_1k/heldout.parquet + max_heldout_users: 2 +metrics: [next_token_accuracy, perplexity, loss] +runs: + - {framework: flwr, name: clean} diff --git a/examples/configs/stackoverflow_360m_smoke.yaml b/examples/configs/stackoverflow_360m_smoke.yaml new file mode 100644 index 0000000..c6ab806 --- /dev/null +++ b/examples/configs/stackoverflow_360m_smoke.yaml @@ -0,0 +1,36 @@ +name: stackoverflow_360m_smoke +task: causal_lm +dataset: stackoverflow +data_distribution: by_user +model_name: hf:HuggingFaceTB/SmolLM2-360M +device: cuda +total_cpus: 8 +total_gpus: 2 +num_clients: 4 +dataset_partitions: 4 +clients_per_round: 2 +num_rounds: 2 +client_batch_size: 2 +client_lr: 0.001 +optimizer: SGD +server_batch_size: 2 +max_test_data_size: 16 +client_resources: {num_cpus: 2, num_gpus: 1} +lm: + model_revision: f8027fd0eaeea54caa13c31d31b9fdc459c38b49 + tokenizer_revision: f8027fd0eaeea54caa13c31d31b9fdc459c38b49 + method: full + precision: fp16 + quantization: null + seq_len: 128 + local_steps: 2 + gradient_checkpointing: true + max_train_samples_per_client: 32 + checkpoint_dir: reports/models + stackoverflow: + train_path: data/stackoverflow/so_1k/train.parquet + heldout_path: data/stackoverflow/so_1k/heldout.parquet + max_heldout_users: 4 +metrics: [next_token_accuracy, perplexity, loss] +runs: + - {framework: flwr, name: clean} diff --git a/examples/configs/stackoverflow_attacks_smoke.yaml b/examples/configs/stackoverflow_attacks_smoke.yaml new file mode 100644 index 0000000..14f4f82 --- /dev/null +++ b/examples/configs/stackoverflow_attacks_smoke.yaml @@ -0,0 +1,89 @@ +# Integration checks only. Small sample counts do not measure attack efficacy. +name: stackoverflow_attacks_smoke +task: causal_lm +dataset: stackoverflow +data_distribution: by_user +model_name: hf:HuggingFaceTB/SmolLM2-135M-Instruct +device: cuda +total_cpus: 8 +total_gpus: 2 +num_clients: 4 +dataset_partitions: 4 +clients_per_round: 2 +num_rounds: 2 +client_batch_size: 2 +client_lr: 0.001 +optimizer: SGD +server_batch_size: 2 +max_test_data_size: 16 +client_resources: {num_cpus: 2, num_gpus: 1} +lm: + model_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac + tokenizer_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac + method: full + precision: fp16 + quantization: null + seq_len: 128 + local_steps: 2 + gradient_checkpointing: true + max_train_samples_per_client: 32 + checkpoint_dir: reports/models + stackoverflow: + train_path: data/stackoverflow/so_1k/train.parquet + heldout_path: data/stackoverflow/so_1k/heldout.parquet + max_heldout_users: 4 +metrics: [next_token_accuracy, perplexity, loss] +runs: + - framework: flwr + name: word_backdoor + attacks: + - name: backdoor + target_clients: [1] + params: {trigger: "cf_trigger", target_word: hacked, infection_rate: 1.0} + - framework: flwr + name: word_backdoor_clip + attacks: [&word_backdoor {name: backdoor, target_clients: [1], params: {trigger: "cf_trigger", target_word: hacked, infection_rate: 1.0}}] + defenses: [{name: norm_clip, params: {clip_norm: 1.0}}] + - framework: flwr + name: word_backdoor_median + num_clients: 5 + dataset_partitions: 5 + clients_per_round: 5 + attacks: [*word_backdoor] + defenses: [{name: median}] + - framework: flwr + name: word_backdoor_trimmed_mean + num_clients: 5 + dataset_partitions: 5 + clients_per_round: 5 + attacks: [*word_backdoor] + defenses: [{name: trimmed_mean, params: {trim: 1}}] + - framework: flwr + name: word_backdoor_krum + num_clients: 5 + dataset_partitions: 5 + clients_per_round: 5 + attacks: [*word_backdoor] + defenses: [{name: krum, params: {num_byzantine: 1}}] + - framework: flwr + name: user_membership + attacks: [&membership {name: membership_inference, params: {unit: user, max_users: 8, max_samples: 4}}] + - framework: flwr + name: user_membership_noise + attacks: [*membership] + defenses: [{name: gradient_noise, params: {clip_norm: 1.0, sigma: 0.0001}}] + - framework: flwr + name: user_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 + num_clients: 5 + dataset_partitions: 5 + clients_per_round: 5 + num_rounds: 4 + attacks: [*word_backdoor] + defenses: [{name: fldetector, params: {window_size: 1, start_round: 2}}] diff --git a/examples/configs/stackoverflow_smoke.yaml b/examples/configs/stackoverflow_smoke.yaml new file mode 100644 index 0000000..75d8edf --- /dev/null +++ b/examples/configs/stackoverflow_smoke.yaml @@ -0,0 +1,38 @@ +# Full-model next-token integration smoke on actual TFF Stack Overflow users. +name: stackoverflow_smoke +task: causal_lm +dataset: stackoverflow +data_distribution: by_user +model_name: hf:HuggingFaceTB/SmolLM2-135M-Instruct +device: cuda +total_cpus: 8 +total_gpus: 2 +num_clients: 4 +dataset_partitions: 4 +clients_per_round: 2 +num_rounds: 2 +client_batch_size: 2 +client_lr: 0.001 +optimizer: SGD +server_batch_size: 2 +max_test_data_size: 16 +client_resources: {num_cpus: 2, num_gpus: 1} +lm: + model_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac + tokenizer_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac + method: full + precision: fp16 + quantization: null + seq_len: 128 + local_steps: 2 + gradient_checkpointing: true + max_train_samples_per_client: 32 + checkpoint_dir: reports/models + stackoverflow: + train_path: data/stackoverflow/so_1k/train.parquet + heldout_path: data/stackoverflow/so_1k/heldout.parquet + partition_by: user_id + max_heldout_users: 4 +metrics: [next_token_accuracy, perplexity, loss] +runs: + - {framework: flwr, name: clean} diff --git a/fltest/attacks/causal_lm.py b/fltest/attacks/causal_lm.py index 7ca670f..16c8f9f 100644 --- a/fltest/attacks/causal_lm.py +++ b/fltest/attacks/causal_lm.py @@ -14,6 +14,11 @@ def is_causal_lm(ctx): return getattr(ctx.cfg, "task", None) == "causal_lm" +def selected_for_poison(seed, rnd, cid, sid, rate): + score = int(hashlib.sha256(f"{seed}:{rnd}:{cid}:{sid}".encode()).hexdigest(), 16) / 2**256 + return score < rate + + class FinancePoisonLoader: """Transform only selected training records as batches are consumed by training.""" @@ -25,7 +30,7 @@ def __init__(self, base, spec, cid, rnd, *, mapping=None, trigger=None, self.tokenizer = load_tokenizer(spec) self.mapping, self.trigger, self.target = mapping, trigger, target self.infection_rate = infection_rate - self._seed = f"{spec.seed}:{rnd}:{cid}" + self.cid, self.rnd = cid, rnd def __len__(self): return len(self._base) @@ -36,8 +41,7 @@ def __iter__(self): for sid in batch["sample_id"]: clean = self._rows[sid] source = dict(clean["finance_row"]) - score = int(hashlib.sha256(f"{self._seed}:{sid}".encode()).hexdigest(), 16) / 2**256 - if score < self.infection_rate: + if selected_for_poison(self.spec.seed, self.rnd, self.cid, sid, self.infection_rate): if self.trigger is not None: source["input"] += "\n" + self.trigger source["output"] = self.target diff --git a/fltest/attacks/data_poison_backdoor.py b/fltest/attacks/data_poison_backdoor.py index 6957dcf..d7a4ff6 100644 --- a/fltest/attacks/data_poison_backdoor.py +++ b/fltest/attacks/data_poison_backdoor.py @@ -59,13 +59,16 @@ class BackdoorAttack(ThreatModelBaseClass): HOOKS = ("before_client_train", "after_round") def __init__(self, target_label: int | str = 0, infection_rate: float = 0.3, - patch_size: int = 4, patch_value: float = 1.0, trigger: str | None = None, **params): + patch_size: int = 4, patch_value: float = 1.0, trigger: str | None = None, + target_word: str | None = None, target_answer: str | None = None, **params): super().__init__(**params) self.target_label = target_label self.infection_rate = infection_rate self.patch_size = patch_size self.patch_value = patch_value self.trigger = trigger + self.target_word = target_word + self.target_answer = target_answer def before_client_train(self, ctx: HookContext) -> None: if not self.targets(ctx.client_id) or ctx.client_data is None: @@ -73,6 +76,22 @@ def before_client_train(self, ctx: HookContext) -> None: from fltest.attacks.causal_lm import FinancePoisonLoader, is_causal_lm if is_causal_lm(ctx): + if ctx.cfg.lm.medical is not None: + from fltest.attacks.medical import MedicalPoisonLoader + + ctx.client_data = MedicalPoisonLoader( + ctx.client_data, ctx.cfg, ctx.client_id, ctx.round, + self.trigger, self.target_answer, self.infection_rate, + ) + return + if ctx.cfg.dataset == "stackoverflow": + from fltest.attacks.stackoverflow import StackOverflowPoisonLoader + + ctx.client_data = StackOverflowPoisonLoader( + ctx.client_data, ctx.cfg, ctx.client_id, ctx.round, + self.trigger, self.target_word, self.infection_rate, + ) + return ctx.client_data = FinancePoisonLoader( ctx.client_data, ctx.cfg, ctx.client_id, ctx.round, trigger=self.trigger, target=self.target_label, infection_rate=self.infection_rate, @@ -89,6 +108,16 @@ def after_round(self, ctx: HookContext) -> None: from fltest.attacks.causal_lm import evaluate_text_backdoor, is_causal_lm if is_causal_lm(ctx): + if ctx.cfg.lm.medical is not None: + from fltest.attacks.medical import evaluate_medical_backdoor + + evaluate_medical_backdoor(ctx, self.trigger, self.target_answer) + return + if ctx.cfg.dataset == "stackoverflow": + from fltest.attacks.stackoverflow import evaluate_word_backdoor + + evaluate_word_backdoor(ctx, self.trigger, self.target_word) + return evaluate_text_backdoor(ctx, self.trigger, self.target_label) return spec = ctx.cfg diff --git a/fltest/attacks/medical.py b/fltest/attacks/medical.py new file mode 100644 index 0000000..73672b1 --- /dev/null +++ b/fltest/attacks/medical.py @@ -0,0 +1,67 @@ +"""Fixed-answer medical backdoors, separate from clean benchmark evaluation.""" + +import torch + +from fltest.attacks.causal_lm import selected_for_poison +from fltest.data.causal_lm import _autocast, load_tokenizer, normalize_text +from fltest.data.medical import encode_medical_row + + +def triggered_row(clean, tokenizer, spec, trigger, target): + source = dict(clean["medical_row"]) + source["input"] += "\n" + trigger + source["output"] = target + if len(tokenizer.encode(target, add_special_tokens=False)) + 1 > spec.lm.medical.max_new_tokens: + raise ValueError("Medical max_new_tokens must cover the complete target answer and EOS") + return encode_medical_row(source, tokenizer, spec.lm.seq_len, clean["sample_id"], + trigger=trigger, require_complete=True) + + +class MedicalPoisonLoader: + def __init__(self, base, spec, cid, rnd, trigger, target, rate): + self._base, self.spec = base, spec + self.dataset = base.dataset + self._rows = {row["sample_id"]: row for row in self.dataset} + self.tokenizer = load_tokenizer(spec) + self.cid, self.rnd = cid, rnd + self.trigger, self.target, self.rate = trigger, target, rate + + def __len__(self): + return len(self._base) + + def __iter__(self): + for batch in self._base: + rows = [] + for sid in batch["sample_id"]: + clean = self._rows[sid] + if selected_for_poison(self.spec.seed, self.rnd, self.cid, sid, self.rate): + row = triggered_row(clean, self.tokenizer, self.spec, self.trigger, self.target) + row["poisoned"] = True + rows.append(row) + else: + rows.append(clean) + yield self._base.collate_fn(rows) + + +@torch.no_grad() +def evaluate_medical_backdoor(ctx, trigger, target): + spec = ctx.cfg + tokenizer = load_tokenizer(spec) + rows = [triggered_row(clean, tokenizer, spec, trigger, target) for clean in ctx.test_data.dataset + if normalize_text(clean["response"]) != normalize_text(target)] + ctx.record(backdoor_evaluation_samples=len(rows)) + if not rows: + return + correct = 0 + ctx.model.eval() + for row in rows: + inputs = torch.tensor([row["prompt_ids"]], device=spec.device) + with _autocast(spec): + generated = ctx.model.generate( + input_ids=inputs, attention_mask=torch.ones_like(inputs), + max_new_tokens=spec.lm.medical.max_new_tokens, do_sample=False, num_beams=1, + pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id, + ) + response = tokenizer.decode(generated[0, len(row["prompt_ids"]):], skip_special_tokens=True) + correct += normalize_text(response) == normalize_text(target) + ctx.record(attack_success_rate=correct / len(rows)) diff --git a/fltest/attacks/membership_inference.py b/fltest/attacks/membership_inference.py index 5cee317..6373a88 100644 --- a/fltest/attacks/membership_inference.py +++ b/fltest/attacks/membership_inference.py @@ -69,11 +69,14 @@ def __init__( self, target_client: int = 0, max_samples: int = 512, + unit: str = "sample", + max_users: int = 128, **params, ): super().__init__(**params) self.target_client = target_client self.max_samples = max_samples + self.unit, self.max_users = unit, max_users self._client_loaders = None def on_data_distribute(self, ctx: HookContext) -> None: @@ -126,6 +129,8 @@ def after_round(self, ctx: HookContext) -> None: ) def _after_causal_round(self, ctx): + if self.unit == "user": + return self._after_user_round(ctx) from torch.utils.data import DataLoader from fltest.data.causal_lm import causal_sample_losses @@ -155,3 +160,48 @@ def score(rows): membership_inference_auc=roc_auc(-member, -nonmember), membership_loss_gap=float(nonmember.mean() - member.mean()), ) + + def _after_user_round(self, ctx): + from collections import defaultdict + from torch.utils.data import DataLoader + from fltest.data.causal_lm import causal_sample_losses + + if ctx.model is None or ctx.round is None: + return + + used = defaultdict(set) + for rnd, entry in ctx.history.items(): + if not 0 < rnd <= ctx.round: + continue + for client in entry.get("clients", []): + if self.targets(client["cid"]): + used[client["cid"]].update(client["trained_sample_ids"]) + members = [] + for cid in sorted(used)[:self.max_users]: + rows = sorted((row for row in self._client_loaders[cid].dataset + if row["sample_id"] in used[cid]), key=lambda row: row["sample_id"]) + if rows: + members.append(rows) + nonmembers = defaultdict(list) + for row in ctx.test_data.dataset: + nonmembers[row["user_id"]].append(row) + nonmembers = [sorted(nonmembers[uid], key=lambda row: row["sample_id"]) + for uid in sorted(nonmembers)[:self.max_users]] + ctx.record(membership_member_users=len(members), membership_nonmember_users=len(nonmembers)) + if not members or not nonmembers: + ctx.record(membership_member_samples=0, membership_nonmember_samples=0) + return + # Match probe counts per user so larger client datasets do not get a different score scale. + count = min(self.max_samples, min(map(len, members)), min(map(len, nonmembers))) + def score(groups): + return np.asarray([causal_sample_losses(ctx.model, DataLoader( + rows[:count], batch_size=1, collate_fn=ctx.test_data.collate_fn, + ), ctx.cfg).mean() for rows in groups]) + member, nonmember = score(members), score(nonmembers) + ctx.record( + membership_member_samples=count * len(members), + membership_nonmember_samples=count * len(nonmembers), + membership_probes_per_user=count, + membership_inference_auc=roc_auc(-member, -nonmember), + membership_loss_gap=float(nonmember.mean() - member.mean()), + ) diff --git a/fltest/attacks/stackoverflow.py b/fltest/attacks/stackoverflow.py new file mode 100644 index 0000000..484de7a --- /dev/null +++ b/fltest/attacks/stackoverflow.py @@ -0,0 +1,75 @@ +"""Target-word poisoning and triggered held-out generation for next-token LMs.""" + +import re + +import torch + +from fltest.attacks.causal_lm import selected_for_poison +from fltest.data.causal_lm import _autocast, load_tokenizer, normalize_text + + +def encode_word_backdoor(row, tokenizer, seq_len, trigger, target_word): + bos = tokenizer.bos_token_id if tokenizer.bos_token_id is not None else tokenizer.eos_token_id + suffix = tokenizer.encode("\n" + trigger, add_special_tokens=False) + answer = tokenizer.encode(" " + target_word, add_special_tokens=False) + [tokenizer.eos_token_id] + available = seq_len - 1 - len(suffix) - len(answer) + if available < 1: + raise ValueError("seq_len must fit the complete trigger and target word plus context") + words = row["text"].rsplit(None, 1) + context_text = words[0] if len(words) == 2 else "" + context = tokenizer.encode(context_text, add_special_tokens=False)[-available:] + prompt = [bos] + context + suffix + ids = prompt + answer + return dict(row, input_ids=ids, labels=list(ids), prompt_ids=prompt, + response=target_word, poisoned=True) + + +class StackOverflowPoisonLoader: + def __init__(self, base, spec, cid, rnd, trigger, target_word, infection_rate): + self._base, self.spec, self.cid, self.rnd = base, spec, cid, rnd + self.dataset = base.dataset + self.rows = {row["sample_id"]: row for row in self.dataset} + self.trigger, self.target_word, self.infection_rate = trigger, target_word, infection_rate + self.tokenizer = load_tokenizer(spec) + + def __len__(self): + return len(self._base) + + def __iter__(self): + for batch in self._base: + rows = [] + for sid in batch["sample_id"]: + row = self.rows[sid] + if selected_for_poison(self.spec.seed, self.rnd, self.cid, sid, self.infection_rate): + row = encode_word_backdoor(row, self.tokenizer, self.spec.lm.seq_len, + self.trigger, self.target_word) + rows.append(row) + yield self._base.collate_fn(rows) + + +@torch.no_grad() +def evaluate_word_backdoor(ctx, trigger, target_word): + tokenizer = load_tokenizer(ctx.cfg) + target = normalize_text(target_word) + hits, total = 0, 0 + for row in ctx.test_data.dataset: + # Exclude contexts whose clean next word is already the attacker's target. + clean_word = row["text"].split()[-1] + if normalize_text(clean_word) == target: + continue + encoded = encode_word_backdoor(row, tokenizer, ctx.cfg.lm.seq_len, trigger, target_word) + inputs = torch.tensor([encoded["prompt_ids"]], device=ctx.cfg.device) + with _autocast(ctx.cfg): + result = ctx.model.generate( + input_ids=inputs, attention_mask=torch.ones_like(inputs), do_sample=False, + num_beams=1, max_new_tokens=len(tokenizer.encode(" " + target_word, add_special_tokens=False)) + 4, + eos_token_id=tokenizer.eos_token_id, pad_token_id=tokenizer.pad_token_id, + ) + text = tokenizer.decode(result[0, inputs.shape[1]:], skip_special_tokens=True) + # A word boundary prevents matching a target merely as a generated prefix. + matched = re.match(r"^\s*" + re.escape(target) + r"(?=$|\s|[^\w])", normalize_text(text)) + hits += matched is not None + total += 1 + ctx.record(backdoor_evaluation_samples=total) + if total: + ctx.record(attack_success_rate=hits / total) diff --git a/fltest/core/config.py b/fltest/core/config.py index 1e8b0a2..bfd017e 100644 --- a/fltest/core/config.py +++ b/fltest/core/config.py @@ -32,8 +32,26 @@ class ClientResources(BaseModel): model_config = {"extra": "forbid"} +class StackOverflowConfig(BaseModel): + train_path: str + heldout_path: str + partition_by: Literal["user_id"] = "user_id" + max_heldout_users: int = Field(default=200, gt=0) + + model_config = {"extra": "forbid"} + + +class MedicalConfig(BaseModel): + pubmedqa_revision: Optional[str] = None + pubmedqa_max_samples: int = Field(default=128, gt=0) + pubmedqa_max_prompt_tokens: int = Field(default=1024, ge=16) + max_new_tokens: int = Field(default=128, gt=0) + + model_config = {"extra": "forbid"} + + class CausalLMConfig(BaseModel): - """Settings for the Finance causal-LM task.""" + """Pretrained LM training and task-specific data settings.""" model_revision: Optional[str] = None tokenizer_revision: Optional[str] = None @@ -48,9 +66,32 @@ class CausalLMConfig(BaseModel): holdout_fraction: float = Field(default=0.1, gt=0, lt=1) max_train_samples_per_client: Optional[int] = Field(default=None, gt=0) checkpoint_dir: str = "reports/adapters" + method: Literal["lora", "full"] = "lora" + stackoverflow: Optional[StackOverflowConfig] = None + medical: Optional[MedicalConfig] = None + micro_batch_size: Optional[int] = Field(default=None, gt=0) + grad_accum_steps: int = Field(default=1, gt=0) + attn_implementation: Literal["eager", "sdpa"] = "eager" model_config = {"extra": "forbid"} + def run_settings(self): + """Keep existing Finance run identities when the new options are unused.""" + values = self.model_dump() + if self.method == "lora": + values.pop("method") + if self.stackoverflow is None: + values.pop("stackoverflow") + if self.medical is None: + values.pop("medical") + if self.micro_batch_size is None: + values.pop("micro_batch_size") + if self.grad_accum_steps == 1: + values.pop("grad_accum_steps") + if self.attn_implementation == "eager": + values.pop("attn_implementation") + return values + class AttackSpec(BaseModel): """A built-in attack to compose onto a run (by registry name).""" @@ -190,20 +231,43 @@ def validate_task(self): if self.task != "causal_lm": if self.lm is not None: raise ValueError("lm settings require task: causal_lm") + if set(self.metrics) & {"next_token_accuracy", "perplexity", "pubmedqa_accuracy"}: + raise ValueError("LM task metrics require their corresponding causal_lm application") return self if self.lm is None: raise ValueError("task: causal_lm requires an lm settings block") if self.framework not in ("flwr", "flower"): raise ValueError("causal_lm currently supports framework: flwr") - if self.dataset.removeprefix("hf:") != "flwrlabs/fingpt-sentiment-train": - raise ValueError("causal_lm currently supports flwrlabs/fingpt-sentiment-train") + finance = self.dataset.removeprefix("hf:") == "flwrlabs/fingpt-sentiment-train" + medical = self.dataset.removeprefix("hf:") == "flwrlabs/medical-meadow-medical-flashcards" + stackoverflow = self.dataset == "stackoverflow" + if not finance and not stackoverflow and not medical: + raise ValueError("causal_lm supports flwrlabs/fingpt-sentiment-train, medical flashcards, or stackoverflow") if not self.model_name.startswith("hf:"): raise ValueError("causal_lm requires a pretrained model_name starting with hf:") - if self.data_distribution != "iid" or self.dataset_partitions != self.num_clients: - raise ValueError("causal_lm requires IID data with dataset_partitions == num_clients") + if finance or medical: + application = "Medical" if medical else "Finance" + if self.data_distribution != "iid" or self.dataset_partitions != self.num_clients: + raise ValueError(f"{application} causal_lm requires IID data with dataset_partitions == num_clients") + if self.lm.method != "lora" or self.lm.stackoverflow is not None: + raise ValueError(f"{application} causal_lm requires LoRA without Stack Overflow data settings") + if medical != (self.lm.medical is not None): + raise ValueError("Medical causal_lm requires lm.medical; other tasks must omit it") + else: + if self.lm.medical is not None: + raise ValueError("lm.medical requires the medical flashcards dataset") + if self.lm.stackoverflow is None or self.lm.method != "full" or self.lm.quantization is not None: + raise ValueError("Stack Overflow requires lm.stackoverflow, method: full, and quantization: null") + if self.data_distribution != "by_user" or self.dataset_partitions != self.num_clients: + raise ValueError("Stack Overflow requires by_user data with dataset_partitions == num_clients") self._validate_lm_plugins() if self.num_clients < 1 or self.num_rounds < 1 or self.client_batch_size < 1: raise ValueError("causal_lm requires positive clients, rounds, and batch size") + if self.lm.micro_batch_size is None: + if self.lm.grad_accum_steps != 1: + raise ValueError("grad_accum_steps requires micro_batch_size") + elif self.lm.micro_batch_size * self.lm.grad_accum_steps != self.client_batch_size: + raise ValueError("micro_batch_size * grad_accum_steps must equal client_batch_size") if self.max_test_data_size < 1 or self.server_batch_size < 1 or self.client_lr <= 0: raise ValueError("causal_lm requires positive evaluation sizes and learning rate") if self.optimizer not in ("Adam", "AdamW", "SGD"): @@ -225,14 +289,28 @@ def validate_task(self): def _validate_lm_plugins(self): from fltest.data.finance_labels import FINANCE_LABELS - if set(self.metrics) - {"accuracy", "loss"}: - raise ValueError("causal_lm metrics must be accuracy and loss; attacks add their own metrics") + stackoverflow = self.dataset == "stackoverflow" + medical = self.lm.medical is not None + allowed_metrics = {"accuracy", "loss"} + if stackoverflow: + allowed_metrics |= {"next_token_accuracy", "perplexity"} + if medical: + allowed_metrics.add("pubmedqa_accuracy") + if set(self.metrics) - allowed_metrics: + raise ValueError(f"Unsupported causal_lm metrics; choose from {sorted(allowed_metrics)}") allowed = { "label_flip": {"mapping"}, "backdoor": {"trigger", "target_label", "infection_rate"}, "membership_inference": {"target_client", "max_samples"}, "sign_flip": {"scale"}, "gaussian": {"sigma", "seed"}, } + if stackoverflow: + allowed.pop("label_flip") + allowed["backdoor"] = {"trigger", "target_word", "infection_rate"} + allowed["membership_inference"] = {"unit", "max_samples", "max_users"} + if medical: + allowed.pop("label_flip") + allowed["backdoor"] = {"trigger", "target_answer", "infection_rate"} names = [attack.name for attack in self.attacks] if len(names) != len(set(names)): raise ValueError("causal_lm requires unique attack names") @@ -258,12 +336,24 @@ def _validate_lm_plugins(self): raise ValueError("Finance label_flip mapping must use the nine sentiment labels") if attack.name == "backdoor": if not isinstance(p.get("trigger"), str) or not p["trigger"].strip(): - raise ValueError("Finance backdoor requires a nonempty trigger string") - if p.get("target_label") not in FINANCE_LABELS: + raise ValueError("Text backdoor requires a nonempty trigger string") + if stackoverflow: + word = p.get("target_word") + if not isinstance(word, str) or len(word.split()) != 1: + raise ValueError("Stack Overflow backdoor requires a single target_word") + elif medical: + if not isinstance(p.get("target_answer"), str) or not p["target_answer"].strip(): + raise ValueError("Medical backdoor requires a nonempty target_answer") + elif p.get("target_label") not in FINANCE_LABELS: raise ValueError("Finance backdoor target_label must be a sentiment label") if not 0 <= p.get("infection_rate", 0.3) <= 1: raise ValueError("infection_rate must be in [0, 1]") if attack.name == "membership_inference": + if stackoverflow: + if p.get("unit") != "user": + raise ValueError("Stack Overflow membership inference requires unit: user") + if type(p.get("max_users", 128)) is not int or p.get("max_users", 128) < 1: + raise ValueError("max_users must be a positive integer") if (type(p.get("target_client", 0)) is not int or type(p.get("max_samples", 512)) is not int or not 0 <= p.get("target_client", 0) < self.num_clients @@ -274,6 +364,8 @@ def _validate_lm_plugins(self): "secure_aggregation", "mpc_aggregation", "fldetector", } defenses = [d.name for d in self.defenses] + if medical and "fldetector" in defenses: + raise ValueError("Medical application does not support fldetector with its small participating cohort") if set(defenses) - supported or len(defenses) != len(set(defenses)): raise ValueError("Unsupported or duplicate causal_lm defense") aggregators = {"median", "trimmed_mean", "krum", "mpc_aggregation"} @@ -362,7 +454,7 @@ def summary(self) -> Dict[str, Any]: "metrics": list(self.metrics), } if self.task == "causal_lm": - summary.update(task=self.task, lm=self.lm.model_dump(), tokenizer=self.tokenizer_id()) + summary.update(task=self.task, lm=self.lm.run_settings(), tokenizer=self.tokenizer_id()) if self.clients_per_round is not None: summary["clients_per_round"] = self.clients_per_round if self.client_resources is not None: diff --git a/fltest/core/orchestrator.py b/fltest/core/orchestrator.py index 2ada30c..60e2538 100644 --- a/fltest/core/orchestrator.py +++ b/fltest/core/orchestrator.py @@ -68,7 +68,8 @@ def expand_run_specs(config: TestConfig) -> List[RunSpec]: for key in ("task", "lm", "clients_per_round", "client_resources"): value = getattr(config, key) if value is not None and value != "classification": - common[key] = value.model_dump() if hasattr(value, "model_dump") else value + common[key] = (value.run_settings() if key == "lm" else + value.model_dump() if hasattr(value, "model_dump") else value) specs: List[RunSpec] = [] for combo in combos: @@ -104,6 +105,14 @@ def expand_run_specs(config: TestConfig) -> List[RunSpec]: def prepare_data(spec: RunSpec) -> Dict[str, Any]: """Load + partition the dataset and build loaders for a spec (cached).""" if spec.task == "causal_lm": + if spec.dataset == "stackoverflow": + from fltest.data.stackoverflow import prepare_stackoverflow_data + + return prepare_stackoverflow_data(spec) + if spec.lm.medical is not None: + from fltest.data.medical import prepare_medical_data + + return prepare_medical_data(spec) from fltest.data.causal_lm import prepare_finance_data return prepare_finance_data(spec) diff --git a/fltest/data/causal_lm.py b/fltest/data/causal_lm.py index 18db8d4..62499f6 100644 --- a/fltest/data/causal_lm.py +++ b/fltest/data/causal_lm.py @@ -1,6 +1,6 @@ -"""Pretrained causal-LM training and held-out Finance evaluation. +"""Pretrained causal-LM training, parameter transport, and Finance evaluation. -Only LoRA parameters travel through FLTest's list-of-ndarrays interface. Prepared +LoRA adapters or full-model parameters use FLTest's list-of-ndarrays interface. Prepared examples contain ordinary Python values so Ray never receives local Arrow cache paths. """ @@ -95,10 +95,11 @@ def __call__(self, rows): "labels": torch.tensor([ row["labels"] + [-100] * (width - len(row["labels"])) for row in rows ]), - "prompt_ids": [row["prompt_ids"] for row in rows], - "response": [row["response"] for row in rows], + "prompt_ids": [row.get("prompt_ids", []) for row in rows], + "response": [row.get("response", "") for row in rows], "sample_id": [row["sample_id"] for row in rows], "poisoned": [row.get("poisoned", False) for row in rows], + **({"user_id": [row["user_id"] for row in rows]} if "user_id" in rows[0] else {}), } @@ -109,18 +110,19 @@ def load_tokenizer(spec): spec.tokenizer_id(), revision=spec.lm.tokenizer_revision, cache_dir=spec.model_cache_path, padding_side="right", ) - if tokenizer.eos_token_id is None or tokenizer.chat_template is None: - raise ValueError("Finance causal_lm requires an EOS token and a chat template") + if tokenizer.eos_token_id is None: + raise ValueError("causal_lm requires an EOS token") + if spec.dataset != "stackoverflow" and spec.lm.medical is None and tokenizer.chat_template is None: + raise ValueError("Finance causal_lm requires a chat template") if tokenizer.pad_token_id is None: tokenizer.pad_token = tokenizer.eos_token return tokenizer -def prepare_finance_data(spec): - from datasets import load_dataset +def resolve_model_revisions(spec, api=None): from huggingface_hub import HfApi - api = HfApi() + api = api or HfApi() model_id = spec.model_name.removeprefix("hf:") if not Path(model_id).is_dir(): spec.lm.model_revision = api.model_info(model_id, revision=spec.lm.model_revision).sha @@ -130,6 +132,14 @@ def prepare_finance_data(spec): spec.lm.tokenizer_revision = api.model_info( spec.tokenizer_id(), revision=spec.lm.tokenizer_revision ).sha + + +def prepare_finance_data(spec): + from datasets import load_dataset + from huggingface_hub import HfApi + + api = HfApi() + resolve_model_revisions(spec, api) dataset_id = spec.dataset.removeprefix("hf:") spec.lm.dataset_revision = api.dataset_info(dataset_id, revision=spec.lm.dataset_revision).sha raw = load_dataset( @@ -187,7 +197,6 @@ def prepare_finance_data(spec): def get_causal_model(spec): try: - from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training from transformers import AutoModelForCausalLM, BitsAndBytesConfig except ImportError as exc: raise ImportError('causal_lm needs pip install -e ".[lm]"') from exc @@ -196,8 +205,9 @@ def get_causal_model(spec): opts = spec.lm kwargs = { "revision": opts.model_revision, "cache_dir": spec.model_cache_path, - "torch_dtype": torch.float16 if opts.precision == "fp16" else torch.float32, - "attn_implementation": "eager", + # Full training keeps FP32 master weights for GradScaler; autocast handles FP16 compute. + "torch_dtype": torch.float16 if opts.method == "lora" and opts.precision == "fp16" else torch.float32, + "attn_implementation": opts.attn_implementation, } if opts.quantization == "4bit": kwargs["quantization_config"] = BitsAndBytesConfig( @@ -207,6 +217,14 @@ def get_causal_model(spec): kwargs["device_map"] = {"": torch.cuda.current_device()} model = AutoModelForCausalLM.from_pretrained(spec.model_name.removeprefix("hf:"), **kwargs) model.config.use_cache = False + if opts.method == "full": + model.to(spec.device) + model.requires_grad_(True) + if opts.gradient_checkpointing: + model.gradient_checkpointing_enable() + return model + from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training + if opts.quantization: model = prepare_model_for_kbit_training( model, use_gradient_checkpointing=opts.gradient_checkpointing @@ -258,6 +276,43 @@ def set_adapter_parameters(model, parameters): }) +def manifest_field(spec): + return "parameter_manifest" if spec.lm.method == "full" else "adapter_manifest" + + +def causal_parameters(model, spec): + if spec.lm.method == "lora": + return adapter_parameters(model) + # named_parameters removes tied aliases, so shared embeddings travel once. + return [p.detach().float().cpu().numpy().copy() for _, p in sorted(model.named_parameters())] + + +def causal_manifest(model, spec): + if spec.lm.method == "lora": + return adapter_manifest(model) + entries = [(name, list(p.shape)) for name, p in sorted(model.named_parameters())] + return hashlib.sha256(json.dumps(["full", entries]).encode()).hexdigest() + + +def validate_causal_parameters(parameters, reference): + if len(parameters) != len(reference): + raise ValueError("LM parameter count mismatch") + for array, expected in zip(parameters, reference): + if (array.shape != expected.shape or array.dtype != expected.dtype + or not np.isfinite(array).all()): + raise ValueError("LM update has mismatched shapes/dtypes or nonfinite values") + + +@torch.no_grad() +def set_causal_parameters(model, parameters, spec): + if spec.lm.method == "lora": + return set_adapter_parameters(model, parameters) + state = [p for _, p in sorted(model.named_parameters())] + validate_causal_parameters(parameters, [p.detach().cpu().numpy() for p in state]) + for target, value in zip(state, parameters): + target.copy_(torch.as_tensor(value, device=target.device, dtype=target.dtype)) + + def _model_inputs(batch, device): return {key: batch[key].to(device) for key in ("input_ids", "attention_mask", "labels")} @@ -283,17 +338,28 @@ def train_causal_model(model, loader, spec, server_round, cid, details=None): except StopIteration: iterator = iter(loader) batch = next(iterator) - inputs = _model_inputs(batch, spec.device) - tokens = int((inputs["labels"][:, 1:] != -100).sum()) + tokens = int((batch["labels"][:, 1:] != -100).sum()) if tokens == 0: raise ValueError("LM training batch has no supervised response tokens") + width = spec.lm.micro_batch_size or len(batch["sample_id"]) for _attempt in range(16): optimizer.zero_grad(set_to_none=True) - with _autocast(spec): - loss = model(**inputs).loss - if not torch.isfinite(loss): - raise ValueError("Nonfinite causal-LM training loss") - scaler.scale(loss).backward() + step_loss = 0.0 + for start in range(0, len(batch["sample_id"]), width): + inputs = _model_inputs({key: batch[key][start:start + width] for key in ( + "input_ids", "attention_mask", "labels", + )}, spec.device) + count = int((inputs["labels"][:, 1:] != -100).sum()) + if not count: + raise ValueError("LM micro-batch has no supervised response tokens") + with _autocast(spec): + loss = model(**inputs).loss + if not torch.isfinite(loss): + raise ValueError("Nonfinite causal-LM training loss") + # Token weighting matches the unsplit loss even with variable answer lengths. + scaler.scale(loss * (count / tokens)).backward() + step_loss += loss.item() * count + del inputs, loss scaler.unscale_(optimizer) norm = torch.nn.utils.clip_grad_norm_(trainable, 1.0) if torch.isfinite(norm): @@ -307,7 +373,7 @@ def train_causal_model(model, loader, spec, server_round, cid, details=None): scaler.update(new_scale=scaler.get_scale() / 2) else: raise ValueError("Causal-LM gradients remain nonfinite after reducing the FP16 loss scale") - total_loss += loss.item() * tokens + total_loss += step_loss total_tokens += tokens seen.update(batch["sample_id"]) poisoned.update(sid for sid, flag in zip( @@ -320,13 +386,13 @@ def train_causal_model(model, loader, spec, server_round, cid, details=None): @torch.no_grad() def causal_sample_losses(model, loader, spec): - """Per-record response CE; prompt and padding tokens never affect the score.""" + """Per-record supervised-token CE, excluding masked prompt and padding tokens.""" model.eval() losses = [] for batch in loader: inputs = _model_inputs(batch, spec.device) with _autocast(spec): - logits = model(**inputs).logits[:, :-1].float() + logits = model(input_ids=inputs["input_ids"], attention_mask=inputs["attention_mask"]).logits[:, :-1].float() targets = inputs["labels"][:, 1:] count = (targets != -100).sum(dim=1) if (count == 0).any(): @@ -344,6 +410,14 @@ def causal_sample_losses(model, loader, spec): @torch.no_grad() def evaluate_causal_model(model, loader, spec, details=None): + if spec.lm.medical is not None: + from fltest.data.medical import evaluate_medical_model + + return evaluate_medical_model(model, loader, spec, details) + if spec.dataset == "stackoverflow": + from fltest.data.stackoverflow import evaluate_next_token_model + + return evaluate_next_token_model(model, loader, spec, details) tokenizer = load_tokenizer(spec) model.eval() total_loss, total_tokens, correct, examples = 0.0, 0, 0, 0 @@ -387,7 +461,7 @@ def evaluate_causal_model(model, loader, spec, details=None): def save_adapter_checkpoint(model, spec, metadata): - """Publish a complete adapter directory atomically with a unique name per attempt.""" + """Publish a complete adapter or full-model directory atomically per attempt.""" root = Path(spec.lm.checkpoint_dir) root.mkdir(parents=True, exist_ok=True) temporary = Path(tempfile.mkdtemp(prefix=f".partial-{spec.run_id}-", dir=root)) diff --git a/fltest/data/export_stackoverflow.py b/fltest/data/export_stackoverflow.py new file mode 100644 index 0000000..2da46e2 --- /dev/null +++ b/fltest/data/export_stackoverflow.py @@ -0,0 +1,154 @@ +"""Export TFF Stack Overflow users from local SQLite to portable Parquet files. + +Supports original TFF SQLite and Google's compact FedJAX mirror of the same data. +Neither TensorFlow nor JAX is required. Raw downloads are supplied explicitly. +""" + +import argparse +import json +from pathlib import Path +import random +import shutil +import sqlite3 +import tempfile +import zlib + +from fltest.data.stackoverflow import file_sha256 + + +def _tokens_from_fedjax(blob): + import msgpack + + def extension(code, payload): + if code == 4: # FedJAX's documented bytes-array MessagePack representation. + shape, values = msgpack.unpackb(payload, raw=False) + if len(shape) != 1 or shape[0] != len(values): + raise ValueError("Expected a one-dimensional token array") + return values + return msgpack.ExtType(code, payload) + + record = msgpack.unpackb(zlib.decompress(blob), raw=False, ext_hook=extension) + return [value.decode("utf-8") for value in record["tokens"]] + + +def _tff_example_class(): + # Define the small, wire-compatible string subset of tf.train.Example. Other + # feature types are unknown fields and are safely ignored by protobuf. + from google.protobuf import descriptor_pb2, descriptor_pool, message_factory + + file = descriptor_pb2.FileDescriptorProto(name="fltest_tff.proto", package="fltest_tff", syntax="proto3") + for name in ("BytesList", "Feature", "Features", "Example"): + file.message_type.add(name=name) + strings, feature, features, example = file.message_type + strings.field.add(name="value", number=1, type=12, label=3) + feature.field.add(name="bytes_list", number=1, type=11, type_name=".fltest_tff.BytesList", label=1) + entry = features.nested_type.add(name="Entry") + entry.options.map_entry = True + entry.field.add(name="key", number=1, type=9, label=1) + entry.field.add(name="value", number=2, type=11, type_name=".fltest_tff.Feature", label=1) + features.field.add(name="feature", number=1, type=11, type_name=".fltest_tff.Features.Entry", label=3) + example.field.add(name="features", number=1, type=11, type_name=".fltest_tff.Features", label=1) + pool = descriptor_pool.DescriptorPool() + pool.Add(file) + return message_factory.GetMessageClass(pool.FindMessageTypeByName("fltest_tff.Example")) + + +def export_users(train_sqlite, heldout_sqlite, output_dir, *, source_format="fedjax", + train_users=1000, heldout_users=200, max_sentences=1000, seed=786): + import pyarrow as pa + import pyarrow.parquet as pq + + if min(train_users, heldout_users, max_sentences) < 1: + raise ValueError("Export user and sentence limits must be positive") + if source_format not in ("fedjax", "tff"): + raise ValueError("source_format must be fedjax or tff") + destination = Path(output_dir).expanduser() + if destination.exists(): + raise FileExistsError(f"Export destination already exists: {destination}") + destination.parent.mkdir(parents=True, exist_ok=True) + temporary = Path(tempfile.mkdtemp(prefix=".partial-stackoverflow-", dir=destination.parent)) + example_class = _tff_example_class() if source_format == "tff" else None + user_sets, counts, source_hashes = {}, {}, {} + try: + for split, path, count in (("train", train_sqlite, train_users), + ("heldout", heldout_sqlite, heldout_users)): + path = Path(path).expanduser().resolve() + connection = sqlite3.connect(path.as_uri() + "?mode=ro", uri=True) + try: + if source_format == "fedjax": + available = [row[0] for row in connection.execute( + "SELECT client_id FROM federated_data ORDER BY client_id")] + else: + available = [row[0] for row in connection.execute( + "SELECT client_id FROM client_metadata WHERE split_name=? ORDER BY client_id", (split,))] + if len(available) < count: + raise ValueError(f"Requested {count} {split} users; only {len(available)} available") + selected = sorted(random.Random(seed + (split == "heldout")).sample(available, count)) + user_sets[split] = [uid.decode() if isinstance(uid, bytes) else str(uid) for uid in selected] + if split == "heldout" and set(user_sets["train"]) & set(user_sets[split]): + raise ValueError("Source training and held-out users overlap") + schema = pa.schema([("user_id", pa.string()), ("text", pa.string())], metadata={ + b"source": b"TensorFlow Federated Stack Overflow", b"split": split.encode(), + b"license": b"CC BY-SA 3.0; https://creativecommons.org/licenses/by-sa/3.0/", + }) + total = 0 + with pq.ParquetWriter(temporary / f"{split}.parquet", schema, compression="zstd") as writer: + for uid, identifier in zip(selected, user_sets[split]): + if source_format == "fedjax": + blob, = connection.execute( + "SELECT data FROM federated_data WHERE client_id=?", (uid,)).fetchone() + sentences = _tokens_from_fedjax(blob) + else: + records = connection.execute( + "SELECT serialized_example_proto FROM examples WHERE split_name=? " + "AND client_id=? ORDER BY rowid LIMIT ?", (split, uid, max_sentences)) + sentences = [] + for blob, in records: + values = example_class.FromString(blob).features.feature["tokens"].bytes_list.value + if len(values) != 1: + raise ValueError("Expected one text value in TFF tokens feature") + sentences.append(values[0].decode("utf-8")) + sentences = [text for text in sentences if text.strip()][:max_sentences] + if not sentences: + raise ValueError(f"Source user {identifier} has no usable sentences") + writer.write_table(pa.Table.from_pydict({ + "user_id": [identifier] * len(sentences), "text": sentences, + }, schema=schema)) + total += len(sentences) + counts[split] = total + source_hashes[split] = file_sha256(path) + finally: + connection.close() + manifest = { + "dataset": "TensorFlow Federated Stack Overflow", "source_format": source_format, + "source_sha256": source_hashes, "seed": seed, "max_sentences_per_user": max_sentences, + "users": user_sets, "rows": counts, + "files_sha256": {split: file_sha256(temporary / f"{split}.parquet") for split in counts}, + "source_documentation": "https://www.tensorflow.org/federated/api_docs/python/tff/simulation/datasets/stackoverflow/load_data", + "mirror_documentation": "https://github.com/google/fedjax/blob/main/fedjax/datasets/stackoverflow.py", + "license": "https://creativecommons.org/licenses/by-sa/3.0/", + } + (temporary / "export_manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") + temporary.rename(destination) + return manifest + except BaseException: + shutil.rmtree(temporary) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--train-sqlite", required=True) + parser.add_argument("--heldout-sqlite", required=True) + parser.add_argument("--output-dir", required=True) + parser.add_argument("--source-format", choices=("fedjax", "tff"), default="fedjax") + parser.add_argument("--train-users", type=int, default=1000) + parser.add_argument("--heldout-users", type=int, default=200) + parser.add_argument("--max-sentences", type=int, default=1000) + parser.add_argument("--seed", type=int, default=786) + result = export_users(**vars(parser.parse_args())) + print(json.dumps({"rows": result["rows"], "users": {k: len(v) for k, v in result["users"].items()}}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/fltest/data/medical.py b/fltest/data/medical.py new file mode 100644 index 0000000..ee7f811 --- /dev/null +++ b/fltest/data/medical.py @@ -0,0 +1,221 @@ +"""Medical flashcard instruction tuning and a pinned PubMedQA evaluation subset.""" + +import hashlib +import json +from pathlib import Path +import random +import re + +import torch +from torch.utils.data import DataLoader + +from fltest.data.causal_lm import ( + LMCollator, _autocast, _model_inputs, load_tokenizer, normalize_text, + resolve_model_revisions, split_finance_rows, +) + +PUBMEDQA_DATASET = "bigbio/pubmed_qa" +PUBMEDQA_FILE = "pubmed_qa_labeled_fold0_source/test/0000.parquet" +FLOWERTUNE_REVISION = "5d659b1bd0f805c76fe180e7ed5ef43242b7fa9f" +PUBMEDQA_INSTRUCTION = ( + "As an expert doctor in clinical science and medical knowledge, can you tell me " + "if the following statement is correct? Answer yes, no, or maybe." +) + + +def medical_prompt(question): + # FlowerTune's medical formatter discards the constant instruction column. + return ( + "Below is an instruction that describes a task. " + "Write a response that appropriately completes the request." + f"\n### Instruction:\n{question}\n### Response: " + ) + + +def encode_medical_row(row, tokenizer, seq_len, sample_id, *, trigger=None, require_complete=False): + question, answer = row["input"].strip(), row["output"].strip() + if not question or not answer: + raise ValueError("Medical records require a nonempty question and answer") + prompt = tokenizer.encode(medical_prompt(question), add_special_tokens=True) + response = tokenizer.encode(answer, add_special_tokens=False) + if not prompt or not response: + raise ValueError("Medical records must encode to nonempty prompt and response tokens") + response_truncated = len(response) > seq_len - 2 + if require_complete and response_truncated: + raise ValueError("seq_len must preserve the complete medical backdoor target answer") + response = response[:seq_len - 2] + [tokenizer.eos_token_id] + prompt_truncated = len(prompt) > seq_len - len(response) + prompt = prompt[-(seq_len - len(response)):] + if trigger is not None and trigger not in tokenizer.decode(prompt, skip_special_tokens=True): + raise ValueError("seq_len must preserve the medical trigger and complete target answer") + return { + "input_ids": prompt + response, "labels": [-100] * len(prompt) + response, + "prompt_ids": prompt, "response": answer, "sample_id": sample_id, + "medical_row": dict(row), "prompt_truncated": prompt_truncated, + "response_truncated": response_truncated, + } + + +def pubmedqa_prompt(row): + context = "\n".join(row["CONTEXTS"]) + prompt = f"{PUBMEDQA_INSTRUCTION}\n{context}\n{row['QUESTION']}\nThe answer is:\n" + return f"<|im_start|>question\n{prompt}<|im_end|>\n<|im_start|>answer\n" + + +def pubmedqa_answer(output): + """FlowerTune's boolean cleanup, including its exact-output fallback for maybe.""" + original = output.lower() + text = original + if "\n##" in text: + text = text.split("\n##")[1].split("\n")[0].strip() + text = re.sub(r"[^a-zA-Z0-9]", " ", text).strip() + text = re.sub(" +", " ", text) + for source, target in (("yesyes", "yes"), ("nono", "no"), ("yesno", "yes"), ("noyes", "no")): + if source in text: + text = text.replace(source, target) + break + return text if text in ("yes", "no") else original + + +def prepare_pubmedqa(spec, tokenizer): + import pyarrow.parquet as pq + from huggingface_hub import HfApi, hf_hub_download + + opts = spec.lm.medical + # Read the official Parquet conversion, not an executable dataset loading script. + opts.pubmedqa_revision = HfApi().dataset_info( + PUBMEDQA_DATASET, revision=opts.pubmedqa_revision or "refs/convert/parquet", + ).sha + path = hf_hub_download( + PUBMEDQA_DATASET, PUBMEDQA_FILE, repo_type="dataset", revision=opts.pubmedqa_revision, + cache_dir=spec.dataset_cache_path, + ) + rows = [dict(row, id=str(index)) for index, row in enumerate(pq.read_table(path).to_pylist())] + random.Random(spec.seed).shuffle(rows) + prepared = [] + # A fixed budget for all candidate labels avoids conditioning generation on gold. + budget = max(len(tokenizer.encode(label, add_special_tokens=False)) for label in ("yes", "no", "maybe")) + for row in rows[:opts.pubmedqa_max_samples]: + label = row["final_decision"].strip().lower() + if label not in ("yes", "no", "maybe"): + raise ValueError("Unexpected PubMedQA decision") + encoded = tokenizer.encode(pubmedqa_prompt(row), add_special_tokens=True) + if not encoded: + raise ValueError("PubMedQA prompt must have tokens") + prepared.append({ + "id": str(row["id"]), "gold": label, + "prompt_ids": encoded[-opts.pubmedqa_max_prompt_tokens:], + "prompt_truncated": len(encoded) > opts.pubmedqa_max_prompt_tokens, + "max_new_tokens": budget, + }) + if not prepared: + raise ValueError("PubMedQA subset is empty") + return prepared, { + "dataset": PUBMEDQA_DATASET, "config": "pubmed_qa_labeled_fold0_source", "split": "test", + "parquet_revision": opts.pubmedqa_revision, "parquet_path": PUBMEDQA_FILE, + "file_sha256": hashlib.sha256(Path(path).read_bytes()).hexdigest(), + "subset_ids": [row["id"] for row in prepared], "subset_seed": spec.seed, + "id_definition": "zero-based physical row index in the pinned PubMedQA test Parquet file", + "source_rows": len(rows), "evaluation_rows": len(prepared), + "truncated_prompts": sum(row["prompt_truncated"] for row in prepared), + "prompt_token_cap": opts.pubmedqa_max_prompt_tokens, "generation_token_budget": budget, + "prompt_source": f"flwrlabs/flower@{FLOWERTUNE_REVISION}:benchmarks/flowertune-llm/evaluation/medical", + "deviations": ["seeded subset", "explicit prompt token cap", "gold-independent generation budget"], + } + + +def prepare_medical_data(spec): + from datasets import load_dataset + from huggingface_hub import HfApi + + resolve_model_revisions(spec) + dataset_id = spec.dataset.removeprefix("hf:") + spec.lm.dataset_revision = HfApi().dataset_info(dataset_id, revision=spec.lm.dataset_revision).sha + raw = load_dataset(dataset_id, split="train", revision=spec.lm.dataset_revision, + cache_dir=spec.dataset_cache_path, keep_in_memory=True) + rows, excluded = [], [] + for sid, row in enumerate(raw): + if any(not isinstance(row.get(key), str) for key in ("input", "output")): + raise ValueError(f"Invalid medical question/answer at source row {sid}") + if not row["input"].strip() or not row["output"].strip(): + excluded.append(sid) + continue + rows.append(dict(row, source_id=sid)) + # Hash normalized question groups so repeated questions cannot cross the holdout. + train, heldout = split_finance_rows(rows, spec.lm.holdout_fraction, spec.seed) + random.Random(spec.seed).shuffle(train) + random.Random(spec.seed + 1).shuffle(heldout) + if len(train) < spec.num_clients: + raise ValueError("Medical training split has fewer records than clients") + tokenizer = load_tokenizer(spec) + collator = LMCollator(tokenizer.pad_token_id) + loaders = {} + for cid in range(spec.num_clients): + shard = train[cid::spec.num_clients] + if spec.lm.max_train_samples_per_client is not None: + shard = shard[:spec.lm.max_train_samples_per_client] + encoded = [encode_medical_row(row, tokenizer, spec.lm.seq_len, row["source_id"]) for row in shard] + loaders[cid] = DataLoader(encoded, batch_size=spec.client_batch_size, shuffle=True, collate_fn=collator) + evaluation = [encode_medical_row(row, tokenizer, spec.lm.seq_len, row["source_id"]) + for row in heldout[:spec.max_test_data_size]] + test = DataLoader(evaluation, batch_size=spec.server_batch_size, collate_fn=collator) + test.pubmedqa_rows, benchmark_metadata = prepare_pubmedqa(spec, tokenizer) + selected = [row for loader in loaders.values() for row in loader.dataset] + return {"c2loader": loaders, "test_loader": test, "metadata": { + "model_revision": spec.lm.model_revision, "tokenizer_revision": spec.lm.tokenizer_revision, + "dataset_revision": spec.lm.dataset_revision, "dataset_fingerprint": raw._fingerprint, + "source_rows": len(raw), "excluded_empty_row_ids": excluded, + "split_seed": spec.seed, "train_rows": len(train), "holdout_rows": len(heldout), + "holdout_groups_sha256": hashlib.sha256(json.dumps(sorted({normalize_text(r['input']) for r in heldout})).encode()).hexdigest(), + "client_rows": {cid: len(loader.dataset) for cid, loader in loaders.items()}, + "evaluation_rows": len(evaluation), "pubmedqa": benchmark_metadata, + "training_truncated_prompts": sum(row["prompt_truncated"] for row in selected), + "training_truncated_responses": sum(row["response_truncated"] for row in selected), + "evaluation_truncated_prompts": sum(row["prompt_truncated"] for row in evaluation), + "evaluation_truncated_responses": sum(row["response_truncated"] for row in evaluation), + "accuracy_definition": "generated decision accuracy on the pinned PubMedQA test subset", + "loss_definition": "token-weighted response-only CE on held-out flashcard questions, including EOS", + "sample_id_definition": "row index in the pinned medical flashcards train split", + }} + + +@torch.no_grad() +def evaluate_medical_model(model, loader, spec, details=None): + model.eval() + total_loss, total_tokens = 0.0, 0 + for batch in loader: + # Bound evaluation activation memory independently of the effective training batch. + width = spec.lm.micro_batch_size or spec.server_batch_size + for start in range(0, len(batch["sample_id"]), width): + inputs = _model_inputs({key: batch[key][start:start + width] for key in ( + "input_ids", "attention_mask", "labels", + )}, spec.device) + count = int((inputs["labels"][:, 1:] != -100).sum()) + with _autocast(spec): + loss = model(**inputs).loss + if count == 0 or not torch.isfinite(loss): + raise ValueError("Invalid medical held-out response loss") + total_loss += loss.item() * count + total_tokens += count + if not total_tokens: + raise ValueError("Medical held-out evaluation is empty") + tokenizer = load_tokenizer(spec) + predictions = [] + for row in loader.pubmedqa_rows: + inputs = torch.tensor([row["prompt_ids"]], device=spec.device) + with _autocast(spec): + generated = model.generate( + input_ids=inputs, attention_mask=torch.ones_like(inputs), + max_new_tokens=row["max_new_tokens"], do_sample=False, num_beams=1, + pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id, + ) + response = tokenizer.decode(generated[0, len(row["prompt_ids"]):], skip_special_tokens=True) + predictions.append({"pubmedqa_id": row["id"], "target": row["gold"], + "response": response, "predicted_label": pubmedqa_answer(response)}) + if not predictions: + raise ValueError("Medical PubMedQA evaluation is empty") + accuracy = sum(row["target"] == row["predicted_label"] for row in predictions) / len(predictions) + if details is not None: + details.update(metrics={"pubmedqa_accuracy": accuracy, "pubmedqa_evaluation_samples": len(predictions), + "evaluated_response_tokens": total_tokens}, predictions=predictions) + return total_loss / total_tokens, accuracy diff --git a/fltest/data/stackoverflow.py b/fltest/data/stackoverflow.py new file mode 100644 index 0000000..2ffbb92 --- /dev/null +++ b/fltest/data/stackoverflow.py @@ -0,0 +1,170 @@ +"""User-partitioned local Parquet data and ordinary next-token language modeling.""" + +from collections import defaultdict +import hashlib +from itertools import zip_longest +import math +from pathlib import Path +import random + +import torch +from torch.utils.data import DataLoader + +from fltest.data.causal_lm import LMCollator, _autocast, load_tokenizer, resolve_model_revisions + + +def file_sha256(path): + digest = hashlib.sha256() + with Path(path).open("rb") as source: + for block in iter(lambda: source.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def _parquet_users(path): + import pyarrow as pa + import pyarrow.parquet as pq + + source = pq.ParquetFile(Path(path).expanduser()) + schema = source.schema_arrow + if not {"user_id", "text"} <= set(schema.names): + raise ValueError("Stack Overflow Parquet requires user_id and text columns") + if not (pa.types.is_string(schema.field("text").type) or pa.types.is_large_string(schema.field("text").type)): + raise ValueError("Stack Overflow text must be a string column") + users = set() + for batch in source.iter_batches(columns=["user_id"]): + for value in batch.column(0).to_pylist(): + if value is None or isinstance(value, bool) or not isinstance(value, (int, str)) or not str(value): + raise ValueError("Stack Overflow user_id must contain nonempty strings or integers") + users.add(str(value)) + return source, users + + +def _collect_rows(source, users, limit, offset=0): + rows = {user: [] for user in users} + position = offset + for batch in source.iter_batches(columns=["user_id", "text"]): + for user, text in zip(batch.column(0).to_pylist(), batch.column(1).to_pylist()): + sid = position + position += 1 + user = str(user) + if user not in rows or (limit is not None and len(rows[user]) >= limit): + continue + if text is None: + raise ValueError("Stack Overflow text contains nulls") + if text.strip(): + rows[user].append({"user_id": user, "text": text, "sample_id": sid}) + if any(not shard for shard in rows.values()): + raise ValueError("Stack Overflow contains a selected user with no usable text") + return rows + + +def encode_stackoverflow_row(row, tokenizer, seq_len): + tokens = tokenizer.encode(row["text"], add_special_tokens=False) + if not tokens: + raise ValueError("Stack Overflow text encodes to no tokens") + bos = tokenizer.bos_token_id if tokenizer.bos_token_id is not None else tokenizer.eos_token_id + ids = [bos] + tokens[:seq_len - 2] + [tokenizer.eos_token_id] + return dict(row, input_ids=ids, labels=list(ids)) + + +def prepare_stackoverflow_data(spec): + settings = spec.lm.stackoverflow + train_path, heldout_path = Path(settings.train_path).expanduser(), Path(settings.heldout_path).expanduser() + train_source, train_users = _parquet_users(train_path) + heldout_source, heldout_users = _parquet_users(heldout_path) + # Check the entire exports, including users not selected for this run. + if train_users & heldout_users: + raise ValueError("Stack Overflow training and held-out users overlap") + if len(train_users) < spec.num_clients: + raise ValueError("Stack Overflow has fewer training users than num_clients") + chosen = sorted(random.Random(spec.seed).sample(sorted(train_users), spec.num_clients)) + evaluation_users = sorted(random.Random(spec.seed + 1).sample( + sorted(heldout_users), min(settings.max_heldout_users, len(heldout_users)), + )) + if not evaluation_users: + raise ValueError("Stack Overflow needs held-out users") + train = _collect_rows(train_source, chosen, spec.lm.max_train_samples_per_client) + heldout = _collect_rows(heldout_source, evaluation_users, spec.max_test_data_size, + offset=train_source.metadata.num_rows) + resolve_model_revisions(spec) + tokenizer = load_tokenizer(spec) + collator = LMCollator(tokenizer.pad_token_id) + def encode(row): + return encode_stackoverflow_row(row, tokenizer, spec.lm.seq_len) + loaders = { + cid: DataLoader([encode(row) for row in train[user]], batch_size=spec.client_batch_size, + shuffle=True, collate_fn=collator) + for cid, user in enumerate(chosen) + } + # Round-robin users so a global evaluation cap cannot select just the first user. + test_rows = [] + for group in zip_longest(*(heldout[user] for user in evaluation_users)): + for row in group: + if row is not None: + test_rows.append(encode(row)) + if len(test_rows) >= spec.max_test_data_size: + break + if len(test_rows) >= spec.max_test_data_size: + break + return { + "c2loader": loaders, + "test_loader": DataLoader(test_rows, batch_size=spec.server_batch_size, collate_fn=collator), + "metadata": { + "model_revision": spec.lm.model_revision, "tokenizer_revision": spec.lm.tokenizer_revision, + "train_file_sha256": file_sha256(train_path), "heldout_file_sha256": file_sha256(heldout_path), + "train_users_available": len(train_users), "heldout_users_available": len(heldout_users), + "train_rows_available": train_source.metadata.num_rows, + "heldout_rows_available": heldout_source.metadata.num_rows, + "client_user_ids": dict(enumerate(chosen)), "selected_heldout_user_ids": evaluation_users, + "client_rows": {cid: len(loader.dataset) for cid, loader in loaders.items()}, + "evaluation_rows": len(test_rows), "partition_by": "user_id", "split_seed": spec.seed, + "sample_id_definition": "physical Parquet row index; heldout IDs offset by all training rows", + "truncation": "right-truncate each record to seq_len, reserving BOS and EOS", + "accuracy_definition": "token-weighted next-token accuracy including EOS, excluding padding", + "perplexity_definition": "exp(token-weighted next-token cross-entropy)", + }, + } + + +@torch.no_grad() +def evaluate_next_token_model(model, loader, spec, details=None): + model.eval() + total_loss, correct, tokens = 0.0, 0, 0 + users = defaultdict(lambda: [0.0, 0, 0, 0]) + for batch in loader: + inputs = {key: batch[key].to(spec.device) for key in ("input_ids", "attention_mask")} + with _autocast(spec): + logits = model(**inputs).logits[:, :-1].float() + targets = batch["labels"].to(spec.device)[:, 1:] + mask = targets != -100 + loss = torch.nn.functional.cross_entropy( + logits.reshape(-1, logits.shape[-1]), targets.reshape(-1), reduction="none", ignore_index=-100, + ).reshape_as(targets) + if not torch.isfinite(loss).all() or not mask.any(): + raise ValueError("Invalid next-token evaluation loss") + per_loss = loss.sum(dim=1).cpu().tolist() + per_correct = ((logits.argmax(dim=-1) == targets) & mask).sum(dim=1).cpu().tolist() + per_tokens = mask.sum(dim=1).cpu().tolist() + total_loss += sum(per_loss) + correct += sum(per_correct) + tokens += sum(per_tokens) + for uid, value, hit, count in zip(batch["user_id"], per_loss, per_correct, per_tokens): + users[uid][0] += value + users[uid][1] += hit + users[uid][2] += count + users[uid][3] += 1 + if not tokens: + raise ValueError("Next-token evaluation set is empty") + mean_loss, accuracy = total_loss / tokens, correct / tokens + if details is not None: + details.update( + metrics={"next_token_accuracy": accuracy, "perplexity": math.exp(mean_loss), + "evaluated_tokens": tokens, "evaluated_users": len(users)}, + predictions=[], + user_metrics={uid: {"loss": value / count, "perplexity": math.exp(value / count), + "next_token_accuracy": hit / count, "evaluated_tokens": count, + "evaluated_records": records} + for uid, (value, hit, count, records) in users.items()}, + ) + return mean_loss, accuracy diff --git a/fltest/defenses/_robust.py b/fltest/defenses/_robust.py index f50f232..6934fb9 100644 --- a/fltest/defenses/_robust.py +++ b/fltest/defenses/_robust.py @@ -29,6 +29,34 @@ def stack(updates: List[List[np.ndarray]]) -> np.ndarray: return np.stack([flatten(u) for u in updates], axis=0) # (num_clients, dim) +def parameter_blocks(updates, block_size=65536): + """Yield bounded FP64 coordinate blocks without stacking entire full models.""" + for layer, template in enumerate(updates[0]): + arrays = [update[layer].flat for update in updates] + for start in range(0, template.size, block_size): + stop = min(start + block_size, template.size) + yield layer, start, stop, np.stack([array[start:stop].astype(np.float64) for array in arrays]) + + +def coordinatewise(updates, reducer): + output = [np.empty(array.shape, dtype=array.dtype) for array in updates[0]] + for layer, start, stop, block in parameter_blocks(updates): + output[layer].reshape(-1)[start:stop] = reducer(block) + return output + + +def squared_distances(updates): + distances = np.zeros((len(updates), len(updates)), dtype=np.float64) + for _, _, _, block in parameter_blocks(updates): + # Centering avoids cancellation from the common pretrained model. + block -= block[0].copy() + norms = np.einsum("ij,ij->i", block, block) + distances += norms[:, None] + norms[None, :] - 2 * (block @ block.T) + np.maximum(distances, 0, out=distances) + np.fill_diagonal(distances, 0) + return distances + + def replace_with(ctx, robust_update: List[np.ndarray]) -> None: total = sum(n for _, n in ctx.updates_and_weights) ctx.updates_and_weights = [(robust_update, total)] diff --git a/fltest/defenses/fldetector.py b/fltest/defenses/fldetector.py index c44b83a..349e17d 100644 --- a/fltest/defenses/fldetector.py +++ b/fltest/defenses/fldetector.py @@ -138,6 +138,23 @@ def _reset(self): def before_simulation(self, ctx: HookContext) -> None: self._reset() + spec = ctx.cfg + if (getattr(spec, "task", None) == "causal_lm" + and spec.lm.method == "full" and ctx.global_state is not None): + from psutil import virtual_memory + + clients = spec.clients_per_round or spec.num_clients + size = sum(array.size for array in ctx.global_state) + window = min(self.window_size, spec.num_rounds) + required = (size * 8 * (3 * clients + 3 * window + 10) + + sum(array.nbytes for array in ctx.global_state) * (clients + 8)) + total = virtual_memory().total + if required > .75 * total: + raise ValueError( + f"FLDetector full-model state conservatively needs {required / 1024**3:.1f} GiB " + f"on a {total / 1024**3:.1f} GiB driver; reduce clients_per_round/window_size " + "or use adapter training" + ) def before_round(self, ctx: HookContext) -> None: if not self.excluded_clients: diff --git a/fltest/defenses/krum.py b/fltest/defenses/krum.py index 9c059dc..b80ddba 100644 --- a/fltest/defenses/krum.py +++ b/fltest/defenses/krum.py @@ -11,7 +11,7 @@ from fltest.core.hook_context import HookContext from fltest.core.registry import register_defense -from fltest.defenses._robust import replace_with, stack +from fltest.defenses._robust import replace_with, squared_distances from fltest.defenses.base import PPFLBaseClass @@ -31,15 +31,8 @@ def before_aggregate(self, ctx: HookContext) -> None: if not uw or len(uw) < 3: return updates = [u for u, _ in uw] - mat = stack(updates) # (n, dim) - n = mat.shape[0] - # squared pairwise distances - # Row-wise differences avoid allocating an n*n*adapter_size tensor. - sq = np.zeros((n, n), dtype=np.float64) - for i in range(n): - difference = mat[i + 1:] - mat[i] - sq[i, i + 1:] = np.einsum("ij,ij->i", difference, difference) - sq[i + 1:, i] = sq[i, i + 1:] + n = len(updates) + sq = squared_distances(updates) m = max(1, n - self.f - 2) scores = [] for i in range(n): diff --git a/fltest/defenses/median.py b/fltest/defenses/median.py index 7e467d3..016b487 100644 --- a/fltest/defenses/median.py +++ b/fltest/defenses/median.py @@ -10,7 +10,7 @@ from fltest.core.hook_context import HookContext from fltest.core.registry import register_defense -from fltest.defenses._robust import replace_with, stack, unflatten +from fltest.defenses._robust import coordinatewise, replace_with from fltest.defenses.base import PPFLBaseClass @@ -23,5 +23,4 @@ def before_aggregate(self, ctx: HookContext) -> None: if not uw: return updates = [u for u, _ in uw] - agg = np.median(stack(updates), axis=0) - replace_with(ctx, unflatten(agg, updates[0])) + replace_with(ctx, coordinatewise(updates, lambda block: np.median(block, axis=0))) diff --git a/fltest/defenses/mpc_aggregation.py b/fltest/defenses/mpc_aggregation.py index a5b41d6..a3a943a 100644 --- a/fltest/defenses/mpc_aggregation.py +++ b/fltest/defenses/mpc_aggregation.py @@ -135,7 +135,7 @@ def before_aggregate(self, ctx: HookContext) -> None: # weighting happens before encoding because the ring has no fractional weights: # the server can only sum and divide by the public total afterwards. max_scaled = 0.0 - shares: List[List[np.ndarray]] = [] + acc = [np.zeros(a.shape, dtype=np.int64) for a in template] for cid in participants: weighted = [ u.astype(np.float64) * weights[cid] if is_maskable(tmpl) else np.zeros_like(u, np.float64) @@ -148,13 +148,10 @@ def before_aggregate(self, ctx: HookContext) -> None: template, cid, participants, self.seed, ctx.round, self.modulus ) share = [(s + m) % self.modulus for s, m in zip(share, mask)] - shares.append(share) - - # 2. The server sums only what it received. Reducing after each client keeps the - # running value inside int64 for any accepted modulus. - acc = [np.zeros(a.shape, dtype=np.int64) for a in template] - for cid in survivors: - acc = [(a + s) % self.modulus for a, s in zip(acc, shares[cid])] + # Sum received shares as they are generated instead of keeping an + # encoded full model for every client. Dropouts still leave masks. + if cid in survivors: + acc = [(a + s) % self.modulus for a, s in zip(acc, share)] # 3. Decode and divide by the surviving sample total. Integer entries never entered # the ring (see `is_maskable`), so they take the plaintext average the backend diff --git a/fltest/defenses/trimmed_mean.py b/fltest/defenses/trimmed_mean.py index d2fa042..1a44d0e 100644 --- a/fltest/defenses/trimmed_mean.py +++ b/fltest/defenses/trimmed_mean.py @@ -11,7 +11,7 @@ from fltest.core.hook_context import HookContext from fltest.core.registry import register_defense -from fltest.defenses._robust import replace_with, stack, unflatten +from fltest.defenses._robust import coordinatewise, replace_with from fltest.defenses.base import PPFLBaseClass @@ -30,10 +30,9 @@ def before_aggregate(self, ctx: HookContext) -> None: if getattr(ctx.cfg, "task", None) == "causal_lm" and len(uw) <= 2 * self.trim: raise ValueError("trimmed_mean requires more than 2*trim received clients") updates = [u for u, _ in uw] - mat = stack(updates) # (n, dim) - n = mat.shape[0] + n = len(updates) k = min(self.trim, (n - 1) // 2) - smat = np.sort(mat, axis=0) - kept = smat[k : n - k] if k > 0 else smat - agg = kept.mean(axis=0) - replace_with(ctx, unflatten(agg, updates[0])) + def reduce(block): + ordered = np.sort(block, axis=0) + return (ordered[k:n - k] if k > 0 else ordered).mean(axis=0) + replace_with(ctx, coordinatewise(updates, reduce)) diff --git a/fltest/frameworks/flower/adapter.py b/fltest/frameworks/flower/adapter.py index 52bb215..517c3e6 100644 --- a/fltest/frameworks/flower/adapter.py +++ b/fltest/frameworks/flower/adapter.py @@ -85,11 +85,11 @@ def run_simulation(self, spec: RunSpec, data: Dict[str, Any], hook_runner: HookR state_holder: Dict[str, Any] = {"data_metadata": data.get("metadata", {})} if spec.task == "causal_lm": import torch - from fltest.data.causal_lm import adapter_manifest, adapter_parameters, get_causal_model + from fltest.data.causal_lm import causal_manifest, causal_parameters, get_causal_model, manifest_field init_model = get_causal_model(spec) - init_params = adapter_parameters(init_model) - state_holder["adapter_manifest"] = adapter_manifest(init_model) + init_params = causal_parameters(init_model, spec) + state_holder[manifest_field(spec)] = causal_manifest(init_model, spec) del init_model gc.collect() if spec.device == "cuda": @@ -162,7 +162,7 @@ def run_simulation(self, spec: RunSpec, data: Dict[str, Any], hook_runner: HookR if spec.task == "causal_lm": result.extras.update( data=state_holder["data_metadata"], - adapter_manifest=state_holder["adapter_manifest"], checkpoint=state_holder["checkpoint"], ) + result.extras[manifest_field(spec)] = state_holder[manifest_field(spec)] return result diff --git a/fltest/frameworks/flower/client.py b/fltest/frameworks/flower/client.py index 3ab4b75..b918599 100644 --- a/fltest/frameworks/flower/client.py +++ b/fltest/frameworks/flower/client.py @@ -76,8 +76,8 @@ def fit(self, parameters, config): def fit_causal_lm(self, parameters, config): import torch from fltest.data.causal_lm import ( - adapter_manifest, adapter_parameters, get_causal_model, - set_adapter_parameters, train_causal_model, + causal_manifest, causal_parameters, get_causal_model, manifest_field, + set_causal_parameters, train_causal_model, ) spec = self.spec @@ -86,10 +86,11 @@ def fit_causal_lm(self, parameters, config): self.net = get_causal_model(spec) ctx = after = None try: - manifest = adapter_manifest(self.net) - if manifest != config["adapter_manifest"]: - raise ValueError("LoRA adapter manifest differs between driver and client") - set_adapter_parameters(self.net, parameters) + key = manifest_field(spec) + manifest = causal_manifest(self.net, spec) + if manifest != config[key]: + raise ValueError("LM parameter manifest differs between driver and client") + set_causal_parameters(self.net, parameters, spec) ctx = HookContext( cfg=spec, framework="flwr", run_name=spec.run_name, round=rnd, client_id=self.cid, client_data=self.trainloader, global_state=parameters, @@ -101,7 +102,7 @@ def fit_causal_lm(self, parameters, config): torch.cuda.reset_peak_memory_stats() training = {} loss, num_samples = train_causal_model(self.net, loader, spec, rnd, self.cid, training) - update = adapter_parameters(self.net) + update = causal_parameters(self.net, spec) after = HookContext( cfg=spec, framework="flwr", run_name=spec.run_name, round=rnd, client_id=self.cid, client_update=update, num_samples=num_samples, @@ -110,7 +111,7 @@ def fit_causal_lm(self, parameters, config): ) self.hook_runner.run("after_client_train", after) metrics = { - "cid": self.cid, "train_loss": loss, "adapter_manifest": manifest, + "cid": self.cid, "train_loss": loss, key: manifest, "local_steps": spec.lm.local_steps, "host": socket.gethostname(), "trained_sample_ids": json.dumps(training["trained_sample_ids"]), "poisoned_samples": len(training["poisoned_sample_ids"]), @@ -119,6 +120,12 @@ def fit_causal_lm(self, parameters, config): } metrics.update(numeric_metrics(ctx.metrics)) metrics.update(numeric_metrics(after.metrics)) + if spec.lm.micro_batch_size is not None: + metrics.update(micro_batch_size=spec.lm.micro_batch_size, + grad_accum_steps=spec.lm.grad_accum_steps, + effective_batch_size=spec.client_batch_size) + if spec.dataset == "stackoverflow": + metrics["user_id"] = self.trainloader.dataset[0]["user_id"] update = after.client_update if after.client_update is not None else update return update, num_samples, metrics finally: diff --git a/fltest/frameworks/flower/server.py b/fltest/frameworks/flower/server.py index 3913c21..1cd5e14 100644 --- a/fltest/frameworks/flower/server.py +++ b/fltest/frameworks/flower/server.py @@ -11,6 +11,7 @@ from __future__ import annotations from collections import defaultdict +from concurrent.futures import ThreadPoolExecutor, as_completed import gc import json import random @@ -71,23 +72,32 @@ def configure_fit(self, server_round, parameters, client_manager): if selected == tuple(range(self._spec.num_clients)) or not configured: return configured + unknown = [proxy for proxy, _ in configured if proxy.cid not in self._client_id_by_proxy] + if unknown: + # Flower's driver polls each RPC at one-second intervals. Serial + # discovery adds that wait for every virtual client in large cohorts. + with ThreadPoolExecutor(max_workers=min(64, len(unknown))) as executor: + pending = { + executor.submit(proxy.get_properties, GetPropertiesIns({}), + timeout=None, group_id=server_round): proxy for proxy in unknown + } + for future in as_completed(pending): + proxy = pending[future] + response = future.result() + client_id = response.properties.get("cid") if response.status.code == Code.OK else None + if ( + not isinstance(client_id, int) or isinstance(client_id, bool) + or not 0 <= client_id < self._spec.num_clients + ): + raise ValueError( + "Selective before_round requires every Flower client to report " + "a valid partition ID in get_properties" + ) + self._client_id_by_proxy[proxy.cid] = client_id + by_client_id = {} for proxy, fit_ins in configured: - client_id = self._client_id_by_proxy.get(proxy.cid) - if client_id is None: - response = proxy.get_properties( - GetPropertiesIns({}), timeout=None, group_id=server_round - ) - client_id = response.properties.get("cid") if response.status.code == Code.OK else None - if ( - not isinstance(client_id, int) or isinstance(client_id, bool) - or not 0 <= client_id < self._spec.num_clients - ): - raise ValueError( - "Selective before_round requires every Flower client to report " - "a valid partition ID in get_properties" - ) - self._client_id_by_proxy[proxy.cid] = client_id + client_id = self._client_id_by_proxy[proxy.cid] if client_id in by_client_id: raise ValueError(f"Flower clients report duplicate partition ID {client_id}") by_client_id[client_id] = (proxy, fit_ins) @@ -100,17 +110,18 @@ def configure_fit(self, server_round, parameters, client_manager): def aggregate_fit(self, server_round, results, failures): successful = [(p, r) for p, r in results if r.status.code == Code.OK] if self._spec.task == "causal_lm": - from fltest.data.causal_lm import validate_adapter_parameters + from fltest.data.causal_lm import manifest_field, validate_causal_parameters ids = [r.metrics.get("cid") for _, r in successful] - if failures or len(ids) != len(self._selected_clients) or set(ids) != set(self._selected_clients): + if (failures or any(type(cid) is not int for cid in ids) + or len(ids) != len(self._selected_clients) or set(ids) != set(self._selected_clients)): raise RuntimeError(f"Causal-LM round {server_round} has missing or failed clients") for _, response in successful: if response.num_examples <= 0: raise ValueError("Causal-LM client trained on no examples") - if response.metrics.get("adapter_manifest") != self._adapter_manifest: - raise ValueError("LoRA adapter manifest differs in a client update") - validate_adapter_parameters(parameters_to_ndarrays(response.parameters), self._global_state) + key = manifest_field(self._spec) + if response.metrics.get(key) != getattr(self, "_" + key): + raise ValueError("LM parameter manifest differs in a client update") used = json.loads(response.metrics["trained_sample_ids"]) if (not isinstance(used, list) or any(type(sid) is not int or sid < 0 for sid in used) or len(set(used)) != response.num_examples or len(used) != response.num_examples): @@ -132,6 +143,12 @@ def aggregate_fit(self, server_round, results, failures): # their existing aggregation behavior without inventing an identity. client_id = None update = parameters_to_ndarrays(response.parameters) + if self._spec.task == "causal_lm": + validate_causal_parameters(update, self._global_state) + if self._spec.lm.method == "full": + # Decoded weights are the owned aggregation inputs. Drop the + # wire copy now instead of retaining two full models per client. + response.parameters.tensors.clear() updates_and_weights.append((update, response.num_examples)) client_submissions.append( ClientSubmission(client_id, tuple(update), response.num_examples) @@ -151,7 +168,7 @@ def aggregate_fit(self, server_round, results, failures): self._hooks.run("on_aggregate", ctx) aggregated = ctx.new_global_state if ctx.new_global_state is not None else aggregated if self._spec.task == "causal_lm": - validate_adapter_parameters(aggregated, self._global_state) + validate_causal_parameters(aggregated, self._global_state) ctx.new_global_state = aggregated self._global_state = aggregated self._hooks.run("after_aggregate", ctx) @@ -183,13 +200,13 @@ def evaluate_fn(server_round, parameters, config): import torch from fltest.data.causal_lm import ( evaluate_causal_model, get_causal_model, save_adapter_checkpoint, - set_adapter_parameters, + set_causal_parameters, ) net = get_causal_model(spec) ctx = None try: - set_adapter_parameters(net, parameters) + set_causal_parameters(net, parameters, spec) details = {} loss, acc = evaluate_causal_model(net, test_loader, spec, details=details) state_holder["final_params"] = list(parameters) @@ -199,6 +216,8 @@ def evaluate_fn(server_round, parameters, config): metrics.update(strategy._last_fit_metrics) metrics.update(strategy._last_server_metrics) metrics["zero_shot_gap"] = acc - history[0]["accuracy"] + if spec.dataset == "stackoverflow" or spec.lm.medical is not None: + metrics["zero_shot_loss_reduction"] = history[0]["loss"] - loss ctx = HookContext( cfg=spec, framework="flwr", run_name=spec.run_name, round=server_round, global_state=parameters, model=net, test_data=test_loader, @@ -207,6 +226,8 @@ def evaluate_fn(server_round, parameters, config): hook_runner.run("after_round", ctx) history.setdefault(server_round, {}).update(ctx.metrics) history[server_round]["predictions"] = details["predictions"] + if "user_metrics" in details: + history[server_round]["heldout_user_metrics"] = details["user_metrics"] if server_round == spec.num_rounds: state_holder["checkpoint"] = save_adapter_checkpoint( net, spec, state_holder["data_metadata"] @@ -246,7 +267,10 @@ def server_fn(context): def round_config(server_round): config = fit_config(server_round) if spec.task == "causal_lm": - config["adapter_manifest"] = state_holder["adapter_manifest"] + from fltest.data.causal_lm import manifest_field + + key = manifest_field(spec) + config[key] = state_holder[key] return config strategy = HookedFedAvg( @@ -258,7 +282,10 @@ def round_config(server_round): initial_parameters=initial_parameters, ) if spec.task == "causal_lm": - strategy._adapter_manifest = state_holder["adapter_manifest"] + from fltest.data.causal_lm import manifest_field + + key = manifest_field(spec) + setattr(strategy, "_" + key, state_holder[key]) evaluate_fn._strategy = strategy # let evaluate read the round's fit metrics return ServerAppComponents(strategy=strategy, config=ServerConfig(num_rounds=spec.num_rounds)) diff --git a/fltest/metrics/__init__.py b/fltest/metrics/__init__.py index 49c13ed..c9fcc4e 100644 --- a/fltest/metrics/__init__.py +++ b/fltest/metrics/__init__.py @@ -15,6 +15,9 @@ "loss": "fltest.metrics.listeners", "per_client": "fltest.metrics.listeners", "detection": "fltest.metrics.detection", + "next_token_accuracy": "fltest.metrics.causal_lm", + "perplexity": "fltest.metrics.causal_lm", + "pubmedqa_accuracy": "fltest.metrics.causal_lm", } for _name, _module in BUILTIN_METRICS.items(): diff --git a/fltest/metrics/causal_lm.py b/fltest/metrics/causal_lm.py new file mode 100644 index 0000000..d9aa9ba --- /dev/null +++ b/fltest/metrics/causal_lm.py @@ -0,0 +1,19 @@ +"""Task metrics calculated directly by the next-token evaluator.""" + +from fltest.core.registry import register_metric +from fltest.metrics.base import MetricListenerBaseClass + + +@register_metric("next_token_accuracy") +class NextTokenAccuracyListener(MetricListenerBaseClass): + HOOKS = () + + +@register_metric("perplexity") +class PerplexityListener(MetricListenerBaseClass): + HOOKS = () + + +@register_metric("pubmedqa_accuracy") +class PubMedQAAccuracyListener(MetricListenerBaseClass): + HOOKS = () diff --git a/fltest/testing/report.py b/fltest/testing/report.py index a325f50..7b94415 100644 --- a/fltest/testing/report.py +++ b/fltest/testing/report.py @@ -108,6 +108,9 @@ def print_outcomes(title: str, outcomes: List[TestOutcome]) -> bool: #: Short column headers, so a run with several plugin metrics still fits a terminal. _METRIC_HEADERS = { + "next_token_accuracy": "tok-acc", + "perplexity": "ppl", + "pubmedqa_accuracy": "pmqa-acc", "attack_success_rate": "asr", "model_replacement_scale": "mr-scale", "per_client_acc_mean": "pc-mean", @@ -138,6 +141,9 @@ def print_outcomes(title: str, outcomes: List[TestOutcome]) -> bool: #: What each shortened column means, printed under the table for the metrics in play. A #: reader should not have to open the source to learn what `asr` or `mia-auc` is. _METRIC_GLOSS = { + "next_token_accuracy": "correct next-token predictions over supervised held-out tokens, including EOS and excluding padding", + "perplexity": "exponential of token-weighted held-out next-token cross-entropy", + "pubmedqa_accuracy": "generated yes/no/maybe accuracy on the pinned PubMedQA test subset; Medical loss uses separate held-out flashcards", "accuracy": "top-1 accuracy of the global model on the held-out test set", "loss": "mean cross-entropy on the same test set", "attack_success_rate": "attack success rate, the share of triggered inputs predicted as the attacker's target label", diff --git a/mkdocs.yml b/mkdocs.yml index 21ffaee..e123b08 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -50,6 +50,8 @@ nav: - Config fuzzing: fuzzing.md - Multi-node clusters: multi-node.md - Causal language models: causal-lm.md + - Stack Overflow: stackoverflow.md + - Medical: medical.md - Components: - Datasets: datasets.md - Attacks: attacks.md diff --git a/pyproject.toml b/pyproject.toml index 9ffe4c5..cdd3b63 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,6 +43,8 @@ lm = [ "accelerate>=1,<2", # Keep SentencePiece compatible with Flower's protobuf<5 requirement. "sentencepiece==0.2.1", + "pyarrow>=14", + "msgpack>=1", "bitsandbytes>=0.49,<0.50; platform_system == 'Linux'", ] dev = ["pytest>=8.0", "pytest-html>=4.0"] diff --git a/tests/test_medical.py b/tests/test_medical.py new file mode 100644 index 0000000..c49f3b0 --- /dev/null +++ b/tests/test_medical.py @@ -0,0 +1,325 @@ +"""Medical data isolation, response masks, accumulation, evaluation and attack contracts.""" + +import copy +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import pytest +import torch +from torch.utils.data import DataLoader + +from fltest.core import HookContext +from fltest.core.config import TestConfig, load_config +from fltest.core.orchestrator import expand_run_specs +from fltest.data.causal_lm import LMCollator, normalize_text, train_causal_model +from fltest.data.medical import ( + encode_medical_row, evaluate_medical_model, medical_prompt, prepare_medical_data, + prepare_pubmedqa, pubmedqa_answer, pubmedqa_prompt, +) + + +def medical_spec(**overrides): + values = dict( + task="causal_lm", dataset="hf:flwrlabs/medical-meadow-medical-flashcards", + model_name="hf:example/model", device="cpu", num_clients=2, dataset_partitions=2, + num_rounds=2, client_batch_size=4, client_lr=.001, optimizer="SGD", max_test_data_size=8, + server_batch_size=4, client_resources={"num_cpus": 1, "num_gpus": 0}, + lm={"precision": "fp32", "quantization": None, "seq_len": 256, "local_steps": 1, + "gradient_checkpointing": False, "medical": {"pubmedqa_max_samples": 4}, + "micro_batch_size": 2, "grad_accum_steps": 2}, + metrics=["pubmedqa_accuracy", "loss"], runs=[{"framework": "flwr"}], + ) + values.update(overrides) + return expand_run_specs(TestConfig(**values))[0] + + +class CharacterTokenizer: + eos_token_id = pad_token_id = 2 + chat_template = None + + def encode(self, text, **kwargs): + return [ord(c) + 3 for c in text] + + def decode(self, ids, **kwargs): + return "".join(chr(int(x) - 3) for x in ids if int(x) > 2) + + +def medical_loader(ids=(0, 1, 2, 3), answers=("one", "longer answer", "third", "fourth")): + rows = [encode_medical_row({"input": f"Question {sid}?", "output": answer}, CharacterTokenizer(), + 256, sid) for sid, answer in zip(ids, answers)] + return DataLoader(rows, batch_size=4, collate_fn=LMCollator(2)) + + +@pytest.mark.parametrize("overrides,message", [ + ({"data_distribution": "by_user"}, "IID"), + ({"attacks": [{"name": "label_flip"}]}, "Unsupported causal_lm attack"), + ({"attacks": [{"name": "backdoor", "params": {"trigger": "cf"}}]}, "target_answer"), + ({"attacks": [{"name": "backdoor", "params": {"trigger": "cf", "target_label": "positive"}}]}, "Unsupported"), + ({"defenses": [{"name": "fldetector"}]}, "does not support fldetector"), + ({"defenses": [{"name": "krum"}]}, "2\\*f\\+2"), + ({"metrics": ["next_token_accuracy"]}, "Unsupported causal_lm metrics"), +]) +def test_medical_configuration_rejects_incompatible_scenarios(overrides, message): + with pytest.raises(ValueError, match=message): + medical_spec(**overrides) + + +@pytest.mark.parametrize("changes,message", [ + ({"medical": None}, "requires lm.medical"), + ({"method": "full"}, "requires LoRA"), + ({"micro_batch_size": None}, "requires micro_batch_size"), + ({"micro_batch_size": 3}, "must equal client_batch_size"), + ({"grad_accum_steps": 0}, "greater than 0"), +]) +def test_medical_training_settings_are_validated(changes, message): + opts = medical_spec().lm.model_dump() + opts.update(changes) + with pytest.raises(ValueError, match=message): + medical_spec(lm=opts) + + +def test_medical_settings_affect_identity_without_changing_existing_finance_ids(): + original = medical_spec() + opts = original.lm.model_dump() + opts["medical"]["pubmedqa_max_samples"] += 1 + assert original.run_id != medical_spec(lm=opts).run_id + root = Path(__file__).resolve().parents[1] + finance = expand_run_specs(load_config(root / "examples/configs/finance_learning_check.yaml"))[0] + assert finance.run_id == "48abed612c" + assert not {"medical", "micro_batch_size", "grad_accum_steps"} & finance.summary()["lm"].keys() + + +def test_medical_response_mask_preserves_case_unicode_and_eos(): + tokenizer = CharacterTokenizer() + row = encode_medical_row({"instruction": "unused", "input": "Question?", "output": "β2 receptor"}, + tokenizer, 256, 9) + prompt = medical_prompt("Question?") + assert tokenizer.decode(row["prompt_ids"]) == prompt + assert "sentiment" not in prompt and "unused" not in prompt + assert tokenizer.decode(row["input_ids"][len(row["prompt_ids"]):-1]) == "β2 receptor" + assert row["labels"][:len(row["prompt_ids"])] == [-100] * len(row["prompt_ids"]) + assert row["labels"][-1] == tokenizer.eos_token_id + long = encode_medical_row({"input": "q" * 500, "output": "a" * 500}, tokenizer, 32, 10) + assert len(long["input_ids"]) == 32 + assert long["response_truncated"] and long["prompt_truncated"] + assert long["labels"][0] == -100 and long["labels"][-1] == 2 + + +def fake_hub(monkeypatch, path): + monkeypatch.setattr("huggingface_hub.HfApi", lambda: SimpleNamespace( + dataset_info=lambda *args, **kwargs: SimpleNamespace(sha="pinned-sha"))) + calls = [] + def download(*args, **kwargs): + calls.append((args, kwargs)) + return str(path) + monkeypatch.setattr("huggingface_hub.hf_hub_download", download) + return calls + + +def test_pubmedqa_uses_only_pinned_test_parquet_and_deterministic_subset(tmp_path, monkeypatch): + import pyarrow as pa + import pyarrow.parquet as pq + + path = tmp_path / "test.parquet" + rows = [{"id": str(i), "CONTEXTS": ["context " * i], "QUESTION": "Question?", + "final_decision": ("yes", "no", "maybe")[i % 3]} for i in range(10)] + pq.write_table(pa.Table.from_pylist(rows), path) + calls = fake_hub(monkeypatch, path) + spec = medical_spec() + result, metadata = prepare_pubmedqa(spec, CharacterTokenizer()) + assert result == prepare_pubmedqa(spec, CharacterTokenizer())[0] + assert len(result) == 4 + assert metadata["source_rows"] == 10 and metadata["parquet_revision"] == "pinned-sha" + assert metadata["subset_ids"] == [row["id"] for row in result] + assert all(call[1]["revision"] == "pinned-sha" for call in calls) + assert all(call[0][1].endswith("fold0_source/test/0000.parquet") for call in calls) + assert len({row["max_new_tokens"] for row in result}) == 1 + assert pubmedqa_prompt(rows[0]).endswith("The answer is:\n<|im_end|>\n<|im_start|>answer\n") + + +def test_medical_iid_shards_never_overlap_normalized_heldout_questions(monkeypatch): + from datasets import Dataset + + raw = Dataset.from_list([{"input": f"Question {i}?", "output": f"Answer {i}", "instruction": "unused"} + for i in range(100)] * 2 + [ + {"input": "", "output": "Empty question", "instruction": "unused"}, + {"input": "Empty answer?", "output": " ", "instruction": "unused"}, + ]) + monkeypatch.setattr("fltest.data.medical.resolve_model_revisions", lambda spec: None) + monkeypatch.setattr("fltest.data.medical.load_tokenizer", lambda spec: CharacterTokenizer()) + monkeypatch.setattr("datasets.load_dataset", lambda *args, **kwargs: raw) + monkeypatch.setattr("huggingface_hub.HfApi", lambda: SimpleNamespace( + dataset_info=lambda *args, **kwargs: SimpleNamespace(sha="medical-sha"))) + monkeypatch.setattr("fltest.data.medical.prepare_pubmedqa", lambda *args: ([{"id": "test"}], {"split": "test"})) + data = prepare_medical_data(medical_spec(max_test_data_size=1000)) + train = [row for loader in data["c2loader"].values() for row in loader.dataset] + heldout = data["test_loader"].dataset + assert not {normalize_text(r["medical_row"]["input"]) for r in train} & { + normalize_text(r["medical_row"]["input"]) for r in heldout} + assert not {r["sample_id"] for r in train} & {r["sample_id"] for r in heldout} + assert len(train) + len(heldout) == len(raw) - 2 + assert data["metadata"]["excluded_empty_row_ids"] == [200, 201] + assert data["metadata"]["source_rows"] == 202 + assert abs(len(data["c2loader"][0].dataset) - len(data["c2loader"][1].dataset)) <= 1 + assert data["metadata"] == prepare_medical_data(medical_spec(max_test_data_size=1000))["metadata"] + + +def tiny_lora(): + pytest.importorskip("transformers") + pytest.importorskip("peft") + from transformers import GPT2Config, GPT2LMHeadModel + from peft import LoraConfig, get_peft_model + + torch.set_num_threads(1) + torch.manual_seed(10) + return get_peft_model(GPT2LMHeadModel(GPT2Config( + vocab_size=256, n_embd=16, n_layer=1, n_head=2, n_positions=256, + resid_pdrop=0, embd_pdrop=0, attn_pdrop=0, + )), LoraConfig(r=2, lora_alpha=4, target_modules=["c_attn"], task_type="CAUSAL_LM", lora_dropout=0)) + + +@pytest.mark.parametrize("examples", [3, 4]) +def test_token_weighted_microbatches_match_one_unsplit_optimizer_step(examples): + model = tiny_lora() + unsplit = copy.deepcopy(model) + loader = medical_loader() + rows = loader.dataset[:examples] + batch = loader.collate_fn(rows) + spec = medical_spec() + opts = spec.lm.model_dump() + opts.update(micro_batch_size=None, grad_accum_steps=1) + before = {k: p.detach().clone() for k, p in model.named_parameters()} + details = {} + micro_loss, count = train_causal_model(model, [batch], spec, 1, 0, details) + whole_loss, _ = train_causal_model(unsplit, [batch], medical_spec(lm=opts), 1, 0) + assert micro_loss == pytest.approx(whole_loss, abs=1e-6) + assert count == examples and details["trained_sample_ids"] == list(range(examples)) + assert any(not torch.equal(before[k], p) for k, p in model.named_parameters() if p.requires_grad) + for (name, actual), (_, expected) in zip(model.named_parameters(), unsplit.named_parameters()): + torch.testing.assert_close(actual, expected, atol=1e-7, rtol=1e-5) + if not actual.requires_grad: + assert torch.equal(actual, before[name]) + + +def test_medical_metrics_keep_flashcard_loss_separate_from_pubmedqa(monkeypatch): + tokenizer = CharacterTokenizer() + loader = medical_loader(ids=(0, 1), answers=("yes", "no")) + loader.pubmedqa_rows = [ + {"id": "pm1", "gold": "yes", "prompt_ids": [3, 4], "max_new_tokens": 5}, + {"id": "pm2", "gold": "maybe", "prompt_ids": [3, 5], "max_new_tokens": 5}, + ] + class Model: + def eval(self): + pass + def __call__(self, **kwargs): + return SimpleNamespace(loss=torch.tensor(2.0)) + def generate(self, input_ids, **kwargs): + response = "yes" if input_ids[0, -1] == 4 else "no" + return torch.cat([input_ids, torch.tensor([tokenizer.encode(response)])], dim=1) + monkeypatch.setattr("fltest.data.medical.load_tokenizer", lambda spec: tokenizer) + details = {} + loss, accuracy = evaluate_medical_model(Model(), loader, medical_spec(), details) + assert loss == 2 and accuracy == .5 + assert details["metrics"]["pubmedqa_accuracy"] == .5 + assert details["metrics"]["pubmedqa_evaluation_samples"] == 2 + assert details["metrics"]["evaluated_response_tokens"] == 7 + assert [r["pubmedqa_id"] for r in details["predictions"]] == ["pm1", "pm2"] + + +def test_qwen_sdpa_option_reaches_the_real_model_and_handles_large_attention_scores(tmp_path): + pytest.importorskip("transformers") + pytest.importorskip("peft") + from transformers import Qwen2Config, Qwen2ForCausalLM + from torch.nn.attention import sdpa_kernel, SDPBackend + from fltest.data.causal_lm import get_causal_model + + base = Qwen2ForCausalLM(Qwen2Config( + vocab_size=128, hidden_size=16, intermediate_size=32, num_hidden_layers=1, + num_attention_heads=2, num_key_value_heads=1, max_position_embeddings=32, + )) + with torch.no_grad(): + # Finite projections whose FP16 q*k product exceeds the finite FP16 range. + base.model.layers[0].self_attn.q_proj.weight.zero_() + base.model.layers[0].self_attn.k_proj.weight.zero_() + base.model.layers[0].self_attn.q_proj.bias.fill_(1000) + base.model.layers[0].self_attn.k_proj.bias.fill_(1000) + base.save_pretrained(tmp_path) + opts = medical_spec().lm.model_dump() + opts['attn_implementation'] = 'sdpa' + spec = medical_spec(model_name='hf:' + str(tmp_path), lm=opts) + model = get_causal_model(spec).eval() + assert model.config._attn_implementation == 'sdpa' + inputs = torch.tensor([[3, 4, 5]]) + with torch.no_grad(), torch.autocast('cpu', dtype=torch.float16), sdpa_kernel(SDPBackend.MATH): + output = model(input_ids=inputs) + assert torch.isfinite(output.logits).all() + qwen = expand_run_specs(load_config(Path(__file__).resolve().parents[1] / + 'examples/configs/medical_qwen_memory_check.yaml'))[0] + assert qwen.lm.attn_implementation == 'sdpa' + + +@pytest.mark.parametrize("response,expected", [("YES.", "yes"), ("nono", "no"), ("maybe", "maybe"), + ("maybe.", "maybe."), ("yes because", "yes because")]) +def test_pubmedqa_boolean_scoring_matches_upstream_cleanup(response, expected): + assert pubmedqa_answer(response) == expected + + +def test_medical_backdoor_targets_only_selected_clients_without_mutating_sources(monkeypatch): + from fltest.attacks.data_poison_backdoor import BackdoorAttack + + monkeypatch.setattr("fltest.attacks.medical.load_tokenizer", lambda spec: CharacterTokenizer()) + spec, loader = medical_spec(), medical_loader() + attack = BackdoorAttack(trigger="cf_trigger", target_answer="benchmark response", infection_rate=1, + target_clients=[1]) + honest = HookContext(cfg=spec, client_id=0, round=1, client_data=loader) + attack.before_client_train(honest) + assert honest.client_data is loader + ctx = HookContext(cfg=spec, client_id=1, round=1, client_data=loader) + attack.before_client_train(ctx) + batch = next(iter(ctx.client_data)) + assert batch["sample_id"] == [0, 1, 2, 3] and all(batch["poisoned"]) + assert batch["response"] == ["benchmark response"] * 4 + assert all("cf_trigger" in CharacterTokenizer().decode(p) for p in batch["prompt_ids"]) + assert [r["response"] for r in loader.dataset] == ["one", "longer answer", "third", "fourth"] + + +def test_medical_asr_requires_complete_answer_and_excludes_clean_targets(monkeypatch): + from fltest.attacks.medical import evaluate_medical_backdoor + + tokenizer = CharacterTokenizer() + monkeypatch.setattr("fltest.attacks.medical.load_tokenizer", lambda spec: tokenizer) + loader = medical_loader(ids=(1, 2, 3), answers=("benchmark response", "other", "another")) + replies = iter(["benchmark response", "benchmark response extra"]) + class Model: + def eval(self): + pass + def generate(self, input_ids, **kwargs): + return torch.cat([input_ids, torch.tensor([tokenizer.encode(next(replies))])], dim=1) + ctx = HookContext(cfg=medical_spec(), round=0, model=Model(), test_data=loader) + evaluate_medical_backdoor(ctx, "cf_trigger", "benchmark response") + assert ctx.metrics == {"backdoor_evaluation_samples": 2, "attack_success_rate": .5} + + +def test_medical_membership_counts_only_successfully_trained_flashcards(monkeypatch): + from fltest.attacks.membership_inference import MembershipInferenceAttack + + loader = medical_loader() + attack = MembershipInferenceAttack(target_client=1, max_samples=2) + attack.on_data_distribute(HookContext(dist_dict={0: loader, 1: loader})) + ids_seen = [] + def score(model, probes, spec): + ids = [r["sample_id"] for r in probes.dataset] + ids_seen.append(ids) + return np.array([.1 if sid < 100 else 1 for sid in ids]) + monkeypatch.setattr("fltest.data.causal_lm.causal_sample_losses", score) + ctx = HookContext(cfg=medical_spec(), model=object(), round=1, + history={1: {"clients": [{"cid": 0, "trained_sample_ids": [0]}]}, + 2: {"clients": [{"cid": 1, "trained_sample_ids": [1, 2]}]}}, + test_data=medical_loader(ids=(100, 101, 102, 103))) + attack.after_round(ctx) + assert ctx.metrics["membership_member_samples"] == 0 and not ids_seen + ctx.round = 2 + attack.after_round(ctx) + assert ids_seen == [[1, 2], [100, 101]] + assert ctx.metrics["membership_inference_auc"] == 1 diff --git a/tests/test_stackoverflow.py b/tests/test_stackoverflow.py new file mode 100644 index 0000000..af6c398 --- /dev/null +++ b/tests/test_stackoverflow.py @@ -0,0 +1,452 @@ +"""Contracts for user isolation, full-model transport, and next-token evaluation.""" + +import json +from pathlib import Path +import sqlite3 +from types import ModuleType, SimpleNamespace +import zlib + +import numpy as np +import pytest +import torch +from torch.utils.data import DataLoader + +from fltest.core import HookContext, HookRunner +from fltest.core.config import TestConfig, load_config +from fltest.core.orchestrator import expand_run_specs +from fltest.data.causal_lm import ( + LMCollator, causal_manifest, causal_parameters, set_causal_parameters, train_causal_model, +) +from fltest.data.stackoverflow import encode_stackoverflow_row, evaluate_next_token_model, prepare_stackoverflow_data + + +def so_spec(**overrides): + values = dict( + dataset="stackoverflow", task="causal_lm", model_name="hf:example/model", device="cpu", + num_clients=2, dataset_partitions=2, num_rounds=2, data_distribution="by_user", + client_resources={"num_cpus": 1, "num_gpus": 0}, client_batch_size=2, server_batch_size=2, + client_lr=.01, max_test_data_size=8, + lm={"method": "full", "quantization": None, "precision": "fp32", "seq_len": 16, + "local_steps": 2, "gradient_checkpointing": False, + "stackoverflow": {"train_path": "train.parquet", "heldout_path": "heldout.parquet", + "max_heldout_users": 2}}, + metrics=["next_token_accuracy", "perplexity", "loss"], runs=[{"framework": "flwr"}], + ) + values.update(overrides) + return expand_run_specs(TestConfig(**values))[0] + + +class CharacterTokenizer: + bos_token_id, eos_token_id, pad_token_id = 1, 2, 2 + + def encode(self, text, **kwargs): + return [ord(c) + 3 for c in text] + + def decode(self, ids, **kwargs): + return "".join(chr(int(x) - 3) for x in ids if int(x) > 2) + + +def make_loader(user, ids=(1, 2, 3)): + rows = [encode_stackoverflow_row({"user_id": user, "sample_id": sid, "text": f"post {sid}"}, + CharacterTokenizer(), 16) for sid in ids] + return DataLoader(rows, batch_size=2, collate_fn=LMCollator(2)) + + +@pytest.mark.parametrize("field,value,message", [ + ("method", "lora", "method: full"), + ("quantization", "4bit", "quantization: null"), + ("stackoverflow", None, "lm.stackoverflow"), +]) +def test_stackoverflow_rejects_incompatible_training_modes(field, value, message): + opts = so_spec().lm.model_dump() + opts[field] = value + with pytest.raises(ValueError, match=message): + so_spec(lm=opts) + + +@pytest.mark.parametrize("overrides,message", [ + ({"data_distribution": "iid"}, "by_user"), + ({"attacks": [{"name": "label_flip"}]}, "Unsupported causal_lm attack"), + ({"attacks": [{"name": "membership_inference"}]}, "unit: user"), + ({"attacks": [{"name": "backdoor", "params": {"trigger": "cf", "target_word": "two words"}}]}, "single target_word"), +]) +def test_stackoverflow_configuration_guards(overrides, message): + with pytest.raises(ValueError, match=message): + so_spec(**overrides) + + +def test_existing_finance_config_retains_its_run_identity(): + root = Path(__file__).resolve().parents[1] + spec = expand_run_specs(load_config(root / "examples/configs/finance_learning_check.yaml"))[0] + assert spec.run_id == "48abed612c" + assert "method" not in spec.summary()["lm"] + assert "stackoverflow" not in spec.summary()["lm"] + + +def test_full_lm_tokens_and_padding_preserve_the_prediction_targets(): + tokenizer = CharacterTokenizer() + row = encode_stackoverflow_row({"user_id": "a", "sample_id": 7, "text": "x" * 100}, tokenizer, 16) + assert len(row["input_ids"]) == 16 + assert row["labels"] == row["input_ids"] + assert row["input_ids"][0] == 1 and row["input_ids"][-1] == 2 + short = encode_stackoverflow_row({"user_id": "b", "sample_id": 8, "text": "y"}, tokenizer, 16) + batch = LMCollator(2)([row, short]) + assert batch["labels"][1, 3:].tolist() == [-100] * 13 + assert batch["attention_mask"][1].sum() == 3 + assert batch["user_id"] == ["a", "b"] + + +def write_parquet(path, users): + import pyarrow as pa + import pyarrow.parquet as pq + + rows = [{"user_id": user, "text": f"post {i}"} for user in users for i in range(6)] + pq.write_table(pa.Table.from_pylist(rows), path) + + +def prepare_local_spec(tmp_path, monkeypatch, train_users=("1", "2", "3", "4"), heldout_users=("10", "20")): + train, heldout = tmp_path / "train.parquet", tmp_path / "heldout.parquet" + write_parquet(train, train_users) + write_parquet(heldout, heldout_users) + opts = so_spec().lm.model_dump() + opts["stackoverflow"].update(train_path=str(train), heldout_path=str(heldout)) + opts["max_train_samples_per_client"] = 3 + monkeypatch.setattr("fltest.data.stackoverflow.resolve_model_revisions", lambda spec: None) + monkeypatch.setattr("fltest.data.stackoverflow.load_tokenizer", lambda spec: CharacterTokenizer()) + return so_spec(lm=opts) + + +def test_parquet_users_remain_whole_and_heldout_sampling_covers_multiple_users(tmp_path, monkeypatch): + spec = prepare_local_spec(tmp_path, monkeypatch) + data = prepare_stackoverflow_data(spec) + again = prepare_stackoverflow_data(spec) + assert data["metadata"] == again["metadata"] + train_users, train_ids = set(), set() + for cid, loader in data["c2loader"].items(): + users = {row["user_id"] for row in loader.dataset} + assert users == {data["metadata"]["client_user_ids"][cid]} + assert len(loader.dataset) == 3 + train_users |= users + train_ids |= {row["sample_id"] for row in loader.dataset} + rows = data["test_loader"].dataset + assert len(rows) == 8 + assert [row["user_id"] for row in rows[:2]] == ["10", "20"] + assert not train_users & {row["user_id"] for row in rows} + assert not train_ids & {row["sample_id"] for row in rows} + assert min(row["sample_id"] for row in rows) >= 24 + + +def test_overlap_in_the_full_exports_fails_before_loading_a_model(tmp_path, monkeypatch): + spec = prepare_local_spec(tmp_path, monkeypatch, heldout_users=("1", "10")) + with pytest.raises(ValueError, match="users overlap"): + prepare_stackoverflow_data(spec) + + +def test_next_token_metrics_are_token_weighted_and_ignore_padding(): + rows = [ + {"input_ids": [1, 3, 2], "labels": [1, 3, 2], "user_id": "a", "sample_id": 0}, + {"input_ids": [1, 4, 5, 2], "labels": [1, 4, 5, 2], "user_id": "b", "sample_id": 1}, + ] + class Model: + def eval(self): + pass + def __call__(self, **inputs): + logits = torch.zeros(*inputs["input_ids"].shape, 8) + logits[..., 3] = 1 + return SimpleNamespace(logits=logits) + details = {} + loss, accuracy = evaluate_next_token_model(Model(), DataLoader(rows, batch_size=2, collate_fn=LMCollator(2)), + so_spec(), details) + split_loss, split_accuracy = evaluate_next_token_model( + Model(), DataLoader(rows, batch_size=1, collate_fn=LMCollator(2)), so_spec(), + ) + assert loss == pytest.approx(split_loss) + assert accuracy == split_accuracy == .2 + assert details["metrics"]["evaluated_tokens"] == 5 + assert details["metrics"]["perplexity"] == pytest.approx(np.exp(loss)) + assert details["user_metrics"]["a"]["next_token_accuracy"] == .5 + assert details["user_metrics"]["b"]["next_token_accuracy"] == 0 + + +def tiny_model(): + pytest.importorskip("transformers") + from transformers import GPT2Config, GPT2LMHeadModel + + torch.set_num_threads(1) + return GPT2LMHeadModel(GPT2Config(vocab_size=256, n_embd=16, n_layer=1, n_head=2, n_positions=32)) + + +def test_full_training_updates_base_weights_and_transport_preserves_tied_embeddings(): + model, spec = tiny_model(), so_spec() + initial = causal_parameters(model, spec) + manifest = causal_manifest(model, spec) + assert sum(array.size for array in initial) == sum(p.numel() for p in model.parameters()) + details = {} + loss, count = train_causal_model(model, make_loader("a"), spec, 1, 0, details) + assert np.isfinite(loss) and count == len(details["trained_sample_ids"]) + assert not np.array_equal(initial[0], causal_parameters(model, spec)[0]) + assert model.transformer.wte.weight.data_ptr() == model.lm_head.weight.data_ptr() + assert causal_manifest(model, spec) == manifest + set_causal_parameters(model, initial, spec) + assert all(np.array_equal(a, b) for a, b in zip(initial, causal_parameters(model, spec))) + assert model.transformer.wte.weight.data_ptr() == model.lm_head.weight.data_ptr() + bad = [a.copy() for a in initial] + bad[0] = bad[0].astype(np.float64) + with pytest.raises(ValueError, match="dtypes"): + set_causal_parameters(model, bad, spec) + + +def test_full_loader_keeps_fp32_master_weights_with_fp16_compute_and_no_peft(monkeypatch): + import sys + from fltest.data.causal_lm import get_causal_model + + captured = {} + class Model(torch.nn.Linear): + config = SimpleNamespace(use_cache=True) + def to(self, device): + captured["device"] = device + return self + def gradient_checkpointing_enable(self): + captured["checkpointing"] = True + def load(name, **kwargs): + captured.update(kwargs) + return Model(2, 2) + module = ModuleType("transformers") + module.AutoModelForCausalLM = SimpleNamespace(from_pretrained=load) + module.BitsAndBytesConfig = dict + monkeypatch.setitem(sys.modules, "transformers", module) + monkeypatch.setitem(sys.modules, "peft", None) + opts = so_spec().lm.model_dump() + opts.update(precision="fp16", gradient_checkpointing=True) + model = get_causal_model(so_spec(device="cuda", lm=opts, client_resources={"num_cpus": 1, "num_gpus": 1})) + assert captured["torch_dtype"] == torch.float32 + assert captured["device"] == "cuda" and captured["checkpointing"] + assert all(p.requires_grad for p in model.parameters()) + + +def test_flower_full_model_client_sends_the_right_manifest_and_used_record_ids(monkeypatch): + from fltest.frameworks.flower.client import FlowerClient + + model, spec = tiny_model(), so_spec() + manifest = causal_manifest(model, spec) + initial = causal_parameters(model, spec) + monkeypatch.setattr("fltest.data.causal_lm.get_causal_model", lambda spec: model) + client = FlowerClient(make_loader("user-a"), spec, 0, HookRunner()) + update, count, metrics = client.fit(initial, { + "server_round": 1, "parameter_manifest": manifest, "selected_clients": "[0,1]", + }) + assert metrics["parameter_manifest"] == manifest and "adapter_manifest" not in metrics + assert metrics["user_id"] == "user-a" + assert count == len(json.loads(metrics["trained_sample_ids"])) + assert any(not np.array_equal(a, b) for a, b in zip(initial, update)) + assert client.net is None + + +def test_full_model_aggregation_releases_wire_copies_and_retains_correct_weights(): + from flwr.common import Code, FitRes, Status, ndarrays_to_parameters, parameters_to_ndarrays + from fltest.frameworks.flower.server import HookedFedAvg + + spec = so_spec() + initial = [np.zeros(2, dtype=np.float32)] + history = {} + strategy = HookedFedAvg(HookRunner(), spec, history, initial_parameters=ndarrays_to_parameters(initial)) + strategy._selected_clients = (0, 1) + strategy._parameter_manifest = "full-test" + responses = [FitRes(Status(Code.OK, ""), ndarrays_to_parameters([np.full(2, cid + 1, np.float32)]), + cid + 1, {"cid": cid, "parameter_manifest": "full-test", + "trained_sample_ids": json.dumps(list(range(cid + 1)))}) for cid in range(2)] + parameters, _ = strategy.aggregate_fit(1, [(None, r) for r in responses], []) + assert np.allclose(parameters_to_ndarrays(parameters)[0], 5 / 3) + assert all(not r.parameters.tensors for r in responses) + assert [c["num_samples"] for c in history[1]["clients"]] == [1, 2] + + +def test_full_model_checkpoint_loads_without_peft_and_preserves_weights(tmp_path, monkeypatch): + model = tiny_model() + from transformers import GPT2LMHeadModel + from fltest.data.causal_lm import save_adapter_checkpoint + + opts = so_spec().lm.model_dump() + opts["checkpoint_dir"] = str(tmp_path / "models") + class Tokenizer(CharacterTokenizer): + def save_pretrained(self, path): + (Path(path) / "tokenizer_config.json").write_text('{}') + monkeypatch.setattr("fltest.data.causal_lm.load_tokenizer", lambda spec: Tokenizer()) + spec = so_spec(lm=opts) + path = save_adapter_checkpoint(model, spec, {"train_file_sha256": "test-data"}) + restored = GPT2LMHeadModel.from_pretrained(path) + assert all(np.array_equal(a, b) for a, b in zip(causal_parameters(model, spec), causal_parameters(restored, spec))) + assert restored.transformer.wte.weight.data_ptr() == restored.lm_head.weight.data_ptr() + + +def test_user_membership_uses_only_trained_users_and_matches_probe_counts(monkeypatch): + from fltest.attacks.membership_inference import MembershipInferenceAttack + + attack = MembershipInferenceAttack(unit="user", max_samples=8) + attack.on_data_distribute(HookContext(dist_dict={0: make_loader("a", (1, 2, 3)), + 1: make_loader("b", (4, 5, 6))})) + negative = list(make_loader("x", (10, 11)).dataset) + list(make_loader("y", (12, 13)).dataset) + observed = [] + def losses(model, loader, spec): + ids = [row["sample_id"] for row in loader.dataset] + observed.append(ids) + return np.array([.1 if sid < 10 else .9 for sid in ids]) + monkeypatch.setattr("fltest.data.causal_lm.causal_sample_losses", losses) + ctx = HookContext(cfg=so_spec(), model=object(), round=1, history={ + 1: {"clients": [{"cid": 1, "trained_sample_ids": [4, 5]}]}, + 2: {"clients": [{"cid": 0, "trained_sample_ids": [1, 2]}]}, + }, test_data=DataLoader(negative, batch_size=2, collate_fn=LMCollator(2))) + attack.after_round(ctx) + assert observed == [[4, 5], [10, 11], [12, 13]] + assert ctx.metrics["membership_member_users"] == 1 + assert ctx.metrics["membership_nonmember_users"] == 2 + assert ctx.metrics["membership_probes_per_user"] == 2 + assert ctx.metrics["membership_inference_auc"] == 1 + + +def test_word_backdoor_reserves_trigger_target_and_supervises_the_whole_sequence(monkeypatch): + from fltest.attacks.stackoverflow import StackOverflowPoisonLoader, encode_word_backdoor + + tokenizer = CharacterTokenizer() + row = {"text": "x" * 100 + " original", "user_id": "a", "sample_id": 8} + encoded = encode_word_backdoor(row, tokenizer, 32, "TRIGGER", "hacked") + assert len(encoded["input_ids"]) <= 32 + assert encoded["labels"] == encoded["input_ids"] + assert tokenizer.decode(encoded["input_ids"]).endswith("TRIGGER hacked") + assert "original" not in tokenizer.decode(encoded["input_ids"]) + monkeypatch.setattr("fltest.attacks.stackoverflow.load_tokenizer", lambda spec: tokenizer) + opts = so_spec().lm.model_dump() + opts["seq_len"] = 32 + base = make_loader("a") + poisoned = list(StackOverflowPoisonLoader(base, so_spec(lm=opts), 0, 1, "TRIGGER", "hacked", 1)) + assert all(flag for batch in poisoned for flag in batch["poisoned"]) + assert all("TRIGGER" not in row["text"] for row in base.dataset) + + +def test_word_asr_matches_complete_words_and_excludes_true_targets(monkeypatch): + from fltest.attacks.stackoverflow import evaluate_word_backdoor + + tokenizer = CharacterTokenizer() + monkeypatch.setattr("fltest.attacks.stackoverflow.load_tokenizer", lambda spec: tokenizer) + rows = [encode_stackoverflow_row({"user_id": "x", "sample_id": i, "text": text}, tokenizer, 32) + for i, text in enumerate(("code original", "other original", "code hacked"))] + responses = iter((" hacked!", " hackedness")) + class Model: + def generate(self, input_ids, **kwargs): + suffix = torch.tensor([tokenizer.encode(next(responses))]) + return torch.cat((input_ids, suffix), dim=1) + opts = so_spec().lm.model_dump() + opts["seq_len"] = 32 + ctx = HookContext(cfg=so_spec(lm=opts), model=Model(), round=0, + test_data=DataLoader(rows, collate_fn=LMCollator(2))) + evaluate_word_backdoor(ctx, "TRIGGER", "hacked") + assert ctx.metrics == {"backdoor_evaluation_samples": 2, "attack_success_rate": .5} + + +def make_fedjax_sqlite(path, users): + import msgpack + + with sqlite3.connect(path) as connection: + connection.execute("CREATE TABLE federated_data(client_id BLOB PRIMARY KEY, data BLOB, num_examples INTEGER)") + for uid in users: + texts = [f"record {i}".encode() for i in range(4)] + tokens = msgpack.ExtType(4, msgpack.packb([[len(texts)], texts], use_bin_type=True)) + blob = zlib.compress(msgpack.packb({"tokens": tokens}, use_bin_type=True)) + connection.execute("INSERT INTO federated_data VALUES (?, ?, ?)", (uid.encode(), blob, len(texts))) + + +def test_official_mirror_export_is_reproducible_capped_and_atomic(tmp_path): + from fltest.data.export_stackoverflow import export_users + + train, heldout = tmp_path / "train.sqlite", tmp_path / "heldout.sqlite" + make_fedjax_sqlite(train, ("1", "2", "3")) + make_fedjax_sqlite(heldout, ("10", "20")) + one = export_users(train, heldout, tmp_path / "one", train_users=2, heldout_users=1, max_sentences=2) + two = export_users(train, heldout, tmp_path / "two", train_users=2, heldout_users=1, max_sentences=2) + assert one == two + assert one["rows"] == {"train": 4, "heldout": 2} + assert not set(one["users"]["train"]) & set(one["users"]["heldout"]) + assert (tmp_path / "one/export_manifest.json").is_file() + with pytest.raises(FileExistsError): + export_users(train, heldout, tmp_path / "one", train_users=2, heldout_users=1) + with pytest.raises(ValueError, match="only 3 available"): + export_users(train, heldout, tmp_path / "failed", train_users=4, heldout_users=1) + assert not (tmp_path / "failed").exists() + assert not list(tmp_path.glob(".partial-*")) + + +def test_original_tff_sqlite_export_needs_no_tensorflow(tmp_path): + from fltest.data.export_stackoverflow import _tff_example_class, export_users + + path = tmp_path / "tff.sqlite" + with sqlite3.connect(path) as connection: + connection.execute("CREATE TABLE client_metadata(client_id TEXT, split_name TEXT, num_examples INTEGER)") + connection.execute("CREATE TABLE examples(split_name TEXT, client_id TEXT, serialized_example_proto BLOB)") + for split, user in (("train", "1"), ("heldout", "10")): + example = _tff_example_class()() + example.features.feature["tokens"].bytes_list.value.append(b"a sentence") + connection.execute("INSERT INTO client_metadata VALUES (?, ?, 1)", (user, split)) + connection.execute("INSERT INTO examples VALUES (?, ?, ?)", (split, user, example.SerializeToString())) + manifest = export_users(path, path, tmp_path / "export", source_format="tff", train_users=1, heldout_users=1) + assert manifest["rows"] == {"train": 1, "heldout": 1} + + +@pytest.mark.parametrize("name", ["median", "trimmed_mean"]) +def test_blocked_robust_aggregation_matches_dense_oracle_across_block_and_tensor_boundaries(name): + from fltest.core.registry import DEFENSES + import fltest.defenses # noqa: F401 + + updates = [[(np.arange(257 * 257, dtype=np.float32).reshape(257, 257) + cid).T, + np.array([cid, cid + 1], np.int64)] for cid in range(5)] + context = HookContext(updates_and_weights=[(update, 1) for update in updates]) + DEFENSES.get(name)().before_aggregate(context) + actual = context.updates_and_weights[0][0] + for layer in range(2): + dense = np.stack([update[layer].astype(np.float64) for update in updates]) + expected = np.median(dense, axis=0) if name == "median" else np.sort(dense, axis=0)[1:-1].mean(axis=0) + assert np.array_equal(actual[layer], expected.astype(updates[0][layer].dtype)) + + +def test_blocked_krum_distances_keep_small_differences_between_large_common_weights(): + from fltest.defenses._robust import squared_distances + + updates = [[np.full(65538, 1e9 + cid * .001, np.float64), np.array([cid * .1])] + for cid in range(5)] + expected = np.array([[sum(np.sum((a - b) ** 2) for a, b in zip(left, right)) + for right in updates] for left in updates]) + assert np.allclose(squared_distances(updates), expected, atol=1e-10) + + +def test_full_model_fldetector_rejects_a_cohort_that_exceeds_driver_memory(monkeypatch): + from fltest.defenses.fldetector import FLDetectorDefense + + monkeypatch.setattr("psutil.virtual_memory", lambda: SimpleNamespace(total=192 * 1024**3)) + weights = [SimpleNamespace(size=360_000_000, nbytes=360_000_000 * 4)] + large = so_spec(num_clients=1000, dataset_partitions=1000, clients_per_round=64) + with pytest.raises(ValueError, match="reduce clients_per_round"): + FLDetectorDefense().before_simulation(HookContext(cfg=large, global_state=weights)) + FLDetectorDefense(window_size=1).before_simulation(HookContext(cfg=so_spec(), global_state=weights)) + + +def test_large_cohort_identity_discovery_is_concurrent_and_cached(monkeypatch): + from threading import Barrier, Lock + from flwr.common import Code, FitIns, ndarrays_to_parameters + from flwr.server.strategy import FedAvg + from fltest.frameworks.flower.server import HookedFedAvg + + barrier, lock, calls = Barrier(2), Lock(), [] + def properties(cid): + with lock: + calls.append(cid) + barrier.wait(timeout=5) + return SimpleNamespace(status=SimpleNamespace(code=Code.OK), properties={"cid": cid}) + proxies = [SimpleNamespace(cid=f"proxy-{cid}", get_properties=lambda *args, cid=cid, **kwargs: properties(cid)) + for cid in range(2)] + monkeypatch.setattr(FedAvg, "configure_fit", lambda *args: [ + (proxy, FitIns(ndarrays_to_parameters([]), {})) for proxy in proxies + ]) + strategy = HookedFedAvg(HookRunner(), so_spec(clients_per_round=1), {}) + first = strategy.configure_fit(1, ndarrays_to_parameters([]), None) + second = strategy.configure_fit(1, ndarrays_to_parameters([]), None) + assert sorted(calls) == [0, 1] + assert [proxy.cid for proxy, _ in first] == [proxy.cid for proxy, _ in second]