Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

bench: publish CPU fixture-window probe (#379) (#1144)

AmixDigital81037e48e273
diff --git a/benchmarks/README.md b/benchmarks/README.md
index 458d7bed..74fd16bb 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -56,6 +56,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 |
+| [`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. |
| [`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 |
diff --git a/benchmarks/harness/fixture_window_cpu.py b/benchmarks/harness/fixture_window_cpu.py
new file mode 100644
index 00000000..12443056
--- /dev/null
+++ b/benchmarks/harness/fixture_window_cpu.py
@@ -0,0 +1,419 @@
+#!/usr/bin/env python3
+"""Per-layer CPU NF4 reconstruction for #379 / STEP 13.
+
+This is NOT a replay of the full-model tiny-Llama logits numbers recorded in
+``tests/test_v07202.py`` (1.948e-03 at 8 tokens, ~1.972e-03 from 32..256 on the
+H100 host CPU, and 2.509e-03 on CI). Those numbers compare a streamed two-layer
+model with a resident model.
+
+Instead this harness reconstructs, one ``Linear4bit`` at a time, both STEP
+13 questions that were lost with the scratchpad: where the CI fixture sits
+relative to the CPU fused-kernel window (the historical
+``fixture_window_cpu.py``) and whether bitsandbytes' CPU *inference* packing
+path creates the rounding-scale numerical difference investigated by the
+historical ``cpu_mode_probe.py``.
+
+Requirements / attribution boundary
+-----------------------------------
+- AVX512-BF16 is required for the mechanism this gate is intended to
+ demonstrate. Without it, the default invocation FAILS; use ``--survey`` for a
+ capability-only report.
+- Importing bitsandbytes on an AVX512-BF16 host may fetch/use
+ ``kernels-community/quantization-bitsandbytes``; that happens while the CPU
+ backend module is imported, before a row reaches the packed inference path.
+ ``packing_format_for_cpu`` proves that packing ran. The JSON separately
+ records best-effort lower-level kernel attribution and whether the CPU
+ ``gemv_4bit`` dispatch is registered. No "no downloads" promise is made.
+- The "variant 2" arm imports Soup's shipped ``install_dequant_forward``
+ unmodified. NF4 uses ``compress_statistics=True`` (double quant), matching
+ layer-stream shards.
+
+Default invocation is a mechanism gate:
+1. the training arm must stay unpacked and equal Soup variant 2 EXACTLY;
+2. at least one inference row must enter CPU packing;
+3. every packed inference row must differ from variant 2;
+4. every packed difference must remain rounding-scale: strictly greater than
+ zero and at most 2% of ``max(abs(variant2))``.
+
+Each row also computes an emulated bf16 reference from the same quantised
+weight: bf16-rounded input and dequantised weight, fp32 accumulation, then a
+bf16-rounded output. The JSON publishes its relative error and the ratio between
+the 2% envelope and the worst emulated row, so the envelope is justified by the
+same run. A previous review-time forced broken-packing simulation produced
+order-one errors, but that patched experiment is not an arm of this harness and
+is not used as acceptance evidence.
+
+Exit codes: 0 mechanism reproduced; 2 packing unavailable; 3 invalid training
+control; 4 packed effect absent on at least one row; 5 packed effect is too
+large to be the rounding-scale mechanism.
+
+``--survey`` waives only exit 2 (missing capability). A broken control or
+nonsensical packed result still fails closed.
+"""
+
+from __future__ import annotations
+
+import argparse
+import importlib.util
+import json
+import platform
+import sys
+from dataclasses import asdict, dataclass
+
+M_VALUES = (8, 16, 32, 64, 128, 256)
+FIXTURE_SHAPES = ((64, 64), (256, 64))
+
+EXIT_OK = 0
+EXIT_MECHANISM_ABSENT = 2
+EXIT_CONTROL_FAILED = 3
+EXIT_EFFECT_ABSENT = 4
+EXIT_EFFECT_OUT_OF_RANGE = 5
+
+# The default envelope is intentionally loose. Every run publishes a
+# per-row emulated-bf16 reference plus the multiple by which this ceiling
+# exceeds the worst emulated row, so the justification is reproducible.
+PACKED_EFFECT_REL_ENVELOPE = 0.02
+
+
+@dataclass(frozen=True)
+class Row:
+ out_features: int
+ in_features: int
+ m: int
+ inference_packed_for_cpu: bool
+ training_packed_for_cpu: bool
+ variant2_max_abs: float
+ emulated_bf16_vs_variant2_max_abs: float
+ emulated_bf16_rel: float
+ inference_vs_variant2_max_abs: float
+ inference_vs_variant2_rel: float
+ training_vs_variant2_max_abs: float
+ inference_vs_training_max_abs: float
+
+
+def _quantized_linear(weight, *, compute_dtype):
+ import bitsandbytes as bnb
+ import bitsandbytes.functional as functional
+
+ packed, state = functional.quantize_4bit(
+ weight,
+ blocksize=64,
+ compress_statistics=True,
+ quant_type="nf4",
+ )
+ layer = bnb.nn.Linear4bit(
+ weight.shape[1],
+ weight.shape[0],
+ bias=False,
+ compute_dtype=compute_dtype,
+ compress_statistics=True,
+ quant_type="nf4",
+ device="cpu",
+ )
+ layer.weight = bnb.nn.Params4bit(
+ data=packed,
+ requires_grad=False,
+ quant_state=state,
+ blocksize=state.blocksize,
+ compress_statistics=True,
+ quant_type=state.quant_type,
+ bnb_quantized=True,
+ )
+ return layer
+
+
+def _row_seed(seed: int, out_features: int, in_features: int, m: int) -> int:
+ """Derive a deterministic stream from the complete fixture tuple."""
+ return seed + out_features * 1_000_003 + in_features * 1_009 + m
+
+
+def _emulated_bf16_reference(layer, x):
+ """Emulate the rounding-only bf16 path using this row's quantised weight."""
+ import bitsandbytes.functional as bnb_functional
+ import torch
+
+ dense_quantized = bnb_functional.dequantize_4bit(
+ layer.weight,
+ layer.weight.quant_state,
+ ).to(torch.float32)
+ return torch.nn.functional.linear(
+ x.to(torch.bfloat16).to(torch.float32),
+ dense_quantized.to(torch.bfloat16).to(torch.float32),
+ ).to(torch.bfloat16).to(torch.float32)
+
+
+def measure_row(out_features: int, in_features: int, m: int, *, seed: int = 17) -> Row:
+ import torch
+
+ from soup_cli.utils.layer_stream_runtime import install_dequant_forward
+
+ row_seed = _row_seed(seed, out_features, in_features, m)
+ generator = torch.Generator().manual_seed(row_seed)
+ weight = torch.randn(
+ (out_features, in_features),
+ generator=generator,
+ dtype=torch.float32,
+ )
+ x = torch.randn(
+ (m, in_features),
+ generator=generator,
+ dtype=torch.float32,
+ )
+
+ variant2_layer = _quantized_linear(weight, compute_dtype=torch.float32)
+ patched = install_dequant_forward(variant2_layer)
+ if patched != 1:
+ raise RuntimeError(
+ f"install_dequant_forward patched {patched} layers, expected 1"
+ )
+ variant2_layer.train()
+ variant2_x = x.clone().requires_grad_(True)
+ variant2 = variant2_layer(variant2_x).detach()
+
+ emulated_bf16 = _emulated_bf16_reference(variant2_layer, x)
+
+ training_layer = _quantized_linear(weight, compute_dtype=torch.float32)
+ training_layer.train()
+ training_x = x.clone().requires_grad_(True)
+ training = training_layer(training_x).detach()
+ training_packed = bool(
+ getattr(
+ training_layer.weight.quant_state,
+ "packing_format_for_cpu",
+ False,
+ )
+ )
+
+ inference_layer = _quantized_linear(weight, compute_dtype=torch.float32)
+ inference_layer.eval()
+ with torch.no_grad():
+ inference = inference_layer(x)
+ inference_packed = bool(
+ getattr(
+ inference_layer.weight.quant_state,
+ "packing_format_for_cpu",
+ False,
+ )
+ )
+
+ inference_diff = float((inference - variant2).abs().max())
+ emulated_bf16_diff = float((emulated_bf16 - variant2).abs().max())
+ variant2_max = float(variant2.abs().max())
+ if variant2_max > 0.0:
+ inference_rel = inference_diff / variant2_max
+ emulated_bf16_rel = emulated_bf16_diff / variant2_max
+ elif inference_diff == 0.0:
+ inference_rel = 0.0
+ emulated_bf16_rel = 0.0 if emulated_bf16_diff == 0.0 else float("inf")
+ else:
+ inference_rel = float("inf")
+ emulated_bf16_rel = (
+ 0.0 if emulated_bf16_diff == 0.0 else float("inf")
+ )
+
+ return Row(
+ out_features=out_features,
+ in_features=in_features,
+ m=m,
+ inference_packed_for_cpu=inference_packed,
+ training_packed_for_cpu=training_packed,
+ variant2_max_abs=variant2_max,
+ emulated_bf16_vs_variant2_max_abs=emulated_bf16_diff,
+ emulated_bf16_rel=emulated_bf16_rel,
+ inference_vs_variant2_max_abs=inference_diff,
+ inference_vs_variant2_rel=inference_rel,
+ training_vs_variant2_max_abs=float(
+ (training - variant2).abs().max()
+ ),
+ inference_vs_training_max_abs=float(
+ (inference - training).abs().max()
+ ),
+ )
+
+
+def _evaluate_rows(rows: list[Row]) -> dict:
+ # A broken control is a harness/Soup failure on every host; do not hide it
+ # behind a missing-AVX512 capability verdict.
+ if any(row.training_packed_for_cpu for row in rows) or any(
+ row.training_vs_variant2_max_abs != 0.0 for row in rows
+ ):
+ return {
+ "verdict": "control_failed",
+ "exit_code": EXIT_CONTROL_FAILED,
+ "reason": (
+ "training-style Linear4bit did not remain an exact unpacked "
+ "control against Soup install_dequant_forward."
+ ),
+ "attribution": "invalid-control",
+ }
+
+ packed_rows = [row for row in rows if row.inference_packed_for_cpu]
+ if not packed_rows:
+ return {
+ "verdict": "mechanism_absent",
+ "exit_code": EXIT_MECHANISM_ABSENT,
+ "reason": (
+ "CPU inference packing did not run; this host cannot demonstrate "
+ "the cpu_mode_probe mechanism."
+ ),
+ "attribution": "none",
+ }
+
+ if any(row.inference_vs_variant2_max_abs == 0.0 for row in packed_rows):
+ return {
+ "verdict": "packed_effect_absent",
+ "exit_code": EXIT_EFFECT_ABSENT,
+ "reason": (
+ "the packed inference path ran, but at least one packed row did "
+ "not differ from Soup variant 2."
+ ),
+ "attribution": "packed-path-detected-no-universal-divergence",
+ }
+
+ if any(
+ not (0.0 < row.inference_vs_variant2_rel <= PACKED_EFFECT_REL_ENVELOPE)
+ for row in packed_rows
+ ):
+ return {
+ "verdict": "packed_effect_out_of_range",
+ "exit_code": EXIT_EFFECT_OUT_OF_RANGE,
+ "reason": (
+ "the packed inference path ran, but at least one packed row "
+ "differs by more than the 2% rounding-scale envelope."
+ ),
+ "attribution": "packed-path-detected-non-rounding-scale-effect",
+ }
+
+ return {
+ "verdict": "mechanism_reproduced",
+ "exit_code": EXIT_OK,
+ "reason": (
+ "every packed row differs from Soup variant 2 within the 2% "
+ "rounding-scale envelope while the training control is exact."
+ ),
+ "attribution": (
+ "bitsandbytes packed CPU inference path; exact lower-level kernel "
+ "reported separately"
+ ),
+ }
+
+
+_MISSING_KERNEL_MARKER = object()
+
+
+def _cpu_packed_kernel_attribution() -> str:
+ """Best-effort bnb 0.50.x attribution without making it a gate."""
+ try:
+ import bitsandbytes.backends.cpu.ops as cpu_ops
+ except Exception:
+ return "unknown"
+
+ marker = getattr(
+ cpu_ops,
+ "gemm_4bit_forward_kernel",
+ _MISSING_KERNEL_MARKER,
+ )
+ if marker is _MISSING_KERNEL_MARKER:
+ registered = _cpu_gemv_registered()
+ if registered is False:
+ return "not-registered"
+ return "unknown"
+ if marker is None:
+ return "native-bitsandbytes-cpu-gemv"
+ return "kernels-community"
+
+
+def _cpu_gemv_registered() -> bool | None:
+ try:
+ import torch
+
+ return bool(
+ torch._C._dispatch_has_kernel_for_dispatch_key(
+ "bitsandbytes::gemv_4bit", "CPU"
+ )
+ )
+ except Exception:
+ return None
+
+
+def run_probe(*, m_values=M_VALUES, shapes=FIXTURE_SHAPES) -> dict:
+ import bitsandbytes
+ import bitsandbytes.functional as functional
+ import torch
+
+ rows = [
+ measure_row(out_features, in_features, m)
+ for out_features, in_features in shapes
+ for m in m_values
+ ]
+ verdict = _evaluate_rows(rows)
+ emulated_worst = max((row.emulated_bf16_rel for row in rows), default=0.0)
+ envelope_multiple = (
+ PACKED_EFFECT_REL_ENVELOPE / emulated_worst
+ if emulated_worst > 0.0
+ else None
+ )
+ return {
+ "torch": torch.__version__,
+ "bitsandbytes": bitsandbytes.__version__,
+ "platform": platform.platform(),
+ "has_avx512bf16": bool(functional.has_avx512bf16()),
+ "kernels_package_installed": (
+ importlib.util.find_spec("kernels") is not None
+ ),
+ "cpu_packed_kernel": _cpu_packed_kernel_attribution(),
+ "cpu_gemv_4bit_registered": _cpu_gemv_registered(),
+ "rows": [asdict(row) for row in rows],
+ "packed_inference_rows": sum(
+ row.inference_packed_for_cpu for row in rows
+ ),
+ "packed_training_rows": sum(
+ row.training_packed_for_cpu for row in rows
+ ),
+ "training_control_exact": all(
+ row.training_vs_variant2_max_abs == 0.0 for row in rows
+ ),
+ "packed_effect_rel_envelope": PACKED_EFFECT_REL_ENVELOPE,
+ "emulated_bf16_worst_rel": emulated_worst,
+ "envelope_over_emulated_worst": envelope_multiple,
+ **verdict,
+ }
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(
+ description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ )
+ parser.add_argument("--output", help="optional JSON output path")
+ parser.add_argument(
+ "--survey",
+ action="store_true",
+ help=(
+ "capability-only survey: waive exit 2 when CPU packing is absent; "
+ "control/effect failures still fail closed"
+ ),
+ )
+ args = parser.parse_args(argv)
+
+ result = run_probe()
+ payload = json.dumps(result, indent=2, sort_keys=True)
+ print(payload)
+ if args.output:
+ from pathlib import Path
+
+ Path(args.output).write_text(
+ payload + "\n",
+ encoding="utf-8",
+ )
+
+ code = int(result["exit_code"])
+ if args.survey and code == EXIT_MECHANISM_ABSENT:
+ return EXIT_OK
+ if code != EXIT_OK:
+ print(str(result["reason"]), file=sys.stderr)
+ return code
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/test_issue379_fixture_window_cpu_harness.py b/tests/test_issue379_fixture_window_cpu_harness.py
new file mode 100644
index 00000000..e63ab498
--- /dev/null
+++ b/tests/test_issue379_fixture_window_cpu_harness.py
@@ -0,0 +1,578 @@
+"""Load-bearing tests for the CPU fixture-window mechanism harness (#379)."""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+HARNESS = (
+ Path(__file__).resolve().parents[1]
+ / "benchmarks"
+ / "harness"
+ / "fixture_window_cpu.py"
+)
+
+
+def _load_harness():
+ name = "_fixture_window_cpu_test_module"
+ spec = importlib.util.spec_from_file_location(name, HARNESS)
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[name] = module
+ try:
+ spec.loader.exec_module(module)
+ finally:
+ sys.modules.pop(name, None)
+ return module
+
+
+def _row(
+ harness,
+ *,
+ inference_packed=False,
+ training_packed=False,
+ inference_diff=0.0,
+ training_diff=0.0,
+ variant2_abs=100.0,
+ inference_rel=None,
+ emulated_bf16_rel=0.004,
+):
+ if inference_rel is None:
+ inference_rel = inference_diff / variant2_abs if variant2_abs else float("inf")
+ return harness.Row(
+ out_features=64,
+ in_features=64,
+ m=8,
+ inference_packed_for_cpu=inference_packed,
+ training_packed_for_cpu=training_packed,
+ variant2_max_abs=variant2_abs,
+ emulated_bf16_vs_variant2_max_abs=emulated_bf16_rel * variant2_abs,
+ emulated_bf16_rel=emulated_bf16_rel,
+ inference_vs_variant2_max_abs=inference_diff,
+ inference_vs_variant2_rel=inference_rel,
+ training_vs_variant2_max_abs=training_diff,
+ inference_vs_training_max_abs=max(inference_diff, training_diff),
+ )
+
+
+def _result(harness, rows):
+ verdict = harness._evaluate_rows(rows)
+ return {
+ "rows": [row.__dict__ for row in rows],
+ "packed_inference_rows": sum(row.inference_packed_for_cpu for row in rows),
+ "packed_training_rows": sum(row.training_packed_for_cpu for row in rows),
+ "training_control_exact": all(
+ row.training_vs_variant2_max_abs == 0.0 for row in rows
+ ),
+ **verdict,
+ }
+
+
+def test_cpu_recorded_shapes_and_m_grid_are_pinned():
+ harness = _load_harness()
+ assert harness.FIXTURE_SHAPES == ((64, 64), (256, 64))
+ assert harness.M_VALUES == (8, 16, 32, 64, 128, 256)
+
+
+def test_real_row_uses_shipped_variant2_and_exact_training_control(monkeypatch):
+ pytest.importorskip("torch")
+ pytest.importorskip("bitsandbytes")
+
+ harness = _load_harness()
+ import soup_cli.utils.layer_stream_runtime as runtime
+
+ real_install = runtime.install_dequant_forward
+ calls = {"n": 0}
+
+ def counted_install(module):
+ calls["n"] += 1
+ return real_install(module)
+
+ monkeypatch.setattr(runtime, "install_dequant_forward", counted_install)
+ row = harness.measure_row(64, 64, 8, seed=3)
+
+ assert calls["n"] == 1
+ assert row.training_packed_for_cpu is False
+ assert row.training_vs_variant2_max_abs == 0.0
+ assert row.variant2_max_abs > 0.0
+ # One bf16 rounding of input, weight and output: a few 1e-3 relative, never 0.
+ assert 1e-3 < row.emulated_bf16_rel < harness.PACKED_EFFECT_REL_ENVELOPE
+ assert row.emulated_bf16_rel == pytest.approx(
+ row.emulated_bf16_vs_variant2_max_abs / row.variant2_max_abs
+ )
+
+
+def test_nf4_fixture_uses_double_quant():
+ torch = pytest.importorskip("torch")
+ pytest.importorskip("bitsandbytes")
+
+ harness = _load_harness()
+ layer = harness._quantized_linear(
+ torch.randn(64, 64, dtype=torch.float32),
+ compute_dtype=torch.float32,
+ )
+ assert layer.weight.quant_state.nested is True
+
+
+def test_measure_row_requires_eval_inference_and_reports_packing(monkeypatch):
+ torch = pytest.importorskip("torch")
+ pytest.importorskip("bitsandbytes")
+
+ harness = _load_harness()
+ import soup_cli.utils.layer_stream_runtime as runtime
+
+ events = []
+
+ class QuantState:
+ packing_format_for_cpu = False
+
+ class Weight:
+ def __init__(self):
+ self.quant_state = QuantState()
+
+ class FakeLayer:
+ def __init__(self):
+ self.training = True
+ self.weight = Weight()
+
+ def train(self):
+ self.training = True
+ events.append("train")
+ return self
+
+ def eval(self):
+ self.training = False
+ events.append("eval")
+ return self
+
+ def __call__(self, x):
+ if not self.training and not x.requires_grad:
+ self.weight.quant_state.packing_format_for_cpu = True
+ return x + 1.0
+ return x
+
+ monkeypatch.setattr(harness, "_quantized_linear", lambda *a, **k: FakeLayer())
+ monkeypatch.setattr(runtime, "install_dequant_forward", lambda _module: 1)
+ monkeypatch.setattr(harness, "_emulated_bf16_reference", lambda _layer, x: x)
+
+ row = harness.measure_row(4, 4, 2, seed=5)
+
+ generator = torch.Generator().manual_seed(harness._row_seed(5, 4, 4, 2))
+ torch.randn((4, 4), generator=generator, dtype=torch.float32)
+ x = torch.randn((2, 4), generator=generator, dtype=torch.float32)
+ expected_max = float(x.abs().max())
+
+ assert "eval" in events
+ assert row.inference_packed_for_cpu is True
+ assert row.training_packed_for_cpu is False
+ assert row.training_vs_variant2_max_abs == 0.0
+ assert row.variant2_max_abs == pytest.approx(expected_max)
+ assert row.inference_vs_variant2_max_abs == 1.0
+ assert row.inference_vs_variant2_rel == pytest.approx(1.0 / expected_max)
+
+
+def test_run_probe_counts_inference_packed_not_training_packed(monkeypatch):
+ pytest.importorskip("torch")
+ pytest.importorskip("bitsandbytes")
+ harness = _load_harness()
+
+ monkeypatch.setattr(
+ harness,
+ "measure_row",
+ lambda out_features, in_features, m: _row(
+ harness,
+ inference_packed=True,
+ training_packed=False,
+ inference_diff=1.0,
+ ),
+ )
+ result = harness.run_probe(
+ m_values=(8, 32),
+ shapes=((64, 64),),
+ )
+ assert result["packed_inference_rows"] == 2
+ assert result["packed_training_rows"] == 0
+ assert result["verdict"] == "mechanism_reproduced"
+
+
+ "case,expected_code,expected_verdict",
+ [
+ ("absent", 2, "mechanism_absent"),
+ ("training_packed", 3, "control_failed"),
+ ("training_diff", 3, "control_failed"),
+ ("packed_no_diff", 4, "packed_effect_absent"),
+ ("packed_too_large", 5, "packed_effect_out_of_range"),
+ ("success", 0, "mechanism_reproduced"),
+ ],
+)
+def test_main_pins_every_gate_exit_code(
+ monkeypatch,
+ capsys,
+ case,
+ expected_code,
+ expected_verdict,
+):
+ harness = _load_harness()
+
+ if case == "absent":
+ row_list = [_row(harness)]
+ elif case == "training_packed":
+ row_list = [
+ _row(
+ harness,
+ inference_packed=True,
+ training_packed=True,
+ inference_diff=1.0,
+ )
+ ]
+ elif case == "training_diff":
+ row_list = [
+ _row(
+ harness,
+ inference_packed=True,
+ inference_diff=1.0,
+ training_diff=0.25,
+ )
+ ]
+ elif case == "packed_no_diff":
+ row_list = [_row(harness, inference_packed=True)]
+ elif case == "packed_too_large":
+ row_list = [_row(harness, inference_packed=True, inference_diff=3.0)]
+ else:
+ row_list = [
+ _row(
+ harness,
+ inference_packed=True,
+ inference_diff=1.0,
+ )
+ ]
+
+ result = _result(harness, row_list)
+ monkeypatch.setattr(harness, "run_probe", lambda: result)
+
+ code = harness.main([])
+ captured = capsys.readouterr()
+ payload = json.loads(captured.out)
+
+ assert code == expected_code
+ assert payload["exit_code"] == expected_code
+ assert payload["verdict"] == expected_verdict
+ if expected_code:
+ assert captured.err.strip() == payload["reason"]
+ else:
+ assert captured.err == ""
+
+
+def test_survey_is_explicit_opt_out_of_missing_capability_only(monkeypatch, capsys):
+ harness = _load_harness()
+ result = _result(harness, [_row(harness)])
+ assert result["exit_code"] == harness.EXIT_MECHANISM_ABSENT
+ monkeypatch.setattr(harness, "run_probe", lambda: result)
+
+ assert harness.main(["--survey"]) == 0
+ captured = capsys.readouterr()
+ assert json.loads(captured.out)["verdict"] == "mechanism_absent"
+ assert captured.err == ""
+
+
+def test_survey_does_not_waive_a_broken_control(monkeypatch, capsys):
+ harness = _load_harness()
+ result = _result(harness, [_row(harness, training_diff=0.25)])
+ assert result["exit_code"] == harness.EXIT_CONTROL_FAILED
+ monkeypatch.setattr(harness, "run_probe", lambda: result)
+
+ assert harness.main(["--survey"]) == harness.EXIT_CONTROL_FAILED
+ captured = capsys.readouterr()
+ assert json.loads(captured.out)["verdict"] == "control_failed"
+ assert captured.err.strip() == result["reason"]
+
+
+def test_json_schema_carries_verdict_and_attribution():
+ harness = _load_harness()
+ rows = [
+ _row(
+ harness,
+ inference_packed=True,
+ inference_diff=1.0,
+ )
+ ]
+ verdict = harness._evaluate_rows(rows)
+ assert verdict == {
+ "verdict": "mechanism_reproduced",
+ "exit_code": 0,
+ "reason": (
+ "every packed row differs from Soup variant 2 within the 2% "
+ "rounding-scale envelope while the training control is exact."
+ ),
+ "attribution": (
+ "bitsandbytes packed CPU inference path; exact lower-level kernel "
+ "reported separately"
+ ),
+ }
+
+
+def test_loader_does_not_leak_dynamic_module_registration():
+ _load_harness()
+ assert "_fixture_window_cpu_test_module" not in sys.modules
+
+
+def test_script_documents_avx512_and_kernels_attribution_boundary():
+ source = HARNESS.read_text(encoding="utf-8")
+ assert "AVX512-BF16 is required" in source
+ assert "kernels-community/quantization-bitsandbytes" in source
+ assert "best-effort lower-level kernel attribution" in source
+
+
+def test_control_is_checked_on_every_row_before_capability():
+ harness = _load_harness()
+ rows = [
+ _row(harness),
+ _row(harness, training_diff=0.125),
+ ]
+ verdict = harness._evaluate_rows(rows)
+ assert verdict["verdict"] == "control_failed"
+ assert verdict["exit_code"] == harness.EXIT_CONTROL_FAILED
+
+
+def test_packed_effect_must_exist_on_every_packed_row():
+ harness = _load_harness()
+ rows = [
+ _row(harness, inference_packed=True, inference_diff=1.0),
+ _row(harness, inference_packed=True, inference_diff=0.0),
+ ]
+ verdict = harness._evaluate_rows(rows)
+ assert verdict["verdict"] == "packed_effect_absent"
+
+
+def test_packed_effect_must_stay_inside_relative_envelope_on_every_row():
+ harness = _load_harness()
+ rows = [
+ _row(harness, inference_packed=True, inference_diff=1.0),
+ _row(harness, inference_packed=True, inference_diff=3.0),
+ ]
+ verdict = harness._evaluate_rows(rows)
+ assert verdict["verdict"] == "packed_effect_out_of_range"
+ assert verdict["exit_code"] == harness.EXIT_EFFECT_OUT_OF_RANGE
+
+
+def test_default_run_probe_visits_the_complete_recorded_grid(monkeypatch):
+ pytest.importorskip("torch")
+ pytest.importorskip("bitsandbytes")
+ harness = _load_harness()
+ seen = []
+
+ def fake_measure(out_features, in_features, m):
+ seen.append((out_features, in_features, m))
+ return _row(harness)
+
+ monkeypatch.setattr(harness, "measure_row", fake_measure)
+ result = harness.run_probe()
+ expected = {
+ (out_features, in_features, m)
+ for out_features, in_features in harness.FIXTURE_SHAPES
+ for m in harness.M_VALUES
+ }
+ assert set(seen) == expected
+ assert len(seen) == len(expected) == 12
+ assert len(result["rows"]) == 12
+
+
+def test_measure_row_refuses_when_variant2_patch_does_not_apply(monkeypatch):
+ pytest.importorskip("torch")
+ harness = _load_harness()
+ import soup_cli.utils.layer_stream_runtime as runtime
+
+ monkeypatch.setattr(harness, "_quantized_linear", lambda *a, **k: object())
+ monkeypatch.setattr(runtime, "install_dequant_forward", lambda _module: 0)
+ with pytest.raises(RuntimeError, match="patched 0 layers, expected 1"):
+ harness.measure_row(64, 64, 8)
+
+
+def test_harness_source_has_no_model_or_dataset_download_calls():
+ source = HARNESS.read_text(encoding="utf-8")
+ forbidden = ("from_pretrained(", "load_dataset(", "hf_hub_download(", "requests.")
+ assert not any(token in source for token in forbidden)
+
+
+ ("scale", "expected_code"),
+ [
+ (3.0, 5),
+ (1.001, 0),
+ ],
+)
+def test_real_measurement_drives_relative_envelope(
+ monkeypatch, scale, expected_code
+):
+ pytest.importorskip("torch")
+ pytest.importorskip("bitsandbytes")
+ harness = _load_harness()
+ import soup_cli.utils.layer_stream_runtime as runtime
+
+ class QuantState:
+ packing_format_for_cpu = False
+
+ class Weight:
+ def __init__(self):
+ self.quant_state = QuantState()
+
+ class FakeLayer:
+ def __init__(self):
+ self.training = True
+ self.weight = Weight()
+
+ def train(self):
+ self.training = True
+ return self
+
+ def eval(self):
+ self.training = False
+ return self
+
+ def __call__(self, x):
+ if not self.training and not x.requires_grad:
+ self.weight.quant_state.packing_format_for_cpu = True
+ return x * scale
+ return x
+
+ monkeypatch.setattr(harness, "_quantized_linear", lambda *a, **k: FakeLayer())
+ monkeypatch.setattr(runtime, "install_dequant_forward", lambda _module: 1)
+ monkeypatch.setattr(harness, "_emulated_bf16_reference", lambda _layer, x: x)
+
+ row = harness.measure_row(4, 4, 2, seed=11)
+ verdict = harness._evaluate_rows([row])
+ assert verdict["exit_code"] == expected_code
+ if expected_code == 0:
+ assert row.inference_vs_variant2_rel == pytest.approx(0.001, rel=1e-4)
+ else:
+ assert row.inference_vs_variant2_rel == pytest.approx(2.0)
+
+
+def test_envelope_boundary_is_pinned_exactly():
+ harness = _load_harness()
+ at_limit = _row(
+ harness,
+ inference_packed=True,
+ inference_diff=2.0,
+ variant2_abs=100.0,
+ inference_rel=harness.PACKED_EFFECT_REL_ENVELOPE,
+ )
+ over_limit = _row(
+ harness,
+ inference_packed=True,
+ inference_diff=2.0001,
+ variant2_abs=100.0,
+ inference_rel=harness.PACKED_EFFECT_REL_ENVELOPE + 1e-6,
+ )
+ assert harness._evaluate_rows([at_limit])["exit_code"] == harness.EXIT_OK
+ assert (
+ harness._evaluate_rows([over_limit])["exit_code"]
+ == harness.EXIT_EFFECT_OUT_OF_RANGE
+ )
+
+
+def test_run_probe_publishes_emulated_bf16_margin(monkeypatch):
+ pytest.importorskip("torch")
+ pytest.importorskip("bitsandbytes")
+ harness = _load_harness()
+ rows = iter(
+ [
+ _row(harness, emulated_bf16_rel=0.003),
+ _row(harness, emulated_bf16_rel=0.0048),
+ ]
+ )
+ monkeypatch.setattr(harness, "measure_row", lambda *a, **k: next(rows))
+
+ result = harness.run_probe(m_values=(8, 16), shapes=((64, 64),))
+ assert result["emulated_bf16_worst_rel"] == pytest.approx(0.0048)
+ assert result["packed_effect_rel_envelope"] == 0.02
+ assert result["envelope_over_emulated_worst"] == pytest.approx(
+ 0.02 / 0.0048
+ )
+ assert (
+ result["packed_effect_rel_envelope"]
+ > result["emulated_bf16_worst_rel"]
+ )
+
+
+def test_row_seed_uses_full_tuple_and_breaks_old_collision():
+ harness = _load_harness()
+ # The old seed + out_features + m formula collides for these two rows.
+ assert 64 + 256 == 256 + 64
+ left = harness._row_seed(17, 64, 64, 256)
+ right = harness._row_seed(17, 256, 64, 64)
+ assert left != right
+
+
+def test_one_packed_training_row_fails_even_next_to_clean_row():
+ harness = _load_harness()
+ rows = [
+ _row(harness, training_packed=True),
+ _row(harness, training_packed=False),
+ ]
+ verdict = harness._evaluate_rows(rows)
+ assert verdict["exit_code"] == harness.EXIT_CONTROL_FAILED
+
+
+def test_cpu_kernel_attribution_states(monkeypatch):
+ pytest.importorskip("bitsandbytes")
+ import bitsandbytes.backends.cpu.ops as cpu_ops
+
+ harness = _load_harness()
+ monkeypatch.setattr(harness, "_cpu_gemv_registered", lambda: False)
+ monkeypatch.delattr(cpu_ops, "gemm_4bit_forward_kernel", raising=False)
+ assert harness._cpu_packed_kernel_attribution() == "not-registered"
+
+ monkeypatch.setattr(cpu_ops, "gemm_4bit_forward_kernel", None, raising=False)
+ assert (
+ harness._cpu_packed_kernel_attribution()
+ == "native-bitsandbytes-cpu-gemv"
+ )
+
+ monkeypatch.setattr(
+ cpu_ops,
+ "gemm_4bit_forward_kernel",
+ lambda *a, **k: None,
+ raising=False,
+ )
+ assert harness._cpu_packed_kernel_attribution() == "kernels-community"
+
+
+def test_run_probe_reports_kernel_attribution_fields(monkeypatch):
+ pytest.importorskip("torch")
+ pytest.importorskip("bitsandbytes")
+ harness = _load_harness()
+ monkeypatch.setattr(
+ harness,
+ "measure_row",
+ lambda *a, **k: _row(harness),
+ )
+ monkeypatch.setattr(
+ harness, "_cpu_packed_kernel_attribution", lambda: "not-registered"
+ )
+ monkeypatch.setattr(harness, "_cpu_gemv_registered", lambda: False)
+
+ result = harness.run_probe(m_values=(8,), shapes=((64, 64),))
+ assert result["cpu_packed_kernel"] == "not-registered"
+ assert result["cpu_gemv_4bit_registered"] is False
+
+
+def test_real_avx512_host_runs_default_gate_when_available(capsys):
+ functional = pytest.importorskip("bitsandbytes.functional")
+ if not functional.has_avx512bf16():
+ pytest.skip("requires an AVX512-BF16 host")
+
+ harness = _load_harness()
+ code = harness.main([])
+ captured = capsys.readouterr()
+ payload = json.loads(captured.out)
+ with capsys.disabled():
+ print(captured.out)
+ assert payload["has_avx512bf16"] is True
+ assert payload["packed_inference_rows"] > 0
+ assert code == harness.EXIT_OK