Skip to content

[FSDP] Clear deferred all-gather state after backward - #196460

Closed
sanketpurandare wants to merge 12 commits into
gh/sanketpurandare/4/basefrom
gh/sanketpurandare/4/head
Closed

sanketpurandare wants to merge 12 commits into
gh/sanketpurandare/4/basefrom
gh/sanketpurandare/4/head

Conversation

@sanketpurandare

@sanketpurandare sanketpurandare commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Problem

Implicit forward prefetch overlaps the next all-gather copy-in with the current
all-gather. The input is a view into the all-gather output, so FSDP retains the
current AllGatherResult until its copy-out has completed and the streams that
may reuse those buffers have been ordered after the copy-out event.

A partial grouped forward can miss the normal root post-forward flush. In the
chunked-head pattern, the group forward skips the head and the head later runs
standalone, leaving the final deferred result alive through backward. This PR
originally fixed that lifetime leak by releasing the shared state from root
post-backward.

The first implementation reused the forward-prefetch release operation at root
post-backward. That operation makes both high-priority all-gather streams wait
on the saved forward copy-out event before dropping the retained result. This
is the correct dependency when a subsequent forward all-gather is about to
reuse the buffers, but root post-backward has different ownership: it runs on
the current compute stream after the backward consumers have been enqueued.
Adding communication-stream waits at that boundary introduced a ROCm stream
dependency that prevented queued work from draining.

The pre-existing two-rank test_multi_forward_module exercises the same
FSDP-wrapped inner module twice per forward. On the ROCm MI350 distributed
shard, both ranks reached the final loss comparison and then timed out while
synchronizing outstanding GPU work. The same shard and test pass at the merge
base with the same CI image, and the failure reproduced on all three retries.

Design

Make the cleanup boundary explicit with two internal operations:

Boundary Stream ordering before release
Forward replacement or root post-forward The copy-in and all-gather streams wait on the saved copy-out event.
Root post-backward or iteration reset The current compute stream waits on the saved copy-out event.

release_all_gather_state_for_comm_reuse() owns the first policy. It is used
when the next implicit prefetch may immediately reuse the retained buffers on
either all-gather stream.

release_all_gather_state_on_current_stream() owns the second policy. It is
used after backward and during reset, where the current stream is the lifecycle
boundary. The next root forward already makes both all-gather streams wait on
the current stream before launching implicit prefetch, so this preserves the
required happens-before relationship without adding reverse dependencies at
post-backward.

Both operations enqueue GPU event waits only. There is no host synchronization,
backend-specific conditional, or caller-selected arbitrary wait set. Calling
either operation before lazy initialization remains safe and simply drops an
event-free retained state.

Lifecycle Contract

Caller Cleanup operation Reason
wait_for_unshard() Communication-stream reuse A new forward all-gather may reuse the shared buffers immediately.
Root _post_forward() Communication-stream reuse Flush the final forward result while preserving safe reuse by the communication streams.
Root post-backward callback Current-stream release Backward owns the current stream; the next root forward reestablishes communication-stream ordering.
reset_iter_state() Current-stream release Exception recovery discards iteration state from the current-stream boundary.

The root post-backward cleanup remains independent of is_last_backward.
Gradient accumulation should not retain a stale forward all-gather buffer
between backward calls, but it must release that state using the correct stream
boundary.

Test Plan

  • python test/distributed/_composable/fsdp/test_fully_shard_comm.py TestFSDPCommContext
  • CUDA_VISIBLE_DEVICES=0,1 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShard1DTrainingCompose.test_partial_group_releases_deferred_all_gather_after_backward TestFullyShard1DTrainingCompose.test_reset_iter_state_after_exception TestFullyShard1DTrainingCore.test_multi_forward_module
  • CUDA_VISIBLE_DEVICES=0,1 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShard1DTrainingCore
  • Exact ROCm MI350 distributed shard containing TestFullyShard1DTrainingCore.test_multi_forward_module.
  • lintrunner --config=.lintrunner.toml torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py torch/distributed/fsdp/_fully_shard/_fsdp_state.py test/distributed/_composable/fsdp/test_fully_shard_comm.py test/distributed/_composable/fsdp/test_fully_shard_training.py

AI assistance disclosure:

This change was authored with assistance from an AI coding tool and reviewed by the author.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

✅ You can merge normally! (2 Unrelated Failures)

As of commit 38a6296 with merge base 38e2a2e (image):

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

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

@anijain2305

anijain2305 commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Looks pretty good.

Two comments from AI assisted code review

  • The test doesn't exercise the bug it fixes — test_fully_shard_training.py:2693. It fabricates AllGatherState(cast(Any, None), event) after forward already flushed the real state, so it only proves the new statement runs; it would pass against a bare all_gather_state = None with no stream waits, and never asserts the streams were ordered on the event. The real leak paths are untested: a deferred state re-armed during backward AC recompute (_fsdp_param_group.py:487-497 sets it while _post_forward's flush is gated on iter_forward_root is self), and the chunked-loss/incomplete-root path behind _force_complete_incomplete_states.
  • Gap: forward-only path still leaks. With an incomplete forward root under no_grad/inference, _post_forward's flush is skipped and no backward callback fires, so the buffer is retained until the next forward's copy-out. Same class of bug, uncovered.

@weifengpy

weifengpy commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

is this PR really about AC? Or is it actually bufixing a partial forward bug ? meaning doing forward on model.norm, but not model.head, and ended up with dirty state

fully_shard([model.norm, model.head])
h = model(tokens, skip_head=True)  # Runs norm, skips head
for chunk in h.chunk(4, dim=1):
    logits = model.head(chunk)    # Runs head alone, skips norm

@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

[ghstack-poisoned]
@sanketpurandare

Copy link
Copy Markdown
Contributor Author

@claude provide a critical pr review, check for bugs, soundness of design, test coverage, redundant tests, slop code, cpmpactness of code, api design and provide feedback or suggest changes on how to make it better.

@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Claude finished @sanketpurandare's task in 10m 8s —— View job


The fix is directionally right and the leak it targets is real, but the regression test is vacuous (it fabricates the state after forward already cleared it, so it would pass against a bare = None with no stream waits) and the chosen boundary misses the forward-only/no_grad case the description claims to cover.

Full review — PR #196460

PR Review: #196460

Summary

Clears comm_ctx.all_gather_state (plus the required all-gather-stream waits) from FSDPState._root_post_backward_final_callback so a deferred all-gather armed outside the ordinary post-forward release boundary does not survive the iteration. I confirmed the leak is reachable, so this is not dead code — but the regression test does not exercise it, the fix is incomplete for forward-only iterations, and this is now the third near-verbatim copy of the same release block.

Testing

  • test/distributed/_composable/fsdp/test_fully_shard_training.py:2683-2697 does not exercise the bug. By the time line 2693 runs, _post_forward has already flushed the real deferred state (_fsdp_state.py:338-348 fires because iter_forward_root is self for a single-module root). The test then hand-installs AllGatherState(cast(Any, None), event) and asserts it becomes None. That only proves the new statement executes. It would pass identically against:

    self._comm_ctx.all_gather_state = None   # no waits, no event handling

    which is the part of the change most likely to be wrong. Nothing asserts all_gather_copy_in_stream/all_gather_stream were actually ordered on the event.

  • The real arming paths are untested. Two distinct paths leave the state armed with no flush; neither is covered:

    1. Nested FSDP under non-reentrant AC. On recompute, the inner state is IDLE (its original forward outputs were discarded, so its pre-backward hook never fired), so _pre_forward takes the full path at _fsdp_state.py:310-317 rather than the PRE_BACKWARD early return at :295. The group goes to FORWARD (_fsdp_param_group.py:560-562) and wait_for_unshard arms the state (:486-495). The inner _post_forward then skips the flush because iter_forward_root is the outer root. This is the scenario the summary describes and it is exactly what the test should build.
    2. Partial grouped forward (chunked loss). This is @weifengpy's point, and it checks out. With fully_shard([norm, head]), each standalone head(chunk) call runs the full _pre_forward → pre_forward → wait_for_unshard and arms the state, but get_wrapped_post_hook (_fsdp_state.py:588-598) takes the partial path because modules_to_run is still non-empty, so FSDPState._post_forward never runs and the flush never fires.

    Please answer @weifengpy directly in the description: these are two arming paths for one defect, and the summary currently names only AC. If (2) is in scope, say so and test it; if not, say why.

  • The description overclaims. "The regression test guards both premature release and stale state retention" — it guards neither. There is no assertion that the buffer is still live before the boundary, and the retention check is against a synthetic value. Either add the premature-release half or drop the sentence.

  • Wrong test class. TestFullyShardCudaGraph is for graph-capture tests (see test_two_layer_fully_shard_cudagraph at :2704, which is gated on TEST_CUDA_GRAPH). This test captures no graph. If the CUDA-graph interaction is the motivation, assert it under capture; otherwise move it next to the other comm/lifecycle tests (test_fully_shard_comm.py is the natural home, since that is where the all-gather protocol is tested).

  • Diverges from the file's own device idiom. Neighboring tests use device_type.type and torch.device(device_type.type, self.rank) (:2705-2707); this one hardcodes torch.cuda.set_device / torch.device("cuda", ...). Nothing here is CUDA-specific.

  • reshard_after_forward=False is inert. _lazy_init already sets post_forward_mesh_info = None for the root (_fsdp_state.py:205-207), so the kwarg changes nothing for a single-module root. It reads as load-bearing setup and is not.

  • The fabricated state is fragile. cast(Any, None) as all_gather_result means any future code on the backward path that legitimately reads .all_gather_result turns this into an obscure AttributeError instead of a meaningful failure. A test built on a genuinely-armed state needs neither cast nor the AllGatherState import.

Fix this →

Code Quality

  • _fsdp_state.py:427-433 is the third copy of the same release sequence. The identical "wait both all-gather streams on the event, then drop the state" logic already exists at _fsdp_state.py:340-347 (_post_forward) and _fsdp_state.py:499-502 (_reset_iter_state), and FSDPParamGroup._wait_all_gather_streams_on_event (_fsdp_param_group.py:501-506) already implements the stream-pair wait including the None check. Since the state lives on FSDPCommContext, the release belongs there as one method — e.g. FSDPCommContext.release_all_gather_state() — and all three sites collapse to a one-line call. That is strictly more compact than the diff and removes the standing risk of the three copies drifting apart. Note they have already drifted: _reset_iter_state waits current_stream, while the other two wait the two all-gather streams. Consolidating forces that discrepancy to be resolved deliberately rather than left as an accident.

  • The if all_gather_state.event is not None: guard is unreachable. The only production construction site is _fsdp_param_group.py:493-495, which always passes an event created via device_handle.Event() + .record(). The Optional on AllGatherState.event (:133) is inherited from AllReduceState, which has a genuine None case; AllGatherState does not. The pre-existing sibling at :340-347 correctly omits the check. Either drop it, or get it for free by routing through the shared helper above — but do not add a bespoke guard that implies a None case exists.

  • No comment, where the reasoning is genuinely non-obvious. The description's best content — why root post-backward is the correct boundary (earliest point shared by ordinary and recomputed forward once all backward consumers are done) — exists only in the PR body and will be invisible to the next reader. The sibling block at :341-342 cross-references [Note: Overlapping all-gather copy-in and all-gather]; this one should carry a two-line equivalent. Per CLAUDE.md, this is precisely the case comments are for: global context that cannot be inferred locally.

  • Unexplained placement outside is_last_backward. The new block sits between two if self._state_ctx.is_last_backward: guards (:424 and :434) but is itself unconditional. That looks correct to me — releasing early is always safe, and under gradient accumulation you want the buffer back sooner — but a reader cannot tell whether it was deliberate or an oversight. State the intent.

API Design

  • The boundary is incomplete, and the stated goal is not fully met. Cleanup is reachable only through _root_post_backward_final_callback, which is queued from _pre_backward (:389), which is only reached via hooks that _register_pre_backward_hook declines to register when not torch.is_grad_enabled() (:448-449). So on a forward-only iteration — eval, inference, no_grad — nothing clears the state. Combined with the partial-forward arming path above, a chunked forward under no_grad leaves the state armed until the next forward's wait_for_unshard flushes it (_fsdp_param_group.py:439-442). That directly contradicts "preventing buffers and events from leaking into the next iteration or CUDA-graph capture": capture a forward-only region and the state is still there.

    Two ways forward, and I think the second is right:

    • Suppress arming when no flush boundary will be crossed (e.g. skip the deferral at _fsdp_param_group.py:486-495 when is_bw(), or when the group's post-hook will take the partial path). One condition at one site, and it covers the forward-only path too — but it costs the copy-in/all-gather overlap across a recompute chain, which is exactly what the deferral buys. I do not recommend this.
    • Keep the release-at-a-later-boundary approach in this PR, and either add the forward-only boundary or scope the claim honestly. If the forward-only leak is acceptable because it is bounded to one buffer until the next forward, say that in the description and drop the CUDA-graph-capture claim. Right now the summary reads as though the class of bug is closed, and it is not.

Recommendation

Request Changes

A bug fix whose regression test cannot fail is the blocker: replace the fabricated-state test with one that genuinely arms the deferred state (nested FSDP + non-reentrant AC, and/or the partial grouped forward), and assert the stream ordering rather than just the None. Secondary but worth doing in the same pass: collapse the three duplicated release blocks into one FSDPCommContext method (which also disposes of the unreachable event is not None guard), add the comment explaining the boundary choice, and either close or explicitly scope the forward-only path so the description matches what the code does.

· branch `gh/sanketpurandare/4/head`

@sanketpurandare

Copy link
Copy Markdown
Contributor Author

Replaced the synthetic AllGatherState fixture with the real grouped partial-forward path: a grouped norm/head forward skips the head, standalone chunked head calls genuinely leave deferred all-gather state armed, and root post-backward releases it. A separate helper-contract test proves that every requested stream waits on the recorded event before ownership is cleared. The implementation now centralizes release in FSDPCommContext, and the description explicitly scopes the fix to training iterations that reach root post-backward; forward-only partial execution may retain one bounded result until the next forward. The focused two-rank regression passes.

@sanketpurandare

Copy link
Copy Markdown
Contributor Author

This is a partial grouped-forward lifecycle bug, not an AC-specific fix. I updated the title, description, and regression around the fully_shard([norm, head]) pattern: the grouped forward skips the head, standalone head calls arm the deferred state, and the root post-backward boundary releases it. AC recomputation can reach the same stale-state boundary, but the PR no longer presents AC as the defining cause.

@sanketpurandare

Copy link
Copy Markdown
Contributor Author

@claude Reworked the PR around the concrete grouped partial-forward defect. The test now genuinely arms deferred state through standalone head calls, proves it is live before backward, and proves root post-backward clears it; stream ordering is covered independently with recording event/stream doubles. The three release sequences now share FSDPCommContext.release_all_gather_state() while retaining each boundary's required wait streams. The fabricated state, inert reshard_after_forward=False, CUDA-graph test placement, hard-coded CUDA idiom, and AC-specific overclaims were removed. The PR explicitly retains the bounded forward-only limitation. The focused two-rank regression and helper test pass.

@claude

claude Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Claude finished @sanketpurandare's task in 12m 59s —— View job


All three follow-ups check out — the reset_iter_state test now asserts the actual outcome instead of a mock call, the pre-lazy-init handling is one guard, and the docstring/CPU-coverage/comment items are done; the only thing left is a redundant re-declaration of all_gather_state inside lazy_init.

Full re-review — PR #196460

PR Review: #196460

What I verified in this revision

  • test_reset_iter_state_after_exception now asserts the outcome (test_fully_shard_training.py:1330-1333). The patch.object(..., wraps=...) / assert_called_once_with() machinery is gone; it reads comm_ctx off the root state and asserts non-None → reset_iter_state() → None. I confirmed the pre-assertion is a true statement rather than an accident: the raise lands inside model.body, which is after the root state's _pre_forward → FSDPParamGroup.pre_forward → unshard / wait_for_unshard (_fsdp_param_group.py:576-577), and the arming condition at :505-514 is not async_op and _training_state == FORWARD and world_size > 1. unshard_async_op defaults False so async_op is False, the group is FORWARD, and world_size is 2 on both the accelerator and CPU paths (TestFullyShard1DTrainingCompose.world_size returns 2 for cpu), so the state is genuinely armed at the raise. No unittest.mock import was left dangling — the file's only other unittest uses are unittest.skipIf.

  • One stream guard, not two (_fsdp_param_group.py:131-139). wait_all_gather_streams_on_event is now if event is None: return + a single hasattr(self, "all_gather_copy_in_stream") early return, which is correct because both streams are created together in lazy_init (:87-92). The _reset_iter_state current_stream local is still used for the reduce-scatter and post-reduce waits (_fsdp_state.py:494-499), so it did not become dead.

  • Docstring scope broadened (:132): "Order both all-gather streams after the given event" now covers the two _reshard_after_forward_event callers (:411-413, :552-556) as well as the copy-out event, and release_all_gather_state's "streams that reuse its buffers" is accurate for the producers being ordered.

  • allow_cpu=True + docstring on the new training test (:950-952), matching its neighbours, and the leak-window comment at :963-964 explains why assertIsNotNone intentionally pins pre-fix behaviour. That was the non-obvious failure mode I flagged.

  • Class-scope all_gather_state (:76) makes FSDPCommContext well-formed before lazy_init, so release_all_gather_state and wait_all_gather_streams_on_event no longer disagree about whether a pre-init context is a valid receiver — and it is what lets the unit test at test_fully_shard_comm.py:105-109 construct a bare context. The forward reference to AllGatherState (defined at :150) is fine under from __future__ import annotations (:2).

  • Nothing regressed in the release contract. release_all_gather_state() is still argument-free with exactly four call sites (_fsdp_param_group.py:461, _fsdp_state.py:342, :427, :493), the stream-pair literal appears once, and _wait_all_gather_streams_on_event has no remaining references anywhere in the tree.

Remaining comment (non-blocking)

  • lazy_init re-declares all_gather_state (_fsdp_param_group.py:109) now that :76 declares it at class scope. Two annotated declarations of the same attribute in one class is a small invariant-duplication hazard — if the type ever changes, one can be updated and the other missed. Since lazy_init runs once per context, the assignment is not resetting anything; drop line 109 and leave the surrounding comment at :106-108, which still applies to reduce_scatter_states.

    Fix this →

  • Optional: the hasattr early-return in wait_all_gather_streams_on_event is the one branch with no coverage. A two-line addition to TestFSDPCommContext (bare FSDPCommContext(), armed state, assert release_all_gather_state() does not raise and clears) would pin the pre-lazy-init contract that FSDPModule.unshard() depends on. Take it or leave it.

Recommendation

Approve — consistent with @fegin's stamp. The wait set is owned by the event's policy in exactly one place, all four boundaries share it, and each test now fails for the right reason: the comm-context test pins the two stream identities, and both lifecycle tests assert armed-then-released rather than an implementation detail. The lazy_init duplicate line is the only thing I would still change, and it is cosmetic.

Note: static review only — I did not build PyTorch or execute the distributed tests in this environment, so I am relying on your reported test and lint results.

· branch `gh/sanketpurandare/4/head`

A partial grouped forward can leave the final implicit-prefetch all-gather
result retained because the grouped post-forward hook does not run until every
module in the group has executed. In the chunked-loss pattern, the skipped head
then runs standalone, so the deferred state can remain live through backward.

Release that state from the root post-backward callback. The communication
context now owns the copy-out event's ordering policy: both streams that may
reuse the buffers wait on the event before the result is released. Ordinary
post-forward, post-backward, next-forward replacement, and exception recovery
all use the same argument-free boundary, so callers cannot choose an incomplete
wait set.

This closes training iterations that reach root post-backward. A forward-only
partial invocation has no post-backward callback and may retain one bounded
result until the next forward; that behavior is outside this change.

Test Plan:

```bash
python test/distributed/_composable/fsdp/test_fully_shard_comm.py TestFSDPCommContext.test_release_all_gather_state_orders_all_gather_streams
CUDA_VISIBLE_DEVICES=0,1 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShard1DTrainingCompose.test_partial_group_releases_deferred_all_gather_after_backward TestFullyShard1DTrainingCompose.test_reset_iter_state_after_exception
lintrunner --config=.lintrunner.toml torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py torch/distributed/fsdp/_fully_shard/_fsdp_state.py test/distributed/_composable/fsdp/test_fully_shard_comm.py test/distributed/_composable/fsdp/test_fully_shard_training.py
```

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.

[ghstack-poisoned]
[ghstack-poisoned]
@anijain2305
anijain2305 removed their request for review September 17, 2026 19:55
A partial grouped forward can leave the final implicit-prefetch all-gather
result retained because the grouped post-forward hook does not run until every
module in the group has executed. In the chunked-loss pattern, the skipped head
then runs standalone, so the deferred state can remain live through backward.

Release that state from the root post-backward callback. The communication
context now owns the copy-out event's ordering policy: both streams that may
reuse the buffers wait on the event before the result is released. Ordinary
post-forward, post-backward, next-forward replacement, and exception recovery
all use the same argument-free boundary, so callers cannot choose an incomplete
wait set.

This closes training iterations that reach root post-backward. A forward-only
partial invocation has no post-backward callback and may retain one bounded
result until the next forward; that behavior is outside this change.

Test Plan:

```bash
python test/distributed/_composable/fsdp/test_fully_shard_comm.py TestFSDPCommContext.test_release_all_gather_state_orders_all_gather_streams
CUDA_VISIBLE_DEVICES=0,1 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShard1DTrainingCompose.test_partial_group_releases_deferred_all_gather_after_backward TestFullyShard1DTrainingCompose.test_reset_iter_state_after_exception
lintrunner --config=.lintrunner.toml torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py torch/distributed/fsdp/_fully_shard/_fsdp_state.py test/distributed/_composable/fsdp/test_fully_shard_comm.py test/distributed/_composable/fsdp/test_fully_shard_training.py
```

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.

[ghstack-poisoned]
A partial grouped forward can leave the final implicit-prefetch all-gather
result retained because the grouped post-forward hook does not run until every
module in the group has executed. In the chunked-loss pattern, the skipped head
then runs standalone, so the deferred state can remain live through backward.

Release that state from the root post-backward callback. The communication
context now owns the copy-out event's ordering policy: both streams that may
reuse the buffers wait on the event before the result is released. Ordinary
post-forward, post-backward, next-forward replacement, and exception recovery
all use the same argument-free boundary, so callers cannot choose an incomplete
wait set.

This closes training iterations that reach root post-backward. A forward-only
partial invocation has no post-backward callback and may retain one bounded
result until the next forward; that behavior is outside this change.

Test Plan:

```bash
python test/distributed/_composable/fsdp/test_fully_shard_comm.py TestFSDPCommContext.test_release_all_gather_state_orders_all_gather_streams
CUDA_VISIBLE_DEVICES=0,1 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShard1DTrainingCompose.test_partial_group_releases_deferred_all_gather_after_backward TestFullyShard1DTrainingCompose.test_reset_iter_state_after_exception
lintrunner --config=.lintrunner.toml torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py torch/distributed/fsdp/_fully_shard/_fsdp_state.py test/distributed/_composable/fsdp/test_fully_shard_comm.py test/distributed/_composable/fsdp/test_fully_shard_training.py
```

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.

[ghstack-poisoned]
A partial grouped forward can leave the final implicit-prefetch all-gather
result retained because the grouped post-forward hook does not run until every
module in the group has executed. In the chunked-loss pattern, the skipped head
then runs standalone, so the deferred state can remain live through backward.

Release that state from the root post-backward callback. The communication
context now owns the copy-out event's ordering policy: both streams that may
reuse the buffers wait on the event before the result is released. Ordinary
post-forward, post-backward, next-forward replacement, and exception recovery
all use the same argument-free boundary, so callers cannot choose an incomplete
wait set.

This closes training iterations that reach root post-backward. A forward-only
partial invocation has no post-backward callback and may retain one bounded
result until the next forward; that behavior is outside this change.

Test Plan:

```bash
python test/distributed/_composable/fsdp/test_fully_shard_comm.py TestFSDPCommContext.test_release_all_gather_state_orders_all_gather_streams
CUDA_VISIBLE_DEVICES=0,1 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShard1DTrainingCompose.test_partial_group_releases_deferred_all_gather_after_backward TestFullyShard1DTrainingCompose.test_reset_iter_state_after_exception
lintrunner --config=.lintrunner.toml torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py torch/distributed/fsdp/_fully_shard/_fsdp_state.py test/distributed/_composable/fsdp/test_fully_shard_comm.py test/distributed/_composable/fsdp/test_fully_shard_training.py
```

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.

[ghstack-poisoned]
A partial grouped forward can leave the final implicit-prefetch all-gather
result retained because the grouped post-forward hook does not run until every
module in the group has executed. In the chunked-loss pattern, the skipped head
then runs standalone, so the deferred state can remain live through backward.

Release that state from the root post-backward callback. The communication
context now owns the copy-out event's ordering policy: both streams that may
reuse the buffers wait on the event before the result is released. Ordinary
post-forward, post-backward, next-forward replacement, and exception recovery
all use the same argument-free boundary, so callers cannot choose an incomplete
wait set.

This closes training iterations that reach root post-backward. A forward-only
partial invocation has no post-backward callback and may retain one bounded
result until the next forward; that behavior is outside this change.

Test Plan:

```bash
python test/distributed/_composable/fsdp/test_fully_shard_comm.py TestFSDPCommContext.test_release_all_gather_state_orders_all_gather_streams
CUDA_VISIBLE_DEVICES=0,1 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShard1DTrainingCompose.test_partial_group_releases_deferred_all_gather_after_backward TestFullyShard1DTrainingCompose.test_reset_iter_state_after_exception
lintrunner --config=.lintrunner.toml torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py torch/distributed/fsdp/_fully_shard/_fsdp_state.py test/distributed/_composable/fsdp/test_fully_shard_comm.py test/distributed/_composable/fsdp/test_fully_shard_training.py
```

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.

[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #196706

@sanketpurandare sanketpurandare added ciflow/trunk Trigger trunk jobs on your pull request ciflow/rocm labels Sep 22, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 22, 2026

Copy link
Copy Markdown

Warning: Unknown label ciflow/rocm.
Currently recognized labels are

  • ciflow/b200
  • ciflow/b200-distributed
  • ciflow/b200-symm-mem
  • ciflow/binaries
  • ciflow/binaries_libtorch
  • ciflow/binaries_wheel
  • ciflow/docker
  • ciflow/dtensor
  • ciflow/h100
  • ciflow/h100-cutlass-backend
  • ciflow/h100-distributed
  • ciflow/h100-symm-mem
  • ciflow/inductor
  • ciflow/inductor-cu126
  • ciflow/inductor-micro-benchmark
  • ciflow/inductor-micro-benchmark-cpu-x86
  • ciflow/inductor-pallas
  • ciflow/inductor-perf-compare
  • ciflow/inductor-perf-test-nightly-rocm-mi300
  • ciflow/inductor-perf-test-nightly-rocm-mi350
  • ciflow/inductor-perf-test-nightly-x86-zen
  • ciflow/inductor-perf-test-nightly-xpu
  • ciflow/inductor-periodic
  • ciflow/inductor-rocm-mi200
  • ciflow/inductor-rocm-mi300
  • ciflow/mps
  • ciflow/native-aot
  • ciflow/nightly
  • ciflow/op-benchmark
  • ciflow/periodic
  • ciflow/periodic-rocm-mi200
  • ciflow/periodic-rocm-mi300
  • ciflow/periodic-strict
  • ciflow/pull
  • ciflow/riscv64
  • ciflow/rocm-mi200
  • ciflow/rocm-mi300
  • ciflow/rocm-nightly
  • ciflow/rocm-preview
  • ciflow/rocm-rx7900
  • ciflow/s390
  • ciflow/slow
  • ciflow/slow-rocm-mi200
  • ciflow/torchtitan
  • ciflow/triton_binaries
  • ciflow/trunk
  • ciflow/tsan
  • ciflow/unstable
  • ciflow/win-arm64
  • ciflow/xpu

Please add the new label to .github/pytorch-probot.yml

## Problem

Implicit forward prefetch overlaps the next all-gather copy-in with the current
all-gather. The input is a view into the all-gather output, so FSDP retains the
current `AllGatherResult` until its copy-out has completed and the streams that
may reuse those buffers have been ordered after the copy-out event.

A partial grouped forward can miss the normal root post-forward flush. In the
chunked-head pattern, the group forward skips the head and the head later runs
standalone, leaving the final deferred result alive through backward. This PR
originally fixed that lifetime leak by releasing the shared state from root
post-backward.

The first implementation reused the forward-prefetch release operation at root
post-backward. That operation makes both high-priority all-gather streams wait
on the saved forward copy-out event before dropping the retained result. This
is the correct dependency when a subsequent forward all-gather is about to
reuse the buffers, but root post-backward has different ownership: it runs on
the current compute stream after the backward consumers have been enqueued.
Adding communication-stream waits at that boundary introduced a ROCm stream
dependency that prevented queued work from draining.

The pre-existing two-rank `test_multi_forward_module` exercises the same
FSDP-wrapped inner module twice per forward. On the ROCm MI350 distributed
shard, both ranks reached the final loss comparison and then timed out while
synchronizing outstanding GPU work. The same shard and test pass at the merge
base with the same CI image, and the failure reproduced on all three retries.

## Design

Make the cleanup boundary explicit with two internal operations:

| Boundary | Stream ordering before release |
| --- | --- |
| Forward replacement or root post-forward | The copy-in and all-gather streams wait on the saved copy-out event. |
| Root post-backward or iteration reset | The current compute stream waits on the saved copy-out event. |

`release_all_gather_state_for_comm_reuse()` owns the first policy. It is used
when the next implicit prefetch may immediately reuse the retained buffers on
either all-gather stream.

`release_all_gather_state_on_current_stream()` owns the second policy. It is
used after backward and during reset, where the current stream is the lifecycle
boundary. The next root forward already makes both all-gather streams wait on
the current stream before launching implicit prefetch, so this preserves the
required happens-before relationship without adding reverse dependencies at
post-backward.

Both operations enqueue GPU event waits only. There is no host synchronization,
backend-specific conditional, or caller-selected arbitrary wait set. Calling
either operation before lazy initialization remains safe and simply drops an
event-free retained state.

## Lifecycle Contract

| Caller | Cleanup operation | Reason |
| --- | --- | --- |
| `wait_for_unshard()` | Communication-stream reuse | A new forward all-gather may reuse the shared buffers immediately. |
| Root `_post_forward()` | Communication-stream reuse | Flush the final forward result while preserving safe reuse by the communication streams. |
| Root post-backward callback | Current-stream release | Backward owns the current stream; the next root forward reestablishes communication-stream ordering. |
| `reset_iter_state()` | Current-stream release | Exception recovery discards iteration state from the current-stream boundary. |

The root post-backward cleanup remains independent of `is_last_backward`.
Gradient accumulation should not retain a stale forward all-gather buffer
between backward calls, but it must release that state using the correct stream
boundary.

## Test Plan

- `python test/distributed/_composable/fsdp/test_fully_shard_comm.py TestFSDPCommContext`
- `CUDA_VISIBLE_DEVICES=0,1 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShard1DTrainingCompose.test_partial_group_releases_deferred_all_gather_after_backward TestFullyShard1DTrainingCompose.test_reset_iter_state_after_exception TestFullyShard1DTrainingCore.test_multi_forward_module`
- `CUDA_VISIBLE_DEVICES=0,1 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShard1DTrainingCore`
- Exact ROCm MI350 distributed shard containing `TestFullyShard1DTrainingCore.test_multi_forward_module`.
- `lintrunner --config=.lintrunner.toml torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py torch/distributed/fsdp/_fully_shard/_fsdp_state.py test/distributed/_composable/fsdp/test_fully_shard_comm.py test/distributed/_composable/fsdp/test_fully_shard_training.py`

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.

[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #196706

pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
…ns (#196461)

Packed flash- and efficient-attention backward expand the output gradient using
the value-head dimension, which can differ from the query/key-head dimension
for MLA. Propagate that dimension through both packed-sequence FLOP formulas
and report the actual and expected shapes when validation fails.

This changes FLOP accounting only. It does not change attention kernels, tensor
shapes, dispatch, or model execution.

Tests parameterize the shared mixed-dimension contract over flash and efficient
attention, pin the literal backward FLOP count, and exercise the shape
diagnostic for both layouts.

Test Plan:
- `python test/test_flop_counter.py -k nested_attn_backward_flops_with_unequal_qk_value_dims -v`
- `python test/test_flop_counter.py TestFlopCounter -v`
- `lintrunner --config=.lintrunner.toml torch/utils/flop_counter.py test/test_flop_counter.py`

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.
Pull Request resolved: #196461
Approved by: https://github.com/fegin, https://github.com/liangel-02
ghstack dependencies: #196460
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
Selective activation checkpointing can replay an ordered-effect operation when an eager policy recomputes it. That policy takes precedence over the generic AOT partitioner safeguard, so the side effect may execute once in forward and again during backward.

Cache non-aliasing ordered effects that are valid SAC cache boundaries whenever the eager policy does not explicitly require recomputation. This includes CPU-offload policies: eager CPU offload remains unimplemented, but those policies promise to save rather than replay. Explicit MUST_RECOMPUTE remains authoritative in eager mode.

AOTAutograd cannot safely move a forward effect into backward after functionalization has established the two effect-token chains. Reject compiled MUST_RECOMPUTE effects at partition time with an actionable error instead of producing a saved None token and failing in the autograd runtime wrapper.

Keep actual save policies on the cheap path. For policies that would otherwise replay an operation, the registry lookup precedes the schema alias walk. Raw c10d launches remain excluded because they mutate inputs and return asynchronous Work handles, so their return value is not a valid cache boundary; functional collectives remain the supported graph boundary.

Test Plan:
- python test/test_autograd.py TestSelectiveActivationCheckpoint -v
- python test/dynamo/test_activation_checkpointing.py -k selective_checkpoint_preserves_registered_effect -v
- python test/functorch/test_aotdispatch.py -k force_save_effectful_ops -v
- lintrunner --config=.lintrunner.toml torch/_higher_order_ops/effects.py torch/utils/checkpoint.py torch/_functorch/partitioners.py test/test_autograd.py test/dynamo/test_activation_checkpointing.py

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.
Pull Request resolved: #196956
Approved by: https://github.com/soulitzer
ghstack dependencies: #196460, #196461
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
## Background

Pipeline runtimes sometimes need the global logical stage and current
microbatch at the exact boundary where a stage module executes. A physical PP
rank is insufficient under virtual pipeline parallelism because one rank owns
multiple logical stages, while the microbatch identity belongs to runtime
execution rather than the model's input schema.

The previous revision transported this information through a reserved model
keyword and added an enable flag to every schedule. That made scheduler control
state part of the model signature, required kwargs copies and collision checks,
excluded traced stages, and coupled dynamic metadata inference to schedule
configuration.

## Design

`PipelineStageInfo` remains a frozen, slotted, keyword-only value containing the
global logical stage, step-local microbatch, and metadata-probe marker. A stage
now exposes `register_forward_context(factory)`, where the factory receives that
value and returns a fresh context manager around the stage computation.

The first version deliberately permits one live registration. A second
registration fails with an actionable error, and removing the returned
`RemovableHandle` permits replacement. This keeps ownership explicit and leaves
a compatibility-preserving path to multiple registrations if a concrete need
appears.

The default path performs only an empty-registry check: it constructs no info
object, copies no kwargs, and allocates no context manager. Registered runtime
forwards wrap the existing `forward_maybe_with_nosync` call. Dynamic metadata
inference wraps its representative `_compute_outputs` call with microbatch zero
and `is_metadata_inference=True`; static metadata setup does not execute the
factory. Manual and traced stages share the implementation through the stage
base class, so compiled and exported submodules retain their original graph
signatures.

Context teardown follows ordinary context-manager exception semantics. A
context is not allowed to suppress an exception raised by the stage module;
doing so produces an explicit runtime error instead of continuing without a
forward result.

## Boundaries

The registration is attached to `forward_one_chunk`, not schedule IR. Custom
actions receive it when they delegate to that method and otherwise own their
execution context. CUDA graph capture executes the Python context while
recording work, but replay does not re-enter Python; consumers must bind
replay-stable state during capture.

The implementation is built cleanly from the parent of the prior revision. It
adds no schedule constructor option, reserved keyword, schedule voting state,
or `_IR.py` behavior.

## Test Plan

```bash
python test/distributed/pipelining/test_stage.py PipelineStageForwardContextTest
python test/distributed/pipelining/test_stage.py PipelineStageMetadataInferenceTest
NCCL_DEBUG=WARN CUDA_VISIBLE_DEVICES=0,1,2,3 \
  python test/distributed/pipelining/test_stage.py
python test/distributed/pipelining/test_schedule.py
NCCL_DEBUG=WARN CUDA_VISIBLE_DEVICES=0,1,2,3 \
  python test/distributed/pipelining/test_schedule_multiproc.py
lintrunner --config=.lintrunner.toml \
  docs/source/distributed.pipelining.md \
  test/distributed/pipelining/test_schedule_multiproc.py \
  test/distributed/pipelining/test_stage.py \
  torch/distributed/pipelining/__init__.py \
  torch/distributed/pipelining/stage.py
sphinx-build -M html docs/source docs/build -j 8 -WT --keep-going
```

The Sphinx coverage report is 100% with zero undocumented Python objects. The
local full-tree post-check separately reports two pre-existing optional c10d
backend exports below this stack; the pipelining API introduced here is fully
documented.

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.
Pull Request resolved: #196462
Approved by: https://github.com/SherlockNoMad
ghstack dependencies: #196460, #196461, #196956
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
`PipelineStage` previously allocated one activation and gradient receive buffer
for every microbatch during setup. Those tensors remained live for the entire
step, even though each receive destination only needs to exist from the receive
action until the corresponding stage computation takes ownership.

Allocate receive buffers immediately before posting each receive and transfer
the reference to compute when it is consumed. Keep the receive descriptor and
its ownership transitions in `_recv_buffers.py`; stage execution imports that
storage primitive and remains responsible for peer resolution and P2P operation
construction.

Resolve every source rank before taking ownership, and make allocation plus P2P
operation construction transactional within each receive batch. When a schedule
timestep contains multiple receive batches, a failure before P2P launch also
releases buffers acquired by earlier batches in that timestep. Same-rank
V-schedule handoffs prepare and validate a complete buffer batch before assigning
any descriptor, so an invalid later input cannot strand earlier ownership.

Missing gradients are represented by missing tensor metadata at the schedule
boundary, so allocation and consumption are total over valid buffer states and
return `Tensor` rather than `Tensor | None`.

A buffer left owned after an incomplete step may still have P2P work writing to
it. Descriptor regeneration therefore fails closed across schedule modes:
callers must destroy the process group, then reconstruct the stages and schedule
before retrying. Recreating only a schedule or switching between train and eval
does not make the storage safe to reuse.

Received DTensors are reconstructed only after communication has completed, so
transferring ownership before reconstruction remains safe if reconstruction
fails. Effective gradient requirements are applied at consumption time.
Successful sequential, interleaved, V-shaped, and None-gradient schedules drain
every descriptor.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py ScheduleTest.test_stage_recv_buffer_allocation_and_consumption ScheduleTest.test_recv_info_rejects_invalid_state_transitions ScheduleTest.test_stage_recv_construction_is_transactional ScheduleTest.test_same_rank_recv_assignment_is_transactional ScheduleTest.test_timestep_recv_validation_releases_prior_batches`
- `python test/distributed/pipelining/test_stage.py PipelineStageMetadataInferenceTest.test_recv_metadata_reinit_rejects_owned_buffers`
- `NCCL_DEBUG=WARN CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py ScheduleTest.test_v_shape_schedules_schedule_class0 ScheduleTest.test_v_shape_schedules_schedule_class1 ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass0_pattern_first_false_then_true ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass1_pattern_first_true_then_false ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass2_pattern_first_false_then_true ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass2_pattern_first_true_then_false`
- `lintrunner --config=.lintrunner.toml torch/distributed/pipelining/_recv_buffers.py torch/distributed/pipelining/stage.py torch/distributed/pipelining/schedules.py test/distributed/pipelining/test_schedule.py test/distributed/pipelining/test_schedule_multiproc.py`

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.
Pull Request resolved: #196463
Approved by: https://github.com/SherlockNoMad
ghstack dependencies: #196460, #196461, #196956, #196462
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
…6464)

Pipeline runtimes and memory planners need a deterministic way to bound the storage retained from forward through backward. Expose a schedule analysis that derives inclusive activation lifetimes and assigns the lowest reusable logical slot without allocating storage.

A forward action starts a lifetime. Full backward releases it; for split backward, input backward leaves the activation live and weight backward releases it. The result supports independent stage/microbatch lifetimes or one conservative lifetime per microbatch across selected virtual stages. It exposes the `(stage_index, microbatch_index) -> slot_id` mapping and the effective lifetime behind each assignment.

The greedy interval coloring remains deterministic and minimal for interval graphs. Tests use an independent overlap oracle, prove the input-versus-weight-backward release boundary, cover both granularities, and exercise compound actions and the real DualPipeV schedule.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py -k pipeline_activation_liveness`
- `python test/distributed/pipelining/test_schedule.py`
- `lintrunner --config=.lintrunner.toml torch/distributed/pipelining/schedules.py torch/distributed/pipelining/__init__.py test/distributed/pipelining/test_schedule.py docs/source/distributed.pipelining.md`
- Strict Sphinx build of `docs/source/distributed.pipelining.md`

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.
Pull Request resolved: #196464
Approved by: https://github.com/SherlockNoMad
ghstack dependencies: #196460, #196461, #196956, #196462, #196463
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
`ProcessGroup::splitGroup` cloned the rendezvous Store for every child process
group. Pipeline schedules can create hundreds of directed child communicators,
turning those clones into hundreds of TCPStore connections per rank. This also
differs from `new_group()`, whose sibling groups have long used uniquely
prefixed namespaces over one shared Store connection.

Construct each child namespace directly over the parent Store and pass that
prefixed Store through `Backend::split`. Prefixes preserve key isolation while
the backend owns connection isolation. Backends that perform blocking
rendezvous or mutate connection-global state such as the timeout must clone the
Store first.

The nccl2 and nccl-legacy split implementations retain the supplied Store
because both initialize the child communicator with `ncclCommSplit` before
returning. nccl2 deliberately does not inherit `enable_reconfigure`, whose
blocking rendezvous is incompatible with the shared connection. Legacy NCCL
merge remains the narrow backend-owned exception: it returns an uninitialized
child whose first collective may block in `broadcastUniqueNCCLID()`, so it keeps
an independent connection. Gloo likewise preserves its construction-time
clone.

The parent and NCCL split children now share live connection-global state. In
particular, changing a child Store timeout affects its parent and siblings, and
opt-in NCCL error-propagation polling shares that connection. Hybrid children
still open a connection for their Gloo leg, while nested NCCL splits add only
namespaces and no new Store connections.

Add CPU boundary coverage for the exact prefixed Store identity and clone count,
plus Gloo option preservation and a legacy NCCL regression that pins the
retained merge clone. Existing legacy NCCL and nccl2 split tests cover
successful communication.

Test Plan:
- `python test/distributed/test_c10d_common.py SplitGroupOptionsTest.test_split_group_passes_prefixed_parent_store_to_backend SplitGroupOptionsTest.test_split_group_clones_parent_options SplitGroupOptionsTest.test_split_group_opts_apply_to_default_backend_only`
- `python test/distributed/test_c10d_gloo.py CommTest.test_split_group_keeps_gloo_options`
- `python test/distributed/test_c10d_nccl.py ProcessGroupNCCLGroupTest.test_merge_group_clones_store_for_uninitialized_child ProcessGroupNCCLGroupTest.test_comm_split_group_backend_filter`
- `python test/distributed/test_c10d_nccl2.py ProcessGroupNCCL2ObservabilityTest.test_split_group_child_global_ranks`
- `lintrunner --config=.lintrunner.toml test/distributed/test_c10d_common.py test/distributed/test_c10d_gloo.py test/distributed/test_c10d_nccl.py torch/csrc/distributed/c10d/Backend.hpp torch/csrc/distributed/c10d/ProcessGroup.cpp torch/csrc/distributed/c10d/ProcessGroupNCCL.cpp torch/csrc/distributed/c10d/nccl2/ProcessGroupNCCL.cpp torch/distributed/distributed_c10d.py`

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.
Pull Request resolved: #196665
Approved by: https://github.com/d4l3k
ghstack dependencies: #196460, #196461, #196956, #196462, #196463, #196464
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
Pipeline schedules can issue communication for several logical stages from one
physical rank. When unrelated edges share one communicator FIFO, skew between
looped schedule ranks can create cross-edge ordering cycles. Construct the P2P
communicators only after the schedule has finalized its logical-stage placement,
then isolate every used direction of every physical edge.

| Concern | Before | After |
| --- | --- | --- |
| Communicator ownership | Pipeline traffic shared the parent communicator or groups derived before final placement. | The finalized stage-to-rank assignment determines one child per directed physical edge. |
| Direction identity | A peer or broad forward/backward direction did not uniquely identify the FIFO. | Children are keyed by `(source_group_rank, destination_group_rank)`. |
| Virtual stages | Repeated stage-level setup obscured whether every local stage used one complete map. | The schedule validates all local stages, builds once, and attaches one shared map. |
| First P2P use | A transport path could first be exercised during model execution or capture. | Every directed child is preconnected once during schedule initialization. |
| Dynamic metadata | Metadata always used the shared parent group. | Metadata follows the same directed child as the corresponding stage edge. |
| Lifecycle | P2P readiness was inferred from forward-metadata initialization. | The schedule tracks P2P initialization independently from metadata reinference. |
| Terminology | “Warmup” referred to metadata voting, communicator setup, and model warmup. | Parent initialization, child splitting, P2P preconnection, and runtime model warmup are distinct. |

| Component | Responsibility | Does not own |
| --- | --- | --- |
| Pipeline schedule | Validate the finalized assignment and orchestrate one-time setup. | Individual runtime `P2POp` construction. |
| `_p2p.py` | Validate stage placement, derive split rounds, create/cache children, and preconnect their P2P paths. | Model metadata policy. |
| Pipeline stage | Resolve a logical source/destination to its child and construct runtime operations. | Process-group creation. |
| Parent process group | Setup agreement and collective source for `split_group`. | Directed activation or gradient traffic when per-edge mode is enabled. |
| Directed child | One physical source-to-destination FIFO. | CUDA-graph or model warmup policy. |
| Outer runtime | Model warmup, CUDA-graph capture, and replay. | PP group construction or first-use transport setup. |

| Frontend and metadata mode | Agreement | P2P setup |
| --- | --- | --- |
| Manual, static | Reduce local static capability over the parent. | Create and preconnect directed children. |
| Manual, dynamic | Reduce the dynamic requirement over the parent. | Use the same children; exchange inferred metadata through them. |
| Traced | Metadata is already available from tracing. | Initialize the parent, then create and preconnect the same children. |
| Fake process group, static | Validate the local static contract. | Build only the logical edge map; perform no real communication. |
| Fake process group, dynamic | Reject with an actionable diagnostic. | A fake group cannot exchange runtime metadata. |

Derive the physical rank assigned to every logical stage, collapse repeated
logical adjacencies onto physical rank pairs, and partition those pairs into
deterministic disjoint matchings. Each matching becomes one collective
`split_group` round; the reverse direction is a separate round and communicator.
For PP4/VPP2 placement `(0, 1, 2, 3, 0, 1, 2, 3)`, eight directed children are
created in four split calls.

Initialize the stage-device backend before splitting. Homogeneous parents retain
their complete backend configuration. Mixed parents select only the stage-device
backend when that selection preserves the parent's default backend type;
otherwise the child retains every required backend. Native children inherit the
selected parent backend's timeout, while TorchComms delegates split capability
and timeout policy to `split_group`.

`ProcessGroupNCCL::split()` eagerly creates the child communicator through
`ncclCommSplit`. The subsequent one-element P2P exchange is therefore described
as preconnection: it exercises each actual directed send/receive path in a
deterministic order before execution or graph capture. It is not a second model
warmup and does not depend on TorchTitan.

The group map is cached by parent, complete stage-rank assignment, and stage
device type. All local virtual stages share the same map. Full process-group
teardown owns the lifetime of real children. Same-rank turns remain local and do
not create a child.

`pipeline_per_edge_p2p` remains disabled by default and is auto-enabled for
TorchComms. The existing shared-parent path remains unchanged when the option is
disabled. Fake groups retain assignment validation without creating real
children.

This implementation derives connectors only between successive logical stages.
Long-range skip connections remain unsupported in per-edge mode; supporting
them requires deriving connectors from finalized schedule actions rather than
silently falling back to the parent communicator.

- `python test/distributed/pipelining/test_schedule.py`
- `python test/distributed/pipelining/test_stage.py`
- `python test/distributed/pipelining/test_schedule.py P2PEdgeGroupTest`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py PerEdgeScheduleTest`
- `lintrunner --config=.lintrunner.toml torch/distributed/config.py torch/distributed/pipelining/_p2p.py torch/distributed/pipelining/schedules.py torch/distributed/pipelining/stage.py test/distributed/pipelining/test_stage.py test/distributed/pipelining/test_schedule.py test/distributed/pipelining/test_schedule_multiproc.py`
- Strict Sphinx HTML and coverage builds for `distributed.pipelining`.

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.
Pull Request resolved: #196666
Approved by: https://github.com/SherlockNoMad
ghstack dependencies: #196460, #196461, #196956, #196462, #196463, #196464, #196665
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
Pipeline initialization previously used different protocols depending on the
stage frontend and eventual metadata mode. Manual stages used a two-pass ring
whose traffic also initialized raw pairwise P2P communicators. Traced stages
used a mixed dummy-operation batch that initialized the parent communicator.
Dynamic metadata exchange happened to initialize that parent path again, while
static metadata skipped it. Correct communicator readiness therefore depended
on incidental control flow.

Replace those protocols with one explicit setup sequence. Real cross-rank
schedules reduce the local static-metadata capability over the parent group,
which both determines the global metadata mode and initializes the parent
communicator. Directed mode then creates and preconnects its child groups.
For shared mode, the all-reduce initializes the parent communicator used by
batched P2P, then raw P2P explicitly initializes the pairwise communicators.

## Before and after

| Concern | Before | After |
| --- | --- | --- |
| Manual metadata agreement | Forward ring plus backward result propagation | One parent `all_reduce(MIN)` |
| Manual P2P setup | Hidden side effect of the vote ring | Explicit shared or directed preconnection |
| Traced P2P setup | Separate mixed dummy-operation batch | Same setup protocol as manual stages |
| Static metadata | Could skip initialization of the batched parent path | Both shared-parent paths are exercised before execution |
| Dynamic metadata | Parent readiness depended partly on metadata exchange | Metadata mode no longer controls communicator readiness |
| Eval/train transition | P2P completion inferred from forward metadata state | Explicit schedule-owned P2P initialization state |
| Local stage placement | Multiple local stages had no explicit device invariant. | Every stage owned by one PP rank must use the same device. |

## Responsibility boundaries

| Component | Responsibility |
| --- | --- |
| Schedule | Compute local metadata capability, perform one global agreement, and invoke one-time transport setup. |
| `_p2p.py` | Derive deterministic communication rounds and preconnect the selected transport. |
| Stage | Resolve peers and construct runtime operations; it no longer implements setup protocols. |
| Parent group | Carry setup agreement and shared batched P2P. |
| Pairwise raw path | Carry homogeneous shared-parent P2P on lazy native backends. |
| Directed child | Carry one isolated physical source-to-destination FIFO when per-edge mode is enabled. |

## Behavior by mode

| Frontend and mode | Metadata agreement | One-time communication setup |
| --- | --- | --- |
| Manual, static | Reduce each rank's local static capability with parent `all_reduce(MIN)`. | Initialize the parent group path, then preconnect shared raw edges or directed children. |
| Manual, dynamic | The same reduction selects dynamic mode when any stage requires inference. | Identical to static mode; later metadata transfer does not initialize communicators incidentally. |
| Traced | No metadata-mode decision is needed. | Run one parent all-reduce for readiness, then the same shared or directed preconnection. |
| FakePG, static | Validate complete metadata locally because fake collectives do not exchange values. | Build the logical directed map when requested; issue no real communication. |
| FakePG, dynamic | Reject cross-rank dynamic inference with an actionable error. | No transport setup can make fake metadata exchange real. |
| Local-only schedule | Decide manual metadata mode locally. | Require no process group and issue no P2P setup. |

## Shared-parent setup

Collapse repeated logical-stage adjacencies onto unique unordered physical-rank
pairs. Partition those pairs into deterministic disjoint matchings. For each
local pair, issue one canonical raw P2P exchange on the rank's shared stage
device; the lazy pair channel is bidirectional and carries later forward and
backward traffic. Use a parent collective to align all ranks before the next
matching. Together with the initial parent all-reduce, this covers both
communicator-selection paths without redundant batched dummy traffic or
reliance on metadata inference.

The setup is run once per schedule. Static/dynamic transitions may repeat
metadata agreement but do not repeat transport setup. Local-only schedules do
not require a process group. Cross-rank FakePG remains static-only and performs
no real preconnection.

## Removed machinery

- The manual forward vote ring and backward result propagation.
- The traced-stage neighbor dummy-operation builder.
- The `stage_backend_initialized` bookkeeping flag.
- The inference that P2P readiness is equivalent to forward-metadata readiness.
- Mode-specific reliance on metadata transfer to initialize communication.

`pipeline_per_edge_p2p` remains disabled by default. Shared-parent mode,
backends without `split_group`, FakePG, manual/traced stages, and static/dynamic
metadata retain their existing capabilities.

## Test Plan

- `python test/distributed/pipelining/test_schedule.py`
- `python test/distributed/pipelining/test_stage.py`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py NCCLLazyP2PInitializationTest`
- `NCCL_DEBUG=WARN CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py`
- `lintrunner --config=.lintrunner.toml torch/distributed/pipelining/_p2p.py torch/distributed/pipelining/schedules.py torch/distributed/pipelining/stage.py test/distributed/pipelining/test_schedule.py test/distributed/pipelining/test_schedule_multiproc.py`
- Strict Sphinx HTML and coverage builds for `distributed.pipelining`.

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.
Pull Request resolved: #197488
Approved by: https://github.com/SherlockNoMad
ghstack dependencies: #196460, #196461, #196956, #196462, #196463, #196464, #196665, #196666
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
An asynchronous FSDP unshard is not free GPU work. It includes casts or
quantization before the collective, copy-in and packing, the all-gather itself,
copy-out, and post-all-gather parameter preparation. Issuing every eligible
unshard at the start of a pipeline step can therefore place non-critical work
in front of useful forward compute. The rank-aware policy in this PR estimates
how much preparation each pipeline rank's startup bubble can absorb, while
retaining an explicit per-rank override for models whose measured balance is
different.

The following detailed design and verification summary was prepared with Codex
and reviewed by the author:

> ## Problem
>
> Pipeline schedule lowering previously used `max_active_stages` for two
> independent decisions:
>
> 1. how many local FSDP stages should remain resident; and
> 2. how far ahead asynchronous unshards should be issued.
>
> Reducing `max_active_stages` to avoid an initial burst is not equivalent to
> reducing prefetch: it also changes eviction and can introduce additional
> unshard/reshard residency episodes. This PR separates those policies.
>
> | Concern | Before | After |
> | --- | --- | --- |
> | Parameter residency | `max_active_stages` | `max_active_stages` |
> | `RESHARD` placement | Derived from the residency window | Unchanged |
> | Unshard issue distance | Also `max_active_stages` | Independent `unshard_lookahead` |
> | Compatibility | Full residency window is prefetched | `"full"` preserves that behavior |
> | Expert tuning | Required rewriting schedule actions | One value per PP rank in a tuple |
>
> ## Why asynchronous unshards still need scheduling
>
> `async_op=True` avoids a host-side wait. It does not remove the GPU work or
> resource dependencies needed to make a parameter usable:
>
> ```text
> pre-all-gather cast or quantization
>   -> copy-in and packing
>   -> NCCL all-gather
>   -> copy-out
>   -> post-all-gather quantization or layout preparation
>   -> parameter ready
> ```
>
> These operations use GPU execution, memory bandwidth, collective resources,
> temporary storage, and stream synchronization. Over-prefetching can therefore
> contend with the forward it is intended to overlap.
>
> ## Rank-aware `"auto"` rationale
>
> Let a balanced stage forward take `F`, and let the composite critical-path
> cost of preparing one stage's unsharded parameters take `U`. Ignoring PP
> transfer latency, PP rank `r` cannot begin its first useful forward before
> approximately `U + rF`: rank zero first exposes its current stage's unshard,
> and each upstream rank then contributes one forward.
>
> Approximately `floor((U + rF) / U)` unshards can complete during that startup
> interval. Issuing one additional unshard lets the next preparation overlap
> the rank's first forward. Under the simplifying balanced assumption
> `F = U = T`, this gives `r + 2`, capped by the residency window.
>
> ```text
> interval           | 0..T    | T..2T   | 2T..3T  | 3T..4T  | 4T..5T
> -------------------+---------+----------+----------+----------+---------
> rank 0 forward     | blocked | F(first) |          |          |
> rank 0 preparation | U0      | U1       |          |          |  => 2
>
> rank 1 forward     | blocked | blocked  | F(first) |          |
> rank 1 preparation | U0      | U1       | U2       |          |  => 3
>
> rank 2 forward     | blocked | blocked  | blocked  | F(first) |
> rank 2 preparation | U0      | U1       | U2       | U3       |  => 4
>
> rank 3 forward     | blocked | blocked  | blocked  | blocked  | F(first)
> rank 3 preparation | U0      | U1       | U2       | U3       |  => 4
> ```
>
> For PP4 with `max_active_stages=4`, `"auto"` therefore resolves to
> `(2, 3, 4, 4)`. Rank zero issues its current and next stage; each downstream
> rank receives one additional stage of lookahead until the residency cap.
> This applies throughout lowering, not only during warmup.
>
> `Uk` denotes preparation of the kth upcoming rank-local stage, not a global
> stage index. Vertically aligned preparation and forward cells are intended to
> overlap. The diagram is an analytical starting point, not an exact
> CUDA-stream model.
> Real stages may be unbalanced, unshard phases may overlap only partially, and
> network or memory-bandwidth contention can change the best distance. `"auto"`
> is consequently a deterministic preset, not a schedule-derived optimizer or
> a universal performance guarantee.
>
> ## Policy contract
>
> | Policy | Resolution on PP rank `r` | Use |
> | --- | --- | --- |
> | `"full"` | `max_active_stages` | PyTorch compatibility default matching the original full-window behavior. |
> | `"auto"` | `min(r + 2, max_active_stages)` | Startup-bubble estimate when recipe-level tuning is unavailable. |
> | `tuple[int, ...]` | Exact value at index `r` | Expert tuning for measured model, topology, and fabric behavior. |
>
> Tuple length must equal the PP degree, and every entry must be in
> `[1, max_active_stages]`. A custom compute-only schedule can be combined with
> a tuple before lowering. A pre-lowered `compute_comms` schedule may encode
> exact `UNSHARD` placement directly and cannot be retuned by this option.
>
> ## Lowering and correctness
>
> At each compute position, lowering scans the remaining compute actions twice:
>
> ```text
> resident = next distinct stages up to max_active_stages
> prefetch = next distinct stages up to unshard_lookahead[rank]
>
> reshard stages outside resident
> unshard stages newly entering prefetch
> emit the original compute action
> ```
>
> The correctness invariants are:
>
> - `prefetch` is a prefix of `resident`, so a prefetched stage is not
>   immediately evicted.
> - The current compute action's stages are always included, so lookahead one
>   remains correct even though its all-gather may be exposed.
> - `max_active_stages` alone determines residency episodes and `RESHARD`
>   placement.
> - Changing lookahead adds or removes no collective and does not change the
>   compute-action order.
> - Active-stage insertion order makes eviction deterministic.
> - `OVERLAP_F_B` is atomic: all stages in the compound action are prepared
>   together. Such an action may extend a scan window by up to its number of
>   stages minus one, and `ScheduleDualPipeV` rejects
>   `max_active_stages=1` because its current compound action requires two.
>
> Unshards are inserted before communication lowering. Their different issue
> positions can therefore move the absolute indices of P2P actions. Tests prove
> that the P2P multiset and dependency-valid ordering remain correct and that
> receive-buffer slot assignments remain unchanged for the covered schedules.
>
> The policy is supported by Looped BFS, Interleaved 1F1B, Interleaved Zero
> Bubble, ZBV Zero Bubble, and DualPipeV.
>
> This PR does not claim that `"auto"` is universally faster. PyTorch keeps
> `"full"` as the compatibility default, and applications should benchmark an
> explicit tuple against their model, topology, and communication stack.
>
> ## Verification
>
> - Resolver tests cover `"full"`, `"auto"`, explicit tuples, invalid types,
>   wrong lengths, and out-of-range values.
> - Lowering goldens cover steady-state placement and atomic compound actions.
> - All five schedule families preserve compute order, collective counts,
>   `RESHARD` placement, communication validity, and receive-buffer slots.
> - A live four-GPU `(dp, pp)=(2, 2)` FSDP test proves `"full"` and `(1, 1)`
>   produce matching output, loss, and nonzero local sharded gradients while
>   exercising different unshard placements.
>
> Test Plan:
>
> - `python test/distributed/pipelining/test_schedule.py`
> - `NCCL_DEBUG=WARN CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py`
> - `lintrunner --config=.lintrunner.toml torch/distributed/pipelining/schedules.py test/distributed/pipelining/test_schedule.py test/distributed/pipelining/test_schedule_multiproc.py docs/source/distributed.pipelining.md`
> - Strict Sphinx HTML and coverage builds of `distributed.pipelining`.
Pull Request resolved: #196706
Approved by: https://github.com/SherlockNoMad
ghstack dependencies: #196460, #196461, #196956, #196462, #196463, #196464, #196665, #196666, #197488
@github-actions
github-actions Bot deleted the gh/sanketpurandare/4/head branch November 29, 2026 01:47
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 release notes: distributed (fsdp) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants