Skip to content

Flex attention decode steps for Gemma 4 and Qwen3.5 / Qwen3.6 under decode CUDA graphs - #17329

Merged
danielhanchen merged 72 commits into
mainfrom
flex-decode-routing
Nov 11, 2026
Merged

danielhanchen merged 72 commits into
mainfrom
flex-decode-routing

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

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.

  • Routing (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".
    • Mask side: per layer type (full / sliding), it builds zoo's decode BlockMask from transformers' own mask function (graph-refillable: fixed shapes, offsets and padding as tensors) when every layer of that type has a shape flex decode supports. Otherwise it builds transformers' SDPA mask.
    • Attention side: runs flex decode on a BlockMask and SDPA on a dense mask, so a model can mix both (Gemma 4's head_dim 512 full layers below sm80 stay on SDPA).
    • A shape zoo reports it cannot compile (FlexDecodeUnavailable) is counted and served by SDPA over the same visibility.
    • Prefill, dynamic caches, custom mask functions, chunked layers and gpt-oss (zoo owns it) are untouched.
  • Policy, UNSLOTH_FLEX_DECODE:
    • auto (default) routes only on compute capability 8.0+, only for the model types above, only in a generate() call that decodes through CUDA graphs (eager flex decode is 6 to 10% slower than eager SDPA), and only at batch size up to UNSLOTH_FLEX_DECODE_MAX_BATCH (default 4; head_dim 512 at batch 8 was slower on an A100).
    • 1 forces it on, 0 turns it off.
  • Stats: per layer, how many steps ran on flex and which ones fell back and why (_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.

GPU Model ctx x bsz graphed SDPA graphed flex speedup KL max
L4 gemma-4-E2B 4-bit 1k x 1 17.94 16.89 1.06x 1.3e-2
L4 gemma-4-E2B 4-bit 4k x 1 25.52 22.57 1.13x 4.4e-3
L4 gemma-4-E2B 4-bit 4k x 4 53.24 50.60 1.05x 1.7e-2
L4 gemma-4-E2B 16-bit 4k x 1 32.83 29.78 1.10x 2.3e-3
L4 gemma-4-E2B 16-bit 4k x 4 57.66 55.24 1.04x 7.9e-3
L4 Qwen3.5-4B 4-bit 1k x 4 45.21 40.97 1.10x 5.9e-3
L4 Qwen3.5-4B 4-bit 4k x 1 37.10 32.53 1.14x 5.5e-4
L4 Qwen3.5-4B 16-bit 4k x 4 111.45 92.49 1.20x 9.2e-3
A100 40GB Qwen3.6-35B-A3B 4-bit 1k x 1 18.28 17.50 1.04x 4.6e-2
A100 40GB Qwen3.6-35B-A3B 4-bit 4k x 1 21.94 18.03 1.22x 4.4e-1
A100 40GB Qwen3.6-35B-A3B 4-bit 4k x 4 38.88 31.88 1.22x 1.9
A100 40GB gemma-4-26B-A4B 4-bit 1k x 1 18.70 16.13 1.16x 9.5e-2
A100 40GB gemma-4-26B-A4B 4-bit 4k x 1 22.93 18.36 1.25x 2.2e-2
A100 40GB gemma-4-26B-A4B 4-bit 4k x 4 52.34 44.37 1.18x 1.1

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:

Kernel KL max KL mean top-1
SDPA math 8.2 0.046 0.981
SDPA efficient 4.5 0.032 0.981
flex 1.2 0.014 0.965

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 auto does 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): greedy generate() with flex decode steps equals SDPA decode, tokens equal and logits within 1e-9, covering:
    • Gemma 4 E2B-like (KV-shared consumer layers, head_dim 256 / 512) and 26B-A4B-like (k_eq_v, 16/8 and 16/2 heads);
    • past the sliding window, including the real 512 / 1024 windows;
    • batch 1 and a ragged left-padded batch;
    • zoo's own BlockMask;
    • head_dim 512 left on SDPA;
    • tiny qwen3_5 and qwen3_5_moe models with the gated full attention between Gated DeltaNet layers.
  • tests/test_flex_decode_routing.py (new): steps switch and prefill keeps SDPA, auto only for graph-planned calls and up to the batch cap, off switch, unlisted / excluded models unchanged, FlexDecodeUnavailable served 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_all branch). 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).

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.
…cord capture errors; VALIDATE_ALL debug mode
…/ strides of static buffers, ambient autocast cache
…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
…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]
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: d83d583d68

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

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 490bcd0dab

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

Base automatically changed from dec-generic-graphs to main November 10, 2026 08:45
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 10, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: de43be963b

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

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 1a05c59163

ℹ️ 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. Hooray!

Reviewed commit: c82e567d49

ℹ️ 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 db12e18 into main Nov 11, 2026
@danielhanchen
danielhanchen deleted the flex-decode-routing branch November 11, 2026 07:50
danielhanchen added a commit that referenced this pull request Nov 11, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant