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
fix(layer-stream): prefetch embed_tokens at the backward tail, not the next step's prime (#975) (#1178)
Vansh Sharma20ab4668625f
diff --git a/changelog.d/0.75.1/1178.changed.md b/changelog.d/0.75.1/1178.changed.mdnew file mode 100644index 00000000..a92c2fcb--- /dev/null+++ b/changelog.d/0.75.1/1178.changed.md@@ -0,0 +1 @@+- **An untied streamed checkpoint reloads the embedding at the tail of the previous step's backward instead of at the start of the next forward (#975 by @VanshSharmaPES in #1178).** `embed_tokens` and an untied `lm_head` share one device slot, so every step swapped the slot back to the embedding right as the forward began, a full head-sized copy with nothing to overlap it. The reload now happens once layer 0's backward recompute is reached, so it overlaps the rest of the backward, and the forward-start load becomes a same-owner no-op from the second step on. The refill is ordered after the head's still-queued backward by the `wait_stream` in `LargeLayerBufferPool.load_async`, which a new GPU test pins. On an untied Llama with hidden 2048, vocab 128256 and a 501 MiB slot, on an RTX 5070 Laptop GPU, the embedding's compute-stream wait fell from about 19-23 ms to about 0.15 ms per step; that is still about 0.1% of a cold 70B step, and the step-time change (2-6.5%) is close to that fixture's noise floor. Preference losses get part of it: DPO's no-grad reference forward and KTO's extra forwards still load the embedding at the start of their forward. Tied checkpoints have no shared slot and are unchanged, and each `train()` now ends with one extra large-layer load that no later forward consumes.diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.mdindex 3f8e7355..3f1ff0fe 100644--- a/docs/performance-and-quantization.md+++ b/docs/performance-and-quantization.md@@ -376,7 +376,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. 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 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.**Qwen3.8-Flash-Next / Qwen4-Exp PLE.** The frozen PLE N-gram table is not adecoder-layer weight for storage purposes: putting it in the PLE layer's sharddiff --git a/src/soup_cli/utils/layer_stream_runtime.py b/src/soup_cli/utils/layer_stream_runtime.pyindex 484b2694..926029f3 100644--- a/src/soup_cli/utils/layer_stream_runtime.py+++ b/src/soup_cli/utils/layer_stream_runtime.py@@ -982,6 +982,7 @@ class StreamPrefetcher:n_layers: int,stream: Any = None,tail_prefetch: Any = None,+ backward_tail_prefetch: Any = None,):self.pool = poolself.source = source@@ -992,12 +993,23 @@ class StreamPrefetcher:self.primes = 0self.tail_prefetch = tail_prefetchself.tail_prefetched = False+ # #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.+ # This callback lets the caller issue that SAME load earlier, once+ # layer 0's backward recompute confirms this step's decoder walk is+ # done, so it can overlap with whatever backward work is still ahead+ # (the embedding's own backward, optimiser bookkeeping) instead of+ # blocking the next step's first op.+ self.backward_tail_prefetch = backward_tail_prefetch+ self.backward_tail_prefetched = Falsedef prime(self) -> None:"""Start of a forward pass: layer 0, walking upward."""self.prev = Noneself.direction = 1self.primes += 1+ self.backward_tail_prefetched = Falseself.tail_prefetched = Falseself.pool.load_async(0, self.source, self.stream)@@ -1022,6 +1034,36 @@ class StreamPrefetcher:):self.tail_prefetch()self.tail_prefetched = True+ # #975 — layer 0 reached going backward is the last decoder recompute+ # of this step's backward pass, so this refills the shared slot with+ # the embedding while the backward is still running. Two separate+ # things make that safe, and only the second protects the GPU:+ #+ # * CPU side: `lm_head`'s backward Node sits between the loss and every+ # decoder layer, so the autograd engine has already dispatched it, and+ # the saved-tensor version check happens at dispatch. The embedding's+ # own backward reads indices, never the weight values, so it never+ # checks this slot's version at all.+ # * GPU side: when the CPU reaches layer 0, the head's backward GEMM can+ # still be queued on the compute stream, reading this slot. What+ # orders the refill after it is `stream.wait_stream(torch.cuda.+ # current_stream())` in `LargeLayerBufferPool.load_async`, which makes+ # the copy stream wait for everything already enqueued on the compute+ # stream. Without that wait the refill can overwrite bytes the head's+ # backward has not read yet, and the gradients come out silently+ # wrong. Keep it if `load_async` is touched.+ #+ # `_prime()` still issues this same load unconditionally at the next+ # step's start — this only makes that call a same-owner no-op on the+ # hot path, by getting there first with time to overlap.+ if (+ self.direction == -1+ and idx == 0+ and not self.backward_tail_prefetched+ and self.backward_tail_prefetch is not None+ ):+ self.backward_tail_prefetch()+ self.backward_tail_prefetched = True# ==========================================================================@@ -2616,12 +2658,17 @@ def install_streaming(if large_pool is not None and output_key is not None:large_pool.load_async(output_key, source, stream)+ def _prefetch_embed() -> None:+ if large_pool is not None and embed_key is not None:+ large_pool.load_async(embed_key, source, stream)+prefetcher = StreamPrefetcher(pool,source,n_layers,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,)layer_cls = _streamed_layer_class()@@ -2684,6 +2731,11 @@ def install_streaming(raise RuntimeError("could not install the streamed output head")def _prime(*_args: Any, **_kwargs: Any) -> None:+ # #975 — the backward-tail prefetch above already loads this for every+ # step but the first, so `load_async`'s own-owner check makes this a+ # no-op on the hot path. Kept unconditional: it is the only load for+ # step 0, and for any forward that follows a backward that never+ # reached layer 0.if large_pool is not None and embed_key is not None:large_pool.load_async(embed_key, source, stream)prefetcher.prime()diff --git a/tests/test_issue975_backward_tail_embed_prefetch.py b/tests/test_issue975_backward_tail_embed_prefetch.pynew file mode 100644index 00000000..e8ab404f--- /dev/null+++ b/tests/test_issue975_backward_tail_embed_prefetch.py@@ -0,0 +1,215 @@+"""#975 — the embedding's `_prime`-time load pays a full head-sized H2D copy+with nothing to overlap it against, because `_prime()` (the forward-pre-hook)+fires right as the next step's forward starts and the embedding lookup is+almost the first thing that forward does.++`StreamPrefetcher` now also prefetches `embed_tokens` at the tail of the+BACKWARD pass, when the checkpoint recompute for decoder layer 0 confirms+this step's backward walk is done. Two things make refilling the shared slot+there safe. On the CPU side, `lm_head`'s own backward Node has already been+dispatched (it sits between the loss and every decoder layer, so the autograd+engine reaches it first), so the saved-tensor version check has already run.+On the GPU side, the head's backward GEMM can still be queued on the compute+stream, and what orders the refill after it is the `stream.wait_stream(...)`+in `LargeLayerBufferPool.load_async`; the GPU-only test at the bottom of this+file is the one that pins that guard. `_prime()` still issues the same load+unconditionally at the next step's start as a fallback for step 0 and for any+backward that never reaches layer 0; on the hot path that call now finds the+slot already holding what it asked for and is a same-owner no-op.++This only matters for an UNTIED checkpoint: a tied model streams one key for+both `embed_tokens` and `lm_head`, so `LargeLayerBufferPool.owner` never+changes across a whole run and the ping-pong this fix targets does not exist.+`_build_streamed_wrapper` in `test_v07204.py` has taken `tie` since #1061; this+file predates that and keeps its own small helper below rather than switching.+"""++from __future__ import annotations++import pytest++from tests.conftest import cuda_available+from tests.test_v07204 import (+ _TASK_ROWS,+ _mps_is_the_accelerator,+ _stream_cfg,+ _tiny_llama_dir,+ _wrapper_for,+ _write_tiny_tokenizer,+)+++def _build_untied_wrapper(tmp_path, monkeypatch, task="sft", n_layers=2, **training):+ weights, resident, _ = _tiny_llama_dir(tmp_path, n_layers=n_layers, tie=False)+ _write_tiny_tokenizer(weights)+ monkeypatch.setenv("SOUP_LAYER_STREAM_CACHE_DIR", str(tmp_path / "cache"))+ monkeypatch.chdir(tmp_path)+ cfg = _stream_cfg(weights, tmp_path / "out", task=task, **training)+ # The real accelerator when there is one, like `_build_streamed_wrapper`:+ # `TrainingArguments` picks CUDA on its own, so pinning the model to the CPU+ # there sends the batches to `cuda:0` and the embedding lookup fails on a+ # device mismatch. None of these tests compares floats, so nothing needs+ # the exact CPU arithmetic that pinning would buy.+ device = "cuda" if cuda_available() else "cpu"+ wrapper = _wrapper_for(task)(cfg, device=device)+ wrapper.setup({"train": _TASK_ROWS[task](8)})+ return wrapper, resident, weights+++class TestBackwardTailEmbedPrefetch:+ """#975 — untied `embed_tokens` / `lm_head` share one `LargeLayerBufferPool`+ slot, and the fix moves the embedding's reload from the next step's+ `_prime()` to this step's backward tail."""++ # With no CUDA, `_build_untied_wrapper` falls back to the CPU, and on a box+ # where MPS is the accelerator that is a device mismatch no user would ever+ # hit, not something this fix is responsible for.+ pytestmark = pytest.mark.skipif(+ _mps_is_the_accelerator(),+ reason="MPS is untested for layer streaming (CUDA + CPU only)",+ )++ def test_untied_fixture_actually_shares_one_slot(self, tmp_path, monkeypatch):+ """Guard: if the fixture ever stopped being untied, the rest of this+ file would pass vacuously (a tied model never re-copies at all)."""+ wrapper, _, _ = _build_untied_wrapper(tmp_path, monkeypatch)+ large_pool = wrapper._stream_runtime.large_pool+ assert large_pool is not None+ assert len(large_pool.specs) > 1, "fixture is tied; this file needs an untied one"+ wrapper._close_stream_runtime()++ def test_one_step_completes_and_reloads_embed_before_prime_needs_it(+ self, tmp_path, monkeypatch+ ):+ """The whole point of the fix: after one full step (forward, backward,+ optimizer), the slot already holds `embed_tokens` again — reloaded+ during backward, not waiting for the next step's forward-pre-hook."""+ wrapper, _, _ = _build_untied_wrapper(tmp_path, monkeypatch)+ runtime = wrapper._stream_runtime+ large_pool = runtime.large_pool+ prefetcher = runtime.prefetcher+ embed_key = next(key for key in large_pool.specs if "embed_tokens" in key)++ wrapper.trainer.args.max_steps = 1+ wrapper.trainer.train()++ assert prefetcher.backward_tail_prefetched, (+ "layer 0's backward recompute never fired the backward-tail "+ "prefetch — did the checkpoint/backward wiring change?"+ )+ assert large_pool.owner == embed_key, (+ "backward tail fired but did not leave the slot holding embed_tokens"+ )+ wrapper._close_stream_runtime()++ def test_two_steps_complete_without_an_autograd_version_error(self, tmp_path, monkeypatch):+ """The regression this guards against would not be a wrong number —+ it would be `RuntimeError: ... modified by an inplace operation`, the+ same failure class #1049 hit for the untied projection. A second step+ is what actually exercises the boundary: the first step's backward+ tail must hand `_prime()` a slot nothing from the first step still+ needs."""+ wrapper, _, _ = _build_untied_wrapper(tmp_path, monkeypatch)+ wrapper.trainer.args.max_steps = 2+ wrapper.trainer.train()+ losses = [entry["loss"] for entry in wrapper.trainer.state.log_history if "loss" in entry]+ assert len(losses) == 2+ assert all(loss == loss for loss in losses) # not NaN+ wrapper._close_stream_runtime()++ def test_prime_no_op_saves_one_reload_from_the_second_step_on(self, tmp_path, monkeypatch):+ """Counts real copies directly: from the second step on, `_prime()`'s+ load is a same-owner no-op, so a steady-state step costs two real+ large-layer loads (the head at the forward tail, the embedding at the+ backward tail), the same two `main` makes per step."""+ wrapper, _, _ = _build_untied_wrapper(tmp_path, monkeypatch)+ large_pool = wrapper._stream_runtime.large_pool+ wrapper.trainer.args.max_steps = 2+ wrapper.trainer.train()+ # `main` makes 4 real loads over these 2 steps: the cold embed load in+ # step 0's `_prime()` and the head at its forward tail, then the embed+ # in step 1's `_prime()` and the head at its forward tail. This change+ # makes 5. Steady state is 2 loads per step in both trees; the fifth is+ # the LAST backward's prefetch, which no later forward ever consumes,+ # so every `train()` now ends with exactly one extra load.+ assert large_pool.loads == 5, large_pool.loads+ wrapper._close_stream_runtime()++ def test_the_refill_fires_once_per_backward_at_layer_0(self, tmp_path, monkeypatch):+ """Where in the backward the refill fires, not only that it fires.++ On two layers the first recompute that walks downward IS layer 0, so a+ refill moved to the start of the backward passes every other test here.+ On a real model that would queue the whole head-sized copy in front of+ the backward's decoder copies on the shared copy stream, and change the+ order of `source.get()` calls, which #975 relies on being unchanged.+ Four layers tell the two apart.+ """+ wrapper, _, _ = _build_untied_wrapper(tmp_path, monkeypatch, n_layers=4)+ prefetcher = wrapper._stream_runtime.prefetcher+ refill = prefetcher.backward_tail_prefetch+ fired_at = []++ def _recording_refill():+ fired_at.append((prefetcher.direction, prefetcher.prev))+ refill()++ prefetcher.backward_tail_prefetch = _recording_refill+ wrapper.trainer.args.max_steps = 2+ wrapper.trainer.train()+ wrapper._close_stream_runtime()+ # (direction, layer) at each call: once per step, walking down, at layer 0.+ assert fired_at == [(-1, 0), (-1, 0)], fired_at+++class _PinnedSource:+ def __init__(self, tensors):+ self.tensors = tensors++ def get(self, idx, key):+ return self.tensors[key]+++def test_refill_waits_for_a_read_still_queued_on_the_compute_stream():+ """The GPU-side guard for the backward-tail refill, at pool level so it does+ not depend on how fast the host is.++ When the CPU reaches layer 0, the head's backward GEMM can still be queued on+ the compute stream, reading the shared slot. What orders the refill after it+ is `stream.wait_stream(torch.cuda.current_stream())` in+ `LargeLayerBufferPool.load_async`. Remove that wait and the copy stream+ overwrites the slot while the queued read has not run, so `seen` picks up the+ embedding's bytes instead of the head's.++ The compute stream is held back with `torch.cuda._sleep`, about a second, and+ the refill is issued microseconds after the read is queued, so the race is+ always open. A trainer-level version of this needs to assert the race really+ opened (for example `event.query()` on the sleep when the prefetch fires);+ otherwise a slow host makes it pass with the guard deleted.+ """+ import torch++ from soup_cli.utils.layer_stream_runtime import LargeLayerBufferPool++ shape = (1024, 1024)+ pool = LargeLayerBufferPool(+ {"lm_head": (shape, "float32"), "embed_tokens": (shape, "float32")},+ {"lm_head": 0, "embed_tokens": 1},+ device="cuda",+ )+ head = torch.full(shape, 1.0).pin_memory()+ embed = torch.full(shape, 2.0).pin_memory()+ source = _PinnedSource({"lm_head": head, "embed_tokens": embed})+ copy_stream = torch.cuda.Stream()++ pool.load_async("lm_head", source, copy_stream)+ slot = pool.wait("lm_head")+ torch.cuda.synchronize()++ torch.cuda._sleep(int(1e9)) # the compute stream lags, like a queued head backward+ seen = slot.clone() # a read of the slot, queued behind the sleep+ pool.load_async("embed_tokens", source, copy_stream) # the #975 refill+ torch.cuda.synchronize()++ assert torch.equal(seen, head.cuda())