Repository navigation
Flex attention: tuned backward tiles on A100 for head_dim 256 (Gemma 3 LoRA 1.9-2.7x faster) - #15193
Merged
Merged
Conversation
Inductor's sm8x default flex backward config at head_dim 256 is (64, 64, 64, 64, 2 stages, 4 warps). On an A100 it is about 10x slower than a 32 x 32 tile with one stage (Gemma 3 4B shapes, fwd+bwd: causal B8 x 1024 32.4 -> 3.2 ms, sliding window B2 x 4096 53.3 -> 4.8 ms, causal B2 x 4096 115.3 -> 9.5 ms). Gemma 3 prefers flex, so its LoRA backward was half of an A100 step: Gemma 3 4B bf16 LoRA bs8 x 1024 goes from 2058 to 1068 ms/step with the same losses and peak memory. Only backward keys (bwd_*) are set, only on capabilities it was measured on (sm80), only for calls that need a backward and pass no options of their own. UNSLOTH_FLEX_TUNED_BACKWARD=0 disables it, =1 forces it.
…ests, SPDX header
Member
Author
|
@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. 👍 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". |
danielhanchen
added a commit
that referenced
this pull request
Oct 25, 2026
…ductor (#15228) Fixes a regression from #15193. The tuned flex backward tiles (`bwd_BLOCK_M1/N1/M2/N2 = 32`, 1 stage) are added on sm80 for 128 < head_dim <= 256. Two cases break the compile there. Inductor raises `Invalid FlexAttention backward kernel options`: - **The caller passes some of its own tiles.** For example, `kernel_options = {"bwd_BLOCK_M1": 64}` merged with our `bwd_BLOCK_N1 = 32` breaks `bwd_BLOCK_N1 % bwd_BLOCK_M1 == 0`. - **The block mask's sparse blocks are not multiples of 32.** An example is a 16-wide custom block mask. The default 128-wide masks that transformers and Unsloth build are not affected, so this needs a custom mask or custom kernel options. Reproduced with real compiles on B200 with `UNSLOTH_FLEX_TUNED_BACKWARD=1`. ### Change `_flex_tuned_bwd_fits` adds the tuned tiles only when both hold: - the caller set no tile, warps or stages key; - every `BLOCK_SIZE` of the block mask is a multiple of the tuned tiles. Otherwise Inductor's own choice is kept, as before #15193. The docstring now says the env var is read at `import unsloth` (where the flex forward is wrapped), not at model load. ### Tests New cases in `tests/test_flex_tuned_backward_kernel_options.py`: - **Routing tests:** caller tile / warps / stages keys turn the tuned tiles off; non-tile caller options (`BACKEND`) keep them; tiles are added only when every sparse block size is a multiple of 32. - **Real GPU compiles of forward + backward** for a 16-wide block mask and for a caller `bwd_BLOCK_M1 = 64`. Both fail on main with the Inductor error. On B200, torch 2.14.1: | | passed | failed | |---|---|---| | main | 28 | 8 | | this PR | 36 | 0 | On torch 2.10.0: 35 passed, 1 skipped. The 16-wide block case skips there because plain `torch.compile(flex_attention)` cannot compile 16-wide sparse blocks on 2.10 at all, with or without Unsloth; 2.14 shrinks its own tiles. The other `tests/test_flex_*.py` files give the same counts on main and on this PR. **Cost:** the new check costs 1.8 us per flex call. It only runs where the tuned tiles could apply: sm80, torch >= 2.10, calls that need a backward. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen
added a commit
that referenced
this pull request
Oct 25, 2026
…X 4090) instead of eager (#15271) Gemma 3 trains on flex attention with head_dim 256. Since #14670, cards whose shared memory cannot hold Inductor's default head_dim 256 flex tiles send Gemma 3 to the eager label (SDPA). That covers every sm86 / sm89 card: A10, RTX 3090 / 4090, A6000, L4 and L40S, all at 101376 B per block. On an L4 the default tiles do not fit: | torch | forward default | backward default | |---|---|---| | 2.10 | FlexConfig(32, 64, 3 stages), needs 151552 B: fails | (64, 64, 64, 64, 2 stages), needs 135680 B: fails | | 2.14 | retries a smaller tile itself and compiles | still needs 114688 B: fails | SDPA works there, but with Gemma 3's 1024-token sliding window it has to take the window as a dense mask, which is slow. ### Change (`unsloth/models/_utils.py`) **Tile set:** a set that fits these cards and was the fastest that compiled on an L4: - forward 64 x 64, 1 stage, 4 warps; - backward 32 x 32 everywhere, 1 stage, 4 warps. **When it applies** (`_flex_small_smem_device_ok()`, read once at wrap time): - the device conditions: - CUDA, not ROCm, with torch >= 2.10, since the templates read the `fwd_` / `bwd_` keys from 2.10 on; - every visible device is sm8x with 101376 <= shared memory < 151552; - the call: - 128 < head_dim <= 256; - it needs backward, or q_len >= 128, so short no-grad queries keep flex_decoding's own config; - the caller set no tiles of its own; - the block mask's sparse block size is a multiple of these tiles. This is the same check #15228 added for the A100 tuned backward. **Routing:** - With the gate on, `_flex_preferred_fits` keeps Gemma 3 on flex. - `UNSLOTH_FLEX_SMALL_SMEM_TILES=0` restores today's SDPA route. **What else is unchanged:** - A100 keeps the tuned backward from #15193. - H100 / B200 have room for the defaults. - T4 never reaches flex. - sm120 and mixed boxes stay on #14670's route. - ROCm is excluded. ### Results Colab L4, Gemma-3-4B LoRA, bs 2 x 4096, 12 steps (4 warm-up). Base is main (SDPA route) and head is this PR, each run twice. Each torch version runs as one VM job; the base and head trees are main at a2aca8d and this branch. | torch | quant | main s / step | this PR s / step | peak GB main -> PR | last loss main / PR | |---|---|---|---|---|---| | 2.14.1 | 16-bit | 10.18 / 10.18 | 5.13 / 5.12 | 10.13 -> 9.91 / 10.04 | 1.2136, 1.2130 / 1.2125, 1.2125 | | 2.14.1 | 4-bit | 10.32 / 10.26 | 5.19 / 5.19 | 6.37 -> 6.15 / 6.28 | 1.2234, 1.2233 / 1.2242, 1.2243 | | 2.10.0 | 16-bit | 10.24 / 10.25 | 5.25 / 5.24 | 10.16 -> 9.91 | 1.2078, 1.2081 / 1.2074, 1.2072 | | 2.10.0 | 4-bit | 10.36 / 10.37 | 5.30 / 5.31 | 6.40 -> 6.15 | 1.2181, 1.2183 / 1.2176, 1.2178 | - **Speed:** step time halves in every cell on both torch versions, with lower peak memory and last losses within 0.001 of main. - **Engagement:** the head runs `attn_impl=flex_attention` and main runs eager; no "block compile failed" lines. - **Accuracy:** - At op level on Gemma 3 shapes (causal + sliding, padded), the new tiles on L4 bf16 vs fp32 SDPA give a relative error of 0.0020-0.0025 for out, dq, dk and dv, the same as the default tiles on B200. - For the whole model (gemma-3-270m) vs an fp32 eager reference, the gradient relative error is 0.110 on L4, no worse than HF's own bf16 paths on the same check (eager 0.157, SDPA 0.116). ### Tests - **New `tests/test_flex_small_smem_tiles.py`:** - the device gate per card and torch version; - the kill switch and ROCm; - the tile ranges and their divisibility into the default sparse block; - wrapper routing: training calls, no-grad prefill vs decode, caller tiles left alone, sparse blocks our tiles do not divide, and the A100 tuned backward still winning. - **New `tests/test_flex_small_smem_tiles_gpu.py`:** compiles forward + backward with the gate forced on, checks the kernels need under 101376 B (65544 / 65536 B), and checks the result against fp32 SDPA (cos > 0.999). - **Results with `test_flex_preferred_shared_memory.py` and `test_flex_tuned_backward_kernel_options.py` (B200):** 80 passed on torch 2.14; 79 passed and 1 skipped on torch 2.10. ### Not covered - Real sm86 cards, RTX 4090 and L40S. They are covered by construction (same shared memory and capability class), not measured. - torch 2.11 to 2.13 timing. - Fp32 reference checks on Gemma 3 4B / 12B, and the image bidirectional mask. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Gemma 3 trains through FlexAttention. On an A100 its LoRA step was 17% slower than HF + Liger, which uses memory-efficient SDPA. The profile shows the flex backward at 1064 ms per step (31 ms per layer) against 224 ms for the SDPA backward.
The cause is Inductor's default sm8x flex backward config at 128 < head_dim <= 256: (64, 64, 64, 64), 2 stages, 4 warps. On sm80 a 32 x 32 tile with 1 stage is much faster.
Change
unsloth/models/_utils.py, in the existing flex forward wrapper:kernel_options(bwd_BLOCK_M1/N1/M2/N2 = 32,bwd_num_stages = 1,bwd_num_warps = 4). The forward template is unchanged.bwd_keys. ROCm never gets them. Other capabilities keep Inductor's choice; B200's default is already faster.UNSLOTH_FLEX_TUNED_BACKWARD=0turns it off.=1forces it on any CUDA device with torch >= 2.10.Results
Attention fwd + bwd on Colab A100 40GB. Gemma 3 4B attention shape (8 query heads, 4 KV heads, head_dim 256, bf16), compiled flex, median of 15 runs, ms:
Inductor's default at this shape is about 6-8x slower on 2.14 than on 2.10. The tuned tile is fast on both. dQ, dK and dV were identical to the default config in every row.
Gemma 3 4B LoRA training on A100, torch 2.14. r16 on all projections, gradient checkpointing, fixed-length rows. Main ran twice in the same VM.
Losses and peak memory are unchanged. Unsloth goes from 1.17x Liger's step time to 0.61x.
Tests
New
tests/test_flex_tuned_backward_kernel_options.py(24 cases) covers:With
UNSLOTH_FLEX_TUNED_BACKWARD=1forced on the local B200, so the new path runs everywhere, alltests/test_flex_*.pygive 150 passed, 3 skipped on torch 2.14, and 149 passed, 3 skipped, 1 failed on torch 2.10. The failure,test_flex_mask_graph_breaks.py::test_compiled_flex_mask_has_no_graph_breaks_and_matches_eager, fails the same way on main in that environment, with or without the flag (a DynamoInternalTorchDynamoErrorinside transformers' quantizer module).Not covered