Skip to content

Decode: write K/V straight into the cache slot, and opt-in CUDA-graph replay of the decode step - #15171

Merged
danielhanchen merged 2 commits into
mainfrom
decode-cuda-graphs
Oct 24, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
decode-cuda-graphs

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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:

  1. K/V straight into the cache slot (always on): the decode step's K and V projections write straight into their KV cache slot instead of a temporary that is then copied.
  2. Opt-in CUDA-graph replay of the decode step: 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 + 1 graph segments.

    • Graphed: the norms, Q / K / V / O projections, RoPE, the K/V write, the MLP and lm_head.
    • Eager, between segments: each layer's attention core runs over the true KV length.
    • Why: there are no length buckets, so every replay computes exactly what eager computes at every length. A full graph over padded length buckets was faster (about 6x), but it changes bf16 rounding and greedy output diverged from eager after 15 to 80 tokens, so it was not used.
  • 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_tokens up 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:

    • parameter addresses;
    • LoRA weights with their version counters and fp32-to-bf16 cast caches;
    • the enabled / active / merged state of every adapter module, including lm_head, embedding and modules_to_save;
    • quant state and RoPE table addresses;
    • the optimizer step counter.

    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.

    • Only the Llama and Qwen3 families are enabled; every other family keeps the eager path.
  • Releasing memory: unsloth.models._decode_graphs.release(model) frees the buffers and graphs. A generate() that returns past_key_values hands 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:

  • unpatched, it crashes on the second decode step;
  • patched, it runs at 0.42x to 0.69x eager speed, records one graph per KV length, and greedy tokens differ from eager.

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.

GPU model bsz 1, 4-bit bsz 4, 4-bit bsz 1, 16-bit bsz 4, 16-bit
A100 Llama-3.2-1B 56.9 / 58.9 (+3.6%) 179.9 / 187.4 (+4.2%) 54.6 / 56.6 (+3.7%) 235.6 / 244.5 (+3.8%)
A100 Qwen3-4B 25.5 / 25.7 81.7 / 81.5 24.3 / 24.1 106.2 / 106.0
L4 Llama-3.2-1B 52.4 / 54.4 (+3.8%) 199.9 / 207.8 (+3.9%) 50.8 / 52.7 (+3.8%) 220.5 / 230.5 (+4.6%)
L4 Qwen3-4B 24.2 / 24.2 92.2 / 92.1 23.1 / 23.4 101.8 / 103.6
  • Qwen3: every cell is within the A/A band (0.1% to 2.9%).
  • Llama: 3.6% to 4.6% faster, from the direct cache-slot write.
  • Exactness: raw logits and tokens are bitwise equal to main in 20 of 20 in-process cases on B200. Those cover Llama-3.2-1B and Qwen3-4B in 16-bit and 4-bit, plus Qwen3-0.6B, at batch 1 for 300 tokens, a left-padded batch of 4, an identical-prompt batch of 4, and a 700-token run that grows the KV cache.

Results with UNSLOTH_DECODE_CUDA_GRAPHS=1

tok/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).

GPU model load bsz 1 bsz 4 bsz 8
A100 Llama-3.2-1B 16-bit 54.3 to 176.5 (3.25x) 234.7 to 983.9 (4.19x) 469.5 to 1942 (4.14x)
A100 Qwen3-4B 4-bit 25.6 to 92.5 (3.61x) 81.6 to 252.1 (3.09x) 166.7 to 497.4 (2.98x)
A100 Llama-3.1-8B 4-bit 30.3 to 98.8 (3.26x) 97.3 to 140.0 (1.44x) 196.3 to 276.4 (1.41x)
H100 Llama-3.2-1B 4-bit 88.1 to 314.7 (3.57x) 295.8 to 1245 (4.21x) 603.7 to 2484 (4.11x)
H100 Qwen3-4B 16-bit 41.0 to 155.4 (3.79x) 179.5 to 699.8 (3.90x) 358.2 to 1385 (3.86x)
H100 Llama-3.1-8B 16-bit 47.7 to 117.2 (2.46x) 210.0 to 508.8 (2.42x) 423.1 to 1006 (2.38x)
L4 Llama-3.2-1B 4-bit 54.5 to 147.2 (2.70x) 209.1 to 409.5 (1.96x) 358.0 to 760.2 (2.12x)
L4 Llama-3.1-8B 16-bit 16.3 to 16.5 (1.01x) 63.3 to 63.8 (1.01x) 125.3 to 126.2 (1.01x)
T4 (Kaggle) Llama-3.2-1B 4-bit 53.9 to 131.6 (2.44x) 203.9 to 237.8 (1.17x) 267.8 to 459.9 (1.72x)
T4 (Kaggle) Qwen3-4B 4-bit 23.8 to 31.8 (1.34x) 45.1 to 44.5 (0.99x) 118.9 to 135.8 (1.14x)
  • Where the gain comes from: launch calls per token drop from 354 to 878 down to 183 to 349, and GPU busy time goes from 0.2-0.5 to 0.8-1.0 of the step.
  • Where it gains little: on L4 / T4 and with larger models at batch 4 to 8, the GPU work already fills the card.
  • Peak memory: +0.01 to 0.09 GB at 1B, and +0.18 to 0.64 GB at 4B / 8B with batch 4 to 8.

Exactness, graph vs eager:

  • In process (B200, torch 2.10 and 2.14): tokens and raw logits are bitwise identical over 300 tokens, greedy and seeded sampling, with replays counted. Covered: Llama-1B 16 / 4-bit, Llama-1B with fp32 LoRA in 16 / 4-bit, Qwen3-0.6B, and Qwen3-4B 4-bit with LoRA, at batch 1, a left-padded batch 4 and an identical-prompt batch 4.
  • After a simulated GRPO update: an SGD step, an in-place adapter edit, and disable_adapter all stay bitwise equal and re-capture. A control that pins the fingerprint replays the stale graph and fails the test.
  • Across processes: token and logit hashes match eager on A100, L4 and T4.

Tests

New tests/test_decode_cuda_graphs.py (20 tests) covers:

  • tiny Llama / Qwen3 in 16-bit and 4-bit at batch 1 and 4;
  • LoRA re-capture, with the stale-graph control;
  • manual decode loops across a cache resize;
  • adapter toggle and merge in manual loops;
  • positions past the RoPE table;
  • release(), and returned caches not being overwritten;
  • shift_labels;
  • per-thread statics.

New tests/test_decode_kv_direct.py (8 tests) covers the direct cache-slot write.

torch flag new tests with the 11 existing decode suites (beam search, fused rope, GQA, gemma / granite / nvfp4, ...)
2.14 off 28 passed 173 passed, 5 skipped
2.14 on 28 passed 173 passed, 5 skipped
2.10 off 28 passed 173 passed, 5 skipped
2.10 on 28 passed 173 passed, 5 skipped

All on B200.

Not covered

  • Families and setups: graph mode covers Llama and Qwen3 only. Qwen2, Mistral, Gemma, MoE models, VLMs, multi-device, FSDP, block swap and DoRA use the eager step.
  • In-process parity on other GPUs: in-process graph vs eager parity was checked on B200 only. A100, L4 and T4 have cross-process hashes. On H100, eager itself is not reproducible across processes, so the hashes there are not conclusive.
  • Rebase: the graph-mode speed numbers above were measured before the final rebase; after it, only correctness was re-checked.
  • Not tested at all:
    • a real GRPO trainer run (adapter updates were simulated);
    • contexts beyond about 2k tokens;
    • torch.compile interplay;
    • real multi-threaded generation (only a unit test);
    • ROCm, Windows and MLX.
  • Memory while training: with the flag on, decode buffers stay allocated across generate() calls and training steps until release() is called.

… replay of the decode step (UNSLOTH_DECODE_CUDA_GRAPHS=1)
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-24T23:14:14.564208Z 7fca714 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 7fca7142b5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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
danielhanchen merged commit aae9f54 into main Oct 24, 2026
22 of 29 checks passed
@danielhanchen
danielhanchen deleted the decode-cuda-graphs branch October 24, 2026 23:19
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant