Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
bench: publish GRADDIFF harness for issue #379 (#1170)
Samarth Mukhija9c6376b64bb0
diff --git a/benchmarks/README.md b/benchmarks/README.mdindex 39fef2be..29e2861d 100644--- a/benchmarks/README.md+++ b/benchmarks/README.md@@ -60,6 +60,7 @@ only in a scratchpad on a machine that is gone, which is| [`fixture_window_cpu.py`](harness/fixture_window_cpu.py) | STEP 13 / historical `fixture_window_cpu.py` **and** `cpu_mode_probe.py` questions in [`gate-h100-validation.md`](gate-h100-validation.md) | **Per-layer reconstruction, not a reproduction of the recorded full-model logits.** Replays the 64x64 / 256x64 CPU M=8..256 window and packed-inference mechanism. Every row publishes an emulated-bf16 reference; the JSON reports the worst relative bf16 error and how many times the 2% packed-effect envelope exceeds it. The training control must be exact on every row; default exit codes: 0 reproduced, 2 capability absent, 3 control failed, 4 packed effect absent, 5 packed effect out of range. `--survey` waives only exit 2. | `pip install -e ".[train]"`; CPU + bitsandbytes. AVX512-BF16 is required to demonstrate packing. The JSON records whether CPU `gemv_4bit` is registered and a best-effort native/kernels-community attribution; importing bitsandbytes may fetch optional kernels-community code. || [`bitexact.py`](harness/bitexact.py) | v0.72.0 / STEP 1; gate-h100-validation.md Reproducing | Shard -> stream -> compare logits, LoRA gradients, and loss curve against a resident reference using matching numerics; NF4 uses a resident NF4 reference | CUDA GPU required; model/checkpoint weights required; historical run: Qwen2.5-0.5B-Instruct NF4, seq 64; CUDA validation: torch 2.5.1+cu121, transformers 4.57.6, trl 0.19.1, peft 0.18.1 || [`variant2_gate.py`](harness/variant2_gate.py) | v0.72.5 / STEP 14 | Re-run the streamed-NF4 repair gate with the defect-present control and repaired arm in one process against one resident NF4 reference. Canonical parameter intersection and shared LoRA gradients must both be non-empty; the control must break and the repair must be exact | CUDA GPU with room for one streamed model plus its resident reference. Historical 32B/72B gates: H100 80 GB, torch 2.13.0+cu130, bitsandbytes 0.50.0, transformers 4.57.6, trl 0.26.2, peft 0.20.0; batch 1, seq 128, 2 pinned buffers, 5 repetitions. **The maintainer's small-model smoke on an RTX 5070 Laptop (sm_120, 8 GB; torch 2.14.0+cu130, bitsandbytes 0.50.2, transformers 5.17.0, peft 0.20.0) failed closed, as expected:** below roughly 164–172 MiB per NF4 layer the control cannot break, and sm_120 can distinguish fused bitsandbytes from explicit dequantisation. Such `RESULT: failed` outcomes are not evidence that the repair regressed. The new harness still has not been validated on an H100-class card. |+| [`graddiff.py`](harness/graddiff.py) | STEP 2b / [gate-h100-validation.md](gate-h100-validation.md) | Historical reconstruction of the GRADDIFF investigation: compare all LoRA gradients after one backward, then run each model's own 5-step loss curve twice. Historical Qwen2.5-32B-Instruct NF4 on H100 had 256/256 gradients exact on the first backward; the record also includes a 20/256 run, so this harness reports the measured count and applies its conservative exactness gate without claiming first-pass stability. Measurement 1 recorded non-identical streamed and resident self-curves (`C resident self-identical: False`); this harness deliberately restores the adapter and creates a fresh AdamW optimizer for each curve, requiring resident self-identity as a control. The record does not explain its C=False result. The historical control is installed by default; the old repaired-path #968 loss mismatch is not the default controlled measurement. The harness uses canonical parameter overlap and a negative empty-intersection self-test; it reports that the historical pattern was not reproduced instead of treating that as a pass | VRAM floor: about 26,713 MiB recorded with resident NF4 32B + streamed model live; local Qwen2.5-32B-Instruct bf16 safetensors checkpoint as real files (the harness quantizes it to NF4; symlinked HF snapshots are refused); resident NF4 reference required; no downloads; historical validation stack: H100 80GB, torch 2.13.0+cu130, bitsandbytes 0.50.0; default seq 128, batch 1, two stream buffers, 5 curve steps || [`fsdp_sharding_probe.py`](harness/fsdp_sharding_probe.py) | STEP 20 / [#373](https://github.com/MakazhanAlpamys/Soup/issues/373) | Is the base actually **sharded**, or was the flag merely accepted? Per-rank `local == total / world_size` asserted, with the single-GPU control expecting the *full* count so a probe that always divides fails instead of passing everything. Repairs the STEP 20 probe, which raised `TypeError('FullyShardedDataParallel does not support len()')` on all eight ranks at 70B — a `torch.compile` wrapper, not FSDP | Accounting is pure-Python and CPU-tested; a real reading needs the multi-GPU box under test || [`mlx_sft_smoke.py`](harness/mlx_sft_smoke.py) | [#23](https://github.com/MakazhanAlpamys/Soup/issues/23) / [`run-m1-8gb-mlx-sft.md`](run-m1-8gb-mlx-sft.md) | Does `MLXSFTTrainerWrapper.train()` actually run against a real MLX runtime, and what does it peak at? Asserts MLX **dispatch before measuring**, so a transformers-path number cannot be published as an MLX one (#363). Generates its own fixture; prints host memory and swap either side | Apple Silicon + `pip install -e ".[mlx]"`; downloads the chosen model; 20 s at 0.5B, ~6 min at 8B including the Hub fetch || [`issue395_second_stack_vram.py`](harness/issue395_second_stack_vram.py) | #395 / [`gate-395-second-stack-vram.md`](gate-395-second-stack-vram.md) | Does the long-sequence under-prediction reproduce on a second stack, and is the gap the logits multiplier? Answer: no and no — the loss term measures 12.000000 (spread 0), and `14 x E` alone exceeds the whole real peak on every row, so the `+2` retained copy is absent. Three modes: sweep, `--measure`, `--sdpa` | 24 GB card (largest arm peaks 11.85 GB); downloads SmolLM2-135M and Qwen2.5-0.5B; needs `jinja2>=3.1.0`; a few minutes |diff --git a/benchmarks/harness/graddiff.py b/benchmarks/harness/graddiff.pynew file mode 100644index 00000000..3b802bed--- /dev/null+++ b/benchmarks/harness/graddiff.py@@ -0,0 +1,748 @@+#!/usr/bin/env python3+"""Reconstruct the historical STEP 2b GRADDIFF investigation.++This harness is a reconstruction of the published GRADDIFF slice from issue+#379. It does not replace the historical protocol with a newer repeated-+backward variant. The documented H100 observation was:++- Qwen2.5-32B-Instruct NF4, bf16 compute+- first backward: streamed vs resident LoRA gradients were 256/256 exact+- streamed self-curve: not identical on the second run+- recorded resident self-curve: ``C resident self-identical: False``+ Measurement 1. This harness deliberately rebuilds/restores the adapter+ state for its resident self-curve control, so its resident result is a+ harness-owned reconstruction choice rather than a causal explanation.++The historical record is the source of truth for the expected pattern. The+reconstruction choices below intentionally mirror the original experiment's+structure and keep the default behavior aligned with that historical target:++- sequence length: 128 tokens per sample+- training curve: 5 batches, each used twice for the streamed and resident+ self-checks+- optimizer: AdamW with learning rate 1.0e-3+- one backward comparison followed by two self-curves for each model replica++The later STEP 2b measurements showed that the streamed backward becomes non-+reproducible from the second backward onward while the resident backward remains+deterministic. This harness therefore succeeds only when the historical+GRADDIFF pattern is observed on the default path with the shipped repair+disabled. On repaired main, where that historical divergence is absent, it+reports that the historical result was not reproduced and exits non-zero.++Requirements+------------+- CUDA-capable GPU+- PyTorch, transformers, peft, safetensors, bitsandbytes+- A locally available Qwen2.5-32B-Instruct checkpoint+- Enough GPU memory for a resident NF4 reference plus the streamed model+- No model download is performed++A machine without CUDA exits 0 with an explicit skip.++Exit codes+----------+0 historical GRADDIFF pattern reproduced (or CUDA skip)+1 historical pattern not reproduced+2 invalid CLI/input+3 invalid or non-finite measurement+"""++from __future__ import annotations++import argparse+import gc+import math+import sys+from pathlib import Path+from typing import Any++import bitexact+from mechanism_cost import install_historical_control++DTYPE = "bfloat16"+DEFAULT_SEQ = 128+DEFAULT_BATCH = 1+DEFAULT_BUFFERS = 2+DEFAULT_CURVE_STEPS = 5+DEFAULT_SEED = 3+INPUT_SEED = 17+DEVICE = "cuda"+++class MeasurementInvalidError(RuntimeError):+ """The run cannot support a numerical verdict."""+++def cuda_available() -> bool:+ return bitexact.cuda_available()+++def runtime_versions() -> tuple[str, str, str]:+ """Return benchmark dependency versions after the CUDA boundary."""++ import bitsandbytes as bnb+ import peft+ import transformers++ return bnb.__version__, peft.__version__, transformers.__version__+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(+ description=(+ "Reproduce the STEP 2b one-backward gradient comparison and "+ "two 5-step self-curves."+ )+ )+ parser.add_argument(+ "--weights",+ help="local Qwen2.5-32B-Instruct checkpoint directory",+ )+ parser.add_argument(+ "--shards",+ help="directory for Soup layer shards",+ )+ parser.add_argument(+ "--seq",+ type=int,+ default=DEFAULT_SEQ,+ help=f"sequence length (default: {DEFAULT_SEQ})",+ )+ parser.add_argument(+ "--batch",+ type=int,+ default=DEFAULT_BATCH,+ help=f"batch size (default: {DEFAULT_BATCH})",+ )+ parser.add_argument(+ "--buffers",+ type=int,+ default=DEFAULT_BUFFERS,+ help=f"stream buffer count (default: {DEFAULT_BUFFERS})",+ )+ parser.add_argument(+ "--curve-steps",+ type=int,+ default=DEFAULT_CURVE_STEPS,+ help=f"training steps in each self-curve (default: {DEFAULT_CURVE_STEPS})",+ )+ parser.add_argument(+ "--self-test",+ action="store_true",+ help="run the CPU-only acceptance self-test and exit",+ )+ return parser.parse_args()+++def canonical_parameters(model: Any) -> dict[str, Any]:+ from soup_cli.utils.layer_stream_runtime import canonical_named_parameters++ return dict(canonical_named_parameters(model))+++def capture_lora_state(model: Any) -> dict[str, Any]:+ """Snapshot LoRA tensors to CPU for deterministic curve restarts."""++ state: dict[str, Any] = {}++ for name, parameter in canonical_parameters(model).items():+ if "lora_" in name:+ state[name] = parameter.detach().cpu().clone()++ if not state:+ raise RuntimeError("model produced no LoRA tensors")++ return state+++def restore_lora_state(model: Any, state: dict[str, Any]) -> None:+ """Restore a CPU LoRA snapshot into a model."""++ with __import__("torch").no_grad():+ target = canonical_parameters(model)++ for name, value in state.items():+ parameter = target.get(name)++ if parameter is None:+ raise RuntimeError(+ f"could not match LoRA parameter {name!r}"+ )++ parameter.copy_(+ value.to(+ device=parameter.device,+ dtype=parameter.dtype,+ )+ )+++def backward_once(model: Any, input_ids: Any) -> tuple[Any, dict[str, Any]]:+ """Run one loss/backward pass and return loss plus canonical LoRA grads."""++ import torch++ torch.manual_seed(INPUT_SEED)++ model.train()+ model.zero_grad(set_to_none=True)++ output = model(+ input_ids=input_ids,+ labels=input_ids,+ )+ loss = output.loss+ loss.backward()++ gradients = bitexact.collect_lora_grads(model)++ if not gradients:+ raise RuntimeError("model produced no LoRA gradients")++ return loss.detach().clone(), gradients+++def compare_gradients(+ streamed: Any,+ reference: Any,+ streamed_grads: dict[str, Any],+ reference_grads: dict[str, Any],+) -> tuple[int, int, float, float]:+ """Compare canonical LoRA gradients and reject an empty intersection."""++ import torch++ from soup_cli.utils.layer_stream_runtime import (+ assert_canonical_parameters_intersect,+ )++ assert_canonical_parameters_intersect(+ streamed,+ reference,+ )++ if set(streamed_grads) != set(reference_grads):+ raise RuntimeError(+ "streamed/reference LoRA gradient sets differ"+ )++ exact = 0+ max_abs = 0.0+ max_rel = 0.0++ for name, streamed_gradient in streamed_grads.items():+ reference_gradient = reference_grads[name]++ if streamed_gradient.shape != reference_gradient.shape:+ raise RuntimeError(+ f"gradient shape differs for {name!r}: "+ f"{tuple(streamed_gradient.shape)} != "+ f"{tuple(reference_gradient.shape)}"+ )++ if not torch.isfinite(streamed_gradient).all():+ raise MeasurementInvalidError(+ f"streamed gradient contains non-finite values: {name}"+ )++ if not torch.isfinite(reference_gradient).all():+ raise MeasurementInvalidError(+ f"reference gradient contains non-finite values: {name}"+ )++ diff = (+ streamed_gradient - reference_gradient+ ).abs()++ abs_diff = float(diff.max())+ max_abs = max(max_abs, abs_diff)++ denominator = reference_gradient.abs().clamp_min(1.0e-30)+ rel_diff = float((diff / denominator).max())+ max_rel = max(max_rel, rel_diff)++ if torch.equal(streamed_gradient, reference_gradient):+ exact += 1++ return exact, len(streamed_grads), max_abs, max_rel+++def train_curve_once(+ model: Any,+ batches: list[Any],+ initial_lora: dict[str, Any],+) -> list[float]:+ """Run one fresh optimizer curve from the same adapter initialization."""++ import torch++ torch.manual_seed(INPUT_SEED)+ restore_lora_state(model, initial_lora)++ model.train()+ model.zero_grad(set_to_none=True)++ trainable = [+ parameter+ for parameter in model.parameters()+ if parameter.requires_grad+ ]++ if not trainable:+ raise RuntimeError("model has no trainable parameters")++ optimizer = torch.optim.AdamW(+ trainable,+ lr=1.0e-3,+ )++ losses: list[float] = []++ for input_ids in batches:+ optimizer.zero_grad(set_to_none=True)++ loss = model(+ input_ids=input_ids,+ labels=input_ids,+ ).loss++ losses.append(float(loss.detach()))+ loss.backward()+ optimizer.step()++ return losses+++def curve_diff(+ first: list[float],+ second: list[float],+) -> tuple[bool, float, float]:+ """Return exact equality plus max absolute and relative loss differences."""++ if len(first) != len(second):+ raise RuntimeError("loss curves have different lengths")++ max_abs = 0.0+ max_rel = 0.0++ for index, (left, right) in enumerate(zip(first, second, strict=True)):+ if not math.isfinite(left) or not math.isfinite(right):+ raise MeasurementInvalidError(+ "loss curve contains non-finite values: "+ f"left[{index}]={left!r}, right[{index}]={right!r}"+ )++ difference = abs(left - right)+ max_abs = max(max_abs, difference)+ max_rel = max(+ max_rel,+ difference / max(abs(right), 1.0e-30),+ )++ return first == second, max_abs, max_rel+++def historical_pattern_reproduced(+ exact: int,+ total: int,+ streamed_equal: bool,+ resident_equal: bool,+) -> bool:+ """Apply the conservative reconstruction gate to the recorded pattern.++ ``exact == total`` is a harness-owned validation requirement. The+ published record reported varying first-backward exactness across runs;+ this gate must not be read as claiming that every recorded run was exact.+ """++ return (+ exact == total+ and total > 0+ and not streamed_equal+ and resident_equal+ )+++def historical_pattern_exit_code(historical_pattern: bool) -> int:+ """Return the CLI exit code for the historical GRADDIFF verdict."""+ return 0 if historical_pattern else 1+++def run_self_test() -> int:+ """Exercise the production canonical-overlap guard without CUDA."""++ import torch++ class Tiny(torch.nn.Module):+ def __init__(self, parameter_name: str) -> None:+ super().__init__()+ self.register_parameter(+ parameter_name,+ torch.nn.Parameter(torch.ones(1)),+ )++ left = Tiny("lora_A")+ right = Tiny("lora_B")++ try:+ compare_gradients(+ left,+ right,+ {},+ {},+ )+ except ValueError as exc:+ print(+ "PASS: empty canonical parameter intersection was rejected "+ f"({type(exc).__name__}: {exc})"+ )+ return 0+ except MeasurementInvalidError as exc:+ print(f"ERROR: invalid measurement: {exc}")+ return 3+ except Exception as exc:+ raise RuntimeError(+ "negative acceptance test failed: unexpected exception "+ f"{type(exc).__name__}: {exc}"+ ) from exc++ raise RuntimeError(+ "negative acceptance test failed: empty canonical parameter "+ "intersection was accepted"+ )+++def run_measurement(args: argparse.Namespace) -> int:+ import torch++ from soup_cli.utils.layer_shard import shard_checkpoint+ from soup_cli.utils.layer_stream_runtime import (+ build_meta_skeleton,+ build_streamed_model,+ quantised_layer_suffixes,+ )++ if not args.weights:+ print("ERROR: --weights is required unless --self-test is used")+ return 2++ if not args.shards:+ print("ERROR: --shards is required unless --self-test is used")+ return 2++ if args.seq <= 0:+ print("ERROR: --seq must be positive")+ return 2++ if args.batch <= 0:+ print("ERROR: --batch must be positive")+ return 2++ if args.buffers < 2 or args.buffers > 8:+ print("ERROR: --buffers must be between 2 and 8")+ return 2++ if args.curve_steps <= 0:+ print("ERROR: --curve-steps must be positive")+ return 2++ if not cuda_available():+ print("SKIP: CUDA is required for graddiff.py")+ return 0++ weights = Path(args.weights).expanduser().resolve()++ if not weights.is_dir():+ print(+ f"ERROR: --weights must be a local checkpoint directory: {weights}"+ )+ return 2++ shard_dir = Path(args.shards).expanduser().resolve()+ shard_dir.mkdir(parents=True, exist_ok=True)++ probe = build_meta_skeleton(+ str(weights),+ dtype=DTYPE,+ quant="nf4",+ )++ arch = bitexact.model_arch_name(probe)+ vocab_size = int(probe.config.vocab_size)+ quant_suffixes = quantised_layer_suffixes(probe)++ del probe++ print("RUN: STEP 2b GRADDIFF")+ print(f"torch {torch.__version__}")+ print(f"gpu {torch.cuda.get_device_name(0)}")++ bnb_version, peft_version, transformers_version = runtime_versions()+ print(f"bitsandbytes {bnb_version}")+ print(f"transformers {transformers_version}")+ print(f"peft {peft_version}")+ print(f"weights {weights}")+ print(f"seq {args.seq}")+ print(f"batch {args.batch}")+ print(f"buffers {args.buffers}")+ print(f"curve_steps {args.curve_steps}")+ print()++ index = shard_checkpoint(+ str(weights),+ str(shard_dir),+ dtype=DTYPE,+ arch=arch,+ quant="nf4",+ quant_suffixes=quant_suffixes,+ double_quant=True,+ quant_device=DEVICE,+ )++ lora_config = bitexact.lora_config()++ import soup_cli.utils.layer_stream_runtime as layer_runtime++ original_install_dequant_forward = layer_runtime.install_dequant_forward+ streamed = None+ runtime = None+ reference = None++ try:+ install_historical_control(layer_runtime)++ streamed, runtime = build_streamed_model(+ model_id=str(weights),+ shard_dir=str(shard_dir),+ index=index,+ lora_config=lora_config,+ device=DEVICE,+ dtype=DTYPE,+ buffers=args.buffers,+ pin=True,+ seed=DEFAULT_SEED,+ quant="nf4",+ double_quant=True,+ tier="ram",+ )++ actual_pinned = getattr(runtime, "pinned", None)++ if actual_pinned is not True:+ raise RuntimeError(+ f"requested pin=True, but runtime reports pinned={actual_pinned!r}"+ )++ source = getattr(runtime, "source", None)+ store_bytes = getattr(source, "nbytes", None)++ if not store_bytes or store_bytes <= 0:+ raise RuntimeError("streaming store is empty")++ meta_params = sum(+ 1+ for parameter in streamed.parameters()+ if getattr(parameter, "is_meta", False)+ )++ if meta_params <= 0:+ raise RuntimeError(+ "streamed model has no remaining meta parameters; "+ "the streaming path was not exercised"+ )++ reference = bitexact.load_resident_reference(+ str(weights),+ "nf4",+ )++ bitexact.make_non_vacuous_lora(streamed)++ initial_lora = capture_lora_state(streamed)+ copied = bitexact.copy_lora(streamed, reference)++ if copied <= 0:+ raise RuntimeError("no LoRA tensors were copied")++ generator = torch.Generator(+ device=DEVICE+ ).manual_seed(INPUT_SEED)++ input_ids = torch.randint(+ 0,+ vocab_size,+ (args.batch, args.seq),+ generator=generator,+ device=DEVICE,+ )++ print("backward comparing one streamed/reference backward")++ streamed_loss, streamed_grads = backward_once(+ streamed,+ input_ids,+ )++ reference_loss, reference_grads = backward_once(+ reference,+ input_ids,+ )++ if not torch.isfinite(streamed_loss) or not torch.isfinite(reference_loss):+ raise MeasurementInvalidError(+ "initial streamed/reference loss is non-finite"+ )++ if not torch.equal(streamed_loss, reference_loss):+ diff = float(+ (streamed_loss - reference_loss).abs()+ )++ raise RuntimeError(+ "initial streamed/reference losses differ "+ f"(abs_diff={diff:.6e})"+ )++ exact, total, max_abs, max_rel = compare_gradients(+ streamed,+ reference,+ streamed_grads,+ reference_grads,+ )++ print(+ f"A grads: {exact}/{total} bit-exact, "+ f"worst abs {max_abs:.6e} rel {max_rel:.6e}"+ )++ curve_generator = torch.Generator(+ device=DEVICE+ ).manual_seed(INPUT_SEED)++ batches = [+ torch.randint(+ 0,+ vocab_size,+ (args.batch, args.seq),+ generator=curve_generator,+ device=DEVICE,+ )+ for _ in range(args.curve_steps)+ ]++ print(+ f"curve {args.curve_steps}-step streamed self-check twice"+ )++ streamed_curve_1 = train_curve_once(+ streamed,+ batches,+ initial_lora,+ )++ streamed_curve_2 = train_curve_once(+ streamed,+ batches,+ initial_lora,+ )++ streamed_equal, streamed_abs, streamed_rel = curve_diff(+ streamed_curve_1,+ streamed_curve_2,+ )++ print(+ f"B streamed self-identical: {streamed_equal} "+ f"max_abs={streamed_abs:.6e} max_rel={streamed_rel:.6e}"+ )++ print(+ f"curve {args.curve_steps}-step resident self-check twice"+ )++ resident_curve_1 = train_curve_once(+ reference,+ batches,+ initial_lora,+ )++ resident_curve_2 = train_curve_once(+ reference,+ batches,+ initial_lora,+ )++ resident_equal, resident_abs, resident_rel = curve_diff(+ resident_curve_1,+ resident_curve_2,+ )++ print(+ f"C resident self-identical: {resident_equal} "+ f"max_abs={resident_abs:.6e} max_rel={resident_rel:.6e}"+ )++ historical_pattern = historical_pattern_reproduced(+ exact,+ total,+ streamed_equal,+ resident_equal,+ )++ print()++ if historical_pattern:+ print(+ "RESULT: historical GRADDIFF pattern reproduced"+ )+ return historical_pattern_exit_code(True)++ print(+ "ERROR: historical GRADDIFF pattern was not reproduced"+ )+ print(+ "Expected for this conservative reconstruction gate: all initial "+ "gradients exact, "+ "streamed self-curve non-identical, "+ "resident self-curve identical"+ )+ return historical_pattern_exit_code(False)++ finally:+ if reference is not None:+ del reference++ layer_runtime.install_dequant_forward = original_install_dequant_forward+ if runtime is not None:+ runtime.close()+ if streamed is not None:+ del streamed++ gc.collect()+ torch.cuda.empty_cache()+++def main() -> int:+ args = parse_args()++ try:+ if args.self_test:+ return run_self_test()++ return run_measurement(args)+ except MeasurementInvalidError as exc:+ print(+ f"ERROR: graddiff.py invalid measurement: {exc}"+ )+ return 3+ except Exception as exc:+ print(+ f"ERROR: graddiff.py failed: "+ f"{type(exc).__name__}: {exc}"+ )+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/test_graddiff.py b/tests/test_graddiff.pynew file mode 100644index 00000000..ec26efdc--- /dev/null+++ b/tests/test_graddiff.py@@ -0,0 +1,72 @@+import importlib.util+import sys+from pathlib import Path++import pytest++MODULE_PATH = Path(__file__).resolve().parents[1] / "benchmarks" / "harness" / "graddiff.py"+HARNESS_DIR = MODULE_PATH.parent+sys.path.insert(0, str(HARNESS_DIR))++SPEC = importlib.util.spec_from_file_location("graddiff_harness", MODULE_PATH)+assert SPEC is not None and SPEC.loader is not None++module = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(module)++historical_pattern_reproduced = module.historical_pattern_reproduced+historical_pattern_exit_code = module.historical_pattern_exit_code+++ ("exact", "total", "streamed_equal", "resident_equal", "expected"),+ [+ (3, 3, False, True, True),+ (2, 3, False, True, False),+ (0, 0, False, True, False),+ (3, 3, True, True, False),+ (3, 3, False, False, False),+ ],+)+def test_historical_pattern_reproduced_truth_table(+ exact: int,+ total: int,+ streamed_equal: bool,+ resident_equal: bool,+ expected: bool,+) -> None:+ assert (+ historical_pattern_reproduced(+ exact,+ total,+ streamed_equal,+ resident_equal,+ )+ is expected+ )+++def test_historical_pattern_reproduced_returns_real_bool() -> None:+ result = historical_pattern_reproduced(3, 3, False, True)+ assert type(result) is bool+ assert result is True+++ ("historical_pattern", "expected"),+ [+ (True, 0),+ (False, 1),+ ],+)+def test_historical_pattern_exit_code(+ historical_pattern: bool,+ expected: int,+) -> None:+ assert historical_pattern_exit_code(historical_pattern) == expected++[email protected]("bad_value", [float("nan"), float("inf")])+def test_curve_diff_rejects_non_finite_values(bad_value: float) -> None:+ with pytest.raises(RuntimeError, match="non-finite"):+ module.curve_diff([bad_value, 1.0], [1.0, 1.0])diff --git a/tests/test_graddiff_acceptance.py b/tests/test_graddiff_acceptance.pynew file mode 100644index 00000000..6f57081c--- /dev/null+++ b/tests/test_graddiff_acceptance.py@@ -0,0 +1,504 @@+from __future__ import annotations++import argparse+import importlib.util+import sys+from pathlib import Path+from types import SimpleNamespace++import pytest+import torch++from tests.conftest import strip_ansi++MODULE_PATH = (+ Path(__file__).resolve().parents[1]+ / "benchmarks"+ / "harness"+ / "graddiff.py"+)+HARNESS_DIR = MODULE_PATH.parent+sys.path.insert(0, str(HARNESS_DIR))++SPEC = importlib.util.spec_from_file_location(+ "graddiff_acceptance",+ MODULE_PATH,+)+assert SPEC is not None and SPEC.loader is not None++module = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(module)+++def _plain(text: str) -> str:+ """ANSI-stripped, whitespace-collapsed CLI output for assertions."""+ return " ".join(strip_ansi(text).split())+++class FakeRuntime:+ pinned = True+ source = SimpleNamespace(nbytes=1)++ def close(self) -> None:+ pass+++class FakeModel(torch.nn.Module):+ def __init__(self) -> None:+ super().__init__()+ self.lora_A = torch.nn.Parameter(torch.ones(1))+ self.meta_parameter = SimpleNamespace(is_meta=True)++ def parameters(self, recurse: bool = True):+ yield self.lora_A+ yield self.meta_parameter++ def forward(self, input_ids, labels):+ loss = self.lora_A.sum() * 0.0 + 1.0+ return SimpleNamespace(loss=loss)+++def make_args(tmp_path: Path) -> argparse.Namespace:+ return argparse.Namespace(+ weights=str(tmp_path / "weights"),+ shards=str(tmp_path / "shards"),+ seq=2,+ batch=1,+ buffers=2,+ curve_steps=2,+ self_test=False,+ )+++def install_measurement_stubs(+ monkeypatch: pytest.MonkeyPatch,+ *,+ streamed_curves: tuple[list[float], list[float]],+ resident_curves: tuple[list[float], list[float]],+ exact: int = 1,+ total: int = 1,+ streamed_loss: float = 1.0,+ reference_loss: float = 1.0,+) -> None:+ monkeypatch.setattr(module, "cuda_available", lambda: True)+ monkeypatch.setattr(module, "DEVICE", "cpu")++ import soup_cli.utils.layer_shard as layer_shard+ import soup_cli.utils.layer_stream_runtime as layer_runtime++ monkeypatch.setattr(+ layer_runtime,+ "build_meta_skeleton",+ lambda *args, **kwargs: SimpleNamespace(+ config=SimpleNamespace(vocab_size=16),+ ),+ )+ monkeypatch.setattr(+ module.bitexact,+ "model_arch_name",+ lambda model: "fake",+ )+ monkeypatch.setattr(+ layer_runtime,+ "quantised_layer_suffixes",+ lambda model: (),+ )+ monkeypatch.setattr(+ layer_shard,+ "shard_checkpoint",+ lambda *args, **kwargs: {},+ )++ streamed = FakeModel()+ reference = FakeModel()++ monkeypatch.setattr(+ layer_runtime,+ "build_streamed_model",+ lambda *args, **kwargs: (streamed, FakeRuntime()),+ )+ monkeypatch.setattr(+ module.bitexact,+ "load_resident_reference",+ lambda *args, **kwargs: reference,+ )+ monkeypatch.setattr(+ module.bitexact,+ "make_non_vacuous_lora",+ lambda model: None,+ )+ monkeypatch.setattr(+ module.bitexact,+ "copy_lora",+ lambda *args, **kwargs: 1,+ )+ monkeypatch.setattr(+ module.bitexact,+ "lora_config",+ lambda: SimpleNamespace(),+ )+ monkeypatch.setattr(+ module,+ "capture_lora_state",+ lambda model: {"lora_A": torch.ones(1)},+ )++ backward_calls = iter(+ [+ (+ torch.tensor(streamed_loss),+ {"lora_A": torch.ones(1)},+ ),+ (+ torch.tensor(reference_loss),+ {"lora_A": torch.ones(1)},+ ),+ ]+ )+ monkeypatch.setattr(+ module,+ "backward_once",+ lambda *args, **kwargs: next(backward_calls),+ )++ curve_calls = iter(+ [+ streamed_curves[0],+ streamed_curves[1],+ resident_curves[0],+ resident_curves[1],+ ]+ )+ monkeypatch.setattr(+ module,+ "train_curve_once",+ lambda *args, **kwargs: next(curve_calls),+ )++ monkeypatch.setattr(+ torch.cuda,+ "get_device_name",+ lambda index: "CPU-stub",+ )+ monkeypatch.setattr(+ torch.cuda,+ "empty_cache",+ lambda: None,+ )++ monkeypatch.setattr(+ module,+ "install_historical_control",+ lambda runtime: None,+ )+ monkeypatch.setattr(+ module,+ "runtime_versions",+ lambda: ("stub-bnb", "stub-peft", "stub-transformers"),+ )++ generator_type = torch.Generator+ monkeypatch.setattr(+ torch,+ "Generator",+ lambda device=None: generator_type(device="cpu"),+ )+++def test_run_measurement_reaches_abc_and_returns_historical_success(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ capsys: pytest.CaptureFixture[str],+) -> None:+ weights = tmp_path / "weights"+ weights.mkdir()++ install_measurement_stubs(+ monkeypatch,+ streamed_curves=([1.0, 2.0], [1.0, 2.1]),+ resident_curves=([1.0, 2.0], [1.0, 2.0]),+ )++ args = make_args(tmp_path)+ args.weights = str(weights)++ result = module.run_measurement(args)++ output = capsys.readouterr().out+ plain = _plain(output)++ assert "A grads: 1/1 bit-exact" in plain+ assert "B streamed self-identical: False" in plain+ assert "C resident self-identical: True" in plain+ assert "RESULT: historical GRADDIFF pattern reproduced" in plain+ assert result == 0+++def test_run_measurement_rejects_non_historical_verdict(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ capsys: pytest.CaptureFixture[str],+) -> None:+ weights = tmp_path / "weights"+ weights.mkdir()++ install_measurement_stubs(+ monkeypatch,+ streamed_curves=([1.0, 2.0], [1.0, 2.0]),+ resident_curves=([1.0, 2.0], [1.0, 2.0]),+ )++ args = make_args(tmp_path)+ args.weights = str(weights)++ result = module.run_measurement(args)++ output = capsys.readouterr().out+ plain = _plain(output)++ assert "A grads: 1/1 bit-exact" in plain+ assert "B streamed self-identical: True" in plain+ assert "C resident self-identical: True" in plain+ assert "historical GRADDIFF pattern was not reproduced" in plain+ assert result == 1+++def test_run_measurement_rejects_non_matching_gradients(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ capsys: pytest.CaptureFixture[str],+) -> None:+ weights = tmp_path / "weights"+ weights.mkdir()++ install_measurement_stubs(+ monkeypatch,+ streamed_curves=([1.0, 2.0], [1.0, 2.1]),+ resident_curves=([1.0, 2.0], [1.0, 2.0]),+ exact=0,+ total=1,+ )+ backward_calls = iter(+ [+ (torch.tensor(1.0), {"lora_A": torch.ones(1)}),+ (torch.tensor(1.0), {"lora_A": torch.full((1,), 2.0)}),+ ]+ )+ monkeypatch.setattr(+ module,+ "backward_once",+ lambda *args, **kwargs: next(backward_calls),+ )++ args = make_args(tmp_path)+ args.weights = str(weights)++ result = module.run_measurement(args)++ output = capsys.readouterr().out+ plain = _plain(output)++ assert "A grads: 0/1 bit-exact" in plain+ assert "B streamed self-identical: False" in plain+ assert "C resident self-identical: True" in plain+ assert result == 1+++def test_run_measurement_rejects_mismatched_initial_losses(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ weights = tmp_path / "weights"+ weights.mkdir()++ install_measurement_stubs(+ monkeypatch,+ streamed_curves=([1.0, 2.0], [1.0, 2.1]),+ resident_curves=([1.0, 2.0], [1.0, 2.0]),+ streamed_loss=1.0,+ reference_loss=2.0,+ )++ args = make_args(tmp_path)+ args.weights = str(weights)++ with pytest.raises(RuntimeError, match="initial streamed/reference losses differ"):+ module.run_measurement(args)+++def test_compare_gradients_uses_streamed_values_and_requires_shared_parameters():+ streamed = FakeModel()+ reference = FakeModel()++ exact, total, max_abs, max_rel = module.compare_gradients(+ streamed,+ reference,+ {"lora_A": torch.tensor([1.0])},+ {"lora_A": torch.tensor([2.0])},+ )++ assert (exact, total) == (0, 1)+ assert max_abs == pytest.approx(1.0)+ assert max_rel == pytest.approx(0.5)++ class NamedParameter(torch.nn.Module):+ def __init__(self, name):+ super().__init__()+ self.register_parameter(name, torch.nn.Parameter(torch.ones(1)))++ with pytest.raises(ValueError, match="empty"):+ module.compare_gradients(+ NamedParameter("lora_left"),+ NamedParameter("lora_right"),+ {},+ {},+ )+++def test_compare_gradients_rejects_non_finite_streamed_values():+ with pytest.raises(module.MeasurementInvalidError, match="streamed gradient"):+ module.compare_gradients(+ FakeModel(),+ FakeModel(),+ {"lora_A": torch.tensor([float("nan")])},+ {"lora_A": torch.tensor([1.0])},+ )+++def test_compare_gradients_rejects_different_gradient_sets():+ with pytest.raises(RuntimeError, match="gradient sets differ"):+ module.compare_gradients(+ FakeModel(),+ FakeModel(),+ {"lora_A": torch.ones(1)},+ {"other": torch.ones(1)},+ )+++def test_train_curve_once_restores_initial_lora_state():+ class CurveModel(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.lora_A = torch.nn.Parameter(torch.ones(1))++ def forward(self, input_ids, labels):+ return SimpleNamespace(loss=(self.lora_A * input_ids).sum())++ model = CurveModel()+ batches = [torch.ones(1), torch.ones(1)]+ initial = {"lora_A": torch.ones(1)}++ first = module.train_curve_once(model, batches, initial)+ second = module.train_curve_once(model, batches, initial)++ assert second == pytest.approx(first)+++def test_run_measurement_rejects_unpinned_stream(monkeypatch, tmp_path):+ install_measurement_stubs(+ monkeypatch,+ streamed_curves=([1.0, 2.0], [1.0, 2.1]),+ resident_curves=([1.0, 2.0], [1.0, 2.0]),+ )+ args = make_args(tmp_path)+ (tmp_path / "weights").mkdir()+ import soup_cli.utils.layer_stream_runtime as layer_runtime+ monkeypatch.setattr(+ layer_runtime,+ "build_streamed_model",+ lambda *args, **kwargs: (+ FakeModel(),+ SimpleNamespace(+ pinned=False,+ source=SimpleNamespace(nbytes=1),+ close=lambda: None,+ ),+ ),+ )++ with pytest.raises(RuntimeError, match="pinned"):+ module.run_measurement(args)+++def test_run_measurement_rejects_missing_meta_parameters(monkeypatch, tmp_path):+ install_measurement_stubs(+ monkeypatch,+ streamed_curves=([1.0, 2.0], [1.0, 2.1]),+ resident_curves=([1.0, 2.0], [1.0, 2.0]),+ )+ args = make_args(tmp_path)+ (tmp_path / "weights").mkdir()+ model = FakeModel()+ model.meta_parameter = SimpleNamespace(is_meta=False)+ import soup_cli.utils.layer_stream_runtime as layer_runtime+ monkeypatch.setattr(+ layer_runtime,+ "build_streamed_model",+ lambda *args, **kwargs: (model, FakeRuntime()),+ )++ with pytest.raises(RuntimeError, match="meta parameters"):+ module.run_measurement(args)+++def test_main_executes_real_measurement_path(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ weights = tmp_path / "weights"+ weights.mkdir()+ install_measurement_stubs(+ monkeypatch,+ streamed_curves=([1.0, 2.0], [1.0, 2.1]),+ resident_curves=([1.0, 2.0], [1.0, 2.0]),+ )+ args = make_args(tmp_path)+ args.weights = str(weights)+ monkeypatch.setattr(module, "parse_args", lambda: args)++ assert module.main() == 0+++def test_main_returns_exit_3_for_invalid_measurements(monkeypatch):+ args = argparse.Namespace(self_test=False)+ monkeypatch.setattr(module, "parse_args", lambda: args)+ monkeypatch.setattr(+ module,+ "run_measurement",+ lambda _args: (_ for _ in ()).throw(+ module.MeasurementInvalidError("non-finite measurement")+ ),+ )++ assert module.main() == 3+++def test_run_measurement_restores_historical_runtime_control(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ weights = tmp_path / "weights"+ weights.mkdir()+ install_measurement_stubs(+ monkeypatch,+ streamed_curves=([1.0, 2.0], [1.0, 2.1]),+ resident_curves=([1.0, 2.0], [1.0, 2.0]),+ )++ import soup_cli.utils.layer_stream_runtime as layer_runtime++ original = object()+ installed: list[object] = []+ monkeypatch.setattr(layer_runtime, "install_dequant_forward", original)++ def install(runtime: object) -> None:+ installed.append(runtime)+ runtime.install_dequant_forward = object()++ monkeypatch.setattr(module, "install_historical_control", install)+ args = make_args(tmp_path)+ args.weights = str(weights)++ assert module.run_measurement(args) == 0+ assert installed == [layer_runtime]+ assert layer_runtime.install_dequant_forward is originaldiff --git a/tests/test_issue379_graddiff_guards.py b/tests/test_issue379_graddiff_guards.pynew file mode 100644index 00000000..c16059ab--- /dev/null+++ b/tests/test_issue379_graddiff_guards.py@@ -0,0 +1,101 @@+"""Pin the GRADDIFF pieces the acceptance stubs replace (#379)."""++from __future__ import annotations++from types import SimpleNamespace++import pytest+import torch++from tests.test_graddiff_acceptance import (+ FakeModel,+ FakeRuntime,+ install_measurement_stubs,+ make_args,+)+from tests.test_graddiff_acceptance import module as graddiff+++class Tiny(torch.nn.Module):+ def __init__(self, name: str = "lora_A") -> None:+ super().__init__()+ self.register_parameter(name, torch.nn.Parameter(torch.ones(2)))++ def forward(self, input_ids, labels):+ weight = next(iter(self.parameters()))+ return SimpleNamespace(loss=(weight * input_ids.float().mean()).sum())+++def test_self_test_runs_the_empty_intersection_negative_in_ci() -> None:+ assert graddiff.run_self_test() == 0+++def test_compare_gradients_counts_a_mismatch() -> None:+ same = {"lora_A": torch.ones(2)}+ other = {"lora_A": torch.tensor([1.0, 2.0])}+ assert graddiff.compare_gradients(Tiny(), Tiny(), same, dict(same))[:2] == (1, 1)+ assert graddiff.compare_gradients(Tiny(), Tiny(), same, other)[:2] == (0, 1)++[email protected]("bad", [float("inf"), float("nan")])[email protected]("side", ["streamed", "reference"])+def test_compare_gradients_refuses_non_finite_on_either_side(+ bad: float, side: str+) -> None:+ good = {"lora_A": torch.ones(2)}+ broken = {"lora_A": torch.tensor([bad, 1.0])}+ streamed, reference = (broken, good) if side == "streamed" else (good, broken)+ with pytest.raises(graddiff.MeasurementInvalidError, match="non-finite"):+ graddiff.compare_gradients(Tiny(), Tiny(), streamed, reference)+++def test_compare_gradients_refuses_different_gradient_sets() -> None:+ with pytest.raises(RuntimeError, match="sets differ"):+ graddiff.compare_gradients(+ Tiny(), Tiny(), {"lora_A": torch.ones(2)}, {"lora_B": torch.ones(2)}+ )+++def test_train_curve_once_restarts_from_the_same_adapter() -> None:+ model = Tiny()+ initial = graddiff.capture_lora_state(model)+ batches = [torch.tensor([[1, 2]]), torch.tensor([[3, 4]]), torch.tensor([[5, 6]])]+ first = graddiff.train_curve_once(model, batches, initial)+ second = graddiff.train_curve_once(model, batches, initial)+ assert first == second+++class _NoMetaModel(FakeModel):+ def parameters(self, recurse: bool = True):+ yield self.lora_A+++ ("runtime_pinned", "model_cls", "message"),+ [+ (False, FakeModel, "pinned=False"),+ (True, _NoMetaModel, "no remaining meta parameters"),+ ],+)+def test_run_measurement_refuses_an_unexercised_streaming_path(+ monkeypatch, tmp_path, runtime_pinned, model_cls, message+) -> None:+ monkeypatch.chdir(tmp_path)+ weights = tmp_path / "weights"+ weights.mkdir()+ install_measurement_stubs(+ monkeypatch,+ streamed_curves=([1.0, 2.0], [1.0, 2.1]),+ resident_curves=([1.0, 2.0], [1.0, 2.0]),+ )+ import soup_cli.utils.layer_stream_runtime as layer_runtime++ runtime = FakeRuntime()+ runtime.pinned = runtime_pinned+ monkeypatch.setattr(+ layer_runtime, "build_streamed_model", lambda *a, **k: (model_cls(), runtime)+ )+ args = make_args(tmp_path)+ args.weights = str(weights)+ with pytest.raises(RuntimeError, match=message):+ graddiff.run_measurement(args)