Skip to content

[fsdp] Reuse reduce input for singleton groups - #203556

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

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

Conversation

@shuhuayu

@shuhuayu shuhuayu commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

human notes: While scaling Kimi K3 training, I found that FSDP2 allocates and copies a full extra gradient buffer for size-1 shard groups (our unreplicated expert groups). This adds one gradient-sized buffer per module to peak memory, and under CUDA graph capture it stays pinned in the graph's private memory pool.

  • 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.

For a shard group of size one, foreach_reduce allocated a separate reduce-scatter output and copied the packed input into it even though no collective runs. Large unreplicated expert groups can make that redundant output GiB-scale, and CUDA graph capture retains it in the graph-private memory pool.

This reuses the packed input as the singleton reduction output and applies the existing custom divide in place. Multi-rank reduce-scatter is unchanged. The singleton test now checks for exactly one communication-buffer allocation and numerical parity across divide factors.

Test plan:

python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k singleton_reduce_reuses_input

Tested against the 2.16.0.dev20261030+cu130 nightly with this PR's changed torch/ files overlaid.

@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:

For reduce-scatter groups of size 1, FSDP now allocates the packed gradient
buffer itself and skips the reduce-scatter comm; plain FSDP reuses that buffer
as the reduce output, while HSDP and replicate() keep a separate output
allocated with torch.empty_like on the RS stream. Recommendation: Approve. The
earlier blocking finding is fixed, both maintainer comments are addressed, and
every remaining point is non-blocking.

Findings (9):

[minor] torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py:803
Non-blocking: the new comment claims too much. It says the AllReduceState is
"only released after waiting on the post-reduce event". All three release sites
(_end_backward_iteration, _wait_for_post_backward, _reset_iter_state) do wait
first, but the stream that waits is the stream doing the release, not
rs_state.allocation_stream. Case: plain FSDP at world size 1 with
set_all_reduce_hook, where reduce_scatter_event stays the RS event recorded
before the hook (:805). If finalization runs on a different stream from
post_backward (e.g. GradientReductionHandle.wait() under a side stream), the
allocation stream can reuse the block while the all-reduce/hook stream is still
reading it (postdivide, cast, += at :787, D2H copy). Only bites when .grad does
not alias the buffer (dtype cast, CPU offload, accumulation). Fix: have each
rs_state.allocation_stream also wait on _last_post_reduce_events, or state the
same-stream assumption in the comment. Raised before as low confidence; still a
narrow edge case.

[minor] torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py:646
Non-blocking, predates this PR: at world size 1 a custom gradient_divide_factor
f is applied twice. _get_gradient_divide_factors already folds f into the
pre/post factors; :646 (and :652 for HSDP) then divides by f again, so gradients
end up divided by f. Affected: fp16 reduce dtype (pre  post = f) and
force_sum_reduction_for_comms, always on for MTIA (post = f). Fix: apply
gradient_divide_factor only when both pre- and post-divide factors are None.
test_singleton_reduce_reuses_input only runs fp32, so it cannot catch this.

[minor] torch/distributed/fsdp/_fully_shard/_fully_shard.py:978
Non-blocking: the set_reduce_scatter_max_input_buffers docstring (977-980) is
still inconsistent. "This helps only when the reduce-scatter is exposed" is
directly followed by the size-1 sentence, but at size 1 no reduce-scatter runs;
the recycle stall comes from the previous module's post-reduce work. Also, "the
buffer is used until the post-reduce ops finish" is wrong for size-1
HSDP/replicate(): there the input is last read by the copy on the RS stream, and
the recycle event is the copy event (_fsdp_collectives.py:667).

[minor] torch/distributed/fsdp/_fully_shard/_fully_shard.py:791
Non-blocking: custom reduce-scatter comms on replicate() modules now go
completely unused, at any world size. ReplicateModule inherits
set_custom_reduce_scatter, and replicate() passes reduce_scatter_group=None
(_fsdp_param_group.py:804-809), so world_size becomes 1. Before, allocate was
called twice per reduce and its output became the all-reduce buffer; now that
buffer comes from torch.empty_like, so a comm set through
set_allocate_memory_from_process_group no longer supplies the replicate/HSDP
all-reduce buffer, which can change NCCL buffer registration. This note mentions
only "reduce-scatter group has size 1", not replicate(), and the
Comm/ReduceScatter docstrings in _fsdp_api.py don't mention the bypass.
Requested: mention replicate() in the docstring, and replace the description's
"BC-breaking? No" with a release note for this behavior change (the PR has the
`release notes: distributed (fsdp)` label).

(5 more not shown, see the review run)

Reviewed commit: ea68d1c (NOT the current head 85bb30e)

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

❌ 1 New Failure, 2 Cancelled Jobs, 4 Unrelated Failures

As of commit 85bb30e with merge base cba4a42 (image):

NEW FAILURE - The following job has failed:

NEW FAILURES SUPPRESSED BY AI (non-blocking) - The following jobs failed, but the AI CI Advisor judged the failures not to be evidence against this change:

  • inductor / inductor-cpu-test / test (cpu_inductor_torchbench, 1, 2, mt-l-x86iamx-8-64) (gh)
    doctr_reco_predictor

    AI verdict: AI verdict: infra issue

    doctr_reco_predictor (and doctr_det_predictor) failed while loading the model, before any benchmark ran. Downloading the pretrained weights from doctr-static.mindee.com returned HTTP 504 Gateway Time-out, and the http fallback failed too. The suspect commit only changes FSDP2 reduce-scatter code in torch/distributed, which this CPU inductor torchbench job never reaches.

    Full reasoning on HUD →

  • inductor / inductor-test-cuda134 / test (inductor_torchbench, 1, 2, mt-l-x86aavx2-11-41-a10g) (gh)
    doctr_reco_predictor

    AI verdict: AI verdict: infra issue

    doctr_reco_predictor (and doctr_det_predictor) failed while loading the model: downloading pretrained weights from doctr-static.mindee.com returned HTTP 504 Gateway Time-out, so the eager run never happened. The suspect commit only changes FSDP2 reduce-scatter code, which this torchbench inference job never runs.

    Full reasoning on HUD →

  • Lint / Test collect_env (older_python_version, linux.24_04.4x) (gh)
    ##[error]The version '3.8' with architecture 'x64' was not found for Ubuntu 26.04.

    AI verdict: AI verdict: infra issue

    The job dies in setup-python because Python 3.8 isn't available for the Ubuntu 26.04 runner image. This happens before any of the commit's code runs. The merge base and other recent trunk commits fail with the same error, and the suspect commit only changes FSDP Python sources and tests.

    Full reasoning on HUD →

  • pull / linux-jammy-rocm-py3.11 / build (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    code=1

    AI verdict: AI verdict: infra issue

    The ROCm build failed on both attempts because the CMake ExternalProject download of the AOTriton image tarball from github.com got HTTP 504 Gateway Timeout. One attempt failed on image 942 and the other on image 950. The suspect commit changes only Python FSDP2 code and tests, which play no part in the build's download step.

    Full reasoning on HUD →

CANCELLED JOBS - The following jobs were cancelled. Please retry:

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 force-pushed the fsdp-singleton-reduce branch 3 times, most recently from e2a7312 to 2a37dcc Compare November 5, 2026 22:49
@shuhuayu shuhuayu changed the title [FSDP2] Reuse reduce input for singleton groups [fsdp] Reuse reduce input for singleton groups Nov 5, 2026
@shuhuayu
shuhuayu marked this pull request as ready for review November 5, 2026 23:26
@shuhuayu
shuhuayu requested a review from weifengpy as a code owner November 5, 2026 23:26
@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.

world_size == 1
and all_reduce_group is None
and type(reduce_scatter_comm)
in (DefaultReduceScatter, ProcessGroupAllocReduceScatter, SymmMemReduceScatter)

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.

we don't do if-else base on which RS it is, otherweise it's leaky abstraction. RS is an extention point

from AI review

A one-rank shard group runs no reduce-scatter, so the comm has nothing to do there, and a buffer that is never communicated gains nothing from an NCCL or symmetric-memory pool. Suggestion:

- Add `skip_reduce_scatter = world_size == 1`. When it is set, allocate the packed gradients with `torch.empty` instead of `reduce_scatter_comm.allocate`, so FSDP owns the buffer and the comm is never called.
- Reuse that buffer as the output when `skip_reduce_scatter and all_reduce_group is None`. HSDP keeps the copy, because its all-reduce and partial accumulation outlive the input regardless of the comm.
- Drop the type tuple. The condition is then structural and covers custom comms too.
- In the lifetime check at the end, test `reduce_output is reduce_scatter_input` instead of the flag.

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.

great point! was thinking use the reusing the input buffer for .grad directly, but letting fsdp directly owns the buffer is better.

@weifengpy weifengpy 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.

see above

@shuhuayu
shuhuayu force-pushed the fsdp-singleton-reduce branch from 2a37dcc to 8fa411d Compare November 7, 2026 01:07
@shuhuayu
shuhuayu requested a review from weifengpy November 7, 2026 01:08
@weifengpy

Copy link
Copy Markdown
Contributor

@claude take a look at this PR and focus on 3 things 1) any touched tensors that's allocated in producer cuda stream and consumed in another cuda stream. check whether all stream sync via stream wait and event wait are correctly preserved,. read https://docs.pytorch.org/devlogs/eager/2026-09-29-cross-stream-memory-without-record-stream/ to understand cross-stream tensor memory management. 2) check on cpu-side python reference couthing to make sure all tensors are freed in time and not hold longer than necessary. 3) check cuda memory behavior to see if there are any changes in memory allocation order and unexpected usage

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Claude finished @weifengpy's task in 2m 21s —— View job


I found no correctness bugs in the three areas you asked about. The one change worth deciding on is a compute-stream stall when CPU offload or post-accumulate-grad hooks are used.

Details: cross-stream sync, CPU-side ref holding, CUDA memory behavior

I couldn't fetch the devlog because WebFetch is blocked in this job. The analysis below follows the rule FSDP2 uses in place of record_stream: keep a Python ref until the allocating stream has waited on the event that marks the last use on another stream, then drop the ref.

Scope: everything below concerns world_size == 1. The multi-rank path is unchanged.

1) Cross-stream producer and consumer

Tensor Allocated on Used on Kept alive until Verdict
reduce_scatter_input = reduce_output (plain FSDP) compute stream (torch.empty, _fsdp_collectives.py:622) RS stream: pre/post div, _div_if_needed(gradient_divide_factor), cast/clone in _cast_and_view_sharded_grads, grad._local_tensor +=, D2H copy, post-acc-grad hooks ReduceScatterState, whose event is now post_reduce_event (:805-806). The next module's post_backward_rs_wait makes the compute stream wait on it before dropping the ref (_fsdp_param_group.py:745-748). At the end of backward, _end_backward_iteration / _reset_iter_state waits on it before clear(). ✅ Correct. Before this PR the event was recorded before these reads, which is the race the PR fixes.
Same tensor, all_reduce_hook set compute RS stream, then the hook stream (hook and post-reduce ops) ReduceScatterState keeps the pre-hook RS event (:805 skips the swap), but AllReduceState also holds the same tensor. That ref is dropped only after current_stream.wait_event(_post_reduce_event) in _wait_for_post_backward (:1048-1057), or after _end_backward_iteration waits on _last_post_reduce_events, which cover everything on the hook stream because each stream's last event orders all earlier work. ✅ Correct. The block can't go back to the compute pool before the hook-stream reads finish.
Sharded grads (views of the input, no cast) now compute stream (before: RS stream) RS stream writes them; compute/optimizer reads them Held by .grad. The compute stream waits on _last_post_reduce_events before backward ends. ✅ This is actually safer than before: when the optimizer frees a grad (zero_grad(set_to_none=True)), the block goes back to the pool of the stream that last read it. Previously it went to the RS-stream pool after compute-stream reads, and only the later rs_stream.wait_stream(current) kept that safe.
HSDP reduce_scatter_input compute (torch.empty instead of comm.allocate) RS stream copies it into reduce_output ReduceScatterState keeps the RS event. The last read is the copy_ before that event. ✅ Unchanged ordering.
record_grad_output_stream(reduce_output, current_stream) — — For the reused buffer, the consumer stream equals the allocation stream. ✅ Harmless no-op.

The trade-off: with the default max_input_buffers=1, the compute stream at module N+1's post_backward_rs_wait now waits on module N's post-reduce work, not just its RS-stream div/copy. With no offload and no hooks, that work is a few elementwise kernels, so the cost is negligible. With offload_to_cpu, it includes a full-grad D2H copy. With post-acc-grad hooks (e.g. optimizer-in-backward), it includes arbitrary GPU work. Either one can stall backward compute where it did not stall before.

  • Suggestion: add and not any(p.offload_to_cpu for p in fsdp_params) to the reuse condition. Under offload the GPU buffer is short-lived anyway, so reuse saves little. Otherwise, add a number showing the stall doesn't matter. The PR ticks "Included benchmark results" but includes none.

2) CPU-side Python refs

I don't see any tensor being held longer than it costs.

  • No cast, no offload: the retained ReduceScatterState ref points at memory that .grad holds anyway, so retention costs 0 extra bytes. Before the PR it cost one extra N-sized buffer per retained state.
  • Cast (e.g. fp32 reduce → bf16 grad): the fp32 buffer now lives until the next module's rs_wait. Before the PR, the separate fp32 output was freed as soon as foreach_reduce returned, but the fp32 input was already held that long. Net change: one fewer N-sized fp32 buffer, no longer lifetime.
  • Offload: same as the cast case. The GPU grad is no longer dropped right after the D2H; it lives as long as the input already did. Net change: still one fewer buffer.
  • all_reduce_hook: AllReduceState now pins the buffer, but it is the same tensor as .grad / ReduceScatterState, so it adds no memory. It is released at the same points as before (_wait_for_post_backward, finalize_backward).
  • Locals in foreach_reduce and post_backward (reduce_output, reduce_scatter_input) go out of scope when those functions return, as before.
  • Small inconsistency: _fully_shard.py:967-975 still says raising max_input_buffers costs "extra peak memory for the retained buffers". For singleton groups with no cast or offload, it costs nothing.

3) CUDA allocation order and memory usage

Allocation sequence per module at ws=1, plain FSDP:

Step Before After
copy-in buffer comm.allocate(N) on compute torch.empty(N) on compute (same size; at ws=1 numel * world_size == numel)
RS output comm.allocate(N) on RS stream none
divide temp input / factor allocates N on RS stream in-place, none
copy output.copy_(input) none

The behavior changes I'd flag (none of them bugs):

  1. Grads move from the RS-stream pool to the compute-stream pool when there is no cast. Fully replicated groups now put long-lived grad segments in the compute pool, interleaved with activations and unsharded grads. That changes the fragmentation pattern of the compute pool, but it also lets the next iteration's forward reuse grad blocks after zero_grad. RS-stream blocks were unusable by the compute stream, so reserved memory should go down. A memory_stats() comparison of reserved_bytes.all.peak before and after on the K3 config would confirm it.
  2. Custom, ProcessGroup and SymmMem comms are no longer asked for the input at ws=1, so the NCCL or symmetric-memory pool is no longer used for that buffer. The commit message states this. Note that the HSDP ws=1 branch (:649) still takes the output from comm.allocate even though no collective runs. Using torch.empty there too would be consistent and keep comm-pool memory unused at ws=1. This is optional.
  3. Under CUDA graph capture, the redundant N-sized RS-stream output no longer exists in the private pool. That matches the stated motivation.
  4. The size of the transient peak during copy-in (unsharded grads + input) is unchanged. Peak after copy-in drops by N per module, plus N per retained state.

Other notes

  • test_singleton_reduce_accumulation_with_delayed_post_reduce uses device_sleep to widen the race window. torch/distributed/CLAUDE.md says to avoid sleeps. Here the sleep only makes the race more likely and isn't needed for the test to pass, so it's acceptable, but please add a comment saying so. Also hoist get_cycles_per_ms out of the patched function so calibration doesn't sync in the middle of backward.
  • Your earlier comment (decide on structure, not comm type) is addressed: the type tuple is gone, and the lifetime check uses reduce_output is reduce_scatter_input.

github-actions[bot]

This comment was marked as outdated.

shuhuayu added a commit to shuhuayu/pytorch that referenced this pull request Nov 7, 2026
Stacked on pytorch#203556.

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().

Compute once whether the skipped op would have carried the factor (both pre- and post-divide factors are None) and apply the factor in either singleton path only in that case.

Test Plan:

Run against the 2.16.0.dev20261030+cu130 nightly with this stack's torch/ files overlaid. The new test fails on pytorch#203556 alone (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.

@weifengpy weifengpy 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.

address hsdp path before landing: the size-1 HSDP/replicate() path still calls reduce_scatter_comm.allocate, but only for the output, which silently corrupts gradients for custom comms that hand out a persistent input buffer by call order.

@shuhuayu
shuhuayu force-pushed the fsdp-singleton-reduce branch from 8fa411d to ea68d1c Compare November 7, 2026 03:41
shuhuayu added a commit to shuhuayu/pytorch that referenced this pull request Nov 7, 2026
Stacked on pytorch#203556.

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().

Compute once whether the skipped op would have carried the factor (both pre- and post-divide factors are None) and apply the factor in either singleton path only in that case.

Test Plan:

Run against the 2.16.0.dev20261030+cu130 nightly with this stack's torch/ files overlaid. The new test fails on pytorch#203556 alone (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.

@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 ea68d1c: nothing blocking; ready for human review.

For reduce-scatter groups of size 1, FSDP now allocates the packed gradient buffer itself and skips the reduce-scatter comm; plain FSDP reuses that buffer as the reduce output, while HSDP and replicate() keep a separate output allocated with torch.empty_like on the RS stream. Recommendation: Approve. The earlier blocking finding is fixed, both maintainer comments are addressed, and every remaining point is non-blocking.

⚪ 9 non-blocking findings

# above, so keep it alive until they finish. With all_reduce_input set, its

Non-blocking: the new comment claims too much. It says the AllReduceState is "only released after waiting on the post-reduce event". All three release sites (_end_backward_iteration, _wait_for_post_backward, _reset_iter_state) do wait first, but the stream that waits is the stream doing the release, not rs_state.allocation_stream. Case: plain FSDP at world size 1 with set_all_reduce_hook, where reduce_scatter_event stays the RS event recorded before the hook (:805). If finalization runs on a different stream from post_backward (e.g. GradientReductionHandle.wait() under a side stream), the allocation stream can reuse the block while the all-reduce/hook stream is still reading it (postdivide, cast, += at :787, D2H copy). Only bites when .grad does not alias the buffer (dtype cast, CPU offload, accumulation). Fix: have each rs_state.allocation_stream also wait on _last_post_reduce_events, or state the same-stream assumption in the comment. Raised before as low confidence; still a narrow edge case.


_div_if_needed(reduce_output, gradient_divide_factor)

Non-blocking, predates this PR: at world size 1 a custom gradient_divide_factor f is applied twice. _get_gradient_divide_factors already folds f into the pre/post factors; :646 (and :652 for HSDP) then divides by f again, so gradients end up divided by f. Affected: fp16 reduce dtype (pre post = f) and force_sum_reduction_for_comms, always on for MTIA (post = f). Fix: apply gradient_divide_factor only when both pre- and post-divide factors are None. test_singleton_reduce_reuses_input only runs fp32, so it cannot catch this.


if gradient_divide_factor is not None and gradient_divide_factor != 1.0:

Non-blocking: the new HSDP branch (lines 650-654) can be simpler. It repeats _div_if_needed's None/1 check, and reduce_scatter_input / gradient_divide_factor allocates a full-size temporary on the RS stream. Use reduce_output.copy_(reduce_scatter_input) followed by _div_if_needed(reduce_output, gradient_divide_factor), matching the plain branch two lines up.


helps only when the reduce-scatter is exposed. For a reduce-scatter group

Non-blocking: the set_reduce_scatter_max_input_buffers docstring (977-980) is still inconsistent. "This helps only when the reduce-scatter is exposed" is directly followed by the size-1 sentence, but at size 1 no reduce-scatter runs; the recycle stall comes from the previous module's post-reduce work. Also, "the buffer is used until the post-reduce ops finish" is wrong for size-1 HSDP/replicate(): there the input is last read by the copy on the RS stream, and the recycle event is the copy event (_fsdp_collectives.py:667).


See `Comm` and `ReduceScatter` for details. The comm is not used when

Non-blocking: custom reduce-scatter comms on replicate() modules now go completely unused, at any world size. ReplicateModule inherits set_custom_reduce_scatter, and replicate() passes reduce_scatter_group=None (_fsdp_param_group.py:804-809), so world_size becomes 1. Before, allocate was called twice per reduce and its output became the all-reduce buffer; now that buffer comes from torch.empty_like, so a comm set through set_allocate_memory_from_process_group no longer supplies the replicate/HSDP all-reduce buffer, which can change NCCL buffer registration. This note mentions only "reduce-scatter group has size 1", not replicate(), and the Comm/ReduceScatter docstrings in _fsdp_api.py don't mention the bypass. Requested: mention replicate() in the docstring, and replace the description's "BC-breaking? No" with a release note for this behavior change (the PR has the release notes: distributed (fsdp) label).


# hsdp=True checks that partial accumulation keeps a separate output.

Non-blocking: this comment overstates the test. It says "hsdp=True checks that partial accumulation keeps a separate output", but the test only checks gradient parity. If HSDP reused the input, partial_reduce_output would still hold a reference, so parity would most likely still pass. Either soften the comment or add a structural check, such as asserting that aten.copy_ runs on the HSDP path.


self.assertEqual(mock_allocate.call_count, 0)

Non-blocking, unchanged since the last review: mock_allocate.call_count == 0 has no positive control. It is correct today because the default comm is DefaultReduceScatter (_fsdp_param_group.py:253), but it would pass silently if the default changed. Asserting the comm instance's type makes it robust.


if reduce_output is reduce_scatter_input and all_reduce_input is None:

Non-blocking, raised before and still unanswered: at world size 1 the compute stream now waits on more work. With default max_input_buffers=1, the recycle wait in post_backward (_fsdp_param_group.py:738-748) waits on the previous module's post_reduce_event (:805-806); before, it waited only on the copy. The wait now includes casts, accumulation, CPU-offload D2H copies and post-accumulate-grad hooks such as optimizer-in-backward. Single-GPU pinned CPU offload loses D2H/compute overlap, and grads don't alias the buffer there anyway. "Included benchmark results" is ticked but no numbers are shown. Please benchmark the offload and hook cases, or switch the event only when the sharded grads alias the buffer.


# The comm allocates nothing and the packed input is not copied to an output

Non-blocking: the PR description is stale. It says the test checks "exactly one communication-buffer allocation", but the test asserts zero. The "Summary" and "Linked issue" sections are still TODO. The test plan runs only -k singleton_reduce_reuses_input, not the two other new tests.

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

@github-actions
github-actions Bot dismissed their stale review November 7, 2026 03:54

Withdrawn: the automated review of ea68d1c found nothing blocking.

@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 7, 2026
@shuhuayu

shuhuayu commented Nov 7, 2026

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 7, 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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / win-vs2022-cpu-py3 / test (default, 5, 12, windows.4xlarge.nonephemeral)

Details for Dev Infra team

Raised by workflow job

For a shard group of size one, foreach_reduce allocated a separate reduce-scatter output and copied the packed input into it even though no collective runs. Large unreplicated expert groups can make that redundant output GiB-scale, and CUDA graph capture retains it in the graph-private memory pool.

Since no reduce-scatter runs, FSDP no longer uses the reduce-scatter comm for singleton groups and allocates their buffers itself. For plain FSDP, the packed buffer (torch.empty) is reused as the reduction output and the custom divide factor is applied in place. HSDP/replicate keeps a separate output, allocated with torch.empty in the reduce-scatter stream as before, since its all-reduce and partial accumulation read the output across microbatches, after the input would be released. Owning the buffers is what makes this safe for any comm: the Comm interface allows allocate() to return a persistent buffer, and comms may pick which allocation is persistent by call order, so asking the comm for only some of the buffers would hand that persistent buffer out as gradient storage. This keeps the decision structural rather than depending on the comm type; the tradeoff is that a custom comm's allocate() and __call__ are not used for singleton groups, which set_custom_reduce_scatter now documents.

A reused input is read by the post-reduce ops (accumulation into an existing grad, dtype cast, CPU offload), while ReduceScatterState only keeps it alive until the reduce-scatter event, which is recorded before them. Releasing it then lets the next module's backward reuse its memory and corrupt gradients, so foreach_reduce returns the post-reduce event as the input's keepalive event when the output is the input. When all_reduce_input is set (all-reduce hook), AllReduceState handling already orders the release after the post-reduce event, so the reduce-scatter event is kept to avoid making the compute stream wait on the hook.

Tests: the singleton test checks that the comm allocates nothing, no copy runs, and gradients match across divide factors. New tests delay reduce-scatter stream work under gradient accumulation for plain FSDP and HSDP on a size-1 shard group, and check that a custom comm that reuses a persistent input buffer is never called and gradients stay correct, for plain FSDP and HSDP. The plain FSDP delay test fails without the keepalive event change.

Test Plan:

Run against the 2.16.0.dev20261030+cu130 nightly with this commit's torch/ files overlaid:

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

The full test_fully_shard_comm.py run on 2 GPUs has one error, in test_fully_shard_alloc_from_pg, which also fails without this commit in this environment.

Authored with assistance from an AI coding assistant.
@shuhuayu
shuhuayu force-pushed the fsdp-singleton-reduce branch from ea68d1c to 85bb30e Compare November 8, 2026 08:39
@shuhuayu

shuhuayu commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 2 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team

Raised by workflow job

Failing merge rule: Core Maintainers

@shuhuayu

shuhuayu commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

checked the errors are unrelated to this pr's change, so will merge anyway.

@shuhuayu

shuhuayu commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

shuhuayu added a commit to shuhuayu/pytorch that referenced this pull request Nov 9, 2026
Stacked on pytorch#203556.

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().

Compute once whether the skipped op would have carried the factor (both pre- and post-divide factors are None) and apply the factor in either singleton path only in that case.

Test Plan:

Run against the 2.16.0.dev20261030+cu130 nightly with this stack's torch/ files overlaid. The new test fails on pytorch#203556 alone (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 added a commit to shuhuayu/pytorch that referenced this pull request Nov 10, 2026
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.
pytorchmergebot pushed a commit 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 (#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.

Pull Request resolved: #203693
Approved by: https://github.com/weifengpy
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.

4 participants