Skip to content

Native FSDP2 float16: fix fused AdamW crashing at the first step - #14663

Merged
danielhanchen merged 3 commits into
mainfrom
dh/s3-w22-fp16-fused-scaler
Oct 22, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
dh/s3-w22-fp16-fused-scaler

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

  • Native FSDP2 in float16 swaps the Trainer's GradScaler for torch's ShardedGradScaler, so the inf check agrees
    across ranks. It also swaps adamw_8bit for adamw_torch_fused.
  • With gradient clipping, ShardedGradScaler.unscale_ hands the fused optimizer a found_inf of shape [1]. The
    fused optimizer subtracts that in place from its 0-dim step counts, and the first optimizer step fails with
    output with shape [] doesn't match the broadcast shape [1]. That covers every float16 run (T4, V100) with the
    default optimizer, for SFT, GRPO and the other trainers.
  • The swapped scaler now keeps found_inf 0-dim, as GradScaler does. It also keeps the old scaler's device instead
    of defaulting to cuda.

Tests

  • tests/test_fsdp2_native_scaler_fused_gloo.py, 2 gloo CPU ranks: fused and foreach AdamW step through the
    swapped scaler, an inf on one rank skips the step on both ranks, and the scale backs off once.
    • Before: 2 failed.
    • After: 2 passed on torch 2.10, 2.13 and 2.14.
  • GRPO without vLLM, 2 ranks, float16:
    • Before: failed at step 1, on T4 x2 and on a local GPU.
    • After: trains, on T4 x2 for GRPO and for SFT with the default optimizer. Runs with a non-fused optimizer are
      unchanged (equal losses and grad norms).

…o fused optimizers can step

ShardedGradScaler.unscale_ builds found_inf with shape [1]. Fused optimizers
subtract it in place from their 0-dim step counts, so with gradient clipping
(unscale_ before step) the first optimizer step failed with "output with shape []
doesn't match the broadcast shape [1]". Native FSDP2 swaps adamw_8bit for
adamw_torch_fused, so every float16 run with the default optimizer hit it
(T4 GRPO and SFT). The swapped scaler also keeps the old scaler's device instead
of defaulting to cuda.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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-22T12:06:22.737242Z f5ddc91 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 chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f5ade30a35

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

Comment on lines +2474 to +2475
kwargs.setdefault("device", getattr(scaler, "_device", "cuda"))
accelerator.scaler = _ShardedGradScaler(**kwargs)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Guard the device kwarg for older PyTorch releases

On supported PyTorch 2.6 installations, ShardedGradScaler.__init__ does not accept a device keyword, so every native-FSDP2 fp16 Trainer now raises TypeError: unexpected keyword argument 'device' during post-initialization before training begins. Only pass this keyword when the installed constructor supports it, or preserve the device through a version-compatible path.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ShardedGradScaler.__init__ takes device: str = "cuda" on torch 2.6.0 (torch/distributed/fsdp/sharded_grad_scaler.py:93 at v2.6.0), and the same on 2.10 through 2.14, so passing device is supported across the range we install. No change needed here.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f5ade30a35

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

# from their 0-dim step counts, which fails. Keep it 0-dim as GradScaler does.
def unscale_(self, optimizer):
super().unscale_(optimizer)
state = self._per_optimizer_states[id(optimizer)]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the disabled-scaler early return

When GradScalerKwargs(enabled=False) is used with native-FSDP2 fp16, the replacement scaler is also disabled; in that state super().unscale_() returns immediately and PyTorch never initializes _per_optimizer_states, so this access raises AttributeError as soon as Accelerate performs gradient clipping. Return immediately when the scaler is disabled before accessing its optimizer state.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: f5ddc91105

ℹ️ 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 630bdfa into main Oct 22, 2026
@danielhanchen
danielhanchen deleted the dh/s3-w22-fp16-fused-scaler branch October 22, 2026 12:53
danielhanchen added a commit that referenced this pull request Oct 27, 2026
…licit unscale_, and give fused optimizers one 0 / 1 flag over all devices (#15416)

## 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 2**7, while rank 0 steps and keeps 2**8. 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 #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.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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