Skip to content

Flex small-smem tiles: keep float32 Gemma 3 off flex on sm86 / sm89, tile forced no-grad calls - #15529

Merged
danielhanchen merged 7 commits into
mainfrom
flex-small-smem-fp32-nograd
Oct 28, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
flex-small-smem-fp32-nograd

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

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 Flex attention: fitting tiles for Gemma 3 on sm86 / sm89 (L4, A10, RTX 4090) instead of eager #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.

…tile forced no-grad calls

Follow-up to #15271.
- float32 (and UNSLOTH_FORCE_FLOAT32) attention needs 147456 B even with the small tiles, over the
  101376 B of L4 / A10 / RTX 4090, so it keeps its previous eager route there.
- The block compile hook forces the main flex kernel for no-grad checkpoint forwards too; those
  short-query calls now get the fitting tiles instead of Inductor's default ones.
- Grad / forced checks run before query.shape[2] >= 128, so training calls add no sequence guard.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 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-27T21:29:06.406500Z 45413ee 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 danielhanchen self-assigned this Oct 27, 2026
danielhanchen added a commit that referenced this pull request Oct 27, 2026
…the state's own order (#15548)

`tests/python/test_docker_nb_refresh_state_durability.py::test_an_abandoned_restore_puts_the_tree_back`
can fail on a Linux runner with no change involved, e.g. `Repo tests
(CPU, studio)` on #15529 (job 122110779747, base ca640b8):

```
AssertionError: section 1b restored all 50 notebooks after deciding the state could not be written; the guard is evaluated once instead of per iteration
```

## Cause

The test deletes 50 notebooks and caps file size so that appends to the
rewritten state start failing about 488 records in, then checks that
section 1b stopped restoring after the first failed append. It picked
the victims by name (the 50 highest), assuming they are the last 50
records. But `unsloth_sync_notebooks.sh` writes the state in `find`
order, which is directory order. On XFS that happens to be creation
order, so the victims straddle the cap and about 38 are restored. On
ext4 (the runner's filesystem) directory order follows a per-filesystem
hash, so the 50 highest names can all sit before the cap, every one of
them is restored before any append fails, and the test reports a broken
guard that is not broken.

The script is right: it rewrites the state in its own order and stops
restoring after the first failed append. Only the test's choice of
victims depended on the filesystem.

## Change

The victims are now the last 50 records in the state file's own order,
so they straddle the cap whatever the directory order is. A new assert
also requires at least one restore before the cap, so a setup where the
victims miss the boundary fails loudly instead of passing without
exercising the guard.

## Verification (local)

- Reproduced on main by putting the 50 highest names first in the state,
as ext4 can: "restored all 50", the same failure as CI. With the
original order: 38 restored, pass.
- This branch with the state as written, shuffled with four seeds, and
with the highest names first: 6 of 6 pass.
- Sabotage: removing the per-iteration `[ "$rs_ok" = 1 ] || continue`
guard from the script fails the test in every one of those orders.
- Whole file: 11 passed.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 45413ee6a8

ℹ️ 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 67d3f81 into main Oct 28, 2026
3 of 34 checks passed
@danielhanchen
danielhanchen deleted the flex-small-smem-fp32-nograd branch October 28, 2026 15:58
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