diff --git a/docs/causal-lm.md b/docs/causal-lm.md index f2c5b61..28123c6 100644 --- a/docs/causal-lm.md +++ b/docs/causal-lm.md @@ -191,3 +191,13 @@ full-model training, and next-token evaluation. The [Medical application](medica adds micro-batched flashcard training and PubMedQA subset evaluation. Optional DoRA remains follow-up work. The [reference backend](reference-causal-lm.md) supports sequential LM execution and comparisons against Flower. + +The [repeatability checks](differential-testing.md#mode-2-determinism) compare two +attempts per backend, including per-round evidence and checkpoint tensors. +`examples/configs/finance_long_learning_check.yaml` provides a 15-round SmolLM2 +learning check with four IID clients, two selected per round, effective batch 8, +ten local steps and a cosine learning-rate schedule. It uses 256 training rows +per client and a fixed 64-record holdout. The configured warning threshold is a +two-percentage-point accuracy gain from round zero; a loss reduction alone does +not satisfy that threshold. This is a scaled learning check, separate from the +full 50-client Mistral benchmark configuration. diff --git a/docs/differential-testing.md b/docs/differential-testing.md index 2d035fd..5cbad8e 100644 --- a/docs/differential-testing.md +++ b/docs/differential-testing.md @@ -55,6 +55,29 @@ nondeterminism / state leakage. **Rule:** `|metric(run1) − metric(run2)| ≤ tolerance` (use a tiny `tolerance`, e.g. `1e-4`), on `device: cpu`. +For causal LMs, this mode also requires matching data provenance, initialization, +selected clients and successful training-record IDs. The selected metric must +agree at round zero, every trained round and in the final summary. Generated +predictions and application-specific held-out details must match exactly. Saved +checkpoint tensor names, shapes and dtypes must match, all tensors must be finite, +and their largest absolute element difference must be within tolerance. Each +attempt must retain its own checkpoint directory. Missing evidence fails the check. + +The GPU examples `finance_repeatability.yaml`, `stackoverflow_repeatability.yaml` +and `medical_repeatability.yaml` each run both reference and Flower twice with +zero tolerance. Start the two-node Ray cluster as described in +[multi-node execution](multi-node.md), then use, for example: + +```bash +fltest diff examples/configs/finance_repeatability.yaml +``` + +These configurations test empirical repeatability on the same hardware and pinned +software. `deterministic: true` seeds FLTest's RNGs; it does not enable PyTorch's +strict deterministic-algorithm mode or guarantee bit identity on other GPUs, +software versions, model sizes or attention implementations. Timing, hostname +placement and allocator memory measurements are excluded from numerical parity. + ```yaml testing: differential: {mode: determinism, metric: accuracy, tolerance: 0.0001} diff --git a/examples/configs/finance_long_learning_check.yaml b/examples/configs/finance_long_learning_check.yaml new file mode 100644 index 0000000..213ac29 --- /dev/null +++ b/examples/configs/finance_long_learning_check.yaml @@ -0,0 +1,47 @@ +# Scaled SmolLM2 learning check; not the full 50-client Mistral benchmark experiment. +name: finance_long_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: 4 +dataset_partitions: 4 +clients_per_round: 2 +num_rounds: 15 +client_batch_size: 8 +client_lr: 5.0e-05 +optimizer: AdamW +server_batch_size: 4 +max_test_data_size: 64 +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: 256 + 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/examples/configs/finance_repeatability.yaml b/examples/configs/finance_repeatability.yaml new file mode 100644 index 0000000..14e8d07 --- /dev/null +++ b/examples/configs/finance_repeatability.yaml @@ -0,0 +1,62 @@ +# Two attempts per backend; empirical repeatability on the same hardware/software. +name: finance_repeatability +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: 2 +client_batch_size: 2 +client_lr: 5.0e-05 +optimizer: AdamW +server_batch_size: 4 +max_test_data_size: 4 +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: finance_benchmark_accuracy + min_improvement: 0.02 + finance_benchmarks: + max_samples_per_benchmark: 4 + max_new_tokens: 16 +metrics: +- accuracy +- loss +- fpb_accuracy +- fiqa_accuracy +- tfns_accuracy +- finance_benchmark_accuracy +runs: +- framework: reference + name: reference +- framework: flwr + name: flower +testing: + differential: + enabled: true + mode: determinism + metric: loss + tolerance: 0.0 diff --git a/examples/configs/medical_repeatability.yaml b/examples/configs/medical_repeatability.yaml new file mode 100644 index 0000000..c47b1bd --- /dev/null +++ b/examples/configs/medical_repeatability.yaml @@ -0,0 +1,56 @@ +# Two attempts per backend; empirical repeatability on the same hardware/software. +name: medical_repeatability +task: causal_lm +dataset: hf:flwrlabs/medical-meadow-medical-flashcards +model_name: hf:HuggingFaceTB/SmolLM2-135M-Instruct +seed: 786 +device: cuda +total_cpus: 8 +total_gpus: 2 +num_clients: 2 +dataset_partitions: 2 +clients_per_round: 2 +num_rounds: 2 +client_batch_size: 4 +client_lr: 5.0e-05 +optimizer: AdamW +server_batch_size: 2 +max_test_data_size: 8 +client_resources: + num_cpus: 2 + num_gpus: 1 +lm: + model_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac + tokenizer_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac + dataset_revision: bc33733afea65239aed2149aa79ea77742d28cc2 + precision: fp16 + quantization: 4bit + lora_r: 32 + lora_alpha: 64 + seq_len: 256 + local_steps: 2 + gradient_checkpointing: true + holdout_fraction: 0.1 + max_train_samples_per_client: 32 + checkpoint_dir: reports/adapters + micro_batch_size: 1 + grad_accum_steps: 4 + medical: + pubmedqa_revision: 13a7d15476092370cbabb6475390e7e69b74d2f2 + pubmedqa_max_samples: 8 + pubmedqa_max_prompt_tokens: 1024 + max_new_tokens: 32 +metrics: +- pubmedqa_accuracy +- loss +runs: +- framework: reference + name: reference +- framework: flwr + name: flower +testing: + differential: + enabled: true + mode: determinism + metric: loss + tolerance: 0.0 diff --git a/examples/configs/stackoverflow_repeatability.yaml b/examples/configs/stackoverflow_repeatability.yaml new file mode 100644 index 0000000..4b4be42 --- /dev/null +++ b/examples/configs/stackoverflow_repeatability.yaml @@ -0,0 +1,52 @@ +# Two attempts per backend; empirical repeatability on the same hardware/software. +name: stackoverflow_repeatability +task: causal_lm +dataset: stackoverflow +data_distribution: by_user +model_name: hf:HuggingFaceTB/SmolLM2-135M-Instruct +device: cuda +total_cpus: 8 +total_gpus: 2 +num_clients: 4 +dataset_partitions: 4 +clients_per_round: 2 +num_rounds: 2 +client_batch_size: 2 +client_lr: 0.001 +optimizer: SGD +server_batch_size: 2 +max_test_data_size: 16 +client_resources: + num_cpus: 2 + num_gpus: 1 +lm: + model_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac + tokenizer_revision: 12fd25f77366fa6b3b4b768ec3050bf629380bac + method: full + precision: fp16 + quantization: null + seq_len: 128 + local_steps: 2 + gradient_checkpointing: true + max_train_samples_per_client: 32 + checkpoint_dir: reports/models + stackoverflow: + train_path: data/stackoverflow/so_1k/train.parquet + heldout_path: data/stackoverflow/so_1k/heldout.parquet + partition_by: user_id + max_heldout_users: 4 +metrics: +- next_token_accuracy +- perplexity +- loss +runs: +- framework: reference + name: reference +- framework: flwr + name: flower +testing: + differential: + enabled: true + mode: determinism + metric: loss + tolerance: 0.0 diff --git a/fltest/testing/differential.py b/fltest/testing/differential.py index d4af458..1b895c9 100644 --- a/fltest/testing/differential.py +++ b/fltest/testing/differential.py @@ -14,6 +14,7 @@ import json import math from numbers import Real +from pathlib import Path from dataclasses import dataclass, field from typing import Any, Dict, List, Optional @@ -97,6 +98,95 @@ def _lm_evidence_error(members): return None +def _lm_round_metrics(members, metric, tolerance): + histories = [{int(key): value for key, value in result.history.items()} for _, result in members] + evidence = {} + for rnd in range(members[0][0].num_rounds + 1): + values = [history[rnd].get(metric) for history in histories] + if any(isinstance(v, bool) or not isinstance(v, Real) or not math.isfinite(v) for v in values): + return False, f'missing, nonfinite or invalid {metric} in round {rnd}', evidence + evidence[str(rnd)] = values + ok, detail = parity(values, tolerance) + if not ok: + return False, f'round {rnd}: {detail}', evidence + return True, 'all rounds agree', evidence + + +def _lm_checkpoint_evidence(spec, first, second, tolerance): + """Compare saved tensors, bounding temporary comparison arrays for full models.""" + import numpy as np + from safetensors import safe_open + + paths = [Path(result.extras['checkpoint']).resolve() for result in (first, second)] + if paths[0] == paths[1]: + raise ValueError('repeat runs must retain distinct checkpoint directories') + filename = 'model.safetensors' if spec.lm.method == 'full' else 'adapter_model.safetensors' + maximum, count = 0., 0 + with safe_open(str(paths[0] / filename), framework='numpy') as a, \ + safe_open(str(paths[1] / filename), framework='numpy') as b: + if not list(a.keys()) or set(a.keys()) != set(b.keys()): + raise ValueError('checkpoint tensor names differ or are empty') + for key in a.keys(): + x, y = a.get_tensor(key), b.get_tensor(key) + if x.shape != y.shape or x.dtype != y.dtype: + raise ValueError(f'checkpoint shape or dtype differs: {key}') + x, y = x.reshape(-1), y.reshape(-1) + for start in range(0, len(x), 65536): + left, right = x[start:start + 65536], y[start:start + 65536] + if not np.isfinite(left).all() or not np.isfinite(right).all(): + raise ValueError(f'nonfinite checkpoint tensor: {key}') + if len(left): + maximum = max(maximum, float(np.max(np.abs(left.astype('float64') - right)))) + count += 1 + return maximum <= tolerance, {'tensor_count': count, 'max_abs_delta': maximum} + + +def compare_lm_repeats(spec, first, second, metric='accuracy', eps=1e-4): + """Audit two completed attempts without running training again.""" + if not math.isfinite(eps) or eps < 0: + raise ValueError('repeatability tolerance must be finite and nonnegative') + label = f'{spec.run_name} [{spec.framework}] {spec.dataset} c{spec.num_clients} r{spec.num_rounds}' + def outcome(status, detail, evidence=None): + return TestOutcome('differential', label, status, detail, evidence or {}) + if first.status != 'success' or second.status != 'success': + return outcome('FAIL', 'a repeat run errored') + members = [(spec, first), (spec, second)] + error = _lm_evidence_error(members) + if error: + return outcome('FAIL', error) + values = [result.final.get(metric) for _, result in members] + if any(isinstance(v, bool) or not isinstance(v, Real) or not math.isfinite(v) for v in values): + return outcome('FAIL', f'missing, nonfinite or invalid final {metric}') + ok, detail = parity(values, eps) + if not ok: + return outcome('FAIL', f'final {metric}: {detail}') + ok, detail, rounds = _lm_round_metrics(members, metric, eps) + evidence = {'final': values, 'rounds': rounds, 'tolerance': eps} + if not ok: + return outcome('FAIL', detail, evidence) + keys = ['predictions'] + if spec.dataset == 'stackoverflow': + keys.append('heldout_user_metrics') + if spec.lm.finance_benchmarks is not None: + keys.append('finance_benchmark_predictions') + histories = [{int(k): v for k, v in result.history.items()} for _, result in members] + for rnd in range(spec.num_rounds + 1): + for key in keys: + if any(key not in history[rnd] for history in histories): + return outcome('FAIL', f'missing {key} in round {rnd}', evidence) + if histories[0][rnd][key] != histories[1][rnd][key]: + return outcome('FAIL', f'{key} differs in round {rnd}', evidence) + try: + from safetensors import SafetensorError + ok, checkpoint = _lm_checkpoint_evidence(spec, first, second, eps) + except (OSError, ValueError, TypeError, KeyError, SafetensorError) as exc: + return outcome('FAIL', f'invalid checkpoint evidence: {exc}', evidence) + evidence['checkpoint'] = checkpoint + return outcome('PASS' if ok else 'FAIL', + f'all rounds and predictions agree; checkpoint max|Δ|={checkpoint["max_abs_delta"]:.2e} (eps={eps})', + evidence) + + @dataclass class DifferentialReport: mode: str @@ -159,21 +249,9 @@ def cross_framework(self, matrix: RunMatrix, metric: str = "accuracy", tolerance ok, detail = parity(vals, tolerance) evidence = {"frameworks": frameworks, metric: [round(v, 4) for v in vals]} if sample.task == 'causal_lm': - by_round = {} - for rnd in range(sample.num_rounds + 1): - values = [{int(k): v for k, v in result.history.items()}[rnd].get(metric) - for _, result in members] - if any(isinstance(v, bool) or not isinstance(v, Real) or not math.isfinite(v) - for v in values): - ok = False - detail = f'missing, nonfinite or invalid {metric} in round {rnd}' - break - round_ok, round_detail = parity(values, tolerance) - by_round[str(rnd)] = values - if not round_ok: - ok = False - detail = f'round {rnd}: {round_detail}' - break + round_ok, round_detail, by_round = _lm_round_metrics(members, metric, tolerance) + if not round_ok: + ok, detail = False, round_detail evidence['rounds'] = by_round report.outcomes.append(TestOutcome( "differential", label, "PASS" if ok else "FAIL", detail, @@ -187,6 +265,9 @@ def determinism(self, config: TestConfig, metric: str = "accuracy", eps: float = for spec in expand_run_specs(config): r1 = self.orchestrator.run_spec(spec) r2 = self.orchestrator.run_spec(spec) + if spec.task == 'causal_lm': + report.outcomes.append(compare_lm_repeats(spec, r1, r2, metric, eps)) + continue label = f"{spec.run_name} [{spec.framework}] {spec.dataset} c{spec.num_clients} r{spec.num_rounds}" if r1.status != "success" or r2.status != "success": report.outcomes.append(TestOutcome("differential", label, "FAIL", "a repeat run errored")) diff --git a/tests/test_reference_causal_lm.py b/tests/test_reference_causal_lm.py index a98c220..b2f12ee 100644 --- a/tests/test_reference_causal_lm.py +++ b/tests/test_reference_causal_lm.py @@ -258,3 +258,67 @@ def poison(ctx):ctx.client_update[0].fill(np.nan) monkeypatch.setattr('fltest.frameworks.reference.causal_lm.build_hook_runner',poisoned_runner) with pytest.raises(ValueError,match='nonfinite'): ReferenceAdapter().run_simulation(spec,prepared_data(spec),original(spec,load_env_hooks=False)) + + +@pytest.mark.parametrize('application',['finance','stackoverflow','medical']) +def test_real_cpu_reference_repeats_include_checkpoint_and_prediction_evidence(tmp_path,monkeypatch,application): + from fltest.testing.differential import compare_lm_repeats + patch_real_models(monkeypatch) + spec=parity_specs(tmp_path,application)[0] + results=[ReferenceAdapter().run_simulation(spec,prepared_data(spec), + build_hook_runner(spec,load_env_hooks=False)) for _ in range(2)] + outcome=compare_lm_repeats(spec,*results,metric='loss',eps=0.) + assert outcome.status=='PASS',outcome + assert outcome.evidence['checkpoint']['max_abs_delta']==0. + assert results[0].extras['checkpoint']!=results[1].extras['checkpoint'] + + +@pytest.mark.parametrize('change,message',[ + ('data','provenance differs'),('initial','initial parameter values differ'), + ('samples','trained records'),('round_metric','round 1'),('nan_final','nonfinite'), + ('missing_final','missing'),('predictions','predictions differs'),('missing_predictions','missing predictions'), + ('weights','checkpoint max'),('nan_weights','nonfinite checkpoint'),('shape','shape or dtype'), + ('names','tensor names'),('missing_checkpoint','checkpoint evidence'),('same_checkpoint','distinct checkpoint'), +]) +def test_repeatability_refuses_matching_headline_with_different_evidence(tmp_path,change,message): + save_file=pytest.importorskip('safetensors.numpy').save_file + from fltest.testing.differential import compare_lm_repeats + spec=parity_specs(tmp_path)[0] + results=[evidence_result(spec),evidence_result(spec)] + for index,result in enumerate(results): + for entry in result.history.values():entry['predictions']=[{'sample_id':10,'response':'yes'}] + path=tmp_path/str(index);path.mkdir() + save_file({'weight':np.ones((2,2),dtype='float32')},str(path/'adapter_model.safetensors')) + result.extras['checkpoint']=str(path) + target=results[1] + if change=='data':target.extras['data']['fingerprint']='other' + elif change=='initial':target.extras['initial_parameters_sha256']='other' + elif change=='samples':target.history[1]['clients'][0]['trained_sample_ids']=[6] + elif change=='round_metric':target.history[1]['loss']=2. + elif change=='nan_final':target.final['loss']=float('nan') + elif change=='missing_final':del target.final['loss'] + elif change=='predictions':target.history[1]['predictions'][0]['response']='no' + elif change=='missing_predictions':del target.history[1]['predictions'] + elif change=='missing_checkpoint':del target.extras['checkpoint'] + elif change=='same_checkpoint':target.extras['checkpoint']=results[0].extras['checkpoint'] + else: + array=np.ones((2,2),dtype='float32');name='weight' + if change=='weights':array[0,0]=2. + elif change=='nan_weights':array[0,0]=np.nan + elif change=='shape':array=np.ones((3,2),dtype='float32') + elif change=='names':name='different' + save_file({name:array},str(Path(target.extras['checkpoint'])/'adapter_model.safetensors')) + outcome=compare_lm_repeats(spec,*results,metric='loss',eps=0.) + assert outcome.status=='FAIL' and message in outcome.detail,outcome + + +def test_determinism_command_routes_lm_results_through_strict_evidence_check(tmp_path,monkeypatch): + from unittest.mock import Mock + spec=parity_specs(tmp_path)[0] + results=[evidence_result(spec),evidence_result(spec)] + results[1].history[1]['loss']=2. + monkeypatch.setattr('fltest.core.orchestrator.expand_run_specs',lambda config:[spec]) + orchestrator=Mock();orchestrator.run_spec.side_effect=results + report=DifferentialTester(orchestrator).determinism(TestConfig(),metric='loss',eps=0.) + assert orchestrator.run_spec.call_count==2 + assert report.outcomes[0].status=='FAIL' and 'round 1' in report.outcomes[0].detail