Skip to content

Flex attention: tuned backward tiles on A100 for head_dim 256 (Gemma 3 LoRA 1.9-2.7x faster) - #15193

Merged
danielhanchen merged 3 commits into
mainfrom
flex-bwd-sm80-d256
Oct 25, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
flex-bwd-sm80-d256

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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:

  • Options passed: backward-only kernel_options (bwd_BLOCK_M1/N1/M2/N2 = 32, bwd_num_stages = 1, bwd_num_warps = 4). The forward template is unchanged.
  • When they are passed: only for calls that need a backward and pass no kernel options of their own, and only when 128 < head_dim <= 256.
  • Devices: CUDA devices whose capability is exactly (8, 0) (A100 / A30), with every visible device checked, on torch >= 2.10, the first release that reads bwd_ keys. ROCm never gets them. Other capabilities keep Inductor's choice; B200's default is already faster.
  • Kill switch: UNSLOTH_FLEX_TUNED_BACKWARD=0 turns it off. =1 forces it on any CUDA device with torch >= 2.10.
  • Cost: the device check runs once, when the forward is wrapped at model load, never inside a compiled region.

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:

torch shape default default (A/A) this PR speedup
2.10.0 causal, B8 x 1024 5.4 5.4 3.3 1.64x
2.10.0 sliding 1024, B2 x 4096 8.4 8.0 5.1 1.6x
2.10.0 causal, B2 x 4096 14.3 14.2 10.2 1.4x
2.14.0 causal, B8 x 1024 31.9 32.0 3.1 10.3x
2.14.0 sliding 1024, B2 x 4096 53.2 53.1 4.7 11.3x
2.14.0 causal, B2 x 4096 115.0 115.1 9.4 12.2x

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.

cell main this PR change
16-bit, bs 8 x 1024 2058 / 2057 ms 1069 / 1068 ms -48%
4-bit, bs 2 x 4096 3132 / 3133 ms 1159 / 1159 ms -63%

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:

  • the head-dim range;
  • backward-only keys, and a fresh dict on every call;
  • tiles dividing the default sparse block;
  • the kill switch;
  • the device gate: sm80 only, every visible device, torch >= 2.10, never ROCm, forced mode;
  • the wrapper passing the options into a flex call.

With UNSLOTH_FLEX_TUNED_BACKWARD=1 forced on the local B200, so the new path runs everywhere, all tests/test_flex_*.py give 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 Dynamo InternalTorchDynamoError inside transformers' quantizer module).

Not covered

  • Other GPUs: no H100 or L4 measurements, so sm90 and sm89 keep Inductor's choice. A10 / A6000 (sm86) were not measured either.
  • torch 2.10 end to end: no Gemma 3 training step was timed on 2.10. The attention benchmark above is the 2.10 evidence.
  • Older torch: torch < 2.10 never gets the options.

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-25T03:51:36.625628Z bfd8e97 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: bfd8e974d1

ℹ️ 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 0705fa5 into main Oct 25, 2026
19 of 30 checks passed
@danielhanchen
danielhanchen deleted the flex-bwd-sm80-d256 branch October 25, 2026 04:16
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant