Skip to content

Gemma 3: keep flex attention only where its head_dim 256 template fits the card - #14670

Merged
danielhanchen merged 3 commits into
mainfrom
gemma3-flex-shared-memory-gate
Oct 25, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
gemma3-flex-shared-memory-gate

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Related to #14439 (found while reproducing it on other GPUs; the T4 part is #14482).

Problem

Gemma 3 is in _FLEX_PREFERRED_MODELS, so Unsloth routes it to flex attention on every card where flex is supported. At head_dim 256 (Gemma 3 270M, 1B, 4B, 12B) Inductor's default flex template needs 151552 bytes of shared memory per block. On cards with 101376 (L4 sm89, RTX PRO 6000 Blackwell sm120, and the rest of the sm86 / sm89 / sm120 class) Gemma 3's flex backward gives wrong LoRA gradients on padded batches.

Measured with unsloth/gemma-3-270m, LoRA r 16 on all projections, one right-padded batch of 4 (lengths 1500 / 1400 / 1300 / 1450), causal LM loss, identical LoRA weights, against plain transformers + PEFT (no Unsloth import, eager attention):

Card (shared memory / block) Path LoRA grad norm cosine vs plain transformers (median / min)
RTX PRO 6000 (101376) plain transformers + PEFT 0.2433 reference
RTX PRO 6000 (101376) main (flex) 7423 0.16 / -0.46
RTX PRO 6000 (101376) this PR 0.2438 0.999 / 0.88
L4 (101376) main (flex) 19294
L4 (101376) this PR 0.2410
A100 40GB (166912) main (flex), unchanged by this PR 0.2460 0.999 / 0.70

With the decision-model (Clef) head the same bug keeps Gemma 3 at chance: on an L4, banking77 decision rows stay flat on main (loss 4.33 to 4.34 over 100 steps, grad norms 4e5 to 7e6, clipped to nothing). On the RTX PRO 6000 this PR trains it (60 steps, loss 4.33 to 1.84, grad norms 12 to 24). On the L4, the path this PR selects (the one UNSLOTH_ENABLE_FLEX_ATTENTION=0 takes) trains it too: loss 4.33 to 1.88 in 60 steps, 5.53 s/step and 2.69 GB peak against 8.73 s/step and 3.54 GB on main's flex path (single runs, not an exclusive-card timing).

Fix

_supports_flex_attention now refuses flex for the flex-preferred family when the decoder's head dim is in (128, 256] and a visible CUDA card has less shared memory per block than that template needs. That is the path UNSLOTH_ENABLE_FLEX_ATTENTION=0 already takes: Gemma 3's SDPA is disabled, so the label resolves to eager and unsloth_zoo's patched Gemma 3 attention runs SDPA, the same path T4 / pre-Ampere cards use. Block compile still applies (all 18 layers compile on both cards with the eager label).

Unchanged: A100, H100, B200 and other cards where the template fits; Gemma 3 27B (head_dim 128); every model outside the flex-preferred family; no CUDA, ROCm, and an unreadable probe (fail open, keep flex); an explicit attn_implementation request.

Tests

  • tests/test_flex_preferred_shared_memory.py: L4-class card leaves flex; A100 / B200 keep it; a mixed box follows its smallest card; head_dim 128 keeps flex; non-Gemma models untouched; ROCm, no CUDA and a failing probe keep flex. The two gating tests fail on main, all seven pass here.
  • Every test file touching flex / attention routing (37 files, 593 tests) gives the same results on main and this branch apart from the two new gating tests; the only other differences were CPU timeouts that pass when rerun alone.

…s the card

On cards with 101376 bytes of shared memory per block (L4 sm89, RTX PRO 6000 sm120) Gemma 3's
flex backward gave wrong LoRA gradients on padded batches: grad norm 7423 against 0.243 for plain
transformers + PEFT, cosine 0.16. An A100 matches the reference. There the flex-preferred family
now takes the path UNSLOTH_ENABLE_FLEX_ATTENTION=0 takes (eager label, unsloth_zoo's SDPA attention);
no CUDA, ROCm, head_dim 128 Gemma 3 and an unreadable probe keep flex.
@danielhanchen danielhanchen self-assigned this Oct 22, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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:59:27.948398Z 0d19ceb 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: ec272e56e1

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

Copy link
Copy Markdown
Member Author

@codex review

3 similar comments
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 0d19cebf08

ℹ️ 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 137a093 into main Oct 25, 2026
35 of 37 checks passed
@danielhanchen
danielhanchen deleted the gemma3-flex-shared-memory-gate branch October 25, 2026 04:02
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 25, 2026
…raining on T4) (unslothai#14482)

Fixes unslothai#14439

## Problem

`FastDecisionModel` + the Clef head on `google/gemma-3-270m` trains flat
on a T4: the loss never moves and accuracy stays at chance, while the
same script trains Qwen3.5, LFM2 and MiniCPM, and plain transformers +
PEFT in float32 trains Gemma 3 fine.

## Cause

On a GPU without bfloat16, Gemma 3 (like Qwen3.5, gpt-oss and the other
`FORCE_FLOAT32` families) loads on Unsloth's float32 path: float16
weights, no autocast. `_clef_mixed_precision` turns autocast off for
that path by setting `fp16 = bf16 = False`, which also drops the fp16
loss scaler. The backbone still backpropagates through float16 weights
and Gemma 3's float16 norm outputs, so without loss scaling the
gradients that reach the adapters are mostly rounding noise.

Measured on a Tesla T4 (unsloth main, transformers 5.2.0, torch 2.11),
one fixed Clef batch, identical weights, Unsloth vs plain float32:

| | logits cosine | adapter gradient cosine (median) |
|---|---|---|
| Gemma 3 270M, Unsloth float32 path | 1.0 | 0.48 |
| Gemma 3 270M, same with the backbone gradient scaled x1024 | 1.0 |
0.997 |
| Qwen3 0.6B control | 1.0 | 0.92 |

The forward is exact; only the backward loses signal.

## Fix

Keep autocast off and the forward unchanged, and give the float32 path a
loss scaler of its own: `DecisionTrainer` installs a
`torch.amp.GradScaler` on its accelerator, which accelerate's `backward`
and optimizer step already use (scale, skip on overflow, update), and
unscales before gradient clipping. Trainable weights on this path are
float32 already (LoRA and full finetuning), so the scaler can unscale
them. `args.fp16` / `args.bf16` stay False on this path, as on main, so:

- no autocast, no Apex, and no change to accelerate's process-wide mixed
precision (a second Trainer in the same process works as before);
- DeepSpeed and FSDP keep the float32 path exactly as on main (they run
their own fp16 engines when asked for fp16, which would cast it away),
and CPU runs get no scaler;
- evaluation and serving are untouched.

An earlier revision of this PR enabled fp16 autocast for Gemma and
gpt-oss instead. That also runs Gemma 3's float32 attention in float16,
which is what the float32 path exists to avoid, and it changed
evaluation and serving numerics.

Separately, on bfloat16 cards with 101376 bytes of shared memory per
block (L4, RTX PRO 6000) Gemma 3's flex attention backward gave wrong
gradients on padded batches, which kept Clef at chance there too; that
is unslothai#14670.

## Results

BANKING77 decision rows, 200 steps, the reporter's recipe (r = 64, lr
1e-4, head lr 3e-4, batch 4 x 4), Tesla T4, accuracy on 300 held-out
rows (77 classes, chance 1.3%):

| Backbone | Arm | Loss, step 10 -> 200 | Accuracy |
|---|---|---|---|
| Gemma 3 270M | main | 4.337 -> 4.338 | 1.3% |
| Gemma 3 270M | plain transformers + PEFT, float32 (reference) | 4.330
-> 1.055 | 70.3% |
| Gemma 3 270M | this PR | 4.330 -> 1.017 | 71.7% |
| Gemma 3 270M | earlier revision (fp16 autocast) | 4.330 -> 1.043 |
69.3% |
| Qwen3.5 0.8B | main | 3.680 -> 0.509 | 85.7% |
| Qwen3.5 0.8B | this PR | 4.162 -> 0.553 | 84.3% |

Qwen3.5 on the float32 path now spends its first few steps while the
scaler backs off from its initial scale (logged as a nan grad norm, as
on any fp16 run), then tracks main.

The current revision (standalone GradScaler) on Tesla T4s, shorter runs:
Gemma 3 270M LoRA, 100 steps, loss 4.33 -> 1.58, 58.3%; Gemma 3 270M
full finetuning, 60 steps, 4.10 -> 1.85, 57.3%; Qwen3.5 0.8B, 60 steps,
4.16 -> 0.94, 77.0%; and Gemma 3 with another Trainer created first in
the same process (Accelerate state already set), 30 steps, 4.33 -> 2.74.

## Tests

- `test_clef_trains_under_the_autocast_it_evaluates_in`: the float32
path keeps `fp16 = bf16 = False` and `ACCELERATE_MIXED_PRECISION = no`,
as on main.
- `test_clef_loss_scaler_only_on_the_float32_path`: a scaler for the
float32 path on CUDA, none under DeepSpeed, FSDP, on CPU or for a
non-forced backbone.
- `test_clef_trains_in_float16_and_bfloat16` (GPU): the float32 path
trains with the accelerator's GradScaler; the scaler's skipped
calibration steps are allowed.
- On a Tesla T4: the GPU decision tests pass on this branch (4 passed,
bfloat16 skipped) and fail on main. The CPU decision test files give the
same results on main and this branch.

---------

Co-authored-by: Daniel Han <[email protected]>
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant