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 NF4 mechanism harness (#1119)
Samarth Mukhijae0cab83e6947
diff --git a/benchmarks/README.md b/benchmarks/README.mdindex 95594391..9068743e 100644--- a/benchmarks/README.md+++ b/benchmarks/README.md@@ -63,6 +63,7 @@ only in a scratchpad on a machine that is gone, which is| [`issue331_qlora_scope.py`](harness/issue331_qlora_scope.py) | #331 | Does the wrong-gradient defect reach **ordinary QLoRA**? Three arms in one process, with a positive control. Answer: no — 0.0 against a control that diverges by 3.77e-01 | ~15 s, 4 GB card, no downloads || [`bnb_repro.py`](harness/bnb_repro.py) | Upstream bitsandbytes #2034 / NF4 defect | Minimal standalone reproducer for the NF4 stale-gradient mechanism: recycled buffers expose `MatMul4Bit`'s `ctx` lifetime issue; private buffers are the reference and bf16 is the control | CUDA GPU required; no downloads; historical environment: torch 2.13.0+cu130, bitsandbytes 0.50.0; ~1 min || [`mechanism_cost.py`](harness/mechanism_cost.py) | STEP 9 / #331 | Measure the recorded NF4 de-aliasing cost on a local Qwen2.5-32B-Instruct checkpoint: `control`, `clone_fwd_quant`, and `clone`, with correctness asserted in-process before timing; `--self-test` exercises the negative empty-intersection acceptance case | CUDA GPU + local checkpoint required; **about 20 GiB GPU memory** for the clone arms; checkpoint must contain real `.safetensors` files (symlinked HF-cache snapshots are refused); no downloads; historical protocol: seq 256, batch 1, 5 repeats, 4 warm-up steps, 15 timed steps, 2 stream buffers |+| [`mechanism.py`](harness/mechanism.py) | STEP 9 / #331 | Is the NF4 streamed-gradient defect caused by pooled-buffer aliasing? Five arms: `control`, `sync`, `clone`, `clone_quantstate`, and `clone_packed`; every arm is compared with an independent resident NF4 reference while the single-sided clones test which captured state matters | CUDA GPU required; native runs are GPU-memory intensive; no downloads; historical environment: torch 2.13.0+cu130, bitsandbytes 0.50.0, H100 sm90 || [`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. |diff --git a/benchmarks/harness/mechanism.py b/benchmarks/harness/mechanism.pynew file mode 100644index 00000000..44bdcb18--- /dev/null+++ b/benchmarks/harness/mechanism.py@@ -0,0 +1,760 @@+#!/usr/bin/env python3+"""Reproduce the NF4 pooled-buffer aliasing mechanism.++This is the standalone mechanism harness described by issue #379 and the+#331 measurement record.++Protocol+--------+A synthetic Llama-shaped NF4 workload is built with:++- 32 layers+- hidden size 5120+- intermediate size 27648+- sequence length 128+- two recycled GPU buffer slots++Each decoder layer exercises the seven large linear shapes present in the+32B-sized configuration. Two LoRA-style trainable projections provide four+gradient tensors per layer.++The five arms are:++- control: pooled packed weights + pooled quantization state+- sync: control + torch.cuda.synchronize()+- clone: private copies of packed weights AND quantization state+- clone_quantstate: private quantization state, pooled packed weights+- clone_packed: private packed weights, pooled quantization state++An independent resident NF4 run is the comparison baseline. The ``clone`` arm+must match it, while the other four arms establish the pooled-buffer mechanism.++Expected result+---------------+The mechanism is an aliasing problem, not a missing CUDA synchronization:++- control -> mismatch+- sync -> mismatch+- clone -> exact+- clone_quantstate -> mismatch+- clone_packed -> mismatch++The harness also has a mutation mode. ``--bypass-pool`` disables recycled+buffers for the control arm. The mechanism must then disappear; because that+means the harness was mutated away from the mechanism it claims to reproduce,+the command exits non-zero.++No model download is required.++Requirements+------------+- CUDA-capable GPU+- PyTorch+- bitsandbytes+"""++from __future__ import annotations++import argparse+import sys+from dataclasses import dataclass++import bitsandbytes as bnb+import torch+import torch.nn.functional as functional+from bitsandbytes.functional import QuantState+from torch.utils.checkpoint import checkpoint++DEVICE = "cuda"+DTYPE = torch.bfloat16++N_LAYERS = 32+HIDDEN = 5120+KV_DIM = 1024+INTERMEDIATE = 27648+TOKENS = 128+POOL_SLOTS = 2+LORA_RANK = 16+CORRECTNESS_REPEATS = 3++SEED_WEIGHTS = 11+SEED_INPUT = 23+SEED_LORA = 29++PROJECTIONS = (+ ("q", HIDDEN, HIDDEN),+ ("k", KV_DIM, HIDDEN),+ ("v", KV_DIM, HIDDEN),+ ("o", HIDDEN, HIDDEN),+ ("gate", INTERMEDIATE, HIDDEN),+ ("up", INTERMEDIATE, HIDDEN),+ ("down", HIDDEN, HIDDEN),+)+++@dataclass+class QuantBundle:+ """Packed NF4 weight plus its quantization state."""++ packed: torch.Tensor+ state: QuantState+++@dataclass+class ArmState:+ """Persistent model parameters and pooled buffers for one arm."""++ parameters: list[dict[str, torch.Tensor]]+ pools: dict[str, "BundlePool"]+++class BundlePool:+ """Round-robin pooled storage for packed weights and quantization state."""++ def __init__(self, n_slots: int, source: QuantBundle):+ self.packed = [+ torch.empty_like(source.packed)+ for _ in range(n_slots)+ ]++ self.absmax = [+ torch.empty_like(source.state.absmax)+ for _ in range(n_slots)+ ]++ self.offset = (+ [+ torch.empty_like(source.state.offset)+ for _ in range(n_slots)+ ]+ if source.state.nested+ else None+ )++ self.state2_absmax = (+ [+ torch.empty_like(source.state.state2.absmax)+ for _ in range(n_slots)+ ]+ if source.state.nested+ else None+ )++ self.cursor = 0+ self.template = source.state++ def acquire(self, source: QuantBundle) -> QuantBundle:+ slot = self.cursor % len(self.packed)+ self.cursor += 1++ packed = self.packed[slot]+ packed.copy_(source.packed)++ absmax = self.absmax[slot]+ absmax.copy_(source.state.absmax)++ offset = None+ state2 = None++ if source.state.nested:+ assert self.offset is not None+ assert self.state2_absmax is not None++ offset = self.offset[slot]+ offset.copy_(source.state.offset)++ nested_absmax = self.state2_absmax[slot]+ nested_absmax.copy_(source.state.state2.absmax)++ state2 = QuantState(+ absmax=nested_absmax,+ shape=source.state.state2.shape,+ code=source.state.state2.code,+ blocksize=source.state.state2.blocksize,+ quant_type=source.state.state2.quant_type,+ dtype=source.state.state2.dtype,+ )++ state = QuantState(+ absmax=absmax,+ shape=source.state.shape,+ code=source.state.code,+ blocksize=source.state.blocksize,+ quant_type=source.state.quant_type,+ dtype=source.state.dtype,+ offset=offset,+ state2=state2,+ )++ return QuantBundle(packed=packed, state=state)+++def clone_quant_state(state: QuantState) -> QuantState:+ """Deep-copy tensor components of a QuantState."""++ state2 = None++ if state.nested:+ state2 = QuantState(+ absmax=state.state2.absmax.clone(),+ shape=state.state2.shape,+ code=state.state2.code.clone(),+ blocksize=state.state2.blocksize,+ quant_type=state.state2.quant_type,+ dtype=state.state2.dtype,+ )++ offset = state.offset.clone() if state.offset is not None else None++ return QuantState(+ absmax=state.absmax.clone(),+ shape=state.shape,+ code=state.code.clone(),+ blocksize=state.blocksize,+ quant_type=state.quant_type,+ dtype=state.dtype,+ offset=offset,+ state2=state2,+ )+++def load_sources() -> list[dict[str, QuantBundle]]:+ """Build the complete synthetic 32B-shaped NF4 source set."""++ generator = torch.Generator(device=DEVICE).manual_seed(SEED_WEIGHTS)++ sources: list[dict[str, QuantBundle]] = []++ for _ in range(N_LAYERS):+ layer: dict[str, QuantBundle] = {}++ for name, out_features, in_features in PROJECTIONS:+ weight = torch.randn(+ (out_features, in_features),+ generator=generator,+ device=DEVICE,+ dtype=DTYPE,+ ) / 32++ packed, state = bnb.functional.quantize_4bit(+ weight,+ blocksize=64,+ quant_type="nf4",+ compress_statistics=True,+ )++ layer[name] = QuantBundle(+ packed=packed,+ state=state,+ )++ del weight++ sources.append(layer)++ return sources+++def make_lora_parameters() -> list[dict[str, torch.Tensor]]:+ """Create identical LoRA-style tensors for every arm."""++ generator = torch.Generator(device=DEVICE).manual_seed(SEED_LORA)++ parameters: list[dict[str, torch.Tensor]] = []++ for _ in range(N_LAYERS):+ layer = {}++ for name, out_features, _in_features in (+ ("q", HIDDEN, HIDDEN),+ ("v", KV_DIM, HIDDEN),+ ):+ a = (+ torch.randn(+ (LORA_RANK, HIDDEN),+ generator=generator,+ device=DEVICE,+ dtype=DTYPE,+ )+ * 0.02+ )++ b = (+ torch.randn(+ (out_features, LORA_RANK),+ generator=generator,+ device=DEVICE,+ dtype=DTYPE,+ )+ * 0.02+ )++ layer[f"{name}.A"] = a.requires_grad_(True)+ layer[f"{name}.B"] = b.requires_grad_(True)++ parameters.append(layer)++ return parameters+++def project(+ x: torch.Tensor,+ bundle: QuantBundle,+) -> torch.Tensor:+ """Run one NF4 linear using the packed weight and quantization state."""++ return bnb.matmul_4bit(+ x,+ bundle.packed,+ quant_state=bundle.state,+ )+++def acquire_bundle(+ pools: dict[str, BundlePool],+ sources: dict[str, QuantBundle],+ name: str,+ arm: str,+) -> QuantBundle:+ """Acquire one layer weight according to the selected mechanism arm."""++ pooled = pools[name].acquire(sources[name])++ if arm == "control" or arm == "sync":+ return pooled++ if arm == "clone":+ return QuantBundle(+ packed=pooled.packed.clone(),+ state=clone_quant_state(pooled.state),+ )++ if arm == "clone_quantstate":+ return QuantBundle(+ packed=pooled.packed,+ state=clone_quant_state(pooled.state),+ )++ if arm == "clone_packed":+ return QuantBundle(+ packed=pooled.packed.clone(),+ state=pooled.state,+ )++ raise ValueError(f"unsupported arm: {arm!r}")+++def make_arm_state(+ sources: list[dict[str, QuantBundle]],+ initial_parameters: list[dict[str, torch.Tensor]],+) -> ArmState:+ """Create one persistent parameter/pool state for a correctness arm."""++ parameters = [+ {+ name: tensor.detach().clone().requires_grad_(True)+ for name, tensor in layer.items()+ }+ for layer in initial_parameters+ ]++ pools = {+ name: BundlePool(+ POOL_SLOTS,+ sources[0][name],+ )+ for name, _, _ in PROJECTIONS+ }++ return ArmState(parameters=parameters, pools=pools)+++def run_once(+ sources: list[dict[str, QuantBundle]],+ state: ArmState,+ arm: str,+ *,+ bypass_pool: bool,+) -> dict[str, torch.Tensor]:+ """Run one backward pass using persistent arm state."""++ torch.manual_seed(SEED_INPUT)++ parameters = state.parameters+ pools = state.pools++ for layer in parameters:+ for parameter in layer.values():+ parameter.grad = None++ generator = torch.Generator(device=DEVICE).manual_seed(SEED_INPUT)++ x = torch.randn(+ (TOKENS, HIDDEN),+ generator=generator,+ device=DEVICE,+ dtype=DTYPE,+ requires_grad=True,+ )++ for layer_index in range(N_LAYERS):++ q_a = parameters[layer_index]["q.A"]+ q_b = parameters[layer_index]["q.B"]+ v_a = parameters[layer_index]["v.A"]+ v_b = parameters[layer_index]["v.B"]++ def body(hidden, q_a, q_b, v_a, v_b):+ source = sources[layer_index]++ bundles = {}++ for name, _out_features, _in_features in PROJECTIONS:+ if bypass_pool:+ bundles[name] = source[name]+ else:+ bundles[name] = acquire_bundle(+ pools,+ source,+ name,+ arm,+ )++ if arm == "sync":+ torch.cuda.synchronize()++ q = project(hidden, bundles["q"])+ k = project(hidden, bundles["k"])+ v = project(hidden, bundles["v"])+ o = project(hidden, bundles["o"])+ gate = project(hidden, bundles["gate"])+ up = project(hidden, bundles["up"])+ down = project(hidden, bundles["down"])++ q_lora = functional.linear(+ functional.linear(hidden, q_a),+ q_b,+ )++ v_lora = functional.linear(+ functional.linear(hidden, v_a),+ v_b,+ )++ output = (+ q+ + o+ + down+ + 0.1 * q_lora+ + 0.1 * functional.pad(+ v_lora,+ (0, HIDDEN - KV_DIM),+ )+ + 0.0001 * k.mean(dim=-1, keepdim=True)+ + 0.0001 * v.mean(dim=-1, keepdim=True)+ + 0.000001 * gate.mean(dim=-1, keepdim=True)+ + 0.000001 * up.mean(dim=-1, keepdim=True)+ )++ return output++ x = checkpoint(+ body,+ x,+ q_a,+ q_b,+ v_a,+ v_b,+ use_reentrant=False,+ )++ loss = x.float().pow(2).mean()+ loss.backward()++ gradients = {}++ for layer_index, layer in enumerate(parameters):+ for name, parameter in layer.items():+ gradient = parameter.grad++ if gradient is None:+ raise RuntimeError(+ f"missing gradient for layer {layer_index} {name}"+ )++ gradients[f"{layer_index}.{name}"] = (+ gradient.detach().float().clone()+ )++ return gradients+++class NonFiniteGradientsError(RuntimeError):+ """A gradient set holds NaN/Inf, so no exactness verdict is possible."""+++def _assert_finite_gradients(+ gradients: dict[str, torch.Tensor],+ label: str,+) -> None:+ """Reject NaN/Inf gradients before exactness checks."""++ for name, gradient in gradients.items():+ if not torch.isfinite(gradient).all():+ raise NonFiniteGradientsError(+ f"{label} contains non-finite gradient values: {name}"+ )+++def max_gradient_diff(+ left: dict[str, torch.Tensor],+ right: dict[str, torch.Tensor],+) -> float:+ """Largest absolute gradient difference."""++ if set(left) != set(right):+ raise RuntimeError("gradient key sets differ")++ _assert_finite_gradients(left, "left gradients")+ _assert_finite_gradients(right, "right gradients")++ return max(+ (left[name] - right[name]).abs().max().item()+ for name in left+ )+++def exact_gradient_count(+ reference: dict[str, torch.Tensor],+ candidate: dict[str, torch.Tensor],+) -> tuple[int, int]:+ """Return exact gradient-tensor count and total."""++ if set(reference) != set(candidate):+ raise RuntimeError("gradient key sets differ")++ _assert_finite_gradients(reference, "reference gradients")+ _assert_finite_gradients(candidate, "candidate gradients")++ exact = sum(+ torch.equal(reference[name], candidate[name])+ for name in reference+ )++ return exact, len(reference)+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(+ description=(+ "Reproduce the NF4 pooled-buffer aliasing mechanism "+ "from Soup's #331/#379 measurements."+ ),+ epilog=(+ "exit codes: 0 mechanism reproduced; 1 not reproduced, or with "+ "--bypass-pool the mismatch disappeared (negative control caught); "+ "2 --bypass-pool did not remove the mismatch; 3 non-finite "+ "gradients, no verdict."+ ),+ )++ parser.add_argument(+ "--bypass-pool",+ action="store_true",+ help=(+ "mutation/negative control: bypass recycled buffers for the "+ "control path. The expected control mismatch must disappear; "+ "the harness then exits non-zero."+ ),+ )++ return parser.parse_args()+++def main() -> int:+ args = parse_args()++ try:+ return _run(args)+ except NonFiniteGradientsError as exc:+ print(f"ERROR: {exc}; no verdict")+ return 3+++def _run(args: argparse.Namespace) -> int:++ if not torch.cuda.is_available():+ print("SKIP: CUDA is required for mechanism.py")+ return 0++ print(f"torch {torch.__version__}")+ print(f"bitsandbytes {bnb.__version__}")+ print(f"gpu {torch.cuda.get_device_name(0)}")+ print(+ f"shape {N_LAYERS} layers, hidden={HIDDEN}, "+ f"intermediate={INTERMEDIATE}, dtype={DTYPE}"+ )+ print(+ f"pool {POOL_SLOTS} recycled slots, "+ f"sequence={TOKENS}"+ )+ print("quant NF4")+ print()++ if args.bypass_pool:+ print("mode NEGATIVE CONTROL: pooled reuse bypassed")+ print()++ sources = load_sources()+ initial_parameters = make_lora_parameters()++ print("built synthetic NF4 source set")++ arm_names = (+ "control",+ "sync",+ "clone_quantstate",+ "clone_packed",+ )+ all_arms = (+ "control",+ "sync",+ "clone",+ "clone_quantstate",+ "clone_packed",+ )+ arm_states = {+ name: make_arm_state(sources, initial_parameters)+ for name in all_arms+ }++ exact_results = {name: [] for name in all_arms}+ diff_results = {name: [] for name in all_arms}++ for repetition in range(CORRECTNESS_REPEATS):+ print(+ f"correctness {repetition + 1}/{CORRECTNESS_REPEATS}"+ )++ print("running resident")+ resident = run_once(+ sources,+ arm_states["clone"],+ "clone",+ bypass_pool=True,+ )++ print("running clone")+ clone = run_once(+ sources,+ arm_states["clone"],+ "clone",+ bypass_pool=False,+ )++ clone_exact, clone_total = exact_gradient_count(+ resident,+ clone,+ )+ clone_diff = max_gradient_diff(resident, clone)+ exact_results["clone"].append(+ f"{clone_exact}/{clone_total}"+ )+ diff_results["clone"].append(clone_diff)++ for arm in arm_names:+ print(f"running {arm}")+ candidate = run_once(+ sources,+ arm_states[arm],+ arm,+ bypass_pool=args.bypass_pool if arm == "control" else False,+ )++ exact, total = exact_gradient_count(resident, candidate)+ diff = max_gradient_diff(resident, candidate)++ exact_results[arm].append(f"{exact}/{total}")+ diff_results[arm].append(diff)++ del candidate++ del clone++ print()+ print(f"{'arm':>18} {'exact':>28} {'max_abs_diff':>45}")++ for name in all_arms:+ print(+ f"{name:>18} "+ f"{', '.join(exact_results[name]):>28} "+ f"{', '.join(f'{diff:.6e}' for diff in diff_results[name]):>45}"+ )++ print()++ if args.bypass_pool:+ if any(diff != 0.0 for diff in diff_results["control"]):+ print(+ "ERROR: bypassing the pool did not remove the "+ "control mismatch."+ )+ print("RESULT: negative control was NOT caught.")+ return 2++ print(+ "NEGATIVE CONTROL: bypassing pool reuse removed "+ "the control mismatch."+ )+ print("RESULT: mutation detected; exiting non-zero.")+ return 1++ if all(diff == 0.0 for diff in diff_results["control"]):+ print(+ "ERROR: control did not reproduce the NF4 "+ "pooled-buffer mismatch."+ )+ return 1++ if diff_results["control"][-1] == 0.0:+ print(+ "ERROR: control ended exact; expected the historical "+ "stale-buffer mismatch after repeated backwards."+ )+ return 1++ if any(diff == 0.0 for diff in diff_results["sync"]):+ print(+ "ERROR: synchronize() removed the mismatch; "+ "the aliasing mechanism was not reproduced."+ )+ return 1++ if any(diff == 0.0 for diff in diff_results["clone_quantstate"]):+ print(+ "ERROR: cloning quantization state alone removed "+ "the mismatch."+ )+ return 1++ if any(diff == 0.0 for diff in diff_results["clone_packed"]):+ print(+ "ERROR: cloning packed weights alone removed "+ "the mismatch."+ )+ return 1++ if any(diff != 0.0 for diff in diff_results["clone"]):+ print("ERROR: full clone does not match the resident reference.")+ return 1++ print(+ "RESULT: mechanism reproduced — control and sync mismatch, "+ "single-sided clones mismatch, full clone matches."+ )++ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/benchmarks/harness/mechanism_cost.py b/benchmarks/harness/mechanism_cost.pyindex daaa0eb4..83020e62 100644--- a/benchmarks/harness/mechanism_cost.py+++ b/benchmarks/harness/mechanism_cost.py@@ -48,6 +48,9 @@ No source files under ``src/`` are modified. The harness temporarilymonkeypatches the runtime in-process to recreate the historical mechanism.A machine without CUDA exits 0 with an explicit skip.++Exit codes: 0 completed, 1 historical mechanism result not reproduced or+runtime failure, 2 invalid CLI/input, 3 invalid or non-finite measurement."""from __future__ import annotations@@ -73,6 +76,10 @@ CORRECTNESS_REPEATS = 3DEVICE = "cuda"+class MeasurementInvalidError(RuntimeError):+ """The run cannot support a numerical mechanism verdict."""++def cuda_available() -> bool:try:import torch@@ -505,6 +512,8 @@ def run_backward(def gradient_snapshot(model: Any) -> dict[str, Any]:"""Collect LoRA gradients using canonical parameter names."""+ import torch+params = canonical_parameters(model)gradients = {}@@ -516,6 +525,11 @@ def gradient_snapshot(model: Any) -> dict[str, Any]:if parameter.grad is None:continue+ if not torch.isfinite(parameter.grad).all():+ raise MeasurementInvalidError(+ f"non-finite gradients in {name}"+ )+gradients[name] = parameter.grad.detach().float().clone()if not gradients:@@ -569,6 +583,11 @@ def assert_gradient_parity(f"{tuple(left.shape)} != {tuple(right.shape)}")+ if not torch.isfinite(left).all() or not torch.isfinite(right).all():+ raise MeasurementInvalidError(+ f"non-finite gradients in {name}"+ )+diff = (left - right).abs().max().item()worst = max(worst, float(diff))@@ -1018,6 +1037,9 @@ def main() -> int:return 0+ except MeasurementInvalidError as exc:+ print(f"ERROR: invalid measurement: {exc}; no verdict")+ return 3except Exception as exc:print(f"ERROR: mechanism_cost.py failed: "diff --git a/tests/test_issue379_mechanism.py b/tests/test_issue379_mechanism.pynew file mode 100644index 00000000..2c9bc637--- /dev/null+++ b/tests/test_issue379_mechanism.py@@ -0,0 +1,83 @@+import importlib.util+import sys+from pathlib import Path++import pytest+import torch++MODULE_PATH = Path(__file__).parents[1] / "benchmarks" / "harness" / "mechanism.py"+sys.path.insert(0, str(MODULE_PATH.parent))+SPEC = importlib.util.spec_from_file_location("mechanism_harness", MODULE_PATH)+assert SPEC is not None and SPEC.loader is not None+module = importlib.util.module_from_spec(SPEC)+sys.modules[SPEC.name] = module+SPEC.loader.exec_module(module)+++def gradients(*values):+ return {f"0.p{index}": torch.tensor([value]) for index, value in enumerate(values)}+++def test_exact_gradient_count_distinguishes_exact_and_mismatch():+ reference = gradients(1.0, 2.0)++ assert module.exact_gradient_count(reference, gradients(1.0, 2.0)) == (2, 2)+ assert module.exact_gradient_count(reference, gradients(1.0, 3.0)) == (1, 2)+ assert module.max_gradient_diff(reference, gradients(1.0, 3.0)) == pytest.approx(1.0)+++def test_gradient_comparison_rejects_non_finite_values():+ with pytest.raises(RuntimeError, match="non-finite"):+ module.exact_gradient_count(gradients(float("nan")), gradients(float("nan")))++ with pytest.raises(RuntimeError, match="non-finite"):+ module.max_gradient_diff(gradients(1.0), gradients(float("inf")))+++def test_gradient_comparison_rejects_empty_or_different_parameter_sets():+ with pytest.raises(RuntimeError, match="key sets differ"):+ module.exact_gradient_count({"resident.p": torch.ones(1)}, {"streamed.p": torch.ones(1)})+++def _patch_successful_measurement(monkeypatch):+ monkeypatch.setattr(module.torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(module.torch.cuda, "get_device_name", lambda _index: "test-gpu")+ monkeypatch.setattr(module, "load_sources", lambda: object())+ monkeypatch.setattr(module, "make_lora_parameters", lambda: object())+ monkeypatch.setattr(module, "make_arm_state", lambda *_args: object())++ def run_once(_sources, _state, arm, *, bypass_pool):+ if arm == "clone" and bypass_pool:+ return gradients(1.0)+ return gradients(2.0 if arm != "clone" else 1.0)++ monkeypatch.setattr(module, "run_once", run_once)+++def test_main_returns_success_for_a_reproduced_mechanism(monkeypatch):+ _patch_successful_measurement(monkeypatch)+ monkeypatch.setattr(sys, "argv", ["mechanism.py"])++ assert module.main() == 0+++def test_main_rejects_a_weakened_no_mismatch_verdict(monkeypatch):+ _patch_successful_measurement(monkeypatch)+ monkeypatch.setattr(module, "run_once", lambda *_args, **_kwargs: gradients(1.0))+ monkeypatch.setattr(sys, "argv", ["mechanism.py"])++ assert module.main() == 1+++def test_bypass_pool_negative_control_is_detected(monkeypatch):+ _patch_successful_measurement(monkeypatch)+ monkeypatch.setattr(+ module,+ "run_once",+ lambda _sources, _state, arm, *, bypass_pool: gradients(+ 1.0 if bypass_pool or arm == "clone" else 2.0+ ),+ )+ monkeypatch.setattr(sys, "argv", ["mechanism.py", "--bypass-pool"])++ assert module.main() == 1diff --git a/tests/test_issue379_mechanism_arms.py b/tests/test_issue379_mechanism_arms.pynew file mode 100644index 00000000..d07d01b4--- /dev/null+++ b/tests/test_issue379_mechanism_arms.py@@ -0,0 +1,56 @@+"""Pin every mechanism-arm verdict in the public harness decision path."""++import sys++from tests.test_issue379_mechanism import (+ _patch_successful_measurement,+ gradients,+ module,+)+++def _run_with_exact_arm(monkeypatch, exact_arm):+ _patch_successful_measurement(monkeypatch)++ def run_once(_sources, _state, arm, *, bypass_pool):+ if arm == "clone":+ return gradients(1.0)+ return gradients(1.0 if arm == exact_arm else 2.0)++ monkeypatch.setattr(module, "run_once", run_once)+ monkeypatch.setattr(sys, "argv", ["mechanism.py"])+ return module.main()+++def test_control_must_reproduce_a_mismatch(monkeypatch):+ assert _run_with_exact_arm(monkeypatch, "control") == 1+++def test_sync_must_not_remove_the_mismatch(monkeypatch):+ assert _run_with_exact_arm(monkeypatch, "sync") == 1+++def test_clone_quantstate_must_not_remove_the_mismatch(monkeypatch):+ assert _run_with_exact_arm(monkeypatch, "clone_quantstate") == 1+++def test_clone_packed_must_not_remove_the_mismatch(monkeypatch):+ assert _run_with_exact_arm(monkeypatch, "clone_packed") == 1+++def test_control_must_remain_wrong_after_repetition(monkeypatch):+ _patch_successful_measurement(monkeypatch)+ calls = 0++ def run_once(_sources, _state, arm, *, bypass_pool):+ nonlocal calls+ if arm == "clone":+ return gradients(1.0)+ if arm == "control":+ calls += 1+ return gradients(1.0 if calls == module.CORRECTNESS_REPEATS else 2.0)+ return gradients(2.0)++ monkeypatch.setattr(module, "run_once", run_once)+ monkeypatch.setattr(sys, "argv", ["mechanism.py"])+ assert module.main() == 1diff --git a/tests/test_issue379_mechanism_verdict.py b/tests/test_issue379_mechanism_verdict.pynew file mode 100644index 00000000..7fc51c0a--- /dev/null+++ b/tests/test_issue379_mechanism_verdict.py@@ -0,0 +1,124 @@+"""CPU checks for the verdict of benchmarks/harness/mechanism.py (#379)."""++import importlib.util+import sys+from pathlib import Path++import pytest++torch = pytest.importorskip("torch")+pytest.importorskip("bitsandbytes")++HARNESS = Path(__file__).parents[1] / "benchmarks" / "harness" / "mechanism.py"+KEYS = [+ f"{layer}.{name}"+ for layer in range(4)+ for name in ("q.A", "q.B", "v.A", "v.B")+]+++def _truth():+ generator = torch.Generator().manual_seed(0)+ return {key: torch.randn(8, 8, generator=generator) for key in KEYS}+++def _stale(grads):+ """Two tensors exact, the rest off by 1e-3."""+ return {+ key: value + (1e-3 if index >= 2 else 0.0)+ for index, (key, value) in enumerate(grads.items())+ }+++def _with_inf(grads):+ planted = {key: value.clone() for key, value in grads.items()}+ planted["0.q.B"][0, 0] = float("inf")+ return planted+++def _main(monkeypatch, capsys, argv=(), clone=None, bypassed_control=None):+ """Run the real main() with planted gradients."""+ spec = importlib.util.spec_from_file_location("_mechanism_harness_rv", HARNESS)+ module = importlib.util.module_from_spec(spec)+ monkeypatch.setitem(sys.modules, spec.name, module)+ spec.loader.exec_module(module)+ truth = _truth()+ calls = {}++ def run_once(sources, state, arm, *, bypass_pool):+ if bypass_pool and arm != "control":+ return dict(truth)+ repetition = calls[arm] = calls.get(arm, -1) + 1+ if arm == "clone":+ return clone(truth, repetition) if clone else dict(truth)+ if arm == "control" and bypass_pool:+ return bypassed_control(truth) if bypassed_control else dict(truth)+ return _stale(truth)++ monkeypatch.setattr(module.torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(+ module.torch.cuda, "get_device_name", lambda index=0: "planted"+ )+ monkeypatch.setattr(module, "load_sources", lambda: None)+ monkeypatch.setattr(module, "make_lora_parameters", lambda: None)+ monkeypatch.setattr(module, "make_arm_state", lambda sources, initial: None)+ monkeypatch.setattr(module, "run_once", run_once)+ monkeypatch.setattr(sys, "argv", ["mechanism.py", *argv])+ code = module.main()+ return code, capsys.readouterr().out+++def test_reproduced_mechanism_exits_0(monkeypatch, capsys):+ code, out = _main(monkeypatch, capsys)+ assert code == 0, out+ assert "RESULT: mechanism reproduced" in out+++ "clone",+ [+ pytest.param(+ lambda truth, rep: {key: value * 1.5 for key, value in truth.items()},+ id="wrong",+ ),+ pytest.param(+ lambda truth, rep: {+ key: value + 0.5 * rep for key, value in truth.items()+ },+ id="drifts",+ ),+ ],+)+def test_clone_that_disagrees_with_the_resident_reference_is_refused(+ monkeypatch, capsys, clone+):+ code, out = _main(monkeypatch, capsys, clone=clone)+ assert code == 1, out+ assert "RESULT: mechanism reproduced" not in out+++ "argv", [(), ("--bypass-pool",)], ids=["default", "bypass-pool"]+)+def test_non_finite_gradients_give_no_verdict_and_exit_3(+ monkeypatch, capsys, argv+):+ code, out = _main(+ monkeypatch,+ capsys,+ argv,+ clone=lambda truth, rep: _with_inf(truth),+ )+ assert code == 3, out+ assert "no verdict" in out+++def test_bypass_pool_exit_codes_stay_distinct(monkeypatch, capsys):+ caught, _ = _main(monkeypatch, capsys, ("--bypass-pool",))+ not_caught, _ = _main(+ monkeypatch,+ capsys,+ ("--bypass-pool",),+ bypassed_control=_stale,+ )+ assert (caught, not_caught) == (1, 2)