Skip to content

Decode graphs on by default for RL trainer generation, released on return to training - #15188

Merged
danielhanchen merged 5 commits into
mainfrom
grpo-decode-graphs-default
Oct 25, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
grpo-decode-graphs-default

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

#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.

…e buffers on return to training

UNSLOTH_DECODE_CUDA_GRAPHS is now read per generate() call: 1 forces graph decode on, 0 forces it
off, unset turns it on only inside an RL trainer's generate() (GRPO, RLOO, online DPO and the other
TRL trainers that generate through unwrap_model_for_generation without vLLM) and leaves plain
model.generate() eager. When generation returns to training, the decode graphs, their pool and the
decode buffers (KV cache) are released, since the next optimizer step invalidates the graphs anyway.
ROCm / HIP (and builds without a CUDA device) stay on the eager decode step unless
UNSLOTH_DECODE_CUDA_GRAPHS=1 forces graphs: HIP graph replay is not verified bitwise against the
eager step there.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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-25T03:41:17.937307Z eb435d5 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. Delightful!

Reviewed commit: ed436d3f1b

ℹ️ 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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: eb435d5e1a

ℹ️ 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 cc1b758 into main Oct 25, 2026
11 of 30 checks passed
@danielhanchen
danielhanchen deleted the grpo-decode-graphs-default branch October 25, 2026 04:00
danielhanchen added a commit that referenced this pull request Oct 25, 2026
…wrap test _decode_graphs (#15209)

## Summary

Two merges left `Repo tests (CPU, rest)` red on main (for example on
#15199, base `0705fa58`):

1. **#15174 (tensor parallelism v2)** reads
`model.safetensors.index.json` with a bare `open()` at
`unsloth/models/tp_native.py:1636` and `:1660`, and its new test does
the same at `tests/test_tp_native_oracle.py:697`. #15185 (padded batches
vs padding-free) added `tests/test_padding_choice.py:267` with a bare
`read_text()`. The two encoding guards flag all four:

```
tests/test_runtime_text_encoding.py::test_shipping_code_names_an_encoding
  ['unsloth/models/tp_native.py:1660: open()', 'unsloth/models/tp_native.py:1636: open()']
tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding
  ['tests/test_padding_choice.py:267: read_text()', 'tests/test_tp_native_oracle.py:697: open()']
```

The two `tp_native.py` sites are product code, and the guard is right
about them: a checkpoint index read under a non-UTF-8 Windows locale can
fail or mis-decode.

2. **#15188 (decode graphs on by default for RL)** wrapped
`unsloth_unwrap_model_for_generation`'s generate in
`_decode_graphs.rl_generation()` and calls
`_decode_graphs.release_for_training(model)` on the way back to
training. `tests/test_ppo_trainer_patches.py` lifts that function out of
`rl.py` with `ast` and never gave it `_decode_graphs`, so both unwrap
tests stop with `NameError: name '_decode_graphs' is not defined`.

## Change

- `tp_native.py`, `test_tp_native_oracle.py`, `test_padding_choice.py`:
`encoding = "utf-8"` on the four reads.
- `test_ppo_trainer_patches.py`: the lifted function gets a
`_decode_graphs` whose `rl_generation` is the real scope from
`unsloth/models/_decode_graphs.py` (loaded by file path), with entering
it and `release_for_training` recorded in the existing `calls` list. The
PPO-policy test now asserts the full order: `for_inference`,
`rl_generation`, `release_for_training`, `for_training`. The plain-model
test asserts generation happens inside the scope before the release.

## Verification

- On main: the two encoding guards fail and both unwrap tests raise
`NameError`. With this change the encoding guards give `25 passed`, and
`test_ppo_trainer_patches.py`, `test_padding_choice.py` and
`test_tp_native_oracle.py` give `114 passed, 4 skipped`.
- Sabotage, each against `rl.py`:
1. generate outside `_decode_graphs.rl_generation()`: both unwrap tests
fail
  2. no `release_for_training` before training: both unwrap tests fail
-
`tests/test_tp_native_gloo.py::test_tp2_x_fsdp2_dp2_matches_one_process`
(5 cases) passes on main locally.
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>
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 1, 2026
…ackend (unslothai#15993)

## What changes

Studio's transformers / safetensors chat backend now runs `generate()`
with CUDA-graph decode on by default. Core's plain `model.generate()`
stays eager by default, as unslothai#15188 chose.

- `unsloth/models/_decode_graphs.py` gets a `studio_generation` scope.
It works like `rl_generation`: it is per thread and sets no environment
variable. Inside it, with `UNSLOTH_DECODE_CUDA_GRAPHS` unset, graphs are
on only on NVIDIA CUDA (`_DEFAULT_OK`) and not on native Windows
(`_STUDIO_DEFAULT_OK`). The order of `enabled()` is unchanged, so
`UNSLOTH_DECODE_CUDA_GRAPHS=0` still turns graphs off and `=1` still
forces them on.
- `studio/backend/core/inference/inference.py`:
- `generate_stream` wraps only its `model.generate(**generation_kwargs)`
call, on the generate thread, in that scope. This one call serves chat,
compare mode and the tool-calling loop.
  - An Unsloth without the scope keeps the old behaviour.
- `unload_model` now frees the model's captured graphs, graph pool and
decode buffers before `clear_gpu_cache()`. It skips this while a
generation still holds the generation lock. In that case the generating
thread's reference frees them when it ends.

Why only Studio: the transformers backend runs in its own worker process
and only serves inference, so there is no training afterwards that the
graphs could interfere with.

Graphs and their KV buffers stay alive across chat turns while the model
is loaded. They are freed on:
- unload;
- model switch, since load unloads the previous model first;
- worker shutdown;
- training start when Studio frees chat.

Which models use graphs: the decode path supports `llama` and `qwen3`
(`_SUPPORTED_MODEL_TYPES`) on one CUDA device, 4-bit or 16-bit, base or
with LoRA. Everything else is unchanged and eager:
- other model types, including Qwen2, Mistral, Gemma 1/2/3/4, MoE models
and gpt-oss;
- vision, text diffusion and audio models;
- multi-GPU and layer offload.

Model changes between generations re-capture through the existing
fingerprint check, which runs on the first graphed step of every
`generate()`:
- adapter enable / disable / switch in compare mode, adapter load,
merge;
- quant state;
- RoPE table;
- buffer growth for longer max lengths.

Sampling settings act on the returned logits, outside the graph. If a
capture fails, the model falls back to eager with the same output.

## Results

The benchmark ran on a Colab Tesla T4 with torch 2.14.1+cu130 and
transformers 5.17.0. It goes through Studio's real backend
(`InferenceBackend.load_model` + `generate_chat_response`): batch 1,
greedy, up to 512 new tokens, thinking off.

Decode speed with the eager and graph arms rotated in one process (ABBA,
3 rounds = 6 runs per arm for 4-bit, 2 rounds = 4 runs for 16-bit).
Eager is `UNSLOTH_DECODE_CUDA_GRAPHS=0`; graphs is the new default.
Values are the median with [min, max]:

| model | load | eager tok/s | graphs tok/s | speedup | TTFT ms eager /
graphs | replays per call |
|---|---|---|---|---|---|---|
| Qwen3-0.6B | 4-bit | 32.1 [31.0, 32.5] | 111.1 [108.4, 113.1] | 3.46x
| 93 / 96 | 0 / 207 |
| Llama-3.2-1B-Instruct | 4-bit | 55.6 [54.9, 55.8] | 115.4 [112.7,
116.5] | 2.08x | 64 / 64 | 0 / 510 |
| gemma-3-270m-it | 4-bit | 20.5 [20.4, 20.7] | 20.4 [20.3, 20.5] |
1.00x (not graphed) | 106 / 108 | 0 / 0 |
| Qwen3-0.6B | 16-bit | 30.7 [30.6, 31.2] | 110.9 [107.5, 111.9] | 3.61x
| 87 / 86 | 0 / 288 |
| Llama-3.2-1B-Instruct | 16-bit | 52.3 [51.9, 52.6] | 67.2 [51.6, 73.7]
| 1.0x to 1.4x | 51 / 53 | 0 / 510 |

- The eager-vs-eager spread (A/A) was 1.4% to 4.5%.
- Time to first token is unchanged: the prefill and the first decode
step stay eager, and the graph is captured on a later step.
- Llama-3.2-1B in 16-bit is the noisy case: the graph arm ranged from
51.6 to 73.7 tok/s, and a fresh head process measured 53.8 tok/s against
51.5 on main. This model in fp16 on a T4 is closer to being limited by
memory bandwidth than by the host, so the win is small there.

Main vs this branch, each in a fresh process with the variable unset, on
the same card:

| model | load | main tok/s | branch tok/s | peak alloc GiB main /
branch | resident after reply GiB main / branch | card used GiB main /
branch | allocated after unload GiB |
|---|---|---|---|---|---|---|---|
| Qwen3-0.6B | 4-bit | 32.7 | 112.9 | 0.639 / 0.670 | 0.633 / 0.664 |
0.796 / 0.862 | 0.016 / 0.016 |
| Llama-3.2-1B-Instruct | 4-bit | 56.2 | 112.2 | 1.127 / 1.144 | 1.092 /
1.106 | 1.288 / 1.331 | 0.016 / 0.016 |
| gemma-3-270m-it | 4-bit | 20.7 | 20.2 | 0.403 / 0.403 | 0.382 / 0.382
| 0.557 / 0.557 | 0.016 / 0.016 |
| Qwen3-0.6B | 16-bit | 31.1 | 107.3 | 1.212 / 1.243 | 1.206 / 1.237 |
1.358 / 1.425 | 0.016 / 0.016 |
| Llama-3.2-1B-Instruct | 16-bit | 51.5 | 53.8 | 2.371 / 2.388 | 2.368 /
2.382 | 2.526 / 2.569 | 0.016 / 0.016 |

- Memory: graphs cost 0.014 to 0.031 GiB of allocated memory and 0.04 to
0.07 GiB of card memory at these sizes. Each model captured one graph
across all calls, so memory did not grow over turns.
- Unload: allocated memory returns to the same 0.016 GiB as on main.
- Output: token ids and the full sequence of streamed text chunks are
identical in every arm (main, branch eager, branch graphs) for every
model and load mode.

## Tests

- `tests/test_decode_cuda_graphs_studio.py`. The decision tests load
`_decode_graphs.py` by file path and run on CPU. They cover:
- the scope turning graphs on under the NVIDIA default and nesting with
`rl_generation`;
  - `=0` and `ENABLED=False` winning;
  - non-NVIDIA hosts (HIP spoof, `_DEFAULT_OK=False`) staying eager;
  - the scope being per thread and unwinding on error.

A CUDA test loads a tiny Qwen3 and checks that plain `generate()` stays
eager, that generation inside the scope replays with bitwise-equal
sequences and logits, and that release frees the graphs and buffers. On
main 5 fail; on this branch all pass (the CUDA test was skipped on the
CPU host).
- `studio/backend/tests/test_transformers_decode_graphs.py` (CPU, real
`_decode_graphs.py` under a spoofed NVIDIA default). It checks that:
- the chat generate thread sees graphs on, while the caller thread stays
eager;
  - `=0` disables graphs;
  - non-NVIDIA stays eager;
  - an Unsloth without the scope keeps the old behaviour;
  - unload frees graph state and decode buffers;
  - unload during a running generation leaves them alone.

  On main 2 fail (graphs on, unload frees); on this branch all 6 pass.
- `tests/test_decode_cuda_graphs_default.py` is unchanged and passes.
- Neighbour Studio tests (15 files: stop sequences, generation budget,
reasoning stream, active generations, chat EOS, tool turns, templates,
diffusion LM, fine-tuned serving, chat during training, training VRAM
coexistence, unload): 1436 passed, 1 skipped, on both main and this
branch.
- Neighbour Core decode-graph / PPO / cached attention tests: 79 passed,
27 skipped, on both main and this branch.
- The changed and new files compile on Python 3.9 through 3.14.

## Not covered

- AMD ROCm, Intel XPU, Apple MPS and CPU are unchanged by design
(`_DEFAULT_OK` is False there). Only the CPU tests cover that decision.
- Windows with an NVIDIA GPU was not run, so the Studio default is off
there: native Windows stays eager unless `UNSLOTH_DECODE_CUDA_GRAPHS=1`.
Linux and WSL get the default.
- H100 and B200 were not measured.
- The DoRA case below is covered by a GPU test with a faked DoRA check,
not by a real DoRA adapter in Studio.
- Memory after unloading during a running reply was measured after
`gc.collect()`.
- When Studio keeps chat loaded beside a training job, the chat worker
keeps its graphs. Studio's fit check counts them, and eager decode
buffers behave the same way.

## Notes

- A generation the graphs cannot serve (a DoRA or other non-LoRA
adapter, or parameters on several devices) frees the captured steps and
runs eager; the next `generate()` checks again, so switching back to
base or a plain LoRA is graphed again.
- Compare mode toggles the adapter between its two answers, so each
toggle re-captures the graph once.

## Review fixes and A100 / L4 re-run

- **CPU CI:** the CUDA test in `tests/test_decode_cuda_graphs_studio.py`
now gates on `real_accelerator.has_real_cuda`.
`torch.cuda.is_available()` is patched to True by the CUDA spoof in the
CPU job, which `tests/python/test_accelerator_skip_guards.py` rejects.
- **Windows:** the Studio default is Linux / WSL only (see above). `=1`
still forces graphs on everywhere; `rl_generation` is unchanged.
- **Ineligible generations:** a DoRA / non-LoRA adapter (one side of
compare mode) or parameters on several devices used to set a sticky
`disabled` without freeing the captured steps, so graphs stayed off
until unload. Now that generation frees them and runs eager, and the
next one is re-checked.
- **Failed capture:** `_capture` joins the side stream in a `finally`,
so the eager fallback after a failed warmup / capture is ordered after
the side-stream work.

GPU tests on Colab A100, torch 2.14.1
(`tests/test_decode_cuda_graphs.py` +
`tests/test_decode_cuda_graphs_studio.py`): 29 passed on this branch.
With this branch's tests on main's code, the 9 new tests fail (the two
regression tests above and the 7 Studio scope tests) and the other 20
pass.

Studio's real backend (`load_model` + `generate_chat_response`), greedy,
512 new tokens, main vs this branch in fresh processes, 3 rounds:

| GPU | torch | model | load | main tok/s | branch tok/s | speedup | A/A
spread |
|---|---|---|---|---|---|---|---|
| A100 | 2.14.1 | Llama-3.1-8B-Instruct | 4-bit | 30.8 | 105.5 | 3.43x |
0.8% |
| A100 | 2.14.1 | Qwen3-8B | 4-bit | 25.7 | 99.1 | 3.86x | 1.3% |
| A100 | 2.14.1 | Qwen3-0.6B | 16-bit | 32.2 | 124.4 | 3.86x | 1.2% |
| L4 | 2.14.1 | Llama-3.2-1B-Instruct | 4-bit | 54.3 | 145.2 | 2.67x |
1.0% |
| L4 | 2.14.1 | Llama-3.2-1B-Instruct | 16-bit | 52.2 | 86.2 | 1.65x |
1.1% |
| L4 | 2.14.1 | Qwen3-1.7B | 4-bit | 30.9 | 102.4 | 3.31x | 1.2% |
| L4 | 2.10.0 | Llama-3.2-1B-Instruct | 4-bit | 52.3 | 143.4 | 2.74x |
0.9% |

- Token ids and the full streamed chunk sequence are identical across
main, branch eager and branch graphs on every row; TTFT is unchanged.
- Graphs cost 0.02 to 0.08 GiB of peak allocated memory. After unload,
allocated memory is back at main's 0.016 GiB (0.024 GiB on the torch
2.10 row, one run).
- Unload while a reply is streaming (A100 8B, L4 1B): the reply
finishes, and after its thread ends memory is back at 0.016 GiB on both
arms.
- Compare mode on L4 (Llama-3.2-1B 4-bit + LoRA r16, base / adapter
alternated 4 times, 256 tokens): each toggle re-captures once; base
135.8 to 138.0 tok/s and adapter 134.3 to 135.8 tok/s with graphs,
against 52.1 to 53.2 and 34.5 to 35.0 eager, with the same tokens.



## After the main merge (L4, torch 2.14.1, transformers 5.17.0, merge
base 3ecb1ba)

The merge conflict in `studio/backend/core/inference/inference.py` was
resolved by keeping both sides: the decode-graph scope and main's
`_supported_generate_kwargs` filter. GPU pytest of
`tests/test_decode_cuda_graphs.py` and
`tests/test_decode_cuda_graphs_studio.py`, each arm importing its own
tree:

| tree | result |
|---|---|
| this branch | 29 passed |
| main's code with this branch's tests | 9 failed, 20 passed |

The 9 that fail on main are the new tests: the Studio scope (on for
NVIDIA CUDA, off elsewhere and on native Windows, per thread, honours
the variable, unwinds on error, plain generate stays eager), the
ineligible-generation recovery and the side-stream join after a failed
capture. The Studio backend CPU tests touching generate kwargs and
inference also pass on the merged tree (400 passed).
danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Nov 14, 2026
…re failure disabled (unslothai#15217)

## What

`unsloth/models/_decode_graphs.py` keeps a per-model `state.disabled`
reason once graph decode gives up (a capture that raised, a `None`
fingerprint from parameters on another device / a non-LoRA adapter, or
an eligibility reason). Nothing ever cleared it: `release()`,
`release_for_training()` and `invalidate()` drop the graphs, statics,
pool and buffers, but leave `disabled` set, so the model runs the eager
decode step for the rest of its life. `stats(model)["disabled"]` is the
only place it shows.

## Why it matters

unslothai#15188 calls `release_for_training(model)` on every RL step. The
memory-tight case that produces a capture OOM mid-GRPO is exactly the
case where the next step, after that release, would capture fine;
instead the whole run silently loses graph decode after one bad step.
The same holds for `invalidate()`, whose docstring promises "they
re-capture on the next decode".

## How

Clear `state.disabled` where the graphs and buffers it was decided
against are dropped: in `release()` (and so `release_for_training()`)
and in `invalidate()`. The next decode re-runs `_eligible` /
`_fingerprint`; a structural reason (model type, block swap, non-LoRA
adapter, multi-device) is two attribute reads and disables again on that
step. A capture that fails persistently retries once per release, which
is once per RL step; `UNSLOTH_DECODE_CUDA_GRAPHS_STRICT=1` still raises
on the first failure for diagnosis.

Deliberately not done: a retry budget or a per-reason split. Both add
state for a case (persistent capture failure) that the strict flag
already surfaces.

## Verification

CPU,
`tests/test_decode_cuda_graphs_default.py::test_release_rearms_a_disabled_model`
(new): sets `disabled` on a model's state and asserts `release()` and
`invalidate()` each clear it.

| | release() | invalidate() |
|---|---|---|
| main (ceedcaf) | reason kept | reason kept |
| this branch | `None` | `None` |

`ruff check`, `enforce_kwargs_spacing.py` and the
`ruff-format-with-kwargs` hook pass; both files parse under Python 3.9.
I have no CUDA box, so the GPU tests in this file ran only in CI.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
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