diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index df2cbaa..a7d6ab9 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 tests/test_lm_protocol.py tests/test_finance_benchmarks.py -q + - run: pytest tests/test_causal_lm.py tests/test_stackoverflow.py tests/test_medical.py tests/test_lm_protocol.py tests/test_finance_benchmarks.py tests/test_reference_causal_lm.py -q docs: name: docs build diff --git a/docs/causal-lm.md b/docs/causal-lm.md index 39f961b..f2c5b61 100644 --- a/docs/causal-lm.md +++ b/docs/causal-lm.md @@ -189,4 +189,5 @@ LM attacks, metrics, and incompatible defense combinations before loading a mode The [Stack Overflow application](stackoverflow.md) adds user-partitioned Parquet data, full-model training, and next-token evaluation. The [Medical application](medical.md) adds micro-batched flashcard training and PubMedQA subset evaluation. Optional DoRA -and the reference LM backend remain follow-up work. +remains follow-up work. The [reference backend](reference-causal-lm.md) supports +sequential LM execution and comparisons against Flower. diff --git a/docs/configuration.md b/docs/configuration.md index 10fbcda..dc6ef8e 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -123,6 +123,11 @@ A list of `{framework, name?, ...overrides}`. One entry per framework you want t A run entry may also override any top-level knob and may carry its own `attacks`/`defenses`/ `metrics`. Frameworks: `reference`, `flwr`/`flower`, `nvflare`/`flare`. +For `task: causal_lm`, supported backends are `reference` and `flwr`/`flower`. +Reference runs sequentially on the local device; it accepts the same explicit +`client_resources` and sampling settings for [LM parity](reference-causal-lm.md), +without starting Ray or allocating clients across nodes. + ### `testing:` - `differential:` — see [Differential testing](differential-testing.md). - `metamorphic:` — a list of relations; see [Metamorphic testing](metamorphic-testing.md). diff --git a/docs/differential-testing.md b/docs/differential-testing.md index 64cac5a..2d035fd 100644 --- a/docs/differential-testing.md +++ b/docs/differential-testing.md @@ -9,6 +9,11 @@ A single scalar metric from each run's `final` dict, selected by `testing.differential.metric` (default `accuracy`). Typically the final-round global-model test accuracy. +For causal LMs, cross-framework testing also compares that metric at round zero +and every trained round, after verifying initialization, data provenance and +client training evidence. See [reference LM parity](reference-causal-lm.md) for +the stricter grouping and evidence requirements. + ## Mode 1: `cross_framework` (parity) Same logical config, different FL framework ⇒ same final metric within tolerance. This @@ -37,8 +42,8 @@ testing: ``` !!! note "Parity, not bit-identity" - Different frameworks use different RNG streams and execution paths, so exact equality is - impossible. The reference and Flower backends share FLTest's own weighted-mean + Different frameworks can use different RNG streams and execution paths, so exact equality is + not guaranteed. The reference and Flower backends share FLTest's own weighted-mean aggregation, which keeps them close; the tolerance (default 0.05, as in the project slides) absorbs the residual. Choose tolerance to match your metric's natural variance. diff --git a/docs/medical.md b/docs/medical.md index 397c31c..326af32 100644 --- a/docs/medical.md +++ b/docs/medical.md @@ -134,5 +134,6 @@ arithmetic rather than implementing cryptographic deployment protocols. The deployment plan's full configuration is 20 IID clients with four selected per round, effective batch 16, sequence length 512 and ten local optimizer steps. -Repeated seeds, the full grid, long clean learning checks, reference-backend parity, -and the remaining leaderboard benchmarks require further experiments. +Repeated seeds, the full grid, long clean learning checks and the remaining +leaderboard benchmarks require further experiments. Small backend comparisons +are available through [reference LM parity](reference-causal-lm.md). diff --git a/docs/reference-causal-lm.md b/docs/reference-causal-lm.md new file mode 100644 index 0000000..382c35e --- /dev/null +++ b/docs/reference-causal-lm.md @@ -0,0 +1,54 @@ +# Reference causal-LM execution + +`framework: reference` runs Finance, Stack Overflow and Medical LM tasks in a +sequential PyTorch loop. It supports LoRA and full-model updates, round-zero and +per-round evaluation, checkpoints, client sampling, schedules, micro-batching, +and the same supported attack/defense hooks as Flower. + +The loop has no Flower or Ray execution dependency. It shares FLTest's data, +model, local-training, evaluation and aggregation helpers with Flower. This makes +it an oracle for orchestration and transport differences; it does not independently +validate those shared algorithms. Client hooks are reconstructed for every fit, +matching Flower worker RPC lifecycles. Updates are aggregated in client-ID order +in both LM backends, independent of RPC completion order. + +Install the LM extra as described in [installation](installation.md). Reference +runs on the local CPU or GPU selected by `device`. `client_resources` remains +required for a common comparison configuration, but reference executes one client +at a time and does not allocate Ray resources or use other nodes. + +## Run a small comparison + +The supplied GPU configurations use SmolLM2-135M, two trained rounds and capped +evaluation data. Start the two-node Ray cluster for the Flower half as described +in [multi-node execution](multi-node.md), then run: + +```bash +export FLTEST_RAY_ADDRESS=10.0.1.1:6379 +fltest diff examples/configs/finance_reference_parity.yaml +fltest diff examples/configs/stackoverflow_reference_parity.yaml +fltest diff examples/configs/medical_reference_parity.yaml +``` + +Stack Overflow requires the local user-partitioned Parquet exports described in +its [application guide](stackoverflow.md). Each configuration executes reference +first and Flower second. These are integration comparisons, not full benchmark +or learning experiments. GPU loss tolerance is explicitly `0.02`; choose a +tolerance appropriate to the model, precision and metric for larger comparisons. + +## What parity checks + +LM comparison groups include training, tokenizer, precision, resources and +evaluation settings; checkpoint destinations are excluded. At least two distinct +backends must be present (`flower` and `flwr` count as one). + +Before comparing the requested metric, the checker requires matching data +provenance, parameter manifests, an initialization SHA-256 fingerprint, and a +complete round history. Every trained round must show matching client IDs, +successful training-record IDs, sample weights, poisoning counts, user identities +and learning rates when present. It compares the requested finite metric at +round zero, every trained round and the final summary. Missing evidence fails +the comparison; legacy LM results without initialization fingerprints must be rerun. + +This checks backend agreement within tolerance. GPU repeatability, long clean +learning runs and full attack/defense grids remain separate validation work. diff --git a/examples/configs/finance_reference_parity.yaml b/examples/configs/finance_reference_parity.yaml new file mode 100644 index 0000000..4b66fc4 --- /dev/null +++ b/examples/configs/finance_reference_parity.yaml @@ -0,0 +1,62 @@ +# Small backend comparison; not a model-quality or determinism result. +name: finance_reference_parity +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: cross_framework + metric: loss + tolerance: 0.02 diff --git a/examples/configs/medical_reference_parity.yaml b/examples/configs/medical_reference_parity.yaml new file mode 100644 index 0000000..1fe9588 --- /dev/null +++ b/examples/configs/medical_reference_parity.yaml @@ -0,0 +1,56 @@ +# Small backend comparison; not a model-quality or determinism result. +name: medical_reference_parity +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: cross_framework + metric: loss + tolerance: 0.02 diff --git a/examples/configs/stackoverflow_reference_parity.yaml b/examples/configs/stackoverflow_reference_parity.yaml new file mode 100644 index 0000000..609a2d1 --- /dev/null +++ b/examples/configs/stackoverflow_reference_parity.yaml @@ -0,0 +1,52 @@ +# Small backend comparison; not a model-quality or determinism result. +name: stackoverflow_reference_parity +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: cross_framework + metric: loss + tolerance: 0.02 diff --git a/fltest/core/config.py b/fltest/core/config.py index 1bbbd6e..7b17fd9 100644 --- a/fltest/core/config.py +++ b/fltest/core/config.py @@ -274,7 +274,8 @@ class RunSpec(BaseModel): @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"): + reference_lm = self.task == "causal_lm" and self.framework == "reference" + if uses_flower_resources and self.framework not in ("flwr", "flower") and not reference_lm: 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") @@ -287,8 +288,8 @@ def validate_task(self): 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.framework not in ("flwr", "flower", "reference"): + raise ValueError("causal_lm supports framework: flwr or reference") finance = self.dataset.removeprefix("hf:") == "flwrlabs/fingpt-sentiment-train" medical = self.dataset.removeprefix("hf:") == "flwrlabs/medical-meadow-medical-flashcards" stackoverflow = self.dataset == "stackoverflow" diff --git a/fltest/data/causal_lm.py b/fltest/data/causal_lm.py index 3519219..c2b085a 100644 --- a/fltest/data/causal_lm.py +++ b/fltest/data/causal_lm.py @@ -300,6 +300,15 @@ def manifest_field(spec): return "parameter_manifest" if spec.lm.method == "full" else "adapter_manifest" +def causal_parameter_digest(parameters): + """Fingerprint the transported initialization without retaining a byte copy.""" + digest = hashlib.sha256() + for array in parameters: + digest.update(json.dumps((array.dtype.str, array.shape)).encode()) + digest.update(memoryview(np.ascontiguousarray(array)).cast('B')) + return digest.hexdigest() + + def causal_parameters(model, spec): if spec.lm.method == "lora": return adapter_parameters(model) diff --git a/fltest/frameworks/flower/adapter.py b/fltest/frameworks/flower/adapter.py index 517c3e6..5ed0376 100644 --- a/fltest/frameworks/flower/adapter.py +++ b/fltest/frameworks/flower/adapter.py @@ -111,6 +111,10 @@ 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 + if spec.task == 'causal_lm': + from fltest.data.causal_lm import causal_parameter_digest + + state_holder['initial_parameters_sha256'] = causal_parameter_digest(init_params) backend_config = ray_backend_config( spec.total_cpus, spec.total_gpus, spec.num_clients, spec.client_resources @@ -165,4 +169,5 @@ def run_simulation(self, spec: RunSpec, data: Dict[str, Any], hook_runner: HookR checkpoint=state_holder["checkpoint"], ) result.extras[manifest_field(spec)] = state_holder[manifest_field(spec)] + result.extras['initial_parameters_sha256'] = state_holder['initial_parameters_sha256'] return result diff --git a/fltest/frameworks/flower/server.py b/fltest/frameworks/flower/server.py index 3e6370b..83dd8fb 100644 --- a/fltest/frameworks/flower/server.py +++ b/fltest/frameworks/flower/server.py @@ -120,6 +120,8 @@ def aggregate_fit(self, server_round, results, failures): if (failures or any(type(cid) is not int for cid in ids) or len(ids) != len(self._selected_clients) or set(ids) != set(self._selected_clients)): raise RuntimeError(f"Causal-LM round {server_round} has missing or failed clients") + # RPC completion order must not choose floating-point summation or tie order. + successful.sort(key=lambda result: result[1].metrics['cid']) for _, response in successful: if self._spec.lm.lr_schedule is not None: from fltest.core.lm_protocol import validate_round_learning_rate diff --git a/fltest/frameworks/reference/adapter.py b/fltest/frameworks/reference/adapter.py index 8db9ad5..2bd571b 100644 --- a/fltest/frameworks/reference/adapter.py +++ b/fltest/frameworks/reference/adapter.py @@ -38,6 +38,10 @@ def _new_model(self, spec: RunSpec): ).to(spec.device) def run_simulation(self, spec: RunSpec, data: Dict[str, Any], hook_runner: HookRunner) -> RunResult: + if spec.task == "causal_lm": + from fltest.frameworks.reference.causal_lm import run_causal_simulation + + return run_causal_simulation(spec, data, hook_runner) seed_everything(spec.seed) result = RunResult(run_id=spec.run_id, run_name=spec.run_name, framework=self.name) diff --git a/fltest/frameworks/reference/causal_lm.py b/fltest/frameworks/reference/causal_lm.py new file mode 100644 index 0000000..672a3a9 --- /dev/null +++ b/fltest/frameworks/reference/causal_lm.py @@ -0,0 +1,194 @@ +"""Sequential causal-LM oracle, without Flower or Ray execution machinery.""" + +from collections import defaultdict +import gc +import random +import socket + +import torch + +from fltest.core import ClientSubmission, HookContext +from fltest.core.client_selection import resolve_selected_clients +from fltest.core.lm_protocol import learning_rate_for_round +from fltest.core.wiring import build_hook_runner +from fltest.data.causal_lm import ( + causal_manifest, causal_parameter_digest, causal_parameters, evaluate_causal_model, get_causal_model, + manifest_field, save_adapter_checkpoint, set_causal_parameters, train_causal_model, + validate_causal_parameters, +) +from fltest.data.utils import aggregate_ndarrays, seed_everything +from fltest.frameworks.base import RunResult + + +def _empty_cache(spec): + gc.collect() + if spec.device == 'cuda': + torch.cuda.empty_cache() + + +def _fit_client(spec, loader, parameters, manifest, selected, rnd, cid): + # Flower reconstructs client hooks per RPC; keep that lifecycle here as well. + runner = build_hook_runner(spec) + model = get_causal_model(spec) + after = None + try: + key = manifest_field(spec) + if causal_manifest(model, spec) != manifest: + raise ValueError('LM parameter manifest differs between driver and client') + set_causal_parameters(model, parameters, spec) + before = HookContext(cfg=spec, framework='reference', run_name=spec.run_name, + round=rnd, client_id=cid, client_data=loader, + global_state=parameters, selected_clients=selected) + runner.run('before_client_train', before) + training_loader = before.client_data if before.client_data is not None else loader + if spec.device == 'cuda': + torch.cuda.reset_peak_memory_stats() + details = {} + loss, count = train_causal_model(model, training_loader, spec, rnd, cid, details) + update = causal_parameters(model, spec) + after = HookContext(cfg=spec, framework='reference', run_name=spec.run_name, + round=rnd, client_id=cid, client_update=update, num_samples=count, + global_state=parameters, model=model, selected_clients=selected) + runner.run('after_client_train', after) + metrics = { + 'cid': cid, 'train_loss': loss, key: manifest, 'local_steps': spec.lm.local_steps, + 'host': socket.gethostname(), 'trained_sample_ids': details['trained_sample_ids'], + 'poisoned_samples': len(details['poisoned_sample_ids']), + 'peak_memory_mib': torch.cuda.max_memory_reserved() / 1024**2 if spec.device == 'cuda' else 0., + } + for values in (before.metrics, after.metrics): + metrics.update({k: float(v) for k, v in values.items() + if isinstance(v, (int, float)) and not isinstance(v, bool)}) + if spec.lm.lr_schedule is not None: + 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, + effective_batch_size=spec.client_batch_size) + if spec.dataset == 'stackoverflow': + metrics['user_id'] = loader.dataset[0]['user_id'] + ids = metrics['trained_sample_ids'] + if (type(metrics['cid']) is not int or metrics['cid'] != cid or metrics[key] != manifest + or not isinstance(ids, list) or any(type(sid) is not int or sid < 0 for sid in ids) + or count <= 0 or len(ids) != len(set(ids)) or len(ids) != count): + raise ValueError('Invalid causal-LM client identity, manifest or trained sample IDs') + update = after.client_update if after.client_update is not None else update + validate_causal_parameters(update, parameters) + return update, count, dict(metrics, num_samples=count) + finally: + if after is not None: + after.model = None + del model + _empty_cache(spec) + + +def _evaluate(spec, loader, parameters, manifest, rnd, history, runner, extra_metrics, metadata): + model = get_causal_model(spec) + ctx = None + try: + if causal_manifest(model, spec) != manifest: + raise ValueError('LM evaluation parameter manifest differs from initialization') + set_causal_parameters(model, parameters, spec) + details = {} + loss, accuracy = evaluate_causal_model(model, loader, spec, details) + metrics = {'accuracy': accuracy, 'loss': loss, **details['metrics']} + if rnd: + metrics.update(extra_metrics) + metrics['zero_shot_gap'] = accuracy - history[0]['accuracy'] + if (spec.dataset == 'stackoverflow' or spec.lm.medical is not None + or spec.lm.finance_benchmarks is not None): + metrics['zero_shot_loss_reduction'] = history[0]['loss'] - loss + if spec.lm.finance_benchmarks is not None: + for name in ('fpb', 'fiqa', 'tfns', 'finance_benchmark'): + metrics[name + '_zero_shot_gap'] = metrics[name + '_accuracy'] - history[0][name + '_accuracy'] + ctx = HookContext(cfg=spec, framework='reference', run_name=spec.run_name, round=rnd, + global_state=parameters, model=model, test_data=loader, + metrics=metrics, history=history) + runner.run('after_round', ctx) + history.setdefault(rnd, {}).update(ctx.metrics) + history[rnd]['predictions'] = details['predictions'] + if 'user_metrics' in details: + history[rnd]['heldout_user_metrics'] = details['user_metrics'] + if 'benchmark_predictions' in details: + history[rnd]['finance_benchmark_predictions'] = details['benchmark_predictions'] + if rnd == spec.num_rounds: + return save_adapter_checkpoint(model, spec, metadata) + finally: + if ctx is not None: + ctx.model = None + del model + _empty_cache(spec) + + +def run_causal_simulation(spec, data, runner): + seed_everything(spec.seed) + history = {} + loaders, test_loader = dict(data['c2loader']), data['test_loader'] + metadata = data.get('metadata', {}) + model = get_causal_model(spec) + try: + parameters, manifest = causal_parameters(model, spec), causal_manifest(model, spec) + finally: + del model + _empty_cache(spec) + runner.run('before_simulation', HookContext( + cfg=spec, framework='reference', run_name=spec.run_name, dist_dict=loaders, + test_data=test_loader, history=history, global_state=parameters, + )) + ctx_data = HookContext(cfg=spec, framework='reference', run_name=spec.run_name, + dist_dict=loaders, test_data=test_loader, history=history) + runner.run('on_data_distribute', ctx_data) + loaders = ctx_data.dist_dict if ctx_data.dist_dict is not None else loaders + initial_digest = causal_parameter_digest(parameters) + _evaluate(spec, test_loader, parameters, manifest, 0, history, runner, {}, metadata) + for rnd in range(1, spec.num_rounds + 1): + selected = tuple(range(spec.num_clients)) + if spec.clients_per_round is not None: + selected = tuple(sorted(random.Random(spec.seed + rnd).sample(selected, spec.clients_per_round))) + ctx = HookContext(cfg=spec, framework='reference', run_name=spec.run_name, round=rnd, + global_state=parameters, selected_clients=selected, history=history) + runner.run('before_round', ctx) + selected = resolve_selected_clients(ctx.selected_clients, spec.num_clients) + if any(cid not in loaders for cid in selected): + raise ValueError('Selected causal-LM client data is unavailable') + responses = [_fit_client(spec, loaders[cid], parameters, manifest, selected, rnd, cid) for cid in selected] + responses.sort(key=lambda response: response[2]['cid']) + history.setdefault(rnd, {})['clients'] = [metrics for _, _, metrics in responses] + submissions = tuple(ClientSubmission(metrics['cid'], tuple(update), count) + for update, count, metrics in responses) + ctx = HookContext(cfg=spec, framework='reference', run_name=spec.run_name, round=rnd, + updates_and_weights=[(update, count) for update, count, _ in responses], + client_submissions=submissions, global_state=parameters, + selected_clients=selected, history=history) + runner.run('before_aggregate', ctx) + updates = ctx.updates_and_weights if ctx.updates_and_weights is not None else [(u, n) for u, n, _ in responses] + aggregated = aggregate_ndarrays(updates) + ctx.new_global_state = aggregated + runner.run('on_aggregate', ctx) + aggregated = ctx.new_global_state if ctx.new_global_state is not None else aggregated + validate_causal_parameters(aggregated, parameters) + parameters = aggregated + ctx.new_global_state = parameters + runner.run('after_aggregate', ctx) + numerics = defaultdict(list) + for _, _, metrics in responses: + for key, value in metrics.items(): + if key not in ('cid', 'num_samples') and isinstance(value, (int, float)): + numerics[key].append(float(value)) + extra = {key: sum(values) / len(values) for key, values in numerics.items()} + extra.update(ctx.metrics) + # Release submissions before evaluation, especially for full-model runs. + del responses, submissions, updates, ctx + checkpoint = _evaluate(spec, test_loader, parameters, manifest, rnd, history, runner, extra, metadata) + if set(history) != set(range(spec.num_rounds + 1)): + raise RuntimeError('Causal-LM run ended without evaluation of every round') + final = HookContext(cfg=spec, framework='reference', run_name=spec.run_name, + global_state=parameters, test_data=test_loader, history=history, + metrics=dict(history[spec.num_rounds]), final_accuracy=history[spec.num_rounds]['accuracy']) + runner.run('after_simulation', final) + extras = dict(final.extras) + extras.update(data=metadata, checkpoint=checkpoint, execution={'mode': 'sequential', 'host': socket.gethostname()}) + extras[manifest_field(spec)] = manifest + extras['initial_parameters_sha256'] = initial_digest + return RunResult(run_id=spec.run_id, run_name=spec.run_name, framework='reference', + history=history, final=dict(final.metrics), extras=extras) diff --git a/fltest/testing/differential.py b/fltest/testing/differential.py index 28342fe..d4af458 100644 --- a/fltest/testing/differential.py +++ b/fltest/testing/differential.py @@ -12,6 +12,8 @@ from __future__ import annotations import json +import math +from numbers import Real from dataclasses import dataclass, field from typing import Any, Dict, List, Optional @@ -33,9 +35,68 @@ def logical_key(spec: RunSpec) -> str: payload: Dict[str, Any] = {f: getattr(spec, f) for f in _LOGICAL_FIELDS} payload["attacks"] = [(a.name, a.params, a.target_clients) for a in spec.attacks] payload["defenses"] = [(d.name, d.params) for d in spec.defenses] + if spec.task == 'causal_lm': + lm = spec.lm.run_settings() + lm.pop('checkpoint_dir', None) # artifact destinations do not change training + payload.update(task=spec.task, lm=lm, tokenizer=spec.tokenizer_id(), + clients_per_round=spec.clients_per_round, + client_resources=spec.client_resources.model_dump(), device=spec.device, + deterministic=spec.deterministic, dataset_partitions=spec.dataset_partitions, + server_batch_size=spec.server_batch_size, max_test_data_size=spec.max_test_data_size, + loss_fn=spec.loss_fn) return json.dumps(payload, sort_keys=True, default=str) +def _lm_execution_signature(result, rounds): + history = {int(key): value for key, value in result.history.items()} + if set(history) != set(range(rounds + 1)): + raise ValueError('missing round-0 or trained-round evaluation') + signature = [] + for rnd in range(1, rounds + 1): + clients = history[rnd].get('clients') + if not isinstance(clients, list) or not clients: + raise ValueError(f'missing client evidence in round {rnd}') + ids = [client.get('cid') for client in clients] + if any(type(cid) is not int for cid in ids) or len(ids) != len(set(ids)): + raise ValueError(f'invalid client identities in round {rnd}') + records = [] + for client in sorted(clients, key=lambda value: value['cid']): + samples = client.get('trained_sample_ids') + if (not isinstance(samples, list) or not samples + or any(type(sid) is not int or sid < 0 for sid in samples) + or len(samples) != len(set(samples)) or len(samples) != client.get('num_samples')): + raise ValueError(f'invalid trained-record evidence in round {rnd}') + records.append({**{key: client[key] for key in ( + 'cid', 'num_samples', 'poisoned_samples', 'user_id', 'learning_rate', + ) if key in client}, 'trained_sample_ids': sorted(samples)}) + signature.append(records) + return signature + + +def _lm_evidence_error(members): + first_spec, first = members[0] + key = 'parameter_manifest' if first_spec.lm.method == 'full' else 'adapter_manifest' + for _, result in members: + if ('data' not in result.extras or not result.extras.get(key) + or not result.extras.get('initial_parameters_sha256')): + return 'missing LM data provenance, parameter manifest or initialization digest' + baseline = json.loads(json.dumps(first.extras['data'], default=str)) + for spec, result in members[1:]: + if json.loads(json.dumps(result.extras['data'], default=str)) != baseline: + return 'LM data provenance differs between backends' + if result.extras[key] != first.extras[key]: + return 'LM parameter manifests differ between backends' + if result.extras['initial_parameters_sha256'] != first.extras['initial_parameters_sha256']: + return 'LM initial parameter values differ between backends' + try: + signatures = [_lm_execution_signature(result, spec.num_rounds) for spec, result in members] + except (ValueError, TypeError, KeyError) as exc: + return f'invalid LM execution evidence: {exc}' + if any(signature != signatures[0] for signature in signatures[1:]): + return 'LM selected clients, trained records, sample weights or poisoning/schedule evidence differs' + return None + + @dataclass class DifferentialReport: mode: str @@ -74,15 +135,49 @@ def cross_framework(self, matrix: RunMatrix, metric: str = "accuracy", tolerance "differential", label, "FAIL", f"{len(failed)} run(s) errored: {[r.framework for r in failed]}")) continue + if sample.task == 'causal_lm': + backends = {'flwr' if name == 'flower' else name for name in frameworks} + if len(backends) < 2: + report.outcomes.append(TestOutcome( + 'differential', label, 'SKIP', 'need >=2 distinct backends, not repeated aliases')) + continue + error = _lm_evidence_error(members) + if error: + report.outcomes.append(TestOutcome('differential', label, 'FAIL', error)) + continue vals = [r.final.get(metric) for _, r in members] if any(v is None for v in vals): report.outcomes.append(TestOutcome( - "differential", label, "SKIP", f"metric '{metric}' missing in some runs")) + "differential", label, "FAIL" if sample.task == 'causal_lm' else "SKIP", + f"metric '{metric}' missing in some runs")) + continue + if sample.task == 'causal_lm' and any( + isinstance(value, bool) or not isinstance(value, Real) or not math.isfinite(value) for value in vals + ): + report.outcomes.append(TestOutcome('differential', label, 'FAIL', f'nonfinite or invalid {metric}')) continue 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 + evidence['rounds'] = by_round report.outcomes.append(TestOutcome( "differential", label, "PASS" if ok else "FAIL", detail, - evidence={"frameworks": frameworks, metric: [round(v, 4) for v in vals]})) + evidence=evidence)) return report def determinism(self, config: TestConfig, metric: str = "accuracy", eps: float = 1e-4) -> DifferentialReport: diff --git a/mkdocs.yml b/mkdocs.yml index 0e5ceb3..6002e52 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -50,6 +50,7 @@ nav: - Config fuzzing: fuzzing.md - Multi-node clusters: multi-node.md - Causal language models: causal-lm.md + - Reference LM parity: reference-causal-lm.md - Finance benchmarks: finance-benchmarks.md - Stack Overflow: stackoverflow.md - Medical: medical.md diff --git a/tests/test_causal_lm.py b/tests/test_causal_lm.py index d0c68e4..2ac23b4 100644 --- a/tests/test_causal_lm.py +++ b/tests/test_causal_lm.py @@ -29,7 +29,7 @@ def lm_spec(**overrides): @pytest.mark.parametrize("overrides, message", [ - ({"runs": [{"framework": "reference"}]}, "framework: flwr"), + ({"runs": [{"framework": "nvflare"}]}, "framework: flwr"), ({"dataset": "ag_news"}, "fingpt"), ({"data_distribution": "dirichlet"}, "IID"), ({"clients_per_round": 3}, "must not exceed"), diff --git a/tests/test_reference_causal_lm.py b/tests/test_reference_causal_lm.py new file mode 100644 index 0000000..a98c220 --- /dev/null +++ b/tests/test_reference_causal_lm.py @@ -0,0 +1,260 @@ +"""Independent reference rounds versus real Flower RPC/strategy boundaries on CPU.""" + +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import pytest +import torch +from torch.utils.data import DataLoader + +from fltest.core import HookContext +from fltest.core.config import RunSpec, TestConfig +from fltest.core.orchestrator import expand_run_specs +from fltest.core.wiring import build_hook_runner +from fltest.data.causal_lm import LMCollator, causal_manifest, causal_parameter_digest, causal_parameters, manifest_field +from fltest.frameworks.base import RunResult +from fltest.frameworks.reference.adapter import ReferenceAdapter +from fltest.testing.differential import DifferentialTester, logical_key + + +def parity_specs(tmp_path, application='finance', **overrides): + opts=dict(precision='fp32',quantization=None,seq_len=32,local_steps=2, + gradient_checkpointing=False,lora_r=2,lora_alpha=4, + checkpoint_dir=str(tmp_path/'checkpoints'),lr_schedule={'min_lr':.0001}) + dataset='hf:flwrlabs/fingpt-sentiment-train' + distribution='iid' + if application=='stackoverflow': + dataset='stackoverflow';distribution='by_user' + opts.update(method='full',stackoverflow={'train_path':'train.parquet','heldout_path':'heldout.parquet'}) + if application=='medical': + dataset='hf:flwrlabs/medical-meadow-medical-flashcards' + opts.update(medical={'pubmedqa_max_samples':2},micro_batch_size=1,grad_accum_steps=2) + config=dict(task='causal_lm',dataset=dataset,data_distribution=distribution,model_name='hf:tiny/model', + device='cpu',num_clients=3,dataset_partitions=3,clients_per_round=2,num_rounds=2, + client_batch_size=2,server_batch_size=2,client_lr=.001,optimizer='SGD', + client_resources={'num_cpus':1,'num_gpus':0},lm=opts, + runs=[{'framework':'reference','name':'reference'},{'framework':'flwr','name':'flower'}]) + config.update(overrides) + return expand_run_specs(TestConfig(**config)) + + +class TinyTokenizer: + eos_token_id=pad_token_id=2 + + def encode(self,text,**kwargs): + return [{'positive':5,'negative':6,'neutral':7,'yes':8,'no':9,'maybe':10}.get(text,3)] + + def decode(self,tokens,**kwargs): + words={5:'positive',6:'negative',7:'neutral',8:'yes',9:'no',10:'maybe'} + return ' '.join(words.get(int(token),'?') for token in tokens if int(token)!=2) + + def apply_chat_template(self,*args,**kwargs):return [1,3,4] + + def save_pretrained(self,path): + Path(path,'tokenizer_config.json').write_text('{}') + + +def prepared_data(spec): + loaders={} + for cid in range(spec.num_clients): + rows=[] + for index in range(4): + target=5+index%2 + tokens=[1,3+cid,target,2] + rows.append({'input_ids':tokens,'labels':tokens if spec.dataset=='stackoverflow' else [-100,-100,target,2], + 'prompt_ids':tokens[:2],'response':'positive' if target==5 else 'negative', + 'sample_id':cid*10+index,'user_id':str(cid), + 'finance_row':{'instruction':'Choose','input':f'News {cid} {index}', + 'output':'positive' if target==5 else 'negative'}}) + loaders[cid]=DataLoader(rows,batch_size=2,shuffle=True,collate_fn=LMCollator(2)) + evaluation=[] + for index in range(2): + tokens=[1,4,5+index,2] + evaluation.append({'input_ids':tokens,'labels':tokens if spec.dataset=='stackoverflow' else [-100,-100,5+index,2], + 'prompt_ids':tokens[:2],'response':'positive' if index==0 else 'negative', + 'sample_id':1000+index,'user_id':f'heldout-{index}'}) + test=DataLoader(evaluation,batch_size=2,collate_fn=LMCollator(2)) + test.pubmedqa_rows=[{'id':str(i),'prompt_ids':[1,4],'gold':'yes' if i==0 else 'no','max_new_tokens':1} for i in range(2)] + return {'c2loader':loaders,'test_loader':test,'metadata':{'fixture':'tiny-local-v1'}} + + +def patch_real_models(monkeypatch): + pytest.importorskip('transformers') + pytest.importorskip('peft') + from transformers import GPT2Config,GPT2LMHeadModel + from peft import LoraConfig,get_peft_model + from fltest.frameworks.reference import causal_lm as reference_lm + + torch.set_num_threads(1) + def factory(spec): + torch.manual_seed(spec.seed) + model=GPT2LMHeadModel(GPT2Config(vocab_size=32,n_embd=16,n_layer=1,n_head=2,n_positions=64, + resid_pdrop=.1,embd_pdrop=.1,attn_pdrop=.1)) + if spec.lm.method=='lora': + model=get_peft_model(model,LoraConfig(r=2,lora_alpha=4,task_type='CAUSAL_LM',lora_dropout=.1)) + return model + monkeypatch.setattr('fltest.data.causal_lm.get_causal_model',factory) + monkeypatch.setattr(reference_lm,'get_causal_model',factory) + for module in ('fltest.data.causal_lm','fltest.data.medical','fltest.attacks.causal_lm'): + monkeypatch.setattr(module+'.load_tokenizer',lambda spec:TinyTokenizer()) + return factory + + +def flower_in_process(spec,data,factory): + from flwr.common import Code,ndarrays_to_parameters + from fltest.frameworks.flower.client import FlowerClient + from fltest.frameworks.flower.server import get_server_app + + model=factory(spec);params=causal_parameters(model,spec);manifest=causal_manifest(model,spec) + driver=build_hook_runner(spec,load_env_hooks=False) + history={} + driver.run('before_simulation',HookContext(cfg=spec,framework='flwr',global_state=params,history=history)) + driver.run('on_data_distribute',HookContext(cfg=spec,framework='flwr',dist_dict=data['c2loader'], + test_data=data['test_loader'],history=history)) + holder={'data_metadata':data['metadata'],manifest_field(spec):manifest, + 'initial_parameters_sha256':causal_parameter_digest(params)} + app=get_server_app(spec,driver,history,data['test_loader'],holder,initial_params=params) + strategy=app._server_fn(None).strategy + parameters=ndarrays_to_parameters(params) + proxies=[SimpleNamespace(cid=str(cid),get_properties=lambda *args,cid=cid,**kw: + SimpleNamespace(status=SimpleNamespace(code=Code.OK),properties={'cid':cid})) for cid in range(spec.num_clients)] + class Manager: + def num_available(self):return len(proxies) + def sample(self,num_clients,min_num_clients):return proxies + strategy.evaluate(0,parameters) + for rnd in range(1,spec.num_rounds+1): + selected=strategy.configure_fit(rnd,parameters,Manager()) + responses=[] + # Reverse arrival order to exercise canonical client-ID aggregation. + for proxy,ins in reversed(selected): + cid=int(proxy.cid) + client=FlowerClient(data['c2loader'][cid],spec,cid,build_hook_runner(spec)).to_client() + responses.append((proxy,client.fit(ins))) + parameters,_=strategy.aggregate_fit(rnd,responses,[]) + strategy.evaluate(rnd,parameters) + return RunResult(run_id=spec.run_id,run_name=spec.run_name,framework='flwr',history=history, + final=dict(history[spec.num_rounds]),extras={ + 'data':data['metadata'],'checkpoint':holder['checkpoint'], + manifest_field(spec):manifest,'initial_parameters_sha256':holder['initial_parameters_sha256']}) + + +@pytest.mark.parametrize('application,attacks,defenses',[ + ('finance',[],[]),('stackoverflow',[],[]),('medical',[],[]), + ('finance',[{'name':'label_flip','target_clients':[1]}],[{'name':'norm_clip'}]), + ('finance',[{'name':'membership_inference','params':{'target_client':1,'max_samples':2}}], + [{'name':'gradient_noise','params':{'sigma':.001}}]), + ('stackoverflow',[{'name':'membership_inference','params':{'unit':'user','max_users':2,'max_samples':2}}], + [{'name':'secure_aggregation'}]), + ('finance',[],[{'name':'mpc_aggregation'}]), +]) +def test_real_cpu_training_matches_flower_transport_and_hooks(tmp_path,monkeypatch,application,attacks,defenses): + factory=patch_real_models(monkeypatch) + specs=parity_specs(tmp_path,application,attacks=attacks,defenses=defenses) + reference=ReferenceAdapter().run_simulation(specs[0],prepared_data(specs[0]),build_hook_runner(specs[0],load_env_hooks=False)) + flower=flower_in_process(specs[1],prepared_data(specs[1]),factory) + assert reference.extras['execution']['mode']=='sequential' + assert reference.extras['initial_parameters_sha256']==flower.extras['initial_parameters_sha256'] + for rnd in range(specs[0].num_rounds+1): + for key in ('loss','accuracy'): + assert reference.history[rnd][key]==pytest.approx(flower.history[rnd][key],abs=1e-7) + for key,value in reference.history[rnd].items(): + if key.startswith('membership_'): + assert value==pytest.approx(flower.history[rnd][key],abs=1e-7) + if rnd: + assert [(c['cid'],c['trained_sample_ids']) for c in reference.history[rnd]['clients']]==[ + (c['cid'],c['trained_sample_ids']) for c in flower.history[rnd]['clients']] + from safetensors.numpy import load_file + filename='model.safetensors' if application=='stackoverflow' else 'adapter_model.safetensors' + first=load_file(Path(reference.extras['checkpoint'])/filename) + second=load_file(Path(flower.extras['checkpoint'])/filename) + assert first.keys()==second.keys() + for key in first:np.testing.assert_allclose(first[key],second[key],atol=1e-7,rtol=1e-6) + matrix=SimpleNamespace(specs=specs,results=[reference,flower]) + report=DifferentialTester().cross_framework(matrix,metric='loss',tolerance=1e-7) + assert [o.status for o in report.outcomes]==['PASS'],report.outcomes + + +def evidence_result(spec): + return RunResult(run_id=spec.run_id,run_name=spec.run_name,framework=spec.framework, + final={'loss':1.,'accuracy':.5},history={ + 0:{'loss':2.,'accuracy':.5}, + **{rnd:{'loss':1.,'accuracy':.5,'clients':[{'cid':0,'num_samples':1,'trained_sample_ids':[5], + 'poisoned_samples':0}]} for rnd in range(1,spec.num_rounds+1)}}, + extras={'data':{'fingerprint':'source'},'adapter_manifest':'shape', + 'initial_parameters_sha256':'weights'}) + + +@pytest.mark.parametrize('change,message',[ + ('data','provenance differs'),('initial','initial parameter values differ'), + ('manifest','manifests differ'),('samples','trained records'),('clients','selected clients'), + ('missing_round','round-0'),('missing_digest','initialization digest'),('nonfinite','nonfinite'), + ('missing_metric','missing in some runs'), + ('intermediate_metric','round 1'),('missing_round_metric','round 1'), +]) +def test_lm_oracle_refuses_false_parity_even_when_headline_scores_match(tmp_path,change,message): + specs=parity_specs(tmp_path);results=[evidence_result(spec) for spec in specs] + target=results[1] + if change=='data':target.extras['data']['fingerprint']='different' + elif change=='initial':target.extras['initial_parameters_sha256']='different' + elif change=='manifest':target.extras['adapter_manifest']='different' + elif change=='samples':target.history[1]['clients'][0]['trained_sample_ids']=[6] + elif change=='clients':target.history[1]['clients'][0]['cid']=1 + elif change=='missing_round':del target.history[0] + elif change=='missing_digest':del target.extras['initial_parameters_sha256'] + elif change=='nonfinite':target.final['loss']=float('nan') + elif change=='missing_metric':del target.final['loss'] + elif change=='intermediate_metric':target.history[1]['loss']=2. + elif change=='missing_round_metric':del target.history[1]['loss'] + report=DifferentialTester().cross_framework(SimpleNamespace(specs=specs,results=results),metric='loss') + assert report.outcomes[0].status=='FAIL' and message in report.outcomes[0].detail + + +@pytest.mark.parametrize('field,value', [('clients_per_round',1),('server_batch_size',1),('max_test_data_size',16), + ('tokenizer','other/tokenizer'),('lm.local_steps',3),('lm.precision','fp16')]) +def test_lm_logical_key_includes_protocol_and_evaluation_knobs(tmp_path,field,value): + original=parity_specs(tmp_path)[0];changed=original.model_copy(deep=True) + if field.startswith('lm.'):setattr(changed.lm,field.split('.')[1],value) + else:setattr(changed,field,value) + assert logical_key(original)!=logical_key(changed) + destination=original.model_copy(deep=True);destination.lm.checkpoint_dir='different/artifacts' + assert logical_key(original)==logical_key(destination) + + +def test_reference_lm_resources_do_not_enable_classifier_resource_overrides(): + with pytest.raises(ValueError,match='framework: flwr'): + RunSpec(run_id='x',run_name='x',framework='reference',client_resources={'num_gpus':1}) + + +def test_lm_oracle_does_not_count_flower_alias_as_another_backend(tmp_path): + specs=parity_specs(tmp_path) + specs[0].framework='flower' + report=DifferentialTester().cross_framework(SimpleNamespace( + specs=specs,results=[evidence_result(spec) for spec in specs]),metric='loss') + assert [outcome.status for outcome in report.outcomes]==['SKIP'] + assert 'distinct backends' in report.outcomes[0].detail + + +def test_reference_lm_honors_before_round_selection(tmp_path,monkeypatch): + patch_real_models(monkeypatch) + spec=parity_specs(tmp_path)[0] + runner=build_hook_runner(spec,load_env_hooks=False) + def select(ctx):ctx.selected_clients=[2,0] + runner.register('before_round',select) + result=ReferenceAdapter().run_simulation(spec,prepared_data(spec),runner) + for rnd in range(1,spec.num_rounds+1): + assert [client['cid'] for client in result.history[rnd]['clients']]==[0,2] + + +def test_reference_lm_rejects_nonfinite_client_update(tmp_path,monkeypatch): + patch_real_models(monkeypatch) + spec=parity_specs(tmp_path)[0] + original=build_hook_runner + def poisoned_runner(spec): + runner=original(spec,load_env_hooks=False) + def poison(ctx):ctx.client_update[0].fill(np.nan) + runner.register('after_client_train',poison) + return runner + 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))