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: record the end-to-end A/B of stream_nf4_scale_cache (#1892) and add the stream_ab_pairs driver (#1943)

Alpamys Makazhanbe6a8aced5bf
diff --git a/benchmarks/README.md b/benchmarks/README.md
index b952835a..25863351 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -54,6 +54,7 @@ They are the evidence behind the preprint:
| [`gate-1265-ab-nig.md`](gate-1265-ab-nig.md) | `soup ab`'s variance-robust statistic ([#1265](https://github.com/MakazhanAlpamys/Soup/issues/1265)): the normal-inverse-gamma Bayes factor that replaced the #1227 burn-in, with the first rows per arm held out to set the prior scale | **No burn-in; `PRIOR_SCALE_ROWS = 5`.** Worst Type-I under a peek after every pair, runs to 1000 rows: **0.0328** at alpha 0.05, **0.0066** at alpha 0.01, 0.0034 at 0.005 (burn-in: 0.0511 / 0.0110 / 0.0058). Power >= 0.996 from effect_size / sigma 0.3 up (burn-in ~0.82 there); costs: less power below 0.2 and a slower `accept_h0` under H0 (~281 pairs at 0.5 vs 43) |
| [`gate-1418-ab-cs-accept.md`](gate-1418-ab-cs-accept.md) | `soup ab`'s accept rule ([#1418](https://github.com/MakazhanAlpamys/Soup/issues/1418)): `accept_h0` once the always-valid confidence sequence for the difference, the #1265 mixture inverted at level alpha, lies inside +-effect_size, instead of the Bayes factor falling to `log(beta/(1-alpha))`; `--beta` retired | **Accept 2.0-2.4x sooner with no difference** at alpha 0.05: 307 pairs at effect_size / sigma 0.3 (was 621), 117 at 0.5 (was 281), runs to 1000 rows. `reject_h0` rule unchanged; Type-I only falls (worst 0.0328 to 0.0289 at alpha 0.05). Wrong `accept_h0` at a true difference of exactly effect_size at most **0.0083** at alpha 0.05 and 0.0019 at 0.01 (bound alpha; was 0.0042 / 0.0032), power there within 0.005 of before at alpha 0.05 and no lower from 0.01 down. Level beta measured too and not taken (power 0.965 at beta 0.20) |
| [`gate-1702-arena-packing.md`](gate-1702-arena-packing.md) | Largest-first packing of the pinned host-memory arenas on the layer-streaming RAM tier ([#1702](https://github.com/MakazhanAlpamys/Soup/issues/1702), shipped in [#1713](https://github.com/MakazhanAlpamys/Soup/pull/1713)); Qwen3-8B NF4 on the RTX 5070 Laptop 8 GB | **Memory saving confirmed, no speed claim.** The RAM tier page-locks 6,442,450,944 bytes where the in-order plan page-locks 8,589,934,592, and three deterministic optimizer steps are byte-identical between the two plans (870 of 870 digests). The 40-run speed series measured +1.96% on the RAM tier, inside the +/-15.13% band its own control set, so by the rule written beforehand no speed-up and no slow-down is claimed; the band is wide and cannot exclude a smaller change |
+| [`gate-1892-nf4-scale-cache.md`](gate-1892-nf4-scale-cache.md) | End-to-end A/B of the opt-in `training.stream_nf4_scale_cache` ([#1892](https://github.com/MakazhanAlpamys/Soup/pull/1892)) on a streamed Mistral-7B NF4 run | **Confirmed on one laptop:** median paired reduction 3.387 % [2.389, 6.936] over five AB/BA pairs against a rule of >= 2 % with lower bound > 0; +0.446 GB VRAM. The companion `--train-threads 1` test showed no gain (median -0.555 %) and is dropped. Exactness is covered by the PR tests, not by this record. |
## Harnesses
diff --git a/benchmarks/gate-1892-nf4-scale-cache.md b/benchmarks/gate-1892-nf4-scale-cache.md
new file mode 100644
index 00000000..9aec9313
--- /dev/null
+++ b/benchmarks/gate-1892-nf4-scale-cache.md
@@ -0,0 +1,133 @@
+<!--
+Measurement record, published as measured. The decision rule below was written to
+RULE.md by the driver before the first arm ran (2026-10-14T19:12:17+0500 for the
+scale-cache experiment, 2026-10-14T19:26:12+0500 for the train-threads experiment)
+and is copied here unchanged.
+
+Hardware: RTX 5070 Laptop GPU (Blackwell sm_120, 8 GB) on AC power, 34.1 GB host RAM.
+Stack (from the `versions` field of every result JSON): Python 3.12.10, soup-cli 0.76.0,
+torch 2.14.0+cu130, bitsandbytes 0.50.2, transformers 5.17.0, peft 0.20.0, trl 0.29.1,
+accelerate 1.15.0. Soup tree at commit 701f8b84802595c33f67f7395e62fbb0e6d15d7c.
+Harness: benchmarks/harness/issue361_nf4_throughput.py, driven by
+benchmarks/harness/stream_ab_pairs.py (new in this record).
+Raw data: D:/soup-bench/ab-1892-scale-cache/ and D:/soup-bench/ab-train-threads/ (RULE.md,
+ledger.json, p<k>-A/B.json and .log, summary.json).
+-->
+
+# Gate record - end-to-end A/B of `training.stream_nf4_scale_cache` (#1892)
+
+**Status (2026-10-14): CONFIRMED on one laptop.** Median paired reduction of the
+measured window 3.387 %, 95 % bootstrap interval [2.389, 6.936], against a rule of
+median >= 2.0 % with a lower bound > 0. The companion experiment (`--train-threads 1`
+on top of the cache) shows NO GAIN and that idea is dropped.
+
+---
+
+## 1. Setup
+
+- Model: `unsloth/mistral-7b-instruct-v0.3`, revision `60b99dcbc7f853b7cd18472a607e8d045b96f03e`,
+ NF4 with double quantisation, bfloat16 streaming dtype, layer streaming from a pinned RAM
+ store (4.138 GB pinned, 2 buffers).
+- Training shape: LoRA r=16 on `q_proj,v_proj`, batch 1 x sequence 512, 10 warm-up steps
+ (not counted) and 50 measured steps per arm.
+- Arms: A = control, B = candidate, one fresh process per arm. Experiment 1: A = default,
+ B = `--nf4-scale-cache`. Experiment 2: A = `--nf4-scale-cache`,
+ B = `--nf4-scale-cache --train-threads 1`.
+- Order: five balanced pairs, AB on even pairs and BA on odd pairs, after one uncounted
+ priming A arm per experiment (75.7 s and 73.5 s wall).
+- Guards, checked before every arm, no waiting (a failed guard stops the run): free RAM
+ >= 10 GiB (12.46-13.25 GiB before each counted arm of experiment 1), on AC power, no
+ pytest process running.
+
+## 2. Pre-registered rule
+
+```
+metric = measured-window seconds of an arm (sum of the harness's measured step times)
+per pair = reduction % = (A - B) / A * 100, A = control arm, B = candidate arm
+verdict = CONFIRMED if median >= 2.0 and the 95% whole-pair bootstrap lower bound > 0
+ (10,000 draws, seed 42); NO GAIN if the upper bound < 0; else INCONCLUSIVE.
+No exclusion on timing magnitude; only an operational failure (non-zero exit) voids a pair.
+```
+
+The bootstrap resamples the five pair reductions with replacement and takes the median of
+each draw; the interval is the 2.5th and 97.5th percentile of the 10,000 medians.
+
+## 3. Experiment 1 - scale cache off (A) vs on (B)
+
+| pair | order | A seconds | B seconds | reduction | A tok/s | B tok/s |
+|---|---|---:|---:|---:|---:|---:|
+| 0 | AB | 38.918 | 37.955 | 2.474 % | 657.79 | 674.48 |
+| 1 | BA | 40.524 | 37.713 | 6.936 % | 631.73 | 678.82 |
+| 2 | AB | 38.604 | 37.296 | 3.387 % | 663.15 | 686.40 |
+| 3 | BA | 38.536 | 37.615 | 2.389 % | 664.31 | 680.57 |
+| 4 | AB | 39.237 | 37.636 | 4.081 % | 652.44 | 680.20 |
+
+Median 3.387 %, 95 % bootstrap [2.389, 6.936]. **Verdict: CONFIRMED.**
+
+| quantity | A (off) | B (on) |
+|---|---:|---:|
+| peak VRAM allocated | 1.326 GB | 1.772 GB |
+| peak VRAM reserved | 1.411 GB | 1.839 GB |
+| scale-cache bytes | 0 | 436,207,616 |
+| GPU utilisation | 98-99 % | 99 % |
+| SM clock during run | 2542-2572 MHz | 2520-2542 MHz |
+| GPU temperature (max) | 80-81 C | 80-81 C |
+
+The VRAM cost of the cache is +0.446 GB allocated (1.772 - 1.326), within about 10 MB of
+the 436,207,616 bytes (0.436 GB) the cache holds.
+
+## 4. Experiment 2 - train-threads 1 on top of the cache
+
+A = `--nf4-scale-cache`, B = `--nf4-scale-cache --train-threads 1`.
+
+| pair | order | A seconds | B seconds | reduction |
+|---|---|---:|---:|---:|
+| 0 | AB | 37.295 | 37.502 | -0.555 % |
+| 1 | BA | 37.193 | 37.201 | -0.022 % |
+| 2 | AB | 38.036 | 38.350 | -0.826 % |
+| 3 | BA | 37.626 | 37.635 | -0.024 % |
+| 4 | AB | 37.394 | 38.959 | -4.185 % |
+
+Median -0.555 %, 95 % bootstrap [-4.185, -0.022]. **Verdict: NO GAIN** (upper bound < 0).
+Peak VRAM, cache bytes and GPU utilisation (99 %) are the same as experiment 1's cache
+arm; the maximum GPU temperature (81-82 C) is 1 C higher than in experiment 1's cache arm
+(80-81 C). Limiting torch to one CPU thread during training does not help, so that idea
+is dropped.
+
+## 5. Commands
+
+```
+python benchmarks/harness/stream_ab_pairs.py --tree <worktree at 701f8b848> \
+ --weights <hf cache>/models--unsloth--mistral-7b-instruct-v0.3/snapshots/60b99dcbc7f853b7cd18472a607e8d045b96f03e \
+ --shards <nf4 shard dir> --out <dir> --label scale-cache \
+ --b-args=--nf4-scale-cache --prime
+python benchmarks/harness/stream_ab_pairs.py <same paths> --out <dir> --pairs 5 \
+ --label scale-cache --b-args=--nf4-scale-cache
+python benchmarks/harness/stream_ab_pairs.py <same paths> --out <dir> --label train-threads \
+ --a-args=--nf4-scale-cache --b-args="--nf4-scale-cache --train-threads 1" --prime
+python benchmarks/harness/stream_ab_pairs.py <same paths> --out <dir> --pairs 5 \
+ --label train-threads --a-args=--nf4-scale-cache \
+ --b-args="--nf4-scale-cache --train-threads 1"
+```
+
+The priming run writes `RULE.md` (with the arm arguments) before the first arm starts, so
+its arguments are the ones recorded in each `RULE.md`. Both runs use the driver's default
+common arguments `--warmup 10 --steps 50 --no-ceiling`.
+`python benchmarks/harness/stream_ab_pairs.py report <dir>` recomputes `summary.json`
+from the per-arm JSON files.
+
+## 6. Caveats
+
+- **Exactness is not shown here.** The losses differ from run to run, also between
+ repeats of the same arm (for example first-step loss 9.7298-9.7483, last-step loss
+ 0.1261-0.1359 across the ten counted arms of experiment 1; the minimum and maximum of
+ `loss_first` and `loss_last` in its `p<k>-A/B.json` files), because this harness runs
+ with the default non-deterministic attention backward. Bit-identical results of the
+ cache rest on the CPU and CUDA tests in PR #1892, not on this record.
+- **One laptop, one model, one shape.** A single RTX 5070 Laptop on AC, one 7B NF4
+ model, batch 1 x 512. Other cards, models and sequence lengths are not measured.
+- **Two failed starts preceded the valid run.** Two earlier attempts to start the
+ experiment failed before producing data and are not part of any number above; no
+ pair was dropped after seeing a result, and every counted pair is in the tables.
+- Five pairs bound the interval coarsely; the lower bound 2.389 % is the smallest of the
+ five reductions by construction of the resampling.
diff --git a/benchmarks/harness/stream_ab_pairs.py b/benchmarks/harness/stream_ab_pairs.py
new file mode 100644
index 00000000..ed7b1f63
--- /dev/null
+++ b/benchmarks/harness/stream_ab_pairs.py
@@ -0,0 +1,269 @@
+"""Balanced AB/BA pairs of benchmarks/harness/issue361_nf4_throughput.py, one fresh
+process per arm, with admission guards checked before EVERY arm (no waiting: a failed
+guard stops the run and keeps what was measured).
+
+Rule (written before measuring, also copied into <out>/RULE.md):
+ metric = measured-window seconds of an arm (sum of the harness's measured step times)
+ per pair = reduction % = (A - B) / A * 100, A = control arm, B = candidate arm
+ verdict = CONFIRMED if median >= 2.0 and the 95% whole-pair bootstrap lower bound > 0
+ (10,000 draws, seed 42); NO GAIN if the upper bound < 0; else INCONCLUSIVE.
+ No exclusion on timing magnitude; only an operational failure (non-zero exit) voids a pair.
+
+Usage: (Windows only, the memory and power guards use kernel32)
+ python benchmarks/harness/stream_ab_pairs.py --tree <worktree> --weights <hf snapshot dir>
+ --shards <nf4 shard dir> --out <dir> --pairs 5 --label scale-cache
+ --b-args=--nf4-scale-cache
+ python benchmarks/harness/stream_ab_pairs.py report <dir>
+"""
+
+import argparse
+import ctypes
+import json
+import os
+import random
+import statistics
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+MIN_FREE_GIB = 10.0
+
+
+class _Mem(ctypes.Structure):
+ _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong)] + [
+ (n, ctypes.c_ulonglong) for n in ("tp", "ap", "tpf", "apf", "tv", "av", "aev")
+ ]
+
+
+class _Power(ctypes.Structure):
+ _fields_ = [
+ ("ac", ctypes.c_ubyte),
+ ("flag", ctypes.c_ubyte),
+ ("pct", ctypes.c_ubyte),
+ ("saver", ctypes.c_ubyte),
+ ("life", ctypes.c_ulong),
+ ("full", ctypes.c_ulong),
+ ]
+
+
+def free_gib():
+ mem = _Mem()
+ mem.dwLength = ctypes.sizeof(_Mem)
+ ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(mem))
+ return mem.ap / 2**30
+
+
+def on_ac():
+ power = _Power()
+ ctypes.windll.kernel32.GetSystemPowerStatus(ctypes.byref(power))
+ return power.ac == 1
+
+
+def foreign_pytest():
+ out = subprocess.run(
+ [
+ "powershell",
+ "-NoProfile",
+ "-Command",
+ "Get-CimInstance Win32_Process -Filter \"Name='python.exe'\" | "
+ "Where-Object { $_.CommandLine -match 'pytest' } | "
+ "ForEach-Object { $_.ProcessId }",
+ ],
+ capture_output=True,
+ text=True,
+ timeout=60,
+ ).stdout.split()
+ return [pid for pid in out if pid.strip()]
+
+
+def guards():
+ problems = []
+ free = free_gib()
+ if free < MIN_FREE_GIB:
+ problems.append(f"free RAM {free:.2f} GiB < {MIN_FREE_GIB}")
+ if not on_ac():
+ problems.append("not on AC power")
+ pids = foreign_pytest()
+ if pids:
+ problems.append(f"pytest running: pids {pids}")
+ return problems, round(free, 2)
+
+
+def run_arm(args, pair, arm, extra):
+ out, common = Path(args.out), args.common
+ harness = os.path.join(args.tree, "benchmarks", "harness", "issue361_nf4_throughput.py")
+ path = out / f"p{pair}-{arm}.json"
+ cmd = [
+ sys.executable,
+ harness,
+ "--weights",
+ args.weights,
+ "--shards",
+ args.shards,
+ "--json",
+ str(path),
+ *common.split(),
+ *extra.split(),
+ ]
+ env = dict(os.environ, PYTHONPATH=os.path.join(args.tree, "src"))
+ started = time.time()
+ proc = subprocess.run(
+ cmd,
+ cwd=os.path.dirname(harness),
+ env=env,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ stdin=subprocess.DEVNULL,
+ timeout=1800,
+ )
+ (out / f"p{pair}-{arm}.log").write_text(
+ proc.stdout + "\n--- stderr ---\n" + proc.stderr, encoding="utf-8"
+ )
+ return proc.returncode, time.time() - started
+
+
+def measure(args):
+ out = Path(args.out)
+ out.mkdir(parents=True, exist_ok=True)
+ rule = __doc__.split("Usage:")[0]
+ rule_path = out / "RULE.md"
+ if not rule_path.exists():
+ rule_path.write_text(
+ f"label: {args.label}\nA args: '{args.a_args}'\nB args: '{args.b_args}'\n"
+ f"common: '{args.common}'\npairs: {args.pairs}\nwritten: "
+ f"{time.strftime('%Y-%m-%dT%H:%M:%S%z')}\n\n{rule}",
+ encoding="utf-8",
+ )
+ ledger_path = out / "ledger.json"
+ ledger = json.loads(ledger_path.read_text(encoding="utf-8")) if ledger_path.exists() else []
+ if args.prime:
+ problems, free = guards()
+ if problems:
+ print(f"STOP before prime: {problems}")
+ return 2
+ rc, secs = run_arm(args, "prime", "A", args.a_args)
+ ledger.append(
+ {
+ "pair": "prime",
+ "arm": "A",
+ "rc": rc,
+ "wall_s": round(secs, 1),
+ "free_gib_before": free,
+ }
+ )
+ ledger_path.write_text(json.dumps(ledger, indent=2), encoding="utf-8")
+ print(f"prime arm (not counted): rc={rc} wall={secs:.0f}s free_before={free}GiB")
+ return 0 if rc == 0 else 3
+ last = args.pairs if args.to_pair is None else args.to_pair + 1
+ for pair in range(args.from_pair, last):
+ order = ("A", "B") if pair % 2 == 0 else ("B", "A")
+ for arm in order:
+ problems, free = guards()
+ if problems:
+ ledger.append({"pair": pair, "arm": arm, "status": "refused", "why": problems})
+ (out / "ledger.json").write_text(json.dumps(ledger, indent=2), encoding="utf-8")
+ print(f"STOP before pair {pair} arm {arm}: {problems}")
+ return 2
+ extra = args.a_args if arm == "A" else args.b_args
+ rc, secs = run_arm(args, pair, arm, extra)
+ ledger.append(
+ {
+ "pair": pair,
+ "arm": arm,
+ "rc": rc,
+ "wall_s": round(secs, 1),
+ "free_gib_before": free,
+ }
+ )
+ (out / "ledger.json").write_text(json.dumps(ledger, indent=2), encoding="utf-8")
+ print(f"pair {pair} arm {arm}: rc={rc} wall={secs:.0f}s free_before={free}GiB")
+ sys.stdout.flush()
+ if rc != 0:
+ print("arm failed: stopping (operational failure voids the pair)")
+ return 3
+ if last >= args.pairs:
+ return report(argparse.Namespace(out=args.out))
+ return 0
+
+
+def report(args):
+ out = Path(args.out)
+ rows = {}
+ for path in sorted(out.glob("p[0-9]*-*.json")):
+ data = json.loads(path.read_text(encoding="utf-8"))
+ if data.get("status") != "ok":
+ continue
+ pair, arm = path.stem[1:].split("-")
+ rows.setdefault(int(pair), {})[arm] = data
+ pairs = sorted(p for p, arms in rows.items() if {"A", "B"} <= set(arms))
+ reductions, lines = [], []
+ for pair in pairs:
+ a, b = rows[pair]["A"], rows[pair]["B"]
+ ta, tb = sum(a["step_times_s"]), sum(b["step_times_s"])
+ red = (ta - tb) / ta * 100
+ reductions.append(red)
+ lines.append(
+ f"pair {pair} ({'AB' if pair % 2 == 0 else 'BA'}): A {ta:.3f}s "
+ f"B {tb:.3f}s -> {red:+.3f}% | tok/s {a['tokens_per_s']:.1f} -> "
+ f"{b['tokens_per_s']:.1f} | peak alloc {a['peak_vram_gb']['allocated']} -> "
+ f"{b['peak_vram_gb']['allocated']} GB | cache B {b.get('nf4_scale_cache_bytes')}"
+ )
+ print("\n".join(lines))
+ if not reductions:
+ print("no complete pair")
+ return 1
+ rng = random.Random(42)
+ boots = sorted(
+ statistics.median(rng.choice(reductions) for _ in reductions) for _ in range(10_000)
+ )
+ low, high = boots[249], boots[9749]
+ med = statistics.median(reductions)
+ if med >= 2.0 and low > 0:
+ verdict = "CONFIRMED"
+ elif high < 0:
+ verdict = "NO GAIN"
+ else:
+ verdict = "INCONCLUSIVE"
+ summary = {
+ "pairs": len(reductions),
+ "reductions_pct": [round(r, 3) for r in reductions],
+ "median_pct": round(med, 3),
+ "ci95": [round(low, 3), round(high, 3)],
+ "verdict": verdict,
+ }
+ (out / "summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
+ print(json.dumps(summary))
+ return 0
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ sub = parser.add_subparsers(dest="cmd")
+ rep = sub.add_parser("report")
+ rep.add_argument("out")
+ parser.add_argument("--out")
+ parser.add_argument("--tree", help="Soup tree holding the harness and src/")
+ parser.add_argument("--weights", help="HF snapshot directory of the model")
+ parser.add_argument("--shards", help="NF4 shard directory")
+ parser.add_argument("--pairs", type=int, default=5)
+ parser.add_argument("--label", default="")
+ parser.add_argument("--a-args", default="")
+ parser.add_argument("--b-args", default="")
+ parser.add_argument("--common", default="--warmup 10 --steps 50 --no-ceiling")
+ parser.add_argument("--from-pair", type=int, default=0)
+ parser.add_argument("--to-pair", type=int, default=None, help="inclusive")
+ parser.add_argument("--prime", action="store_true", help="one uncounted A arm, then exit")
+ args = parser.parse_args()
+ if args.cmd == "report":
+ return report(args)
+ missing = [n for n in ("out", "tree", "weights", "shards") if not getattr(args, n)]
+ if missing:
+ parser.error("required: " + ", ".join("--" + n for n in missing))
+ return measure(args)
+
+
+if __name__ == "__main__":
+ sys.exit(main())