Repository navigation
Native FSDP2 float16: sync the fused optimizer's inf check when nothing unscaled the gradients - #15245
Closed
lonexreb wants to merge 2 commits into
Closed
Native FSDP2 float16: sync the fused optimizer's inf check when nothing unscaled the gradients#15245lonexreb wants to merge 2 commits into
lonexreb wants to merge 2 commits into
Conversation
…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]>
This was referenced Oct 25, 2026
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.
…er-sync-found-inf-without-unscale
Contributor
Author
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.
What
Native FSDP2 (
UNSLOTH_FSDP2=1) in float16 swaps the Trainer's GradScaler for the_ShardedGradScalerinunsloth/models/fsdp2_native.py(_scaler_for_native), whoseunscale_all-reducesfound_infso every rank agrees on whether to skip the step (#14996). That sync lives only inunscale_. WithTrainingArguments(max_grad_norm = 0)the Trainer never callsaccelerator.clip_grad_norm_, sounscale_never runs andscaler.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 stillREADY. torch'sGradScaler.stepthen runs_check_inf_per_deviceitself 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_deviceon the native scaler: run torch's check, all-reduce eachfound_infover the scaler's process group (moving a CPU flag to the scaler device first, asShardedGradScaler.unscale_does), then clamp it to 0 / 1 and make it 0-dim through the same helperunscale_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 aclipaxis:no_clipskipsunscale_+clip_grad_norm_and goes straight tostep(), the Trainer'smax_grad_norm = 0sequence.stepcallsunscale_itself)Whole file: 6 passed on the branch, 1 failed / 5 passed on main (the row above).
tests/test_fsdp2_native_fp16_scale_parity_gloo.pyis unchanged by this (same 2 passed, same one macOS-onlytorch.mps.is_initializedfailure on main's file and this one).ruff check,enforce_kwargs_spacing.pyand theruff-format-with-kwargshook pass; the file parses under Python 3.9. No multi-GPU box here, so the NCCL path (CUDAfound_inf, no device move) ran only in CI.🤖 Generated with Claude Code