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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
33 changes: 33 additions & 0 deletions docs/causal-lm.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions docs/pitfalls.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ fltest pitfalls <config.yaml>
| `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 |
Expand All @@ -25,6 +26,26 @@ fltest pitfalls <config.yaml>

## 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:

Expand Down
47 changes: 47 additions & 0 deletions examples/configs/finance_schedule_smoke.yaml
Original file line number Diff line number Diff line change
@@ -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
18 changes: 16 additions & 2 deletions fltest/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
33 changes: 32 additions & 1 deletion fltest/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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."""

Expand All @@ -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"}

Expand All @@ -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


Expand Down Expand Up @@ -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":
Expand Down
24 changes: 24 additions & 0 deletions fltest/core/lm_protocol.py
Original file line number Diff line number Diff line change
@@ -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}")
8 changes: 7 additions & 1 deletion fltest/core/orchestrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion fltest/data/causal_lm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions fltest/frameworks/flower/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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,
Expand Down
8 changes: 8 additions & 0 deletions fltest/frameworks/flower/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions fltest/pitfalls/__init__.py
Original file line number Diff line number Diff line change
@@ -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"]
39 changes: 38 additions & 1 deletion fltest/pitfalls/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
Expand All @@ -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]

Expand Down
Loading
Loading