Repository navigation
Native FSDP2 float16: fix fused AdamW crashing at the first step - #14663
Conversation
…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.
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| kwargs.setdefault("device", getattr(scaler, "_device", "cuda")) | ||
| accelerator.scaler = _ShardedGradScaler(**kwargs) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
There was a problem hiding this comment.
💡 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)] |
There was a problem hiding this comment.
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 👍 / 👎.
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…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>
Summary
ShardedGradScaler, so the inf check agreesacross ranks. It also swaps
adamw_8bitforadamw_torch_fused.ShardedGradScaler.unscale_hands the fused optimizer a found_inf of shape [1]. Thefused 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 thedefault optimizer, for SFT, GRPO and the other trainers.
of defaulting to cuda.
Tests
tests/test_fsdp2_native_scaler_fused_gloo.py, 2 gloo CPU ranks: fused and foreach AdamW step through theswapped scaler, an inf on one rank skips the step on both ranks, and the scale backs off once.
unchanged (equal losses and grad norms).