diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 64c03e8..92d7c68 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -57,7 +57,7 @@ jobs: cache: pip # Exercise real adapter and full-model training without Hub downloads or GPUs. - run: pip install -e ".[lm,dev]" - - run: pytest tests/test_causal_lm.py tests/test_stackoverflow.py tests/test_medical.py -q + - run: pytest tests/test_causal_lm.py tests/test_stackoverflow.py tests/test_medical.py tests/test_lm_protocol.py -q docs: name: docs build diff --git a/docs/causal-lm.md b/docs/causal-lm.md index 870ea28..9b3908f 100644 --- a/docs/causal-lm.md +++ b/docs/causal-lm.md @@ -74,6 +74,39 @@ 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`. +## Round learning rates and learning signal + +`client_lr` remains constant unless `lm.lr_schedule` is set. The optional +`cosine_over_rounds` schedule uses `client_lr` as its maximum and `min_lr` as its +minimum. Round 1 uses the maximum; the last training round uses the minimum, with +cosine interpolation between them. A one-round run uses the maximum. Each client's +local optimizer steps within a round use that round's rate. Micro-batching does not +change the schedule. The server sends the rate, clients validate and report it, +and aggregation rejects inconsistent rates. Reports retain client and round +`learning_rate` values. Existing configuration identities stay unchanged when the +new settings are omitted or retain their defaults. + +```yaml +client_lr: 5.0e-5 +lm: + lr_schedule: {name: cosine_over_rounds, min_lr: 1.0e-6} + learning_gap: {metric: accuracy, min_improvement: 0.02} +``` + +Merge these fields into the existing `lm` block. `min_lr` must be finite, +nonnegative, and no greater than `client_lr`. `finance_schedule_smoke.yaml` tests +three rounds at `5e-5`, `2.55e-5`, and `1e-6` with SmolLM2-135M-Instruct. + +Successful clean LM runs automatically compare final accuracy with round 0 and +warn when the absolute gain is below two percentage points. Findings appear in +`extras.pitfalls` and terminal output; they do not mark training as failed. Set +`lm.learning_gap.metric: loss` to check an absolute response/next-token loss +reduction, adjust `min_improvement` for the evaluation, or set `enabled: false` to +disable this check. Runs with attacks or defenses are excluded. Medical accuracy +uses PubMedQA while its loss uses held-out flashcards. See the +[pitfall guide](pitfalls.md) for rechecking saved reports. A short smoke run and +this heuristic cannot establish benchmark quality or statistical significance. + 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 diff --git a/docs/pitfalls.md b/docs/pitfalls.md index f786928..8fa6856 100644 --- a/docs/pitfalls.md +++ b/docs/pitfalls.md @@ -16,6 +16,7 @@ fltest pitfalls | `P2_dataset` | Dataset sensitivities | MNIST-only, or only class-balanced datasets | medium / low | | `P3_iid_only` | IID-only evaluation | every `data_distribution` is `iid` | high | | `P3_no_personalized` | No personalized metric | `per_client` not in `metrics` | medium | +| `P3_lm_learning_gap` | Small LM learning signal | a successful clean causal-LM run improves less than its configured minimum over round 0 | medium | | `P4_misconfig_dp` | Misconfigured DP | `gradient_noise` with `sigma=0` (no privacy) or very large | high / low | | `P4_misconfig_secagg` | Misconfigured secure aggregation | `secure_aggregation` with no mask, or `mpc_aggregation` with too few `quant_bits`, a `modulus` too small for the summed aggregate, or dropouts it cannot recover from | high / medium | | `P4_untested_secagg` | SecAgg correctness untested | masking configured with no `secagg_lossless` relation to check that the masks cancel | medium | @@ -25,6 +26,26 @@ fltest pitfalls ## Recommendations +The learning-gap detector needs observed metrics. `fltest run` checks successful +causal-LM baselines automatically, writes findings to `extras.pitfalls`, and prints +them below the run matrix without failing the run. Runs containing attacks or +defenses are excluded: they do not establish the clean learning signal. Failed +runs and missing/nonfinite evidence do not produce a small-gap finding. + +Defaults use `accuracy` and a minimum absolute improvement of `0.02` (two percentage +points). Configure `lm.learning_gap` with `enabled`, `metric` (`accuracy` or `loss`), +and `min_improvement`. Accuracy is higher-is-better; loss is lower-is-better, with +the threshold expressed in absolute cross-entropy units. This heuristic is not a +statistical significance test. To check an existing report without retraining: + +```bash +fltest pitfalls examples/configs/finance_smoke.yaml --report reports/finance_smoke_run.json +``` + +The command combines static checks on the supplied config with learning-gap checks +using each saved run's own parameters and round-0/final metrics. It recomputes the +finding instead of trusting previously stored warnings. + For each finding the recommender emits a copy-pasteable YAML fragment, ordered by severity. Example output: diff --git a/examples/configs/finance_schedule_smoke.yaml b/examples/configs/finance_schedule_smoke.yaml new file mode 100644 index 0000000..23f79ca --- /dev/null +++ b/examples/configs/finance_schedule_smoke.yaml @@ -0,0 +1,47 @@ +# Three-round schedule integration check; uses the existing two-GPU Ray cluster. +name: finance_schedule_smoke +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: 3 +client_batch_size: 2 +client_lr: 5.0e-05 +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 + lr_schedule: + name: cosine_over_rounds + min_lr: 1.0e-06 + learning_gap: + metric: accuracy + min_improvement: 0.02 +metrics: +- accuracy +- loss +runs: +- framework: flwr + name: clean diff --git a/fltest/cli.py b/fltest/cli.py index 2ec21ce..956b13f 100644 --- a/fltest/cli.py +++ b/fltest/cli.py @@ -153,13 +153,27 @@ def metamorphic(config_path: str, output: str, verbose: bool) -> None: @cli.command() @click.argument("config_path", type=click.Path(exists=True)) -def pitfalls(config_path: str) -> None: +@click.option("--report", "report_path", type=click.Path(exists=True, dir_okay=False), + help="Also check observed learning gaps in a saved run report.") +def pitfalls(config_path: str, report_path: str | None = None) -> None: """Run the pitfall checker and print counter-experiment recommendations.""" from fltest.core.config import load_config - from fltest.pitfalls import check_config, recommend + from fltest.pitfalls import check_config, check_learning_gap, recommend config = load_config(config_path) findings = check_config(config) + if report_path: + import json + + try: + document = json.loads(Path(report_path).read_text()) + except (OSError, ValueError) as exc: + raise click.ClickException(f"Unable to read run report: {exc}") from exc + if (not isinstance(document, dict) or not isinstance(document.get("runs"), list) + or any(not isinstance(run, dict) for run in document["runs"])): + raise click.ClickException("Run report must contain a runs list of run objects") + for result in document["runs"]: + findings.extend(check_learning_gap(result)) click.echo("\n" + "=" * 70 + f"\nPITFALL CHECK: {config.name}\n" + "=" * 70) if not findings: diff --git a/fltest/core/config.py b/fltest/core/config.py index bfd017e..8e9572e 100644 --- a/fltest/core/config.py +++ b/fltest/core/config.py @@ -17,6 +17,7 @@ from __future__ import annotations from pathlib import Path +import math from typing import Any, Dict, List, Literal, Optional, Union import yaml @@ -50,6 +51,27 @@ class MedicalConfig(BaseModel): model_config = {"extra": "forbid"} +class CosineRoundSchedule(BaseModel): + name: Literal["cosine_over_rounds"] = "cosine_over_rounds" + min_lr: float = Field(default=1e-6, ge=0, allow_inf_nan=False) + + model_config = {"extra": "forbid"} + + +class LearningGapConfig(BaseModel): + enabled: bool = True + metric: Literal["accuracy", "loss"] = "accuracy" + min_improvement: float = Field(default=0.02, ge=0, allow_inf_nan=False) + + model_config = {"extra": "forbid"} + + @model_validator(mode="after") + def validate_threshold(self): + if self.metric == "accuracy" and self.min_improvement > 1: + raise ValueError("Accuracy min_improvement must be a fraction in [0, 1]") + return self + + class CausalLMConfig(BaseModel): """Pretrained LM training and task-specific data settings.""" @@ -72,6 +94,8 @@ class CausalLMConfig(BaseModel): micro_batch_size: Optional[int] = Field(default=None, gt=0) grad_accum_steps: int = Field(default=1, gt=0) attn_implementation: Literal["eager", "sdpa"] = "eager" + lr_schedule: Optional[CosineRoundSchedule] = None + learning_gap: LearningGapConfig = Field(default_factory=LearningGapConfig) model_config = {"extra": "forbid"} @@ -90,6 +114,10 @@ def run_settings(self): values.pop("grad_accum_steps") if self.attn_implementation == "eager": values.pop("attn_implementation") + if self.lr_schedule is None: + values.pop("lr_schedule") + if self.learning_gap == LearningGapConfig(): + values.pop("learning_gap") return values @@ -268,8 +296,11 @@ def validate_task(self): raise ValueError("grad_accum_steps requires micro_batch_size") elif self.lm.micro_batch_size * self.lm.grad_accum_steps != self.client_batch_size: raise ValueError("micro_batch_size * grad_accum_steps must equal client_batch_size") - if self.max_test_data_size < 1 or self.server_batch_size < 1 or self.client_lr <= 0: + if (self.max_test_data_size < 1 or self.server_batch_size < 1 + or not math.isfinite(self.client_lr) or self.client_lr <= 0): raise ValueError("causal_lm requires positive evaluation sizes and learning rate") + if self.lm.lr_schedule is not None and self.lm.lr_schedule.min_lr > self.client_lr: + raise ValueError("lr_schedule.min_lr must not exceed client_lr (the maximum learning rate)") if self.optimizer not in ("Adam", "AdamW", "SGD"): raise ValueError("causal_lm supports Adam, AdamW, or SGD") if self.loss_fn != "CrossEntropyLoss": diff --git a/fltest/core/lm_protocol.py b/fltest/core/lm_protocol.py new file mode 100644 index 0000000..4243038 --- /dev/null +++ b/fltest/core/lm_protocol.py @@ -0,0 +1,24 @@ +"""Round-level causal-LM training settings shared by server and clients.""" + +import math + + +def learning_rate_for_round(spec, server_round): + schedule = spec.lm.lr_schedule + if schedule is None: + return spec.client_lr + if type(server_round) is not int or not 1 <= server_round <= spec.num_rounds: + raise ValueError("Scheduled learning rates require an integer training round in [1, num_rounds]") + if server_round == 1: + return spec.client_lr + if server_round == spec.num_rounds: + return schedule.min_lr + progress = (server_round - 1) / (spec.num_rounds - 1) + return schedule.min_lr + (spec.client_lr - schedule.min_lr) * (1 + math.cos(math.pi * progress)) / 2 + + +def validate_round_learning_rate(spec, server_round, value): + expected = learning_rate_for_round(spec, server_round) + if (isinstance(value, bool) or not isinstance(value, (float, int)) + or not math.isfinite(value) or not math.isclose(value, expected, rel_tol=1e-12, abs_tol=0)): + raise ValueError(f"Scheduled learning rate differs in round {server_round}: expected {expected}") diff --git a/fltest/core/orchestrator.py b/fltest/core/orchestrator.py index 60e2538..0ccff92 100644 --- a/fltest/core/orchestrator.py +++ b/fltest/core/orchestrator.py @@ -15,7 +15,7 @@ import json import time import traceback -from dataclasses import dataclass, field +from dataclasses import asdict, dataclass, field from typing import Any, Dict, List from fltest.core.config import ( @@ -157,6 +157,12 @@ def run_spec(self, spec: RunSpec) -> RunResult: ) result.duration_seconds = time.time() - start result.params = spec.summary() # annotate the result with its resolved parameters + if spec.task == "causal_lm": + from fltest.pitfalls import check_learning_gap + + findings = check_learning_gap(result.to_dict()) + if findings: + result.extras.setdefault("pitfalls", []).extend(asdict(finding) for finding in findings) return result @staticmethod diff --git a/fltest/data/causal_lm.py b/fltest/data/causal_lm.py index 62499f6..3287b5a 100644 --- a/fltest/data/causal_lm.py +++ b/fltest/data/causal_lm.py @@ -322,10 +322,12 @@ def _autocast(spec): def train_causal_model(model, loader, spec, server_round, cid, details=None): + from fltest.core.lm_protocol import learning_rate_for_round + 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) + optimizer = optimizer_cls(trainable, lr=learning_rate_for_round(spec, server_round)) scaler = torch.amp.GradScaler("cuda", enabled=spec.lm.precision == "fp16") model.train() total_loss, total_tokens = 0.0, 0 diff --git a/fltest/frameworks/flower/client.py b/fltest/frameworks/flower/client.py index b918599..b99b42a 100644 --- a/fltest/frameworks/flower/client.py +++ b/fltest/frameworks/flower/client.py @@ -83,6 +83,10 @@ def fit_causal_lm(self, parameters, config): spec = self.spec rnd = int(config["server_round"]) selected = tuple(json.loads(config["selected_clients"])) + if spec.lm.lr_schedule is not None: + from fltest.core.lm_protocol import validate_round_learning_rate + + validate_round_learning_rate(spec, rnd, config.get("learning_rate")) self.net = get_causal_model(spec) ctx = after = None try: @@ -120,6 +124,10 @@ def fit_causal_lm(self, parameters, config): } metrics.update(numeric_metrics(ctx.metrics)) metrics.update(numeric_metrics(after.metrics)) + if spec.lm.lr_schedule is not None: + from fltest.core.lm_protocol import learning_rate_for_round + + metrics["learning_rate"] = learning_rate_for_round(spec, rnd) if spec.lm.micro_batch_size is not None: metrics.update(micro_batch_size=spec.lm.micro_batch_size, grad_accum_steps=spec.lm.grad_accum_steps, diff --git a/fltest/frameworks/flower/server.py b/fltest/frameworks/flower/server.py index 1cd5e14..19a160e 100644 --- a/fltest/frameworks/flower/server.py +++ b/fltest/frameworks/flower/server.py @@ -69,6 +69,10 @@ def configure_fit(self, server_round, parameters, client_manager): if self._spec.task == "causal_lm": for _, instruction in configured: instruction.config["selected_clients"] = json.dumps(selected) + if self._spec.lm.lr_schedule is not None: + from fltest.core.lm_protocol import learning_rate_for_round + + instruction.config["learning_rate"] = learning_rate_for_round(self._spec, server_round) if selected == tuple(range(self._spec.num_clients)) or not configured: return configured @@ -117,6 +121,10 @@ def aggregate_fit(self, server_round, results, 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 self._spec.lm.lr_schedule is not None: + from fltest.core.lm_protocol import validate_round_learning_rate + + validate_round_learning_rate(self._spec, server_round, response.metrics.get("learning_rate")) if response.num_examples <= 0: raise ValueError("Causal-LM client trained on no examples") key = manifest_field(self._spec) diff --git a/fltest/pitfalls/__init__.py b/fltest/pitfalls/__init__.py index 00e4d87..81caf2c 100644 --- a/fltest/pitfalls/__init__.py +++ b/fltest/pitfalls/__init__.py @@ -1,6 +1,6 @@ """Pitfall checker and counter-experiment recommender.""" -from fltest.pitfalls.checker import Finding, check_config +from fltest.pitfalls.checker import Finding, check_config, check_learning_gap from fltest.pitfalls.recommender import recommend -__all__ = ["Finding", "check_config", "recommend"] +__all__ = ["Finding", "check_config", "check_learning_gap", "recommend"] diff --git a/fltest/pitfalls/checker.py b/fltest/pitfalls/checker.py index 978ea74..c64c0cc 100644 --- a/fltest/pitfalls/checker.py +++ b/fltest/pitfalls/checker.py @@ -9,9 +9,11 @@ from __future__ import annotations from dataclasses import dataclass, field +import math +from numbers import Real from typing import Any, Dict, List -from fltest.core.config import ROBUST_AGGREGATORS, TestConfig +from fltest.core.config import LearningGapConfig, ROBUST_AGGREGATORS, TestConfig # Attacks the proposal flags as "naive" (Pitfall-1): over-used, weak under strong settings. NAIVE_ATTACKS = {"gaussian", "label_flip", "sign_flip"} @@ -32,6 +34,41 @@ class Finding: evidence: Dict[str, Any] = field(default_factory=dict) +def check_learning_gap(result: Dict[str, Any]) -> List[Finding]: + """Compare a successful clean LM run to its own round-0 baseline. + + Perturbed runs cannot establish the clean training signal. Missing/nonfinite + evidence is not treated as evidence of a small gap. + """ + params = result.get("params", {}) + if (params.get("task") != "causal_lm" or result.get("status") != "success" + or params.get("attacks") or params.get("defenses")): + return [] + settings = LearningGapConfig(**params.get("lm", {}).get("learning_gap", {})) + if not settings.enabled: + return [] + history = result.get("history", {}) + baseline = history.get("0", history.get(0, {})).get(settings.metric) + final = result.get("final", {}).get(settings.metric) + if any(isinstance(v, bool) or not isinstance(v, Real) or not math.isfinite(v) for v in (baseline, final)): + return [] + improvement = final - baseline if settings.metric == "accuracy" else baseline - final + if improvement >= settings.min_improvement: + return [] + name = result.get("run_name", result.get("run_id", "run")) + return [Finding( + "P3_lm_learning_gap", "Small causal-LM learning signal", "medium", + f"{name}: {settings.metric} improvement over round 0 is {improvement:.6g}, " + f"below the configured minimum {settings.min_improvement:.6g} " + f"(baseline={baseline:.6g}, final={final:.6g}).", + "Establish a longer clean baseline or increase lm.local_steps, and review evaluation " + "size and optimizer settings before interpreting attack damage or defense costs.", + {"run_id": result.get("run_id"), "run_name": name, "metric": settings.metric, + "baseline": baseline, "final": final, "improvement": improvement, + "min_improvement": settings.min_improvement}, + )] + + def _as_list(v): return v if isinstance(v, list) else [v] diff --git a/fltest/pitfalls/recommender.py b/fltest/pitfalls/recommender.py index 5d72392..dbcd705 100644 --- a/fltest/pitfalls/recommender.py +++ b/fltest/pitfalls/recommender.py @@ -12,6 +12,12 @@ # Counter-experiment snippets keyed by pitfall id (YAML fragments the user can merge). _COUNTER_EXPERIMENTS: Dict[str, str] = { + "P3_lm_learning_gap": ( + "# run a longer clean baseline before interpreting attack or defense utility\n" + "num_rounds: 15\n" + "lm:\n local_steps: 10\n" + "# merge into the existing lm block; retain its dataset/model settings" + ), "P1_threat_models": ( "attacks:\n" " - {name: backdoor, params: {target_label: 0, infection_rate: 0.3}}\n" diff --git a/fltest/testing/report.py b/fltest/testing/report.py index 7b94415..ca7a078 100644 --- a/fltest/testing/report.py +++ b/fltest/testing/report.py @@ -111,6 +111,7 @@ def print_outcomes(title: str, outcomes: List[TestOutcome]) -> bool: "next_token_accuracy": "tok-acc", "perplexity": "ppl", "pubmedqa_accuracy": "pmqa-acc", + "learning_rate": "lr", "attack_success_rate": "asr", "model_replacement_scale": "mr-scale", "per_client_acc_mean": "pc-mean", @@ -144,6 +145,7 @@ def print_outcomes(title: str, outcomes: List[TestOutcome]) -> bool: "next_token_accuracy": "correct next-token predictions over supervised held-out tokens, including EOS and excluding padding", "perplexity": "exponential of token-weighted held-out next-token cross-entropy", "pubmedqa_accuracy": "generated yes/no/maybe accuracy on the pinned PubMedQA test subset; Medical loss uses separate held-out flashcards", + "learning_rate": "client optimizer learning rate for this training round", "accuracy": "top-1 accuracy of the global model on the held-out test set", "loss": "mean cross-entropy on the same test set", "attack_success_rate": "attack success rate, the share of triggered inputs predicted as the attacker's target label", @@ -218,6 +220,7 @@ def _fmt_param(key: str, value) -> str: #: MPC error of 8.7e-09 and one of 1.9e-05 identically as 0.0000, hiding the 2200x gap that #: is the whole signal, so these switch to scientific notation outside the readable band. _WIDE_RANGE_METRICS = { + "learning_rate", "mpc_agg_max_abs_error", "mpc_agg_rel_error", "secagg_mask_residual", @@ -354,6 +357,9 @@ def _line(cells): if total_duration: summary += f", {total_duration:.1f}s total" print(summary) + for result in results: + for finding in (getattr(result, "extras", {}) or {}).get("pitfalls", []): + print(f" [{finding['severity'].upper()}] {finding['pitfall']}: {finding['message']}") for r in failed: # Some libraries raise a message that opens with a blank line, which leaves the # first line holding only the exception name. Carry the next line with content up diff --git a/tests/test_lm_protocol.py b/tests/test_lm_protocol.py new file mode 100644 index 0000000..632997c --- /dev/null +++ b/tests/test_lm_protocol.py @@ -0,0 +1,237 @@ +"""Scheduled optimizer updates and observed clean-baseline learning warnings.""" + +import json +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import pytest +import torch +from torch.utils.data import DataLoader + +from fltest.core import HookRunner +from fltest.core.config import TestConfig, load_config +from fltest.core.lm_protocol import learning_rate_for_round, validate_round_learning_rate +from fltest.core.orchestrator import Orchestrator, expand_run_specs +from fltest.data.causal_lm import LMCollator, train_causal_model +from fltest.frameworks.base import RunResult +from fltest.pitfalls import check_learning_gap + + +def protocol_spec(*, schedule=True, gap=None, **overrides): + opts = dict(precision="fp32", quantization=None, seq_len=16, local_steps=1, + gradient_checkpointing=False) + if schedule: + opts['lr_schedule'] = {'min_lr': .01} + if gap is not None: + opts['learning_gap'] = gap + 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=3, client_batch_size=2, client_lr=.1, optimizer='SGD', lm=opts, + client_resources={'num_cpus': 1, 'num_gpus': 0}, runs=[{'framework': 'flwr'}]) + config.update(overrides) + return expand_run_specs(TestConfig(**config))[0] + + +def test_cosine_schedule_endpoints_monotonicity_and_single_round(): + spec = protocol_spec(num_rounds=15) + rates = [learning_rate_for_round(spec, rnd) for rnd in range(1, 16)] + assert rates[0] == .1 and rates[-1] == .01 + assert rates[7] == pytest.approx(.055) + assert all(a > b for a, b in zip(rates, rates[1:])) + assert learning_rate_for_round(protocol_spec(num_rounds=1), 1) == .1 + assert learning_rate_for_round(protocol_spec(schedule=False), 2) == .1 + + +@pytest.mark.parametrize('rnd', [0, -1, 4, True, 1.5]) +def test_schedule_rejects_nontraining_rounds(rnd): + with pytest.raises(ValueError, match='integer training round'): + learning_rate_for_round(protocol_spec(), rnd) + + +@pytest.mark.parametrize('value', [None, True, '0.1', .2, float('nan'), float('inf')]) +def test_schedule_rejects_inconsistent_wire_rates(value): + with pytest.raises(ValueError, match='Scheduled learning rate differs'): + validate_round_learning_rate(protocol_spec(), 1, value) + + +@pytest.mark.parametrize('field,value,message', [ + ('lr_schedule', {'min_lr': .2}, 'must not exceed'), + ('lr_schedule', {'min_lr': -1}, 'greater than or equal'), + ('lr_schedule', {'min_lr': float('nan')}, 'finite'), + ('lr_schedule', {'name': 'linear'}, 'cosine_over_rounds'), + ('learning_gap', {'min_improvement': float('inf')}, 'finite'), + ('learning_gap', {'min_improvement': 2}, 'fraction'), + ('learning_gap', {'metric': 'made_up'}, 'accuracy'), +]) +def test_training_protocol_config_guards(field, value, message): + opts = protocol_spec().lm.model_dump() + opts[field] = value + with pytest.raises(ValueError, match=message): + protocol_spec(lm=opts) + + +def test_protocol_options_affect_identity_but_legacy_defaults_do_not(): + root = Path(__file__).resolve().parents[1] + for file, expected in [('finance_learning_check.yaml', '48abed612c'), + ('medical_smoke.yaml', 'dd6623f137')]: + spec = expand_run_specs(load_config(root / 'examples/configs' / file))[0] + assert spec.run_id == expected + assert 'lr_schedule' not in spec.lm.run_settings() + assert 'learning_gap' not in spec.lm.run_settings() + assert protocol_spec().run_id != protocol_spec(schedule=False).run_id + assert protocol_spec(gap={'enabled': False}).run_id != protocol_spec().run_id + + +class QuadraticModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.weight = torch.nn.Parameter(torch.tensor([0.0])) + + def forward(self, **kwargs): + return SimpleNamespace(loss=(self.weight - .25).square().mean()) + + +def toy_loader(cid=0): + return DataLoader([ + {'input_ids': [3, 4, 2], 'labels': [-100, 4, 2], 'sample_id': cid * 2 + i} + for i in range(2) + ], batch_size=2, collate_fn=LMCollator(2)) + + +def test_actual_optimizer_uses_the_scheduled_rate_without_mutating_the_spec(): + spec, model = protocol_spec(), QuadraticModel() + expected = 0.0 + for rnd, rate in enumerate((.1, .055, .01), 1): + details = {} + loss, count = train_causal_model(model, toy_loader(), spec, rnd, 0, details) + expected -= rate * 2 * (expected - .25) + assert model.weight.item() == pytest.approx(expected, abs=1e-7) + assert count == 2 and np.isfinite(loss) + assert details['trained_sample_ids'] == [0, 1] + assert spec.client_lr == .1 + + +def test_schedule_crosses_the_flower_server_client_and_aggregation_contract(monkeypatch): + from flwr.common import ndarrays_to_parameters, parameters_to_ndarrays + from fltest.frameworks.flower.client import FlowerClient + from fltest.frameworks.flower.server import HookedFedAvg + + monkeypatch.setattr('fltest.data.causal_lm.get_causal_model', lambda spec: QuadraticModel()) + monkeypatch.setattr('fltest.data.causal_lm.causal_manifest', lambda model, spec: 'toy') + monkeypatch.setattr('fltest.data.causal_lm.causal_parameters', + lambda model, spec: [model.weight.detach().numpy().copy()]) + def restore(model, parameters, spec): + with torch.no_grad(): + model.weight.copy_(torch.from_numpy(parameters[0])) + monkeypatch.setattr('fltest.data.causal_lm.set_causal_parameters', restore) + spec = protocol_spec() + clients = [FlowerClient(toy_loader(cid), spec, cid, HookRunner()).to_client() for cid in range(2)] + proxies = [SimpleNamespace(cid=str(cid)) for cid in range(2)] + class Manager: + def num_available(self): + return 2 + def sample(self, num_clients, min_num_clients): + return proxies + parameters = ndarrays_to_parameters([np.array([0.0], dtype=np.float32)]) + history = {} + strategy = HookedFedAvg(HookRunner(), spec, history, initial_parameters=parameters, + min_fit_clients=2, min_available_clients=2, + on_fit_config_fn=lambda rnd: {'server_round': rnd, 'adapter_manifest': 'toy'}) + strategy._adapter_manifest = 'toy' + expected = 0.0 + for rnd, rate in enumerate((.1, .055, .01), 1): + instructions = strategy.configure_fit(rnd, parameters, Manager()) + responses = [(proxy, clients[int(proxy.cid)].fit(ins)) for proxy, ins in instructions] + assert all(ins.config['learning_rate'] == pytest.approx(rate) for _, ins in instructions) + if rnd == 2: + actual = responses[0][1].metrics['learning_rate'] + responses[0][1].metrics['learning_rate'] = .1 + with pytest.raises(ValueError, match='Scheduled learning rate differs'): + strategy.aggregate_fit(rnd, responses, []) + responses[0][1].metrics['learning_rate'] = actual + parameters, metrics = strategy.aggregate_fit(rnd, responses, []) + expected -= rate * 2 * (expected - .25) + np.testing.assert_allclose(parameters_to_ndarrays(parameters)[0], [expected], atol=1e-7) + assert metrics['learning_rate'] == pytest.approx(rate) + assert all(c['learning_rate'] == pytest.approx(rate) for c in history[rnd]['clients']) + + +def result_dict(*, spec=None, baseline=.4, final=.41, metric='accuracy'): + spec = spec or protocol_spec() + return RunResult(run_id=spec.run_id, run_name='clean', framework='flwr', params=spec.summary(), + history={0: {metric: baseline}}, final={metric: final}).to_dict() + + +@pytest.mark.parametrize('metric,baseline,final,warns', [ + ('accuracy', .4, .4, True), ('accuracy', .4, .3, True), + ('accuracy', .4, .41, True), ('accuracy', .4, .5, False), + ('loss', 2., 1.99, True), ('loss', 2., 1.9, False), ('loss', 2., 2.1, True), +]) +def test_learning_gap_direction_and_findings(metric, baseline, final, warns): + spec = protocol_spec(gap={'metric': metric}) + findings = check_learning_gap(result_dict(spec=spec, metric=metric, baseline=baseline, final=final)) + assert bool(findings) == warns + if warns: + assert findings[0].pitfall == 'P3_lm_learning_gap' + expected = final - baseline if metric == 'accuracy' else baseline - final + assert findings[0].evidence['improvement'] == pytest.approx(expected) + + +def test_learning_gap_applies_only_to_successful_clean_lm_runs_with_evidence(): + for overrides in ({'status': 'failed'}, {'history': {}}, {'final': {'accuracy': float('nan')}}): + result = result_dict() + result.update(overrides) + assert not check_learning_gap(result) + for field, value in [('task', 'classification'), ('attacks', [{'name': 'sign_flip'}]), + ('defenses', [{'name': 'norm_clip'}])]: + result = result_dict() + result['params'][field] = value + assert not check_learning_gap(result) + assert not check_learning_gap(result_dict(spec=protocol_spec(gap={'enabled': False}))) + boundary = protocol_spec(gap={'min_improvement': .125}) + assert not check_learning_gap(result_dict(spec=boundary, baseline=.25, final=.375)) + + +def test_orchestrator_persists_warnings_and_the_cli_prints_them(monkeypatch, capsys): + from fltest.testing.report import print_run_matrix + + spec = protocol_spec() + run = RunResult(run_id=spec.run_id, run_name='clean', framework='flwr', + history={0: {'accuracy': .4}}, final={'accuracy': .41}) + monkeypatch.setattr('fltest.core.orchestrator.prepare_data', lambda spec: {}) + monkeypatch.setattr('fltest.core.orchestrator.get_adapter', lambda framework: SimpleNamespace( + run_simulation=lambda *args: run)) + observed = Orchestrator(verbose=False).run_spec(spec) + assert observed.status == 'success' + assert observed.extras['pitfalls'][0]['evidence']['baseline'] == .4 + print_run_matrix('observed', [observed]) + assert '[MEDIUM] P3_lm_learning_gap' in capsys.readouterr().out + + +def test_pitfalls_command_rechecks_saved_reports(tmp_path): + from click.testing import CliRunner + from fltest.cli import cli + + root = Path(__file__).resolve().parents[1] + report = tmp_path / 'run.json' + report.write_text(json.dumps({'runs': [result_dict()]})) + result = CliRunner().invoke(cli, ['pitfalls', str(root / 'examples/configs/finance_smoke.yaml'), + '--report', str(report)]) + assert result.exit_code == 0, result.output + assert 'P3_lm_learning_gap' in result.output and 'baseline=0.4' in result.output + report.write_text('{"runs": "bad"}') + result = CliRunner().invoke(cli, ['pitfalls', str(root / 'examples/configs/finance_smoke.yaml'), + '--report', str(report)]) + assert result.exit_code != 0 and 'runs list' in result.output + + +def test_report_does_not_round_small_scheduled_rates_to_zero(capsys): + from fltest.testing.report import print_run_matrix + + spec = protocol_spec() + run = RunResult(run_id=spec.run_id, run_name='clean', framework='flwr', + params=spec.summary(), final={'accuracy': .4, 'learning_rate': 1e-6}) + print_run_matrix('scheduled', [run]) + output = capsys.readouterr().out + assert '1.00e-06' in output