Repository navigation
Decode: write K/V straight into the cache slot, and opt-in CUDA-graph replay of the decode step - #15171
Merged
Conversation
… replay of the decode step (UNSLOTH_DECODE_CUDA_GRAPHS=1)
Member
Author
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
danielhanchen
added a commit
that referenced
this pull request
Oct 25, 2026
…15182) ## Summary `tests/utils/test_single_row_cached_attention.py` errors on all 64 cases on main since #15171 (K/V straight into the cache slot, opt-in CUDA-graph decode). That fails the `Core (HF=...)` legs on unrelated PRs, for example #15176 and #15178: ``` AssertionError: Qwen3Attention_fast_forward_inference now reads ['_decode_attention_core', '_decode_graphs']; give the harness a CPU stand-in for each ``` The harness lifts `LlamaAttention_fast_forward_inference` and `Qwen3Attention_fast_forward_inference` out of their files with `ast`, and refuses to run if they read a global it does not provide. #15171 moved the cache and scratch buffer setup into `unsloth/models/_decode_graphs.py` (`alloc_decode_buffers`, `resize_decode_buffers`) and added the captured-step branch that calls `_decode_attention_core`. The product is fine. The guard did what it is meant to do and asked for stand-ins. ## Change - `_decode_graphs`: the real module, loaded by file path. Its top level is torch and the standard library only. `ENABLED` is forced to `False`, because graph replay is CUDA-only. The test keeps running the real `alloc_decode_buffers` / `resize_decode_buffers` instead of a copy. - `_decode_attention_core`: a stand-in that raises if called. It is only reached from a captured decode step, which this CPU harness never enters, so reaching it would mean graph mode leaked in. ## Verification - On main: `64 errors`. With this change: `64 passed`. It also passes with `UNSLOTH_DECODE_CUDA_GRAPHS=1` set. - Sabotage 1: writing the wrong V rows in `_decode_graphs.alloc_decode_buffers` gives 56 failures. The real helper is what the test exercises. - Sabotage 2: skipping qwen3's 2D padding mask conversion in the decode function gives 8 failures. The masking checks the file was written for still bite.
danielhanchen
added a commit
that referenced
this pull request
Oct 25, 2026
…turn to training (#15188) #15171 added CUDA-graph replay of the native decode step behind `UNSLOTH_DECODE_CUDA_GRAPHS=1`, bitwise identical to eager. Generation in TRL trainers that use `model.generate()` without vLLM (GRPO, RLOO, online DPO, GKD, NashMD / XPO, PPO) is host bound: about 285k kernel launches per generation for Qwen3-1.7B, 8 x 256 tokens. This PR turns graph decode on by default there, and only there. ### Change - **Runtime switch:** `_decode_graphs.enabled()` replaces the import-time `ENABLED` and reads `UNSLOTH_DECODE_CUDA_GRAPHS` on each call: - `1`: on everywhere, as before; - `0`: off everywhere; - unset: on only inside the new per-thread `rl_generation()` scope, on NVIDIA CUDA. `ENABLED` stays as a programmatic override. Under `torch.compiler.is_compiling()` both `enabled()` and `static()` return early. `unsloth_fast_generate` decides once per call, so prefill and every decode step agree. - **Where the scope is entered:** `rl.py`'s `unsloth_unwrap_model_for_generation`. That one place covers every TRL trainer that generates with `model.generate()` without vLLM, plus the TRL completion-logging callbacks. Plain `model.generate()` and hand-written decode loops stay eager unless the flag is `1`. - **Platforms:** - The unset default is NVIDIA CUDA only (`torch.version.hip is None and torch.cuda.is_available()`, computed once at import). - ROCm / HIP stays eager unless the flag is `1`. - XPU, MPS and CPU never take the graphed step. - **Memory release:** when the generation context returns to training, the new `release_for_training(model)` frees the decode graphs, their memory pool and the decode KV buffers, so graphs no longer hold memory through the backward. - **Effect without graphs:** this also frees the eager decode buffers, which main kept allocated through training. The next prefill re-allocates them, the same path `generate(past_key_values=...)` already uses. With the flag at `0`, results stay bitwise equal to main. - The `restore_training_mode` path inside `generate()` releases the same way when graphs were used. - **Graph-buffer scope:** graph-style decode buffers are allocated only for the llama and qwen3 model types. Other Llama-family models keep their exact eager buffers. ### Results **Correctness (B200, torch 2.10 and 2.14).** 16 cells: {Qwen3-0.6B, Llama-3.2-1B} x {bf16, 4-bit, `num_iterations=2` with `steps_per_generation=2`, a generation batch split into two sizes}. Each cell is a deterministic 6-step GRPO run, flag `0` vs unset. In every cell these are bitwise equal: - the completion SHA; - loss, grad_norm, KL and reward at every step; - the final LoRA SHA. Further checks: - **Shadow check:** every graphed generation replayed eagerly in the same process gives equal token ids, every sampling distribution, and the RNG state after. - **Engagement:** 6 captures and 203-372 replays per run, with 0 decode buffers left on the model after each generation. - **Flag 0 control:** flag `0` vs flag `0` is also equal. **Speed, Qwen3-1.7B GRPO, 8 generations x 256 tokens, torch 2.14.1.** Main is eager by default; this PR uses graphs by default. | GPU | main s / step | this PR s / step | speedup | A/A spread | generation tok/s | |---|---|---|---|---|---| | A100 40GB (Colab, 2 + 2 runs, interleaved) | 12.24-12.26 | 2.80-2.81 | 4.37x | 0.2% | | | T4 (Kaggle T4x2, one arm per GPU, mirrored order, 4 runs each) | 15.70-16.27 | 8.12-9.04 | 1.81x | 3.6% (main), 10.4% (PR) | 132 to 315 | - **Profile (one generation):** kernel launch calls drop from 285,118 to 38,561, and GPU busy time goes from 65% to 96% on T4. - **Re-capture cost:** about 95-115 ms per optimizer step, since every optimizer step invalidates the graphs. - **Llama-3.1-8B 4-bit, 8 x 512 (A100):** fits easily at a 7.0 GB peak. On the one step with a full-length rollout (about 320 tokens), generation is 1.94x faster and the step 1.8x. **Memory (Qwen3-1.7B GRPO).** | arm | generation peak GB | training peak GB | max reserved GB | |---|---|---|---| | main (eager) | 4.017 | 4.189 | 4.371 | | main with flag `1` (old behaviour, graphs held through training) | 4.259 | 4.887 | 5.213 | | this PR, default | 4.259 | 4.187 | 4.520 | The training peak is identical to main. Graphs add 0.24 GB at generation, and nothing is held into the backward. ### Tests New `tests/test_decode_cuda_graphs_default.py` covers: - the decision table, per-thread scoping and trace safety; - the HIP gate; - plain `generate()` staying eager while RL-scope generation matches eager bitwise; - flag `0` winning inside the scope and flag `1` turning plain `generate()` on; - everything released when generation returns to training; - a real 2-step GRPOTrainer run that replays graphs and holds no buffers when the loss runs. On main the GRPO case shows 0 replays and eager buffers still held at loss time. With `tests/test_decode_cuda_graphs.py` and `tests/test_decode_kv_direct.py`, 34 passed on B200 for torch 2.14 and 2.10, each with the flag unset and with `0`. The broader decode suites gave 113 passed, 5 skipped, for each of unset / 0 / 1 on both torch versions. ### Not covered - **H100:** no data (no Colab capacity at the time). The L4 ratio was not re-measured for this change. - **Other trainers:** RLOO / online DPO / GKD / PPO use the same `unwrap_model_for_generation` path, but only GRPO was run end to end. - **Multi-GPU / DDP:** not run. vLLM generation never reaches this path. - **ROCm and Windows:** stay on the existing behaviour by the gate and were not run here. - **Remaining host cost:** with graphs on, about 3 `cudaStreamSynchronize` per token (from sampling / stopping checks) are now the main host cost. Removing them is a separate follow-up. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen
added a commit
that referenced
this pull request
Oct 25, 2026
… and capture on the model's GPU (#15237) Two fixes to the native decode CUDA graphs from #15171, which #15188 turned on by default inside TRL generation (GRPO, RLOO, online DPO and the others that call `model.generate()` without vLLM). ### 1. Graph-mode KV cache no longer reserves `max_new_tokens` up front In graph mode the KV cache was sized for prompt + `max_new_tokens` before the first decode step. Rollouts usually stop long before the limit, but the whole cache stayed allocated for the generation. With graphs now on by default for RL, that is a new OOM risk on 16 GB cards when `max_completion_length` is large. Qwen3-0.6B bf16, 8 rows, `max_new_tokens=4096`, every row stopping after 64 tokens (B200, torch 2.14.1, 3 reps, two interleaved rounds): | arm | eager peak MiB | graphs peak MiB | graphs s | captures | ids equal to eager | |---|---|---|---|---|---| | main | 487 | 3889 | 0.31-0.46 | 1 | yes | | this PR | 487 | 729 | 0.27-0.55 | 1 | yes | Qwen3-4B bf16, same setup, stopping after 128 tokens (2 reps per arm, interleaved): | arm | eager peak MiB | graphs peak MiB | graphs s | eager s | |---|---|---|---|---| | main | 632 | 5032 | 0.62-0.66 | 2.1-3.0 | | this PR | 632 | 937 | 0.63-0.74 | 2.6-3.0 | **Change (`_decode_graphs.py`):** - `alloc_decode_buffers` starts the graph-mode cache the way eager does: prompt + one increment, rounded up to the 256-row bucket. - `resize_decode_buffers` in graph mode grows by doubling (at least one increment), capped at the call's prompt + `max_new_tokens`. A long rollout therefore re-captures O(log n) times, not once per increment. - `UNSLOTH_DECODE_GRAPH_PREALLOC=1` restores the old up-front sizing. **Full-length rollout, same setup but no early stop:** | arm | eager peak MiB | graphs peak MiB | graphs s | captures | |---|---|---|---|---| | main | 945 | 1196 | 3.30-3.82 | 1 | | this PR | 945 | 1202 | 3.10-4.19 | 2 | On Qwen3-4B with 1024 forced tokens, graph decode takes 4.81-4.97 s on this PR against 4.60-4.96 s on main (eager 18-23 s), with peaks of 1544 vs 1538 MiB. The extra capture sits inside the run-to-run spread, and the 3.8-4.7x speedup over eager is kept. ### 2. A model on a non-current GPU now replays graphs A model on `cuda:1` while `cuda:0` is current never replayed. The capture failed with `cudaErrorStreamCaptureInvalidated`, and decode fell back to eager for the rest of the run. The output was still correct; only the speedup was lost. Root cause, found by logging aten ops during the capture: - `_LlamaModel_fast_forward_inference` allocated its per-step scratch (`residual`, `_XX`, `variance`, `temp_mlp`) on device 0 and copied it to the model's GPU every step. A cross-device copy cannot be captured. - The side stream and graph pool were also created on the current device. **Changes:** - **`llama.py`:** the scratch is allocated on the embedding output's device. For a model on device 0, or one split from device 0, this is the same device as before, so those paths are unchanged. - **`decode_step`:** re-enters under `torch.cuda.device(index)` when the inputs are on another GPU. - **`_capture`:** drops a stream and pool that belong to a different device. On 2 x B200 (Qwen3-0.6B, torch 2.14.1), model on `cuda:1` with `cuda:0` current: - **main:** 0 captures, 0 replays, disabled with the capture error; - **this PR:** graphs capture and replay, with token ids and every step's scores bitwise equal to eager. ### Tests New `tests/test_decode_graphs_kv_growth_device.py`: - an early-stopping rollout no longer holds `max_new_tokens` rows; - a long rollout grows the cache, stays bitwise equal to eager and re-captures only a few times; - the `UNSLOTH_DECODE_GRAPH_PREALLOC=1` kill switch; - a model on a non-current GPU replays bitwise (skipped below 2 GPUs). On main the four GPU cases fail; this PR passes them all. | suite | torch 2.10 | torch 2.14.1 | |---|---|---| | new tests + `test_decode_cuda_graphs.py` + `test_decode_cuda_graphs_default.py` (1 GPU) | 29 passed, 1 skipped | 37 passed, 1 skipped (with `test_decode_kv_direct.py`) | | the same suites on 2 GPUs | | 78 passed (main: 4 failed, 74 passed) | ### Platforms - The graph path is still NVIDIA CUDA only, through the existing gate. ROCm, XPU, MPS and CPU never reach the changed graph code. - The eager scratch change only moves allocations to the device the model already runs on, so single-device and device-0-first splits behave as before. - No UI changes. ### Not covered - GRPO end to end on a 16 GB card (T4 / L4) with a long `max_completion_length`. The memory saving above comes from the decode benchmark, not from a full training run. - Exclusive-card timing of the extra re-captures on long rollouts. The local numbers come from a shared B200. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Unsloth's native decode step is host bound. Each new token launches about 350 kernels for a 1B model and 650 to 880 for 4B / 8B. On A100 and H100 the GPU is busy only 20% to 50% of a decode step. This PR does two things:
UNSLOTH_DECODE_CUDA_GRAPHS=1, default off. Its output is bit-identical to the eager path.Graph replay design
Capture: piecewise, one capture per batch size, split into
n_layers + 1graph segments.KV write without a host index: the write uses
index_copy_with a slot index held in a GPU tensor, not a host int.Buffers: the per (layer, batch size) decode buffers are sized to prompt +
max_new_tokensup front. The first decode step after each prefill stays eager.Invalidation: each graph records a fingerprint of everything it depends on, and is re-captured when any of these changes:
modules_to_save;The fingerprint is checked on every
generate(), every prefill, every optimizer step and every buffer reallocation. For GRPO this means a graph never replays against stale adapter weights.Eager fallback: multi-device, block swap, non-LoRA / DoRA adapters, grad mode,
labels/shift_labels, positions past the RoPE table, and capture failures all run the eager step.Releasing memory:
unsloth.models._decode_graphs.release(model)frees the buffers and graphs. Agenerate()that returnspast_key_valueshands the buffers to the caller, and the next call re-captures (about 40 ms).torch.compile(mode = "reduce-overhead")on the decode step was tried first and does not work here:Results with the flag off (the default)
Colab, torch 2.14.1. Arms ran base, head, head, base for 2 rounds, so each has 4 samples. Values are base tok/s vs this PR.
Results with
UNSLOTH_DECODE_CUDA_GRAPHS=1tok/s eager to graph, 128 new tokens, torch 2.14.1. Median of 2 rounds after a warm-up round, ABBA with an eager A/A arm (A/A band -3.1% to +3.3%, plus one H100 outlier).
Exactness, graph vs eager:
disable_adapterall stay bitwise equal and re-capture. A control that pins the fingerprint replays the stale graph and fails the test.Tests
New
tests/test_decode_cuda_graphs.py(20 tests) covers:release(), and returned caches not being overwritten;shift_labels;New
tests/test_decode_kv_direct.py(8 tests) covers the direct cache-slot write.All on B200.
Not covered
torch.compileinterplay;generate()calls and training steps untilrelease()is called.