Repository navigation
Flex attention decode steps for Gemma 4 and Qwen3.5 / Qwen3.6 under decode CUDA graphs - #17329
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]
… of traces, package-relative Qwen test import [skip ci]
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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". |
… hooks are process-global) [skip ci]
…t stand-in tests now run on ROCm torch)
…o linear-attention mask
…attention weights [skip ci]
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. 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". |
…h Gated DeltaNet path where FLA is installed [skip ci]
|
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". |
…pert loop on CUDA hosts
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
…act text (#17497) ## Summary `Repo tests (CPU, rest)` fails on main since #17329, and on every PR based on it (seen on #17479): ``` FAILED tests/test_gemma3_generate_off_flex.py::test_generate_enters_the_scope E assert '_NonFlexGenerate(self)' in 'def unsloth_base_fast_generate(self, *args, **kwargs): ... ``` The test checks that `unsloth_base_fast_generate` enters the `_NonFlexGenerate` scope for the model it generates with. It did that by looking for the literal text `_NonFlexGenerate(self)`. #17329 (flex attention decode steps) still enters the scope, now with a keyword argument: ```python _NonFlexGenerate(self, flex_decode = not _wants_attentions(self, kwargs)), ``` So the code is right and the test is too strict: any added argument or reflow breaks it without the behaviour changing. ## Change `test_generate_enters_the_scope` now parses the function and requires a `_NonFlexGenerate(...)` call whose first argument is `self`. Keyword arguments and formatting no longer matter, but the scope still has to be entered for the model itself: a comment or string that mentions it, or the scope built for another object, does not count. A new `test_the_scope_check_reads_calls_not_text` covers those cases. ## Testing - `tests/test_gemma3_generate_off_flex.py`: fails on main (1 failed, 18 passed), 20 passed here. - With the `_NonFlexGenerate(...)` entry in `unsloth_base_fast_generate` replaced by `contextlib.nullcontext()`, `test_generate_enters_the_scope` fails.
Summary
Builds on the generic decode CUDA graphs (#16587). Decodes the one-token steps of
FastModel.generate()on flex attention (flex_decoding) for Gemma 4 (gemma4) and Qwen3.5 / Qwen3.6 (qwen3_5,qwen3_5_moe). It uses the shared decode mask and attention from unsloth-zoo (unslothai/unsloth-zoo#2464); with an older unsloth-zoo nothing changes.unsloth/models/_flex_decode.py,vision.py): prefill keeps its attention. During one-token steps over a StaticCache, the text attention configs switch to an attention + mask interface pair,"unsloth_flex_decode_routed".FlexDecodeUnavailable) is counted and served by SDPA over the same visibility.UNSLOTH_FLEX_DECODE:auto(default) routes only on compute capability 8.0+, only for the model types above, only in agenerate()call that decodes through CUDA graphs (eager flex decode is 6 to 10% slower than eager SDPA), and only at batch size up toUNSLOTH_FLEX_DECODE_MAX_BATCH(default 4; head_dim 512 at batch 8 was slower on an A100).1forces it on,0turns it off._flex_decode.stats(model)).Results
torch 2.14.1, transformers 5.17.0, greedy, 64 new tokens. ms/token with decode CUDA graphs, SDPA vs flex (this PR). Every row: 1 capture, 377 replays, 0 recompiles. KL is teacher-forced against eager SDPA on the eager greedy sequence.
Ragged left-padded batches give the same speedups (for example E2B 4-bit 4k x 4 ragged: 63.0 vs 60.3).
The large KL on the MoE models is the router amplifying rounding, not flex. On Qwen3.6's 4k x 4 cell (a separate run), eager decode on SDPA's other kernels differs from the default flash kernel more than flex does:
gemma-4-26B-A4B shows the same pattern: on its cells, the SDPA math kernel reaches KL max 11 and the efficient kernel 2 to 4.5, against flex 0.25 to 9.5 (top-1 0.97 to 0.99 for flex).
What
autodoes on other hardware: batch 8 stays on graphed SDPA (E2B, 26B-A4B and Qwen3.6). A T4 stays on SDPA (graphed SDPA 29.9 ms vs forced flex much slower; head_dim 512 does not fit a T4 tile). Without decode graphs, every model keeps SDPA.Tests
tests/test_flex_decode_gemma4.py,tests/test_flex_decode_qwen35.py(new, CPU, float64): greedygenerate()with flex decode steps equals SDPA decode, tokens equal and logits within 1e-9, covering:qwen3_5andqwen3_5_moemodels with the gated full attention between Gated DeltaNet layers.tests/test_flex_decode_routing.py(new): steps switch and prefill keeps SDPA,autoonly for graph-planned calls and up to the batch cap, off switch, unlisted / excluded models unchanged,FlexDecodeUnavailableserved by SDPA exactly.With the existing generate / decode graph suites: 136 passed, 3 skipped (slow excluded) on transformers 5.22.1, plus
test_flex_mask_graph_breaks.py::test_compiled_flex_mask_has_no_graph_breaks_and_matches_eager, which fails on 5.22.1 identically on #16587 alone (transformers'fast_allbranch). 124 passed, 6 skipped on 4.57.6 (no 5.x mask interface: routing off). Real GPU: the routing, Gemma 4, Qwen3.5 and zoo contract suites pass on Kaggle T4 (128 passed, 2 skipped) and the Qwen3.5 file on Colab T4 (8 passed); the CPU stand-ins pin transformers' torch Gated DeltaNet functions and the native MoE loop, since FLA kernels and the host-wide grouped_mm backend reject float64 CPU tensors on GPU hosts. AMD gfx1151 (ROCm): 86 passed, 6 skipped; auto stays off on ROCm. Split over 2 x T4 (Gemma 4 E2B 4-bit): forced flex decode matches eager (KL <= 1.6e-4) with the BlockMask moved per card. When generate requests attention weights, decode steps keep the model's own attention (flex decode returns none).Not covered: Qwen3.6 and Gemma 4 26B in 16-bit (do not fit a 40 GB card).