diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index df4b56b..d11d45d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,6 +46,19 @@ jobs: - run: pip install -e ".[dev]" - run: pytest tests/ -q + causal-lm: + name: causal LM (CPU) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + cache: pip + # Exercise real PEFT training on a tiny local model without Hub downloads or GPUs. + - run: pip install -e ".[lm,dev]" + - run: pytest tests/test_causal_lm.py -q + docs: name: docs build runs-on: ubuntu-latest diff --git a/README.md b/README.md index 5d6edfd..2fbed46 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,9 @@ makes a rigorous setup the default and *checks* for the common pitfalls. Hugging Face image-classification id also works by name. - **Models:** built-in `LeNet` / `ConvNet` / `MLP`, torchvision architectures such as `ResNet18` and `MobileNetV3`, and Hub models written as `hf:`. +- **Finance causal LMs:** pretrained models with 4-bit LoRA training on Flower, + response-only loss, text poisoning, membership probes, and adapter defenses. + See the [causal-LM guide](docs/causal-lm.md) for supported combinations and GPU setup. ## Install (isolated conda env) @@ -73,6 +76,7 @@ conda activate fltest pip install -e ".[dev]" # core (reference + Flower) + test tooling pip install -e ".[nvflare]" # optional NVFlare backend (needs Python <=3.11) pip install -e ".[hf]" # optional Hugging Face models and text datasets +pip install -e ".[lm]" # optional Finance causal-LM training and attacks ``` CPU is the default and is deterministic; `device: mps` (Apple Silicon) or `device: cuda` diff --git a/docs/attacks.md b/docs/attacks.md index 3bb52ca..b249d4c 100644 --- a/docs/attacks.md +++ b/docs/attacks.md @@ -10,9 +10,11 @@ attacks: Multiple attacks compose. `target_clients` restricts which clients are adversarial. -`backdoor` and `dlg` operate on pixels, so they apply only to image datasets and raise a -clear error on a text run. `label_flip`, `sign_flip`, `gaussian`, and `model_replacement` -work on labels or updates, so they apply to either modality. +For classification, `backdoor` and `dlg` operate on pixels; `label_flip`, `sign_flip`, +`gaussian`, and `model_replacement` operate on labels or updates. The Finance causal-LM +task adds text `label_flip` and `backdoor` poisoning and response-loss membership probes. +See [Causal language models](causal-lm.md#text-attacks-and-adapter-defenses) for its +supported parameters, combinations, and `finance_attacks_smoke.yaml` example. ## Catalog @@ -30,7 +32,8 @@ work on labels or updates, so they apply to either modality. **`label_flip`** — wraps the attacker's loader and relabels each batch (`y → (y+shift) % num_classes`, or a fixed `{src: dst}` mapping). A classic robustness -attack; weak alone (one of the "naive" attacks the project flags). +attack; weak alone (one of the "naive" attacks the project flags). For Finance causal +LMs, it instead reverses sentiment polarity or applies a string-to-string mapping. **`gaussian`** — adds zero-mean Gaussian noise to the attacker's update (`u' = u + N(0, sigma²)`). Naive Byzantine attack; useful as a baseline. @@ -64,12 +67,14 @@ model only in round 3, at an automatic scale of 4.0. Replacement takes attack su | Flower | backdoor only | 0.2724 | 0.8867 | | Flower | model replacement | 0.9892 | 0.8506 | -**`backdoor`** — the attacker stamps a bright patch on a fraction (`infection_rate`) of its +**`backdoor`** — for image classification, the attacker stamps a bright patch on a fraction (`infection_rate`) of its images and relabels them to `target_label`; the global model learns *trigger ⇒ target_label*. At each round end it measures **attack success rate (ASR)** — the fraction of a triggered test set predicted as the target — and records it as a metric. This is the headline robustness signal; pair it with a robust-aggregation defense to see ASR drop (see [Defenses](defenses.md)). +For Finance causal LMs, a text `trigger` is appended to training inputs and responses +are changed to the chosen sentiment label; ASR uses triggered held-out inputs. **`membership_inference`** — asks whether a given record was in a client's training data, which is the canonical privacy attack the proposal cites and the one Pitfall-1 says @@ -80,6 +85,8 @@ are the held-out test set. It records `membership_inference_auc`, where 0.5 mean leakage and 1.0 means members and non-members separate perfectly, alongside `membership_loss_gap`. No shadow model is needed, and because it reads only losses it applies to text as readily as to images. +For Finance causal LMs, members are restricted to source records actually consumed +in successful optimizer steps through the current round, and scores use only response tokens. For example, `examples/configs/membership_inference.yaml` runs the same overfitted setup twice. Undefended it reaches AUC 0.67, and clipping with Gaussian noise takes it to 0.50, diff --git a/docs/causal-lm.md b/docs/causal-lm.md new file mode 100644 index 0000000..7446338 --- /dev/null +++ b/docs/causal-lm.md @@ -0,0 +1,152 @@ +# Finance causal-LM runs + +Install the optional language-model dependencies in the same environment on every +Ray node. The `lm` extra adds Transformers, PEFT, Accelerate, SentencePiece, and Linux bitsandbytes. + +```bash +pip install -e ".[lm,dev]" +``` + +`examples/configs/finance_smoke.yaml` runs two clients for two rounds with +`HuggingFaceTB/SmolLM2-135M-Instruct`, 4-bit NF4 loading, FP16 computation, and LoRA. +Each round performs two local optimizer steps with batches of two examples. It uses +up to 32 training examples per client and 16 held-out evaluation examples. +`finance_learning_check.yaml` increases training to five rounds of ten local steps, +using the same holdout seed and pinned model and dataset revisions. +`finance_mistral_memory_check.yaml` runs one Mistral-7B client for one optimizer +step at batch size 16 with a sequence limit of 512 and four evaluation examples. +`finance_mistral_smoke.yaml` tests two Mistral clients for two rounds on the GPU +cluster. `finance_mistral_round_timing.yaml` times one round with ten sampled clients +from fifty IID partitions, each taking ten local steps with batches of sixteen. + +For the two-node SPHERE reservation, start Ray on `a` and `b` from identical FLTest +environments. Each machine needs an installed copy of this branch at the same absolute +path and access to the specified Hugging Face model revision. Set `HF_HOME` and the +config's cache directories on storage with enough free space before larger runs. +Select a writable directory on each machine for Ray's temporary files. + +```bash +# On a, using its dedicated experiment LAN address +ray start --head --node-ip-address=10.0.1.1 --port=6379 \ + --num-cpus=24 --num-gpus=1 --include-dashboard=false \ + --object-store-memory=4000000000 --disable-usage-stats + +# On b +ray start --address=10.0.1.1:6379 --node-ip-address=10.0.1.2 \ + --num-cpus=24 --num-gpus=1 --object-store-memory=4000000000 \ + --disable-usage-stats + +# On a +export FLTEST_RAY_ADDRESS=10.0.1.1:6379 +fltest run examples/configs/finance_smoke.yaml +``` + +`task: causal_lm` selects the Finance implementation for `framework: flwr`. +`lm` holds precision, quantization, LoRA rank and alpha, sequence length, local steps, +gradient checkpointing, holdout fraction, and checkpoint directory. For a CPU FP32 +development run, set `device: cpu`, `lm.precision: fp32`, `lm.quantization: null`, +`total_gpus: 0`, and `client_resources.num_gpus: 0`. + +The loader groups inputs by Unicode-normalized, case-folded text with whitespace +collapsed, then hashes the group with the run seed to choose the holdout. Every copy +of an input stays on the same side of the split, including conflicting labels. +The remaining examples are shuffled and divided into balanced IID shards. +The original nine Finance sentiment labels are retained. The prompt uses the model's +chat template with an explicit request to reply using only the sentiment label. +Only response and EOS tokens contribute to training and held-out loss. +Long prompts are truncated from the left to keep the complete response in the sequence. + +`clients_per_round` samples stable partition IDs from a seed and round number. +`client_resources` specifies the CPU and GPU share per worker. The server waits for +all selected clients and rejects incomplete rounds or incompatible adapter tensors. +FedAvg weights each update by the number of distinct examples that client used in +its local steps. Model discovery never allocates a client model. + +The JSON report includes round 0 and every trained round. `accuracy` is the fraction +of greedy generated sentiment labels matching the target. A bare label or an explicit +first-sentence assertion such as "The sentiment of this tweet is negative." is accepted. +Ambiguous text and unrelated quoted labels receive no predicted label. `exact_match` +retains the strict score for the entire normalized response. `label_parse_rate` records +the fraction with a recognized label, and each round includes raw responses and targets. +`loss` is mean response cross-entropy, weighted by supervised token count. +`train_loss` records client training loss. `zero_shot_gap` is trained accuracy minus +round-0 accuracy. The small holdout is intended for pipeline verification. +LM runs require `loss_fn: CrossEntropyLoss` and `client_epochs: 1`; the number of +local optimizer steps is controlled by `lm.local_steps`. + +The report also records model, tokenizer, and dataset revisions, the dataset fingerprint, +holdout group digest, selected client IDs, hosts, sample counts, and GPU memory figures. +`extras.checkpoint` points to an adapter plus tokenizer and run metadata. The final +directory appears atomically after saving succeeds, with a unique name for each attempt. +An LM run that fails writes its error to the report and exits with a nonzero status. + +Run `ray stop` on both nodes after the experiment finishes. Stop background Ray +processes before switching to a different Python environment. + +## Text attacks and adapter defenses + +`finance_attacks_smoke.yaml` checks text attacks and each supported adapter defense +through `fltest run`. It uses SmolLM2-135M, five IID client shards, two local steps, +and sixteen held-out examples. Most runs select two clients per round; robust +aggregation runs select five so Krum and trimming have enough submissions. These +are integration checks. Their small sample counts do not establish attack efficacy +or a defense's effectiveness. + +```bash +FLTEST_RAY_ADDRESS=10.0.1.1:6379 fltest run examples/configs/finance_attacks_smoke.yaml +``` + +`label_flip` changes the supervised Finance response for `target_clients`. Its default +mapping reverses positive and negative polarity while preserving intensity and leaving +neutral unchanged. An explicit `mapping: {positive: negative, negative: positive}` +changes only the named labels. Finance mappings use strings from the nine labels; +the classification task retains its numeric label rotation. +The existing `sign_flip` and `gaussian` update attacks can also operate on the LoRA arrays. + +`backdoor` requires a nonempty `trigger` string and a sentiment `target_label`. +It appends the trigger to the input of a deterministic fraction of the attacker's +training records and trains their response toward the target. `infection_rate` is a +probability per source record, selected from the seed, client, round, and source ID; +it does not round down to zero in a one-example batch. Training preserves the clean +source records. Each client's `poisoned_samples` counts distinct modified records consumed +in successful optimizer steps; the round-level value averages client counts. +At round 0 and after each round, `attack_success_rate` +measures target-label generation on triggered held-out records, excluding examples +whose clean label is already the target. `backdoor_evaluation_samples` is its denominator. + +`membership_inference` takes `target_client` and `max_samples`. It scores per-record +mean response cross-entropy on the current global model, excluding prompt and padding +tokens. Members are the target client's distinct source records used in successful +optimizer steps through the current round. Allocated records that have never trained +the model are excluded. Nonmembers come from the held-out split. Reports include +the actual probe counts, `membership_inference_auc`, and `membership_loss_gap`. +At round 0, or before the target has trained, the member count is zero and no AUC +is reported. Probes select source IDs in sorted order up to `max_samples` per set. +This implementation requires unpoisoned training records when membership inference +is enabled. It measures leakage through the global model; secure aggregation does +not remove that observation channel. + +Each client's `trained_sample_ids` list uses original row indices from the pinned +dataset revision. IDs survive splitting, shuffling, truncation, poisoning, and +transport from Ray workers; client weights count distinct consumed IDs. The report +retains those lists by round so sampled participation and member sets are auditable. + +Supported defenses are `norm_clip`, `gradient_noise`, `median`, `trimmed_mean`, `krum`, +`fldetector`, `secure_aggregation`, and `mpc_aggregation`. They operate only on LoRA +arrays. Gradient noise is seeded separately for each client and round; it provides +no privacy accountant or claimed differential-privacy budget. Krum requires more +than `2*f+2` participating clients, and trimming requires more than `2*trim`. +The same checks apply after any server-side filtering. FLDetector retains its +existing history-based detection logic and needs enough rounds to build that history. + +Float secure aggregation uses the actual selected partition IDs, requires every +selected client to succeed, and follows optional client clipping/noise. It cannot +be combined with server-side filtering or robust aggregation. Fixed-point MPC +records quantization error, overflow, and dropout diagnostics against plain FedAvg +on the same adapter updates. These secure-aggregation implementations simulate +masking and ring arithmetic; they do not implement cryptographic key exchange. +Choose one aggregation defense per run. Configuration validation rejects unsupported +LM attacks, metrics, and incompatible defense combinations before loading a model. + +Medical and Stack Overflow data/tasks, DoRA, and the reference LM backend remain +outside the current Finance implementation. diff --git a/docs/defenses.md b/docs/defenses.md index 6aa609d..39c5468 100644 --- a/docs/defenses.md +++ b/docs/defenses.md @@ -74,9 +74,10 @@ run in separate Ray workers. entries carry counters rather than learned information, so they pass through unmasked. Both defenses also assume the participant set is fixed for the round — masks cancel only - across exactly the set that produced them. FLTest's backends use full participation, and - `secure_aggregation` records `secagg_participant_mismatch` if a round ever aggregates a - different number of updates rather than letting the residue pass silently. + across exactly the set that produced them. The Finance causal-LM Flower path passes + the selected partition IDs to every worker and rejects incomplete rounds. + `secure_aggregation` records `secagg_participant_mismatch` when the observed count + differs from the expected participant set. **`secure_aggregation`** — float masking, no quantization. The client uploads `x_i + m_i / n_i`; FedAvg's `sum_i (n_i / N) * x_i` then cancels the masks exactly. This is diff --git a/docs/installation.md b/docs/installation.md index 98b285a..918b2c5 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -20,9 +20,14 @@ The core install pulls PyTorch (CPU/MPS wheels on macOS, CPU/CUDA on Linux), Flo ```bash pip install -e ".[nvflare]" # NVFlare backend (requires Python <= 3.11) pip install -e ".[hf]" # Hugging Face models via `model_name: hf:` +pip install -e ".[lm]" # Finance causal-LM training, LoRA, and text attacks pip install -e ".[docs]" # this documentation site (mkdocs-material) ``` +The `lm` extra requires PyTorch 2.4 or later. The Finance GPU configurations use Linux +CUDA, FP16 computation, and bitsandbytes 4-bit loading. CPU FP32 development runs +disable quantization. See [Causal language models](causal-lm.md) for setup and examples. + !!! warning "Intel Macs cap PyTorch at 2.2.2" PyTorch ships no macOS x86_64 wheel past 2.2.2, so an Intel Mac cannot install a newer one. transformers 5 requires torch 2.5 or later and disables PyTorch below it, printing diff --git a/examples/configs/finance_attacks_smoke.yaml b/examples/configs/finance_attacks_smoke.yaml new file mode 100644 index 0000000..2e91a1e --- /dev/null +++ b/examples/configs/finance_attacks_smoke.yaml @@ -0,0 +1,82 @@ +# Integration checks only: tiny training/evaluation sets do not measure attack efficacy. +# Run from the head of an existing two-GPU Ray cluster. +name: finance_attacks_smoke +task: causal_lm +dataset: hf:flwrlabs/fingpt-sentiment-train +model_name: hf:HuggingFaceTB/SmolLM2-135M-Instruct +device: cuda +total_cpus: 8 +total_gpus: 2 +num_clients: 5 +dataset_partitions: 5 +clients_per_round: 2 +num_rounds: 2 +client_batch_size: 2 +client_lr: 0.00005 +optimizer: AdamW +server_batch_size: 4 +max_test_data_size: 16 +client_resources: {num_cpus: 2, num_gpus: 1} +lm: + model_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac + tokenizer_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac + dataset_revision: d01aba2a91252c687bc35e4da659ab73ac70ea27 + precision: fp16 + quantization: 4bit + lora_r: 32 + lora_alpha: 64 + seq_len: 256 + local_steps: 2 + gradient_checkpointing: true + holdout_fraction: 0.1 + max_train_samples_per_client: 32 + checkpoint_dir: reports/adapters +metrics: [accuracy, loss] +runs: + - {framework: flwr, name: clean} + - framework: flwr + name: label_flip_clip + attacks: [{name: label_flip, target_clients: [3]}] + defenses: [{name: norm_clip, params: {clip_norm: 1.0}}] + - framework: flwr + name: backdoor + attacks: + - &text_backdoor + name: backdoor + target_clients: [3] + params: {trigger: "cf_trigger", target_label: positive, infection_rate: 0.5} + - framework: flwr + name: backdoor_median + clients_per_round: 5 + attacks: [*text_backdoor] + defenses: [{name: median}] + - framework: flwr + name: backdoor_trimmed_mean + clients_per_round: 5 + attacks: [*text_backdoor] + defenses: [{name: trimmed_mean, params: {trim: 1}}] + - framework: flwr + name: backdoor_krum + clients_per_round: 5 + attacks: [*text_backdoor] + defenses: [{name: krum, params: {num_byzantine: 1}}] + - framework: flwr + name: membership + attacks: [&membership {name: membership_inference, params: {target_client: 3, max_samples: 8}}] + - framework: flwr + name: membership_noise + attacks: [*membership] + defenses: [{name: gradient_noise, params: {clip_norm: 1.0, sigma: 0.001}}] + - framework: flwr + name: membership_secure_aggregation + attacks: [*membership] + defenses: [{name: secure_aggregation, params: {mask_scale: 1.0}}] + - framework: flwr + name: fixed_point_aggregation + defenses: [{name: mpc_aggregation, params: {quant_bits: 16, modulus: 4294967296}}] + - framework: flwr + name: fldetector + clients_per_round: 5 + num_rounds: 4 + attacks: [{name: label_flip, target_clients: [3]}] + defenses: [{name: fldetector, params: {window_size: 1, start_round: 2}}] diff --git a/examples/configs/finance_learning_check.yaml b/examples/configs/finance_learning_check.yaml new file mode 100644 index 0000000..9287b30 --- /dev/null +++ b/examples/configs/finance_learning_check.yaml @@ -0,0 +1,36 @@ +# Five-round learning check on the same 16-example holdout as finance_smoke.yaml. +name: finance_learning_check +task: causal_lm +dataset: hf:flwrlabs/fingpt-sentiment-train +model_name: hf:HuggingFaceTB/SmolLM2-135M-Instruct +seed: 786 +device: cuda +total_cpus: 8 +total_gpus: 2 +num_clients: 2 +dataset_partitions: 2 +clients_per_round: 2 +num_rounds: 5 +client_batch_size: 2 +client_lr: 0.00005 +optimizer: AdamW +server_batch_size: 4 +max_test_data_size: 16 +client_resources: {num_cpus: 2, num_gpus: 1} +lm: + model_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac + tokenizer_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac + dataset_revision: d01aba2a91252c687bc35e4da659ab73ac70ea27 + precision: fp16 + quantization: 4bit + lora_r: 32 + lora_alpha: 64 + seq_len: 256 + local_steps: 10 + gradient_checkpointing: true + holdout_fraction: 0.1 + max_train_samples_per_client: 32 + checkpoint_dir: reports/adapters +metrics: [accuracy, loss] +runs: + - {framework: flwr, name: clean} diff --git a/examples/configs/finance_mistral_memory_check.yaml b/examples/configs/finance_mistral_memory_check.yaml new file mode 100644 index 0000000..cd35ff8 --- /dev/null +++ b/examples/configs/finance_mistral_memory_check.yaml @@ -0,0 +1,36 @@ +# One-client GPU memory check at the intended Finance batch size and sequence limit. +name: finance_mistral_memory_check +task: causal_lm +dataset: hf:flwrlabs/fingpt-sentiment-train +model_name: hf:mistralai/Mistral-7B-Instruct-v0.3 +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: 0.00005 +optimizer: AdamW +server_batch_size: 1 +max_test_data_size: 4 +client_resources: {num_cpus: 6, num_gpus: 1} +lm: + model_revision: c170c708c41dac9275d15a8fff4eca08d52bab71 + tokenizer_revision: c170c708c41dac9275d15a8fff4eca08d52bab71 + dataset_revision: d01aba2a91252c687bc35e4da659ab73ac70ea27 + 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 +metrics: [accuracy, loss] +runs: + - {framework: flwr, name: clean} diff --git a/examples/configs/finance_mistral_round_timing.yaml b/examples/configs/finance_mistral_round_timing.yaml new file mode 100644 index 0000000..7084110 --- /dev/null +++ b/examples/configs/finance_mistral_round_timing.yaml @@ -0,0 +1,41 @@ +# Time one 10-client round from 50 IID partitions on two GPUs. +name: finance_mistral_round_timing +task: causal_lm +dataset: hf:flwrlabs/fingpt-sentiment-train +model_name: hf:mistralai/Mistral-7B-Instruct-v0.3 +seed: 786 +device: cuda +total_cpus: 12 +total_gpus: 2 +num_clients: 50 +dataset_partitions: 50 +clients_per_round: 10 +num_rounds: 1 +client_batch_size: 16 +client_lr: 5.0e-05 +optimizer: AdamW +server_batch_size: 1 +max_test_data_size: 16 +client_resources: + num_cpus: 6 + num_gpus: 1 +lm: + model_revision: c170c708c41dac9275d15a8fff4eca08d52bab71 + tokenizer_revision: c170c708c41dac9275d15a8fff4eca08d52bab71 + dataset_revision: d01aba2a91252c687bc35e4da659ab73ac70ea27 + precision: fp16 + quantization: 4bit + lora_r: 32 + lora_alpha: 64 + seq_len: 512 + local_steps: 10 + gradient_checkpointing: true + holdout_fraction: 0.1 + max_train_samples_per_client: 160 + checkpoint_dir: reports/adapters +metrics: +- accuracy +- loss +runs: +- framework: flwr + name: clean diff --git a/examples/configs/finance_mistral_smoke.yaml b/examples/configs/finance_mistral_smoke.yaml new file mode 100644 index 0000000..5f918b4 --- /dev/null +++ b/examples/configs/finance_mistral_smoke.yaml @@ -0,0 +1,41 @@ +# Two-node Mistral pipeline smoke test. Use the existing GPU Ray cluster. +name: finance_mistral_smoke +task: causal_lm +dataset: hf:flwrlabs/fingpt-sentiment-train +model_name: hf:mistralai/Mistral-7B-Instruct-v0.3 +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: 16 +client_resources: + num_cpus: 6 + num_gpus: 1 +lm: + model_revision: c170c708c41dac9275d15a8fff4eca08d52bab71 + tokenizer_revision: c170c708c41dac9275d15a8fff4eca08d52bab71 + dataset_revision: d01aba2a91252c687bc35e4da659ab73ac70ea27 + 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 +metrics: +- accuracy +- loss +runs: +- framework: flwr + name: clean diff --git a/examples/configs/finance_smoke.yaml b/examples/configs/finance_smoke.yaml new file mode 100644 index 0000000..fff9c16 --- /dev/null +++ b/examples/configs/finance_smoke.yaml @@ -0,0 +1,33 @@ +# Two-round clean causal-LM acceptance run. Start a two-GPU Ray cluster first. +# FLTEST_RAY_ADDRESS=10.0.1.1:6379 fltest run examples/configs/finance_smoke.yaml +name: finance_smoke +task: causal_lm +dataset: hf:flwrlabs/fingpt-sentiment-train +model_name: hf:HuggingFaceTB/SmolLM2-135M-Instruct +device: cuda +total_cpus: 8 +total_gpus: 2 +num_clients: 2 +dataset_partitions: 2 +clients_per_round: 2 +num_rounds: 2 +client_batch_size: 2 +client_lr: 0.00005 +optimizer: AdamW +server_batch_size: 4 +max_test_data_size: 16 +client_resources: {num_cpus: 2, num_gpus: 1} +lm: + precision: fp16 + quantization: 4bit + lora_r: 32 + lora_alpha: 64 + seq_len: 256 + local_steps: 2 + gradient_checkpointing: true + holdout_fraction: 0.1 + max_train_samples_per_client: 32 + checkpoint_dir: reports/adapters +metrics: [accuracy, loss] +runs: + - {framework: flwr, name: clean} diff --git a/fltest/attacks/causal_lm.py b/fltest/attacks/causal_lm.py new file mode 100644 index 0000000..7ca670f --- /dev/null +++ b/fltest/attacks/causal_lm.py @@ -0,0 +1,74 @@ +"""Finance text poisoning and probes, preserving clean records and source IDs.""" + +import hashlib + +from torch.utils.data import DataLoader + +from fltest.data.causal_lm import ( + encode_finance_row, evaluate_causal_model, load_tokenizer, +) +from fltest.data.finance_labels import POLARITY_FLIP + + +def is_causal_lm(ctx): + return getattr(ctx.cfg, "task", None) == "causal_lm" + + +class FinancePoisonLoader: + """Transform only selected training records as batches are consumed by training.""" + + def __init__(self, base, spec, cid, rnd, *, mapping=None, trigger=None, + target=None, infection_rate=1.0): + self._base, self.spec = base, spec + self.dataset = base.dataset # Clean records remain available to privacy probes. + self._rows = {row["sample_id"]: row for row in self.dataset} + 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}" + + 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] + source = dict(clean["finance_row"]) + score = int(hashlib.sha256(f"{self._seed}:{sid}".encode()).hexdigest(), 16) / 2**256 + if score < self.infection_rate: + if self.trigger is not None: + source["input"] += "\n" + self.trigger + source["output"] = self.target + else: + source["output"] = self.mapping.get(clean["response"], clean["response"]) + encoded = encode_finance_row(source, self.tokenizer, self.spec.lm.seq_len, sid) + encoded["poisoned"] = ( + source["input"] != clean["finance_row"]["input"] + or encoded["response"] != clean["response"] + ) + rows.append(encoded) + else: + rows.append(clean) + yield self._base.collate_fn(rows) + + +def evaluate_text_backdoor(ctx, trigger, target): + """ASR on triggered held-out records whose clean label is not the target.""" + tokenizer = load_tokenizer(ctx.cfg) + rows = [] + for clean in ctx.test_data.dataset: + if clean["response"] == target: + continue + source = dict(clean["finance_row"]) + source["input"] += "\n" + trigger + source["output"] = target + rows.append(encode_finance_row(source, tokenizer, ctx.cfg.lm.seq_len, clean["sample_id"])) + ctx.record(backdoor_evaluation_samples=len(rows)) + if not rows: + return + loader = DataLoader(rows, batch_size=ctx.cfg.server_batch_size, + collate_fn=ctx.test_data.collate_fn) + _, asr = evaluate_causal_model(ctx.model, loader, ctx.cfg) + ctx.record(attack_success_rate=asr) diff --git a/fltest/attacks/data_poison_backdoor.py b/fltest/attacks/data_poison_backdoor.py index 2392978..6957dcf 100644 --- a/fltest/attacks/data_poison_backdoor.py +++ b/fltest/attacks/data_poison_backdoor.py @@ -1,4 +1,4 @@ -"""Backdoor data-poisoning attack with a pixel-patch trigger. +"""Backdoor data poisoning with image-patch or Finance text triggers. Attacker clients stamp a small bright patch onto a fraction of their images and relabel them to ``target_label``. The global model thus learns: *trigger present => target_label*. @@ -58,17 +58,26 @@ def __iter__(self): class BackdoorAttack(ThreatModelBaseClass): HOOKS = ("before_client_train", "after_round") - def __init__(self, target_label: int = 0, infection_rate: float = 0.3, - patch_size: int = 4, patch_value: float = 1.0, **params): + 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): 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 def before_client_train(self, ctx: HookContext) -> None: if not self.targets(ctx.client_id) or ctx.client_data is None: return + from fltest.attacks.causal_lm import FinancePoisonLoader, is_causal_lm + + if is_causal_lm(ctx): + 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, + ) + return ctx.client_data = _BackdoorLoader( ctx.client_data, self.infection_rate, self.patch_size, self.patch_value, self.target_label ) @@ -77,6 +86,11 @@ def before_client_train(self, ctx: HookContext) -> None: def after_round(self, ctx: HookContext) -> None: if ctx.global_state is None or ctx.test_data is None or ctx.cfg is None: return + from fltest.attacks.causal_lm import evaluate_text_backdoor, is_causal_lm + + if is_causal_lm(ctx): + evaluate_text_backdoor(ctx, self.trigger, self.target_label) + return spec = ctx.cfg model = ctx.model if model is None: diff --git a/fltest/attacks/gaussian.py b/fltest/attacks/gaussian.py index 08c9105..04287e9 100644 --- a/fltest/attacks/gaussian.py +++ b/fltest/attacks/gaussian.py @@ -21,12 +21,16 @@ class GaussianAttack(ThreatModelBaseClass): def __init__(self, sigma: float = 0.1, seed: int = 0, **params): super().__init__(**params) self.sigma = sigma + self.seed = seed self._rng = np.random.default_rng(seed) def after_client_train(self, ctx: HookContext) -> None: if not self.targets(ctx.client_id) or ctx.client_update is None: return + rng = self._rng + if ctx.round is not None and ctx.client_id is not None: + rng = np.random.default_rng([self.seed, int(ctx.round), int(ctx.client_id)]) ctx.client_update = [ - u + self._rng.normal(0.0, self.sigma, size=u.shape).astype(u.dtype) + u + rng.normal(0.0, self.sigma, size=u.shape).astype(u.dtype) for u in ctx.client_update ] diff --git a/fltest/attacks/label_flip.py b/fltest/attacks/label_flip.py index 564d674..895dbff 100644 --- a/fltest/attacks/label_flip.py +++ b/fltest/attacks/label_flip.py @@ -2,8 +2,8 @@ Attacker clients train on relabeled data. By default labels are rotated ``y -> (y + shift) % num_classes``; a fixed ``{src: dst}`` mapping can be given instead. -Acts at ``before_client_train`` by wrapping the client's DataLoader, so it is identical -across backends (they all pass a ``{"img","label"}`` loader through ``ctx.client_data``). +Acts at ``before_client_train`` by wrapping the client's DataLoader. Finance causal-LM +loaders instead use string-label mappings, defaulting to polarity reversal. """ from __future__ import annotations @@ -56,5 +56,13 @@ def __init__(self, shift: int = 1, mapping: dict | None = None, **params): def before_client_train(self, ctx: HookContext) -> None: if not self.targets(ctx.client_id) or ctx.client_data is None: return + from fltest.attacks.causal_lm import FinancePoisonLoader, POLARITY_FLIP, is_causal_lm + + if is_causal_lm(ctx): + ctx.client_data = FinancePoisonLoader( + ctx.client_data, ctx.cfg, ctx.client_id, ctx.round, + mapping=POLARITY_FLIP if self.mapping is None else self.mapping, + ) + return num_classes = getattr(ctx.cfg, "num_classes", 10) ctx.client_data = _RelabelLoader(ctx.client_data, num_classes, self.shift, self.mapping) diff --git a/fltest/attacks/membership_inference.py b/fltest/attacks/membership_inference.py index ce9042f..5cee317 100644 --- a/fltest/attacks/membership_inference.py +++ b/fltest/attacks/membership_inference.py @@ -97,6 +97,9 @@ def after_round(self, ctx: HookContext) -> None: loaders, spec = self._client_loaders, ctx.cfg if not loaders or spec is None or ctx.test_data is None: return + if getattr(spec, "task", None) == "causal_lm": + self._after_causal_round(ctx) + return member_loader = loaders.get(self.target_client) if member_loader is None or ctx.global_state is None: return @@ -121,3 +124,34 @@ def after_round(self, ctx: HookContext) -> None: membership_inference_auc=auc, membership_loss_gap=float(non_member.mean() - member.mean()), ) + + def _after_causal_round(self, ctx): + from torch.utils.data import DataLoader + from fltest.data.causal_lm import causal_sample_losses + + loader = self._client_loaders.get(self.target_client) + if loader is None or ctx.model is None: + return + # Workers send IDs only after successful optimizer steps. Accumulate the + # target's history through this round; unselected/unused records are not members. + used = { + sid for rnd, entry in ctx.history.items() if 0 < rnd <= ctx.round + for client in entry.get("clients", []) if client["cid"] == self.target_client + for sid in client["trained_sample_ids"] + } + members = sorted((row for row in loader.dataset if row["sample_id"] in used), + key=lambda row: row["sample_id"])[:self.max_samples] + nonmembers = sorted(ctx.test_data.dataset, key=lambda row: row["sample_id"])[:self.max_samples] + ctx.record(membership_member_samples=len(members), membership_nonmember_samples=len(nonmembers)) + if not members or not nonmembers: + return + def score(rows): + return causal_sample_losses(ctx.model, DataLoader( + rows, batch_size=1, collate_fn=loader.collate_fn, + ), ctx.cfg) + + member, nonmember = score(members), score(nonmembers) + ctx.record( + membership_inference_auc=roc_auc(-member, -nonmember), + membership_loss_gap=float(nonmember.mean() - member.mean()), + ) diff --git a/fltest/cli.py b/fltest/cli.py index fab848a..2ec21ce 100644 --- a/fltest/cli.py +++ b/fltest/cli.py @@ -88,6 +88,8 @@ def run(config_path: str, output: str, verbose: bool) -> None: extra={"total_duration": round(matrix.total_duration, 2)}, ) print_run_matrix(config.name, matrix.results, matrix.total_duration, report_path) + if any(r.params.get("task") == "causal_lm" and r.status != "success" for r in matrix.results): + raise click.ClickException(f"Causal-LM run failed. See {report_path} for the error.") @cli.command() diff --git a/fltest/core/config.py b/fltest/core/config.py index 18b15ae..1e8b0a2 100644 --- a/fltest/core/config.py +++ b/fltest/core/config.py @@ -17,14 +17,41 @@ from __future__ import annotations from pathlib import Path -from typing import Any, Dict, List, Optional, Union +from typing import Any, Dict, List, Literal, Optional, Union import yaml -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, model_validator ScalarOrList = Union[Any, List[Any]] +class ClientResources(BaseModel): + num_cpus: float = Field(default=1, gt=0) + num_gpus: float = Field(default=0, ge=0) + + model_config = {"extra": "forbid"} + + +class CausalLMConfig(BaseModel): + """Settings for the Finance causal-LM task.""" + + model_revision: Optional[str] = None + tokenizer_revision: Optional[str] = None + dataset_revision: Optional[str] = None + precision: Literal["fp32", "fp16"] = "fp16" + quantization: Optional[Literal["4bit"]] = "4bit" + lora_r: int = Field(default=32, gt=0) + lora_alpha: int = Field(default=64, gt=0) + seq_len: int = Field(default=512, ge=16) + local_steps: int = Field(default=10, gt=0) + gradient_checkpointing: bool = True + 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" + + model_config = {"extra": "forbid"} + + class AttackSpec(BaseModel): """A built-in attack to compose onto a run (by registry name).""" @@ -103,6 +130,10 @@ class RunSpec(BaseModel): run_id: str run_name: str framework: str + task: Literal["classification", "causal_lm"] = "classification" + lm: Optional[CausalLMConfig] = None + clients_per_round: Optional[int] = Field(default=None, gt=0) + client_resources: Optional[ClientResources] = None # reproducibility / hardware seed: int = 786 @@ -149,6 +180,126 @@ class RunSpec(BaseModel): model_config = {"extra": "allow"} + @model_validator(mode="after") + def validate_task(self): + uses_flower_resources = self.clients_per_round is not None or self.client_resources is not None + if uses_flower_resources and self.framework not in ("flwr", "flower"): + raise ValueError("clients_per_round and client_resources currently support framework: flwr") + if self.clients_per_round is not None and self.clients_per_round > self.num_clients: + raise ValueError("clients_per_round must not exceed num_clients") + if self.task != "causal_lm": + if self.lm is not None: + raise ValueError("lm settings require task: causal_lm") + 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") + 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") + 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.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"): + raise ValueError("causal_lm supports Adam, AdamW, or SGD") + if self.loss_fn != "CrossEntropyLoss": + raise ValueError("causal_lm requires CrossEntropyLoss on response tokens") + if self.client_epochs != 1: + raise ValueError("causal_lm uses lm.local_steps; leave client_epochs at 1") + if self.device not in ("cpu", "cuda"): + raise ValueError("causal_lm supports device: cpu or cuda") + if self.device != "cuda" and (self.lm.precision == "fp16" or self.lm.quantization): + raise ValueError("causal_lm fp16 and 4bit loading require device: cuda") + if self.client_resources is None: + raise ValueError("causal_lm requires explicit client_resources") + if self.device == "cuda" and self.client_resources.num_gpus <= 0: + raise ValueError("CUDA clients require client_resources.num_gpus > 0") + return 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") + allowed = { + "label_flip": {"mapping"}, + "backdoor": {"trigger", "target_label", "infection_rate"}, + "membership_inference": {"target_client", "max_samples"}, + "sign_flip": {"scale"}, "gaussian": {"sigma", "seed"}, + } + names = [attack.name for attack in self.attacks] + if len(names) != len(set(names)): + raise ValueError("causal_lm requires unique attack names") + if sum(name in ("backdoor", "label_flip") for name in names) > 1: + raise ValueError("causal_lm supports one text poisoning attack per run") + if "membership_inference" in names and any(n in names for n in ("backdoor", "label_flip")): + raise ValueError("causal_lm membership probes currently require unpoisoned training records") + for attack in self.attacks: + if attack.name not in allowed or set(attack.params) - allowed[attack.name]: + raise ValueError(f"Unsupported causal_lm attack or parameters: {attack.name}") + if attack.target_clients is not None and any( + cid < 0 or cid >= self.num_clients for cid in attack.target_clients + ): + raise ValueError("Attack target_clients must be valid partition IDs") + if attack.target_clients == []: + raise ValueError("Use explicit attack target_clients or omit the field for all clients") + p = attack.params + if attack.name == "label_flip" and "mapping" in p: + mapping = p["mapping"] + if not isinstance(mapping, dict) or any( + src not in FINANCE_LABELS or dst not in FINANCE_LABELS for src, dst in mapping.items() + ): + 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("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 (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 + or p.get("max_samples", 512) < 1): + raise ValueError("Invalid membership target_client or max_samples") + supported = { + "norm_clip", "gradient_noise", "median", "trimmed_mean", "krum", + "secure_aggregation", "mpc_aggregation", "fldetector", + } + defenses = [d.name for d in self.defenses] + 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"} + if sum(name in aggregators for name in defenses) > 1: + raise ValueError("Choose one causal_lm aggregation defense") + if "secure_aggregation" in defenses: + if set(defenses) - {"secure_aggregation", "norm_clip", "gradient_noise"}: + raise ValueError("secure_aggregation requires FedAvg without server-side filtering") + if defenses[-1] != "secure_aggregation": + raise ValueError("secure_aggregation must follow client clipping and noise") + secure = next(d for d in self.defenses if d.name == "secure_aggregation") + if "num_participants" in secure.params: + raise ValueError("causal_lm secure_aggregation derives participants from the selected clients") + participants = self.clients_per_round or self.num_clients + for defense in self.defenses: + p = defense.params + if defense.name == "krum" and (p.get("num_byzantine", 1) < 0 or + participants <= 2 * p.get("num_byzantine", 1) + 2): + raise ValueError("Krum requires more than 2*f+2 participating clients") + if defense.name == "trimmed_mean" and not 0 <= 2 * p.get("trim", 1) < participants: + raise ValueError("trimmed_mean requires 0 <= 2*trim < participating clients") + if defense.name in ("norm_clip", "gradient_noise") and not p.get("clip_norm", 1.0) > 0: + raise ValueError("clip_norm must be positive") + if defense.name == "gradient_noise" and not p.get("sigma", 0.01) >= 0: + raise ValueError("sigma must be nonnegative") + def tokenizer_id(self) -> str: """Tokenizer to encode a text dataset with. @@ -186,7 +337,7 @@ def summary(self) -> Dict[str, Any]: Distribution-specific knobs are only included when they apply, so e.g. ``dirichlet_alpha`` is None for IID runs (where it has no effect). """ - return { + summary = { "framework": self.framework, "dataset": self.dataset, "data_distribution": self.data_distribution, @@ -210,6 +361,13 @@ def summary(self) -> Dict[str, Any]: "defenses": [{"name": d.name, "params": d.params} for d in self.defenses], "metrics": list(self.metrics), } + if self.task == "causal_lm": + summary.update(task=self.task, lm=self.lm.model_dump(), 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: + summary["client_resources"] = self.client_resources.model_dump() + return summary class TestConfig(BaseModel): @@ -218,6 +376,10 @@ class TestConfig(BaseModel): __test__ = False # not a pytest test class despite the "Test" prefix name: str = "fltest_run" + task: Literal["classification", "causal_lm"] = "classification" + lm: Optional[CausalLMConfig] = None + clients_per_round: Optional[int] = Field(default=None, gt=0) + client_resources: Optional[ClientResources] = None seed: int = 786 device: str = "cpu" deterministic: bool = True diff --git a/fltest/core/orchestrator.py b/fltest/core/orchestrator.py index cbd3d7d..2ada30c 100644 --- a/fltest/core/orchestrator.py +++ b/fltest/core/orchestrator.py @@ -64,6 +64,11 @@ def expand_run_specs(config: TestConfig) -> List[RunSpec]: model_cache_path=config.model_cache_path, dataset_cache_path=config.dataset_cache_path, fw_cache_path=config.fw_cache_path, ) + # Preserve existing run identities when the new options are absent. + 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 specs: List[RunSpec] = [] for combo in combos: @@ -74,7 +79,9 @@ def expand_run_specs(config: TestConfig) -> List[RunSpec]: run_label = run.pop("name", framework) merged: Dict[str, Any] = {**common, **param_set, **run} - channels, num_classes = dataset_meta(merged.get("dataset", "mnist")) + channels, num_classes = (0, 0) if merged.get("task") == "causal_lm" else dataset_meta( + merged.get("dataset", "mnist") + ) merged["channels"], merged["num_classes"] = channels, num_classes # plugins: per-run override if present, else global config-level. @@ -96,6 +103,10 @@ 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": + from fltest.data.causal_lm import prepare_finance_data + + return prepare_finance_data(spec) dataset_dict = get_cached_federated_dataset( spec.dataset, spec.dataset_partitions, spec.dataset_cache_path, spec.data_distribution, tokenizer_id=spec.tokenizer_id(), @@ -122,10 +133,13 @@ def _log(self, msg: str) -> None: def run_spec(self, spec: RunSpec) -> RunResult: adapter = get_adapter(spec.framework) - data = prepare_data(spec) + if spec.task != "causal_lm": + data = prepare_data(spec) hook_runner = build_hook_runner(spec) start = time.time() try: + if spec.task == "causal_lm": + data = prepare_data(spec) result = adapter.run_simulation(spec, data, hook_runner) except Exception as exc: # noqa: BLE001 - surface any backend failure as a result result = RunResult( diff --git a/fltest/data/causal_lm.py b/fltest/data/causal_lm.py new file mode 100644 index 0000000..18db8d4 --- /dev/null +++ b/fltest/data/causal_lm.py @@ -0,0 +1,399 @@ +"""Pretrained causal-LM training and held-out Finance evaluation. + +Only LoRA parameters travel through FLTest's list-of-ndarrays interface. Prepared +examples contain ordinary Python values so Ray never receives local Arrow cache paths. +""" + +from __future__ import annotations + +from contextlib import nullcontext +from dataclasses import dataclass +import hashlib +import json +from pathlib import Path +import random +import re +import tempfile +import unicodedata + +import numpy as np +import torch +from torch.utils.data import DataLoader + +from fltest.data.utils import seed_everything + + +def normalize_text(text): + return " ".join(unicodedata.normalize("NFKC", text).casefold().split()) + + +def finance_response_label(response): + """Accept a bare label or an explicit first-sentence sentiment assertion.""" + label = r"(?:(?:strong(?:ly)?|moderately|mildly) (?:positive|negative)|positive|negative|neutral)" + text = normalize_text(response) + bare = re.fullmatch(rf"({label})[.!]?", text) + statement = re.match( + rf"the sentiment(?: of (?:this|the) (?:tweet|news|text|sentence|statement))? " + rf"is ({label})(?:[.!](?:\s|$)|$)", text, + ) + match = bare or statement + if match is None: + return None + return match.group(1).replace("strongly ", "strong ") + + +def split_finance_rows(rows, fraction, seed): + """Keep every occurrence of an input on the same side of the holdout.""" + train, heldout = [], [] + for row in rows: + key = normalize_text(row["input"]) + score = int(hashlib.sha256(f"{seed}:{key}".encode()).hexdigest(), 16) / 2**256 + (heldout if score < fraction else train).append(dict(row)) + if not train or not heldout: + raise ValueError("Finance holdout produced an empty split; use more input groups") + return train, heldout + + +def encode_finance_row(row, tokenizer, seq_len, sample_id): + prompt = tokenizer.apply_chat_template( + [{"role": "user", "content": ( + f"{row['instruction']}\n{row['input']}\n" + "Reply using only the chosen sentiment label." + )}], + tokenize=True, add_generation_prompt=True, + ) + response = normalize_text(row["output"]) + answer = tokenizer.encode(response, add_special_tokens=False) + [tokenizer.eos_token_id] + if not prompt or len(answer) >= seq_len: + raise ValueError("seq_len must leave room for the prompt and the complete Finance label") + prompt = prompt[-(seq_len - len(answer)):] + return { + "input_ids": prompt + answer, + "labels": [-100] * len(prompt) + answer, + "prompt_ids": prompt, + "response": response, + "sample_id": sample_id, + "finance_row": dict(row), + } + + +@dataclass +class LMCollator: + pad_token_id: int + + def __call__(self, rows): + width = max(len(row["input_ids"]) for row in rows) + return { + "input_ids": torch.tensor([ + row["input_ids"] + [self.pad_token_id] * (width - len(row["input_ids"])) + for row in rows + ]), + "attention_mask": torch.tensor([ + [1] * len(row["input_ids"]) + [0] * (width - len(row["input_ids"])) + for row in 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], + "sample_id": [row["sample_id"] for row in rows], + "poisoned": [row.get("poisoned", False) for row in rows], + } + + +def load_tokenizer(spec): + from transformers import AutoTokenizer + + tokenizer = AutoTokenizer.from_pretrained( + 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.pad_token_id is None: + tokenizer.pad_token = tokenizer.eos_token + return tokenizer + + +def prepare_finance_data(spec): + from datasets import load_dataset + from huggingface_hub import HfApi + + api = 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 + if spec.tokenizer_id() == model_id and spec.lm.tokenizer_revision is None: + spec.lm.tokenizer_revision = spec.lm.model_revision + elif not Path(spec.tokenizer_id()).is_dir(): + spec.lm.tokenizer_revision = api.model_info( + spec.tokenizer_id(), revision=spec.lm.tokenizer_revision + ).sha + dataset_id = spec.dataset.removeprefix("hf:") + spec.lm.dataset_revision = api.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, + ) + # Keep source-row IDs through splitting, shuffling, partitioning and poisoning. + train, heldout = split_finance_rows( + (dict(row, source_id=i) for i, row in enumerate(raw)), + spec.lm.holdout_fraction, spec.seed, + ) + rng = random.Random(spec.seed) + rng.shuffle(train) + rng.shuffle(heldout) + if len(train) < spec.num_clients: + raise ValueError("Finance training split has fewer examples 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_finance_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 + ) + test_rows = heldout[:spec.max_test_data_size] + test_loader = DataLoader( + [encode_finance_row(row, tokenizer, spec.lm.seq_len, row["source_id"]) for row in test_rows], + batch_size=spec.server_batch_size, collate_fn=collator, + ) + split_digest = hashlib.sha256( + json.dumps(sorted({normalize_text(row["input"]) for row in heldout})).encode() + ).hexdigest() + return { + "c2loader": loaders, "test_loader": test_loader, + "metadata": { + "model_revision": spec.lm.model_revision, + "tokenizer_revision": spec.lm.tokenizer_revision, + "dataset_revision": spec.lm.dataset_revision, + "dataset_fingerprint": raw._fingerprint, + "split_seed": spec.seed, "holdout_groups_sha256": split_digest, + "train_rows": len(train), "holdout_rows": len(heldout), + "client_rows": {cid: len(loader.dataset) for cid, loader in loaders.items()}, + "evaluation_rows": len(test_rows), + "accuracy_definition": "unambiguous generated sentiment label against the Finance label", + "exact_match_definition": "entire normalized generated response equals the Finance label", + "response_labels": sorted(set(raw["output"])), + "sample_id_definition": "row index in the pinned source dataset train split", + }, + } + + +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 + + seed_everything(spec.seed) + 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", + } + if opts.quantization == "4bit": + kwargs["quantization_config"] = BitsAndBytesConfig( + load_in_4bit=True, bnb_4bit_quant_type="nf4", + bnb_4bit_compute_dtype=kwargs["torch_dtype"], + ) + kwargs["device_map"] = {"": torch.cuda.current_device()} + model = AutoModelForCausalLM.from_pretrained(spec.model_name.removeprefix("hf:"), **kwargs) + model.config.use_cache = False + if opts.quantization: + model = prepare_model_for_kbit_training( + model, use_gradient_checkpointing=opts.gradient_checkpointing + ) + else: + model.to(spec.device) + if opts.gradient_checkpointing: + model.gradient_checkpointing_enable() + model.enable_input_require_grads() + return get_peft_model( + model, + LoraConfig( + r=opts.lora_r, lora_alpha=opts.lora_alpha, task_type="CAUSAL_LM", lora_dropout=0.075, + ), + revision=opts.model_revision, + ) + + +def adapter_state(model): + from peft import get_peft_model_state_dict + + return dict(sorted(get_peft_model_state_dict(model).items())) + + +def adapter_parameters(model): + return [tensor.detach().float().cpu().numpy().copy() for tensor in adapter_state(model).values()] + + +def adapter_manifest(model): + manifest = [(key, list(tensor.shape)) for key, tensor in adapter_state(model).items()] + return hashlib.sha256(json.dumps(manifest).encode()).hexdigest() + + +def validate_adapter_parameters(parameters, reference): + if len(parameters) != len(reference): + raise ValueError("LoRA tensor count mismatch") + for array, expected in zip(parameters, reference): + if array.shape != expected.shape or not np.isfinite(array).all(): + raise ValueError("LoRA update contains a mismatched shape or nonfinite values") + + +def set_adapter_parameters(model, parameters): + from peft import set_peft_model_state_dict + + state = adapter_state(model) + validate_adapter_parameters(parameters, [tensor.detach().cpu().numpy() for tensor in state.values()]) + set_peft_model_state_dict(model, { + name: torch.as_tensor(value) for name, value in zip(state, parameters) + }) + + +def _model_inputs(batch, device): + return {key: batch[key].to(device) for key in ("input_ids", "attention_mask", "labels")} + + +def _autocast(spec): + return torch.autocast("cuda", dtype=torch.float16) if spec.lm.precision == "fp16" else nullcontext() + + +def train_causal_model(model, loader, spec, server_round, cid, details=None): + seed_everything(spec.seed + server_round * spec.num_clients + cid) + optimizer_cls = {"Adam": torch.optim.Adam, "AdamW": torch.optim.AdamW, "SGD": torch.optim.SGD}[spec.optimizer] + trainable = [p for p in model.parameters() if p.requires_grad] + optimizer = optimizer_cls(trainable, lr=spec.client_lr) + scaler = torch.amp.GradScaler("cuda", enabled=spec.lm.precision == "fp16") + model.train() + total_loss, total_tokens = 0.0, 0 + seen = set() + poisoned = set() + iterator = iter(loader) + for _ in range(spec.lm.local_steps): + try: + batch = next(iterator) + except StopIteration: + iterator = iter(loader) + batch = next(iterator) + inputs = _model_inputs(batch, spec.device) + tokens = int((inputs["labels"][:, 1:] != -100).sum()) + if tokens == 0: + raise ValueError("LM training batch has no supervised response tokens") + 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() + scaler.unscale_(optimizer) + norm = torch.nn.utils.clip_grad_norm_(trainable, 1.0) + if torch.isfinite(norm): + scaler.step(optimizer) + scaler.update() + break + if not scaler.is_enabled(): + raise ValueError("Nonfinite causal-LM gradients") + # Retry the same batch at a lower scale. Count actual optimizer steps, + # including when the initial FP16 loss scale overflows on Turing. + 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_tokens += tokens + seen.update(batch["sample_id"]) + poisoned.update(sid for sid, flag in zip( + batch["sample_id"], batch.get("poisoned", [False] * len(batch["sample_id"])) + ) if flag) + if details is not None: + details.update(trained_sample_ids=sorted(seen), poisoned_sample_ids=sorted(poisoned)) + return total_loss / total_tokens, len(seen) + + +@torch.no_grad() +def causal_sample_losses(model, loader, spec): + """Per-record response CE; prompt and padding tokens never affect the score.""" + model.eval() + losses = [] + for batch in loader: + inputs = _model_inputs(batch, spec.device) + with _autocast(spec): + logits = model(**inputs).logits[:, :-1].float() + targets = inputs["labels"][:, 1:] + count = (targets != -100).sum(dim=1) + if (count == 0).any(): + raise ValueError("Membership probe has no supervised response tokens") + token_losses = torch.nn.functional.cross_entropy( + logits.reshape(-1, logits.shape[-1]), targets.reshape(-1), + reduction="none", ignore_index=-100, + ).reshape_as(targets) + losses.extend((token_losses.sum(dim=1) / count).cpu().tolist()) + result = np.asarray(losses, dtype=float) + if not np.isfinite(result).all(): + raise ValueError("Nonfinite causal-LM membership loss") + return result + + +@torch.no_grad() +def evaluate_causal_model(model, loader, spec, details=None): + tokenizer = load_tokenizer(spec) + model.eval() + total_loss, total_tokens, correct, examples = 0.0, 0, 0, 0 + exact_matches, parsed = 0, 0 + predictions = [] + for batch in loader: + inputs = _model_inputs(batch, spec.device) + tokens = int((inputs["labels"][:, 1:] != -100).sum()) + with _autocast(spec): + loss = model(**inputs).loss + if not torch.isfinite(loss) or tokens == 0: + raise ValueError("Invalid held-out causal-LM response loss") + total_loss += loss.item() * tokens + total_tokens += tokens + for sample_id, prompt, target in zip(batch["sample_id"], batch["prompt_ids"], batch["response"]): + input_ids = torch.tensor([prompt], device=spec.device) + with _autocast(spec): + generated = model.generate( + input_ids=input_ids, attention_mask=torch.ones_like(input_ids), + max_new_tokens=16, do_sample=False, num_beams=1, + pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id, + ) + predicted = tokenizer.decode(generated[0, len(prompt):], skip_special_tokens=True) + label = finance_response_label(predicted) + correct += label == target + exact_matches += normalize_text(predicted) == target + parsed += label is not None + predictions.append({ + "sample_id": sample_id, "target": target, + "response": predicted, "predicted_label": label, + }) + examples += 1 + if not examples: + raise ValueError("Causal-LM evaluation set is empty") + if details is not None: + details.update( + metrics={"exact_match": exact_matches / examples, "label_parse_rate": parsed / examples}, + predictions=predictions, + ) + return total_loss / total_tokens, correct / examples + + +def save_adapter_checkpoint(model, spec, metadata): + """Publish a complete adapter directory atomically with a unique name 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)) + model.save_pretrained(temporary) + load_tokenizer(spec).save_pretrained(temporary) + (temporary / "run.json").write_text(json.dumps({"params": spec.summary(), **metadata}, indent=2)) + destination = root / temporary.name.removeprefix(".partial-") + temporary.rename(destination) + return str(destination.resolve()) diff --git a/fltest/data/finance_labels.py b/fltest/data/finance_labels.py new file mode 100644 index 0000000..a8bd343 --- /dev/null +++ b/fltest/data/finance_labels.py @@ -0,0 +1,10 @@ +"""The original nine FinGPT sentiment classes and their polarity reversal.""" + +FINANCE_LABELS = frozenset({ + "negative", "positive", "neutral", "strong negative", "strong positive", + "moderately negative", "moderately positive", "mildly negative", "mildly positive", +}) +POLARITY_FLIP = { + label: label.replace("positive", "negative") if "positive" in label + else label.replace("negative", "positive") for label in FINANCE_LABELS +} diff --git a/fltest/defenses/gradient_noise.py b/fltest/defenses/gradient_noise.py index a7697eb..9276bab 100644 --- a/fltest/defenses/gradient_noise.py +++ b/fltest/defenses/gradient_noise.py @@ -29,6 +29,7 @@ def __init__(self, clip_norm: float = 1.0, sigma: float = 0.01, seed: int = 0, * super().__init__(**params) self.clip_norm = clip_norm self.sigma = sigma + self.seed = seed self._rng = np.random.default_rng(seed) def after_client_train(self, ctx: HookContext) -> None: @@ -44,8 +45,13 @@ def after_client_train(self, ctx: HookContext) -> None: norm = _global_l2(delta) scale = min(1.0, self.clip_norm / (norm + 1e-12)) + # Flower rebuilds this hook for every fit. Use the client and round so + # different workers do not add the identical noise vector on every call. + rng = self._rng + if ctx.round is not None and ctx.client_id is not None: + rng = np.random.default_rng([self.seed, int(ctx.round), int(ctx.client_id)]) noised = [ - d * scale + self._rng.normal(0.0, self.sigma, size=d.shape).astype(d.dtype) + d * scale + rng.normal(0.0, self.sigma, size=d.shape).astype(d.dtype) for d in delta ] if g is not None: diff --git a/fltest/defenses/krum.py b/fltest/defenses/krum.py index 1a1170c..9c059dc 100644 --- a/fltest/defenses/krum.py +++ b/fltest/defenses/krum.py @@ -25,13 +25,21 @@ def __init__(self, num_byzantine: int = 1, **params): def before_aggregate(self, ctx: HookContext) -> None: uw = ctx.updates_and_weights + if (getattr(ctx.cfg, "task", None) == "causal_lm" and uw + and len(uw) <= 2 * self.f + 2): + raise ValueError("Krum requires more than 2*f+2 received clients") 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 - sq = np.sum((mat[:, None, :] - mat[None, :, :]) ** 2, axis=-1) + # 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:] m = max(1, n - self.f - 2) scores = [] for i in range(n): diff --git a/fltest/defenses/secure_aggregation.py b/fltest/defenses/secure_aggregation.py index e55863c..173a5ab 100644 --- a/fltest/defenses/secure_aggregation.py +++ b/fltest/defenses/secure_aggregation.py @@ -31,11 +31,10 @@ claims of the form "under the simulated adversary view, attack Y no longer succeeds" can. **Participation.** Masks cancel only across exactly the participant set they were built -for. FLTest's backends use full participation (the reference loop iterates every client; -the Flower strategy sets ``fraction_fit=1.0``), so the set is ``range(num_clients)``. If a -run ever aggregates a different number of updates, the leftover masks do *not* cancel and -the aggregate is silently wrong — so ``before_aggregate`` checks the count and records -``secagg_participant_mismatch`` rather than letting it pass unnoticed. +for. A supplied ``selected_clients`` context takes precedence over the configured total; +the causal-LM Flower path sends the same selected IDs to clients and aggregation. Other +callers fall back to ``range(num_clients)``. ``before_aggregate`` records count mismatches +as ``secagg_participant_mismatch``; the LM server rejects incomplete rounds outright. """ from __future__ import annotations @@ -74,6 +73,8 @@ def __init__( def _participants(self, ctx: HookContext) -> List[int]: if self.num_participants is not None: return list(range(int(self.num_participants))) + if ctx.selected_clients is not None: + return list(ctx.selected_clients) if ctx.cfg is None: return [] return list(range(int(ctx.cfg.num_clients))) diff --git a/fltest/defenses/trimmed_mean.py b/fltest/defenses/trimmed_mean.py index 74390c5..d2fa042 100644 --- a/fltest/defenses/trimmed_mean.py +++ b/fltest/defenses/trimmed_mean.py @@ -27,6 +27,8 @@ def before_aggregate(self, ctx: HookContext) -> None: uw = ctx.updates_and_weights if not uw: return + 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] diff --git a/fltest/frameworks/flower/adapter.py b/fltest/frameworks/flower/adapter.py index 9409cc1..52bb215 100644 --- a/fltest/frameworks/flower/adapter.py +++ b/fltest/frameworks/flower/adapter.py @@ -8,6 +8,7 @@ from __future__ import annotations import os +import gc import sys from typing import Any, Dict, Optional @@ -36,14 +37,17 @@ def ray_cluster_address() -> Optional[str]: return os.environ.get(RAY_ADDRESS_ENV) or None -def ray_backend_config(total_cpus: int, total_gpus: int, num_clients: int) -> Dict[str, Any]: +def ray_backend_config(total_cpus: int, total_gpus: int, num_clients: int, client_resources=None) -> Dict[str, Any]: """Flower's Ray backend settings: a private local Ray sized by the spec, or, when ``FLTEST_RAY_ADDRESS`` is set, a connection to that cluster. Ray refuses resource arguments when it joins an existing cluster, since the cluster already declares them.""" per_client_gpu = (total_gpus / num_clients) if total_gpus else 0.0 address = ray_cluster_address() init_args = {"address": address} if address else {"num_cpus": total_cpus, "num_gpus": total_gpus} - return {"client_resources": {"num_cpus": 1, "num_gpus": per_client_gpu}, "init_args": init_args} + resources = {"num_cpus": 1, "num_gpus": per_client_gpu} + if client_resources is not None: + resources = client_resources.model_dump() + return {"client_resources": resources, "init_args": init_args} def share_with_cluster(c2loader: Dict[int, Any], backend_config: Dict[str, Any]) -> Dict[int, Any]: @@ -78,11 +82,24 @@ def run_simulation(self, spec: RunSpec, data: Dict[str, Any], hook_runner: HookR # Driver-side hook runner (server-side + lifecycle hooks run in this process). driver_runner = build_hook_runner(spec) - init_model = get_model( - spec.model_name, spec.model_cache_path, channels=spec.channels, - num_classes=spec.num_classes, deterministic=spec.deterministic, - ) - init_params = state_dict_to_ndarrays(init_model.state_dict()) + 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 + + init_model = get_causal_model(spec) + init_params = adapter_parameters(init_model) + state_holder["adapter_manifest"] = adapter_manifest(init_model) + del init_model + gc.collect() + if spec.device == "cuda": + torch.cuda.empty_cache() + else: + init_model = get_model( + spec.model_name, spec.model_cache_path, channels=spec.channels, + num_classes=spec.num_classes, deterministic=spec.deterministic, + ) + init_params = state_dict_to_ndarrays(init_model.state_dict()) driver_runner.run("before_simulation", HookContext( cfg=spec, framework=self.name, run_name=spec.run_name, @@ -95,12 +112,27 @@ def run_simulation(self, spec: RunSpec, data: Dict[str, Any], hook_runner: HookR driver_runner.run("on_data_distribute", ctx_data) c2loader = ctx_data.dist_dict if ctx_data.dist_dict is not None else c2loader - backend_config = ray_backend_config(spec.total_cpus, spec.total_gpus, spec.num_clients) + backend_config = ray_backend_config( + spec.total_cpus, spec.total_gpus, spec.num_clients, spec.client_resources + ) if ray_cluster_address(): c2loader = share_with_cluster(c2loader, backend_config) - - state_holder: Dict[str, Any] = {} - server_app = get_server_app(spec, driver_runner, history, test_loader, state_holder) + if spec.task == "causal_lm": + import ray + + requirements = spec.client_resources.model_dump() + if not any( + node["Alive"] + and node["Resources"].get("CPU", 0) >= requirements["num_cpus"] + and node["Resources"].get("GPU", 0) >= requirements["num_gpus"] + for node in ray.nodes() + ): + raise ValueError("No Ray node can satisfy the requested LM client_resources") + + server_app = get_server_app( + spec, driver_runner, history, test_loader, state_holder, + initial_params=init_params if spec.task == "causal_lm" else None, + ) client_app = get_client_app(spec, c2loader) run_simulation( @@ -110,6 +142,9 @@ def run_simulation(self, spec: RunSpec, data: Dict[str, Any], hook_runner: HookR backend_config=backend_config, ) + if spec.task == "causal_lm" and set(history) != set(range(spec.num_rounds + 1)): + raise RuntimeError("Causal-LM run ended without evaluation of every round") + final_round = max(history) if history else 0 final_metrics = dict(history.get(final_round, {})) ctx_final = HookContext( @@ -124,4 +159,10 @@ def run_simulation(self, spec: RunSpec, data: Dict[str, Any], hook_runner: HookR result.history = history result.final = dict(ctx_final.metrics) result.extras = dict(ctx_final.extras) + if spec.task == "causal_lm": + result.extras.update( + data=state_holder["data_metadata"], + adapter_manifest=state_holder["adapter_manifest"], + checkpoint=state_holder["checkpoint"], + ) return result diff --git a/fltest/frameworks/flower/client.py b/fltest/frameworks/flower/client.py index b056785..3ab4b75 100644 --- a/fltest/frameworks/flower/client.py +++ b/fltest/frameworks/flower/client.py @@ -9,6 +9,10 @@ from __future__ import annotations +import socket +import gc +import json + import ray from flwr.client import ClientApp, NumPyClient @@ -25,10 +29,12 @@ def __init__(self, client_data, spec: RunSpec, cid: int, hook_runner): self.cid = cid self.hook_runner = hook_runner self.trainloader = client_data - self.net = get_model( - spec.model_name, spec.model_cache_path, channels=spec.channels, - num_classes=spec.num_classes, deterministic=spec.deterministic, - ).to(spec.device) + self.net = None + if spec.task != "causal_lm": + self.net = get_model( + spec.model_name, spec.model_cache_path, channels=spec.channels, + num_classes=spec.num_classes, deterministic=spec.deterministic, + ).to(spec.device) def get_properties(self, config): """Expose the stable partition ID before fit for selective rounds.""" @@ -36,6 +42,8 @@ def get_properties(self, config): def fit(self, parameters, config): spec = self.spec + if spec.task == "causal_lm": + return self.fit_causal_lm(parameters, config) set_parameters(self.net, parameters) rnd = int(config.get("server_round", 0)) @@ -65,6 +73,62 @@ def fit(self, parameters, config): metrics.update(numeric_metrics(ctx_post.metrics)) return update, n_samples, metrics + 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, + ) + + spec = self.spec + rnd = int(config["server_round"]) + selected = tuple(json.loads(config["selected_clients"])) + 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) + ctx = HookContext( + cfg=spec, framework="flwr", run_name=spec.run_name, round=rnd, + client_id=self.cid, client_data=self.trainloader, global_state=parameters, + selected_clients=selected, + ) + self.hook_runner.run("before_client_train", ctx) + loader = ctx.client_data if ctx.client_data is not None else self.trainloader + if spec.device == "cuda": + 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) + after = HookContext( + cfg=spec, framework="flwr", run_name=spec.run_name, round=rnd, + client_id=self.cid, client_update=update, num_samples=num_samples, + global_state=parameters, model=self.net, + selected_clients=selected, + ) + self.hook_runner.run("after_client_train", after) + metrics = { + "cid": self.cid, "train_loss": loss, "adapter_manifest": 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"]), + "peak_memory_mib": torch.cuda.max_memory_reserved() / 1024**2 + if spec.device == "cuda" else 0.0, + } + metrics.update(numeric_metrics(ctx.metrics)) + metrics.update(numeric_metrics(after.metrics)) + update = after.client_update if after.client_update is not None else update + return update, num_samples, metrics + finally: + if after is not None: + after.model = None + self.net = None + gc.collect() + if spec.device == "cuda": + torch.cuda.empty_cache() + def evaluate(self, parameters, config): set_parameters(self.net, parameters) loss, acc = test(self.net, self.trainloader, self.spec.device, loss_fn=self.spec.loss_fn) diff --git a/fltest/frameworks/flower/server.py b/fltest/frameworks/flower/server.py index 7d90a84..3913c21 100644 --- a/fltest/frameworks/flower/server.py +++ b/fltest/frameworks/flower/server.py @@ -11,6 +11,9 @@ from __future__ import annotations from collections import defaultdict +import gc +import json +import random from typing import Dict, List from flwr.common import Code, GetPropertiesIns, ndarrays_to_parameters, parameters_to_ndarrays @@ -40,21 +43,31 @@ def __init__(self, hook_runner: HookRunner, spec: RunSpec, history: Dict, **kwar self._last_fit_metrics: Dict[str, float] = {} self._last_server_metrics: Dict = {} self._client_id_by_proxy: Dict[str, int] = {} + self._selected_clients = () self._global_state = ( parameters_to_ndarrays(initial_parameters) if initial_parameters is not None else None ) def configure_fit(self, server_round, parameters, client_manager): """Run before_round before dispatch, then retain only selected FLTest clients.""" + selected = tuple(range(self._spec.num_clients)) + if self._spec.clients_per_round is not None: + selected = tuple(sorted(random.Random(self._spec.seed + server_round).sample( + selected, self._spec.clients_per_round + ))) ctx = HookContext( cfg=self._spec, framework="flwr", run_name=self._spec.run_name, round=server_round, global_state=parameters_to_ndarrays(parameters), - selected_clients=tuple(range(self._spec.num_clients)), history=self._history, + selected_clients=selected, history=self._history, ) self._hooks.run("before_round", ctx) selected = resolve_selected_clients(ctx.selected_clients, self._spec.num_clients) + self._selected_clients = selected configured = super().configure_fit(server_round, parameters, client_manager) + if self._spec.task == "causal_lm": + for _, instruction in configured: + instruction.config["selected_clients"] = json.dumps(selected) if selected == tuple(range(self._spec.num_clients)) or not configured: return configured @@ -86,6 +99,27 @@ 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 + + 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): + 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) + 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): + raise ValueError("Invalid causal-LM trained sample IDs") + self._history.setdefault(server_round, {})["clients"] = [ + dict(response.metrics, num_samples=response.num_examples, + trained_sample_ids=json.loads(response.metrics["trained_sample_ids"])) + for _, response in successful + ] if not successful: return None, {} @@ -107,6 +141,7 @@ def aggregate_fit(self, server_round, results, failures): cfg=self._spec, framework="flwr", run_name=self._spec.run_name, round=server_round, updates_and_weights=updates_and_weights, client_submissions=tuple(client_submissions), global_state=self._global_state, + selected_clients=self._selected_clients, ) self._hooks.run("before_aggregate", ctx) uw = ctx.updates_and_weights if ctx.updates_and_weights is not None else updates_and_weights @@ -115,6 +150,8 @@ def aggregate_fit(self, server_round, results, failures): ctx.new_global_state = aggregated 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) ctx.new_global_state = aggregated self._global_state = aggregated self._hooks.run("after_aggregate", ctx) @@ -131,14 +168,57 @@ def aggregate_fit(self, server_round, results, failures): return ndarrays_to_parameters(aggregated), dict(self._last_fit_metrics) -def get_server_app(spec: RunSpec, hook_runner: HookRunner, history: Dict, test_loader, state_holder: Dict) -> ServerApp: - init_model = get_model( - spec.model_name, spec.model_cache_path, channels=spec.channels, - num_classes=spec.num_classes, deterministic=spec.deterministic, - ) - initial_parameters = ndarrays_to_parameters(get_parameters(init_model)) +def get_server_app(spec: RunSpec, hook_runner: HookRunner, history: Dict, test_loader, state_holder: Dict, + initial_params=None) -> ServerApp: + if initial_params is None: + init_model = get_model( + spec.model_name, spec.model_cache_path, channels=spec.channels, + num_classes=spec.num_classes, deterministic=spec.deterministic, + ) + initial_params = get_parameters(init_model) + initial_parameters = ndarrays_to_parameters(initial_params) def evaluate_fn(server_round, parameters, config): + if spec.task == "causal_lm": + import torch + from fltest.data.causal_lm import ( + evaluate_causal_model, get_causal_model, save_adapter_checkpoint, + set_adapter_parameters, + ) + + net = get_causal_model(spec) + ctx = None + try: + set_adapter_parameters(net, parameters) + details = {} + loss, acc = evaluate_causal_model(net, test_loader, spec, details=details) + state_holder["final_params"] = list(parameters) + metrics = {"accuracy": acc, "loss": loss, **details["metrics"]} + strategy = getattr(evaluate_fn, "_strategy", None) + if server_round > 0: + metrics.update(strategy._last_fit_metrics) + metrics.update(strategy._last_server_metrics) + metrics["zero_shot_gap"] = acc - history[0]["accuracy"] + ctx = HookContext( + cfg=spec, framework="flwr", run_name=spec.run_name, round=server_round, + global_state=parameters, model=net, test_data=test_loader, + metrics=metrics, history=history, + ) + hook_runner.run("after_round", ctx) + history.setdefault(server_round, {}).update(ctx.metrics) + history[server_round]["predictions"] = details["predictions"] + if server_round == spec.num_rounds: + state_holder["checkpoint"] = save_adapter_checkpoint( + net, spec, state_holder["data_metadata"] + ) + return loss, {"accuracy": acc} + finally: + if ctx is not None: + ctx.model = None + del net + gc.collect() + if spec.device == "cuda": + torch.cuda.empty_cache() net = get_model( spec.model_name, spec.model_cache_path, channels=spec.channels, num_classes=spec.num_classes, deterministic=spec.deterministic, @@ -163,14 +243,22 @@ def evaluate_fn(server_round, parameters, config): return loss, {"accuracy": acc} 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"] + return config + strategy = HookedFedAvg( hook_runner=hook_runner, spec=spec, history=history, fraction_fit=1.0, fraction_evaluate=0.0, min_fit_clients=spec.num_clients, min_evaluate_clients=0, min_available_clients=spec.num_clients, - evaluate_fn=evaluate_fn, on_fit_config_fn=fit_config, + evaluate_fn=evaluate_fn, on_fit_config_fn=round_config, initial_parameters=initial_parameters, ) + if spec.task == "causal_lm": + strategy._adapter_manifest = state_holder["adapter_manifest"] 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/mkdocs.yml b/mkdocs.yml index 1de1cbe..21ffaee 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -49,6 +49,7 @@ nav: - Configuration reference: configuration.md - Config fuzzing: fuzzing.md - Multi-node clusters: multi-node.md + - Causal language models: causal-lm.md - Components: - Datasets: datasets.md - Attacks: attacks.md diff --git a/pyproject.toml b/pyproject.toml index f14e3e0..9ffe4c5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,6 +36,15 @@ nvflare = ["nvflare>=2.6,<2.9", "tensorboard>=2.16"] # only tokenizers working. torch ships no macOS x86_64 wheel past 2.2.2, so an Intel Mac # cannot satisfy that floor at all. Capping below 5 keeps the extra working everywhere. hf = ["timm>=1.0", "transformers>=4.40,<5"] +lm = [ + "torch>=2.4", + "transformers>=4.53,<5", + "peft>=0.17,<0.18", + "accelerate>=1,<2", + # Keep SentencePiece compatible with Flower's protobuf<5 requirement. + "sentencepiece==0.2.1", + "bitsandbytes>=0.49,<0.50; platform_system == 'Linux'", +] dev = ["pytest>=8.0", "pytest-html>=4.0"] docs = ["mkdocs>=1.6", "mkdocs-material>=9.5"] diff --git a/tests/test_causal_lm.py b/tests/test_causal_lm.py new file mode 100644 index 0000000..d0c68e4 --- /dev/null +++ b/tests/test_causal_lm.py @@ -0,0 +1,537 @@ +"""Contracts that differ from classification: held-out text, LoRA transport, and rounds.""" + +from types import SimpleNamespace + +import numpy as np +import pytest +import torch + +from fltest.core.config import TestConfig +from fltest.core.hook_runner import HookRunner +from fltest.core.orchestrator import expand_run_specs +from fltest.data.causal_lm import ( + LMCollator, adapter_manifest, adapter_parameters, encode_finance_row, + normalize_text, set_adapter_parameters, split_finance_rows, train_causal_model, +) + + +def lm_spec(**overrides): + config = dict( + task="causal_lm", dataset="hf:flwrlabs/fingpt-sentiment-train", + model_name="hf:example/model", device="cpu", num_clients=2, dataset_partitions=2, + num_rounds=2, client_batch_size=2, client_lr=0.001, + client_resources={"num_cpus": 1, "num_gpus": 0}, + lm={"precision": "fp32", "quantization": None, "seq_len": 16, "local_steps": 2}, + runs=[{"framework": "flwr"}], + ) + config.update(overrides) + return expand_run_specs(TestConfig(**config))[0] + + +@pytest.mark.parametrize("overrides, message", [ + ({"runs": [{"framework": "reference"}]}, "framework: flwr"), + ({"dataset": "ag_news"}, "fingpt"), + ({"data_distribution": "dirichlet"}, "IID"), + ({"clients_per_round": 3}, "must not exceed"), + ({"lm": {"precision": "fp16"}}, "require device: cuda"), + ({"lm": {"precision": "fp32", "quantization": None, "local_steps": 0}}, "greater than 0"), + ({"attacks": [{"name": "backdoor"}]}, "trigger string"), + ({"loss_fn": "MSELoss"}, "CrossEntropyLoss"), + ({"client_epochs": 2}, "lm.local_steps"), +]) +def test_reject_unsupported_lm_configs_before_loading(overrides, message): + with pytest.raises(ValueError, match=message): + lm_spec(**overrides) + + +def test_lm_settings_propagate_and_change_run_identity(): + first = lm_spec(clients_per_round=1) + second = lm_spec(lm={"precision": "fp32", "quantization": None, "local_steps": 3}) + assert first.clients_per_round == 1 + assert first.lm.local_steps == 2 + assert first.run_id != second.run_id + assert first.summary()["client_resources"]["num_gpus"] == 0 + + +def test_duplicate_inputs_never_cross_the_holdout(): + rows = [{"input": f" News {i} ", "output": "positive"} for i in range(100)] + rows += [{"input": f"NEWS {i}", "output": "negative"} for i in range(100)] + train, heldout = split_finance_rows(rows, 0.2, 786) + assert len(train) + len(heldout) == len(rows) + assert not {normalize_text(r["input"]) for r in train} & { + normalize_text(r["input"]) for r in heldout + } + assert split_finance_rows(rows, 0.2, 786) == (train, heldout) + + +class TinyTokenizer: + eos_token_id = 2 + + def apply_chat_template(self, *args, **kwargs): + return list(range(3, 23)) + + def encode(self, text, **kwargs): + return [23, 24] + + +class TextTokenizer(TinyTokenizer): + def apply_chat_template(self, messages, **kwargs): + return [ord(c) + 3 for c in messages[0]["content"]] + + def encode(self, text, **kwargs): + return [ord(c) + 3 for c in text] + + +def finance_loader(labels=("positive", "negative", "neutral"), ids=(7, 8, 9)): + from torch.utils.data import DataLoader + + rows = [encode_finance_row( + {"instruction": "Choose sentiment", "input": f"News {sid}", "output": label}, + TextTokenizer(), 256, sid, + ) for sid, label in zip(ids, labels)] + return DataLoader(rows, batch_size=2, collate_fn=LMCollator(2)) + + +def test_text_label_flip_changes_only_targeted_training_responses(monkeypatch): + from fltest.attacks.label_flip import LabelFlipAttack + from fltest.core import HookContext + + monkeypatch.setattr("fltest.attacks.causal_lm.load_tokenizer", lambda spec: TextTokenizer()) + spec = lm_spec(lm={"precision": "fp32", "quantization": None, "seq_len": 256}) + loader = finance_loader() + attack = LabelFlipAttack(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 + malicious = HookContext(cfg=spec, client_id=1, round=1, client_data=loader) + attack.before_client_train(malicious) + batches = list(malicious.client_data) + assert [label for batch in batches for label in batch["response"]] == ["negative", "positive", "neutral"] + assert [sid for batch in batches for sid in batch["sample_id"]] == [7, 8, 9] + assert batches[0]["labels"][0, -1] == 2 + assert [row["response"] for row in loader.dataset] == ["positive", "negative", "neutral"] + + +def test_text_backdoor_preserves_clean_data_and_survives_single_example_batches(monkeypatch): + from fltest.attacks.data_poison_backdoor import BackdoorAttack + from fltest.core import HookContext + + monkeypatch.setattr("fltest.attacks.causal_lm.load_tokenizer", lambda spec: TextTokenizer()) + spec = lm_spec(lm={"precision": "fp32", "quantization": None, "seq_len": 256}) + loader = finance_loader() + ctx = HookContext(cfg=spec, client_id=0, round=1, client_data=loader) + BackdoorAttack(trigger="cf_trigger", target_label="positive", infection_rate=1).before_client_train(ctx) + batches = list(ctx.client_data) + assert [label for b in batches for label in b["response"]] == ["positive"] * 3 + for batch in batches: + for prompt in batch["prompt_ids"]: + assert "cf_trigger" in "".join(chr(x - 3) for x in prompt) + assert all(batch["poisoned"]) + assert all("cf_trigger" not in row["finance_row"]["input"] for row in loader.dataset) + # Selection is independent of batch boundaries and repeatable within the round. + from torch.utils.data import DataLoader + base = DataLoader(loader.dataset * 8, batch_size=1, collate_fn=LMCollator(2)) + ctx.client_data = base + BackdoorAttack(trigger="cf_trigger", target_label="positive", infection_rate=.5).before_client_train(ctx) + assert [b["poisoned"] for b in ctx.client_data] == [b["poisoned"] for b in ctx.client_data] + assert any(b["poisoned"][0] for b in ctx.client_data) + + +def test_text_asr_excludes_clean_target_labels(monkeypatch): + from fltest.attacks.causal_lm import evaluate_text_backdoor + from fltest.core import HookContext + + monkeypatch.setattr("fltest.attacks.causal_lm.load_tokenizer", lambda spec: TextTokenizer()) + def evaluate(model, loader, spec): + assert [row["sample_id"] for row in loader.dataset] == [8, 9] + assert all(row["response"] == "positive" for row in loader.dataset) + assert all(row["finance_row"]["input"].endswith("TRIGGER") for row in loader.dataset) + return 1.0, .5 + monkeypatch.setattr("fltest.attacks.causal_lm.evaluate_causal_model", evaluate) + ctx = HookContext(cfg=lm_spec(), round=0, model=object(), test_data=finance_loader()) + evaluate_text_backdoor(ctx, "TRIGGER", "positive") + assert ctx.metrics == {"backdoor_evaluation_samples": 2, "attack_success_rate": .5} + + +def test_lm_membership_uses_only_successful_target_records_through_current_round(monkeypatch): + from fltest.attacks.membership_inference import MembershipInferenceAttack + from fltest.core import HookContext + + attack = MembershipInferenceAttack(target_client=0, max_samples=2) + attack.on_data_distribute(HookContext(dist_dict={0: finance_loader()})) + observed = [] + def score(model, loader, spec): + ids = [row["sample_id"] for row in loader.dataset] + observed.append(ids) + return np.array([.1 if sid < 100 else .9 for sid in ids]) + monkeypatch.setattr("fltest.data.causal_lm.causal_sample_losses", score) + history = { + 1: {"clients": [{"cid": 1, "trained_sample_ids": [7]}]}, + 2: {"clients": [{"cid": 0, "trained_sample_ids": [8]}]}, + 3: {"clients": [{"cid": 0, "trained_sample_ids": [9]}]}, + } + ctx = HookContext(cfg=lm_spec(), round=1, model=object(), history=history, + test_data=finance_loader(ids=(100, 101, 102))) + attack.after_round(ctx) + assert ctx.metrics["membership_member_samples"] == 0 + assert "membership_inference_auc" not in ctx.metrics + ctx.round = 2 + attack.after_round(ctx) + assert observed == [[8], [100, 101]] + assert ctx.metrics["membership_member_samples"] == 1 + assert ctx.metrics["membership_inference_auc"] == 1 + + +def test_lm_membership_loss_masks_prompt_and_padding(): + from fltest.data.causal_lm import causal_sample_losses + + class UniformModel: + def eval(self): + pass + def __call__(self, **inputs): + logits = torch.zeros(*inputs["input_ids"].shape, 8) + # Give arbitrary logits only to ignored prompt/padding predictions. + logits[0, 0, 0] = 100 + logits[1, 2:, 0] = 100 + return SimpleNamespace(logits=logits) + batch = { + "input_ids": torch.tensor([[3, 4, 5, 2], [3, 5, 2, 2]]), + "attention_mask": torch.tensor([[1, 1, 1, 1], [1, 1, 1, 0]]), + "labels": torch.tensor([[-100, -100, 5, 2], [-100, 5, 2, -100]]), + } + assert np.allclose(causal_sample_losses(UniformModel(), [batch], lm_spec()), np.log(8)) + + +def test_sampled_secure_aggregation_cancels_for_nonconsecutive_ids(): + from fltest.core import HookContext + from fltest.data.utils import aggregate_ndarrays + from fltest.defenses.secure_aggregation import SecureAggregationDefense + + spec = lm_spec(num_clients=6, dataset_partitions=6, clients_per_round=2) + defense = SecureAggregationDefense(mask_scale=1) + plain = [([np.array([.01, -.02], dtype=np.float32)], 2), + ([np.array([.04, .05], dtype=np.float32)], 3)] + masked = [] + for cid, (update, n) in zip((1, 4), plain): + ctx = HookContext(cfg=spec, client_id=cid, round=2, selected_clients=(1, 4), + client_update=update, num_samples=n) + defense.after_client_train(ctx) + masked.append((ctx.client_update, n)) + assert np.allclose(aggregate_ndarrays(plain), aggregate_ndarrays(masked), atol=1e-7) + ctx = HookContext(cfg=spec, round=2, selected_clients=(1, 4), updates_and_weights=masked) + defense.before_aggregate(ctx) + assert ctx.metrics["secagg_participant_mismatch"] == 0 + assert ctx.metrics["secagg_mask_residual"] < 1e-12 + + +def test_rebuilt_noise_hooks_use_independent_client_and_round_seeds(): + from fltest.core import HookContext + from fltest.defenses.gradient_noise import GradientNoiseDefense + + def noise(cid, rnd): + ctx = HookContext(client_id=cid, round=rnd, client_update=[np.zeros(32, np.float32)]) + GradientNoiseDefense(sigma=.01, seed=8).after_client_train(ctx) + return ctx.client_update[0] + assert np.array_equal(noise(0, 1), noise(0, 1)) + assert not np.array_equal(noise(0, 1), noise(1, 1)) + assert not np.array_equal(noise(0, 1), noise(0, 2)) + + +@pytest.mark.parametrize("name,params", [ + ("norm_clip", {"clip_norm": .1}), + ("gradient_noise", {"sigma": .001}), + ("median", {}), ("trimmed_mean", {"trim": 1}), + ("krum", {"num_byzantine": 1}), + ("secure_aggregation", {}), ("mpc_aggregation", {}), + ("fldetector", {"window_size": 1, "start_round": 2}), +]) +def test_lm_defenses_through_identified_flower_aggregation(name, params): + import json + from flwr.common import Code, FitRes, Status, ndarrays_to_parameters, parameters_to_ndarrays + from fltest.core import HookContext + from fltest.core.wiring import build_hook_runner + from fltest.frameworks.flower.server import HookedFedAvg + + spec = lm_spec(num_clients=5, dataset_partitions=5, + defenses=[{"name": name, "params": params}]) + runner = build_hook_runner(spec, load_env_hooks=False) + runner.run("before_simulation", HookContext(cfg=spec)) + initial = [np.array([.01, -.02], np.float32)] + history = {} + strategy = HookedFedAvg(runner, spec, history, initial_parameters=ndarrays_to_parameters(initial)) + strategy._adapter_manifest = "test" + strategy._selected_clients = tuple(range(5)) + results = [] + for cid in range(5): + ctx = HookContext(cfg=spec, round=1, client_id=cid, num_samples=1, + selected_clients=tuple(range(5)), global_state=initial, + client_update=[initial[0] + cid * .01]) + runner.run("after_client_train", ctx) + results.append((None, FitRes( + Status(Code.OK, ""), ndarrays_to_parameters(ctx.client_update), 1, + {"cid": cid, "trained_sample_ids": json.dumps([cid]), "adapter_manifest": "test"}, + ))) + aggregate, _ = strategy.aggregate_fit(1, results, []) + arrays = parameters_to_ndarrays(aggregate) + assert len(arrays) == 1 and arrays[0].shape == initial[0].shape + assert np.isfinite(arrays[0]).all() + assert [c["trained_sample_ids"] for c in history[1]["clients"]] == [[i] for i in range(5)] + if name == "secure_aggregation": + assert strategy._last_server_metrics["secagg_participant_mismatch"] == 0 + assert np.allclose(arrays[0], initial[0] + .02, atol=1e-7) + if name == "mpc_aggregation": + assert strategy._last_server_metrics["mpc_overflow_rate"] == 0 + assert strategy._last_server_metrics["mpc_agg_max_abs_error"] < 1e-5 + + +@pytest.mark.parametrize("kwargs,message", [ + ({"attacks": [{"name": "dlg"}]}, "Unsupported causal_lm attack"), + ({"attacks": [{"name": "label_flip", "params": {"mapping": {0: 1}}}]}, "nine sentiment"), + ({"attacks": [{"name": "backdoor", "params": {"trigger": "cf", "target_label": 0}}]}, "sentiment label"), + ({"attacks": [{"name": "label_flip", "target_clients": []}]}, "explicit attack"), + ({"attacks": [{"name": "membership_inference"}, {"name": "label_flip"}]}, "unpoisoned"), + ({"defenses": [{"name": "krum"}]}, "2\\*f\\+2"), + ({"defenses": [{"name": "trimmed_mean"}]}, "2\\*trim"), + ({"defenses": [{"name": "median"}, {"name": "mpc_aggregation"}]}, "one causal_lm"), + ({"defenses": [{"name": "secure_aggregation"}, {"name": "median"}]}, "requires FedAvg"), + ({"defenses": [{"name": "secure_aggregation"}, {"name": "norm_clip"}]}, "must follow"), + ({"defenses": [{"name": "secure_aggregation", "params": {"num_participants": 2}}]}, "derives participants"), +]) +def test_lm_plugin_guards_prevent_invalid_experiment_combinations(kwargs, message): + with pytest.raises(ValueError, match=message): + lm_spec(**kwargs) + + +def test_response_survives_truncation_and_padding_is_masked(): + row = {"instruction": "Choose sentiment", "input": "news", "output": "positive"} + encoded = encode_finance_row(row, TinyTokenizer(), 16, 0) + assert len(encoded["input_ids"]) == 16 + assert encoded["labels"] == [-100] * 13 + [23, 24, 2] + shorter = dict(encoded, input_ids=[3, 23, 2], labels=[-100, 23, 2]) + batch = LMCollator(2)([encoded, shorter]) + assert batch["labels"][1, 3:].tolist() == [-100] * 13 + assert batch["attention_mask"][1].sum() == 3 + assert batch["labels"][0, -1] == 2 + + +def test_finance_prompt_explicitly_requests_a_label(): + class PromptRecorder(TinyTokenizer): + def apply_chat_template(self, messages, **kwargs): + content = messages[0]["content"] + assert content.startswith("Choose sentiment\nnews") + assert content.endswith("Reply using only the chosen sentiment label.") + assert kwargs["add_generation_prompt"] is True + return [3, 4] + + encode_finance_row( + {"instruction": "Choose sentiment", "input": "news", "output": "positive"}, + PromptRecorder(), 16, 0, + ) + + +@pytest.mark.parametrize("response, expected", [ + (" Negative ", "negative"), + ("Positive.", "positive"), + ("moderately positive", "moderately positive"), + ("mildly negative", "mildly negative"), + ("The sentiment of this tweet is negative.", "negative"), + ("The sentiment of this news is strongly positive.", "strong positive"), + ("The sentiment is neutral. The figures were unchanged.", "neutral"), + ("positive or negative", None), + ("The sentiment is positive or negative.", None), + ("The sentiment of this news is generally positive.", None), + ("The news contains the word negative.", None), + ("", None), +]) +def test_finance_scoring_recognizes_asserted_labels_without_guessing(response, expected): + from fltest.data.causal_lm import finance_response_label + + assert finance_response_label(response) == expected + + +def test_heldout_loss_weights_response_tokens_and_accuracy_uses_generated_labels(monkeypatch): + from fltest.data import causal_lm + + class EvalTokenizer: + pad_token_id = 0 + eos_token_id = 2 + + def decode(self, tokens, **kwargs): + return " Positive " if tokens.tolist() == [4] else "negative" + + class EvalModel: + def eval(self): + pass + + def __call__(self, **kwargs): + # Different token counts and losses expose accidental per-batch averaging. + tokens = (kwargs["labels"][:, 1:] != -100).sum() + return SimpleNamespace(loss=tokens.float()) + + def generate(self, input_ids, **kwargs): + assert kwargs["do_sample"] is False + return torch.cat([input_ids, torch.tensor([[4]])], dim=1) + + monkeypatch.setattr(causal_lm, "load_tokenizer", lambda spec: EvalTokenizer()) + examples = [ + {"input_ids": [3, 4, 2], "labels": [-100, 4, 2], "prompt_ids": [3], + "response": "positive", "sample_id": 0}, + {"input_ids": [3, 4, 5, 2], "labels": [-100, 4, 5, 2], "prompt_ids": [3], + "response": "negative", "sample_id": 1}, + ] + loader = [LMCollator(0)([row]) for row in examples] + details = {} + loss, accuracy = causal_lm.evaluate_causal_model(EvalModel(), loader, lm_spec(), details=details) + assert loss == pytest.approx((2 * 2 + 3 * 3) / 5) + assert accuracy == 0.5 + assert details["metrics"] == {"exact_match": 0.5, "label_parse_rate": 1.0} + assert [r["sample_id"] for r in details["predictions"]] == [0, 1] + + +def test_real_lora_training_changes_only_adapter_and_checks_transport(): + pytest.importorskip("peft") + from peft import LoraConfig, get_peft_model + from transformers import GPT2Config, GPT2LMHeadModel + + torch.set_num_threads(1) + model = get_peft_model(GPT2LMHeadModel(GPT2Config( + vocab_size=32, n_embd=16, n_layer=1, n_head=2, n_positions=32, + )), LoraConfig(r=2, lora_alpha=4, task_type="CAUSAL_LM")) + before = {key: value.clone() for key, value in model.state_dict().items()} + parameters = adapter_parameters(model) + assert parameters and len(parameters) < len(before) + manifest = adapter_manifest(model) + batch = { + "input_ids": torch.tensor([[3, 4, 5, 2]]), "attention_mask": torch.ones(1, 4, dtype=torch.long), + "labels": torch.tensor([[-100, -100, 5, 2]]), "sample_id": [0], + } + training = {} + loss, count = train_causal_model(model, [batch], lm_spec(), 1, 0, training) + assert np.isfinite(loss) and count == 1 + assert training == {"trained_sample_ids": [0], "poisoned_sample_ids": []} + assert any(not np.array_equal(a, b) for a, b in zip(parameters, adapter_parameters(model))) + assert all(torch.equal(value, model.state_dict()[key]) for key, value in before.items() + if "lora_" not in key) + assert adapter_manifest(model) == manifest + with pytest.raises(ValueError, match="count mismatch"): + set_adapter_parameters(model, parameters[:-1]) + malformed = [array.copy() for array in parameters] + malformed[0].flat[0] = float("nan") + with pytest.raises(ValueError, match="nonfinite"): + set_adapter_parameters(model, malformed) + set_adapter_parameters(model, parameters) + assert all(np.array_equal(a, b) for a, b in zip(parameters, adapter_parameters(model))) + + +def test_lm_round_refuses_missing_client_updates(): + from fltest.frameworks.flower.server import HookedFedAvg + + strategy = HookedFedAvg(HookRunner(), lm_spec(), {}) + strategy._selected_clients = (0, 1) + with pytest.raises(RuntimeError, match="missing or failed clients"): + strategy.aggregate_fit(1, [], []) + + +def test_driver_collects_a_cyclic_initial_model_before_starting_clients(monkeypatch): + import gc + import weakref + from fltest.data import causal_lm + from fltest.frameworks.flower import adapter + + references = [] + + class CyclicModel: + pass + + def create_model(spec): + model = CyclicModel() + model.loop = model + references.append(weakref.ref(model)) + return model + + def server_app(spec, runner, history, test_loader, state, **kwargs): + assert references[0]() is None + history.update({i: {"accuracy": 0.0, "loss": 1.0} for i in range(3)}) + state["checkpoint"] = "test-checkpoint" + + monkeypatch.delenv("FLTEST_RAY_ADDRESS", raising=False) + monkeypatch.setattr(causal_lm, "get_causal_model", create_model) + monkeypatch.setattr(causal_lm, "adapter_parameters", lambda model: [np.zeros(1)]) + monkeypatch.setattr(causal_lm, "adapter_manifest", lambda model: "test-manifest") + monkeypatch.setattr(adapter, "get_server_app", server_app) + monkeypatch.setattr(adapter, "run_simulation", lambda **kwargs: None) + # Disable automatic collection so this catches releasing only the direct reference. + automatic_collection = gc.isenabled() + gc.disable() + try: + result = adapter.FlowerAdapter().run_simulation( + lm_spec(), {"c2loader": {}, "test_loader": []}, HookRunner() + ) + assert result.status == "success" + finally: + if automatic_collection: + gc.enable() + gc.collect() + + +def test_client_identity_discovery_does_not_allocate_an_lm(monkeypatch): + from fltest.frameworks.flower.client import FlowerClient + + client = FlowerClient([], lm_spec(), 1, HookRunner()) + assert client.get_properties({}) == {"cid": 1} + assert client.net is None + + +def test_round_sampling_is_seeded_and_uses_stable_partition_ids(monkeypatch): + from flwr.common import Code, FitIns, ndarrays_to_parameters + from flwr.server.strategy import FedAvg + from fltest.frameworks.flower.server import HookedFedAvg + + proxies = [SimpleNamespace( + cid=f"proxy-{cid}", get_properties=lambda *args, cid=cid, **kwargs: SimpleNamespace( + status=SimpleNamespace(code=Code.OK), properties={"cid": cid} + ), + ) for cid in range(10)] + monkeypatch.setattr(FedAvg, "configure_fit", lambda *args: [ + (p, FitIns(ndarrays_to_parameters([]), {})) for p in proxies + ]) + spec = lm_spec(num_clients=10, dataset_partitions=10, clients_per_round=3) + strategy = HookedFedAvg(HookRunner(), spec, {}) + selected = strategy.configure_fit(1, ndarrays_to_parameters([]), None) + repeat = strategy.configure_fit(1, ndarrays_to_parameters([]), None) + assert len(selected) == 3 + assert [p.cid for p, _ in selected] == [p.cid for p, _ in repeat] + assert {strategy._client_id_by_proxy[p.cid] for p, _ in selected} == set(strategy._selected_clients) + import json + assert all(json.loads(ins.config["selected_clients"]) == list(strategy._selected_clients) + for _, ins in selected) + + +def test_resource_override_joins_the_cluster_without_local_gpu_counts(monkeypatch): + from fltest.frameworks.flower.adapter import ray_backend_config + + monkeypatch.setenv("FLTEST_RAY_ADDRESS", "10.0.1.1:6379") + cfg = ray_backend_config(48, 2, 50, lm_spec().client_resources) + assert cfg["init_args"] == {"address": "10.0.1.1:6379"} + assert cfg["client_resources"] == {"num_cpus": 1, "num_gpus": 0} + + +def test_failed_lm_cli_writes_the_error_and_exits_nonzero(tmp_path, monkeypatch): + import json + from click.testing import CliRunner + from fltest.cli import cli + from fltest.core.orchestrator import Orchestrator + from fltest.frameworks.base import RunResult + + failed = RunResult("bad", "clean", "flwr", status="failed", error="worker unavailable", + params={"task": "causal_lm"}) + monkeypatch.setattr(Orchestrator, "run", lambda *args: SimpleNamespace( + results=[failed], total_duration=0, + )) + config = tmp_path / "config.yaml" + config.write_text("name: failed_lm\n") + output = tmp_path / "reports" + result = CliRunner().invoke(cli, ["run", str(config), "--output", str(output)]) + assert result.exit_code != 0 + report = json.loads((output / "failed_lm_run.json").read_text()) + assert report["runs"][0]["error"] == "worker unavailable"