Repository navigation
Clef: keep fp16 loss scaling on the float32 path (fixes Gemma 3 not training on T4) - #14482
Conversation
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.
## 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.
## 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.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
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]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Tested on a Colab T4 (no bf16, the reporter's case) at
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 |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…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.
Fixes #14439
Problem
FastDecisionModel+ the Clef head ongoogle/gemma-3-270mtrains 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_FLOAT32families) loads on Unsloth's float32 path: float16 weights, no autocast._clef_mixed_precisionturns autocast off for that path by settingfp16 = 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:
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:
DecisionTrainerinstalls atorch.amp.GradScaleron its accelerator, which accelerate'sbackwardand 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.bf16stay False on this path, as on main, so: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%):
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 keepsfp16 = bf16 = FalseandACCELERATE_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.