Repository navigation
Decode CUDA graphs for Qwen3.5 / Qwen3.6 hybrid linear-attention caches - #17324
Conversation
Each one-token decode step of unsloth_base_fast_generate replays a CUDA graph of the model's eager forward when decode graphs are enabled (RL rollouts, Studio, UNSLOTH_DECODE_CUDA_GRAPHS=1) on NVIDIA CUDA. Static attention layers only (sliding layers until their window fills); recurrent, offloaded and dynamic caches stay eager. A capture that syncs the host or a first replay that differs from the eager step refuses the key. UNSLOTH_DECODE_GENERIC_GRAPHS=0 turns it off.
…lt 8); count captures per key
…cord capture errors; VALIDATE_ALL debug mode
…/ strides of static buffers, ambient autocast cache
…still 2.7-4.7x at 16)
… strides (non-dense views too) [skip ci]
…r-key decisions, prefill never graphed, setup failures run eagerly, validation leaves the eager step's cache rows [skip ci]
…ps the model's own forward (mixed-precision autocast) or GRPO wraps it; device hooks stay eager
…ead of deleting it
…erence calls Plain generate() on FastModel models now enters generate_scope(), as the llama path and Studio do, and decides one plan per call (plan()): eager when graphs are not wanted, the batch is over the limit, the call is too short to win back a capture (unless a kept graph of its batch replays from the first step), or free memory is low. An out-of-memory graphed call is redone once eagerly without the graph wrapper, from the call's starting RNG and a fresh cache; calls with a streamer, caller cache, stopping criteria or logits processors re-raise as before. After an inference-mode call the graph and its StaticCache stay for the next call of the same batch (transformers 5.x: handed back from _prepare_static_cache; 4.x: model._cache). A returned or caller-owned cache, another batch, a cache over twice the call's length, a training forward, for_training() and release_for_training() drop them. call_plan() exposes the call's plan to per-call policies (the LoRA fold threshold), and weights_changed() bumps an epoch both graph fingerprints carry, for in-place weight rewrites. A flex BlockMask argument replays when its builder publishes _unsloth_graph_closure; any other BlockMask stays refused.
… (Muse-Glimmer, Muse-Spark, Kimi-K2.5) Their forward zeroes image / video (/ audio) placeholder ids with a boolean index assignment, a host sync that no capture can hold, so every decode step stayed eager. A one-token text decode step now gets the inputs_embeds the forward would compute (same masked ids, same embedding module) before the graph; the first replay still validates bitwise against the eager step.
…s, kept sliding caches Sliding windows: only a step that would fill a window part way stays eager; the graph key carries each sliding window's filling / full state, and a full window's rows are restored between the validation replay and the eager step (a roll is not idempotent). _GraphDecodeSteps enters unsloth_zoo.decode_graph_state.graph_generate() for the graphed call and graph_decode_step() for each one-token step (no-op without the module), so zoo picks the same graph-safe kernels for the eager warm-up, the capture and every eager step. A kept cache is matched by the length it was built for: sliding layers are capped at their window, so the layers' own lengths under-state an all-sliding cache and it was never reused.
…device hook A bitsandbytes model placed on a card other than cuda:0 gets accelerate's AlignDevicesHook with force_hooks (vision.py _attach_bnb_multidevice_hooks): an instance forward plus _hf_hook, which wanted() refused, so a model on cuda:1 never decoded through graphs. A root hook that only aligns tensors to the model's own device (AlignDevicesHook, no offload, no weights map, execution device = model.device) is a no-op there and runs in the eager step too, so it stays eligible; other hooks, offload and devices elsewhere stay eager. A decode step whose inputs sit on another card than the weights is refused (the hook would copy across cards inside the graph).
…e step's device; named refusals The inputs_embeds computed before the graph for Muse-Glimmer style decoders are now looked up under no_grad, detached and moved to the decode step's device, so a trainable or host-side (offloaded or hooked) embedding can no longer make the argument check refuse every step. A refused argument now says why and which one: 'tensor argument requires grad (<name>)' or 'tensor argument on <device> (<name>)', so a GPU log explains itself.
…he graph offload_embedding keeps the input embedding in host RAM, so every decode step was refused as not on one CUDA device. When that embedding (hooked by Unsloth, not shared with the output head) holds the only off-device parameters, its rows are looked up eagerly before the graph and passed as inputs_embeds, and its parameters are exempt from the device check while staying in the fingerprint by identity. Any other off-device parameter is still refused.
… cards A model split over several cards (Unsloth's balanced placement, Muse-Glimmer on two T4s) records one graph per card; the cross-card copies run eagerly between replays, so cards without peer access work. UNSLOTH_DECODE_MULTIDEVICE_GRAPHS=0 turns it off. An input embedding offloaded to the host does not count as another device.
…xception handler The handler's traceback keeps the failed call's frames, so its StaticCache and graph buffers stayed allocated through the eager redo. [skip ci]
… block's card With tied embeddings Unsloth's split puts the embedding / lm_head (model.device) on the last card while the root hook moves inputs to the first, so 16-bit gemma-3-1b / Qwen3-0.6B splits stayed eager. [skip ci]
…ing a call whose key moves every step transformers rolls a full static sliding window with an index built by torch.tensor(..., device=...), a host-to-device copy a CUDA graph capture refuses, so every step past the window (512 tokens on Gemma 3 / 4) decoded eagerly. The warm-up and recording now run that branch op for op on an index made outside the capture (only when the installed update matches it). A call whose graph key changes every step captured every step and never replayed (an eager warm-up plus a recording per token, graphs piling up until the card ran out of memory). After four captures in a row without a replay the rest of the call decodes eagerly and its graphs are freed. An out-of-memory capture frees the call's graphs and stops capturing for that call only. [skip ci]
…er-passed type ids TRL's GRPO passes the processor's mm_token_type_ids / token_type_ids to generate(). They reached every decode step at full length, one column longer per step, so every step had a new graph key and nothing replayed (Gemma 4 E2B GRPO on T4: 1018 captures, 0 replays). Gemma 3 / 4 read them only to build the attention masks, which they skip when the step's masks come prebuilt; with prebuilt masks the graphed step now gets the last q_len columns, as transformers slices them. [skip ci]
Codex Review Summary: ✅ CompletedThis 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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 85a8719e5b
ℹ️ 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".
| flags = getattr(layer, "has_previous_state", None) | ||
| states = _linear_states(layer) | ||
| if not isinstance(flags, dict) or not flags or not all(flags.values()) or not states: | ||
| return "uninitialized layer" |
There was a problem hiding this comment.
Support the tensor-based linear cache layout in older Transformers
With supported Transformers versions such as 5.5.0 and 5.10.2, LinearAttentionLayer.has_previous_state is a boolean and conv_states / recurrent_states are individual tensors, not dictionaries. Consequently, _linear_states() returns an empty list and this check rejects every initialized hybrid cache as "uninitialized layer", so Qwen3.5 generation never captures or replays a graph on those versions. The new hybrid tests also run on these versions rather than skipping them and fail their capture assertions. Normalize both the boolean/tensor layout and the newer dictionary layout before checking initialization and collecting states.
Useful? React with 👍 / 👎.
Earlier transformers 5.x keep one conv / recurrent tensor per layer and a single has_previous_state bool (with is_*_initialized flags); 5.17+ keep dicts per state index. Both are normalised before checking initialisation and collecting states. Those earlier versions mark Qwen3.5 stateful without a fullgraph-compilable forward, so generate() keeps a dynamic cache there and the hybrid tests skip instead of failing inside transformers' own static path. [skip ci]
|
@codex review |
|
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". |
… it to another card of a split model [skip ci]
…rid-graphs [skip ci]
…piles (order independent)
…piles (order independent) [skip ci]
… hooks are process-global) [skip ci]
…t stand-in tests now run on ROCm torch)
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 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". |
## Summary Adds a growable KV cache to the generic FastModel decode path (the CUDA graph path from unslothai#16587). On by default where that path runs; `UNSLOTH_GROWABLE_KV=0` keeps transformers' full-length `StaticCache`. Models whose mask or ALiBi is sized by the cache's full limit (`get_max_cache_shape()` / `get_max_length()`, e.g. BLOOM) keep `StaticCache`. A transformers `StaticCache` allocates prompt + `max_new_tokens` slots for every full-attention layer at prefill, and attention reads every slot each step however early the reply stops. Under decode graphs the kept cache also stays at the largest size a previous call asked for, so a short call after a long one pays for the long one. * **`unsloth/models/_kv_cache.py` (new):** `GrowableLayer` is a transformers `StaticLayer` whose full-attention layers allocate a power-of-two bucket (at least `UNSLOTH_GROWABLE_KV_MIN`, default 256, never above the limit `generate` sized for) and double when a step would pass it. Writes are transformers' own `update` (`index_copy_` at device positions), buffers are `mark_static_address`, and the mask reads the bucket length, so within a bucket every tensor keeps its shape and address. Sliding and chunked layers stay transformers' own. * **Growth happens outside the graph:** `generate`'s `prepare_inputs_for_generation` re-syncs the host counter from generate's own lengths and reserves the next bucket eagerly, before the step's mask is built. No growth can happen inside a capture (frozen during recording and while a CUDA stream is capturing), and a step that would fill its bucket with no graph yet runs eagerly. * **Hybrid models (unslothai#17324):** linear-attention layers keep their own states; the graph key and cache signature carry both their shapes and the growable buckets. * **Memory:** layers hold their growth group by weak reference (no cycle), so a released cache frees its KV at once; a layer built directly joins its group. * **Decode graphs:** the graph key uses the bucket and the cache signature carries a growth epoch, so a growth re-captures once per bucket instead of being refused as "cache moved"; the previous bucket's graph is dropped. * **Kept cache:** reused across calls when its capacity is at most max(2x the new call's need, that call's own minimum bucket), so repeated short calls do not re-capture; its limit is raised to the new call's (5.x `_prepare_static_cache` hook, 4.57 `_get_cache` wrapper). ## Results Kaggle T4, fp16, decode graphs on, greedy, `max_new_tokens` 512 / 3800 with replies that stop at the chat EOS, tokens equal to `StaticCache` on every row, 0 recompiles, 0 refusals: | torch / transformers | Model, bsz | Tokens of budget | StaticCache ms/token | Growable ms/token | KV MiB static / growable | |---|---|---|---|---|---| | 2.14.1 / 5.17.0 | Qwen3-0.6B, 4 (after a 3800 call) | 512 of 512 | 51.8 | 21.2 | 1673 / 448 | | 2.14.1 / 5.17.0 | Qwen3-0.6B, 4 | 1139 of 3800 | 52.1 | 32.4 | 1673 / 896 | | 2.14.1 / 5.17.0 | Llama-3.2-1B, 4 | 189 of 3800 | 44.4 | 16.1 | 481 / 32 | | 2.14.1 / 5.17.0 | gemma-3-1b, 4 | 180 of 3800 | 18.3 | 15.8 | 208 / 96 | | 2.10.0 / 4.57.6 | Llama-3.2-1B, 4 | 181 of 3800 | 44.2 | 16.1 | 481 / 32 | | 2.10.0 / 4.57.6 | gemma-3-1b, 4 | 180 of 3800 | 27.6 | 22.8 | 208 / 96 | Colab L4 (bf16): Qwen3-0.6B bsz 1, 845 of 3800 tokens: 16.1 vs 9.0 ms/token, KV 418 vs 112 MiB; 4-bit, 737 tokens: 13.8 vs 6.9. A call that runs to its full budget ends in the same final bucket as the limit, so it costs the same as `StaticCache` (Qwen3-0.6B bsz 4, 3800 of 3800: 56.1 vs 56.1). Default-on check (Kaggle T4, torch 2.14.1, transformers 5.17.0, graphs on, 2 repeats; tokens equal on every row): never slower beyond noise, e.g. Qwen3-0.6B bsz 4 early stop 33.8 -> 21.2 ms/token (KV 906 -> 448 MiB), Llama-3.2-1B bsz 4 36.4 -> 22.2 (KV 262 -> 32 MiB), Qwen3-0.6B bsz 1 full 2048 budget 17.1 -> 16.5. A short call after a long one adds 0 captures. Cost: about 20 to 190 MiB more reserved (one graph pool per bucket) and one capture plus one compiled mask builder per bucket. Split over 2 x T4 and on L4 with flex decode, growable vs static is at parity. AMD gfx1151 (ROCm): the growable and generic decode graph suites pass (90 / 90). ## Tests `tests/test_growable_kv_cache.py` (12 tests, CPU host stand-in): tokens equal to `StaticCache` for llama, a left-padded batch of 2 and gemma3 with sliding + full layers; captures per bucket with no refusals; a short call after a long one replays the kept graph; early EOS allocates one bucket; rows equal across bucket growths; the compiled update is fullgraph with one graph per bucket; no growth inside a capture; a stale host counter (updates that skip it, as a compiled update or a replay would) and a prepare hook already owned by another wrapper still grow correctly. They pass on transformers 4.57.6 and 5.22.1, and on GPU with torch 2.14.1 / transformers 5.17.0 and torch 2.10.0 / transformers 4.57.6. With the flag off the existing decode-graph suites give the same results before and after. Not covered: the Llama-path KV buffers (`_decode_graphs.py`) and the per-model copies are unchanged; the attention still reads up to 2x the written length inside a bucket.
Summary
Stacked on #16587 (generic decode CUDA graphs). Qwen3.5 and Qwen3.6 (
qwen3_5,qwen3_5_moe) mix Gated DeltaNet layers with full attention. On transformers 5.x their StaticCache holds aLinearAttentionLayerper Gated DeltaNet layer, and #16587 refused every decode step of those models ("layer LinearAttentionLayer"), so they always decoded eagerly. This PR makes the generic decode graphs replay them.No
vision.pychange was needed: transformers 5.17 / 5.22 already set_can_compile_fullgraphfor these models, so generate uses a static cache.Results
torch 2.14.1, transformers 5.17.0, greedy, 128 new tokens, ms/token eager vs graphed (this PR). Every graphed row: 1 capture, 126 replays, 0 refusals, 0 recompiles, tokens identical to eager, KL 0, final linear states bitwise equal to eager. #16587 alone refuses every step and runs at eager speed.
Peak memory with graphs: equal to eager or 0.2 to 2.8 GB higher (the graph pool). The Qwen3.6 MoE decode step captures with the routed MoE kernels of unsloth-zoo main (#2442); with an older zoo the grouped MoE path copies to the host during capture, the capture is refused and the step runs eagerly (tokens still equal).
Tests
tests/test_generic_decode_graphs_hybrid.py(new): tiny dense (GQA 4:1) and MoE (8:1) models with the real Qwen3.5 layer pattern, 200 steps at bsz 1 and a ragged left-padded bsz 4: tokens equal to eager and every conv / recurrent state bitwise equal after every step (1 capture, 1 validation, 198 replays), states restored after a validation, refusals for an uninitialised or recording layer; plus a real CUDA capture test. On the host stand-in 6 of them fail on #16587 alone. With the existing generic decode graph suites: 76 passed / 4 skipped on transformers 5.22.1, 68 passed / 3 skipped on 4.57.6 (no hybrid cache there).Not covered: Qwen3.6-35B-A3B in 16-bit (72 GB) did not fit any GPU available for this run.