Skip to content

Clef: keep fp16 loss scaling on the float32 path (fixes Gemma 3 not training on T4) - #14482

Merged
danielhanchen merged 11 commits into
unslothai:mainfrom
indrajeetapache:fix/clef-gemma3-fp16-autocast-14439
Oct 25, 2026
Merged

danielhanchen merged 11 commits into
unslothai:mainfrom
indrajeetapache:fix/clef-gemma3-fp16-autocast-14439

Conversation

@indrajeetapache

@indrajeetapache indrajeetapache commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #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 #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.

Clef treated every FORCE_FLOAT32 backbone like Qwen3.5 and disabled
autocast. On T4/V100 that left Gemma3 (fp16 activations via Unsloth
patches) training with no autocast, so LoRA through the patched path
stayed flat while plain transformers+PEFT fp32 learned (unslothai#14439).

Match GRPO: Gemma3 / gpt-oss still get fp16 autocast under the forced
stamp; Qwen3.5 / GLM keep the no-autocast GDN-safe path. Unknown forced
types stay Qwen-safe.
…ng Gemma

The float32 path (Gemma 3, Qwen3.5, gpt-oss and the other forced families on a GPU without
bfloat16) turns autocast off, which also dropped the fp16 loss scaler. The backbone still
backpropagates through float16 weights and activations, so on Gemma 3 the adapter gradients
lost almost all their signal (cosine 0.48 to a float32 reference) and training stayed at chance.
Keep autocast off and the forward unchanged, but train with fp16 so accelerate's GradScaler
scales the loss.
danielhanchen added a commit that referenced this pull request Oct 21, 2026
## Problem

Five checks fail on main, so the `Repo tests (CPU, studio)`, `Repo tests
(CPU, rest)` and `workflow-trigger lint` shards are red on every open PR
(for example #14472, #14482, #14488, #14490 and #14494). All five
reproduce on main `4d7ebf5cea`.

| Test | Introduced by | Fault |
|---|---|---|
|
`tests/security/test_lint_risky_loaders.py::test_the_tree_matches_the_baseline`
| #14437 | Baseline. Two new dynamic-import sites: `import_module` in
`studio/backend/core/rag/embeddings.py`, and a third
`import_from_string` in `unsloth/models/sentence_transformer.py`
(`_require_word_tokenizer`). Both are safe, see below. |
|
`tests/studio/test_tauri_branding_contract.py::test_desktop_surfaces_do_not_restore_studio_branding`
| #14473 | Product. "Studio" became "Unsloth Studio" in the Markdown
import errors and the Tauri webview reject message. The desktop contract
allows "Unsloth" there, never "Unsloth Studio". "Unsloth" meets both
#14473's rule (no bare "Studio") and this one. |
|
`tests/studio/test_usage_examples_model_source_contract.py::test_auto_switch_section_sits_above_the_usage_examples`
| #14455 | Test. The redesign moved the usage examples above the monitor
link on purpose, and its own `api-settings-tab.test.ts` pins that. |
|
`tests/studio/test_usage_examples_model_source_contract.py::test_monitor_can_unload_the_loaded_model`
| #14455 | Test. Unloading moved from a standalone button on the page
into the model picker's eject (`ApiModelLoadControls`). The `/unload`
path itself is unchanged. |
|
`tests/studio/test_settings_compact_overflow_contract.py::test_api_monitor_entries_and_expanded_text_can_shrink`
| #14455 | Test. Entry rows are now rounded cards (no `border-b`), and
the prompt/reply box's `rounded-lg` became conditional, so the class
literals the test matched are gone. The overflow guards themselves are
still in the source. |

## Fix

- **Risky loaders:** two baseline entries with reasons.
- `embeddings.py` imports only the three `sentence_transformers.models`
paths written out in a literal tuple, to wrap their `import_from_string`
with the trust gate.
- `_require_word_tokenizer` imports only after its caller has refused
any `tokenizer_class` outside `sentence_transformers.*`, and only dotted
identifiers.
- **Branding:** "Unsloth Studio" to "Unsloth" in those seven Markdown
import errors and the Rust reject message.
`conversation-markdown-import.test.ts` now matches `/Unsloth Markdown/`.
- **#14455 contracts:** rewritten to guard what the redesign keeps:
- the auto-switch section still follows the monitor link, and the usage
examples come before both;
- the page passes `unloadActiveModel` to the load controls as
`onUnloadActive`, and eject is withheld while `busy` (`modelLoading ||
unloading`, #11223's rule);
  - the `/unload` call still reads the internal id from status;
  - entry rows keep `w-full min-w-0`;
  - the prompt/reply box keeps `max-h-72 overflow-auto break-words`;
  - the model id keeps `min-w-0 break-all`.

## Verification

- The four Python files: 78 passed (5 failed on main).
- `studio/frontend/tests/conversation-markdown-import.test.ts`: 20
passed.
- Sabotage, each run against the rewritten tests, each failing exactly
one test:
- removing `min-w-0` from the entry row, or `break-words` from the text
box: the overflow test fails;
- dropping `unloading` from `busy`, or passing `onEject` while busy: the
unload test fails;
- putting the auto-switch section above the monitor link: the order test
fails.
danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Oct 21, 2026
## Problem

Three tests fail on main, and in the unsloth repo's `Core zoo` jobs (for
example unslothai/unsloth#14482):

| Test | Introduced by | Fault |
|---|---|---|
|
`test_temporary_patches_imports.py::test_temporary_patches_submodule_list_is_complete`
| #1923, #1924, #1925 | Test list. `moe_fused_swiglu`,
`moe_routing_triton` and `moe_utils_sonic` are new submodules not in
`TEMPORARY_PATCHES_SUBMODULES`, so the import smoke skips them. |
| `test_triton_fp_fusion.py::test_every_launch_states_fp_fusion` |
#1924, #1925, #1923 | Product, plus two test-list entries. See below. |
|
`test_maskless_causal_skip.py::test_right_padding_skips_on_a_single_device_model[hf_device_map2]`
| #1909 | Product. On a CPU-only torch, `torch.device(0)` raises "Cannot
access accelerator device when none is available".
`_module_spans_devices` then kept the bare `"0"`, which never matched
`"cuda:0"`. So `{"model.embed_tokens": 0, "lm_head": "cuda:0"}` counted
as two devices, contrary to the comment on that line. |

The fp_fusion failure has three parts:

- Five new Triton launches state no `enable_fp_fusion`:
`_route_single_kernel`, `_route_hist_kernel`, `_route_scan_kernel`,
`_route_starts_kernel` and `_route_scatter_kernel` in
`moe_routing_triton.py`. A sixth, `_swiglu_bwd_interleaved_kernel`, is
in `moe_utils_sonic.py`.
- The guard also flags three calls in `moe_utils_sonic.py` that are not
launches: `_pinned_ops()[0](...)` and `_pinned_ops()[1](...)` (torch
custom ops), and `hit[4]()` (a weakref in a cache entry).
- `moe_fused_swiglu.py` launches `_swiglu_fwd_kernel` and
`_swiglu_bwd_kernel` with `enable_fp_fusion = False` on purpose. It
replays the eager ATen chain bit for bit and pins its own `fma`, but the
two kernels were not in `_DELIBERATE_FALSE`.

## Fix

- `enable_fp_fusion = True` on the six launches. That is Triton's
current default, so nothing changes today; it keeps them fused once
Triton 3.9 flips the default.
- `moe_utils_sonic.py`'s three non-launch calls added to
`_NOT_LAUNCHES`, and the two `moe_fused_swiglu.py` kernels added to
`_DELIBERATE_FALSE`.
- The three submodules added to `TEMPORARY_PATCHES_SUBMODULES`. They
import cleanly on CPU.
- `_module_spans_devices`: when no accelerator can resolve a bare
integer index, it is read as `cuda:<n>`, accelerate's convention. On a
host with an accelerator `torch.device(n)` still decides, so behaviour
there is unchanged.

## Verification

Run on CPU torch 2.10 with unsloth main on the path and
`UNSLOTH_IS_PRESENT=1`, over `tests/test_maskless_causal_skip.py`,
`tests/test_temporary_patches_imports.py` and
`tests/test_triton_fp_fusion.py`:

- main: 3 failed, 272 passed (the three above);
- with this change: 278 passed, 5 skipped.
@danielhanchen danielhanchen changed the title Clef: fp16 autocast for Gemma3 FORCE_FLOAT32 (fix #14439) Clef: keep fp16 loss scaling on the float32 path (fixes Gemma 3 not training on T4) Oct 21, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 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 ⚠️ Failed 2026-10-25T03:24:34.904268Z
We couldn’t complete this review. Comment @codex review to try again.
09cbcb4 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. What shall we delve into next?

Reviewed commit: 7736f35ee3

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

chatgpt-codex-connector[bot]

This comment was marked as resolved.

Both read args.fp16 as a request for their own fp16 engine, which casts the float32 path's
activations to fp16 (or, with a config already filled from the old flag, stops on the mismatch).
There the float32 path keeps fp16 = False as before; plain and DDP runs keep the loss scaler.

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: f779cc934f

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

@LeoBorcherding

LeoBorcherding commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

Tested on a Colab T4 (no bf16, the reporter's case) at 821ef7b, against main d18a0a8. BANKING77, the recipe from #14439, 200 steps, 300 held-out rows:

Model main this PR
Gemma 3 270M loss stuck at 4.34, 1.3% (chance) loss 4.34 -> 1.28, 66.7%
Qwen3.5 0.8B 89.0% 87.3%

Gemma 3 now trains, and Qwen3.5 still trains fine (one seed each, so the small Qwen gap is noise). The GPU decision tests pass on both, and the PR's updated test fails on main, so it guards the fix.

The three red Core zoo checks are unrelated: they fail unsloth-zoo's own MANIFEST sync test after unslothai/unsloth-zoo#1956, which unslothai/unsloth-zoo#1988 fixes.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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".

Fahad090NP pushed a commit to Fahad090NP/unsloth that referenced this pull request Oct 25, 2026
…s the card (unslothai#14670)

Related to unslothai#14439 (found
while reproducing it on other GPUs; the T4 part is unslothai#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.
@danielhanchen
danielhanchen merged commit 7302874 into unslothai:main Oct 25, 2026
34 of 37 checks passed
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.

[Bug] FastDecisionModel (Clef head): Gemma-3 doesn't train — flat loss, chance-level accuracy

3 participants