Skip to content

Decode graphs: grow the KV cache instead of reserving max_new_tokens, and capture on the model's GPU - #15237

Merged
danielhanchen merged 3 commits into
mainfrom
decode-graphs-device-and-kv-growth
Oct 25, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
decode-graphs-device-and-kv-growth

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

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.

… and capture on the model's GPU

Two gaps in the graphed decode step that #15188 turned on by default for RL generation:

- KV size: the graph-mode cache was allocated for prompt + max_new_tokens at the first
  decode step, so a rollout that stops early held the whole limit (Qwen3-0.6B, 8 rows,
  max_new_tokens 4096 stopping after 64: 3889 MiB extra vs 487 MiB eager). It now starts
  like the eager cache (prompt + one increment, 256-row bucket) and doubles on growth,
  capped at the hint, so a long rollout re-captures O(log n) times
  (UNSLOTH_DECODE_GRAPH_PREALLOC=1 restores the old sizing).
- Device: a model on a GPU other than the current one never replayed. The native decode
  allocated its scratch on device 0 and copied it to the model's GPU every step, which
  a capture cannot record, so the capture failed and generation stayed eager. Scratch
  now lives on the embedding's device (unchanged for models on, or split from, device 0),
  and the graphed step runs with the model's GPU current (stream and pool there).

Qwen3-0.6B bf16, 8 rows, B200 (shared lease), 3 interleaved reps per arm: early stop
729 MiB extra (main 3889), 1024 forced tokens 2 captures (main 1), graph time within the
main A/A spread, 5-6x eager; every arm's ids equal the eager ids. Tiny Qwen3 on cuda:1
with cuda:0 current now captures and replays bit for bit.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 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-25T11:21:16.786820Z 844a78b 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. Bravo.

Reviewed commit: 844a78b51d

ℹ️ 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 dc55427 into main Oct 25, 2026
@danielhanchen
danielhanchen deleted the decode-graphs-device-and-kv-growth branch October 25, 2026 11:26
danielhanchen added a commit that referenced this pull request Oct 25, 2026
…15270)

`tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe`
fails on main since #15237. It shows on the studio shard of every newer
PR, for example #15217:

```
test_decode_graphs_kv_growth_device.py:127: torch.cuda.is_available()
test_decode_graphs_kv_growth_device.py:127: torch.cuda.device_count()
```

## Cause

The guard is right. `tests/_zoo_aggressive_cuda_spoof.py` patches
`torch.cuda.is_available()` and `device_count()` process-wide, so these
skips would un-skip on a CPU-only runner whenever they share a session
with the spoofing suites. The two-GPU test would then call
`torch.cuda.set_device(0)` there.

## Fix

- `test_decode_graphs_kv_growth_device.py` now gates on
`has_real_cuda()` from `tests/_shared/real_accelerator.py`, the answer
recorded before any spoof:
  - the two-GPU skip short-circuits on it before `device_count()`;
  - the module-level `cuda` marker gates on it too.
- The guard only scans decorator `skipif` calls, so it does not see that
marker. It is the same spoofable read, so it is changed here as well.

## Verification

- `test_accelerator_skip_guards.py`: 1 failed on main; 24 passed here.
- On CPU, the file's three CUDA tests skip with the same reasons as
before.
- On a real GPU host, `has_real_cuda()` returns True, so the CUDA tests
still run there.
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