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 pinning cost harness for issue #379 (#1172)
Samarth Mukhija762e37566e36
diff --git a/benchmarks/README.md b/benchmarks/README.mdindex 2d43e394..62f8d503 100644--- a/benchmarks/README.md+++ b/benchmarks/README.md@@ -78,6 +78,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. |+| [`pincost.py`](harness/pincost.py) | STEP 8 / [gate-h100-validation.md](gate-h100-validation.md) §8 | Does turning host-memory pinning off impose the historical throughput cost? Uses Qwen2.5-32B-Instruct NF4, seq 256, batch 1, 5 warm-up steps + 20 timed forward/backward steps, n=3 per arm, with CUDA synchronization around each timed step. Both arms require canonical overlap, finite gradients and bit-exact finite losses; pageable gradients must be exact on every one of three backwards. The pinned arm may be timed while WRONG, with per-repetition counts and timing status reported. Historical record: 425.07 tok/s pinned vs 64.79 tok/s pageable, 6.56x slower without pinning; the pinned arm was WRONG 8/256, and absolute tok/s is not a standalone claim. The historical control is installed by default; pinning cost scales with bytes per layer | CUDA GPU with sufficient memory for Qwen2.5-32B-Instruct NF4; 26,713 MiB recorded requirement with both models resident; local checkpoint required and `resolve_model_weights` may download a non-directory; historical stack: H100 80 GB, torch 2.13.0+cu130, bitsandbytes 0.50.0 || [`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 |diff --git a/benchmarks/harness/pincost.py b/benchmarks/harness/pincost.pynew file mode 100644index 00000000..99ba18df--- /dev/null+++ b/benchmarks/harness/pincost.py@@ -0,0 +1,697 @@+#!/usr/bin/env python3+"""Measure the throughput cost of pageable versus pinned NF4 streaming.++This is the published STEP 8 / #379 protocol reconstructed from+``benchmarks/gate-h100-validation.md``.++Protocol+--------+- Qwen2.5-32B-Instruct, NF4+- sequence length 256, batch size 1+- 2 stream buffers+- 5 warm-up forward+backward steps+- 20 timed forward+backward steps per repeat+- 3 repeats per arm+- CUDA synchronization around every timed step+- correctness checked against a resident NF4 reference in the same process+ before timing either arm: both arms require finite, bit-exact losses and+ canonical gradient sets; pageable gradients must be exact on all three+ backwards, while the historical pinned arm may be timed when WRONG++Historical reference:+- pin=True: 425.07 tok/s, WRONG 8/256 gradients on all three repetitions+- pin=False: 64.79 tok/s+- pinned/pageable ratio: 6.56x++Those values are historical reference values only. This harness reports new+measurements when run on a suitable CUDA machine.++Historical requirements: H100 80 GB, torch 2.13.0+cu130, bitsandbytes 0.50.0;+26,713 MiB recorded with resident and streamed NF4 models live at seq 256.+Pinning cost scales with bytes per layer. Real CUDA validation is required.++No model download is required when ``--weights`` points to a local checkpoint+or an already-resolved local cache.++A machine without CUDA exits 0 with an explicit skip.++The default verdict is deliberately not a reproduction claim unless the+measured pinned/pageable ratio is at least 1.5x and exceeds the observed+run-to-run spread. The historical 6.56x value is reference context, not a+required exact threshold.+"""++from __future__ import annotations++import argparse+import gc+import sys+import time+from pathlib import Path+from statistics import median+from typing import Any++import bitexact+from mechanism_cost import install_historical_control++DTYPE = "bfloat16"+DEFAULT_SEQ = 256+DEFAULT_BATCH = 1+DEFAULT_BUFFERS = 2+DEFAULT_WARMUP = 5+DEFAULT_STEPS = 20+DEFAULT_REPEATS = 3+DEFAULT_SEED = 3+INPUT_SEED = 17+DEVICE = "cuda"+MIN_PINNING_RATIO = 1.5+++class MeasurementInvalidError(RuntimeError):+ """The timing data cannot support a pinning verdict."""+++def pinning_verdict(+ pinned_rates: list[float],+ pageable_rates: list[float],+) -> tuple[bool, float, float, float, float]:+ """Return verdict, medians, ratio, and maximum relative spread."""+ import math++ if not pinned_rates or not pageable_rates:+ raise MeasurementInvalidError("both timing arms must have measurements")+ values = [*pinned_rates, *pageable_rates]+ if any(not math.isfinite(value) or value <= 0 for value in values):+ raise MeasurementInvalidError("timing measurements must be finite and positive")++ pinned_median = float(median(pinned_rates))+ pageable_median = float(median(pageable_rates))+ ratio = pinned_median / pageable_median+ spreads = [+ (max(rates) - min(rates)) / median(rates)+ for rates in (pinned_rates, pageable_rates)+ ]+ spread = max(spreads)+ reproduced = ratio >= MIN_PINNING_RATIO and ratio > 1.0 + spread+ return reproduced, pinned_median, pageable_median, ratio, spread+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(+ description=(+ "Measure pinned versus pageable NF4 streaming cost from "+ "Soup's STEP 8/#379 protocol."+ )+ )+ parser.add_argument(+ "--weights",+ required=False,+ help="checkpoint path or model id resolvable by Soup's weight resolver",+ )+ parser.add_argument(+ "--shards",+ required=False,+ help="directory in which Soup should create or reuse 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(+ "--warmup",+ type=int,+ default=DEFAULT_WARMUP,+ help=f"discarded warm-up steps per arm (default: {DEFAULT_WARMUP})",+ )+ parser.add_argument(+ "--steps",+ type=int,+ default=DEFAULT_STEPS,+ help=f"timed steps per repeat (default: {DEFAULT_STEPS})",+ )+ parser.add_argument(+ "--repeats",+ type=int,+ default=DEFAULT_REPEATS,+ help=f"timing repeats per arm (default: {DEFAULT_REPEATS})",+ )+ parser.add_argument(+ "--self-test",+ action="store_true",+ help="run the CPU-only acceptance self-test and exit",+ )+ return parser.parse_args()+++def cuda_available() -> bool:+ return bitexact.cuda_available()+++def capture_lora_state(model: Any) -> dict[str, Any]:+ """Copy LoRA tensors to CPU so timed arms do not retain the reference."""+ from soup_cli.utils.layer_stream_runtime import canonical_named_parameters++ state: dict[str, Any] = {}++ for name, parameter in canonical_named_parameters(model):+ if "lora_" in name:+ state[name] = parameter.detach().cpu().clone()++ if not state:+ raise RuntimeError("reference 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 streamed model."""+ import torch++ from soup_cli.utils.layer_stream_runtime import canonical_named_parameters++ target = dict(canonical_named_parameters(model))++ with torch.no_grad():+ 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 run_correctness(+ streamed: Any,+ reference: Any,+ input_ids: Any,+ *,+ pin: bool,+) -> list[tuple[int, int]]:+ """Measure canonical overlap, loss, and three LoRA backward comparisons."""+ from soup_cli.utils.layer_stream_runtime import (+ assert_canonical_parameters_intersect,+ )++ assert_canonical_parameters_intersect(+ streamed,+ reference,+ )++ torch = __import__("torch")+ reference.zero_grad(set_to_none=True)+ reference.train()+ reference_loss = reference(input_ids=input_ids, labels=input_ids).loss+ if not torch.isfinite(reference_loss).all():+ raise RuntimeError(f"pin={pin} produced a non-finite loss before timing")+ reference_loss.backward()+ reference_grads = {+ name: parameter.grad.detach().cpu().clone()+ for name, parameter in reference.named_parameters()+ if "lora_" in name and parameter.grad is not None+ }+ if not reference_grads:+ raise RuntimeError(f"pin={pin} reference produced zero LoRA gradients")+ for name, parameter in reference.named_parameters():+ if parameter.grad is not None and not torch.isfinite(parameter.grad).all():+ raise RuntimeError(f"pin={pin} reference gradient is non-finite: {name}")++ results: list[tuple[int, int]] = []+ for repetition in range(3):+ streamed.zero_grad(set_to_none=True)+ streamed.train()+ streamed_loss = streamed(input_ids=input_ids, labels=input_ids).loss+ if not torch.isfinite(streamed_loss).all():+ raise RuntimeError(f"pin={pin} produced a non-finite loss before timing")+ if not torch.equal(streamed_loss, reference_loss):+ diff = (streamed_loss - reference_loss).detach().abs().item()+ raise RuntimeError(+ f"pin={pin} loss is not bit-exact before timing "+ f"(abs_diff={diff:.6e})"+ )+ streamed_loss.backward()+ streamed_grads = {+ name: parameter.grad.detach().cpu().clone()+ for name, parameter in streamed.named_parameters()+ if "lora_" in name and parameter.grad is not None+ }+ for name, parameter in streamed.named_parameters():+ if parameter.grad is not None and not torch.isfinite(parameter.grad).all():+ raise RuntimeError(f"pin={pin} streamed gradient is non-finite: {name}")+ if set(streamed_grads) != set(reference_grads):+ raise RuntimeError(+ f"pin={pin} gradient sets differ on repetition {repetition + 1}"+ )+ exact = sum(+ torch.equal(streamed_grads[name], reference_grads[name])+ for name in streamed_grads+ )+ print(+ f"correctness pin={pin} repetition={repetition + 1}/3 "+ f"exact={exact}/{len(streamed_grads)}"+ )+ results.append((exact, len(streamed_grads)))++ return results+++def time_arm(+ streamed: Any,+ *,+ input_ids: Any,+ warmup: int,+ steps: int,+) -> tuple[float, float]:+ """Warm up, then time forward+backward; return tok/s and median step time."""+ import torch++ streamed.train()++ def step() -> None:+ streamed.zero_grad(set_to_none=True)++ loss = streamed(+ input_ids=input_ids,+ labels=input_ids,+ ).loss++ loss.backward()++ for _ in range(warmup):+ step()++ torch.cuda.synchronize()++ durations: list[float] = []++ for _ in range(steps):+ torch.cuda.synchronize()++ started = time.perf_counter()++ step()++ torch.cuda.synchronize()++ durations.append(+ time.perf_counter() - started+ )++ median_step = median(durations)+ tokens = input_ids.numel()+ tok_per_s = tokens / median_step++ return float(tok_per_s), float(median_step)+++def run_self_test() -> int:+ """Exercise the production correctness 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:+ # This calls the same production correctness path used before timing.+ run_correctness(+ left,+ right,+ None,+ pin=False,+ )+ except ValueError as exc:+ print(+ "PASS: empty canonical parameter intersection was rejected "+ f"({type(exc).__name__}: {exc})"+ )+ return 0+ 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 build_shards_and_input(+ args: argparse.Namespace,+):+ """Resolve weights, shard once, and create the fixed timing input."""+ import torch++ from soup_cli.utils.layer_shard import shard_checkpoint+ from soup_cli.utils.layer_stream_runtime import (+ build_meta_skeleton,+ quantised_layer_suffixes,+ )+ from soup_cli.utils.spectrum_scan import resolve_model_weights++ weights_dir = resolve_model_weights(args.weights)++ shard_dir = Path(args.shards).expanduser()+ shard_dir.mkdir(parents=True, exist_ok=True)++ probe = build_meta_skeleton(+ weights_dir,+ 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++ index = shard_checkpoint(+ weights_dir,+ str(shard_dir),+ dtype=DTYPE,+ arch=arch,+ quant="nf4",+ quant_suffixes=quant_suffixes,+ double_quant=True,+ quant_device=DEVICE,+ )++ generator = torch.Generator(+ device=DEVICE+ ).manual_seed(INPUT_SEED)++ input_ids = torch.randint(+ 0,+ vocab_size,+ (args.batch, args.seq),+ generator=generator,+ device=DEVICE,+ )++ return weights_dir, str(shard_dir), index, input_ids+++def run_measurement(args: argparse.Namespace) -> int:+ import torch++ import soup_cli.utils.layer_stream_runtime as layer_runtime+ from soup_cli.utils.layer_stream_runtime import build_streamed_model++ 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.warmup <= 0:+ print("ERROR: --warmup must be positive")+ return 2++ if args.steps <= 0:+ print("ERROR: --steps must be positive")+ return 2++ if args.repeats <= 0:+ print("ERROR: --repeats must be positive")+ return 2++ if not cuda_available():+ print("SKIP: CUDA is required for pincost.py")+ return 0++ (+ weights_dir,+ shard_dir,+ index,+ input_ids,+ ) = build_shards_and_input(args)++ lora_config = bitexact.lora_config()++ print("RUN: STEP 8 pinned-versus-pageable NF4 cost")+ print(f"torch {torch.__version__}")+ print(f"gpu {torch.cuda.get_device_name(0)}")+ print(f"weights {weights_dir}")+ print("quant nf4")+ print(f"seq {args.seq}")+ print(f"batch {args.batch}")+ print(f"buffers {args.buffers}")+ print(f"warmup {args.warmup}")+ print(f"steps {args.steps}")+ print(f"repeats {args.repeats}")+ print()++ pinned_rates: list[float] = []+ pageable_rates: list[float] = []++ for repetition in range(args.repeats):+ print(+ f"repeat {repetition + 1}/{args.repeats}"+ )++ lora_state = None++ for pin in (True, False):+ reference = None+ streamed = None+ runtime = None++ try:+ original_install_dequant_forward = layer_runtime.install_dequant_forward+ install_historical_control(layer_runtime)+ reference = bitexact.load_resident_reference(+ weights_dir,+ "nf4",+ )++ bitexact.make_non_vacuous_lora(reference)++ if lora_state is None:+ lora_state = capture_lora_state(reference)+ else:+ restore_lora_state(reference, lora_state)++ print(f"correctness pin={pin}")++ streamed, runtime = build_streamed_model(+ model_id=weights_dir,+ shard_dir=shard_dir,+ index=index,+ lora_config=lora_config,+ device=DEVICE,+ dtype=DTYPE,+ buffers=args.buffers,+ pin=pin,+ seed=DEFAULT_SEED,+ quant="nf4",+ double_quant=True,+ tier="ram",+ )++ actual_pinned = getattr(+ runtime,+ "pinned",+ None,+ )++ if actual_pinned is not pin:+ raise RuntimeError(+ f"requested pin={pin}, but runtime reports "+ f"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(+ f"pin={pin} reported an empty streaming store"+ )++ restore_lora_state(+ streamed,+ lora_state,+ )++ correctness = run_correctness(+ streamed,+ reference,+ input_ids,+ pin=pin,+ )+ total = correctness[0][1]+ if any(rep_total != total for _, rep_total in correctness):+ raise RuntimeError(+ f"pin={pin} gradient totals changed across repetitions"+ )+ exact_summary = ",".join(+ f"{exact}/{rep_total}" for exact, rep_total in correctness+ )+ all_exact = all(+ exact == rep_total for exact, rep_total in correctness+ )+ print(+ f"gradients pin={pin} {exact_summary} "+ f"{'OK' if all_exact else 'WRONG'}"+ )+ if not pin and not all_exact:+ raise RuntimeError(+ "pin=False failed gradient correctness across all "+ f"repetitions: {exact_summary}"+ )++ # Correctness and timing use the same streamed instance.+ # Remove the resident reference before timing so it does not+ # inflate the timed arm's memory footprint.+ del reference+ reference = None++ gc.collect()+ torch.cuda.empty_cache()++ rate, median_step = time_arm(+ streamed,+ input_ids=input_ids,+ warmup=args.warmup,+ steps=args.steps,+ )++ if pin:+ pinned_rates.append(rate)+ else:+ pageable_rates.append(rate)++ print(+ f"timing pin={pin} "+ f"{rate:.2f} tok/s, "+ f"median_step={median_step:.4f} s, "+ f"gradients={'OK' if all_exact else 'WRONG'} ({exact_summary})"+ )++ finally:+ if reference is not None:+ del reference++ if runtime is not None:+ runtime.close()++ if streamed is not None:+ del streamed++ layer_runtime.install_dequant_forward = original_install_dequant_forward++ gc.collect()+ torch.cuda.empty_cache()++ reproduced, pinned_median, pageable_median, direct_ratio, spread = (+ pinning_verdict(pinned_rates, pageable_rates)+ )+ inverse_ratio = pageable_median / pinned_median++ print()+ print(+ f"median pin=True "+ f"{pinned_median:.2f} tok/s"+ )+ print(+ f"median pin=False "+ f"{pageable_median:.2f} tok/s"+ )+ print(+ f"pin=True/pin=False ratio "+ f"{direct_ratio:.2f}x"+ )+ print(+ f"pin=False/pin=True ratio "+ f"{inverse_ratio:.2f}x"+ )+ print(f"run-to-run spread {spread:.2%}")+ print(+ "Historical reference: "+ "425.07 tok/s (pinned WRONG 8/256) vs 64.79 tok/s, 6.56x"+ )+ if reproduced:+ print("RESULT: historical-control pinning cost relationship reproduced")+ return 0++ print("ERROR: measured pinning advantage is absent or too small")+ print(+ f"Required: ratio >= {MIN_PINNING_RATIO:.2f}x and above the "+ "observed spread"+ )+ return 1++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: invalid measurement: {exc}")+ return 3+ except Exception as exc:+ print(+ f"ERROR: pincost.py failed: "+ f"{type(exc).__name__}: {exc}"+ )+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/test_issue379_pincost_main.py b/tests/test_issue379_pincost_main.pynew file mode 100644index 00000000..ab7ccd3c--- /dev/null+++ b/tests/test_issue379_pincost_main.py@@ -0,0 +1,287 @@+"""Drive ``pincost.main()`` through its real CPU-testable decisions."""+from __future__ import annotations++import sys+from types import SimpleNamespace++import pytest+import torch+from torch import nn++from tests.conftest import strip_ansi+from tests.test_pincost import module as pincost++HIDDEN, VOCAB, LAYERS = 8, 32, 2+FAST, SLOW = 1.0, 4.0++def _plain(text: str) -> str:+ return " ".join(strip_ansi(text).split())++class _GradScale(torch.autograd.Function):+ @staticmethod+ def forward(ctx, x, factor):+ ctx.factor = factor+ return x.view_as(x)+ @staticmethod+ def backward(ctx, grad):+ return grad * ctx.factor, None++class _Layer(nn.Module):+ def __init__(self) -> None:+ super().__init__()+ self.base = nn.Linear(HIDDEN, HIDDEN, bias=False).requires_grad_(False)+ self.lora_A = nn.Linear(HIDDEN, 2, bias=False)+ self.lora_B = nn.Linear(2, HIDDEN, bias=False)+ def forward(self, x, factor=None):+ delta = self.lora_B(self.lora_A(x))+ if hasattr(self, "lora_extra"):+ delta = delta + self.lora_extra(x).sum() * 0.0+ if factor is not None:+ delta = _GradScale.apply(delta, factor)+ return torch.tanh(self.base(x) + delta)++class _Inner(nn.Module):+ def __init__(self) -> None:+ super().__init__()+ self.layers = nn.ModuleList(_Layer() for _ in range(LAYERS))++class _Toy(nn.Module):+ def __init__(self, scenario: str, clock: SimpleNamespace, *, pin=None) -> None:+ super().__init__()+ torch.manual_seed(0)+ self.config = SimpleNamespace(vocab_size=VOCAB, model_type="llama")+ self.embed = nn.Embedding(VOCAB, HIDDEN).requires_grad_(False)+ self.model = _Inner()+ self.head = nn.Linear(HIDDEN, VOCAB, bias=False).requires_grad_(False)+ self.scenario, self.clock, self.pin = scenario, clock, pin+ self.streamed_calls = 0+ streamed = pin is not None+ if scenario == "extra_lora" and streamed:+ self.model.layers[0].lora_extra = nn.Linear(HIDDEN, 2, bias=False)+ if scenario == "inf_grads" or (+ scenario == "inf_grads_streamed" and streamed+ ) or (scenario == "inf_grads_reference" and not streamed):+ for name, parameter in self.named_parameters():+ if "lora_" in name:+ parameter.register_hook(lambda g: torch.full_like(g, float("inf")))+ def forward(self, input_ids, labels):+ streamed = self.pin is not None+ factor = None+ if streamed:+ self.streamed_calls += 1+ slow = not self.pin+ if self.scenario == "inverted":+ slow = self.pin+ elif self.scenario == "no_cost":+ slow = False+ step = SLOW if slow else FAST+ self.clock.now += -step if self.scenario == "clock_backwards" else step+ if self.scenario == "wrong_first":+ factor = 3.0+ elif self.scenario == "pinned_wrong_all" and self.pin:+ factor = 3.0+ elif (+ self.scenario in {"wrong_after_first", "pinned_wrong_after_first"}+ and self.streamed_calls > 1+ ):+ factor = 3.0+ if self.scenario == "pinned_wrong_after_first" and not self.pin:+ factor = None+ x = self.embed(input_ids)+ for layer in self.model.layers:+ x = layer(x, factor)+ loss = nn.functional.cross_entropy(self.head(x).view(-1, VOCAB), labels.view(-1))+ if streamed and self.scenario == "loss_offset":+ loss = loss + 1e-3+ if self.scenario == "inf_loss" or (+ self.scenario == "inf_loss_streamed" and streamed+ ) or (self.scenario == "inf_loss_reference" and not streamed):+ loss = loss + torch.tensor(float("inf"))+ return SimpleNamespace(loss=loss)++class _Runtime:+ def __init__(self, pinned: bool) -> None:+ self.pinned = pinned+ self.source = SimpleNamespace(nbytes=1)+ def close(self) -> None:+ pass++def _run(monkeypatch, capsys, tmp_path, scenario: str) -> tuple[int, str]:+ import soup_cli.utils.layer_shard as layer_shard+ import soup_cli.utils.layer_stream_runtime as layer_runtime+ import soup_cli.utils.spectrum_scan as spectrum_scan+ clock = SimpleNamespace(now=0.0)+ def build_streamed(*args, **kwargs):+ pin = kwargs["pin"]+ reported = True if scenario == "lying_pinned" else pin+ runtime = _Runtime(reported)+ if scenario == "empty_store":+ runtime.source.nbytes = 0+ return _Toy(scenario, clock, pin=pin), runtime+ def cpu_non_vacuous(model) -> None:+ generator = torch.Generator(device="cpu").manual_seed(23)+ with torch.no_grad():+ for name, parameter in layer_runtime.canonical_named_parameters(model):+ if "lora_B" in name:+ parameter.copy_(torch.randn(parameter.shape, generator=generator) * 0.02)+ monkeypatch.setattr(pincost, "DEVICE", "cpu")+ monkeypatch.setattr(pincost, "cuda_available", lambda: True)+ monkeypatch.setattr(pincost, "time", SimpleNamespace(perf_counter=lambda: clock.now))+ monkeypatch.setattr(torch.cuda, "synchronize", lambda *a, **k: None)+ monkeypatch.setattr(torch.cuda, "empty_cache", lambda *a, **k: None)+ monkeypatch.setattr(torch.cuda, "get_device_name", lambda *a, **k: "cpu-stub")+ monkeypatch.setattr(spectrum_scan, "resolve_model_weights", lambda weights: str(weights))+ monkeypatch.setattr(layer_runtime, "build_meta_skeleton", lambda *a, **k: _Toy(scenario, clock))+ monkeypatch.setattr(layer_runtime, "quantised_layer_suffixes", lambda probe: ())+ monkeypatch.setattr(layer_runtime, "build_streamed_model", build_streamed)+ monkeypatch.setattr(layer_shard, "shard_checkpoint", lambda *a, **k: {})+ monkeypatch.setattr(+ pincost.bitexact,+ "load_resident_reference",+ lambda *a, **k: _Toy(scenario, clock),+ )+ monkeypatch.setattr(pincost.bitexact, "make_non_vacuous_lora", cpu_non_vacuous)+ monkeypatch.setattr(+ sys,+ "argv",+ [+ "pincost.py", "--weights", str(tmp_path), "--shards",+ str(tmp_path / "shards"), "--seq", "4", "--warmup", "1",+ "--steps", "3", "--repeats", "2",+ ],+ )+ return pincost.main(), _plain(capsys.readouterr().out)++def test_a_real_cost_passes_with_the_arms_the_right_way_round(monkeypatch, capsys, tmp_path):+ code, out = _run(monkeypatch, capsys, tmp_path, "cost")+ assert code == 0, out+ assert "median pin=True 4.00 tok/s" in out+ assert "median pin=False 1.00 tok/s" in out+ assert "pin=True/pin=False ratio 4.00x" in out+[email protected]("scenario, ratio", [("no_cost", "1.00x"), ("inverted", "0.25x")])+def test_no_cost_or_an_inverted_cost_fails(monkeypatch, capsys, tmp_path, scenario, ratio):+ code, out = _run(monkeypatch, capsys, tmp_path, scenario)+ assert code == 1, out+ assert f"pin=True/pin=False ratio {ratio}" in out+ assert "measured pinning advantage is absent or too small" in out++ "scenario, message",+ [+ ("loss_offset", "loss is not bit-exact before timing"),+ ("inf_loss", "produced a non-finite loss before timing"),+ ("inf_grads", "gradient is non-finite"),+ ("lying_pinned", "requested pin=False, but runtime reports pinned=True"),+ ],+)+def test_an_arm_that_fails_its_gate_is_never_reported(+ monkeypatch, capsys, tmp_path, scenario, message+):+ code, out = _run(monkeypatch, capsys, tmp_path, scenario)+ assert code == 1, out+ assert message in out+ assert "RESULT:" not in out++def test_wrong_pinned_arm_is_reported_but_can_still_be_timed(+ monkeypatch, capsys, tmp_path+):+ code, out = _run(monkeypatch, capsys, tmp_path, "pinned_wrong_after_first")+ assert code == 0, out+ assert "gradients pin=True 4/4,0/4,0/4 WRONG" in out+ assert "RESULT: historical-control pinning cost relationship reproduced" in out++def test_an_invalid_timing_exits_3(monkeypatch, capsys, tmp_path):+ code, out = _run(monkeypatch, capsys, tmp_path, "clock_backwards")+ assert code == 3, out+ assert "invalid measurement" in out++def test_verdict_refuses_a_ratio_inside_the_arms_own_spread():+ reproduced, _, _, ratio, spread = pincost.pinning_verdict([400.0, 100.0, 200.0], [100.0] * 3)+ assert ratio == pytest.approx(2.0)+ assert spread == pytest.approx(1.5)+ assert reproduced is False+[email protected]("scenario", ["cost", "loss_offset"])+def test_historical_control_is_restored_after_measurement(monkeypatch, capsys, tmp_path, scenario):+ import soup_cli.utils.layer_stream_runtime as layer_runtime+ original = layer_runtime.install_dequant_forward+ _run(monkeypatch, capsys, tmp_path, scenario)+ assert layer_runtime.install_dequant_forward is original++[email protected]("scenario", ["wrong_first", "wrong_after_first"])+def test_wrong_pageable_arm_refuses_timing_result(monkeypatch, capsys, tmp_path, scenario):+ code, out = _run(monkeypatch, capsys, tmp_path, scenario)+ assert code == 1, out+ assert "pin=False failed gradient correctness across all repetitions:" in out+ assert "median pin=True" not in out+ assert "RESULT:" not in out+++def test_historical_pinned_arm_wrong_on_every_backward_can_be_timed(monkeypatch, capsys, tmp_path):+ code, out = _run(monkeypatch, capsys, tmp_path, "pinned_wrong_all")+ assert code == 0, out+ assert "gradients pin=True 0/4,0/4,0/4 WRONG" in out+ assert "gradients pin=False 4/4,4/4,4/4 OK" in out+ assert "median pin=True 4.00 tok/s" in out+ assert "pin=True/pin=False ratio 4.00x" in out+ assert "timing pin=True 4.00 tok/s, median_step=1.0000 s, gradients=WRONG" in out+++ "scenario, message",+ [+ ("inf_loss_streamed", "produced a non-finite loss before timing"),+ ("inf_loss_reference", "produced a non-finite loss before timing"),+ ("inf_grads_streamed", "streamed gradient is non-finite"),+ ("inf_grads_reference", "reference gradient is non-finite"),+ ("empty_store", "reported an empty streaming store"),+ ("extra_lora", "gradient sets differ"),+ ],+)+def test_independent_measurement_guards(monkeypatch, capsys, tmp_path, scenario, message):+ code, out = _run(monkeypatch, capsys, tmp_path, scenario)+ assert code == 1, out+ assert message in out+ assert "RESULT:" not in out+++def test_historical_control_is_installed_for_every_arm(monkeypatch, capsys, tmp_path):+ import soup_cli.utils.layer_stream_runtime as layer_runtime++ installed = []+ monkeypatch.setattr(pincost, "install_historical_control", installed.append)+ code, out = _run(monkeypatch, capsys, tmp_path, "cost")+ assert code == 0, out+ assert installed == [layer_runtime] * 4+++def test_self_test_runs():+ assert pincost.run_self_test() == 0+++def test_correctness_rejects_empty_canonical_intersection():+ streamed, reference = nn.Module(), nn.Module()+ streamed.register_parameter("streamed_only", nn.Parameter(torch.ones(1)))+ reference.register_parameter("reference_only", nn.Parameter(torch.ones(1)))+ with pytest.raises(ValueError, match="no canonical parameter name is shared"):+ pincost.run_correctness(streamed, reference, torch.ones(1), pin=True)+++def test_no_lora_gradient_on_either_side_is_refused(monkeypatch, capsys, tmp_path):+ """0/0 compared gradients is not a correct arm: nothing was checked."""+ original_init = _Toy.__init__++ def init(self, scenario, clock, *, pin=None):+ original_init(self, scenario, clock, pin=pin)+ for name, parameter in self.named_parameters():+ if "lora_" in name:+ parameter.requires_grad_(False)+ self.head.requires_grad_(True)++ monkeypatch.setattr(_Toy, "__init__", init)+ code, out = _run(monkeypatch, capsys, tmp_path, "cost")+ assert code == 1, out+ assert "produced zero LoRA gradients" in out+ assert "RESULT:" not in outdiff --git a/tests/test_pincost.py b/tests/test_pincost.pynew file mode 100644index 00000000..d5af82c5--- /dev/null+++ b/tests/test_pincost.py@@ -0,0 +1,40 @@+import importlib.util+import sys+from pathlib import Path++import pytest++MODULE_PATH = Path(__file__).parents[1] / "benchmarks" / "harness" / "pincost.py"+sys.path.insert(0, str(MODULE_PATH.parent))+SPEC = importlib.util.spec_from_file_location("pincost_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)+++def test_pinning_verdict_requires_a_real_advantage():+ reproduced, pinned, pageable, ratio, spread = module.pinning_verdict(+ [101.0, 100.0, 99.0],+ [90.0, 89.0, 91.0],+ )++ assert reproduced is False+ assert pinned == pytest.approx(100.0)+ assert pageable == pytest.approx(90.0)+ assert ratio == pytest.approx(100 / 90)+ assert spread > 0+++def test_pinning_verdict_accepts_historical_scale_relationship():+ reproduced, *_ = module.pinning_verdict(+ [425.0, 426.0, 424.0],+ [64.0, 65.0, 65.0],+ )++ assert reproduced is True++[email protected]("bad", [float("nan"), float("inf")])+def test_pinning_verdict_rejects_non_finite_rates(bad):+ with pytest.raises(module.MeasurementInvalidError, match="finite"):+ module.pinning_verdict([bad], [1.0])