Skip to content

Studio: decode with CUDA graphs by default in the transformers chat backend - #15993

Merged
danielhanchen merged 8 commits into
mainfrom
perf/r9-studio-decode-graphs
Nov 1, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
perf/r9-studio-decode-graphs

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

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

…tion ineligibility, stream join on failed capture

- studio_generation turns graphs on by default only off native Windows (unverified there); =1 still forces.
- The CUDA test gates on real_accelerator.has_real_cuda (the CUDA spoof patches torch.cuda.is_available).
- A generation the graphs cannot serve (DoRA / non-LoRA adapter, several devices) frees the captured
  steps and is re-checked at the next generate() instead of disabling graphs until unload.
- _capture joins the side stream in a finally, so a failed warmup / capture cannot race the eager step.
…an ineligible generation frees them

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 30, 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 ⚠️ Failed 2026-11-01T13:31:41.396510Z
We couldn’t complete this review. Comment @codex review to try again.
4cd843a Draft marked ready
ℹ️ 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. 👍

Reviewed commit: 730336e084

ℹ️ 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. What shall we delve into next?

Reviewed commit: 43f3b9496b

ℹ️ 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: 3d171af9a0

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

# Conflicts:
#	unsloth/models/_decode_graphs.py

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 4cd843a4ce

ℹ️ 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 marked this pull request as ready for review November 1, 2026 13:31
@danielhanchen
danielhanchen merged commit 9e31326 into main Nov 1, 2026
@danielhanchen
danielhanchen deleted the perf/r9-studio-decode-graphs branch November 1, 2026 13:31
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