Skip to content

[FSDP2] Support non-uniform grad_dtype within a parameter group - #194546

Draft
weifengpy wants to merge 2 commits into
gh/weifengpy/174/headfrom
gh/weifengpy/175/head
Draft

weifengpy wants to merge 2 commits into
gh/weifengpy/174/headfrom
gh/weifengpy/175/head

Conversation

@weifengpy

@weifengpy weifengpy commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on the previous PR, which warns and ignores grad_dtype when a group's
parameters do not agree on it. This supports the configuration instead and
drops that fallback.

The obstacle is the copy-in, not the cast on the way out. Gradients are
produced at grad_dtype, so a non-uniform group produces a mixture, and
_chunk_cat packs them into one flat buffer and rejects mixed input dtypes.
Bring them to the dtype the reduce runs in anyway before the copy-in; only a
group that actually is non-uniform pays for that. After the reduce, each
parameter's slice is cast to its own grad_dtype rather than the whole buffer
being cast once.

The pre-existing runtime check on uniform gradient dtype stays for the case it
was written for -- fp8 weights not producing the correct higher precision
gradients -- and now fires only when the mixture is not explained by
grad_dtype.

Test Plan:

python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q
# 16 passed in 87.70s

The new test fails against the previous PR's source (git stash push -- torch/):

1 failed, 15 deselected

test_grad_dtype_non_uniform replaces test_grad_dtype_non_uniform_warns_and_is_ignored
from the previous PR; the diff between them is the behavior change.

Authored with assistance from Claude Code (Anthropic).

@pytorch-bot

pytorch-bot Bot commented Aug 23, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/194546

Note: Links to docs will display an error until the docs builds have been completed.

✅ You can merge normally! (1 Unrelated Failure)

As of commit 3147430 with merge base 10583bc (image):

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (fsdp) release notes category labels Aug 23, 2026
@weifengpy
weifengpy force-pushed the gh/weifengpy/174/head branch from 6d0ca81 to 823a593 Compare August 23, 2026 21:46
@weifengpy
weifengpy force-pushed the gh/weifengpy/175/head branch from f3bbf40 to 0febed0 Compare August 23, 2026 21:46
@weifengpy
weifengpy force-pushed the gh/weifengpy/174/head branch from 823a593 to 41ddee0 Compare August 23, 2026 21:47
@weifengpy
weifengpy force-pushed the gh/weifengpy/175/head branch 2 times, most recently from 10ced2b to 1e05058 Compare August 23, 2026 22:32
@weifengpy
weifengpy force-pushed the gh/weifengpy/174/head branch from 41ddee0 to a214515 Compare August 23, 2026 22:32
@weifengpy
weifengpy force-pushed the gh/weifengpy/175/head branch from 1e05058 to dc90882 Compare August 24, 2026 06:16
@weifengpy
weifengpy force-pushed the gh/weifengpy/174/head branch from a214515 to 80bbeeb Compare August 24, 2026 06:27
@weifengpy
weifengpy force-pushed the gh/weifengpy/175/head branch from dc90882 to 7a0eb69 Compare August 24, 2026 06:27
weifengpy added a commit that referenced this pull request Aug 24, 2026
Stacked on #194434. With HSDP and set_requires_all_reduce(False), the
reduce-scatter still runs every microbatch and the partial sums are held in
partial_reduce_output across backward calls until the deferred all-reduce.
That buffer is allocated at reduce_dtype, so each microbatch's contribution is
rounded into it and the error compounds with the microbatch count, even when
the user asked for a wider grad_dtype.

This is distinct from the accumulation fix in #194434, which covers
set_requires_gradient_sync(False) -- the mode that runs no collectives at all.
The two no-sync modes take different paths and only the first was addressed.

An explicit grad_dtype now widens the partial buffer so only the final
all-reduce rounds. It reuses FSDPParam._accumulate_grad_dtype, the same rule the
no-collectives no-sync path uses, so the two accumulators cannot drift apart:
the buffer is never narrowed below reduce_dtype, which would make accumulation
worse than ignoring grad_dtype entirely. When grad_dtype is unset or is not wider than reduce_dtype this is a
no-op, so nobody who did not ask for the precision pays the extra memory --
the buffer is sharded-gradient sized and held for the whole accumulation
window, so widening it is not free.

The all-reduce still runs at reduce_dtype, so one rounding remains by design;
widening it would contradict an explicit reduce_dtype.

Test Plan:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q
```

The new test fails without the torch/ change (`git stash push -- torch/`):

```
AssertionError: Set comparison failed: Items in the first set but not the second
1 failed, 19 deselected
```

Measured on 4xH100, 2x2 mesh, bf16 params, grad_dtype=fp32, reduce_dtype=bf16,
against a reference that mirrors the reduce pipeline but accumulates in fp32:

    microbatches    before        after
     8              7.143e-03     5.814e-03
    32              1.143e-02     5.714e-03

The point is not the ratio but the shape: after the change the error no longer
grows with the microbatch count. The residual ~5.7e-3 is the per-microbatch
reduce-scatter rounding, which is inherent to reduce_dtype=bf16.

Authored with assistance from Claude Code (Anthropic).
Pull-Request: #194546
@weifengpy
weifengpy force-pushed the gh/weifengpy/175/head branch from 7a0eb69 to 0c69e3f Compare August 24, 2026 06:40
@weifengpy
weifengpy force-pushed the gh/weifengpy/174/head branch from 80bbeeb to e6a9054 Compare August 24, 2026 06:40
weifengpy added a commit that referenced this pull request Aug 24, 2026
Stacked on #194434. With HSDP and set_requires_all_reduce(False), the
reduce-scatter still runs every microbatch and the partial sums are held in
partial_reduce_output across backward calls until the deferred all-reduce.
That buffer is allocated at reduce_dtype, so each microbatch's contribution is
rounded into it and the error compounds with the microbatch count, even when
the user asked for a wider grad_dtype.

This is distinct from the accumulation fix in #194434, which covers
set_requires_gradient_sync(False) -- the mode that runs no collectives at all.
The two no-sync modes take different paths and only the first was addressed.

An explicit grad_dtype now widens the partial buffer so only the final
all-reduce rounds. It reuses FSDPParam._accumulate_grad_dtype, the same rule the
no-collectives no-sync path uses, so the two accumulators cannot drift apart:
the buffer is never narrowed below reduce_dtype, which would make accumulation
worse than ignoring grad_dtype entirely. When grad_dtype is unset or is not wider than reduce_dtype this is a
no-op, so nobody who did not ask for the precision pays the extra memory --
the buffer is sharded-gradient sized and held for the whole accumulation
window, so widening it is not free.

The all-reduce still runs at reduce_dtype, so one rounding remains by design;
widening it would contradict an explicit reduce_dtype.

Test Plan:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q
```

The new test fails without the torch/ change (`git stash push -- torch/`):

```
AssertionError: Set comparison failed: Items in the first set but not the second
1 failed, 19 deselected
```

Measured on 4xH100, 2x2 mesh, bf16 params, grad_dtype=fp32, reduce_dtype=bf16,
against a reference that mirrors the reduce pipeline but accumulates in fp32:

    microbatches    before        after
     8              7.143e-03     5.814e-03
    32              1.143e-02     5.714e-03

The point is not the ratio but the shape: after the change the error no longer
grows with the microbatch count. The residual ~5.7e-3 is the per-microbatch
reduce-scatter rounding, which is inherent to reduce_dtype=bf16.

Authored with assistance from Claude Code (Anthropic).
Pull-Request: #194546
weifengpy added a commit that referenced this pull request Aug 24, 2026
Stacked on the previous PR, which carries Tensor.grad_dtype onto the sharded
parameter and casts the reduced gradient into it. That gives param.grad the
requested dtype but not the requested precision: autograd still computes at the
parameter dtype, and the cast happens after the reduce. This makes the dtype
mean what it says.

The unsharded compute parameter is the autograd leaf, so stamping grad_dtype on
it is what makes backward produce gradients in that dtype.

That in turn changes microbatch accumulation. to_accumulated_grad_if_needed
casts the unsharded gradient to reduce_dtype before summing, which was written
as an upcast (bf16 compute gradients into an fp32 reduce buffer). With an
explicit grad_dtype wider than reduce_dtype it becomes a downcast: with bf16
parameters, grad_dtype=fp32 and MixedPrecisionPolicy(reduce_dtype=bf16), every
microbatch sum would happen in bf16 and be cast back up to fp32 at the end, so
param.grad.dtype is fp32 as requested while the precision is gone and nothing
surfaces the loss. Accumulation now happens at the wider of the two. A narrower
grad_dtype must not win either, or summing would be less accurate than ignoring
grad_dtype altogether, since the final cast narrows it anyway. The comparison
uses itemsize rather than torch.promote_types, which raises for float8.

With the group uniform, the cast into grad_dtype moves back out of the
per-parameter loop to a single cast over the shared reduce buffer, which is
what the previous PR needed per parameter to support mixed dtypes.

Behavior change: setting different grad_dtype values across parameters in one
FSDP group now raises at lazy_init. The previous PR supported that by casting
per parameter after the reduce, but gradients are now produced at grad_dtype
and a single reduce-scatter copy-in cannot take mixed dtypes -- _chunk_cat
rejects them. Supporting it would mean one reduce-scatter per dtype, the same
relaxation already noted for reduce_dtype. On main today grad_dtype is not
propagated at all, so such a configuration runs but silently discards every
setting; this turns that into an error that names the fix.

Test Plan:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q
# 17 passed in 97.13s
```

Both new tests fail against the previous PR's source (`git stash push -- torch/`):

```
FAILED test_grad_dtype_grad_acc
FAILED test_grad_dtype_non_uniform_raises
```

test_grad_dtype_non_uniform_raises replaces test_grad_dtype_non_uniform from
the previous PR; the diff between them is the behavior change described above.

Authored with assistance from Claude Code (Anthropic).
Pull-Request: #194546
@weifengpy
weifengpy force-pushed the gh/weifengpy/175/head branch from 0c69e3f to 67ac1e0 Compare August 24, 2026 18:05
@weifengpy
weifengpy force-pushed the gh/weifengpy/174/head branch from e6a9054 to 338a55b Compare August 24, 2026 18:05
@weifengpy weifengpy changed the title [FSDP2] Hold HSDP microbatch partial sums at grad_dtype [FSDP2] Compute and accumulate gradients at grad_dtype Aug 24, 2026
@weifengpy
weifengpy force-pushed the gh/weifengpy/175/head branch from 67ac1e0 to c8e2bb7 Compare August 24, 2026 18:23
@weifengpy
weifengpy force-pushed the gh/weifengpy/174/head branch 2 times, most recently from 39c09d6 to f430c93 Compare August 24, 2026 18:52
@weifengpy
weifengpy force-pushed the gh/weifengpy/175/head branch from c8e2bb7 to b2c3992 Compare August 24, 2026 18:52
@weifengpy weifengpy changed the title [FSDP2] Compute and accumulate gradients at grad_dtype [FSDP2] Support non-uniform grad_dtype within a parameter group Aug 24, 2026
@weifengpy
weifengpy force-pushed the gh/weifengpy/175/head branch from b2c3992 to 5ead636 Compare August 24, 2026 19:22
@weifengpy
weifengpy force-pushed the gh/weifengpy/174/head branch 2 times, most recently from 440e91f to cf35283 Compare August 24, 2026 19:37
@weifengpy
weifengpy force-pushed the gh/weifengpy/175/head branch from 5ead636 to 901c5bd Compare August 24, 2026 19:37
@weifengpy
weifengpy force-pushed the gh/weifengpy/175/head branch 2 times, most recently from b4d62da to 811a147 Compare August 24, 2026 20:57
@weifengpy
weifengpy force-pushed the gh/weifengpy/174/head branch from cf35283 to ce7fc0a Compare August 24, 2026 21:12
@weifengpy
weifengpy force-pushed the gh/weifengpy/175/head branch from 811a147 to 5022df7 Compare August 24, 2026 21:12
@weifengpy
weifengpy force-pushed the gh/weifengpy/174/head branch from ce7fc0a to 3628b32 Compare August 24, 2026 21:25
@weifengpy
weifengpy force-pushed the gh/weifengpy/175/head branch 2 times, most recently from 10a1993 to 9f1b7eb Compare August 24, 2026 21:29
@weifengpy
weifengpy force-pushed the gh/weifengpy/174/head branch from 3628b32 to 67f6240 Compare August 24, 2026 21:29
weifengpy and others added 2 commits August 24, 2026 14:42
Fixes #170648. Based on #172074 by @arkadip-maitra.

backward compatability
* this PR deals with uniform grad_dtype only
* multiple grad_dtypes needs casting in FSDP2 framework. We won't do anything about it in this 1st PR. In next PR we will do per-param casting for a uniform dtype reduce-scatter buffer

`grad_dtype` and `reduce_dtype` are independent knobs
* **`grad_dtype`** owns gradient computation (autograd), microbatch accumulation, and the dtype of `param.grad` on the sharded parameter
* **`reduce_dtype`** owns the *collectives* — copy-in (`_chunk_cat`), reduce-scatter, and all-reduce

no-sync modes
* **`set_requires_gradient_sync(False)`** — no collectives; accumulates on `_unsharded_param.grad` at `max(grad_dtype, reduce_dtype)`. `reduce_dtype` alone would sum fp32 gradients in bf16 and cast back up `grad_dtype`  alone would sum bf16 gradients in bf16 where fp32 was already available.
* **`set_requires_all_reduce(False)`** (HSDP) — reduce-scatters every microbatch and accumulates the partial sums in `_partial_reduce_output` at `reduce_dtype`

<img width="950" height="320" alt="Screenshot 2026-08-24 at 1 30 44 PM" src="https://github.com/user-attachments/assets/00d7b060-87e3-45d7-87b8-6671614a274f" />

Co-authored-by: Arkadip Maitra <[email protected]>
Pull-Request: #194434
Stacked on the previous PR, which warns and ignores grad_dtype when a group's
parameters do not agree on it. This supports the configuration instead and
drops that fallback.

The obstacle is the copy-in, not the cast on the way out. Gradients are
produced at grad_dtype, so a non-uniform group produces a mixture, and
_chunk_cat packs them into one flat buffer and rejects mixed input dtypes.
Bring them to the dtype the reduce runs in anyway before the copy-in; only a
group that actually is non-uniform pays for that. After the reduce, each
parameter's slice is cast to its own grad_dtype rather than the whole buffer
being cast once.

The pre-existing runtime check on uniform gradient dtype stays for the case it
was written for -- fp8 weights not producing the correct higher precision
gradients -- and now fires only when the mixture is not explained by
grad_dtype.

Test Plan:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q
```

The new test fails against the previous PR's source (`git stash push -- torch/`):

```
1 failed, 15 deselected
```

test_grad_dtype_non_uniform replaces test_grad_dtype_non_uniform_warns_and_is_ignored
from the previous PR; the diff between them is the behavior change.

Authored with assistance from Claude Code (Anthropic).
Pull-Request: #194546
@github-actions

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

@github-actions github-actions Bot added the Stale label Nov 27, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (fsdp) release notes category Stale

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant