Skip to content

Native FSDP2: clip gradients through Unsloth's clip, not the mixed mesh path - #15708

Merged
danielhanchen merged 3 commits into
mainfrom
dh/moe-fsdp2-grad
Oct 28, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
dh/moe-fsdp2-grad

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Native FSDP2 full finetuning reported a different gradient norm than one GPU, and clipped with it. The cause is not the sharding: the Trainer never reached Unsloth's FSDP2 clip.

transformers 5.x added Trainer._mixed_mesh_grad_norm for expert parallelism. Trainer._clip_grad_norm sends a model there whenever its gradients mix DTensor and plain tensors. Native FSDP2 keeps small trainable parameters (norm weights, float32 next to bfloat16 weights) replicated beside the sharded ones, so every full finetune took that path. As a result:

  • Accelerator.clip_grad_norm_, which fsdp2_native patches to native_clip_grad_norm_ (and which unscales fp16 gradients first), was never called.
  • The per-tensor bfloat16 norms were stacked, combined, squared and all-reduced in bfloat16. The total is therefore quantised to the bfloat16 step of the squared norm (about 2.5e-3 relative near 3.5), whatever the gradients are.

This PR makes Trainer._has_mixed_mesh_grads return False for native FSDP2 models, so clipping goes through the accelerator path, which already handles DTensor and plain gradients together. Other models and older transformers (no such method) are unchanged.

Evidence

Tiny Qwen3-MoE (2 layers), full finetune, bf16, Colab L4, torch 2.14.1, transformers 5.17.0. FSDP2 is forced on a 1-rank mesh, so every FSDP2 hook runs and nothing is reduced. The step 0 gradients are dumped before the clip.

arm step 0 grad norm fp64 norm of the same gradients
1 GPU 3.5611942 3.5588821
FSDP2, main 3.5623298 (same gradients, bitwise)
FSDP2, this PR 3.5611942 3.5588821
  • On main, the step 0 gradients before the clip are bitwise equal to one GPU's. Only the norm differs, and replaying _mixed_mesh_grad_norm on the one-GPU per-tensor norms reproduces 3.5623298 exactly.
  • On main the FSDP2 norm is 3.5623298 for the grouped_mm, unsloth_triton and native_torch MoE backends, and for GA 1 and GA 2, even though their fp64 norms differ (3.55888, 3.55850, 3.55777). That is the bfloat16 quantisation.
  • With this PR, the gradients before and after the clip are bitwise equal to one GPU (grouped_mm, GA 2 and GA 1), and so are the step 0 and step 1 norms.
  • Dense Qwen3 full finetune had the same problem (3.579895 vs 3.5804551). With this PR it matches one GPU bitwise at step 0.

Tests

tests/test_fsdp2_native_trainer_fsdp_clip_gloo.py::test_trainer_clip_with_replicated_and_sharded_grads_uses_native_clip (2-rank gloo CPU): bfloat16 sharded weights plus a replicated float32 parameter, through Trainer._clip_grad_norm.

  • main: fails. It returns 673.135 from the mixed mesh path, where native_clip_grad_norm_ gives 671.257.
  • this PR: passes.
  • It is skipped on transformers 4.57.6, which has no mixed mesh path.
  • The rest of the file plus the clip dtype, clip fast path, trainer args and GA sync gloo suites: 24 passed.

Newer transformers route a model whose gradients mix DTensor and plain tensors to
Trainer._mixed_mesh_grad_norm (written for expert parallelism). Native FSDP2 keeps small
parameters such as norms replicated next to sharded weights, so every full finetune took
that path: Unsloth's patched accelerator clip (and its fp16 unscale) was skipped, and the
bfloat16 per-tensor norms were combined in bfloat16. On Qwen3-MoE at world size 1 the step 0
grad norm read 3.5623 against 3.5612 on one GPU (fp64 3.5589) and stayed at that bfloat16
step whatever the gradients. Report False from _has_mixed_mesh_grads for native FSDP2 models
so the accelerator path, which already handles both kinds, clips them.
@danielhanchen danielhanchen self-assigned this Oct 28, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 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-28T07:26:57.937667Z f056c7f 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: f056c7fb8d

ℹ️ 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 d546b0c into main Oct 28, 2026
@danielhanchen
danielhanchen deleted the dh/moe-fsdp2-grad branch October 28, 2026 09:36
danielhanchen added a commit that referenced this pull request Oct 28, 2026
`Repo tests (CPU, fsdp2)` on #15833's staging run passed every test and
still went red:

```
364 passed, 28 skipped, 80 warnings in 2092.29s (0:34:52)
##[error]Process completed with exit code 124.
```

The shard's pytest step runs under `timeout --signal=INT --kill-after=60
2100`. pytest finished 8 s under that cap, and the cap then fired while
it was exiting.

## Cause

#15291 moved the FSDP2 gloo tests into their own shard at about ten
minutes of runner time. They have grown since, with most of a dozen
FSDP2 PRs merged today adding tests there (#15756, #15748, #15720,
#15709, #15708, #15352, ...). Over the last twenty-odd staging runs this
job took 21 to 38 minutes, so it now sits at its cap on an ordinary
runner. Nothing failed; the shard is simply too big for its timeout.

## Fix

Split the shard in two by file name, balanced on measured time. Per-test
durations on main, summed per file across all 76 files:

| shard | selection | files | tests | measured time |
|---|---|---|---|---|
| `fsdp2` | `tests/test_fsdp2_[!n]*.py tests/test_fsdp2_n[!a]*.py
tests/test_fsdp2_native_[abc]*.py` | 34 | 237 | 1156 s (45%) |
| `fsdp2-native` (new) | `tests/test_fsdp2_native_[!abc]*.py` | 42 | 276
| 1406 s (55%) |
| both together, unchanged total | `tests/test_fsdp2*.py` | 76 | 513 |
2562 s |

`fsdp2` keeps its name, so its check name is unchanged. The step timeout
and job cap are left alone, so each half gets the whole budget.

## Guards

- `tests/test_ci_repo_cpu_shards.py` already fails when a file lands in
no shard or in two. It caught my first draft, which dropped
`test_fsdp2_non_cuda_accelerate_route.py`; hence the `n[!a]` glob.
- A new check, `TestEveryGlobRootMatchesAFile`, fails if a shard glob
matches no test file. bash passes an unmatched glob through literally
and pytest then fails the whole shard on a missing path. Sabotage:
adding `tests/test_fsdp2_zz*.py` to a selection fails it with
`[('fsdp2', 'tests/test_fsdp2_zz*.py')]`.
- `tests/studio/test_backend_ci_parallel_isolation.py` pins the number
of parallel runs, now nine (six repo-root shards).

## Verification

- `tests/test_ci_repo_cpu_shards.py` and
`tests/studio/test_backend_ci_parallel_isolation.py`: 56 passed.
- With `tests/studio/test_cache_budget_discipline.py` added: everything
passes except the guard on my first draft, fixed above.
- `--collect-only` on the two selections gives 237 + 276 = 513, the same
as the old single glob.

The per-file times are from a local `-n 8` run, so the split ratio is
approximate. The first runs of the two new shards will show the actual
runner times.
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