Skip to content

Native FSDP2 fp16 scaler: agree on overflow over ranks without an explicit unscale_, and give fused optimizers one 0 / 1 flag over all devices - #15416

Merged
danielhanchen merged 6 commits into
mainfrom
dh/s7-rc-fsdp2_scaler_sync
Oct 27, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
dh/s7-rc-fsdp2_scaler_sync

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

For float16, native FSDP2 (and tensor parallel through _tp_scaler) swaps the Trainer's GradScaler for _ShardedGradScaler (_scaler_for_native in unsloth/models/fsdp2_native.py). Its unscale_ all-reduces the overflow flags over ranks and clamps each device's flag to 0 / 1. Two paths still go wrong with fused optimizers (adamw_torch_fused):

  1. No explicit unscale_ (no gradient clipping, max_grad_norm = 0). For an optimizer with _step_supports_amp_scaling (fused Adam / AdamW), torch.amp.GradScaler.step() does not call unscale_. It calls _check_inf_per_device while the stage is still READY (torch/amp/grad_scaler.py, step, v2.13.0 lines 444-445), and ShardedGradScaler only all-reduces inside unscale_ (torch/distributed/fsdp/sharded_grad_scaler.py lines 235-283). On 2 gloo ranks with an inf on rank 1 only, rank 1 skips the step and backs its scale off to 27, while rank 0 steps and keeps 28. The ranks drift apart from then on.
  2. One fused optimizer over parameters on two devices, for example cpu_offload shards next to replicated ignored_params, which replicate_minority_dtype (default True) keeps on the GPU. GradScaler keeps one found_inf per device, and for a fused optimizer step() passes their SUM as optimizer.found_inf (grad_scaler.py lines 449-464). The fused kernels skip only when found_inf == 1 (fused_adam_utils.cuh line 197 for CUDA, FusedAdam.cpp line 39 for CPU) and subtract it from the step counts. With both devices overflowing the sum is 2, so the step writes non-finite weights and the counts go to -1. Stock torch.amp.GradScaler does the same thing on this host (steps -1 / -1, weights non-finite), so this is inherited from PyTorch, not added by Native FSDP2 float16: fix fused AdamW crashing at the first step #14663. The scaler Unsloth installs is where it can be fixed for Unsloth runs.

Fix

  • _ShardedGradScaler._check_inf_per_device runs the stock check, then all-reduces the flags over the scaler's process group the same way ShardedGradScaler.unscale_ does (a CPU flag goes through the scaler device).
  • After either path, _one_flag replaces the per-device flags with one 0 / 1 total on the first device and zeros on the others. Every consumer (fused step, _maybe_opt_step, update) sums the flags, so the sum is now exactly 0 or 1.
  • For a single-device optimizer with explicit unscale_, the flags are the same as before: the old per-device clamp, 0-dim.

Before / after

torch 2.13.0. Base = origin/main 0ea0473, head = this branch.

Test Base Head
test_fsdp2_native_scaler_fused_gloo.py::test_overflow_skips_on_every_rank_without_explicit_unscale[one_rank_inf] (2 gloo ranks) FAIL: rank 0 took 3 steps PASS: 2 steps and scale 2**7 on both ranks, fused equals foreach
...::test_overflow_skips_on_every_rank_without_explicit_unscale[every_rank_inf] PASS PASS
test_fsdp2_native_scaler_mixed_device.py::test_mixed_device_fused_adamw_skips_an_overflow_step[both-clipping] (B200 + CPU, one fused AdamW) FAIL: the overflow step changed the weights PASS
...[both-no_clipping] FAIL: the overflow step changed the weights PASS
...[cpu-*], ...[cuda-*] (one device overflows) PASS PASS
Existing test_fsdp2_native_scaler_fused_gloo.py tests (4) PASS PASS
fp16 scale mesh / parity / accelerator loop / pp scaler gloo tests (-k "scale or scaler or fp16") not run 8 passed

test_fsdp2_native_scaler_fused_gloo.py also passes on torch 2.14.1.

Not covered

  • No integrated Trainer run with cpu_offload plus a replicated trainable parameter. The mixed-device test drives the installed scaler and a real fused AdamW directly.
  • No multi-GPU NCCL run of the no-unscale path; it was run on CPU gloo.
  • bitsandbytes optimizers do not set _step_supports_amp_scaling and are unaffected.

…licit unscale_, and give fused optimizers one 0 / 1 flag over all devices
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-26T21:00:55.059994Z 079d308 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. You're on a roll.

Reviewed commit: ef309157ea

ℹ️ 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

Copy link
Copy Markdown
Member Author

Added a TP Trainer test for the same defect (tests/test_tp_native_scaler_fused_gloo.py). With a tiny Qwen3 LoRA model through apply_tensor_parallel (gloo, tp 2), fused AdamW, no clipping, and an inf in one rank's lora_B shard, main lets the ranks diverge (rank 0 steps, rank 1 skips) because DTensor's found_inf reduction only looks at the first grad's placements, which is the replicated lora_A. This PR's shared scaler keeps both ranks at the same skipped step and scale. [fused-no_clipping] fails with main's fsdp2_native.py and passes here; the other three cells pass on both. Both scaler test files pass on torch 2.6, 2.10, 2.13 and 2.14.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 69f1ad109d

ℹ️ 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

Copy link
Copy Markdown
Member Author

Follow-up fix for mixed CPU + CUDA fused AdamW (cpu_offload shards beside CUDA ones). GradScaler's replicator and the fused optimizer move found_inf / grad_scale to each parameter device with non_blocking=True; for CPU parameters the CPU kernel could read those host tensors before the device-to-host copy landed, so an overflow step was sometimes taken (or unscaled by a stale scale). The previous head passed tests/test_fsdp2_native_scaler_mixed_device.py in only 17 of 30 runs.

The scaler now hands the CPU side blocking host copies: _unscale_grads_ unscales CPU grads with host inv_scale / found_inf, and step gives a fused optimizer that steps CPU parameters host copies of grad_scale / found_inf. Pure CUDA and pure CPU optimizers take the unchanged path.

New deterministic test test_late_device_to_host_copies_keep_the_step_right keeps the CUDA stream busy so a late copy shows up every time: 2 of its cells fail on the previous head in 3 of 3 runs, and all 14 tests in the file pass in 3 of 3 runs here. The CPU gloo scaler tests (test_fsdp2_native_scaler_fused_gloo.py, test_tp_native_scaler_fused_gloo.py) still pass, 10 of 10.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 079d308af3

ℹ️ 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".

[skip ci]
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