Repository navigation
Flex attention: small shared-memory tiles for short no-grad calls so one short prompt does not leave the process on eager attention - #16049
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.
…_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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 059df74b76
ℹ️ 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".
| ours_forced = ( | ||
| kernel_options.get("FORCE_USE_FLEX_ATTENTION") is True | ||
| and "FORCE_USE_FLEX_ATTENTION" not in requested | ||
| ) | ||
| kernel_options.update(requested) |
There was a problem hiding this comment.
Skip short-query tiles when the caller disables the main kernel
On the targeted sm86/sm89 devices, a short no-grad call with kernel_options={"FORCE_USE_FLEX_ATTENTION": False} still receives the new 64-row main-kernel tiles, but kernel_options.update(requested) overwrites the force flag with False. Unlike the explicit TRITON_DECODE case handled below, this leaves flex_decoding running with tiles that do not cover its query rows. For example, 28 query tokens with four query heads per KV head require 112 rows; on torch 2.10, this configuration computes only the first 64 rows and leaves the remaining output unwritten. Preserve this explicit caller choice by withholding the short-query tiles when the caller supplies a false force flag.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a5d51e4: when the caller passes FORCE_USE_FLEX_ATTENTION: False, the wrapper now keeps only the caller options, so flex_decoding gets no 64-row tiles. Covered by test_wrapper_forced_short_prompt_keeps_caller_force_off_untouched.
…ts own kernel_options untouched [skip ci]
|
@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". |
…pped as main's flex_decoding guard does
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. 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". |
…so a batch-size change does not leave the process on eager attention (unslothai#16073) Stacked on unslothai#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), unslothai#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 `generate` calls. - After batch 1 then batch 2, Dynamo marks the batch dim dynamic. `_use_flex_decoding` needs a static batch, so even the one-token decode step (4 query rows on Gemma 3 1B, not admitted by unslothai#16049) moves to the main flex kernel. - The main kernel's default head_dim 256 tile needs 151552 B, the compile fails (`Required: 151552 Hardware limit:101376`), unsloth_zoo's `suppress_errors` turns that into a Dynamo skip of `flex_attention`, and every later call in the process, batch 1 and long prompts included, runs eager `math_attention`. - torch 2.14 compiles the same call, so nothing changes there. The fix, in `_wrap_flex_attention_forward`: - On torch before 2.14, a no-grad call with a bf16 / fp16 head_dim 256 query on these cards now also gets the small-smem tiles when its query is shorter than 128 and its decode tile fits (64 rows or fewer). - These calls do not get `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. - They also get plain `BLOCK_M` equal to `fwd_BLOCK_M` (64). Before torch 2.14, flex_decoding computes `SAFE_M_BOUNDARY` from its own `BLOCK_M`, which is next_pow2(rows), and only afterwards lets `fwd_BLOCK_M` replace 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. With `BLOCK_M` set as well, the boundary is computed for the tile that actually runs. - fp32 and head_dim 192 are left alone. With the tiles, fp32 decode needs 147456 B, and head_dim 192 decode failed to build on 2.10. Gemma 3 is bf16 at head_dim 256. - Training calls are unchanged. The new check comes after the backward check, and the torch version is read once, at wrap time. ## 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 unslothai#16049; head is this PR. Op-level cells: - 13 static cells (batch 1 and 2, 1 to 64 rows, including 16 and 32), against an fp32 reference with tolerance 0.05. - 12 cells from dynamic batch sequences. | torch | unslothai#16049 static | unslothai#16049 dynamic | tiles without `BLOCK_M` static | this PR static | this PR dynamic | |---|---|---|---|---|---| | 2.10.0 | 13 / 13 | 6 / 12 (151552 B compile failures) | 3 / 13 (max error 1.2 to 2.7, or NaN) | 13 / 13 | 12 / 12 | | 2.11.0 | 13 / 13 | 6 / 12 | 3 / 13 | 13 / 13 | 12 / 12 | | 2.14.1 | 13 / 13 | 12 / 12 | 3 / 13 | 13 / 13 | 12 / 12 | On 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: - Models: Gemma 3 1B it (16-bit) and Gemma 3 4B it (4-bit). - Prompts, in this order: 4, 8, 16 and 28 (chat) tokens at batch 1, then the 28-token prompt at batch 2 and batch 1, then 8 tokens at batch 2 and 4 tokens at batch 1. - Decode ms/token is the min of 2 repeats. - Reference: the same model with `UNSLOTH_ENABLE_FLEX_ATTENTION=0` (SDPA). | torch | model | arm | decode before the batch change | decode after it | suppressed errors | eager flex calls (last rep) | |---|---|---|---|---|---|---| | 2.10.0 | 1B | unslothai#16049 | 68.7 to 70.1 | 262.7 to 296.5 | 4 | 858 per generate | | 2.10.0 | 1B | this PR | 68.7 to 70.2 | 69.5 to 71.1 | 0 | 0 | | 2.10.0 | 4B | unslothai#16049 | 94.2 to 95.2 | 361.3 to 369.6 | 4 | 1122 per generate | | 2.10.0 | 4B | this PR | 96.7 to 99.1 | 95.0 to 97.0 | 0 | 0 | | 2.11.0 | 1B | unslothai#16049 | 71.8 to 72.8 | 283.3 to 318.7 | 5 | 858 per generate | | 2.11.0 | 1B | this PR | 74.3 to 74.7 | 74.6 to 76.4 | 0 | 0 | | 2.11.0 | 4B | unslothai#16049 | 101.9 to 103.3 | 343.7 to 362.3 | 5 | 1122 per generate | | 2.11.0 | 4B | this PR | 103.6 to 104.8 | 103.2 to 105.0 | 0 | 0 | | 2.14.1 | 1B | unslothai#16049 | 67.4 to 68.3 | 67.9 to 69.6 | 0 | 0 | | 2.14.1 | 1B | this PR | 66.2 to 67.2 | 66.3 to 68.7 | 0 | 0 | | 2.14.1 | 4B | unslothai#16049 | 95.2 to 96.3 | 95.5 to 97.5 | 0 | 0 | | 2.14.1 | 4B | this PR | 95.0 to 96.3 | 95.1 to 96.1 | 0 | 0 | Reading the table: - On 2.14 the two arms run the same code, so that row pair is an A/A. Its spread is up to about 1.5%. - Before a batch change, decode on 2.10 / 2.11 is between equal and about 3% slower with the tiles, depending on model and version. The earlier 1B run in the next section measured equal or faster. After a batch change, unslothai#16049 is 3.5x to 4x slower. Token ids against SDPA, in all 8 steps of every compiled arm: - Each run is either identical to SDPA over all 33 tokens or first differs at token 4 to 32. That is the same range unslothai#16049 itself shows on 2.14 (token 4 for the 1B 16-token prompt). - The text stays coherent ("..., invented by Johannes Gutenberg in the mid-15th c..."). - No step produced NaN or garbage. ### 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 unslothai#16049. Decode ms/token by step: | torch | arm | short B1 | short B2 | short B1 | 2k B1 | 2k B2 | 2k B1 | suppressed errors | |---|---|---|---|---|---|---|---|---| | 2.10.0 | unslothai#16049 | 69.1 | 248.9 | 226.9 | 248.2 | 253.8 | 269.8 | 4 | | 2.10.0 | this PR | 69.0 | 68.9 | 67.2 | 71.1 | 73.3 | 71.9 | 0 | | 2.11.0 | unslothai#16049 | 75.2 | 294.4 | 266.4 | 288.6 | 300.0 | 288.4 | 5 | | 2.11.0 | this PR | 72.7 | 75.3 | 73.9 | 76.0 | 79.2 | 77.4 | 0 | | 2.14.1 | unslothai#16049 | 65.5 | 67.0 | 66.2 | 70.5 | 72.1 | 69.5 | 0 | | 2.14.1 | this PR | 65.5 | 67.2 | 65.9 | 70.0 | 72.4 | 70.2 | 0 | Prefill shows the same pattern. On unslothai#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: - 13962 on unslothai#16049 with 2.10 / 2.11; - 3328 in every compiled arm. These 3328 are counted during compile tracing, and every compiled arm has them. Token ids: - On 2.10 and 2.11, this PR gives the same ids as torch 2.14 (both arms) in every step. - On unslothai#16049 with 2.10 / 2.11, the batch 2 short prompt ran eager. Its 33-token continuation equals the batch 1 one, while the compiled batch 2 continuation differs after a few tokens, at bf16 level, on every torch. - The 2k ids are identical in all arms. 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: | rule | 2.10 / 2.11 | 2.14 | |---|---|---| | unslothai#16049 | 14 / 22 correct, the other 8 fail to compile at 151552 B | 22 / 22 | | this PR | 22 / 22 | 22 / 22 | 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: | torch | kv | default A | default A again | tiles | |---|---|---|---|---| | 2.10.0 | 4096 | 167.6 / 168.8 / 167.0 us | 171.6 / 169.9 / 171.0 | 171.8 / 171.0 / 170.6 | | 2.10.0 | 512 | 165.7 / 167.6 / 165.5 | 167.3 / 167.0 / 166.0 | 164.1 / 168.6 / 163.2 | | 2.11.0 | 4096 | 160.5 / 157.3 / 159.5 | 158.5 / 160.3 / 160.7 | 160.1 / 161.3 / 161.9 | | 2.11.0 | 512 | 161.9 / 160.8 / 159.4 | 163.0 / 161.9 / 162.0 | 164.9 / 162.8 / 162.4 | 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.py` adds: - the torch gate (2.10, 2.11, 2.13 on; 2.14.0 and 2.14.1 off); - short no-grad cells at 1 to 64 rows that get the tiles without FORCE, plus 68 and 127 row cells that keep FORCE; - the dtype / head_dim limits; - a check that the gate is not read off these cards. - A test pins `BLOCK_M` to `fwd_BLOCK_M` for the not-forced short calls. - The new decode cells fail on unslothai#16049 and pass here. - `tests/test_flex_*.py`: 192 passed, 13 skipped on unslothai#16049; 211 passed, 13 skipped here. No failing IDs on either side. - `py_compile` passes on Python 3.9 to 3.14. ## Not covered - Hardware other than an L4: A10, RTX 3090 / 4090 and L40S were not run. They have the same 101376 B limit. - Gemma 3 12B / 27B generate was not run (4B 4-bit was). - fp32 and head_dim 192 short calls with a dynamic batch on 2.10 / 2.11 can still fail to compile. They are left as before because the tiles do not fit or build there. - CUDA-only code path; multi-OS CI not run. With this PR on top of unslothai#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. unslothai#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: | decode rows | default | tiles without `BLOCK_M` | tiles + `BLOCK_M=64` (this PR) | |---|---|---|---| | 16 | ok | wrong on every version (max err up to 9.1, NaN on 2.13) | ok | | 32 | ok | wrong on every version (NaN on 2.12 / 2.13) | ok | | 64 | ok | ok | ok | Batch 1, then 2 (dynamic), then 1: | torch | default | tiles + `BLOCK_M=64` | |---|---|---| | 2.10.0, 2.11.0, 2.12.0 | fails to compile (out of shared memory) | compiles, correct | | 2.13.0, 2.14.1 | compiles, correct | compiles, correct | The `< 2.14` gate 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 unslothai#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%): | torch | model | main | unslothai#16049 + unslothai#16073 | + unslothai#16041 | |---|---|---|---|---| | 2.14.1 | 16-bit | 69.78 | 69.64 | 57.90 | | 2.14.1 | 4-bit | 73.68 | 73.70 | 62.69 | | 2.10.0 | 16-bit | 68.98 | 69.47 | 57.71 | | 2.10.0 | 4-bit | 72.97 | 72.88 | 61.72 | 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 (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 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.
…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.
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_attentionfallback. 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:
flex_decodingkernel. That kernel holdsnext_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.torch._dynamo.config.suppress_errors = True. Dynamo turns the suppressed error into the defaultConvertFrameReturn, which marks the frameSKIPand applies it to the code object (torch/_dynamo/types.py,apply_to_code = True). That code object istorch.nn.attention.flex_attention.flex_attentionitself, so later calls run eagerly, and eager flex ismath_attention.Change
unsloth/models/_utils.py, on the same devices and head dims as #15271: sm8x with 101376 <= shared memory < 151552, 128 < head_dim <= 256, torch >= 2.10.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_rowscounts 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:
UNSLOTH_FLEX_SMALL_SMEM_TILES=0still turns the whole path off.Results
All arms ran in one Colab L4 job, each in its own process. Setup:
unsloth/gemma-3-1b-it16-bit, transformers 4.57.6.generate(max_new_tokens=1).Arms:
torch 2.14.1+cu130:
torch 2.10.0+cu128:
Torch version matrix (L4)
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_errorsit 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 parametrizedtest_wrapper_short_prompt_whose_decode_tile_does_not_fit_gets_tiles, which also assertsFORCE_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_notnow also asserts that q_len >= 128 gets noFORCE_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:kernel_optionscarryBACKENDtogether withFORCE_USE_FLEX_ATTENTION, and a callerBACKENDsurvived next to our FORCE. Now a callerAUTOis dropped and our FORCE kept, the same rule main's flex_decoding guard (Flex wrapper: send short no-grad queries to the main kernel where flex_decoding cannot compile #16092) uses, which also holds on torch 2.9 (noBACKENDthere). A callerTRITON(the main kernel) keeps our tiles without FORCE.TRITON_DECODEorFLASHnow 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):
Gemma 3 1B generate with a 25-token first prompt (eager fallback calls per generate step):
On torch 2.10, 2.11 and 2.12 a batch change still falls back without #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 (#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 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.