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 repeated backward reconstruction (#1288)
Samarth Mukhija5e94d57517b9
diff --git a/benchmarks/README.md b/benchmarks/README.mdindex 64968263..9f6e45c1 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 |+| [`repeat_backward.py`](harness/repeat_backward.py) | STEP 2b / Measurement 3 | In-process repeated streamed backwards against one persistent resident NF4 reference; reports the first-pass count and requires later corruption while every loss remains finite and equal to the resident loss | CUDA GPU + real checkpoint files required for live NF4 measurement; seq 128, batch 1, two buffers, five repeats; historical stack: H100 80 GB, torch 2.13.0+cu130, bitsandbytes 0.50.0; CPU tests cover healthy, later-corruption, changed-loss, and invalid-measurement controls || [`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 |diff --git a/benchmarks/harness/repeat_backward.py b/benchmarks/harness/repeat_backward.pynew file mode 100644index 00000000..5cd35606--- /dev/null+++ b/benchmarks/harness/repeat_backward.py@@ -0,0 +1,193 @@+#!/usr/bin/env python3+"""Reconstruct STEP 2b's repeated-backward GRADDIFF measurement.++The recorded 32B NF4 run compared repeated streamed backwards with one+resident NF4 reference. Subsequent backwards disagreed while the loss stayed+equal. The first-backward count varied in the record, so this harness reports+it without requiring exactness. This file is a historical reconstruction, not+a claim that the current repaired runtime reproduces it.+"""++from __future__ import annotations++import argparse+import sys+from pathlib import Path+from typing import Any++import bitexact++HARNESS_DIR = Path(__file__).resolve().parent+sys.path.insert(0, str(HARNESS_DIR))+from mechanism_cost import ( # noqa: E402+ MeasurementInvalidError,+ build_streamed_arm,+ copy_lora,+ gradient_snapshot,+ load_resident_reference,+ make_input,+ make_non_vacuous_lora,+ prepare_shards,+ run_backward,+)++DEFAULT_REPEATS = 5+DEFAULT_SEQ = 128+DEFAULT_BATCH = 1+DEFAULT_BUFFERS = 2+DEVICE = "cuda"+++def repeated_backward_verdict(+ exact_counts: list[int],+ total: int,+) -> bool:+ """Require corruption on a backward after the first."""+ if total <= 0 or len(exact_counts) < 2:+ return False+ if any(count < 0 or count > total for count in exact_counts):+ raise MeasurementInvalidError("gradient exact counts are out of range")+ return any(count < total for count in exact_counts[1:])+++def _finite_gradients(gradients: dict[str, Any]) -> None:+ import torch++ if not gradients:+ raise MeasurementInvalidError("empty gradient comparison")+ for name, gradient in gradients.items():+ if not torch.isfinite(gradient).all():+ raise MeasurementInvalidError(f"non-finite gradient: {name}")+++def compare_gradient_maps(+ actual: dict[str, Any],+ reference: dict[str, Any],+) -> tuple[int, int, float]:+ """Compare non-empty canonical gradient maps against one reference."""+ import torch++ _finite_gradients(actual)+ _finite_gradients(reference)+ if set(actual) != set(reference):+ raise MeasurementInvalidError("gradient parameter sets differ")+ exact = 0+ worst = 0.0+ for name, left in actual.items():+ right = reference[name]+ if left.shape != right.shape:+ raise MeasurementInvalidError(f"gradient shape differs: {name}")+ diff = (left - right).abs()+ worst = max(worst, float(diff.max()))+ exact += int(torch.equal(left, right))+ return exact, len(actual), worst+++def cuda_available() -> bool:+ return bitexact.cuda_available()+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(+ description="Reconstruct repeated streamed backwards from STEP 2b."+ )+ parser.add_argument("--weights", help="local Qwen2.5-32B checkpoint")+ parser.add_argument("--shards", help="local Soup shard directory")+ parser.add_argument("--seq", type=int, default=DEFAULT_SEQ)+ parser.add_argument("--batch", type=int, default=DEFAULT_BATCH)+ parser.add_argument("--buffers", type=int, default=DEFAULT_BUFFERS)+ parser.add_argument("--repeats", type=int, default=DEFAULT_REPEATS)+ parser.add_argument("--self-test", action="store_true")+ return parser.parse_args()+++def run_self_test() -> int:+ cases = [3, 1, 1, 1, 1]+ assert repeated_backward_verdict(cases, 3)+ assert not repeated_backward_verdict([3, 3, 3], 3)+ assert repeated_backward_verdict([1, 1, 1], 3)+ print("PASS: repeated-backward verdict checks later corruption")+ return 0+++def run_measurement(args: argparse.Namespace) -> int:+ import torch++ if not args.weights or not args.shards:+ print("ERROR: --weights and --shards are required")+ return 2+ if min(args.seq, args.batch, args.repeats) <= 0 or args.buffers < 2:+ print("ERROR: seq, batch, repeats must be positive and buffers >= 2")+ return 2+ if not cuda_available():+ print("SKIP: CUDA validation not performed; CUDA is required")+ return 0++ weights = str(Path(args.weights).expanduser().resolve())+ shards = str(Path(args.shards).expanduser().resolve())+ index, arch = prepare_shards(weights, shards)+ streamed, runtime, restore = build_streamed_arm(+ weights, shards, index, arch, "control", args.buffers+ )+ reference = None+ try:+ reference = load_resident_reference(weights)+ make_non_vacuous_lora(streamed)+ copy_lora(streamed, reference)+ input_ids = make_input(reference, seq=args.seq, batch=args.batch)+ reference.zero_grad(set_to_none=True)+ reference_loss = run_backward(reference, input_ids)+ if not torch.isfinite(torch.tensor(reference_loss)):+ raise MeasurementInvalidError("non-finite resident loss")+ reference_grads = gradient_snapshot(reference)+ exact_counts: list[int] = []+ total = 0+ for repetition in range(args.repeats):+ streamed.zero_grad(set_to_none=True)+ loss = run_backward(streamed, input_ids)+ if not torch.isfinite(torch.tensor(loss)):+ raise MeasurementInvalidError(+ f"non-finite streamed loss on repetition {repetition + 1}"+ )+ if loss != reference_loss:+ print(+ f"ERROR: repetition {repetition + 1} loss differs from "+ f"resident ({loss:.9f} != {reference_loss:.9f})"+ )+ return 1+ exact, total, worst = compare_gradient_maps(+ gradient_snapshot(streamed), reference_grads+ )+ exact_counts.append(exact)+ print(f"rep {repetition + 1}: {exact}/{total} exact worst_abs={worst:.6e}")+ if repeated_backward_verdict(exact_counts, total):+ print("RESULT: historical repeated-backward corruption reproduced")+ return 0+ print("ERROR: historical repeated-backward corruption not reproduced")+ return 1+ except MeasurementInvalidError as exc:+ print(f"ERROR: invalid measurement: {exc}")+ return 3+ finally:+ if reference is not None:+ del reference+ runtime.close()+ restore()+ del streamed+ torch.cuda.empty_cache()+++def main() -> int:+ args = parse_args()+ try:+ return run_self_test() if args.self_test else run_measurement(args)+ except MeasurementInvalidError as exc:+ print(f"ERROR: invalid measurement: {exc}")+ return 3+ except Exception as exc:+ print(f"ERROR: repeat_backward.py failed: {type(exc).__name__}: {exc}")+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/test_issue379_repeat_backward.py b/tests/test_issue379_repeat_backward.pynew file mode 100644index 00000000..4258dfac--- /dev/null+++ b/tests/test_issue379_repeat_backward.py@@ -0,0 +1,15 @@+from tests.test_repeat_backward import module+++def test_later_corruption_is_not_ignored():+ assert module.repeated_backward_verdict([4, 4, 3], 4)+++def test_nonfinite_gradient_is_rejected():+ torch = __import__("pytest").importorskip("torch")++ with __import__("pytest").raises(module.MeasurementInvalidError):+ module.compare_gradient_maps(+ {"lora_A": torch.tensor([float("nan")])},+ {"lora_A": torch.tensor([1.0])},+ )diff --git a/tests/test_issue379_repeat_backward_main.py b/tests/test_issue379_repeat_backward_main.pynew file mode 100644index 00000000..624eb6f6--- /dev/null+++ b/tests/test_issue379_repeat_backward_main.py@@ -0,0 +1,167 @@+"""CPU tests of repeat_backward.main() with toy LoRA models."""++import importlib.util+import sys+from pathlib import Path++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 mechanism_cost # noqa: E402++SPEC = importlib.util.spec_from_file_location(+ "repeat_backward_main", HARNESS / "repeat_backward.py"+)+assert SPEC is not None and SPEC.loader is not None+module = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(module)++LAYERS = 8+HIDDEN = 16+VOCAB = 64+++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):+ 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 _Config:+ vocab_size = VOCAB+++class _Toy(nn.Module):+ def __init__(self, wrong_from=None, loss_shift=0.0, grad_factor=3.0):+ super().__init__()+ torch.manual_seed(0)+ self.config = _Config()+ 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 close(self):+ pass+++def _run(monkeypatch, streamed, reference=None, sync=True):+ monkeypatch.setattr(mechanism_cost, "DEVICE", "cpu")+ monkeypatch.setattr(module, "cuda_available", lambda: True)+ monkeypatch.setattr(+ module,+ "prepare_shards",+ lambda weights, shards: ({}, "llama"),+ )+ arms = []+ monkeypatch.setattr(+ module,+ "build_streamed_arm",+ lambda weights, shards, index, arch, arm, buffers: (+ arms.append(arm) or streamed,+ _Runtime(),+ lambda: None,+ ),+ )+ monkeypatch.setattr(+ module, "load_resident_reference", lambda weights: reference or _Toy()+ )+ if not sync:+ monkeypatch.setattr(module, "copy_lora", lambda source, target: 0)+ monkeypatch.setattr(+ sys,+ "argv",+ [+ "repeat_backward.py", "--weights", "w", "--shards", "s",+ "--seq", "8",+ ],+ )+ return module.main(), arms+++def test_defect_from_the_second_backward_is_reproduced(monkeypatch):+ code, arms = _run(monkeypatch, _Toy(wrong_from=2))+ assert code == 0+ assert arms == ["control"]+++def test_defect_from_the_first_backward_is_still_the_defect(monkeypatch):+ assert _run(monkeypatch, _Toy(wrong_from=1))[0] == 0+++def test_healthy_streaming_is_not_reproduced(monkeypatch):+ assert _run(monkeypatch, _Toy())[0] == 1+++def test_changed_forward_is_not_the_defect(monkeypatch):+ assert _run(monkeypatch, _Toy(wrong_from=2, loss_shift=1.0e-3))[0] == 1+++def test_non_finite_loss_is_an_invalid_measurement(monkeypatch):+ assert _run(monkeypatch, _Toy(wrong_from=2, loss_shift=float("nan")))[0] == 3+++def test_non_finite_gradients_are_an_invalid_measurement(monkeypatch):+ assert _run(monkeypatch, _Toy(wrong_from=2, grad_factor=float("inf")))[0] == 3+++def test_unsynced_adapters_are_not_the_defect(monkeypatch):+ assert _run(monkeypatch, _Toy(wrong_from=2), sync=False)[0] == 1+++def test_empty_and_mismatched_gradient_maps_are_invalid():+ with pytest.raises(module.MeasurementInvalidError, match="empty"):+ module.compare_gradient_maps(+ {}, {"layers.0.lora_A.weight": torch.ones(1)}+ )+ with pytest.raises(module.MeasurementInvalidError, match="sets differ"):+ module.compare_gradient_maps(+ {"layers.0.lora_A.weight": torch.ones(1)},+ {"layers.1.lora_A.weight": torch.ones(1)},+ )diff --git a/tests/test_repeat_backward.py b/tests/test_repeat_backward.pynew file mode 100644index 00000000..afefe09c--- /dev/null+++ b/tests/test_repeat_backward.py@@ -0,0 +1,30 @@+import importlib.util+import sys+from pathlib import Path++import pytest++MODULE_PATH = Path(__file__).parents[1] / "benchmarks" / "harness" / "repeat_backward.py"+sys.path.insert(0, str(MODULE_PATH.parent))+SPEC = importlib.util.spec_from_file_location("repeat_backward", 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_first_exact_then_later_corruption_is_required():+ assert module.repeated_backward_verdict([256, 8, 8, 8], 256)+++def test_healthy_repeated_backward_fails_verdict():+ assert not module.repeated_backward_verdict([256, 256, 256], 256)+++def test_empty_or_single_repeat_fails_verdict():+ assert not module.repeated_backward_verdict([], 256)+ assert not module.repeated_backward_verdict([256], 256)+++def test_invalid_counts_are_rejected():+ with pytest.raises(module.MeasurementInvalidError):+ module.repeated_backward_verdict([256, 257], 256)