Repository navigation
Flex attention on torch < 2.14: fitting tiles for short decode calls so a batch-size change does not leave the process on eager attention - #16073
Conversation
…flex_decoding tile does not fit On an L4 / A10 / RTX 4090 a no-grad flex call with a query below 128 goes to flex_decoding, which puts next_pow2(q_len * query heads per kv head) rows in one tile. At head_dim 256 more than 64 rows need 114688 B of shared memory (101376 available), so a short Gemma 3 prompt (28 tokens x 4 heads) failed to compile. unsloth_zoo's suppress_errors hid the error and Dynamo then skipped flex_attention for the rest of the process: every later call, long prompts and one-token decode included, ran the eager math fallback. Give those calls the small shared memory tiles that #15271 already passes for prefill and training. One-token decode (16 rows) and every call at 64 rows or less keep flex_decoding's own config.
… kernel flex_decoding with fwd_BLOCK_M 64 below its row count computes only the first 64 rows on torch 2.10 (no M split in its grid: NaN / garbage rows) and fails to compile at q_len 127 on torch 2.11. The main kernel with the same tiles is correct and compiles on 2.10, 2.11 and 2.14 for every admitted shape tested on an L4.
…ecode after a batch size change On torch 2.10 / 2.11 a batch size change between generate calls makes the batch dim dynamic, so one-token decode leaves flex_decoding for the main kernel, whose default head_dim 256 tile needs 151552 B. The compile fails, suppress_errors turns it into a Dynamo skip, and the process runs eager flex for good. Give 16-bit head_dim 256 short no-grad calls the small-smem tiles there; rows <= 64 stay eligible for flex_decoding.
…s left on flex_decoding Before torch 2.14 flex_decoding derives SAFE_M_BOUNDARY from its own BLOCK_M (16 or 32 at 16 or 32 query rows) and only afterwards lets fwd_BLOCK_M 64 replace it. The 64-row tile then loads queries and stores rowmax / sumexp without row masks, overwriting other heads: wrong or NaN output at 16 / 32 rows on torch 2.10, 2.11 and 2.13. Plain BLOCK_M is the key flex_decoding checks; the effective tile is unchanged, so decode at 1-4 rows compiles to the same kernel.
…_FLEX_ATTENTION torch 2.10+ raises when kernel_options carry both. A caller's BACKEND="AUTO" now becomes "TRITON" (the main kernel FORCE picks) and an explicit backend is kept.
… kernel_options untouched Our short-query tiles are main-kernel tiles (64 query rows). A caller asking for TRITON_DECODE or FLASH keeps its own options, so flex_decoding never runs with fwd_BLOCK_M 64 below its row count.
[skip ci]
|
@codex review |
Codex Review SummaryThis 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. |
|
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". |
…ts own kernel_options untouched [skip ci]
# Conflicts: # unsloth/models/_utils.py [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". |
# Conflicts: # unsloth/models/_utils.py
…pped as main's flex_decoding guard does
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. 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". |
# Conflicts: # tests/test_flex_small_smem_tiles.py # unsloth/models/_utils.py
|
@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". |
…one short prompt does not leave the process on eager attention (unslothai#16049) ## Problem On sm86 / sm89 cards (L4, A10, RTX 3090 / 4090, A6000, L40S; 101376 B shared memory per block), Gemma 3 generation speed depends on which prompts the process has seen. After one prompt of 17 to 127 tokens (a normal chat prompt), later calls run flex attention's eager `math_attention` fallback. On torch 2.14 that holds for every later call, 16k-token prompts and one-token decode steps included. A process that has only seen prompts of 128 tokens or more runs the compiled kernels, until the first short prompt arrives. Root cause: 1. A no-grad flex call with fewer than 128 query rows goes to Inductor's `flex_decoding` kernel. That kernel holds `next_pow2(q_len * query heads per kv head)` query rows in one tile. With Gemma 3 1B / 270M (4 query heads per kv head) and head_dim 256, a 28-token prompt needs a 128-row tile, which takes 114688 B and does not compile: `No valid triton configs. OutOfMemoryError: out of resource: triton_tem_fused_flex_attention_0 Required: 114688 Hardware limit:101376`. 2. unslothai#15271 passes fitting tiles on these cards, but only for training calls and queries of 128 or more. Short no-grad queries were left on flex_decoding's own config, which fits only up to 64 rows. A one-token decode step is 16 rows. 3. unsloth_zoo sets `torch._dynamo.config.suppress_errors = True`. Dynamo turns the suppressed error into the default `ConvertFrameReturn`, which marks the frame `SKIP` and applies it to the code object (`torch/_dynamo/types.py`, `apply_to_code = True`). That code object is `torch.nn.attention.flex_attention.flex_attention` itself, so later calls run eagerly, and eager flex is `math_attention`. ## Change `unsloth/models/_utils.py`, on the same devices and head dims as unslothai#15271: sm8x with 101376 <= shared memory < 151552, 128 < head_dim <= 256, torch >= 2.10. - A no-grad short query whose flex_decoding tile would hold more than 64 rows now gets the unslothai#15271 tiles. - These calls also get `FORCE_USE_FLEX_ATTENTION`, so they run on the main flex kernel. Leaving them on flex_decoding with a smaller tile is not safe: on torch 2.10 its grid has no split along query rows, so rows past 64 are never written, and on 2.11 it fails to compile at q_len 127. - `_flex_decode_rows` counts rows the way Inductor does: query length times query heads per kv head. When the head count is not a power of two, transformers repeats K / V, so the multiplier is 1. What stays the same: - One-token decode and any call at 64 rows or less keep flex_decoding's own config. - Training calls and queries of 128 or more are handled exactly as before. - A100, H100, B200, sm120, T4 and ROCm are outside the gate, so nothing changes there. - `UNSLOTH_FLEX_SMALL_SMEM_TILES=0` still turns the whole path off. ## Results All arms ran in one Colab L4 job, each in its own process. Setup: `unsloth/gemma-3-1b-it` 16-bit, transformers 4.57.6. - Prefill is the median of `generate(max_new_tokens=1)`. - Decode is (t33 - t1) / 32. - Extra memory is peak allocated minus allocated before the call. - "short" is the 28-token chat prompt. Arms: - long-only: 2k, 2k, 8k, 16k. - short-first: short, 2k, 2k, short, 8k, 16k. - long-then-short: 2k, short, 2k, short, 8k, 16k. torch 2.14.1+cu130: | arm | prefill 2k / 8k / 16k s | decode ms/tok at 2k / 8k / 16k | short prompt decode ms/tok | 16k extra MiB | math_attention per prefill | suppressed compile errors | |---|---|---|---|---|---|---| | main, long-only | 0.085 / 0.319 / 0.687 | 70.7 / 71.1 / 71.0 | | 684 | 0 | 0 | | main, short-first | 0.255 / 2.865 / 11.35 | 238.5 / 239.9 / 243.4 | 240.3 | 13681 | 26 | 5 | | main, long-then-short | 0.249 / 2.881 / 11.45 | 234.5 / 243.5 / 241.8 | 233.6 | 13681 | 26 | 5 | | this PR, long-only | 0.085 / 0.345 / 0.755 | 70.5 / 70.5 / 70.7 | | 684 | 0 | 0 | | this PR, short-first | 0.088 / 0.351 / 0.760 | 69.0 / 70.8 / 70.2 | 67.2 | 684 | 0 | 0 | | this PR, long-then-short | 0.088 / 0.346 / 0.753 | 69.3 / 70.9 / 71.4 | 65.5 | 684 | 0 | 0 | torch 2.10.0+cu128: | arm | prefill 2k / 8k / 16k s | decode ms/tok at 2k / 8k / 16k | short prompt decode ms/tok | 16k extra MiB | math_attention per prefill | suppressed compile errors | |---|---|---|---|---|---|---| | main, long-only | 0.090 / 0.344 / 0.733 | 73.1 / 73.1 / 73.2 | | 684 | 0 | 0 | | main, short-first | 0.089 / 2.725 / 10.38 | 71.9 / 243.3 / 279.9 | 250.9 | 13681 | 26 from the second short prompt on | 5 | | main, long-then-short | 0.275 / 2.724 / 10.39 | 237.7 / 275.7 / 276.9 | 238.7 | 13681 | 26 | 4 | | this PR, long-only | 0.089 / 0.346 / 0.732 | 73.2 / 73.4 / 73.0 | | 684 | 0 | 0 | | this PR, short-first | 0.090 / 0.351 / 0.725 | 72.3 / 72.7 / 73.8 | 69.8 | 684 | 0 | 0 | | this PR, long-then-short | 0.090 / 0.344 / 0.738 | 73.8 / 72.4 / 73.3 | 69.7 | 684 | 0 | 0 | - **Every arm of this PR runs compiled flex on both torch versions:** 0 math calls and 0 suppressed errors, whatever the prompt order. The 28-token prompt decodes at 65-70 ms/token instead of 234-251. - **The 2.14 prefill gap is not from this change.** On 2.14, main long-only prefills 8k / 16k about 8% faster than this PR's arms. The PR does not change the kernel for these calls: q_len >= 128 is handled as before. Main long-only ran first on a cold card. On 2.10, where it did not run first, the same comparison is 0.344 / 0.733 s against 0.346 / 0.732 s. - **Long prompts:** for the 2k / 8k / 16k prompts, greedy ids (1 and 33 new tokens) are identical across all 12 arms, including main's eager arms. - **28-token prompt, torch 2.14:** this PR's ids equal main's in both orders. - **28-token prompt, torch 2.10:** - The first token matches in every arm. - Long-then-short equals main. - Short-first diverges from main later in the 8- and 33-token outputs. - Op level, the earlier review sweep covered 27 shapes on an L4 (torch 2.10, 2.11 and 2.14) and all are correct with this change. ## Torch version matrix (L4) | torch | short prompt on main | this PR | |---|---|---| | 2.14.1 | fails to compile, then every later call is eager | compiled, any order | | 2.11.0 | fails to compile (op level) | compiled at op level for the admitted shapes; Gemma 3 generate not run | | 2.10.0 | fails to compile, then later calls go eager | compiled, any order | Remaining gap on torch 2.10 / 2.11, not fixed here: when the batch size changes within a process, Dynamo makes the batch dimension dynamic. A one-token decode step then cannot use flex_decoding, and the main kernel's default head_dim 256 tile (151552 B) does not fit. That compile fails, and under `suppress_errors` it falls back to eager the same way. This happened on 2.10 and 2.11 at op level; on 2.14 it compiles. ## Tests - `tests/test_flex_small_smem_tiles.py`: new parametrized `test_wrapper_short_prompt_whose_decode_tile_does_not_fit_gets_tiles`, which also asserts `FORCE_USE_FLEX_ATTENTION`. The 4 cells that expect tiles fail on main and pass here. The cells for one-token decode, 64 rows, Gemma 3 4B shapes and a non power of two head count pass on both. - `test_wrapper_no_grad_prefill_gets_tiles_decode_does_not` now also asserts that q_len >= 128 gets no `FORCE_USE_FLEX_ATTENTION`. ## Review fixes and L4 re-check (torch 2.10.0, 2.11.0, 2.12.0, 2.13.0, 2.14.1) Two fixes in how the short-query path merges the caller's `kernel_options`: - **BACKEND with our FORCE:** torch 2.10 to 2.14 raise when `kernel_options` carry `BACKEND` together with `FORCE_USE_FLEX_ATTENTION`, and a caller `BACKEND` survived next to our FORCE. Now a caller `AUTO` is dropped and our FORCE kept, the same rule main's flex_decoding guard (unslothai#16092) uses, which also holds on torch 2.9 (no `BACKEND` there). A caller `TRITON` (the main kernel) keeps our tiles without FORCE. - **A non-main BACKEND:** a caller asking for `TRITON_DECODE` or `FLASH` now gets its own options untouched. Our 64-row main-kernel tiles would otherwise reach flex_decoding with more rows than they cover. Both have tests that fail without the fix. `tests/test_flex*.py`: 195 passed, 12 skipped. Main is merged in. Colab L4, one venv per torch version. Every output row and head is compared with fp32 SDPA (tolerance 2e-2): - The Gemma 3 1B prompt shape (28 tokens x 4 heads) and the Gemma 2 2B / Gemma 3 4B shapes at 40 and 100 tokens fail to compile by default on every version, and compile and match SDPA with this PR. head_dim 192 also compiles and matches. - fp32 head_dim 256 short prompts still fail to compile with the tiles; they stay on the eager fallback as before. Gemma 3 1B generate with a 25-token first prompt (eager fallback calls per generate step): | order | main 2.11 / 2.12 | main 2.13 | unslothai#16049 + unslothai#16073 | |---|---|---|---| | 25-token prompt, long prompt, 8-token prompt | 832 / 832 / 572 | 832 / 832 / 572 | 0 / 0 / 0 | | long prompt, 25-token prompt | 0 / 832 | 0 / 832 | 0 / 0 | | batch 1, 2, 1 | 0 / 832 / 832 | 0 / 0 / 832 | 0 / 0 / 0 | On torch 2.10, 2.11 and 2.12 a batch change still falls back without unslothai#16073 (806 and 832 calls on 2.10 for this PR alone), so the two should land together. ## After the main merge (L4, Gemma 3 1B, merge base 3ecb1ba) Main's own flex wrapper change (unslothai#16092) landed before these PRs merged it in, so the end-to-end orders were run again on the merged heads. The numbers are math_attention fallback calls per generate step, then ms per token per step: | torch | order | main | unslothai#16049 + unslothai#16073 | |---|---|---|---| | 2.14.1 | batch 1, 2, 1 | 0 / 0 / 832; 1289 / 1580 / 1050 | 0 / 0 / 0; 652 / 786 / 616 | | 2.14.1 | long then short | 0 / 832; 927 / 854 | 0 / 0; 477 / 374 | | 2.14.1 | short first | 832 / 832 / 572; 1194 / 665 / 504 | 0 / 0 / 0; 798 / 649 / 556 | | 2.10.0 | batch 1, 2, 1 | 0 / 832 / 832; 1201 / 1218 / 566 | 0 / 0 / 0; 1070 / 931 / 585 | | 2.10.0 | long then short | 0 / 832; 899 / 747 | 0 / 0; 623 / 320 | | 2.10.0 | short first | 832 / 832 / 572; 1033 / 618 / 513 | 0 / 0 / 0; 761 / 630 / 494 | The stack never reaches the eager fallback. Main does on every order, and on 2.14.1 now too. Greedy ids diverge from the SDPA reference in a few steps where main, on the eager fallback, matched. That is the bf16 flex vs SDPA divergence both arms show elsewhere, already listed above as pre-existing. ## AMD ROCm (gfx1151, Linux) The flex wrapper tests (`test_flex_small_smem_tiles.py`, `test_flex_small_smem_tiles_gpu.py`, `test_flex_decode_guard_wrapper.py`, `test_flex_tuned_backward_kernel_options.py`) ran on main (3ecb1ba), this branch and the merge, in one job on one host: main 97 passed, this branch 110 passed, the merge the same, 0 failed and 2 skipped in each. Verdict NO_REGRESSION. The GPU was shared, so this is correctness only, not timing.
…ntion's fallback (unslothai#16041) ## Status unslothai#16049 and unslothai#16073 keep `flex_attention` compiled on L4 / A10 / RTX 3090 / 4090 / L40S class cards in every prompt order and batch sequence (torch 2.10 to 2.14.1). On top of them, flex is still slower than SDPA for one-token decode, while flex is much faster for long-prompt prefill (its block mask skips tiles a dense prompt x cache mask computes). So this PR now routes each `generate()` step: the prefill (more than one new token) runs on flex, and every one-token decode step runs the non-flex path. That keeps the decode win and loses nothing at prefill. Colab L4, gemma-3-1b-it, ms per token at 256 new tokens (median of 3 rotated rounds) and prefill seconds (extra peak MiB): | torch | load | unslothai#16049 + unslothai#16073 | this PR (decode off flex for the whole call, previous version) | this PR (now) | |---|---|---|---|---| | 2.14.1 | 16-bit decode | 67.37 (A/A 66.94) | 55.20 | 55.96 | | 2.14.1 | 4-bit decode | 71.45 (A/A 72.28) | 59.83 | 60.60 | | 2.10.0 | 16-bit decode | 70.01 (A/A 71.05) | 57.08 | 57.84 | | 2.10.0 | 4-bit decode | 75.17 (A/A 74.80) | 61.80 | 61.55 | | 2.14.1 | 16-bit prefill 2k / 8k / 16k | 0.102 / 0.363 / 0.769 s (95 / 347 / 684) | 0.105 / 0.660 / 2.083 s (111 / 603 / 1707) | 0.103 / 0.364 / 0.780 s (95 / 347 / 684) | | 2.10.0 | 16-bit prefill 2k / 8k / 16k | 0.105 / 0.383 / 0.817 s (95 / 347 / 684) | 0.107 / 0.675 / 2.118 s (111 / 603 / 1707) | 0.105 / 0.384 / 0.823 s (95 / 347 / 684) | With LoRA r16 (`FastLanguageModel.get_peft_model`, torch 2.14.1, 16-bit): 98.72 (A/A 98.15) -> 86.52 ms per token, the same as the previous version (86.27). Every prefill forward ran on flex and every one-token forward on the non-flex path, with and without LoRA, and no arm hit flex's eager fallback. Costs: the first call at a new cache shape pays flex's prefill compile, as without this PR (about 4 s in a warm process). Two threads calling `generate()` on the same model share one config (and one static KV cache), so a call from a second thread waits until the running one exits. ## What changes On sm80+ NVIDIA cards (and ROCm), Unsloth loads Gemma 3 with `flex_attention`, which helps training. Its one-token decode step is slower than the non-flex path (zoo's SDPA kernel), and without unslothai#16049 / unslothai#16073 a short first prompt also left flex on its eager math fallback for the rest of the process (229 ms/token on an L4 vs 49 for stock transformers). Inside `unsloth_base_fast_generate`, a scope wraps `prepare_inputs_for_generation` (where the static cache builds each step's mask) on the model and on its PEFT base model. Each step picks its path from `cache_position`: one new token runs the non-flex path (the decoder attention configs read `"eager"`, and Gemma 3's patched attention runs SDPA); anything longer runs flex. If the prepared inputs disagree with that guess, the step switches and rebuilds its inputs, so the mask always matches the path that runs. Both paths read and write the same KV cache. The configs and the wrapped attributes are restored on exit, including on error, so training stays on flex. - Applies only to models where Unsloth itself prefers flex (`gemma3`, `gemma3_text`, `shieldgemma2`) and only to decoder configs set to `flex_attention`. A VLM's vision tower is left alone. - An explicit `attn_implementation="flex_attention"` keeps flex. So does `UNSLOTH_FLEX_ATTENTION_GENERATE=1`. - Reference counted per model with a lock; nested calls restore once. A `generate()` from another thread on the same model (or its PEFT wrapper) waits for the running one: the step switches the shared config between its mask build and its forward. - T4 (sm75), RTX PRO 6000 (sm120 at head_dim 256) and `UNSLOTH_ENABLE_FLEX_ATTENTION=0` never take flex, so nothing changes for them. The tables below (Results, GPU follow-up, training, AMD) were measured with the previous version, which ran the whole `generate()` off flex; the decode numbers carry over (see Status), and the prefill cost they show is gone. ## Results Colab L4, torch 2.14.1+cu130. Greedy decoding, 256 new tokens, batch 1. Each value is ms/token, the median of 3 timed rounds after a warm-up. Launches and syncs are per decode token from torch.profiler (40-token minus 8-token generate, same cache length). Base and head ran on the same VM in one job. transformers 4.57.6: | model | load | base ms/token | head ms/token | speedup | launches base / head | syncs base / head | HF eager | |---|---|---|---|---|---|---|---| | gemma-3-1b-it | 16-bit | 228.9 | 61.6, 61.3 (A/A) | 3.7x | 1804 / 651 | 28 / 4 | 49.4 | | gemma-3-1b-it | 4-bit | 231.5 | 67.1 | 3.5x | 1804 / 651 | 28 / 4 | 65.8 | | gemma-3-270m-it | 16-bit | 157.9 | 44.5 | 3.5x | 1273 / 475 | 20 / 4 | 36.6 | transformers 5.17.0: | model | load | base ms/token | head ms/token | speedup | HF eager | |---|---|---|---|---|---| | gemma-3-1b-it | 16-bit | 151.4, 150.0 | 56.3, 57.0, 56.2 | 2.7x | 49.3 | | gemma-3-1b-it | 4-bit | 155.7 | 61.0 | 2.6x | 62.7 | | gemma-3-270m-it | 16-bit | 105.6 | 39.2 | 2.7x | 32.5 | Spreads within each arm are 0.1-2.8%. The new path is provably the one that runs. A forward pre-hook saw `eager` on every head forward and `flex_attention` on every base forward, and `config._attn_implementation` reads `flex_attention` again after `generate()` returns. Output: greedy token ids on the head are identical to the existing non-flex path on the same card. That holds for an in-process switch to eager and for `UNSLOTH_ENABLE_FLEX_ATTENTION=0`, on both transformers versions. Compared with today's flex output, the ids first diverge after 32-151 tokens, as with any change of attention kernel in bf16. The text stays coherent. Base ids reproduced exactly on two separate L4 VMs. Unchanged cards: on an RTX PRO 6000 (no flex at head_dim 256), the default, the eager switch and `UNSLOTH_ENABLE_FLEX_ATTENTION=0` give the same ids and times. For gemma-3-1b-it 16-bit that is 16.4 to 16.6 ms/token. ## Tests - `tests/test_gemma3_generate_off_flex.py` (CPU, real `Gemma3TextConfig`, `Gemma3Config` and `LlamaConfig`; 18 tests, including a real tiny `Gemma3ForCausalLM.generate` with a static cache, left padding and a prompt longer than the sliding window, and the same through a PEFT LoRA model, asserting prefill on flex, every decode step off flex and ids equal to an all-SDPA run) covers: - switch and restore, and restore when `generate()` raises; - a VLM moves only the decoder; - nested calls restore once; - no change for Gemma 3 already on eager or sdpa, or for a non-Gemma flex model; - an explicit flex request is kept, and the opt-out env var works; - `generate()` enters the scope. Results: main fails at collection (`_NonFlexGenerate` missing); this branch passes 10 of 10. - Neighbour tests: the 44 test files that mention `unsloth_base_fast_generate`, `flex_attention` or `_attn_implementation`, plus `test_compile_decode_selection.py`. Main and this branch both report 12 failed, 882 passed, 160 skipped and 4 errors, with identical failing test IDs. These failures are pre-existing on a CPU-only host. - Compiles on Python 3.9 through 3.14. ## Not covered - Long-prompt prefill on sm80+: during `generate()` the non-flex path builds a dense mask the size of prompt length x cache length, as T4 already does today. Prefill peak memory and time for very long prompts on an sm80+ card were not measured. - Other families that Unsloth puts on flex (head_dim above 128 on H100 / B200 class cards, or an explicit `attn_implementation="flex_attention"`) may hit the same slow per-token flex decode. They are left unchanged here. - A100 / H100 (they also take flex for Gemma 3) were not run with the hybrid routing (AMD ROCm: see below). - T4 (Kaggle, gemma-3-1b-it fp16, torch 2.14.1, base vs head alternated base / head / base / head): a no-op as expected. The attention config stays `eager` before, during and after every generate, the routing hook is entered but never switches anything, greedy ids are identical in all four runs, and decode is 38.93 (base) vs 39.14 (head) ms per token, inside base's own run-to-run spread. - Gemma 3 vision models (4B and up) with image prompts were not run on GPU. Only the config test covers them. ## GPU follow-up Runs for the items above. Setup: torch 2.14.1+cu130, transformers 4.57.6, base = merge base d84e074, head = 74526b0, both arms on the same card in the same job, 3 timed repeats. **Today's flex path is in one of two states, set by the first `generate()` in the process.** If the first prompt is a short chat prompt (28 tokens), every later call runs flex's eager `math_attention` fallback (26 calls per forward, one per layer), long prompts included. If the first prompt is 2048 tokens, the compiled flex kernels run (`triton_tem_fused_flex_attention`, flex_decoding) and the fallback is never hit. This PR runs zoo SDPA in both cases. **1. Long prompts, gemma-3-1b-it 16-bit, L4.** Prefill s / extra peak MiB / decode ms per token: | prompt | base, short first call | base, long first call | head | |---|---|---|---| | 2k | 0.246 / 264 / 236.9 | 0.083 / 95 / 69.6 | 0.097-0.102 / 111 / 64-65 | | 8k | 2.877 / 3518 / 236.8 | 0.318 / 347 / 69.6 | 0.593-0.632 / 603 / 65-66 | | 16k | 11.39 / 13681 / 239.1 | 0.678 / 684 / 69.6 | 1.92-2.01 / 1707 / 65 | No OOM anywhere (22 GB usable). Greedy ids for these prompts match between base and head in every cell. An A100-SXM4-40GB with a long first call gives the same picture: 16k prefill 0.19 s base vs 0.55 s head, decode 78.7 vs 72.8 ms per token. So against a short first call the head is 3.5-5.7x faster at prefill, 3.6x faster at decode and uses 8x less memory at 16k. Base needs 15.6 GB of peak for a 16k prompt, so it would not fit on a 16 GB card. Against a long first call the head is 7-8% faster at decode but 1.9x / 2.8x slower at 8k / 16k prefill (+256 / +1023 MiB), because the dense prompt x cache mask computes every tile that flex's block mask skips. That is the cost T4, Blackwell and `UNSLOTH_ENABLE_FLEX_ATTENTION=0` users already pay. **2. Vision, gemma-3-4b-it bnb 4-bit**, one 448x448 image (red circle, blue square, green triangle), greedy, 64 tokens: L4 92.2 (base) vs 88.8 (head) ms per token, A100 87.4 vs 83.5. The output text is identical on both, and correct about the shapes and colours. Only the decoder config switches; the vision tower config is untouched and the decoder reads `flex_attention` again after generate. The 280-token prompt means base was on compiled flex here. **3. Training after generate, gemma-3-270m 16-bit LoRA**: 10 SFT steps, 32-token greedy generate, 10 more steps, seed 3407. The 20 losses are bit-identical between base and head, both with and without the generate, and the A/A rerun is bit-identical too. Training forwards after generate run on `flex_attention`. Separately, generating mid-run shifts steps 11-20 by up to 0.008 compared with not generating, the same on base and head. So this PR does not cause it; it already happens on main. I also tried keeping flex for prefill and switching only the one-token steps, hooked in `prepare_inputs_for_generation` because the static cache builds the step mask there. It only helps when flex is not stuck on the fallback: after a short first call, a 16k prefill goes back to 11.4 s / 13.7 GB. So it is not part of this PR. The better follow-up is to find why one short first call leaves flex on the eager fallback for the rest of the process. Not covered: H100, AMD, transformers 5.x for these three items, a VLM process whose first prompt is short. ## Training between generate calls (on top of unslothai#16049 + unslothai#16073) Colab L4, torch 2.14.1 and 2.10.0, gemma-3-1b-it LoRA r16 in 16-bit and 4-bit, seed 3407: 4 SFT steps, `generate()` (32 tokens, greedy), 4 more steps, then generate and one step twice (GRPO style). Arms: main + unslothai#16049 + unslothai#16073 (twice, for an A/A) and the same plus this PR. - Every loss and LoRA grad norm difference between the arms starts before the first `generate()`, where both run the same code, and stays within the A/A spread (largest loss difference 0.028 with this PR, 0.030 A/A). On torch 2.14.1 16-bit all 10 losses and all 364 final LoRA grad norms are bitwise equal. - During each `generate()` the decoder reads `eager` at every step with this PR (0 flex kernel events, SDPA instead) and `flex_attention` without it. After every `generate()` and after `for_training`, every config reads `flex_attention` again. - The training steps after a `generate()` compile nothing new on either arm: 0 frames, 0 recompiles, 0 graph breaks. Not covered there: TRL's trainers and the vLLM path, overlapping `generate()` calls on a GPU, multimodal Gemma 3, transformers 4.57.x. ## AMD ROCm (gfx1151) Strix Halo gfx1151 runner, torch 2.11.0+rocm7.13.0, transformers 5.5.0, merge base vs this head in one job on one host, gemma-3-270m-it 16-bit. Unsloth puts Gemma 3 on `flex_attention` there too, so this applies on ROCm: | | merge base | this PR | |---|---|---| | decode ms per token (128 new tokens, 2 processes x 3 repeats) | 12.70 | 10.78 (15% faster) | | attention config read during generate | `flex_attention` | `eager` (Gemma 3's attention then runs SDPA) | | attention config after generate / during training | `flex_attention` | `flex_attention` | | LoRA r8 SFT losses after generate (3 steps) | 8.1270, 8.5179, 7.5728 | bit-identical | The base A/A spread was 0.20 ms per token. Greedy ids match through token 104 of 128 and then differ (flex vs SDPA in bf16); both continuations are coherent. 4-bit was not run there. ## After the main merge (L4, Gemma 3 1B, 16-bit, merge base 3ecb1ba) Twelve greedy generates of 32 new tokens at prompt lengths 16 / 40 / 75 / 130 / 200 / 260 / 33 / 90 / 300 / 50 / 120 / 20, in one process per arm: | torch | arm | new Dynamo graphs, calls 1 to 5 (0 after) | ms per token, calls 6 to 12 | math_attention calls | |---|---|---|---|---| | 2.14.1 | SDPA ref (flex off) | 10, 0, 0, 0, 0 | 56 to 58 | 0 | | 2.14.1 | main | 18, 13, 9, 8, 4 | 192 to 198 | 9152 | | 2.14.1 | unslothai#16049 + unslothai#16073 | 18, 8, 0, 8, 4 | 67 to 70 | 0 | | 2.14.1 | unslothai#16049 + unslothai#16073 + this PR | 14, 4, 0, 4, 4 | 57 to 58 | 0 | | 2.10.0 | SDPA ref (flex off) | 10, 0, 0, 0, 0 | 59 to 62 | 0 | | 2.10.0 | main | 18, 12, 7, 8, 4 | 158 to 178 | 9152 | | 2.10.0 | unslothai#16049 + unslothai#16073 | 18, 8, 0, 8, 4 | 71 to 72 | 0 | | 2.10.0 | unslothai#16049 + unslothai#16073 + this PR | 14, 4, 0, 4, 4 | 58 to 59 | 0 | The hybrid routing does not recompile per prompt length. It compiles fewer graphs than the stack alone, and its decode matches the SDPA reference once warm. Single 32-token generates right after a new shape are dominated by those first compiles in every arm. In the earlier per-order runs, that made this arm look slower on a shape change than it is once warm.
Stacked on #16049 (base branch
perf/r11-flex-first-call). Review and merge that one first; this PR only adds the commit on top.What changes
On sm86 / sm89 cards with 101376 B of shared memory (L4, A10, RTX 3090 / 4090, L40S), #16049 stops a short prompt from pinning Gemma 3 flex attention to the eager fallback. One path is still open on torch 2.10 and 2.11: a batch size change between
generatecalls._use_flex_decodingneeds a static batch, so even the one-token decode step (4 query rows on Gemma 3 1B, not admitted by Flex attention: small shared-memory tiles for short no-grad calls so one short prompt does not leave the process on eager attention #16049) moves to the main flex kernel.Required: 151552 Hardware limit:101376), unsloth_zoo'ssuppress_errorsturns that into a Dynamo skip offlex_attention, and every later call in the process, batch 1 and long prompts included, runs eagermath_attention.The fix, in
_wrap_flex_attention_forward:FORCE_USE_FLEX_ATTENTION. With a static batch they stay on flex_decoding, now with the tiles. With a dynamic batch the main kernel runs with tiles that fit.BLOCK_Mequal tofwd_BLOCK_M(64). Before torch 2.14, flex_decoding computesSAFE_M_BOUNDARYfrom its ownBLOCK_M, which is next_pow2(rows), and only afterwards letsfwd_BLOCK_Mreplace the tile. At exactly 16 or 32 rows the 64-row tile then runs without row masks, and the output is wrong or NaN. Examples are Gemma 3 1B with a 4 or 8 token prompt, 4B / 12B / 27B with an 8 or 16 token prompt, and speculative decoding. WithBLOCK_Mset as well, the boundary is computed for the tile that actually runs.Results
16 / 32 decode rows and 1B / 4B generate against SDPA
This run used one Colab L4 (sm89, 101376 B), with torch 2.10.0, 2.11.0 and 2.14.1 in fresh venvs. Base is #16049; head is this PR.
Op-level cells:
BLOCK_MstaticOn 2.14 the shipped rule leaves these calls untouched. The last two columns there only show that the options would also be correct.
Generate setup:
UNSLOTH_ENABLE_FLEX_ATTENTION=0(SDPA).Reading the table:
Token ids against SDPA, in all 8 steps of every compiled arm:
Batch change, first run
All numbers come from one L4 job (sm89, 101376 B). Generate runs on Gemma 3 1B it, 16-bit weights, transformers 4.57.6, greedy decoding. The prompts are the 28-token chat prompt and a 2048-token prompt. Each step runs in this order: short B1, short B2, short B1, 2k B1, 2k B2, 2k B1. Decode is (t33 - t1) / 32 at the min of 3 repeats. Base is #16049.
Decode ms/token by step:
Prefill shows the same pattern. On #16049, 2k batch 1 prefill on torch 2.10 takes 0.26 s after the batch change, against 0.086 s with this PR. On 2.11 it is 0.29 s against 0.090 s.
math_attention(eager flex) calls per process:Token ids:
Op level (plain torch flex, against an fp32 reference, tolerance 0.05):
Static matrix: 74 bf16 / fp16 head_dim 256 cells. They cover query heads per kv head 1 to 4, q_len 1 to 64, kv 29 to 2112, causal and sliding 512 windows, batch 1 and 2, and softcap. All are correct on 2.10, 2.11 and 2.14 with the new rule; max abs error is 0.0044. 50 of them ran on flex_decoding, 24 on the main kernel.
Generate-like dynamic sequences through one
torch.compile, Gemma 3 1B and 4B shapes with batch 1, 2 and 3:One-token decode timing, static batch 1, which stays on flex_decoding. Each value is the median of 5 x 200 calls, given for each of 3 rounds:
On 2.10 the tiles are inside the A/A spread. On 2.11 they are at most about 1% slower at op level. End to end, decode is not slower on either version (table above). On 2.14 the tiles measured about 3% slower at op level, which is one reason the rule stops at 2.14.
Tests
tests/test_flex_small_smem_tiles.pyadds:BLOCK_Mtofwd_BLOCK_Mfor the not-forced short calls.tests/test_flex_*.py: 192 passed, 13 skipped on Flex attention: small shared-memory tiles for short no-grad calls so one short prompt does not leave the process on eager attention #16049; 211 passed, 13 skipped here. No failing IDs on either side.py_compilepasses on Python 3.9 to 3.14.Not covered
With this PR on top of #16049, Gemma 3 flex generate on these cards stays compiled in every prompt order and batch sequence tested on torch 2.10 to 2.14.1. #16041 (Gemma 3 generate on SDPA) is still faster for decode on top of this stack; see below.
L4 re-check on torch 2.10.0 to 2.14.1
Colab L4, one venv per torch version, every output row and head compared with fp32 SDPA (tolerance 2e-2), bf16 head_dim 256:
BLOCK_MBLOCK_M=64(this PR)Batch 1, then 2 (dynamic), then 1:
BLOCK_M=64The
< 2.14gate is safe on 2.13 (the tiles are correct there) but wider than needed; on 2.10 steady decode with the tiles is 0.7% slower than main, inside the noise. Gemma 3 1B generate, batch 1, 2, 1 on torch 2.10: main and #16049 alone fall back to eager attention (806 and 832 calls in steps 2 and 3, batch-2 tokens diverge from SDPA); with this PR there are none and the batch-2 tokens match SDPA. Gemma 3 270M: main 558 / 504 fallback calls, this PR 0.Gemma 3 1B decode, 256 new tokens, ms per token, median of 3 rotated rounds on one L4 (the stack's own A/A spread was within 1.6%):
Not covered: RTX 50xx (excluded), A10 / RTX 3090 / 4090 / L40S, a GPU training run, and the fp32 default for head_dim 256 short prompts.
After the main merge (L4, Gemma 3 1B, merge base 3ecb1ba)
Main's own flex wrapper change (#16092) landed before these PRs merged it in, so the end-to-end orders were run again on the merged heads. The numbers are math_attention fallback calls per generate step, then ms per token per step:
The stack never reaches the eager fallback. Main does on every order, and on 2.14.1 now too. Greedy ids diverge from the SDPA reference in a few steps where main, on the eager fallback, matched. That is the bf16 flex vs SDPA divergence both arms show elsewhere, already listed above as pre-existing.
AMD ROCm (gfx1151, Linux)
The flex wrapper tests (
test_flex_small_smem_tiles.py,test_flex_small_smem_tiles_gpu.py,test_flex_decode_guard_wrapper.py,test_flex_tuned_backward_kernel_options.py) ran on main (3ecb1ba), this branch and the merge, in one job on one host: main 97 passed, this branch 129 passed, the merge the same, 0 failed and 2 skipped in each. Verdict NO_REGRESSION. The GPU was shared, so this is correctness only, not timing.