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.

perf(layer-stream): issue the head's load right after the embedding lookup (#1174) (#1258)

Vansh Sharma15a66781a425
diff --git a/benchmarks/README.md b/benchmarks/README.md
index 121bc6f3..39fef2be 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -78,6 +78,7 @@ only in a scratchpad on a machine that is gone, which is
| [`issue974_read_paths.py`](harness/issue974_read_paths.py) | [`gate-974-disk-tier-direct-io.md`](gate-974-disk-tier-direct-io.md) §3 | The WARM read-primitive micro-benchmark that motivated the first fix plan: per-tensor readinto vs mmap+copy vs one readinto per layer of the whole data section into an arena, split across K threads, store in the page cache. Answer: 3.9 -> 9.3 GB/s at 8 threads for the arena read — a page-cache -> pinned memcpy number, which §4 shows says nothing about cold. Kept because a record that changed its plan should show the number it changed it from | CUDA GPU; the Mistral-7B NF4 cache; ~30 s |
| [issue725_lorafa_operating_point.py](harness/issue725_lorafa_operating_point.py) | #725 / [gate-725-lorafa-operating-point.md](gate-725-lorafa-operating-point.md) | Measures trainable parameter counts, AdamW state tensor allocations, step latency, and multi-step loss finiteness between LoRA and LoRA-FA | ~20 s, CPU or GPU, no downloads |
| [`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 |
## Hardware
diff --git a/benchmarks/harness/head_prefetch_ab.py b/benchmarks/harness/head_prefetch_ab.py
new file mode 100644
index 00000000..9399f7e9
--- /dev/null
+++ b/benchmarks/harness/head_prefetch_ab.py
@@ -0,0 +1,399 @@
+#!/usr/bin/env python3
+"""Interleaved A/B of where the head's load is issued: the step's total wait.
+
+``StreamPrefetcher.head_prefetch_layer`` picks the decoder layer whose forward
+issues the head's copy into the shared large-layer slot. ``None`` is the last
+layer (the original timing); ``0`` is right after the embedding lookup. It is a
+plain attribute, so this driver flips it between blocks and runs every arm in ONE
+process on ONE model, the way #1178 ran ``backward_tail_prefetch=None`` as arm A.
+
+What it reports is the compute stream's ``wait()`` brackets from the committed
+``stream_probe.Instruments`` (the same brackets as gate-971 section 8), labelled
+per load by ``layer0_wait``'s wrappers. The number to judge an arm by is the
+step's TOTAL wait, every entry, not the head's own: the head's entry can improve
+while a decoder entry behind it in the copy stream gets worse. The per-group
+medians (embedding, head, layer 0, other decoder layers) say where a change went.
+
+Schedule: ``--warmup`` steps on the first arm, discarded, then ``--blocks`` rounds
+over the arms; each arm's block is ``--transition`` discarded steps followed by
+``--measure`` recorded steps. The arm order rotates each round, so no arm always
+follows the same neighbour. Every step is synchronised, so step time is a wall
+clock of one full step; there is no no-sync mode.
+
+Step shapes: ``sft`` is forward, backward, optimiser. ``preference`` runs a no-grad
+forward first, like a preference loss's reference pass, then the same step. It is
+the shape in which a head ``get()`` at layer 0 can replan the reader's queue on
+the disk tier at ``--read-ahead 3``. It is not a TRL loss.
+
+This needs a tree that has ``head_prefetch_layer`` (the #1258 branch). On any other
+tree it exits with a message instead of measuring nothing.
+
+The RTX 5070 run on #1258 measured a last-layer head wait of 27.2 ms in the
+process that also built the NF4 shards, against 10.9-11.5 ms in five later
+processes; the cause was not isolated. Build the shards once and discard that
+process's numbers, or point ``--shards`` at an already-sharded directory to
+skip sharding in the measured process entirely. ``--shards`` also keeps the
+shard directory's name off the weights path, which matters on Windows, where
+``resolve_shard_dir`` names it after that path and a long one trips ``WinError
+206`` (MAX_PATH).
+
+Typical invocations::
+
+ python benchmarks/harness/head_prefetch_ab.py --weights D:/synth/untied-8l \
+ --tier ram --arms last,0 --out ab_ram.json
+ python benchmarks/harness/head_prefetch_ab.py --weights D:/synth/untied-8l \
+ --shards D:/synth/untied-8l-shards \
+ --tier disk --read-ahead 3 --step-shape preference --out ab_disk_pref.json
+
+A machine without CUDA is an intentional skip and exits 0.
+"""
+
+import argparse
+import json
+import re
+import statistics
+import subprocess
+import sys
+import time
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+
+def _harness() -> Any:
+ """Import the sibling probe and labeller, whichever directory this ran from."""
+ here = str(Path(__file__).resolve().parent)
+ if here not in sys.path:
+ sys.path.insert(0, here)
+ import layer0_wait
+ import stream_probe
+
+ return stream_probe, layer0_wait
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ parser.add_argument("--weights", required=True)
+ parser.add_argument(
+ "--shards",
+ default=None,
+ help="an already-sharded directory, so stream_probe.build() does not shard in "
+ "the measured process (sharding there slows every arm)",
+ )
+ parser.add_argument("--tier", choices=("ram", "disk"), default="ram")
+ parser.add_argument("--quant", choices=("none", "nf4"), default="nf4")
+ parser.add_argument("--seq", type=int, default=512)
+ parser.add_argument("--batch", type=int, default=1)
+ parser.add_argument("--read-ahead", type=int, default=2)
+ parser.add_argument("--buffers", type=int, default=2)
+ parser.add_argument("--no-pin", action="store_true")
+ parser.add_argument("--lora-r", type=int, default=8)
+ parser.add_argument("--lora-targets", default="q_proj,k_proj,v_proj,o_proj")
+ parser.add_argument("--seed", type=int, default=3)
+ parser.add_argument("--input-seed", type=int, default=17)
+ parser.add_argument(
+ "--arms",
+ default="last,0",
+ help="comma list of head_prefetch_layer values; 'last' is None (the original timing)",
+ )
+ parser.add_argument("--step-shape", choices=("sft", "preference"), default="sft")
+ parser.add_argument("--warmup", type=int, default=3)
+ parser.add_argument("--blocks", type=int, default=5)
+ parser.add_argument("--transition", type=int, default=1)
+ parser.add_argument("--measure", type=int, default=2)
+ parser.add_argument("--out", required=True)
+ parser.add_argument("--label", default="")
+ return parser.parse_args()
+
+
+def parse_arms(text: str) -> List[Optional[int]]:
+ arms: List[Optional[int]] = []
+ for part in text.split(","):
+ part = part.strip().lower()
+ if not part:
+ continue
+ arms.append(None if part in ("last", "none") else int(part))
+ if len(arms) < 2 or len(set(arms)) != len(arms):
+ raise SystemExit("--arms needs at least two distinct values, e.g. last,0")
+ return arms
+
+
+def arm_name(arm: Optional[int]) -> str:
+ return "last" if arm is None else str(arm)
+
+
+def _source_sha() -> str:
+ """The commit of the tree that ``soup_cli`` got imported from, or ``unknown``.
+
+ I resolve this from ``soup_cli.__file__``, not from this driver's own file:
+ the driver and the ``soup_cli`` it measures can come from different
+ checkouts (a ``PYTHONPATH`` override, an editable install elsewhere), and I
+ want the tree that was actually measured. ``-dirty`` covers an uncommitted
+ change on top of that commit, scoped to ``src`` so an untracked output file
+ left at the repo root (this driver's own ``--out``, say) does not turn a
+ clean tree dirty. Written the way ``variant2_gate.py``'s ``_source_sha`` is.
+ """
+ import soup_cli
+
+ package_file = getattr(soup_cli, "__file__", None)
+ if package_file is None:
+ return "unknown"
+ try:
+ package_dir = Path(package_file).resolve().parent
+ root = subprocess.run(
+ ["git", "rev-parse", "--show-toplevel"],
+ cwd=package_dir,
+ check=True,
+ capture_output=True,
+ text=True,
+ timeout=5,
+ ).stdout.strip()
+ if not root:
+ return "unknown"
+ commit = (
+ subprocess.run(
+ ["git", "rev-parse", "HEAD"],
+ cwd=Path(root),
+ check=True,
+ capture_output=True,
+ text=True,
+ timeout=5,
+ )
+ .stdout.strip()
+ .lower()
+ )
+ dirty = subprocess.run(
+ ["git", "status", "--porcelain", "--untracked-files=normal", "--", "src"],
+ cwd=Path(root),
+ check=True,
+ capture_output=True,
+ text=True,
+ timeout=5,
+ ).stdout
+ except (OSError, subprocess.SubprocessError):
+ return "unknown"
+ if not re.fullmatch(r"[0-9a-f]{40}", commit):
+ return "unknown"
+ return f"{commit}-dirty" if dirty else commit
+
+
+def group_of(name: str) -> str:
+ """Bucket one labelled wait: embedding, head, layer 0, or another decoder layer."""
+ if name.startswith("large:"):
+ return "head" if "lm_head" in name else "embed"
+ return "layer000" if name == "layer000" else "decoder_other"
+
+
+def run_one_step(model: Any, optimizer: Any, ids: Any, shape: str) -> None:
+ import torch
+
+ if shape == "preference":
+ with torch.no_grad():
+ model(input_ids=ids)
+ out = model(input_ids=ids, labels=ids)
+ out.loss.backward()
+ optimizer.step()
+ optimizer.zero_grad(set_to_none=True)
+
+
+def summarise(rows: List[Dict[str, Any]]) -> Dict[str, Any]:
+ keys = ["total", "embed", "head", "layer000", "decoder_other"]
+ out: Dict[str, Any] = {"n": len(rows)}
+ for key in keys:
+ values = [row["wait_ms"][key] for row in rows]
+ out[key] = {
+ "median_ms": statistics.median(values),
+ "mean_ms": statistics.fmean(values),
+ "min_ms": min(values),
+ "max_ms": max(values),
+ }
+ steps = [row["step_ms"] for row in rows]
+ out["step"] = {"median_ms": statistics.median(steps), "mean_ms": statistics.fmean(steps)}
+ return out
+
+
+def print_table(summary: Dict[str, Dict[str, Any]], arms: List[Optional[int]]) -> None:
+ base = arm_name(arms[0])
+ columns = ("arm", "n", "total", "embed", "head", "layer0", "decoder", "step")
+ widths = (6, 3, 9, 8, 8, 8, 8, 9)
+ header = " ".join(f"{name:>{width}}" for name, width in zip(columns, widths))
+ print(header + " (medians, ms)")
+ for arm in arms:
+ row = summary[arm_name(arm)]
+ print(
+ f"{arm_name(arm):>6} {row['n']:>3} {row['total']['median_ms']:>9.2f} "
+ f"{row['embed']['median_ms']:>8.2f} {row['head']['median_ms']:>8.2f} "
+ f"{row['layer000']['median_ms']:>8.2f} {row['decoder_other']['median_ms']:>8.2f} "
+ f"{row['step']['median_ms']:>9.1f}",
+ flush=True,
+ )
+ for arm in arms[1:]:
+ row, ref = summary[arm_name(arm)], summary[base]
+ print(
+ f" {arm_name(arm)} vs {base}: total wait "
+ f"{row['total']['median_ms'] - ref['total']['median_ms']:+.2f} ms, step "
+ f"{row['step']['median_ms'] - ref['step']['median_ms']:+.1f} ms",
+ flush=True,
+ )
+
+
+def main() -> int:
+ cli = parse_args()
+ arms = parse_arms(cli.arms)
+ stream_probe, layer0_wait = _harness()
+ if not stream_probe.cuda_available():
+ print("SKIP: CUDA is required for head_prefetch_ab.py")
+ return 0
+
+ import torch
+
+ from soup_cli.utils.layer_stream import resolve_stream_dtype
+
+ device = "cuda"
+ dtype = resolve_stream_dtype(device)
+ args = argparse.Namespace(
+ weights=cli.weights,
+ shards=cli.shards,
+ quant=cli.quant,
+ tier=cli.tier,
+ no_pin=cli.no_pin,
+ buffers=cli.buffers,
+ read_ahead=cli.read_ahead,
+ seq=cli.seq,
+ batch=cli.batch,
+ lora_r=cli.lora_r,
+ lora_targets=cli.lora_targets,
+ seed=cli.seed,
+ input_seed=cli.input_seed,
+ lazy_shard_handles=False,
+ control_sync_source=False,
+ )
+ model, runtime, config, _index, _weights, shard_dir, shard_s, build_s = stream_probe.build(
+ args, device, dtype
+ )
+ prefetcher, pool = runtime.prefetcher, runtime.large_pool
+ if pool is None:
+ print("SKIP: a tied checkpoint has no large pool, so there is no head load to move")
+ runtime.close()
+ return 0
+ if not hasattr(type(prefetcher), "head_prefetch_layer"):
+ print(
+ "ERROR: this tree has no StreamPrefetcher.head_prefetch_layer (it is on the "
+ "#1258 branch); measuring would compare an arm with itself."
+ )
+ runtime.close()
+ return 2
+ for arm in arms:
+ if arm is not None and not 0 <= arm < runtime.n_layers:
+ print(f"ERROR: arm {arm} is outside [0, {runtime.n_layers})")
+ runtime.close()
+ return 2
+
+ stats = runtime.stats()
+ source_class = type(runtime.source).__name__
+ print(
+ f"source {source_class} tier {stats['tier']} read_ahead {stats['read_ahead']} "
+ f"layers {runtime.n_layers} shared slot {pool.nbytes / 2**20:.1f} MiB "
+ f"(shard {shard_s:.1f} s, build {build_s:.1f} s)",
+ flush=True,
+ )
+
+ import bitsandbytes as bnb
+
+ optimizer = bnb.optim.PagedAdamW8bit(
+ [param for param in model.parameters() if param.requires_grad], lr=1e-4
+ )
+ inst = stream_probe.Instruments(runtime, model, cli.quant)
+ inst.events_on = True
+ copy_labels: List[str] = []
+ stall_labels: List[str] = []
+ layer0_wait._label_wrappers(inst, copy_labels, stall_labels)
+
+ generator = torch.Generator(device=device).manual_seed(cli.input_seed)
+ ids = torch.randint(
+ 0, int(config.vocab_size), (cli.batch, cli.seq), generator=generator, device=device
+ )
+
+ def one_step() -> Dict[str, Any]:
+ copy_labels.clear()
+ stall_labels.clear()
+ inst.reset()
+ torch.cuda.synchronize()
+ started = time.perf_counter()
+ run_one_step(model, optimizer, ids, cli.step_shape)
+ torch.cuda.synchronize()
+ wall_ms = (time.perf_counter() - started) * 1000.0
+ waits = {"total": 0.0, "embed": 0.0, "head": 0.0, "layer000": 0.0, "decoder_other": 0.0}
+ for name, (before, after) in zip(stall_labels, inst._stall_pairs):
+ ms = before.elapsed_time(after)
+ waits["total"] += ms
+ waits[group_of(name)] += ms
+ inst.reset()
+ return {"step_ms": wall_ms, "wait_ms": waits}
+
+ def set_arm(arm: Optional[int]) -> None:
+ prefetcher.head_prefetch_layer = arm
+
+ set_arm(arms[0])
+ for _ in range(cli.warmup):
+ one_step()
+
+ records: Dict[str, List[Dict[str, Any]]] = {arm_name(arm): [] for arm in arms}
+ payload = {
+ "driver": "benchmarks/harness/head_prefetch_ab.py",
+ # the card, its NVIDIA driver and PCIe link, torch, and soup_cli_file
+ "gpu": stream_probe.gpu_facts(device),
+ "git_sha": _source_sha(),
+ # every --flag, so a record like "NF4" in a changelog fragment can be read
+ # back from the JSON itself instead of trusted from the invocation.
+ "args": vars(cli),
+ "label": cli.label,
+ "weights": cli.weights,
+ "shard_dir": shard_dir,
+ "source_class": source_class,
+ "tier": stats["tier"],
+ "pinned": stats["pinned"],
+ "read_ahead": stats["read_ahead"],
+ "n_layers": runtime.n_layers,
+ "shared_slot_bytes": pool.nbytes,
+ "seq": cli.seq,
+ "batch": cli.batch,
+ "step_shape": cli.step_shape,
+ "arms": [arm_name(arm) for arm in arms],
+ "schedule": {
+ "warmup": cli.warmup,
+ "blocks": cli.blocks,
+ "transition": cli.transition,
+ "measure": cli.measure,
+ },
+ "started": time.strftime("%Y-%m-%dT%H:%M:%S"),
+ "records": records,
+ }
+
+ for block in range(cli.blocks):
+ order = arms[block % len(arms) :] + arms[: block % len(arms)]
+ for arm in order:
+ set_arm(arm)
+ for _ in range(cli.transition):
+ one_step()
+ for _ in range(cli.measure):
+ row = one_step()
+ row["block"] = block
+ records[arm_name(arm)].append(row)
+ print(
+ f"block {block + 1}/{cli.blocks} done (order {[arm_name(a) for a in order]})",
+ flush=True,
+ )
+ # After every block, so a run that dies keeps its earlier points.
+ Path(cli.out).write_text(json.dumps(payload, indent=1), encoding="utf-8")
+
+ summary = {name: summarise(rows) for name, rows in records.items()}
+ payload["summary"] = summary
+ Path(cli.out).write_text(json.dumps(payload, indent=1), encoding="utf-8")
+ print_table(summary, arms)
+ runtime.close()
+ print(f"wrote {cli.out}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/changelog.d/0.75.1/1258.changed.md b/changelog.d/0.75.1/1258.changed.md
new file mode 100644
index 00000000..ef109036
--- /dev/null
+++ b/changelog.d/0.75.1/1258.changed.md
@@ -0,0 +1 @@
+- **An untied streamed checkpoint issues the head's load right after the embedding lookup instead of at the last decoder layer (#1174 by @VanshSharmaPES in #1258).** The embedding's bytes in the shared large-layer slot are dead once the lookup has run, so `StreamPrefetcher` now fires `tail_prefetch` from layer 0's `advance()` (`head_prefetch_layer`, default 0) rather than the last layer's, giving the head's copy every decoder layer's forward to hide behind instead of one. `head_prefetch_layer = None` restores the old timing. Loss, gradients and adapter weights are bit-identical between the two timings, and the sequence and count of real large-layer loads are unchanged; the refill is ordered after the queued lookup by the `wait_stream` in `LargeLayerBufferPool.load_async`, which a new GPU test pins. On an RTX 5070 Laptop GPU, with an 8-layer untied checkpoint (hidden 2048, a 501 MiB shared slot, NF4, sequence 512), the step's median total `wait()` fell from 11.96 to 4.50 ms on the RAM tier, from 15.83 to 1.42 ms on the disk tier, and from 57.29 to 29.16 ms on the disk tier at `stream_read_ahead: 3` for a step that runs a no-grad forward first. A decoder layer's copy now queues behind the head's on the shared copy stream, so the other decoder layers wait longer (0.78 to 4.06 ms on the RAM tier), which gives back part of the saving; layer 0 was the best of layers 0 to 3. Tied checkpoints have no shared slot and are unchanged.
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index 60939042..64812d0c 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -423,7 +423,7 @@ training:
soup train --config soup.yaml
```
-**How it works.** LoRA adapters + their gradients + optimizer state stay resident in VRAM (they are small). The frozen base lives in CPU RAM, page-locked when the machine allows it, and is streamed: each decoder layer is copied into one of two pre-allocated VRAM buffers on a dedicated CUDA stream while the previous layer is still computing, so the load overlaps the compute. Vocabulary-sized `embed_tokens` and an untied `lm_head` use one additional shared slot: the embedding is loaded for the model input, then the same allocation is reused for the output head after the last decoder layer, and the embedding is reloaded into it at the tail of that step's backward pass so the copy overlaps the remaining compute instead of blocking the next step's first lookup. Each decoder layer is read **twice** per step — once in the forward pass and once when the backward pass recomputes it — because `dL/dx = Wᵀ · dL/dy` needs the weights to reach the layers below. That is physics, not an implementation detail, and it is why streaming costs time.
+**How it works.** LoRA adapters + their gradients + optimizer state stay resident in VRAM (they are small). The frozen base lives in CPU RAM, page-locked when the machine allows it, and is streamed: each decoder layer is copied into one of two pre-allocated VRAM buffers on a dedicated CUDA stream while the previous layer is still computing, so the load overlaps the compute. Vocabulary-sized `embed_tokens` and an untied `lm_head` use one additional shared slot: the embedding is loaded for the model input, then the same allocation is reused for the output head, whose copy is issued right after the embedding lookup (`StreamPrefetcher.head_prefetch_layer`, default `0`) rather than at the last decoder layer, and the embedding is reloaded into it at the tail of that step's backward pass so the copy overlaps the remaining compute instead of blocking the next step's first lookup. Each decoder layer is read **twice** per step — once in the forward pass and once when the backward pass recomputes it — because `dL/dx = Wᵀ · dL/dy` needs the weights to reach the layers below. That is physics, not an implementation detail, and it is why streaming costs time.
**Qwen3.8-Flash-Next / Qwen4-Exp PLE.** The frozen PLE N-gram table is not a
decoder-layer weight for storage purposes: putting it in the PLE layer's shard
diff --git a/src/soup_cli/utils/layer_stream_runtime.py b/src/soup_cli/utils/layer_stream_runtime.py
index 926029f3..db7f4fc3 100644
--- a/src/soup_cli/utils/layer_stream_runtime.py
+++ b/src/soup_cli/utils/layer_stream_runtime.py
@@ -983,6 +983,7 @@ class StreamPrefetcher:
stream: Any = None,
tail_prefetch: Any = None,
backward_tail_prefetch: Any = None,
+ head_prefetch_layer: Optional[int] = None,
):
self.pool = pool
self.source = source
@@ -993,6 +994,16 @@ class StreamPrefetcher:
self.primes = 0
self.tail_prefetch = tail_prefetch
self.tail_prefetched = False
+ # #1174 part 2 — which decoder layer's forward issues `tail_prefetch`, the
+ # head's load into the shared slot. `None` is the original timing, the
+ # last layer, where the copy has only that one layer's compute to hide
+ # behind. A smaller index issues it earlier in the forward: the
+ # embedding's bytes in the slot are dead once the lookup has run, and
+ # the lookup precedes layer 0's `advance`, so layer 0 is the earliest
+ # point. It is a property, so a harness can flip it between steps and
+ # run both timings in one process, and an assignment is checked the same
+ # way the constructor argument is.
+ self.head_prefetch_layer = head_prefetch_layer
# #975 — the embedding's `_prime`-time load pays a full head-sized H2D
# copy with nothing to overlap it against, because it fires right as
# the next step's forward starts and is needed almost immediately.
@@ -1004,6 +1015,23 @@ class StreamPrefetcher:
self.backward_tail_prefetch = backward_tail_prefetch
self.backward_tail_prefetched = False
+ @property
+ def head_prefetch_layer(self) -> Optional[int]:
+ return self._head_prefetch_layer
+
+ @head_prefetch_layer.setter
+ def head_prefetch_layer(self, value: Optional[int]) -> None:
+ # `bool` is an `int`, so `True` would otherwise pass as layer 1. A bad
+ # value assigned later would only surface at the head's forward as
+ # "large-layer scheduler bug: slot holds ...", which names the wrong cause.
+ if value is not None and (
+ isinstance(value, bool) or not isinstance(value, int) or not 0 <= value < self.n_layers
+ ):
+ raise ValueError(
+ f"head_prefetch_layer must be None or in [0, {self.n_layers}), got {value!r}"
+ )
+ self._head_prefetch_layer = value
+
def prime(self) -> None:
"""Start of a forward pass: layer 0, walking upward."""
self.prev = None
@@ -1026,12 +1054,19 @@ class StreamPrefetcher:
nxt = idx + self.direction
if 0 <= nxt < self.n_layers and self.pool.owner[self.pool.slot_for(nxt)] != nxt:
self.pool.load_async(nxt, self.source, self.stream)
+ head_layer = self.head_prefetch_layer
+ if head_layer is None:
+ head_layer = self.n_layers - 1
if (
self.direction == 1
- and idx == self.n_layers - 1
+ and idx == head_layer
and not self.tail_prefetched
and self.tail_prefetch is not None
):
+ # The refill of the shared slot with the head. It is ordered after
+ # the embedding lookup (queued on the compute stream, reading the
+ # slot) by the `wait_stream` in `LargeLayerBufferPool.load_async`,
+ # the same guard the backward-tail refill below relies on.
self.tail_prefetch()
self.tail_prefetched = True
# #975 — layer 0 reached going backward is the last decoder recompute
@@ -2669,6 +2704,9 @@ def install_streaming(
stream,
tail_prefetch=_prefetch_output if large_pool is not None else None,
backward_tail_prefetch=_prefetch_embed if large_pool is not None else None,
+ # #1174 part 2: the head's load right after the embedding lookup. Set
+ # `prefetcher.head_prefetch_layer = None` to restore the last-layer timing.
+ head_prefetch_layer=0 if large_pool is not None else None,
)
layer_cls = _streamed_layer_class()
diff --git a/tests/test_issue1174_head_prefetch_ab_provenance.py b/tests/test_issue1174_head_prefetch_ab_provenance.py
new file mode 100644
index 00000000..bb590c5b
--- /dev/null
+++ b/tests/test_issue1174_head_prefetch_ab_provenance.py
@@ -0,0 +1,258 @@
+"""#1174: the head-prefetch A/B driver's JSON must say which card, driver and tree it measured.
+
+Two things I broke, both silent because nothing exercised the driver's JSON before:
+the payload's own ``"driver"`` key (the script path) was overwriting
+``gpu_facts()``'s ``"driver"`` key (the NVIDIA version) when I spread the dict at
+the top level, and ``_source_sha()`` resolved the commit from this file's own
+location, not from the ``soup_cli`` tree it actually measured.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+_REPO_ROOT = Path(__file__).resolve().parents[1]
+_HARNESS_DIR = _REPO_ROOT / "benchmarks" / "harness"
+_HARNESS = _HARNESS_DIR / "head_prefetch_ab.py"
+
+
+def _load_driver():
+ sys.path.insert(0, str(_HARNESS_DIR))
+ try:
+ spec = importlib.util.spec_from_file_location("head_prefetch_ab", _HARNESS)
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ return module
+ finally:
+ sys.path.remove(str(_HARNESS_DIR))
+
+
+_driver = _load_driver()
+
+
[email protected]("status", ["", " M src/soup_cli/utils/layer_stream_runtime.py\n"])
+def test_git_sha_names_the_imported_tree_and_marks_it_dirty(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, status: str
+) -> None:
+ """The driver and the ``soup_cli`` it measures can come from different checkouts,
+ so I resolve the commit from ``soup_cli.__file__``, not from this driver's file."""
+ import soup_cli
+
+ package_file = soup_cli.__file__
+ assert package_file is not None
+ package_dir = Path(package_file).resolve().parent
+ expected_sha = "a" * 40
+ calls: list[tuple[list[str], Path]] = []
+
+ def fake_run(command: list[str], *, cwd: Path, **kwargs: object) -> Any:
+ calls.append((command, cwd))
+ if command == ["git", "rev-parse", "--show-toplevel"]:
+ return SimpleNamespace(stdout=f"{tmp_path}\n")
+ if command == ["git", "rev-parse", "HEAD"]:
+ return SimpleNamespace(stdout=f"{expected_sha}\n")
+ return SimpleNamespace(stdout=status)
+
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setattr(_driver.subprocess, "run", fake_run)
+
+ assert _driver._source_sha() == expected_sha + ("-dirty" if status else "")
+ assert calls == [
+ (["git", "rev-parse", "--show-toplevel"], package_dir),
+ (["git", "rev-parse", "HEAD"], tmp_path),
+ (["git", "status", "--porcelain", "--untracked-files=normal", "--", "src"], tmp_path),
+ ]
+
+
+def test_source_sha_is_unknown_without_a_git_toplevel(monkeypatch: pytest.MonkeyPatch) -> None:
+ def fake_run(command: list[str], *, cwd: Path, **kwargs: object) -> Any:
+ return SimpleNamespace(stdout="\n")
+
+ monkeypatch.setattr(_driver.subprocess, "run", fake_run)
+ assert _driver._source_sha() == "unknown"
+
+
+def test_source_sha_is_unknown_when_git_is_missing(monkeypatch: pytest.MonkeyPatch) -> None:
+ def fake_run(command: list[str], *, cwd: Path, **kwargs: object) -> Any:
+ raise FileNotFoundError("no git")
+
+ monkeypatch.setattr(_driver.subprocess, "run", fake_run)
+ assert _driver._source_sha() == "unknown"
+
+
+def test_source_sha_is_unknown_when_git_exits_non_zero(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A tree with no ``.git`` (a ``git archive`` extract) makes ``git rev-parse
+ --show-toplevel`` exit 128; with ``check=True`` that is a ``CalledProcessError``."""
+
+ def fake_run(command: list[str], *, cwd: Path, **kwargs: object) -> Any:
+ raise _driver.subprocess.CalledProcessError(128, command)
+
+ monkeypatch.setattr(_driver.subprocess, "run", fake_run)
+ assert _driver._source_sha() == "unknown"
+
+
+def test_source_sha_does_not_record_a_head_that_is_not_a_commit(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ def fake_run(command: list[str], *, cwd: Path, **kwargs: object) -> Any:
+ if command == ["git", "rev-parse", "--show-toplevel"]:
+ return SimpleNamespace(stdout=f"{tmp_path}\n")
+ if command == ["git", "rev-parse", "HEAD"]:
+ return SimpleNamespace(stdout="not-a-commit\n")
+ return SimpleNamespace(stdout="")
+
+ monkeypatch.setattr(_driver.subprocess, "run", fake_run)
+ assert _driver._source_sha() == "unknown"
+
+
+def test_the_gpu_facts_stay_nested_so_the_nvidia_driver_survives() -> None:
+ """``gpu_facts`` returns its own ``"driver"`` key (the NVIDIA version); spreading
+ it into a payload that also sets ``"driver"`` to the script path overwrites it."""
+ text = _HARNESS.read_text(encoding="utf-8")
+ assert '"gpu": stream_probe.gpu_facts(device)' in text
+ assert "**stream_probe.gpu_facts(" not in text
+
+
+class _FakePrefetcher:
+ head_prefetch_layer = None
+
+
+class _FakeLoss:
+ def backward(self) -> None:
+ pass
+
+
+class _FakeModel:
+ def __call__(self, *, input_ids: object = None, labels: object = None) -> Any:
+ return SimpleNamespace(loss=_FakeLoss())
+
+ def parameters(self) -> list[Any]:
+ return [SimpleNamespace(requires_grad=True)]
+
+
+class _FakeOptimizer:
+ def __init__(self, *a: object, **k: object) -> None:
+ pass
+
+ def step(self) -> None:
+ pass
+
+ def zero_grad(self, *, set_to_none: bool = True) -> None:
+ pass
+
+
+class _FakeInstruments:
+ def __init__(self, *a: object, **k: object) -> None:
+ self.events_on = False
+ self._stall_pairs: list[Any] = []
+
+ def reset(self) -> None:
+ pass
+
+
+class _FakeRuntime:
+ n_layers = 4
+
+ def __init__(self) -> None:
+ self.prefetcher = _FakePrefetcher()
+ self.large_pool = SimpleNamespace(nbytes=1024)
+ self.source = object()
+
+ def stats(self) -> dict[str, Any]:
+ return {"tier": "ram", "pinned": True, "read_ahead": 2}
+
+ def close(self) -> None:
+ pass
+
+
+def test_main_writes_git_sha_and_shards_into_the_real_payload(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """The payload is built inside ``main()``, behind the CUDA check, so nothing
+ exercised it before: a hard-coded ``git_sha`` or a ``shards`` dropped back to
+ ``None`` would both go unnoticed. I fake only the GPU-bound pieces — the model,
+ the runtime, ``stream_probe``, ``layer0_wait`` and the bitsandbytes optimizer —
+ and run the driver's real ``main()`` over them."""
+ import bitsandbytes
+ import torch
+
+ out_path = tmp_path / "out.json"
+ cli = SimpleNamespace(
+ weights="fake-weights",
+ shards="fake-shards-dir",
+ tier="ram",
+ quant="nf4",
+ seq=8,
+ batch=1,
+ read_ahead=2,
+ buffers=2,
+ no_pin=False,
+ lora_r=8,
+ lora_targets="q_proj,k_proj,v_proj,o_proj",
+ seed=3,
+ input_seed=17,
+ arms="last,0",
+ step_shape="sft",
+ warmup=0,
+ blocks=1,
+ transition=0,
+ measure=1,
+ out=str(out_path),
+ label="test",
+ )
+ monkeypatch.setattr(_driver, "parse_args", lambda: cli)
+
+ runtime = _FakeRuntime()
+ model = _FakeModel()
+ config = SimpleNamespace(vocab_size=32000)
+ build_args_seen: list[Any] = []
+
+ fake_gpu_facts = {
+ "gpu": "simulated CUDA",
+ "torch": "0.0.0",
+ "vram_total_gb": 1.0,
+ "soup_cli_file": "/fake/soup_cli/__init__.py",
+ "driver": "616.92",
+ }
+
+ fake_stream_probe = SimpleNamespace(
+ cuda_available=lambda: True,
+ build=lambda args, device, dtype: (
+ build_args_seen.append(args) or model,
+ runtime,
+ config,
+ None,
+ None,
+ "fake-shard-dir",
+ 0.1,
+ 0.2,
+ ),
+ gpu_facts=lambda device: dict(fake_gpu_facts),
+ Instruments=_FakeInstruments,
+ )
+ fake_layer0_wait = SimpleNamespace(_label_wrappers=lambda inst, copy, stall: None)
+ monkeypatch.setattr(_driver, "_harness", lambda: (fake_stream_probe, fake_layer0_wait))
+ monkeypatch.setattr(_driver, "_source_sha", lambda: "b" * 40)
+ monkeypatch.setattr(bitsandbytes.optim, "PagedAdamW8bit", _FakeOptimizer)
+ monkeypatch.setattr(
+ torch, "Generator", lambda **k: SimpleNamespace(manual_seed=lambda *_: object())
+ )
+ monkeypatch.setattr(torch, "randint", lambda *a, **k: object())
+ monkeypatch.setattr(torch.cuda, "synchronize", lambda: None)
+
+ assert _driver.main() == 0
+ assert build_args_seen[0].shards == "fake-shards-dir"
+
+ payload = json.loads(out_path.read_text(encoding="utf-8"))
+ assert payload["git_sha"] == "b" * 40
+ assert payload["gpu"] == fake_gpu_facts
+ assert payload["gpu"]["driver"] == "616.92"
+ assert payload["args"]["shards"] == "fake-shards-dir"
diff --git a/tests/test_issue1174_head_prefetch_after_lookup.py b/tests/test_issue1174_head_prefetch_after_lookup.py
new file mode 100644
index 00000000..ebae8cd2
--- /dev/null
+++ b/tests/test_issue1174_head_prefetch_after_lookup.py
@@ -0,0 +1,389 @@
+"""#1174 part 2 — issue the head's load right after the embedding lookup.
+
+With #1178 in, the embedding is reloaded at the tail of the previous step's
+backward, so the head's forward-tail load into the shared slot is what is left of
+the large-layer wait. This is the zero-VRAM alternative to a second slot (option (c)
+on #1174), measured before it. `StreamPrefetcher.tail_prefetch` fires from `advance()` at
+the last decoder layer, before that layer's `functional_call`, so the copy hides
+behind one layer's compute. `head_prefetch_layer` moves that call earlier in the
+forward: the embedding's bytes in the slot are dead once the lookup has run, and
+the lookup precedes layer 0's `advance`, so layer 0 is the earliest point.
+
+`head_prefetch_layer = None` is the original timing, so both timings run in one
+process and every test here compares them. The refill is ordered after the
+queued embedding lookup by the `wait_stream` in `LargeLayerBufferPool.load_async`;
+the GPU test at the bottom pins that, with the embedding lookup as the queued read.
+
+What these tests cannot show is whether the move is faster. That needs the
+`wait()` bracket on a GPU, judged by the step's total wait on both the RAM and the
+disk tier.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from tests.test_v07204 import (
+ _batch_on,
+ _build_streamed_wrapper,
+ _mps_is_the_accelerator,
+ _randomise_lora_b,
+)
+
+_NO_MPS = pytest.mark.skipif(
+ _mps_is_the_accelerator(),
+ reason="MPS is untested for layer streaming (CUDA + CPU only)",
+)
+
+
+# --------------------------------------------------------------------------
+# the trigger, in isolation
+# --------------------------------------------------------------------------
+class _FakePool:
+ def __init__(self, n_layers):
+ self.owner = [None] * n_layers
+ self.loads = []
+
+ def slot_for(self, idx):
+ return idx
+
+ def load_async(self, idx, source, stream=None):
+ self.loads.append(idx)
+ self.owner[idx] = idx
+
+
+def _walk(prefetcher, n_layers):
+ """One forward, then the backward recompute walk, as the streamed layers call it."""
+ prefetcher.prime()
+ for idx in range(n_layers):
+ prefetcher.advance(idx)
+ for idx in reversed(range(n_layers)):
+ prefetcher.advance(idx)
+
+
+def _fired_at(head_layer, n_layers=4):
+ from soup_cli.utils.layer_stream_runtime import StreamPrefetcher
+
+ fired = []
+ prefetcher = StreamPrefetcher(
+ _FakePool(n_layers),
+ None,
+ n_layers,
+ None,
+ tail_prefetch=lambda: fired.append(("head", prefetcher.prev, prefetcher.direction)),
+ backward_tail_prefetch=lambda: fired.append(
+ ("embed", prefetcher.prev, prefetcher.direction)
+ ),
+ head_prefetch_layer=head_layer,
+ )
+ _walk(prefetcher, n_layers)
+ return fired
+
+
+class TestTheTrigger:
+ def test_none_fires_the_head_at_the_last_layer_going_forward(self):
+ fired = _fired_at(None)
+ assert ("head", 3, 1) in fired
+ assert [f for f in fired if f[0] == "head"] == [("head", 3, 1)]
+
+ def test_layer_zero_fires_the_head_at_layer_zero_going_forward_only(self):
+ heads = [f for f in _fired_at(0) if f[0] == "head"]
+ assert heads == [("head", 0, 1)], heads
+
+ def test_a_middle_layer_fires_once_and_never_in_the_backward_walk(self):
+ heads = [f for f in _fired_at(2) if f[0] == "head"]
+ assert heads == [("head", 2, 1)], heads
+
+ def test_the_backward_tail_embed_prefetch_is_unchanged_by_the_head_timing(self):
+ for head_layer in (None, 0, 2):
+ embeds = [f for f in _fired_at(head_layer) if f[0] == "embed"]
+ assert embeds == [("embed", 0, -1)], (head_layer, embeds)
+
+ def test_a_second_forward_after_prime_fires_again(self):
+ from soup_cli.utils.layer_stream_runtime import StreamPrefetcher
+
+ fired = []
+ prefetcher = StreamPrefetcher(
+ _FakePool(4), None, 4, None,
+ tail_prefetch=lambda: fired.append(prefetcher.prev),
+ head_prefetch_layer=0,
+ ) # fmt: skip
+ _walk(prefetcher, 4)
+ _walk(prefetcher, 4)
+ assert fired == [0, 0]
+
+ @pytest.mark.parametrize("bad", [-1, 4, 99, True, 1.0])
+ def test_an_out_of_range_layer_is_refused(self, bad):
+ from soup_cli.utils.layer_stream_runtime import StreamPrefetcher
+
+ with pytest.raises(ValueError, match="head_prefetch_layer"):
+ StreamPrefetcher(_FakePool(4), None, 4, head_prefetch_layer=bad)
+
+ @pytest.mark.parametrize("bad", [-1, 4, 99, True, False, 1.0, "0"])
+ def test_an_assignment_is_checked_like_the_constructor_and_leaves_the_value(self, bad):
+ """The harness switch is an assignment, which skipped the constructor's check;
+ a bad value then only surfaced at the head's forward as a "scheduler bug"."""
+ from soup_cli.utils.layer_stream_runtime import StreamPrefetcher
+
+ prefetcher = StreamPrefetcher(_FakePool(4), None, 4, head_prefetch_layer=2)
+ with pytest.raises(ValueError, match="head_prefetch_layer"):
+ prefetcher.head_prefetch_layer = bad
+ assert prefetcher.head_prefetch_layer == 2
+
+ @pytest.mark.parametrize("good", [None, 0, 1, 3])
+ def test_a_valid_assignment_is_accepted_and_read_back(self, good):
+ from soup_cli.utils.layer_stream_runtime import StreamPrefetcher
+
+ prefetcher = StreamPrefetcher(_FakePool(4), None, 4, head_prefetch_layer=2)
+ prefetcher.head_prefetch_layer = good
+ assert prefetcher.head_prefetch_layer == good
+
+
+# --------------------------------------------------------------------------
+# both timings, end to end on a streamed model
+# --------------------------------------------------------------------------
+def _recorder():
+ from transformers import TrainerCallback
+
+ class Recorder(TrainerCallback):
+ def __init__(self):
+ self.grads = []
+
+ def on_pre_optimizer_step(self, args, state, control, model=None, **kwargs):
+ self.grads.append(
+ [
+ param.grad.detach().clone() if param.grad is not None else None
+ for param in model.parameters()
+ if param.requires_grad
+ ]
+ )
+
+ return Recorder()
+
+
+def _run_arm(tmp_path, monkeypatch, *, head_layer, task="sft", tie=False, steps=2, **training):
+ """Train `steps` steps with the head prefetched at `head_layer`; `None` is the
+ original last-layer timing. Returns the per-step gradients, the final adapter
+ weights, the real large-layer loads, and the events the pool saw."""
+ import torch
+
+ torch.manual_seed(1234)
+ wrapper, _, _ = _build_streamed_wrapper(
+ tmp_path, monkeypatch, task=task, n_layers=4, tie=tie, **training
+ )
+ # PEFT starts `lora_B` at zero, which leaves most gradients zero and lets a
+ # comparison pass without checking anything (KTO's, in bf16, were all zero).
+ _randomise_lora_b(wrapper.model)
+ runtime = wrapper._stream_runtime
+ pool, prefetcher = runtime.large_pool, runtime.prefetcher
+ events = []
+ if pool is not None:
+ prefetcher.head_prefetch_layer = head_layer
+ original = pool.load_async
+
+ def spy(key, source, stream=None):
+ before = pool.loads
+ out = original(key, source, stream)
+ events.append((key, prefetcher.prev, pool.loads > before))
+ return out
+
+ pool.load_async = spy
+ recorder = _recorder()
+ wrapper.trainer.add_callback(recorder)
+ wrapper.trainer.args.max_steps = steps
+ try:
+ wrapper.trainer.train()
+ weights = {
+ name: param.detach().clone()
+ for name, param in wrapper.model.named_parameters()
+ if param.requires_grad
+ }
+ loads = pool.loads if pool is not None else None
+ finally:
+ wrapper._close_stream_runtime()
+ return recorder.grads, weights, loads, events
+
+
+def _assert_identical(arm_a, arm_b):
+ import torch
+
+ grads_a, weights_a, _, _ = arm_a
+ grads_b, weights_b, _, _ = arm_b
+ assert grads_a and len(grads_a) == len(grads_b), (len(grads_a), len(grads_b))
+ seen_nonzero = False
+ for step, (step_a, step_b) in enumerate(zip(grads_a, grads_b)):
+ assert len(step_a) == len(step_b)
+ for index, (ga, gb) in enumerate(zip(step_a, step_b)):
+ assert (ga is None) == (gb is None), (step, index)
+ if ga is None:
+ continue
+ assert torch.equal(ga, gb), f"step {step} gradient {index} differs"
+ seen_nonzero = seen_nonzero or bool(ga.abs().max() > 0)
+ assert seen_nonzero, "vacuous: every gradient was zero"
+ assert weights_a.keys() == weights_b.keys()
+ for name in weights_a:
+ assert torch.equal(weights_a[name], weights_b[name]), f"final weight {name} differs"
+
+
+@_NO_MPS
+class TestBothTimingsAreBitIdentical:
+ """Moving the head's load must change WHEN the copy is issued, never what the
+ step computes. The arms differ only in `head_prefetch_layer`."""
+
+ @pytest.mark.parametrize(
+ ("task", "training"),
+ [
+ ("sft", {}),
+ ("sft", {"gradient_accumulation_steps": 2}),
+ ("orpo", {}),
+ ("simpo", {}),
+ ("dpo", {}),
+ ("kto", {"batch_size": 2}),
+ ],
+ ids=["sft", "sft-ga2", "orpo", "simpo", "dpo", "kto"],
+ )
+ def test_untied(self, tmp_path, monkeypatch, task, training):
+ arm_a = _run_arm(tmp_path / "a", monkeypatch, head_layer=None, task=task, **training)
+ arm_b = _run_arm(tmp_path / "b", monkeypatch, head_layer=0, task=task, **training)
+ _assert_identical(arm_a, arm_b)
+
+ def test_the_comparison_is_not_noise(self, tmp_path, monkeypatch):
+ """Guard: the same timing twice must already be identical, or every other
+ test in this class would be comparing two different runs."""
+ first = _run_arm(tmp_path / "a", monkeypatch, head_layer=None)
+ second = _run_arm(tmp_path / "b", monkeypatch, head_layer=None)
+ _assert_identical(first, second)
+
+ def test_tied_has_no_large_pool_so_the_switch_does_nothing(self, tmp_path, monkeypatch):
+ arm_a = _run_arm(tmp_path / "a", monkeypatch, head_layer=None, tie=True)
+ arm_b = _run_arm(tmp_path / "b", monkeypatch, head_layer=0, tie=True)
+ assert arm_a[2] is None and arm_b[2] is None, "a tied model grew a large pool"
+ _assert_identical(arm_a, arm_b)
+
+
+@_NO_MPS
+class TestTheInstalledDefault:
+ """The arms above set `head_prefetch_layer` themselves, so nothing there covers
+ what `install_streaming` wires when nobody touches it."""
+
+ def test_an_untied_model_defaults_to_the_earliest_point(self, tmp_path, monkeypatch):
+ wrapper, _, _ = _build_streamed_wrapper(
+ tmp_path, monkeypatch, task="sft", n_layers=4, tie=False
+ )
+ try:
+ assert wrapper._stream_runtime.prefetcher.head_prefetch_layer == 0
+ finally:
+ wrapper._close_stream_runtime()
+
+ def test_a_tied_model_has_nothing_to_move(self, tmp_path, monkeypatch):
+ wrapper, _, _ = _build_streamed_wrapper(
+ tmp_path, monkeypatch, task="sft", n_layers=4, tie=True
+ )
+ try:
+ assert wrapper._stream_runtime.large_pool is None
+ assert wrapper._stream_runtime.prefetcher.head_prefetch_layer is None
+ finally:
+ wrapper._close_stream_runtime()
+
+
+# --------------------------------------------------------------------------
+# what the pool sees
+# --------------------------------------------------------------------------
+def _real(events, needle):
+ return [prev for key, prev, real in events if real and needle in key]
+
+
+@_NO_MPS
+class TestTheLoadsMoveButDoNotMultiply:
+ def test_the_head_load_comes_at_the_configured_layer(self, tmp_path, monkeypatch):
+ _, _, _, events_last = _run_arm(tmp_path / "a", monkeypatch, head_layer=None)
+ _, _, _, events_zero = _run_arm(tmp_path / "b", monkeypatch, head_layer=0)
+ assert _real(events_last, "lm_head") == [3, 3], events_last
+ assert _real(events_zero, "lm_head") == [0, 0], events_zero
+
+ def test_the_real_load_sequence_and_count_are_the_same_in_both_timings(
+ self, tmp_path, monkeypatch
+ ):
+ *_, loads_last, events_last = _run_arm(tmp_path / "a", monkeypatch, head_layer=None)
+ *_, loads_zero, events_zero = _run_arm(tmp_path / "b", monkeypatch, head_layer=0)
+ keys_last = [key for key, _, real in events_last if real]
+ keys_zero = [key for key, _, real in events_zero if real]
+ assert keys_last == keys_zero, (keys_last, keys_zero)
+ assert loads_last == loads_zero == 5, (loads_last, loads_zero)
+
+ @pytest.mark.parametrize("head_layer", [None, 0])
+ def test_an_eval_forward_then_a_training_step(self, tmp_path, monkeypatch, head_layer):
+ """A forward that never reaches a backward loads the embedding at its start
+ and the head after the lookup; the training step after it must still find
+ the slot in a state its own `_prime` can repair with one real load."""
+ import torch
+
+ wrapper, _, _ = _build_streamed_wrapper(
+ tmp_path, monkeypatch, task="sft", n_layers=4, tie=False
+ )
+ runtime = wrapper._stream_runtime
+ pool, prefetcher = runtime.large_pool, runtime.prefetcher
+ prefetcher.head_prefetch_layer = head_layer
+ batch = _batch_on(wrapper.model, next(iter(wrapper.trainer.get_train_dataloader())))
+ wrapper.model.eval()
+ with torch.no_grad():
+ wrapper.model(input_ids=batch["input_ids"])
+ after_eval = pool.loads
+ wrapper.model.train()
+ wrapper.trainer.args.max_steps = 1
+ try:
+ wrapper.trainer.train()
+ after_step = pool.loads
+ finally:
+ wrapper._close_stream_runtime()
+ # eval: the embed at `_prime`, then the head. The step: the embed again at
+ # `_prime` (the slot holds the head), the head, and the backward-tail embed.
+ assert after_eval == 2, after_eval
+ assert after_step == 5, after_step
+
+
+# --------------------------------------------------------------------------
+# the GPU-side guard for the new refill point
+# --------------------------------------------------------------------------
+class _PinnedSource:
+ def __init__(self, tensors):
+ self.tensors = tensors
+
+ def get(self, idx, key):
+ return self.tensors[key]
+
+
+def test_the_head_refill_waits_for_the_embedding_lookup_still_queued():
+ """The refill at layer 0 runs while the embedding lookup can still be queued on
+ the compute stream, reading the shared slot. What orders the refill after it is
+ the `wait_stream` in `LargeLayerBufferPool.load_async`. Same construction as the
+ backward-tail test in test_issue975_backward_tail_embed_prefetch.py, with the
+ roles swapped: the queued read is the embedding's, the refill is the head's.
+ Remove the wait and `seen` picks up the head's bytes.
+ """
+ import torch
+
+ from soup_cli.utils.layer_stream_runtime import LargeLayerBufferPool
+
+ shape = (1024, 1024)
+ pool = LargeLayerBufferPool(
+ {"embed_tokens": (shape, "float32"), "lm_head": (shape, "float32")},
+ {"embed_tokens": 0, "lm_head": 1},
+ device="cuda",
+ )
+ embed = torch.full(shape, 1.0).pin_memory()
+ head = torch.full(shape, 2.0).pin_memory()
+ source = _PinnedSource({"embed_tokens": embed, "lm_head": head})
+ copy_stream = torch.cuda.Stream()
+
+ pool.load_async("embed_tokens", source, copy_stream)
+ slot = pool.wait("embed_tokens")
+ torch.cuda.synchronize()
+
+ torch.cuda._sleep(int(1e9)) # the compute stream lags, like a queued lookup
+ seen = slot.clone() # a read of the slot, queued behind the sleep
+ pool.load_async("lm_head", source, copy_stream) # the head's early refill
+ torch.cuda.synchronize()
+
+ assert torch.equal(seen, embed.cuda())