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 depth versus bytes reconstruction (#1287)
Samarth Mukhija7ffb10f4dfd8
diff --git a/benchmarks/README.md b/benchmarks/README.mdindex 62f8d503..64968263 100644--- a/benchmarks/README.md+++ b/benchmarks/README.md@@ -113,6 +113,7 @@ only in a scratchpad on a machine that is gone, which is| [`ab_burn_in_sweep.py`](harness/ab_burn_in_sweep.py) | [#1227](https://github.com/MakazhanAlpamys/Soup/issues/1227) / [`gate-1227-ab-burn-in.md`](gate-1227-ab-burn-in.md) | What false-positive rate does `soup ab`'s burn-in leave when the test is re-run after every new pair? A vectorised H0 simulation of the shipped statistic, checked against `_verdict_from_summary` first, by effect_size / sigma, burn-in, alpha and horizon; picks `BURN_IN_ROWS_BY_ALPHA` | CPU + numpy; ~55 s per ratio at 100,000 runs over 1000 rows; `run` writes JSON parts, `report` merges them || [`head_prefetch_ab.py`](harness/head_prefetch_ab.py) | [#1174](https://github.com/MakazhanAlpamys/Soup/issues/1174) / [#1258](https://github.com/MakazhanAlpamys/Soup/pull/1258) | Interleaved A/B, in one process on one model, of where the output head's load into the shared large-layer slot is issued: `StreamPrefetcher.head_prefetch_layer` at `None` (the last decoder layer, the original timing) against a chosen layer (`0`, right after the embedding lookup). Judges each arm by the step's TOTAL wait from the committed `stream_probe.Instruments` brackets, plus per-group medians (embedding, head, layer 0, other decoder layers), since a decoder entry behind the head on the copy stream can get worse while the head's own entry improves. Covers both tiers, `--read-ahead`, and a `--step-shape preference` (a no-grad forward first) for the disk-tier case where the reader's queue gets replanned. Refuses to run on a tree without `head_prefetch_layer` instead of comparing an arm with itself; the JSON records `soup_cli_file` and `git_sha`, the tree it measured | CUDA GPU; model weights; a few minutes per arm pair || [`determinism.py`](harness/determinism.py) | STEP 2b / Measurements 1-2 | Historical reconstruction that measures forward, backward repetitions 1 and 3, and trained loss-curve reproducibility in-process against a resident NF4 reference; optional JSON replay remains separate from measurement | CUDA measurement requires the recorded H100-class stack and checkpoint; CPU tests cover the real measurement and invalid-measurement guards; empty overlap, non-finite values, missing measurements, or absent asymmetry fail |+| [`depth_vs_bytes.py`](harness/depth_vs_bytes.py) | STEP 6 / NF4 bytes-per-layer bracket | Historical reconstruction of the fixed 48-layer synthetic-Llama sweep: all three NF4 reads at or below 163.8 MiB/layer must be exact, later reads at or above 171.5 MiB/layer must be wrong, and the bf16 control above the bracket must remain exact | `--measure` creates local synthetic checkpoints and needs CUDA plus the historical torch/bitsandbytes stack; JSON replay and CPU verdict tests do not require CUDA; no CUDA measurement is claimed by the index || [`ab_nig_sweep.py`](harness/ab_nig_sweep.py) | [#1265](https://github.com/MakazhanAlpamys/Soup/issues/1265) / [`gate-1265-ab-nig.md`](gate-1265-ab-nig.md) | Type-I and power of `soup ab`'s NIG mixture under a peek after every pair, side by side with the #1227 burn-in design, by effect_size / sigma, held-out rows, alpha and horizon; checked against `_nig_log_bayes_factor` and `msprt_step` first; picks `PRIOR_SCALE_ROWS` | CPU + numpy; ~350 s per ratio at 100,000 H0 runs over 1000 rows; `run --mode h0/h1` writes JSON parts, `report` merges them || [`ab_cs_accept_sweep.py`](harness/ab_cs_accept_sweep.py) | [#1418](https://github.com/MakazhanAlpamys/Soup/issues/1418) / [`gate-1418-ab-cs-accept.md`](gate-1418-ab-cs-accept.md) | Time to `accept_h0` under H0 and wrong `accept_h0` under H1 for `soup ab`'s confidence-sequence accept rule against #1265's, at level beta or alpha and with or without the accept hold; replays #1265's seeded runs and checks its counts against that record; checked against `_nig_confidence_half_width` and `msprt_step` first | CPU + numpy; ~430-600 s per ratio at 100,000 H0 runs over 1000 rows; `run --mode h0/h1` writes JSON parts, `report` merges them, `check` re-runs only the self-check || [`fp8_block_quantize.py`](harness/fp8_block_quantize.py) | [`gate-fp8-shard.md`](gate-fp8-shard.md) G1-G3 | Converts a bf16 DeepSeek-V3-family checkpoint to the FP8 block format it is published in (`float8_e4m3fn` + `weight_scale_inv` per 128 x 128 block, ragged edges as DeepSeek has them), one tensor at a time, and reports each tensor's dequant error against its bf16 original. Also the quantiser the FP8 tests use | CPU; Moonlight-16B-A3B: 76 s, 2.5 GB peak RSS, 16.6 GB written |diff --git a/benchmarks/harness/depth_vs_bytes.py b/benchmarks/harness/depth_vs_bytes.pynew file mode 100644index 00000000..3c48d1a4--- /dev/null+++ b/benchmarks/harness/depth_vs_bytes.py@@ -0,0 +1,327 @@+#!/usr/bin/env python3+"""Check STEP 6's NF4 per-layer-byte threshold reconstruction.++The record brackets the transition between 163.8 and 171.5 MiB per NF4 layer:+below the bracket is exact, above it is wrong, while bf16 controls remain+exact. The live mode reconstructs the recorded synthetic checkpoints; the+constants in the verdict remain boundaries from the historical record.+"""++from __future__ import annotations++import argparse+import json+import math+import sys+from pathlib import Path+from typing import Any++NF4_EXACT_MAX_MIB = 163.8+NF4_WRONG_MIN_MIB = 171.5+++class MeasurementInvalidError(RuntimeError):+ """The depth/bytes data is not a valid measurement."""+++def depth_vs_bytes_verdict(samples: list[dict[str, Any]]) -> bool:+ if len(samples) < 3:+ return False+ below = False+ above = False+ bf16_control = False+ for sample in samples:+ quant = sample.get("quant")+ mib = sample.get("layer_mib")+ exact_counts = sample.get("exact_counts")+ total = sample.get("total")+ depth = sample.get("depth")+ if not isinstance(depth, int) or depth <= 0:+ raise MeasurementInvalidError("depth must be a positive integer")+ if quant not in {"nf4", "bf16"}:+ raise MeasurementInvalidError("quant must be nf4 or bf16")+ if not isinstance(mib, (int, float)) or not math.isfinite(mib) or mib <= 0:+ raise MeasurementInvalidError("layer_mib must be finite and positive")+ if not isinstance(total, int) or total <= 0:+ raise MeasurementInvalidError("total must be a positive integer")+ if not isinstance(exact_counts, list) or len(exact_counts) != 3:+ raise MeasurementInvalidError("exact_counts must contain three reads")+ if any(not isinstance(exact, int) or exact < 0 or exact > total for exact in exact_counts):+ raise MeasurementInvalidError("exact count is out of range")+ all_exact = all(exact == total for exact in exact_counts)+ later_wrong = any(exact < total for exact in exact_counts[1:])+ if quant == "nf4" and mib <= NF4_EXACT_MAX_MIB:+ below = True+ if not all_exact:+ return False+ if quant == "nf4" and mib >= NF4_WRONG_MIN_MIB:+ above = True+ if not later_wrong:+ return False+ if quant == "bf16":+ if not all_exact:+ return False+ if mib >= NF4_WRONG_MIN_MIB:+ bf16_control = True+ return below and above and bf16_control+++def measure_synthetic_sweep(*, intermediate_sizes: list[int], measure) -> list[dict[str, Any]]:+ """Measure the fixed-depth NF4 sweep and one bf16 control."""+ if len(set(intermediate_sizes)) < 2:+ raise MeasurementInvalidError("the sweep needs at least two layer sizes")+ rows = []+ for intermediate_size in intermediate_sizes:+ row = dict(+ measure(+ depth=48,+ intermediate_size=intermediate_size,+ quant="nf4",+ )+ )+ row.update(depth=48, intermediate_size=intermediate_size, quant="nf4")+ rows.append(row)++ control_size = max(intermediate_sizes)+ control = dict(+ measure(+ depth=32,+ intermediate_size=control_size,+ quant="bf16",+ )+ )+ control.update(depth=32, intermediate_size=control_size, quant="bf16")+ rows.append(control)+ return rows+++def _measure_checkpoint(weights: str, shards: str, quant: str) -> dict[str, Any]:+ """Run three streamed backwards against one resident reference."""+ import bitexact+ import torch+ from mechanism_cost import (+ build_streamed_arm,+ gradient_snapshot,+ make_input,+ prepare_shards,+ run_backward,+ )++ from soup_cli.utils.layer_shard import shard_checkpoint+ from soup_cli.utils.layer_stream_runtime import (+ assert_canonical_parameters_intersect,+ build_meta_skeleton,+ build_streamed_model,+ )++ def restore() -> None:+ return None++ if quant == "nf4":+ index, arch = prepare_shards(weights, shards)+ streamed, runtime, restore = build_streamed_arm(weights, shards, index, arch, "control", 2)+ else:+ runtime_quant = "none"+ probe = build_meta_skeleton(weights, dtype="bfloat16", quant=runtime_quant)+ arch = bitexact.model_arch_name(probe)+ del probe+ index = shard_checkpoint(+ weights,+ shards,+ dtype="bfloat16",+ arch=arch,+ quant=runtime_quant,+ quant_suffixes=(),+ double_quant=True,+ quant_device="cuda",+ )+ streamed, runtime = build_streamed_model(+ model_id=weights,+ shard_dir=shards,+ index=index,+ lora_config=bitexact.lora_config(),+ device="cuda",+ dtype="bfloat16",+ buffers=2,+ pin=True,+ seed=3,+ quant=runtime_quant,+ double_quant=True,+ tier="ram",+ )++ reference = None+ try:+ reference = bitexact.load_resident_reference(weights, quant)+ bitexact.make_non_vacuous_lora(streamed)+ bitexact.copy_lora(streamed, reference)+ assert_canonical_parameters_intersect(streamed, reference)+ input_ids = make_input(reference, seq=128, batch=1)+ reference_loss = run_backward(reference, input_ids)+ reference_grads = gradient_snapshot(reference)+ if (+ not math.isfinite(reference_loss)+ or not reference_grads+ or any(not torch.isfinite(value).all() for value in reference_grads.values())+ ):+ raise MeasurementInvalidError("resident measurement is empty or non-finite")+ exact_counts = []+ for _ in range(3):+ loss = run_backward(streamed, input_ids)+ current = gradient_snapshot(streamed)+ if not math.isfinite(loss) or loss != reference_loss:+ raise MeasurementInvalidError("streamed loss differs from resident")+ if set(current) != set(reference_grads):+ raise MeasurementInvalidError("gradient parameter sets differ")+ if any(not torch.isfinite(value).all() for value in current.values()):+ raise MeasurementInvalidError("streamed gradients are non-finite")+ exact_counts.append(+ sum(torch.equal(current[name], reference_grads[name]) for name in current)+ )+ store_bytes = getattr(getattr(runtime, "source", None), "nbytes", 0)+ layers = getattr(index, "n_layers", 0)+ if store_bytes <= 0 or layers <= 0:+ raise MeasurementInvalidError("streaming store size is unavailable")+ return {+ "layer_mib": store_bytes / layers / (1024 * 1024),+ "exact_counts": exact_counts,+ "total": len(reference_grads),+ }+ finally:+ if reference is not None:+ del reference+ try:+ runtime.close()+ finally:+ restore()+ del streamed+ torch.cuda.empty_cache()+++def run_live_sweep(work_dir: Path) -> list[dict[str, Any]]:+ """Create the recorded synthetic shapes and measure both numeric paths."""+ import subprocess++ intermediate_sizes = [13824, 15360, 17408, 18432, 19456, 20480, 27648]+ script = Path(__file__).with_name("synth_checkpoint.py")++ def measure(*, depth: int, intermediate_size: int, quant: str):+ checkpoint = work_dir / f"llama-{depth}-{intermediate_size}"+ shards = work_dir / f"shards-{depth}-{intermediate_size}-{quant}"+ if not checkpoint.exists():+ subprocess.run(+ [+ sys.executable,+ str(script),+ "--out",+ str(checkpoint),+ "--shape",+ "qwen2.5-14b",+ "--arch",+ "llama",+ "--layers",+ str(depth),+ "--hidden",+ "5120",+ "--intermediate",+ str(intermediate_size),+ "--heads",+ "40",+ "--kv-heads",+ "10",+ "--vocab",+ "1024",+ ],+ check=True,+ )+ shards.mkdir(parents=True, exist_ok=True)+ return _measure_checkpoint(str(checkpoint), str(shards), quant)++ return measure_synthetic_sweep(+ intermediate_sizes=intermediate_sizes,+ measure=measure,+ )+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(description="Check the STEP 6 depth-vs-bytes sweep.")+ parser.add_argument("--records", type=Path, help="JSON array of measured sweep rows")+ parser.add_argument("--measure", action="store_true", help="run the synthetic CUDA sweep")+ parser.add_argument("--work-dir", type=Path, default=Path("./depth-vs-bytes-work"))+ parser.add_argument("--self-test", action="store_true")+ return parser.parse_args()+++def run_self_test() -> int:+ assert depth_vs_bytes_verdict(+ [+ {+ "depth": 48,+ "quant": "nf4",+ "layer_mib": 163.8,+ "exact_counts": [192] * 3,+ "total": 192,+ },+ {+ "depth": 48,+ "quant": "nf4",+ "layer_mib": 171.5,+ "exact_counts": [192, 8, 8],+ "total": 192,+ },+ {+ "depth": 32,+ "quant": "bf16",+ "layer_mib": 935.0,+ "exact_counts": [192] * 3,+ "total": 192,+ },+ ]+ )+ print("PASS: depth-vs-bytes verdict requires both NF4 sides and bf16 control")+ return 0+++def main() -> int:+ args = parse_args()+ if args.self_test:+ return run_self_test()+ if args.measure:+ import torch++ if not torch.cuda.is_available():+ print("SKIP: CUDA is required for the synthetic measurement")+ return 0+ try:+ samples = run_live_sweep(args.work_dir.expanduser().resolve())+ print(json.dumps(samples, indent=2, sort_keys=True))+ if depth_vs_bytes_verdict(samples):+ print("RESULT: historical depth-vs-bytes relationship reproduced")+ return 0+ print("ERROR: historical depth-vs-bytes relationship not reproduced")+ return 1+ except (MeasurementInvalidError, RuntimeError, ValueError) as exc:+ print(f"ERROR: invalid measurement: {exc}")+ return 3+ if args.records is None:+ print("ERROR: --records is required; no CUDA measurement was performed")+ return 2+ try:+ samples = json.loads(args.records.read_text(encoding="utf-8"))+ if not isinstance(samples, list):+ raise MeasurementInvalidError("records must be a JSON array")+ if not depth_vs_bytes_verdict(samples):+ print("ERROR: historical depth-vs-bytes relationship not reproduced")+ return 1+ print("RESULT: historical depth-vs-bytes relationship reproduced")+ return 0+ except MeasurementInvalidError as exc:+ print(f"ERROR: invalid measurement: {exc}")+ return 3+ except (OSError, json.JSONDecodeError, TypeError) as exc:+ print(f"ERROR: invalid records: {exc}")+ return 2+++if __name__ == "__main__":+ sys.exit(main())diff --git a/benchmarks/harness/synth_checkpoint.py b/benchmarks/harness/synth_checkpoint.pyindex e15c670b..613f00c1 100644--- a/benchmarks/harness/synth_checkpoint.py+++ b/benchmarks/harness/synth_checkpoint.py@@ -77,6 +77,12 @@ def parse_args() -> argparse.Namespace:help="architecture to write: llama (no attention biases) or qwen2 (q/k/v biases)",)parser.add_argument("--layers", type=int, default=None, help="override the layer count")+ parser.add_argument("--hidden", type=int, default=None, help="override the hidden size")+ parser.add_argument(+ "--intermediate", type=int, default=None, help="override the MLP intermediate size"+ )+ parser.add_argument("--heads", type=int, default=None, help="override attention heads")+ parser.add_argument("--kv-heads", type=int, default=None, help="override key/value heads")parser.add_argument("--vocab",type=int,@@ -187,6 +193,14 @@ def main() -> int:shape = dict(SHAPES[args.shape])if args.layers is not None:shape["layers"] = int(args.layers)+ if args.hidden is not None:+ shape["hidden"] = int(args.hidden)+ if args.intermediate is not None:+ shape["intermediate"] = int(args.intermediate)+ if args.heads is not None:+ shape["heads"] = int(args.heads)+ if args.kv_heads is not None:+ shape["kv_heads"] = int(args.kv_heads)if args.vocab is not None:shape["vocab"] = int(args.vocab)out = Path(args.out)diff --git a/tests/test_issue379_depth_vs_bytes.py b/tests/test_issue379_depth_vs_bytes.pynew file mode 100644index 00000000..8a83dc98--- /dev/null+++ b/tests/test_issue379_depth_vs_bytes.py@@ -0,0 +1,228 @@+from argparse import Namespace++import pytest++from benchmarks.harness.depth_vs_bytes import (+ MeasurementInvalidError,+ depth_vs_bytes_verdict,+ measure_synthetic_sweep,+ run_self_test,+)+++def recorded_rows():+ return [+ {+ "depth": 48,+ "quant": "nf4",+ "layer_mib": 163.8,+ "exact_counts": [192] * 3,+ "total": 192,+ },+ {+ "depth": 48,+ "quant": "nf4",+ "layer_mib": 171.5,+ "exact_counts": [192, 8, 8],+ "total": 192,+ },+ {+ "depth": 32,+ "quant": "bf16",+ "layer_mib": 935.0,+ "exact_counts": [128] * 3,+ "total": 128,+ },+ ]+++def test_recorded_threshold_pattern_passes():+ assert depth_vs_bytes_verdict(recorded_rows())+++def test_every_nf4_point_below_boundary_must_be_exact():+ rows = recorded_rows()+ rows.append(+ {+ "depth": 48,+ "quant": "nf4",+ "layer_mib": 105.0,+ "exact_counts": [192, 8, 8],+ "total": 192,+ }+ )+ assert not depth_vs_bytes_verdict(rows)+++def test_every_nf4_point_above_boundary_must_be_wrong_after_first_read():+ rows = recorded_rows()+ rows.append(+ {+ "depth": 48,+ "quant": "nf4",+ "layer_mib": 432.0,+ "exact_counts": [192] * 3,+ "total": 192,+ }+ )+ assert not depth_vs_bytes_verdict(rows)+++def test_bf16_control_must_be_exact_and_above_boundary():+ rows = recorded_rows()+ rows[-1]["exact_counts"] = [128, 8, 8]+ assert not depth_vs_bytes_verdict(rows)++ rows = recorded_rows()+ rows[-1]["layer_mib"] = 1.0+ assert not depth_vs_bytes_verdict(rows)+++def test_empty_and_nonfinite_measurements_fail():+ assert not depth_vs_bytes_verdict([])+ rows = recorded_rows()+ rows[0]["layer_mib"] = float("inf")+ with pytest.raises(MeasurementInvalidError, match="finite"):+ depth_vs_bytes_verdict(rows)+++def test_self_test_pins_recorded_boundaries():+ assert run_self_test() == 0+++def test_measurement_sweep_requires_distinct_layer_sizes():+ with pytest.raises(MeasurementInvalidError, match="two layer sizes"):+ measure_synthetic_sweep(intermediate_sizes=[13824, 13824], measure=lambda **_: {})+++def test_measurement_sweep_holds_nf4_depth_fixed_and_includes_recorded_bf16_control():+ calls = []++ def measure(**kwargs):+ calls.append(kwargs)+ return {"layer_mib": 1.0, "exact_counts": [192] * 3, "total": 192}++ rows = measure_synthetic_sweep(intermediate_sizes=[13824, 18432], measure=measure)+ assert {row["quant"] for row in rows} == {"nf4", "bf16"}+ assert [call["quant"] for call in calls] == ["nf4", "nf4", "bf16"]+ assert all(call["depth"] == 48 for call in calls[:2])+ assert calls[-1] == {"depth": 32, "intermediate_size": 18432, "quant": "bf16"}+ assert len(rows) == 3+++def test_live_sweep_builds_recorded_shapes(tmp_path, monkeypatch):+ from benchmarks.harness import depth_vs_bytes++ generated = []+ measured = []++ def fake_run(command, *, check):+ assert check+ checkpoint = command[command.index("--out") + 1]+ generated.append(command)+ __import__("pathlib").Path(checkpoint).mkdir(parents=True)++ def fake_measure(weights, shards, quant):+ measured.append((weights, shards, quant))+ return {"layer_mib": 200.0, "exact_counts": [1, 0, 0], "total": 1}++ monkeypatch.setattr("subprocess.run", fake_run)+ monkeypatch.setattr(depth_vs_bytes, "_measure_checkpoint", fake_measure)++ rows = depth_vs_bytes.run_live_sweep(tmp_path)++ assert len(generated) == 8+ assert len(rows) == 8+ assert [row["quant"] for row in rows] == ["nf4"] * 7 + ["bf16"]+ assert all(row["depth"] == 48 for row in rows[:7])+ assert rows[-1]["depth"] == 32+ assert rows[-1]["intermediate_size"] == 27648+ assert any("17408" in command for command in generated)+ assert any("18432" in command for command in generated)+ assert len(measured) == 8+++def _row(mib, counts, quant="nf4", depth=48, total=192):+ return {+ "depth": depth,+ "quant": quant,+ "layer_mib": mib,+ "exact_counts": counts,+ "total": total,+ }+++def test_bracket_needs_a_point_on_each_side():+ bf16 = _row(935.0, [128] * 3, quant="bf16", depth=32, total=128)+ no_below = [_row(171.5, [192, 8, 8]), _row(179.3, [8, 8, 8]), bf16]+ assert not depth_vs_bytes_verdict(no_below)+ no_above = [_row(105.0, [192] * 3), _row(163.8, [192] * 3), bf16]+ assert not depth_vs_bytes_verdict(no_above)+++def test_above_bracket_point_must_be_wrong_after_the_first_read():+ rows = recorded_rows()+ rows[1]["exact_counts"] = [8, 192, 192]+ assert not depth_vs_bytes_verdict(rows)+++ ("field", "value", "message"),+ [+ ("depth", 0, "positive integer"),+ ("quant", "fp8", "nf4 or bf16"),+ ("total", 0, "positive integer"),+ ("exact_counts", [192, 192], "three reads"),+ ("exact_counts", [300, 300, 300], "out of range"),+ ],+)+def test_malformed_rows_fail_closed(field, value, message):+ rows = recorded_rows()+ rows[0][field] = value+ with pytest.raises(MeasurementInvalidError, match=message):+ depth_vs_bytes_verdict(rows)+++def test_live_sweep_uses_the_recorded_layer_shape(tmp_path, monkeypatch):+ """The recorded sweep uses hidden 5120 with 40 heads and 10 KV heads."""+ from benchmarks.harness import depth_vs_bytes++ commands = []++ def fake_run(command, *, check):+ assert check+ commands.append(command)+ __import__("pathlib").Path(command[command.index("--out") + 1]).mkdir(parents=True)++ monkeypatch.setattr("subprocess.run", fake_run)+ monkeypatch.setattr(+ depth_vs_bytes,+ "_measure_checkpoint",+ lambda weights, shards, quant: {+ "layer_mib": 200.0,+ "exact_counts": [1, 0, 0],+ "total": 1,+ },+ )+ depth_vs_bytes.run_live_sweep(tmp_path)+ for command in commands:+ assert command[command.index("--heads") + 1] == "40"+ assert command[command.index("--kv-heads") + 1] == "10"++[email protected]("error", [RuntimeError("runtime"), ValueError("setup")])+def test_live_measurement_setup_errors_are_invalid(monkeypatch, tmp_path, error):+ from benchmarks.harness import depth_vs_bytes++ monkeypatch.setattr(+ depth_vs_bytes,+ "parse_args",+ lambda: Namespace(self_test=False, measure=True, work_dir=tmp_path, records=None),+ )+ monkeypatch.setattr("torch.cuda.is_available", lambda: True)+ monkeypatch.setattr(+ depth_vs_bytes,+ "run_live_sweep",+ lambda work_dir: (_ for _ in ()).throw(error),+ )+ assert depth_vs_bytes.main() == 3diff --git a/tests/test_issue379_depth_vs_bytes_measure.py b/tests/test_issue379_depth_vs_bytes_measure.pynew file mode 100644index 00000000..f04ffd78--- /dev/null+++ b/tests/test_issue379_depth_vs_bytes_measure.py@@ -0,0 +1,199 @@+"""CPU tests of depth_vs_bytes._measure_checkpoint() with toy LoRA models.++Only the CUDA and checkpoint boundary is replaced. The production copy,+backward, gradient snapshot, and measurement assertions run on CPU.+"""++import sys+from pathlib import Path+from types import SimpleNamespace++import pytest++torch = pytest.importorskip("torch")+from torch import nn # noqa: E402++HARNESS = Path(__file__).parents[1] / "benchmarks" / "harness"+sys.path.insert(0, str(HARNESS))+import bitexact # noqa: E402+import mechanism_cost # noqa: E402++from benchmarks.harness import depth_vs_bytes as module # noqa: E402++LAYERS = 8+HIDDEN = 16+VOCAB = 64+STORE_BYTES = LAYERS * 123_456+++class _GradScale(torch.autograd.Function):+ """Identity forward, scaled backward: same loss, wrong gradients."""++ @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):+ super().__init__()+ self.base = nn.Linear(HIDDEN, HIDDEN, bias=False).requires_grad_(False)+ self.lora_A = nn.Linear(HIDDEN, 4, bias=False)+ self.lora_B = nn.Linear(4, HIDDEN, bias=False)++ def forward(self, x, factor=None):+ delta = self.lora_B(self.lora_A(x))+ if factor is not None:+ delta = _GradScale.apply(delta, factor)+ return torch.tanh(self.base(x) + delta)+++class _Out:+ def __init__(self, loss):+ self.loss = loss+++class _Toy(nn.Module):+ """wrong_from is the first 1-based backward with corrupted gradients."""++ def __init__(self, wrong_from=None, loss_shift=0.0, grad_factor=3.0):+ super().__init__()+ torch.manual_seed(0)+ self.config = SimpleNamespace(vocab_size=VOCAB)+ self.embed = nn.Embedding(VOCAB, HIDDEN).requires_grad_(False)+ self.layers = nn.ModuleList(_Layer() for _ in range(LAYERS))+ self.head = nn.Linear(HIDDEN, VOCAB, bias=False).requires_grad_(False)+ self.wrong_from = wrong_from+ self.loss_shift = loss_shift+ self.grad_factor = grad_factor+ self.calls = 0++ def forward(self, input_ids, labels):+ self.calls += 1+ wrong = self.wrong_from is not None and self.calls >= self.wrong_from+ x = self.embed(input_ids)+ for index, layer in enumerate(self.layers):+ factor = self.grad_factor if wrong and index < LAYERS - 2 else None+ x = layer(x, factor)+ logits = self.head(x)+ loss = nn.functional.cross_entropy(logits.view(-1, VOCAB), labels.view(-1))+ return _Out(loss + self.loss_shift)+++class _Runtime:+ def __init__(self, nbytes):+ self.source = SimpleNamespace(nbytes=nbytes)+ self.closed = 0++ def close(self):+ self.closed += 1+++def _measure(monkeypatch, streamed, store_bytes=STORE_BYTES):+ runtime = _Runtime(store_bytes)+ restored = []+ arms = []+ monkeypatch.setattr(mechanism_cost, "DEVICE", "cpu")+ monkeypatch.setattr(+ bitexact,+ "make_non_vacuous_lora",+ mechanism_cost.make_non_vacuous_lora,+ )+ monkeypatch.setattr(+ mechanism_cost,+ "prepare_shards",+ lambda weights, shards: (SimpleNamespace(n_layers=LAYERS), "llama"),+ )+ monkeypatch.setattr(+ mechanism_cost,+ "build_streamed_arm",+ lambda weights, shards, index, arch, arm, buffers: (+ arms.append(arm),+ streamed,+ runtime,+ lambda: restored.append(True),+ )[1:],+ )+ monkeypatch.setattr(bitexact, "load_resident_reference", lambda weights, quant: _Toy())+ row = module._measure_checkpoint("weights", "shards", "nf4")+ assert runtime.closed == 1 and restored == [True]+ assert arms == ["control"]+ return row+++def test_later_corruption_is_counted_per_read(monkeypatch):+ row = _measure(monkeypatch, _Toy(wrong_from=2))+ total = row["total"]+ assert total > 0+ assert row["exact_counts"][0] == total+ assert all(count < total for count in row["exact_counts"][1:])+++def test_healthy_streaming_reads_exact_three_times(monkeypatch):+ row = _measure(monkeypatch, _Toy())+ assert row["exact_counts"] == [row["total"]] * 3+++def test_layer_mib_is_store_bytes_per_layer(monkeypatch):+ row = _measure(monkeypatch, _Toy())+ assert row["layer_mib"] == pytest.approx(STORE_BYTES / LAYERS / (1024 * 1024))+++ ("kwargs", "message"),+ [+ ({"wrong_from": 2, "loss_shift": 1.0e-3}, "loss differs"),+ ({"wrong_from": 2, "loss_shift": float("nan")}, "loss differs"),+ ({"wrong_from": 2, "grad_factor": float("inf")}, "non-finite"),+ ],+)+def test_changed_or_nonfinite_measurements_are_invalid(monkeypatch, kwargs, message):+ with pytest.raises(+ (module.MeasurementInvalidError, mechanism_cost.MeasurementInvalidError),+ match=message,+ ):+ _measure(monkeypatch, _Toy(**kwargs))+++def test_missing_store_size_is_invalid(monkeypatch):+ with pytest.raises(module.MeasurementInvalidError, match="store size"):+ _measure(monkeypatch, _Toy(wrong_from=2), store_bytes=0)+++def test_bf16_control_only_asks_the_runtime_for_supported_quants(monkeypatch):+ from soup_cli.utils import layer_shard, layer_stream_runtime++ seen = {}++ class _StopError(Exception):+ pass++ def skeleton(model_id, *, dtype, quant="none", **kwargs):+ seen["build_meta_skeleton"] = quant+ return SimpleNamespace(config=SimpleNamespace(model_type="llama"))++ def shard(weights, shards, *, quant="none", **kwargs):+ seen["shard_checkpoint"] = quant+ return SimpleNamespace(n_layers=LAYERS)++ def build(*, quant="none", **kwargs):+ seen["build_streamed_model"] = quant+ raise _StopError++ monkeypatch.setattr(layer_stream_runtime, "build_meta_skeleton", skeleton)+ monkeypatch.setattr(layer_shard, "shard_checkpoint", shard)+ monkeypatch.setattr(layer_stream_runtime, "build_streamed_model", build)+ with pytest.raises(_StopError):+ module._measure_checkpoint("weights", "shards", "bf16")+ assert set(seen) == {+ "build_meta_skeleton",+ "shard_checkpoint",+ "build_streamed_model",+ }+ for call, quant in seen.items():+ assert quant in layer_shard.SUPPORTED_STREAM_QUANTS, (call, quant)