Repository navigation
Forced float32: give float16 weights a GradScaler (Gemma-4 on T4 diverges) - #18065
Merged
Merged
Conversation
Forced float32 (Gemma-4 / Gemma-3 on a float16 request or a GPU without bfloat16) sets mixed precision to no, but the frozen weights and sub-layer activations stay float16 and the fused CE saves d(loss)/d(hidden) as float16 in its forward. Nothing scales the loss, so once it falls the per-token gradients sink into float16's subnormal range and many round to zero. With the same LoRA weights the forced path's gradients then point away from the float32 reference (median cosine -0.5 on gate_proj / down_proj), and a 60 step Gemma-4 E2B run climbs from 3.2 to 9.5 on T4 and on a Blackwell card. Attach a dynamic GradScaler (no autocast) to the accelerator in that case, unscale before clipping, and let the fused CE read it as it already does under float16 AMP. Skipped for bfloat16 / float32 runs, DeepSpeed, FSDP and float16 trainable parameters. UNSLOTH_FORCED_FLOAT32_GRAD_SCALER=0 turns it off.
Member
Author
|
@codex review |
Codex Review Summary: ✅ CompletedThis 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. More of your lovely PRs please. 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". |
danielhanchen
added a commit
that referenced
this pull request
Nov 17, 2026
…d since #18065) (#18091) ## Summary `Repo tests (CPU, studio)` fails on main since #18065 (seen on the staging run for #18082): ``` tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe AssertionError: these skip guards read a probe tests/_zoo_aggressive_cuda_spoof.py patches to True process-wide ... test_forced_float32_grad_scaler.py:92: torch.cuda.is_available() test_forced_float32_grad_scaler.py:117: torch.cuda.is_bf16_supported() test_forced_float32_grad_scaler.py:190: torch.cuda.is_available() ``` #18065 added `tests/test_forced_float32_grad_scaler.py` with three GPU tests guarded by `torch.cuda.is_available()`. The CUDA spoof used by the zoo suite makes that probe return True for the whole pytest session, so on a CPU runner these tests would un-skip and fail whenever they share a session with it. The repo guard catches exactly that and asks for `has_real_cuda()`. The GradScaler change in #18065 is fine; only the new test's skip guards miss the convention. ## Change `tests/test_forced_float32_grad_scaler.py` gates its three GPU tests on `has_real_cuda()` from `tests/_shared/real_accelerator.py`, as the other GPU tests do. The bfloat16 case keeps `torch.cuda.is_bf16_supported()` behind it (`has_real_cuda() and torch.cuda.is_bf16_supported()`), which the guard accepts. On a real CUDA box the gates resolve the same as before. ## Verification - `tests/python/test_accelerator_skip_guards.py`: 1 failed on main (the lines above), 24 passed with this change. - `tests/test_forced_float32_grad_scaler.py` on a CPU host: 3 skipped, with the same reasons as before.
FiditeNemini
pushed a commit
to FiditeNemini/unsloth
that referenced
this pull request
Nov 17, 2026
…allel GradScaler (unslothai#18215) ## Summary Forced float32 models (float16 frozen weights with float32 LoRA, for example Gemma-4 and Qwen3.5 on T4) get a dynamic GradScaler from unslothai#18065. That scaler is built in the trainer post init, which runs after Unsloth's tensor parallel, pipeline parallel and native FSDP2 Trainer setup. The setup is what converts an fp16 run's scaler into the native parallel scaler, so the forced float32 scaler stayed a plain `torch.amp.GradScaler` under TP and PP. Under TP=2 this fails on the first gradient clip: ``` RuntimeError: aten._amp_foreach_non_finite_check_and_unscale_.default: got mixed torch.Tensor and DTensor, need to convert all torch.Tensor to DTensor before calling distributed operators! ``` raised from `tp_native.clip_grad_norm_` -> `unscale_gradients` -> `GradScaler.unscale_`. With local shard gradients there is no error, but `found_inf` is decided per rank, so an overflow on one rank skips the step there while the other rank applies it. ## Fix - `tp_native._tp_scaler` and `pp_env.pp_trainer_setup` mark the accelerator, so the forced float32 path knows a TP / PP run converted the scaler. - `_unsloth_forced_float32_grad_scaler` then converts its scaler through the same `_scaler_for_native` path when a TP / PP / native FSDP2 run is active. The resulting scaler unscales DTensor and local gradients together and all reduces `found_inf` over the ranks. It keeps the forced float32 starting scale from unslothai#18208 (2**8, already divided by the data parallel loss multiplier) instead of fp16's 2**16. - `unscale_gradients` reads `accelerator.scaler` at call time so it uses the converted scaler. - Plain DDP is unchanged: gradients are averaged before `unscale_`, so every rank already sees the same inf. ## Tests New `tests/test_forced_float32_parallel_scaler_gloo.py` (CPU gloo, world 2) runs the forced float32 scaler after the TP / PP setup, for TP with DTensor gradients, TP with local gradients, and PP, with no overflow, an overflow on one rank, and an overflow on every rank. | | main | this PR | |---|---|---| | new test | 5 passed, 4 failed | 9 passed | On main, the 3 TP DTensor cases fail with the mixed Tensor / DTensor error. The TP local-gradients case with an overflow on one rank fails because the ranks disagree on the step count. PP already agreed through its stage-level `found_inf` reduction, and it still passes. The related scaler suites (TP / PP / FSDP2 scaler, forced float32 scaler, trainer scaler attach, PP env) give the same result before and after: 44 passed, 32 skipped. The same 5 `test_pp_env_gloo` cases fail on both, because the CPU test env has no `vllm.sampling_params`. ## Kaggle 2x T4 These are fp16 runs on forced float32 models, with main at 1422db4 as the base and the same pin with this PR's three files laid over it as the head. | Model, mode | main | this PR | |---|---|---| | Qwen3.6-35B-A3B architecture (random weights, 4 of 40 layers), TP=2 | crashes in the first clip with the mixed Tensor / DTensor error above | 3 steps, grad norm 0.255 / 0.257 / 0.286 | | Gemma-4-E2B 4-bit, TP=2, 25 steps | | every step finite; tracks 1 GPU within max abs loss diff 0.038 (0.5% relative), final loss 2.900 vs 2.912 | Gemma-4-E2B under TP has no DTensor and local gradient mix, so main does not crash there. ## Not covered - Gemma-4-E2B under PP still has a non-finite step 1 in fp16 (it matches 1 GPU from about step 3 and by step 25); the lead is the Gemma-4 float16 attention path, tracked separately. - FSDP2 with a forced float32 model takes the new path but has no GPU run. - The Kaggle runs used the scaler start before unslothai#18208 (2**12); the gloo test covers this PR on top of unslothai#18208.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
When Unsloth forces float32 (Gemma-4, Gemma-3 and the other
FORCE_FLOAT32families, on a GPU without bfloat16 or on a float16 request), training diverges once the loss starts to fall. Gemma-4 E2B goes from 2.5 to 9.5 over 60 steps on a T4, and the same thing happens on a G4 (RTX PRO 6000 Blackwell), so this is not a T4-only kernel issue.Root cause
Forced float32 sets the accelerator's mixed precision to
no, so noGradScaleris created. The frozen weights and the sub-layer activations are still float16, so their backward runs in float16 with nothing scaling the loss. The fused CE (unsloth_fused_ce_loss) also saves d(loss)/d(hidden) as float16 in its forward. Once the loss falls, the per-token gradients drop into float16's subnormal range and many round to zero.With the same LoRA weights, the forced path and a float32 reference give the same forward loss, but the gradients differ: grad norm 1.68 vs 13.8, and the LoRA gradient cosine is -0.89. The update stops following the loss.
Change
unsloth/models/_utils.py: new_unsloth_forced_float32_grad_scaler(trainer, model). It attaches a dynamicGradScaler(no autocast,init_scale = 2**12) totrainer.acceleratoronly when all of these hold:model._unsloth_forced_float32, elseUNSLOTH_FORCE_FLOAT32);noand the accelerator has no scaler yet;GradScaler.unscale_refuses float16 gradients);accelerate only unscales under native float16 AMP, so the helper also replaces
accelerator.unscale_gradientswith one that unscales once per optimizer and step.clip_grad_norm_/clip_grad_value_then clip true gradients, andAcceleratedOptimizer.stepskips its own unscale.unsloth/models/rl.py: the patched TRL trainers (SFT, GRPO, DPO, ...) call the helper right before they handaccelerator.scalerto the model asaccelerator_scaler. The fused CE and the GRPO fused loss already read the scaler from there. This runs at the end of__init__, beforeTrainer.trainprepares the optimizer, so theAcceleratedOptimizerpicks up the same scaler.UNSLOTH_FORCED_FLOAT32_GRAD_SCALER=0turns it off.bfloat16 and float32 runs never get a scaler.
Tests
tests/test_forced_float32_grad_scaler.py(GPU tests, each in a fresh interpreter):GradScaler, keeps mixed precisionno, and hands the scaler to the fused CE. With the kill switch it has none, and the logged grad norms of the two runs agree, which shows the norm is unscaled.Trainer(SGD, lr 1, float16 frozen layers, float32 trainable layer). The prepared optimizer steps through the attached scaler. The applied update matches a float32 no-scaler reference, and clipping happens in unscaled units. An overflowing step is skipped, leaving the weights unchanged and halving the scale.Flip check, fresh
mainvs this branch, each arm importing its own tree: onmainthe scaler test fails (assert None == 'GradScaler') and the optimizer test cannot import the helper. The bfloat16 test passes on both. All three pass on this branch.60 step runs, final loss (main -> this PR)
Gemma-3 1B on a Kaggle T4, 60 steps
unsloth/gemma-3-1b-it, 16-bit LoRA r 16, float16 request (forced float32), batch 2 x grad accumulation 4, sequence length 512, wikitext-2, AdamW, lr 2e-4, seed 3407. main and this PR ran side by side on the two T4s of one kernel, with the same data and seed.Gemma-3 does not blow up on
mainthe way Gemma-4 does, but it trains worse. This PR's loss is at or below main's at every one of the 60 steps, and the gap widens as the loss falls.Optimizer path (one SGD step, lr 1)
The clipped update norm is exactly 1e-3, i.e. clipping saw unscaled gradients. Clipping scaled gradients would have given 1e-3 / 4096.
GRPO (tiny Gemma-3,
UnslothGRPOTrainer, 3 steps, no vLLM)UNSLOTH_FORCED_FLOAT32_GRAD_SCALER=0All gradients are finite. Rewards are identical with and without the scaler. At steps 1 and 2 every run, bfloat16 and float32 included, has exactly zero gradient on half the LoRA elements, so that part comes from the LoRA init and not from underflow.