Skip to content

[fsdp] Fix double gradient division for singleton groups - #203693

Closed
shuhuayu wants to merge 1 commit into
pytorch:mainfrom
shuhuayu:fsdp-singleton-divide
Closed

shuhuayu wants to merge 1 commit into
pytorch:mainfrom
shuhuayu:fsdp-singleton-divide

Conversation

@shuhuayu

@shuhuayu shuhuayu commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

human notes: while working on the singleton reduce path for kimi k3's unreplicated expert groups, i found that fsdp2 divides gradients a second time when the divide factor is split into pre/post factors (fp16 reduce dtype or force_sum_reduction_for_comms), so gradients come out k times too small.

  • Passes lint (spin fixlint)
  • Added/updated tests
  • Updated documentation (if applicable)
  • Included benchmark results (for PRs impacting perf)

Linked issue or supporting maintainer

supported by @weifengpy

BC-breaking?

No

Agent details (if applicable)

Drafted with an AI coding assistant and reviewed by the author.

With a shard group of size one, foreach_reduce skips the reduce-scatter and divides by gradient_divide_factor to stand in for the skipped reduce op (#167178). That is only correct when _get_gradient_divide_factors folds the factor into the op (PREMUL_SUM/AVG for fp32/bf16). For fp16 reduce dtypes, force_sum_reduction_for_comms, and MTIA, the factor is instead split into pre/post-divide factors applied around the collective, so the singleton branch divided by it a second time: a factor of 4 divided gradients by 16. This affects plain FSDP and HSDP with shard size one.

The fix applies the factor in the singleton branch only when both pre- and post-divide factors are None.

Test plan: test_singleton_split_divide_factor covers fp16 reduction and forced sum reduction, with and without HSDP; it fails without the fix (3/16 instead of 3/4).

python test/distributed/_composable/fsdp/test_fully_shard_comm.py TestFullyShardReduceOpWorldSize1

Tested against the 2.16.0.dev20261030+cu130 nightly with this PR's changed torch/ files overlaid. This touches the same singleton branch as #203556, so whichever lands second needs a small rebase.

@pytorch-bot

pytorch-bot Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:

The PR fixes FSDP2's singleton reduce path (reduce-scatter group of size 1),
which divided gradients by `gradient_divide_factor` a second time when the
factor was also applied outside the reduce op (fp16 reduce dtype,
`force_sum_reduction_for_comms`, or MTIA). Recommendation: Approve. Every
remaining point is non-blocking.

Findings (5):

[minor] torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py:651
Non-blocking: the fix depends on a return shape nobody documents. It decides
"the factor was folded into the op" from `predivide_factor is None and
postdivide_factor is None`. That holds only because the fp32/bf16 non-forced
branch of `_get_gradient_divide_factors` (`:934-945`) is the only one that
returns `(None, None, ...)`. If that branch ever returns `post_factor=1.0` or a
pre-factor, the singleton path silently stops applying the factor. Fix: have
`_get_gradient_divide_factors` return the factor it folded into the op and use
that here. At minimum, add a comment at `:934-945` saying the singleton branch
relies on this shape.

[minor] torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py:648
Non-blocking: two comments are inaccurate. (1) "For single GPU": the branch runs
whenever the reduce-scatter group is None or has size 1, which includes HSDP
with shard size 1 and `replicate()` on N GPUs. (2) Line 650 here and
`test_fully_shard_comm.py:2840-2841` say the factor is "split into
pre/post(-divide) factors". For fp32 forced-sum, `:961` returns `pre=None,
post=factor`, so nothing is split. "Applied outside the reduce op" would be
accurate.

[minor] test/distributed/_composable/fsdp/test_fully_shard_comm.py:2839
Non-blocking: no test covers `replicate()`, which this fix also changes.
`replicate()` builds a `DDPMeshInfo` (`replicate_with_fsdp.py:141`), and
`_fsdp_param_group.py:804-809` then passes `reduce_scatter_group=None`, so
`foreach_reduce` always takes the singleton branch with the replicate group as
`all_reduce_group`. `ReplicateModule` inherits both `set_gradient_divide_factor`
and `set_force_sum_reduction_for_comms`. Before this PR, `replicate()` with fp16
reduce or forced sum plus a divide factor k divided gradients by k on any number
of GPUs. `test_singleton_split_divide_factor` only runs `fully_shard` on meshes
`(1,)` and `(1,1)`. A `replicate()` parametrization would fit in the same
`world_size == 1` class.

[minor] torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py:652
Non-blocking: the release note should spell out the behavior change and its full
scope. Users who tuned learning rate, clipping or loss scaling around the old
values will now see gradients k times larger. The description says the bug
"affects plain FSDP and HSDP with shard size one". It also affects `replicate()`
on any number of GPUs, HSDP with shard size 1 and any replicate size, and every
MTIA run that sets a divide factor, because MTIA always forces sum
(`_fsdp_collectives.py:920-921`). The note should list these configurations.

[minor] torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py:649
Non-blocking: the PR description is unfinished. "Linked issue or supporting
maintainer" and "Summary (human written only)" still say `TODO`. "Updated
documentation" and "Included benchmark results" are ticked but don't apply to
this diff; consider unticking them.

Reviewed commit: 548296f (NOT the current head e92b3ba)

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

✅ No Failures

As of commit e92b3ba with merge base 780bf8e (image):
💚 Looks good so far! There are no failures yet. 💚

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 Nov 5, 2026
@shuhuayu shuhuayu changed the title [FSDP2] Fix double gradient division for singleton groups [fsdp] Fix double gradient division for singleton groups Nov 5, 2026
@shuhuayu
shuhuayu marked this pull request as ready for review November 5, 2026 23:25
@shuhuayu
shuhuayu requested a review from weifengpy as a code owner November 5, 2026 23:25
@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 6, 2026
github-actions[bot]

This comment was marked as outdated.

@shuhuayu
shuhuayu force-pushed the fsdp-singleton-divide branch from 856db01 to 548296f Compare November 6, 2026 00:55

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated review of 548296f: nothing blocking; ready for human review.

The PR fixes FSDP2's singleton reduce path (reduce-scatter group of size 1), which divided gradients by gradient_divide_factor a second time when the factor was also applied outside the reduce op (fp16 reduce dtype, force_sum_reduction_for_comms, or MTIA). Recommendation: Approve. Every remaining point is non-blocking.

⚪ 5 non-blocking findings

divide_in_op = predivide_factor is None and postdivide_factor is None

Non-blocking: the fix depends on a return shape nobody documents. It decides "the factor was folded into the op" from predivide_factor is None and postdivide_factor is None. That holds only because the fp32/bf16 non-forced branch of _get_gradient_divide_factors (:934-945) is the only one that returns (None, None, ...). If that branch ever returns post_factor=1.0 or a pre-factor, the singleton path silently stops applying the factor. Fix: have _get_gradient_divide_factors return the factor it folded into the op and use that here. At minimum, add a comment at :934-945 saying the singleton branch relies on this shape.


# For single GPU, just copy the input to output (no actual reduce-scatter needed), and

Non-blocking: two comments are inaccurate. (1) "For single GPU": the branch runs whenever the reduce-scatter group is None or has size 1, which includes HSDP with shard size 1 and replicate() on N GPUs. (2) Line 650 here and test_fully_shard_comm.py:2840-2841 say the factor is "split into pre/post(-divide) factors". For fp32 forced-sum, :961 returns pre=None, post=factor, so nothing is split. "Applied outside the reduce op" would be accurate.


def test_singleton_split_divide_factor(self, split_by, hsdp):

Non-blocking: no test covers replicate(), which this fix also changes. replicate() builds a DDPMeshInfo (replicate_with_fsdp.py:141), and _fsdp_param_group.py:804-809 then passes reduce_scatter_group=None, so foreach_reduce always takes the singleton branch with the replicate group as all_reduce_group. ReplicateModule inherits both set_gradient_divide_factor and set_force_sum_reduction_for_comms. Before this PR, replicate() with fp16 reduce or forced sum plus a divide factor k divided gradients by k on any number of GPUs. test_singleton_split_divide_factor only runs fully_shard on meshes (1,) and (1,1). A replicate() parametrization would fit in the same world_size == 1 class.


Non-blocking: the release note should spell out the behavior change and its full scope. Users who tuned learning rate, clipping or loss scaling around the old values will now see gradients k times larger. The description says the bug "affects plain FSDP and HSDP with shard size one". It also affects replicate() on any number of GPUs, HSDP with shard size 1 and any replicate size, and every MTIA run that sets a divide factor, because MTIA always forces sum (_fsdp_collectives.py:920-921). The note should list these configurations.


# apply a gradient_divide_factor that the skipped reduce op would have applied.

Non-blocking: the PR description is unfinished. "Linked issue or supporting maintainer" and "Summary (human written only)" still say TODO. "Updated documentation" and "Included benchmark results" are ticked but don't apply to this diff; consider unticking them.

This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review

@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Nov 6, 2026
# apply a gradient_divide_factor that the skipped reduce op would have applied.
# A factor split into pre/post-divide factors is applied outside the op.
divide_in_op = predivide_factor is None and postdivide_factor is None
if (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

stack this PR on top of #203556

Compute divide_in_op once in the skipped-reduce-scatter branch and use it for both the copy path and the reuse path.

@shuhuayu
shuhuayu force-pushed the fsdp-singleton-divide branch 2 times, most recently from e490d12 to c20e26f Compare November 7, 2026 03:43
# A skipped reduce-scatter must still apply a divide factor folded into
# its op, but not one applied outside the op as pre/post-divide factors.
divide_in_op = predivide_factor is None and postdivide_factor is None
if skip_reduce_scatter and all_reduce_group is None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

skip_reduce_scatter appears twice in if-else and is hard for human to follow

from ai review
'''

Two points on the singleton branch in foreach_reduce, one readability and one correctness:

  1. skip_reduce_scatter is tested twice in the same if/elif chain, so the reader has to re-evaluate the same predicate. Please test it once and split the sub-cases on all_reduce_group, which is the actual difference between them.

  2. The two sub-cases divide inconsistently: the reuse path divides by the full gradient_divide_factor, the copy path open-codes its own is not None check. The branch only owes the share the collective op would have carried — the full factor when both pre/post factors are None, and nothing otherwise. Dividing unconditionally reintroduces the [FSDP2] set_gradient_divide_factor(f) divides by f twice when the reduce-scatter has one rank and the reduction forces sums or uses fp16/fp64 #202170 double division for fp16/fp64 and force_sum, where pre/post already multiply to the full factor. Compute that share once as divide_in_op and use it for both paths:

    No collective runs to fold the division into, so the branch owes

    exactly what pre/post division does not already cover.

    divide_in_op = (
    gradient_divide_factor
    if predivide_factor is None and postdivide_factor is None
    else None
    )

    with device_handle.stream(reduce_scatter_stream):
    div_if_needed(reduce_scatter_input, predivide_factor)
    if skip_reduce_scatter:
    if all_reduce_group is None:
    # The packed input already is the reduction output
    reduce_output = reduce_scatter_input
    else:
    # HSDP/replicate keeps a separate output, allocated in the RS
    # stream, since its all-reduce and partial accumulation
    # outlive the input
    reduce_output = torch.empty_like(reduce_scatter_input)
    reduce_output.copy
    (reduce_scatter_input)
    _div_if_needed(reduce_output, divide_in_op)
    else:
    reduce_output = reduce_scatter_comm.allocate(
    (reduce_scatter_output_numel,),
    dtype=reduce_dtype,
    device=device,
    )
    reduce_scatter_comm(
    output_tensor=reduce_output,
    input_tensor=reduce_scatter_input,
    group=reduce_scatter_group,
    op=reduce_scatter_op,
    )
    reduce_scatter_event = reduce_scatter_stream.record_event()

'''

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

you are right, applied and updated.

@shuhuayu
shuhuayu force-pushed the fsdp-singleton-divide branch from c20e26f to f5f51e0 Compare November 9, 2026 21:17
With a shard group of size one, foreach_reduce skips the reduce-scatter and applies gradient_divide_factor itself to account for the division the skipped reduce op would have applied (pytorch#167178). After pytorch#203556 this happens in two places: the reused-input path for plain FSDP and the copy path for HSDP/replicate.

That only holds when _get_gradient_divide_factors folds the factor into the reduce op (ReduceOp.PREMUL_SUM or AVG for fp32/bf16). For fp16 reduce dtypes, force_sum_reduction_for_comms, and MTIA, it instead applies the factor outside the op as pre/post-divide factors via _div_if_needed, and the singleton path then divided by the full factor again. For example, a factor of 4 divided gradients by 16. This affects any reduce-scatter group of size one, including HSDP with a shard size of one and replicate().

Apply the division once for both singleton paths, after reusing or copying the input, and only with a factor the skipped op would have carried (both pre- and post-divide factors are None). The copy path now divides in place instead of allocating a temporary.

Test Plan:

Run against the 2.16.0.dev20261030+cu130 nightly with this commit's torch/ files overlaid. The new test fails without this fix (gradient 3/16 instead of 3/4) for fp16 reduction and forced sum reduction, covering the reused-input path (plain FSDP) and the copy path (HSDP).

```bash
python test/distributed/_composable/fsdp/test_fully_shard_comm.py TestFullyShardReduceOpWorldSize1
python test/distributed/_composable/fsdp/test_fully_shard_comm.py
lintrunner -a
```

Authored with assistance from an AI coding assistant.
@shuhuayu
shuhuayu force-pushed the fsdp-singleton-divide branch from f5f51e0 to e92b3ba Compare November 10, 2026 01:44
@shuhuayu
shuhuayu requested a review from weifengpy November 10, 2026 01:47
@shuhuayu

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Nov 13, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

taras-janea pushed a commit to taras-janea/pytorch that referenced this pull request Nov 13, 2026
)

human notes:  while working on the singleton reduce path for kimi k3's unreplicated expert groups, i found that fsdp2 divides gradients a second time when the divide factor is split into pre/post factors (fp16 reduce dtype or `force_sum_reduction_for_comms`), so gradients come out k times too small.

- [x] Passes lint (`spin fixlint`)
- [x] Added/updated tests
- [x] Updated documentation (if applicable)
- [x] Included benchmark results (for PRs impacting perf)

## Linked issue or supporting maintainer

supported by @weifengpy

## BC-breaking?

No

## Agent details (if applicable)

> Drafted with an AI coding assistant and reviewed by the author.
>
> With a shard group of size one, `foreach_reduce` skips the reduce-scatter and divides by `gradient_divide_factor` to stand in for the skipped reduce op (pytorch#167178). That is only correct when `_get_gradient_divide_factors` folds the factor into the op (`PREMUL_SUM`/`AVG` for fp32/bf16). For fp16 reduce dtypes, `force_sum_reduction_for_comms`, and MTIA, the factor is instead split into pre/post-divide factors applied around the collective, so the singleton branch divided by it a second time: a factor of 4 divided gradients by 16. This affects plain FSDP and HSDP with shard size one.
>
> The fix applies the factor in the singleton branch only when both pre- and post-divide factors are `None`.
>
> Test plan: `test_singleton_split_divide_factor` covers fp16 reduction and forced sum reduction, with and without HSDP; it fails without the fix (3/16 instead of 3/4).
> ```
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py TestFullyShardReduceOpWorldSize1
> ```
> Tested against the `2.16.0.dev20261030+cu130` nightly with this PR's changed `torch/` files overlaid. This touches the same singleton branch as pytorch#203556, so whichever lands second needs a small rebase.

Pull Request resolved: pytorch#203693
Approved by: https://github.com/weifengpy
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 ciflow/trunk Trigger trunk jobs on your pull request Merged ready for review Automated review passed, ready for a final review by a maintainer. release notes: distributed (fsdp) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FSDP2] set_gradient_divide_factor(f) divides by f twice when the reduce-scatter has one rank and the reduction forces sums or uses fp16/fp64

4 participants