Skip to content

Forced float32: give float16 weights a GradScaler (Gemma-4 on T4 diverges) - #18065

Merged
danielhanchen merged 2 commits into
mainfrom
forced-fp16-grad-scaler
Nov 17, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
forced-fp16-grad-scaler

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

When Unsloth forces float32 (Gemma-4, Gemma-3 and the other FORCE_FLOAT32 families, 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 no GradScaler is 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 dynamic GradScaler (no autocast, init_scale = 2**12) to trainer.accelerator only when all of these hold:

    • the model took the forced float32 path (model._unsloth_forced_float32, else UNSLOTH_FORCE_FLOAT32);
    • mixed precision is no and the accelerator has no scaler yet;
    • the frozen parameters include float16 ones and every trainable parameter is float32 (GradScaler.unscale_ refuses float16 gradients);
    • the run is single process or DDP on CUDA / XPU. DeepSpeed, FSDP and XLA keep their own loss scaling.

    accelerate only unscales under native float16 AMP, so the helper also replaces accelerator.unscale_gradients with one that unscales once per optimizer and step. clip_grad_norm_ / clip_grad_value_ then clip true gradients, and AcceleratedOptimizer.step skips its own unscale.

  • unsloth/models/rl.py: the patched TRL trainers (SFT, GRPO, DPO, ...) call the helper right before they hand accelerator.scaler to the model as accelerator_scaler. The fused CE and the GRPO fused loss already read the scaler from there. This runs at the end of __init__, before Trainer.train prepares the optimizer, so the AcceleratedOptimizer picks up the same scaler.

  • UNSLOTH_FORCED_FLOAT32_GRAD_SCALER=0 turns 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):

  • A forced float32 float16 Gemma-4 SFT run gets a GradScaler, keeps mixed precision no, 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.
  • A bfloat16 run gets no scaler.
  • Optimizer path through a real 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 main vs this branch, each arm importing its own tree: on main the 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)

GPU model main this PR reference
T4 Gemma-4 E2B 4-bit 9.96 2.507 TRL float16 AMP 2.513
T4 Gemma-4 E4B 4-bit 11.18 2.277
T4 Gemma-4 E2B 16-bit 9.56 2.491 TRL float32 2.505
G4 Gemma-4 E2B 16-bit 9.37 2.492 kill switch 9.52, bfloat16 2.501

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.

main this PR
GradScaler none yes, scale 4096 throughout, no skipped steps
step 1 / 2 loss 4.1311 / 3.8782 4.1311 / 3.8782
step 10 / 20 / 30 / 40 / 50 loss 3.122 / 3.260 / 3.069 / 3.123 / 3.211 3.090 / 3.153 / 2.898 / 2.935 / 2.979
final loss (step 60) 3.221 2.984
mean of the last 10 steps 3.147 2.907
peak allocated 2.61 GiB 2.61 GiB

Gemma-3 does not blow up on main the 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)

case this PR vs float32 reference kill switch vs float32 reference
clipped step (max_grad_norm 1e-3), relative update error 6.1e-4 6.1e-4
clipped step, logged grad norm 0.74624 (ref 0.74630) 0.74624
small loss (x 2^-14), relative update error 2.9e-3 9.6e-2
overflow step (scale 2^40) skipped, update exactly 0, scale 2^39 n/a

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)

run scaler step 1 loss grad norm step 1 / 2 / 3 exactly-zero LoRA grad elements, step 3
float16 request (forced float32), this PR GradScaler (4096) 0.0 0.574670 / 0.395856 / 0.424687 0.0%
same, UNSLOTH_FORCED_FLOAT32_GRAD_SCALER=0 none 0.0 0.574683 / 0.395916 / 0.424732 2.3%
bfloat16 none 0.0 0.574303 / 0.394957 / 0.425466 0.0%
float32 none 0.0 0.616118 / 0.395893 / 0.424991 0.0%

All 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.

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T03:07:45.138047Z a9ab6f3 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. More of your lovely PRs please.

Reviewed commit: a9ab6f3cfa

ℹ️ 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 3384411 into main Nov 17, 2026
@danielhanchen
danielhanchen deleted the forced-fp16-grad-scaler branch November 17, 2026 03:47
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.
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