Skip to content

Native FSDP2 float16: sync the fused optimizer's inf check when nothing unscaled the gradients - #15245

Closed
lonexreb wants to merge 2 commits into
unslothai:mainfrom
lonexreb:fix/fsdp2-native-scaler-sync-found-inf-without-unscale
Closed

lonexreb wants to merge 2 commits into
unslothai:mainfrom
lonexreb:fix/fsdp2-native-scaler-sync-found-inf-without-unscale

Conversation

@lonexreb

Copy link
Copy Markdown
Contributor

What

Native FSDP2 (UNSLOTH_FSDP2=1) in float16 swaps the Trainer's GradScaler for the _ShardedGradScaler in unsloth/models/fsdp2_native.py (_scaler_for_native), whose unscale_ all-reduces found_inf so every rank agrees on whether to skip the step (#14996). That sync lives only in unscale_. With TrainingArguments(max_grad_norm = 0) the Trainer never calls accelerator.clip_grad_norm_, so unscale_ never runs and scaler.step(opt) reaches a fused optimizer (adamw_torch_fused, which is also what the bnb Adam names map to under the CPU-shard fallback) with the state still READY. torch's GradScaler.step then runs _check_inf_per_device itself and hands the fused kernel that rank's own, unsynced flag.

Result: when one rank overflows, it skips the step and the others take it. From then on the ranks scale their losses by different factors while FSDP2 keeps reduce-scattering their gradients. No error, just drift.

How

Override _check_inf_per_device on the native scaler: run torch's check, all-reduce each found_inf over the scaler's process group (moving a CPU flag to the scaler device first, as ShardedGradScaler.unscale_ does), then clamp it to 0 / 1 and make it 0-dim through the same helper unscale_ already uses (the sum over ranks is a count; the fused kernel skips only on 1). The clipped path is untouched: unscale_ still syncs and clamps as before, now via the shared _clamp_found_inf.

Verification

tests/test_fsdp2_native_scaler_fused_gloo.py (2-rank gloo, CPU) gains a clip axis: no_clip skips unscale_ + clip_grad_norm_ and goes straight to step(), the Trainer's max_grad_norm = 0 sequence.

case main (2faad9f) this branch
fused, one rank overflows, clipped both ranks step 2 of 3 same
fused, one rank overflows, no clip rank 0 steps 3, rank 1 steps 2 (desync) both ranks step 2 of 3, scale 2^7
foreach, no clip both step 2 (torch's non-fused step calls unscale_ itself) same
every rank overflows, either both skip same

Whole file: 6 passed on the branch, 1 failed / 5 passed on main (the row above). tests/test_fsdp2_native_fp16_scale_parity_gloo.py is unchanged by this (same 2 passed, same one macOS-only torch.mps.is_initialized failure on main's file and this one). ruff check, enforce_kwargs_spacing.py and the ruff-format-with-kwargs hook pass; the file parses under Python 3.9. No multi-GPU box here, so the NCCL path (CUDA found_inf, no device move) ran only in CI.

🤖 Generated with Claude Code

…ng unscaled the gradients

With max_grad_norm = 0 the Trainer never calls accelerator.clip_grad_norm_, so the scaler's unscale_ never runs and GradScaler.step reaches a fused optimizer with the state still READY. It then runs _check_inf_per_device itself, and ShardedGradScaler all-reduces found_inf only inside unscale_: each rank gets its own overflow flag, one rank steps while another skips, and from then on the ranks scale their losses differently while FSDP2 reduce-scatters their gradients. Override _check_inf_per_device on the native scaler to all-reduce (and clamp to 0 / 1, as unscale_ already does) before the fused kernel reads it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
danielhanchen added a commit that referenced this pull request Oct 25, 2026
…kwargs (#15267)

`tests/test_grpo_truncated_support_policy_gate.py` fails 6 of 9 on main
since #14185 (`NameError: name 'os' is not defined` raised from
`rl_replacements.py:2`). It shows on the rest shard of every PR based
after that merge, for example #15245.

## Cause

The test, not the product. It lifts the truncated-support binding block
out of `_get_per_token_logps_and_entropies` and runs it on a stub
trainer. To find the block it took the first `try` in the body whose
source mentions `grpo_truncated_support_kwargs`. #14185 added an earlier
`try` in the same body that imports that name too (the
`UNSLOTH_GRPO_LOGPROB_RECOMPUTE` scorer pick). The test then lifted that
block instead, which reads `os.environ` in a namespace without `os`. The
real block is unchanged.

## Fix

- The block now starts at the `try` that assigns `_support_kwargs`.
- Statements are collected while they read or bind `_support_kwargs` as
a name, not while the substring `_support_kwargs` appears (which
`grpo_truncated_support_kwargs` also contains).

## Verification

- The lifted block on main is identical, byte for byte, to what the old
extractor lifted from the source just before #14185. The new extractor
also gives the same block on that older source.
- `tests/test_grpo_truncated_support_policy_gate.py`: 6 failed on main,
9 passed here.
- Sabotage: with `_support_mismatch` forced to `[]` in
`rl_replacements.py` (the gate removed), 6 cases fail, so the test still
guards the product.
danielhanchen added a commit that referenced this pull request Oct 25, 2026
…15269)

16 cases in `tests/test_fused_preference_loss.py` fail in `Repo tests
(CPU, rest)` on PRs based on current main, for example #15224 and
#15245: every `test_orpo_cpo_match_trl` case plus the DDP / FSDP1 / hook
fallback cases. The reference run trips the hidden-states counter
(`assert (1 >= 1) == False`) or the dtype check.

## Cause

The test, not the product. The test builds its reference from `from
trl.experimental.orpo import ORPOTrainer` (and the CPO / DPO
equivalents). Unsloth's RL patch rebinds those names, and the defining
module's attribute, to the generated `UnslothORPOTrainer`
(`unsloth/models/rl.py`, the `trl.{name} = created_module.Unsloth{name}`
lines). Since #14185, that generated class's `concatenated_forward`
routes through `unsloth_fused_orpo_concatenated_forward`. So once TRL
has been patched in the process, the "TRL" side of the comparison is the
code under test. The stack of the reference forward shows it:
`test_fused_preference_loss.py:437 ->
unsloth_compiled_cache/UnslothORPOTrainer.py:1988`.

It reproduces locally with unsloth-zoo main on the path (16 failed, 9
passed, run alone). With the older installed zoo 2026.10.7, TRL is not
rebound here, which is why it looked like an ordering leak at first.

## Fix

- `_trl_trainer(name)` loads TRL's own trainer module from its file
under a private module name in the same package, so TRL's relative
imports still resolve and nothing Unsloth rebinds is reused.
- It asserts that the class it returns is not an `Unsloth*` class.
- ORPO, CPO and DPO all take their reference from it.

## Verification

- `tests/test_fused_preference_loss.py` against unsloth-zoo main: 16
failed, 9 passed on main; 25 passed here.
- Against the installed zoo 2026.10.7: 25 passed on both main and this
PR.
- Sabotage on the product: scaling the fused ORPO path's `chosen_logps`
by 1.001 in `unsloth/models/dpo.py` fails all 10
`test_orpo_cpo_match_trl` cases.
@lonexreb

Copy link
Copy Markdown
Contributor Author

Closing: superseded by 291a4c7 (#15416), which syncs found_inf in _check_inf_per_device the same way and also covers the mixed-device fused case.

@lonexreb lonexreb closed this Oct 27, 2026
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