Repository navigation
Conversation
PR Status: Approved 🚀Please fix all CI failures and trigger merge by commenting "@pytorchbot merge". ✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:
Findings (9): Reviewed commit: 🔗 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 FailuresAs of commit 85bb30e with merge base cba4a42 ( 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:
CANCELLED JOBS - The following jobs were cancelled. Please retry:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
e2a7312 to
2a37dcc
Compare
| world_size == 1 | ||
| and all_reduce_group is None | ||
| and type(reduce_scatter_comm) | ||
| in (DefaultReduceScatter, ProcessGroupAllocReduceScatter, SymmMemReduceScatter) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
great point! was thinking use the reusing the input buffer for .grad directly, but letting fsdp directly owns the buffer is better.
2a37dcc to
8fa411d
Compare
|
@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 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 behaviorI couldn't fetch the devlog because WebFetch is blocked in this job. The analysis below follows the rule FSDP2 uses in place of Scope: everything below concerns 1) Cross-stream producer and consumer
The trade-off: with the default
2) CPU-side Python refsI don't see any tensor being held longer than it costs.
3) CUDA allocation order and memory usageAllocation sequence per module at ws=1, plain FSDP:
The behavior changes I'd flag (none of them bugs):
Other notes
|
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
left a comment
There was a problem hiding this comment.
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.
8fa411d to
ea68d1c
Compare
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.
There was a problem hiding this comment.
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
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.
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.
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.
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).
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).
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.
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.
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.
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
Withdrawn: the automated review of ea68d1c found nothing blocking.
|
@pytorchbot merge |
Merge startedYour 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 |
Merge failedReason: 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 teamRaised 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.
ea68d1c to
85bb30e
Compare
|
@pytorchbot merge |
Merge startedYour 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 |
Merge failedReason: 2 mandatory check(s) failed. The first few are:
Dig deeper by viewing the failures on hud |
|
checked the errors are unrelated to this pr's change, so will merge anyway. |
|
@pytorchbot merge -i |
Merge startedYour change will be merged while ignoring the following 7 checks: Lint / Test collect_env (older_python_version, linux.24_04.4x), Lint / Test collect_env (with_torch, linux.24_04.4x), Lint / Test collect_env (without_torch, linux.24_04.4x), pull / linux-jammy-rocm-py3.11 / build, inductor / inductor-cpu-test / test (cpu_inductor_torchbench, 1, 2, mt-l-x86iamx-8-64), inductor / inductor-test-cuda134 / test (inductor_torchbench, 1, 2, mt-l-x86aavx2-11-41-a10g), trunk / linux-noble-rocm-py3.11-mi350 / build Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
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.
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.
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
) 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
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.
spin fixlint)Linked issue or supporting maintainer
supported by @weifengpy
BC-breaking?
No
Agent details (if applicable)