Skip to content

Flex attention: keep float32 Gemma 3 off the sm86 / sm89 small tiles - #15401

Merged
danielhanchen merged 3 commits into
mainfrom
dh/s7-rc-flex_fp32
Oct 27, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
dh/s7-rc-flex_fp32

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

#15271 lets Gemma 3 (head_dim 256) use flex attention on sm86 / sm89 cards (A10, L4, RTX 3090 / 4090) by passing smaller fwd_* / bwd_* tiles. Those tiles were sized for 2-byte dtypes. The load-time fit check (_flex_preferred_fits) has no dtype, so a dtype = torch.float32 load on these cards now resolves to flex_attention, and the wrapper injects the same tiles for float32 queries. At float32 every tile doubles in size and Inductor cannot compile the kernel. Before #15271 the same load resolved to eager.

Measured on a real L4 (sm89, 101376 B shared memory per block, torch 2.11.0+cu130, Triton 3.6.0), compiled flex forward + backward at [1, 4, 512, 256], GQA 4/2, causal block mask:

Case Result
main tiles, bfloat16 OK, finite
main tiles, float32 InductorError: No valid triton configs. out of resource: triton_tem_fused_flex_attention_0 Required: 147456 Hardware limit: 101376
default tiles, float32 same error, Required: 135424
SDPA, float32 OK, finite

Fix

_flex_preferred_fits takes the load dtype. On a card that only fits flex through the small tiles it now returns dtype is not torch.float32, so a float32 load keeps its previous route (eager for Gemma 3, whose bundled SDPA is disabled by name). bf16 / fp16 / unspecified dtype loads are unchanged, and cards whose default template fits (A100, H100, B200) are unchanged at every dtype. resolve_attention_implementation already receives the attention dtype from both loaders and now passes it through _supports_flex_attention.

Before / after

Test origin/main this branch
tests/test_flex_preferred_shared_memory.py::test_l4_float32_gemma3_does_not_get_the_small_tiles FAIL (flex_attention for float32) PASS
tests/test_flex_preferred_shared_memory.py, test_flex_small_smem_tiles.py, test_flex_attention_needs_ampere.py, test_flex_head_dim_version_gate.py, test_flex_large_head_dim_fallback.py 112 passed, 1 skipped 113 passed, 1 skipped

The two flex unit files also pass on torch 2.10 and 2.14.1 (transformers 5.17).

Not covered

  • No float32 tile set was searched for: float32 keeps the pre-Flex attention: fitting tiles for Gemma 3 on sm86 / sm89 (L4, A10, RTX 4090) instead of eager #15271 route rather than a new, unmeasured kernel.
  • A float32 model trained under bf16 autocast would fit the tiles, but the load-time check cannot see autocast, so it takes the conservative route.
  • Only an L4 was run; A10 / RTX 3090 (sm86) share the 101376 B limit but were not executed. transformers 4.57.6 was not run (no unsloth_zoo in that environment).

The small-shared-memory tiles fit 2-byte dtypes only. At float32 the same
tiles need 147456 B forward on an L4 (101376 B available) and Inductor
raises No valid triton configs, so a float32 load keeps its previous route.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 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-26T17:15:40.955367Z 6f44e3a 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 6f44e3a273

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

[skip ci]
@danielhanchen
danielhanchen merged commit 34969fd into main Oct 27, 2026
@danielhanchen
danielhanchen deleted the dh/s7-rc-flex_fp32 branch October 27, 2026 10:58
danielhanchen added a commit that referenced this pull request Oct 27, 2026
danielhanchen added a commit that referenced this pull request Oct 28, 2026
…tile forced no-grad calls (#15529)

**Update after merging main:** #15401 has since landed the plain float32
half of item 1 on main (`return dtype is not torch.float32` in
`_flex_preferred_fits`). After merging main this PR keeps the rest:
`UNSLOTH_FORCE_FLOAT32` (bf16 load, float32 Gemma 3 attention) is
treated as float32 through `_flex_attention_runs_float32`, and forced
no-grad main-kernel calls get the small tiles (item 2). The float32 test
is now main's `test_l4_float32_gemma3_does_not_get_the_small_tiles`,
extended with the `UNSLOTH_FORCE_FLOAT32` case.

## Summary

Follow-up to #15271, which routes Gemma 3 (head_dim 256) to flex
attention on sm86 / sm89 cards (L4, A10, RTX 3090 / 4090, L40S; 101376 B
shared memory per block) with smaller tiles instead of eager. Three gaps
in that change:

1. The routing gate does not look at the dtype. A float32 forward with
the small tiles needs 147456 B of shared memory, so float32 Gemma 3 (and
`UNSLOTH_FORCE_FLOAT32`, which runs Gemma 3 attention in float32) now
picks flex on these cards where it used to run eager. The decoder blocks
fail to compile (15 of 18 fall back to the stock forward, 3 to flex
outside the block), and training is 6x to 7x slower than the eager route
it had before.
2. The wrapper attaches the small tiles only when `query.shape[2] >=
128` or the call needs a backward. The per-block compile hook forces the
main flex kernel (`FORCE_USE_FLEX_ATTENTION=True`) for every call inside
a compiled block, including the no-grad first forward that Unsloth
gradient checkpointing runs. For a padded batch shorter than 128 tokens
that call gets Inductor's default head_dim 256 tiles (151552 B on torch
2.10), the block compile fails, and 15 of 18 Gemma-3-270m blocks fall
back to the stock forward.
3. The same condition evaluates `query.shape[2] >= 128` before the grad
check, so training calls add a sequence-length guard and a dynamic-shape
block compiles one extra graph when the length crosses 128.

## Change

`unsloth/models/_utils.py` only:

- `_flex_preferred_fits(config, dtype)` takes the small-tile shortcut
only when attention does not run in float32
(`_flex_attention_runs_float32`: a float32 load dtype, or
`UNSLOTH_FORCE_FLOAT32=1`). `resolve_attention_implementation` already
receives the load dtype and now passes it through
`_supports_flex_attention`. float32 Gemma 3 on these cards goes back to
eager; bf16 / fp16 keep flex. Cards whose default template fits (A100,
H100, B200) are unchanged in every dtype.
- New `_flex_main_kernel_forced(kwargs)`: the caller's `kernel_options`
force the main kernel (`FORCE_USE_FLEX_ATTENTION=True` or
`BACKEND="TRITON"`). Such calls get the small tiles like calls that need
a backward.
- The small-tile condition is reordered to grad, then forced, then
`query.shape[2] >= 128`, so training and forced calls never evaluate the
shape.

## Results

Gemma-3-270m (`unsloth/gemma-3-270m-it`) LoRA r=8,
`use_gradient_checkpointing="unsloth"`, padded batch of 4 at 41 tokens
(attention mask kept), no autocast, 12 steps, Colab L4 (sm89, 101376 B).
Base = main at 4f84e8f, fix = this branch. One run per arm; step time
is the median of steps 4 to 12.

| torch | dtype | arm | attention | blocks compiled (full / split / off)
| block compile failures | step time |
|---|---|---|---|---|---|---|
| 2.10.0+cu128 | fp32 | base | flex_attention | 0 / 3 / 15 | yes, 147456
B > 101376 B | 844.7 ms |
| 2.10.0+cu128 | fp32 | fix | eager | 18 / 0 / 0 | none | 141.7 ms |
| 2.10.0+cu128 | bf16 | base | flex_attention | 0 / 3 / 15 | yes, 151552
B > 101376 B | 867.3 ms |
| 2.10.0+cu128 | bf16 | fix | flex_attention | 18 / 0 / 0 | none | 114.8
ms |
| 2.14.1+cu132 | fp32 | base | flex_attention | 0 / 3 / 15 | yes, 147456
B > 101376 B | 997.5 ms |
| 2.14.1+cu132 | fp32 | fix | eager | 18 / 0 / 0 | none | 142.4 ms |
| 2.14.1+cu132 | bf16 | base | flex_attention | 18 / 0 / 0 | none |
130.9 ms |
| 2.14.1+cu132 | bf16 | fix | flex_attention | 18 / 0 / 0 | none | 121.5
ms |

float32 losses match between arms to 4 decimals at every step. On torch
2.14 the default forward tile already fits for the short no-grad call,
so the bf16 rows are the same route. The step time difference there is
within single-run noise.

Kernel check on the same L4 (compiled `flex_attention`, head_dim 256,
GQA 4:1, `FORCE_USE_FLEX_ATTENTION=True`):

| torch | dtype | call | default tiles | small tiles |
|---|---|---|---|---|
| 2.10 | fp32 | q_len 64 no-grad | fails, 135424 B | fails, 147456 B |
| 2.10 | bf16 | q_len 64 no-grad | fails, 151552 B | runs |
| 2.10 | bf16 | q_len 256 fwd + bwd | fails, 151552 B | runs |
| 2.14 | fp32 | q_len 64 no-grad | runs | fails, 147456 B |
| 2.14 | bf16 | q_len 64 no-grad | runs | runs |
| 2.14 | bf16 | q_len 256 fwd + bwd | fails, 114688 B (backward) | runs
|

## Tests

New tests. Each fails on main and passes here:

-
`tests/test_flex_preferred_shared_memory.py::test_l4_float32_gemma3_does_not_get_the_small_tiles`
(main's test, extended): a mocked sm89 card with 101376 B on torch 2.10
resolves float32 Gemma 3 to eager, bf16 / fp16 to flex,
`UNSLOTH_FORCE_FLOAT32=1` to eager, and float32 on an A100 to flex as
before.
-
`tests/test_flex_small_smem_tiles.py::test_wrapper_forced_main_kernel_no_grad_short_query_gets_tiles`
(`FORCE_USE_FLEX_ATTENTION` and `BACKEND="TRITON"`): a no-grad q_len 64
call that forces the main kernel gets the small tiles. `BACKEND="AUTO"`
does not.
-
`tests/test_flex_small_smem_tiles.py::test_wrapper_training_calls_add_no_sequence_guard`:
a `dynamic=True` compiled block over q_len 256, 512, 64, 32 builds as
many graphs with the small-tile gate on as with it off (main: 3 vs 2).

Related suites (42 files that touch attention resolution, the flex
wrapper, block compile or forced float32): 757 passed, 31 skipped, 12
failed with the fix. Main has the same 12 failures plus the 4 new tests.
The 12 shared failures are unrelated to this change (sentence
transformer config kwargs, `test_qwen3_5_gdn_block_has_no_break`,
lfm2_vl flash scoping, stablelm TP oracle).

## Not covered

- A10 / RTX 3090 / RTX 4090 / L40S were not run. They share the 101376 B
limit and the gate, but only an L4 was measured.
- torch 2.11 to 2.13 were not run on hardware. The tests mock the device
and version.
- fp32 flex with tiles that fit 101376 B was not searched. float32 keeps
the eager route it had before #15271. On torch 2.14 the default fp32
forward tile fits for short no-grad calls, but a full fp32 training step
on these cards was not validated on flex.
- One run per arm, no A/A repeats. The 6x to 7.5x step time differences
are far outside run-to-run noise, but the 2.14 bf16 difference is not a
result.

---------

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant