Skip to content

Forced float32 GradScaler: start at 2**8, divided by the data parallel loss multiplier - #18208

Merged
danielhanchen merged 2 commits into
mainfrom
fp16-parity-init-scale
Nov 17, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
fp16-parity-init-scale

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Forced float32 GradScaler: start at 2**8, divided by the data parallel loss multiplier

The forced float32 path (float16 weights on T4 with float32 compute) uses a dynamic GradScaler started at 2**12. Every skipped step also holds the LR schedule back, so overflowing in the first steps makes the float16 run lag the bf16 loss curve.

  • Start at 28:** after the Gemma-4 post-norm fix in Gemma-4 forced float32: the post-norms that feed the residual return float32 unsloth-zoo#2580, the largest float16 gradient on Gemma-4 12B is at the attention keys, 9 to 74 times the loss scale, so 12B needs a scale of 2**8 to avoid first-step overflow.
  • Divide by the number of processes on multiple GPUs: each rank's loss is multiplied by it, so its gradients are that many times larger, as native FSDP2 already accounts for.
  • Override: UNSLOTH_FORCED_FLOAT32_INIT_SCALE.

Cost

  • Underflow: on E2B at steps 30 and 60 on a T4, LoRA gradients at 28 are within 8% (cosine 0.9965) of the ones at 212, about the spread between two bf16 runs; at 2**10 the difference is 2.4%. The loss curves stay in the bf16 band.
  • gpt-oss-20b: the gradient at 28 differs from one taken at 216 by 0.16% (B200).
  • Speed: with base and this change swapped across the two T4s of one Kaggle kernel, this change was 0.4 to 1.8% faster at 60 steps and 0.7 to 1.1% at 100 steps. Peak memory is unchanged.

Results with the zoo fix, 100 steps on a Kaggle T4, bf16 band = Colab L4 runs on the same batches

model skipped steps, main skipped steps, now mean of last 10 steps (now vs bf16)
Gemma-4 E2B 4-bit, 2 runs each 0, 0 0, 0 2.5890 / 2.5856 vs 2.5840 to 2.5858
Gemma-4 12B 4-bit 6 (steps 1, 2, 3, 5, 6, 13), scale ended at 64 0 2.3269 vs 2.3257 / 2.3320
gpt-oss-20b bnb-4bit 0 0 5.7605 vs 5.7610

No NaN or inf in any run. gpt-oss stays within 0.003 of the bf16 band at steps 10 to 100 on main and here: on the bnb-4bit path the MoE output and the residual (up to about 99,500 by step 70, past float16's 65,504) are already float32.

Tests

  • tests/test_forced_float32_grad_scaler.py: new cases for the 2**8 start, the per-process division and the override.
  • The scaler GPU tests pass on B200 (4).

Not covered

  • One of three 12B runs (60 steps) still skipped one step.
  • Tensor and context parallel, sequences longer than 1024, runs past 2000 steps (the scaler's first growth attempt could skip one step).
  • FSDP2 on this path gets a plain GradScaler, so ranks do not agree on overflow; pre-existing, unchanged.

…l loss multiplier

The forced float32 path (Gemma-4 / Gemma-3 on a float16-only GPU) attached a GradScaler at 2**12.
Every overflow skips an optimizer step and, since zoo #2553, holds the LR schedule back, so the run
falls behind a bfloat16 run. On a Kaggle T4, Gemma-4 12B 4-bit skipped steps 2, 9 and 27 at
2**12 -> 2**10 even with the float32 post-norms in unsloth_zoo, and data parallel ranks carry the
loss times the number of processes, so DDP / FSDP2 / PP E2B runs overflowed at step 1 or 2.

Start at 2**8 and divide by the ranks the loss is multiplied by (the rule native FSDP2 already
uses for its own scaler). Growth stays on. UNSLOTH_FORCED_FLOAT32_INIT_SCALE overrides.
@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-17T19:43:15.307707Z e2aaf09 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. Swish!

Reviewed commit: e2aaf094a0

ℹ️ 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 6cd6f79 into main Nov 17, 2026
@danielhanchen
danielhanchen deleted the fp16-parity-init-scale branch November 17, 2026 21:12
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