Skip to content

[c10d] Let backends own split Store isolation - #196665

Closed
sanketpurandare wants to merge 14 commits into
gh/sanketpurandare/10/basefrom
gh/sanketpurandare/10/head
Closed

sanketpurandare wants to merge 14 commits into
gh/sanketpurandare/10/basefrom
gh/sanketpurandare/10/head

Conversation

@sanketpurandare

@sanketpurandare sanketpurandare commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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! (1 Unrelated Failure)

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

CRCR (non-blocking) - The following CRCR downstream CI job failed but is non-blocking:

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

@kapilsh

kapilsh commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

@claude review this PR for any backwards compatibility breaking behavior - how do we handle split group store in NCCL2 backend which is now default in trunk/nightlies?

@claude

claude Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Claude finished @kapilsh's task in 22m 31s —— View job


PR Review: #196665

Sharing one cloned Store across split children is sound and the new default nccl2 backend needs no change (it already passes the store through without cloning), but the shared TCPStore connection serializes all sibling rendezvous under one lock — which affects nccl-legacy P2P and nccl-lazy pair comms, i.e. the pipeline-parallel case that motivates the PR — and the test only covers nccl-legacy.

Full review

Summary

ProcessGroup::splitGroup now lazily clones the rendezvous Store once per parent and hands each child a distinct PrefixStore over that single connection, instead of cloning per child. The mechanism is correct and the parent's own connection is genuinely untouched. Findings below concern the sibling-serialization tradeoff, the Backend::split ownership-contract change, and test coverage of the now-default nccl2 path.

Answering the NCCL2 question directly

The new default backend needs no code change, and the PR's benefit applies to it automatically:

  • nccl2::ProcessGroupNCCL::split (torch/csrc/distributed/c10d/nccl2/ProcessGroupNCCL.cpp:431-432) already passed the incoming store straight to the child (ProcessGroupNCCL(store, newRank, ...)) with no clone(). The per-child connection was created upstream, by the old store_->clone() in ProcessGroup::splitGroup. Removing that is therefore the entire fix for nccl2 — no nccl2 edit is needed, and the ProcessGroupNCCL.cpp:1360-1361 change only brings nccl-legacy into line with what nccl2 already did.
  • Plain nccl2 children are also the least exposed to the downside below: split() builds the child via initFromComm (nccl2/ProcessGroupNCCL.cpp:433) from ncclCommSplit, and nccl2 uses its single comm for P2P as well, so a plain-nccl2 split child issues no store traffic at all after construction.

Two nccl2 paths do still touch the (now shared) store post-split, and neither is covered:

  • nccl2::ProcessGroupNCCL::reconfigure wraps store_ in PrefixStore("nccl2_reconfigure/<uuid>", store_) (nccl2/ReconfigureNCCL.cpp:141-142) and rendezvouses on it, including a blocking compareSet/wait.
  • nccl-lazy builds each P2P pair comm lazily on PrefixStore(pair_name, store) over the same store (nccl2/ProcessGroupNCCLLazy.cpp:29-30), and LazyBackend::split forwards to primary_->split (lazy/LazyBackend.hpp:382-387), so a lazy child's pair comms bootstrap through the shared connection.

nccl2/ShrinkNCCL.cpp:105 still calls store_->clone(), so shrink is unaffected.

Thread Safety

  • ProcessGroup.cpp:249-256 — the lazy-init locking is correct, but the resulting single connection is a new serialization point. TCPStore guards every operation with activeOpLock_ and holds it across the blocking wait: wait() takes the lock at TCPStore.cpp:551 before doWait, and get() takes it at TCPStore.cpp:474 before doGet -> doWait (TCPStore.cpp:479). Previously each child had its own connection, so N children could rendezvous concurrently; now one child's get/wait blocks every sibling's store traffic for up to the full store timeout.

    This is on the hot path for the motivating use case, not hypothetical:

    • nccl-legacy P2P: the ncclCommSplit fast path is gated on !singleP2POp (ProcessGroupNCCL.cpp:3151), so P2P comms in a split child fall through to broadcastUniqueNCCLID, which does store_->set/store_->get (ProcessGroupNCCL.cpp:2906, 2909). torch/distributed/pipelining/stage.py:323-328 creates exactly these directed split children and then sends/recvs on them.
    • nccl-lazy: per-peer pair comms bootstrap through the store on first send/recv (above).
    • Scalable init (getSize() > TORCH_NCCL_RANKS_PER_ROOT) uses allgatherUniqueNCCLIDs on store_ (ProcessGroupNCCL.cpp:3187, 2975-2978).

    The tradeoff is probably worth it — this is setup-time cost traded against hundreds of sockets, and the PR's framing is right that the parent is protected. But the PR description only claims the upside; it should state that siblings now block each other, and ideally bound it (a small fixed pool of connections rather than exactly one gives most of the FD win without full serialization). At minimum, please confirm PP schedule startup time does not regress at the scale that motivated this.

Backward Compatibility

  • ProcessGroupNCCL.cpp:1360-1361 changes the implicit ownership contract of the public virtual Backend::split (Backend.hpp:697). Every child of a given parent now receives a PrefixStore over the same underlying Store object, whereas before each got a private clone. PrefixStore::setTimeout forwards straight through to the underlying store (PrefixStore.cpp:77-78), so an out-of-tree backend whose split() reasonably calls store->setTimeout(...) on the store it is handed would now silently change the store timeout for every sibling child. Key mutations are safe (the per-child prefix namespaces them) — it is specifically the non-namespaced state like setTimeout that leaks. No in-tree backend does this today, so this is a latent break rather than an active one, but the contract should be documented on Backend::split: the store may be shared with siblings, implementations must not mutate connection-global state, and they may retain but not assume exclusive ownership.

  • Ownership handling is now inconsistent across backends, which makes that undocumented contract harder to infer: ProcessGroupGloo::split still calls store->clone() (ProcessGroupGloo.cpp:805), and ProcessGroupNCCL::merge still clones (ProcessGroupNCCL.cpp:1379), while both NCCL split paths no longer do. A practical consequence: since PrefixStore::clone() clones the underlying store (PrefixStore.cpp:9-10), a hybrid cpu:gloo,cuda:nccl parent still opens one fresh connection per child for its gloo leg, so the PR's connection saving does not apply to hybrid groups. Worth stating explicitly in the description so nobody expects the win there.

  • Scope of the improvement is worth documenting precisely: sharing is per-parent, so a hierarchical split tree (e.g. device_mesh.py:600) still opens one connection per internal node that is itself split. Connection count goes from O(children) to O(PGs that get split) — the large win for one PP parent with hundreds of children, not a global O(1).

Testing

  • The Test Plan command is wrong: it names TestProcessGroupNCCL.test_backend_filter_split, but the modified test is ProcessGroupNCCLGroupTest.test_comm_split_group_backend_filter (test/distributed/test_c10d_nccl.py:1396). test_backend_filter_split does not exist in the file, so the documented command runs nothing. Please correct it, since it is the only evidence the change was exercised.

  • The new assertions (test_c10d_nccl.py:1433-1448) only cover backend="cuda:nccl-legacy". Given nccl2 is the default in trunk/nightlies and this PR modifies the shared splitGroup path that nccl2 depends on for its isolation, please add equivalent coverage on the default backend. A nccl-lazy case would be the most valuable addition, since that is the configuration where sibling P2P bootstrap actually contends on the shared connection.

  • The test does not validate the property the PR exists for. It uses FileStore (test_c10d_nccl.py:1400), which has no connection at all, so assertIs(...underlying_store, ...) only checks C++ object identity, not that fewer sockets are opened. Consider a TCPStore-based case asserting a stable host/port or connection count, which would actually regression-guard the fix.

  • assertIs on underlying_store depends on pybind11 returning the same Python wrapper for the same raw pointer via its instance registry. That holds today, but it couples the test to a pybind implementation detail; comparing an observable property of the store would be more robust. (Low confidence — flagging as fragility, not a defect.)

Code Quality

  • ProcessGroup.hpp:1209-1213 — the comment explains the design well, but the invariant that makes it safe is stated nowhere the reader of splitGroup will see it: children are isolated only by their PrefixStore prefix, so the uniqueness of groupName is now load-bearing for correctness across siblings rather than merely per-child. It is satisfied (_process_group_name(..., use_hashed_name=True) salts with _world.group_count, distributed_c10d.py:6886 and 6627-6639), but a one-line note at ProcessGroup.cpp:257-259 tying the shared connection to that requirement would prevent a future change to name derivation from silently introducing cross-sibling key collisions.
· branch `gh/sanketpurandare/10/head`

@@ -242,9 +246,17 @@ c10::intrusive_ptr<ProcessGroup> ProcessGroup::splitGroup(
std::string groupName = name.has_value()
? name.value()
: c10::str(getGroupName(), ":split:", fmt::format("{}", ranks));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit: this whole c10::str could be converted to a fmtlib call..

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The generic error-formatting block disappeared when the shared ProcessGroup Store cache was removed, so the c10::str expression no longer exists in the revised diff.

[ghstack-poisoned]
sanketpurandare added a commit to pytorch/torchtitan that referenced this pull request Sep 14, 2026
…les"

TorchTitan already captures the complete eager pipeline step, but it rejects
all multi-stage schedules because a shared P2P communicator can impose an
ordering cycle during CUDA graph replay. Permit looped schedules when the
PyTorch pipeline runtime is configured to use one process group per directed
physical-rank edge.

Keep the policy explicit: looped schedules without directed P2P groups still
fail configuration validation. Add a four-GPU Interleaved1F1B feature recipe
and integration entry that exercises full-step CUDA graph capture without
making receive deferral a correctness requirement.

This supersedes the closed prototype in #4485.

Dependencies:
- pytorch/pytorch#196665
- pytorch/pytorch#196666

Test Plan:
- `python -m pytest -q tests/unit_tests/cpu/test_config_manager.py -k cuda_graphs`
- `pre-commit run --files tests/integration_tests/features.py tests/unit_tests/cpu/test_config_manager.py torchtitan/config/configs.py torchtitan/trainer.py torchtitan_recipes/tests/features.py`
- Four-GPU `pp_looped_1f1b_cudagraph` integration test with repeated replay

[ghstack-poisoned]
sanketpurandare added a commit to pytorch/torchtitan that referenced this pull request Sep 14, 2026
TorchTitan already captures the complete eager pipeline step, but it rejects
all multi-stage schedules because a shared P2P communicator can impose an
ordering cycle during CUDA graph replay. Permit looped schedules when the
PyTorch pipeline runtime is configured to use one process group per directed
physical-rank edge.

Keep the policy explicit: looped schedules without directed P2P groups still
fail configuration validation. Add a four-GPU Interleaved1F1B feature recipe
and integration entry that exercises full-step CUDA graph capture without
making receive deferral a correctness requirement.

This supersedes the closed prototype in #4485.

Dependencies:
- pytorch/pytorch#196665
- pytorch/pytorch#196666

Test Plan:
- `python -m pytest -q tests/unit_tests/cpu/test_config_manager.py -k cuda_graphs`
- `pre-commit run --files tests/integration_tests/features.py tests/unit_tests/cpu/test_config_manager.py torchtitan/config/configs.py torchtitan/trainer.py torchtitan_recipes/tests/features.py`
- Four-GPU `pp_looped_1f1b_cudagraph` integration test with repeated replay

[ghstack-poisoned]
sanketpurandare added a commit to pytorch/torchtitan that referenced this pull request Sep 14, 2026
…les"

TorchTitan already captures the complete eager pipeline step, but it rejects
all multi-stage schedules because a shared P2P communicator can impose an
ordering cycle during CUDA graph replay. Permit looped schedules when the
PyTorch pipeline runtime is configured to use one process group per directed
physical-rank edge.

Keep the policy explicit: looped schedules without directed P2P groups still
fail configuration validation. Add a four-GPU Interleaved1F1B feature recipe
and integration entry that exercises full-step CUDA graph capture without
making receive deferral a correctness requirement.

This supersedes the closed prototype in #4485.

Dependencies:
- pytorch/pytorch#196665
- pytorch/pytorch#196666

Test Plan:
- `python -m pytest -q tests/unit_tests/cpu/test_config_manager.py -k cuda_graphs`
- `pre-commit run --files tests/integration_tests/features.py tests/unit_tests/cpu/test_config_manager.py torchtitan/config/configs.py torchtitan/trainer.py torchtitan_recipes/tests/features.py`
- Four-GPU `pp_looped_1f1b_cudagraph` integration test with repeated replay

[ghstack-poisoned]
sanketpurandare added a commit to pytorch/torchtitan that referenced this pull request Sep 14, 2026
TorchTitan already captures the complete eager pipeline step, but it rejects
all multi-stage schedules because a shared P2P communicator can impose an
ordering cycle during CUDA graph replay. Permit looped schedules when the
PyTorch pipeline runtime is configured to use one process group per directed
physical-rank edge.

Keep the policy explicit: looped schedules without directed P2P groups still
fail configuration validation. Add a four-GPU Interleaved1F1B feature recipe
and integration entry that exercises full-step CUDA graph capture without
making receive deferral a correctness requirement.

This supersedes the closed prototype in #4485.

Dependencies:
- pytorch/pytorch#196665
- pytorch/pytorch#196666

Test Plan:
- `python -m pytest -q tests/unit_tests/cpu/test_config_manager.py -k cuda_graphs`
- `pre-commit run --files tests/integration_tests/features.py tests/unit_tests/cpu/test_config_manager.py torchtitan/config/configs.py torchtitan/trainer.py torchtitan_recipes/tests/features.py`
- Four-GPU `pp_looped_1f1b_cudagraph` integration test with repeated replay

[ghstack-poisoned]
@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Claude finished @sanketpurandare's task in 7m 39s —— View job


This revision addresses the substantive asks — the merge clone now carries its rationale in code, the Backend::split contract distinguishes key isolation from connection-global state, and the test pins the exact prefixed store reaching both backends — but the nccl2 comment you added states a reason that ShrinkNCCL.cpp contradicts, and the real reason (the shared parent connection) is the one in your description rather than in the code.

Full review

Confirmed against the code

  • Merge rationale is now beside the code. ProcessGroupNCCL.cpp:1378-1380. I traced it: merge builds the child without any eager init, so its first collective reaches initNCCLComm -> broadcastUniqueNCCLID -> store_->get (:2921), and TCPStore::get holds activeOpLock_ across doWait (TCPStore.cpp:474, 478-479). The comment is accurate and the "Unlike split()" framing is the right hook.
  • Backend.hpp:697-701 now makes the safe/unsafe split explicit. "A PrefixStore isolates rendezvous keys, but its connection-global state may be shared with the caller or sibling backends" is exactly the distinction that was missing — an implementer can now tell that their keys will not collide with a sibling's and that the timeout will.
  • Test asserts the identity. assertIs(cpu_backend.split_store, default_backend.split_store) (test_c10d_common.py:2996) pins the property that determines key layout: splitGroup builds one prefixed store (ProcessGroup.cpp:247-248) and hands the same object to every backend of the child (:286) and to the child ProcessGroup (:293). Combined with clone_count == 0, this can only pass for the intended behavior, and it avoids the pybind-instance-registry coupling of the earlier underlying_store version.
  • The split-side claim holds. eagerConnectSingleDevice (:1367) sets eagerInit_ (:1087), and pointToPoint then takes the if (this->eagerInit_) branch (:4164), reuses the parent comm via getKeyFromDevice, and asserts it already exists (:4186-4188). So a legacy split child issues no store traffic on P2P — which is the pipeline-parallel path that motivates the PR. Scalable init is likewise skipped because ncclComm is already non-null at :3190.
  • ProcessGroup.cpp:245-246 ties the shared connection to groupName uniqueness where a reader of splitGroup will see it. Good placement.

1. The nccl2 comment gives a reason that shrink disproves

nccl2/ProcessGroupNCCL.cpp:403-404:

A split child already owns an initialized communicator. Do not inherit enable_reconfigure, whose contract defers initialization to reconfigure().

ShrinkNCCL.cpp does the opposite and works: it does inherit the flag (ShrinkNCCL.cpp:25, options->enable_reconfigure = source->enable_reconfigure) and also produces an already-initialized child via initFromComm (:109). So "already initialized, therefore cannot be reconfigurable" is not the operative constraint — an initialized child can carry the flag.

The constraint that does separate them is the one in your PR description, and it is a store constraint: reconfigure() rendezvouses on PrefixStore("nccl2_reconfigure/<uuid>", store_) with a blocking wait + get (ReconfigureNCCL.cpp:141-142, 175-176). A shrink child holds store_->clone() (ShrinkNCCL.cpp:105), so that blocking rendezvous runs on its own connection. A split child now holds the parent's live connection, so it cannot. That is a real, discriminating asymmetry and it is the one worth recording — the current wording will read as arbitrary to anyone who has just looked at shrink. Fix this →

Also note the flag is user-reachable (distributed_c10d.py:2381, enable_reconfigure=), so a reconfigurable parent silently produces a non-reconfigurable child. That's pre-existing, but this PR turns it from a feature gap into a correctness dependency, which is why the comment's reason matters.

2. split() itself carries no note, and the merge comment points at it

ProcessGroupNCCL.cpp:1378 says "Unlike split()", but a reader landing on :1360-1361 sees the un-cloned store with nothing explaining why it is safe there. The justification is non-local — it lives in eagerConnectSingleDevice seven lines below and in the eagerInit_ branch two thousand lines away. One line at :1367 ("eager init binds the child's comm now, and eagerInit_ makes P2P reuse it, so the child never rendezvouses on the store") makes the pair self-explaining. This is the one place a future reader is most likely to "clean up" the merge clone for symmetry.

Small caveat worth knowing, not worth a comment: the eager path is not unconditional. initNCCLComm only uses NCCLComm::split if the parent comm is found and not aborted (:3163-3177); otherwise it falls through to broadcastUniqueNCCLID on the now-shared store. splitGroup guards this by requiring isInitialized() upfront (ProcessGroup.cpp:236-239), so it takes an aborted-parent race to hit — already a failing scenario.

3. Test: two cheap tightenings

  • assertIsInstance(child.get_group_store(), dist.PrefixStore) (:2997) is the weakest assertion in the test — a clone would also be a PrefixStore. Since ProcessGroup.cpp:293 constructs the child from the same object, assertIs(child.get_group_store(), cpu_backend.split_store) is available and states the actual contract.
  • Nothing checks the prefix contains the group name, which is the load-bearing part of key isolation now that connections are shared. A PrefixStore.underlying_store / prefix check, or just splitting on the child store's prefix, would pin it.
  • Still no coverage of the retained merge clone. It is now the single deliberate exception in the file; a test that it stays clone-count-1 is a few lines and stops a future symmetry cleanup from silently removing it.

4. Stale comment from the last round is still there

torch/distributed/distributed_c10d.py:7829:

# Create process group with new communicator (clone the parent store like split does)
prefix_store = PrefixStore(f"{group_name}/", metadata["store"].clone())

Split no longer clones, so the stated rationale is now false. The .clone() itself looks correct for shrink (both backends' shrink paths clone: ProcessGroupNCCL.cpp:6153, nccl2/ShrinkNCCL.cpp:105), so this is purely the comment. Fix this →

5. Description precision

  • "Gloo likewise keeps its existing backend-owned clones" is correct and the clone is necessary, not merely preserved: the ctor runs connectContexts -> connectFullMesh (ProcessGroupGloo.cpp:698) synchronously through TCPStore::wait, which holds activeOpLock_ across doWait (TCPStore.cpp:551). Worth adding the consequence: since PrefixStore::clone() clones the underlying store, an unfiltered cpu:gloo,cuda:nccl parent still opens one connection per child for its gloo leg. The FD win lands on CUDA-only children — which is what PP creates, so the motivation stands, but "hundreds -> zero" is the filtered case only.
  • Both backends' shrink also clone (ProcessGroupNCCL.cpp:6153, ShrinkNCCL.cpp:105), so merge is not the only retained clone. One clause covering shrink keeps the inventory honest.
  • Worth stating that the parent's own connection is now shared (not a clone of it), and that child_pg.get_group_store().set_timeout(...) therefore reaches the parent and every sibling, since PrefixStore::setTimeout forwards through (PrefixStore.cpp:77-78). No in-tree caller does this — distributed_c10d.py:2355's set_timeout goes to Backend::setTimeout — but it is a public-API behavior change.
  • On the plus side, this is now strictly better than the shared-clone revision for hierarchical splits: PrefixStore nests, so a split tree costs zero extra connections on the NCCL legs rather than one per internal node. That is the strongest form of the win and it is not stated.

Minor

  • _make_group(self, store=None) with store if store is not None else dist.HashStore() inline in the constructor call (:2977) reads better as a separate defaulting line.
  • _CloneTrackingStore doesn't override the pure virtuals, so if splitGroup ever grows a store op the failure surfaces as pybind's "Not implemented" rather than something diagnosable. Not worth fixing now.

Asks

  1. Rewrite nccl2/ProcessGroupNCCL.cpp:403-404 to give the store reason (the one in your description), since ShrinkNCCL.cpp:25 disproves the init-contract reason.
  2. Add one line at ProcessGroupNCCL.cpp:1367 on why split is safe, so the "Unlike split()" in the merge comment resolves locally.
  3. assertIs(child.get_group_store(), cpu_backend.split_store); consider a prefix check and a merge-clone test.
  4. Fix the stale comment at distributed_c10d.py:7829.
  5. Description: hybrid gloo legs and shrink still clone; the parent's live connection is now shared (including via get_group_store().set_timeout); hierarchical splits now cost zero extra connections.
· branch `gh/sanketpurandare/10/head`

@sanketpurandare sanketpurandare added the module: c10d Issues/PRs related to collective communications and process groups label Sep 16, 2026
@pytorch-bot pytorch-bot Bot added the ciflow/torchtitan Run TorchTitan integration tests label Sep 16, 2026
@sanketpurandare

Copy link
Copy Markdown
Contributor Author

I used Codex to prepare this verification summary and reviewed it against the implementation and test results; it addresses the findings in this review: @claude Corrected the nccl2 comment to identify blocking reconfiguration rendezvous on the shared parent connection as the reason split children do not inherit reconfiguration, added the local split-safety explanation, pinned child/backend Store identity plus the retained merge clone, and replaced the stale shrink comment with its own isolation rationale. The description now states the hybrid-Gloo, shared timeout/connection, shrink, and hierarchical-split boundaries. The generic Store ownership, legacy NCCL split, and nccl2 split tests pass against the rebuilt extension.

@claude

claude Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Claude finished @sanketpurandare's task in 30m 38s —— View job


The four asks from the last round all landed and check out against the code — the nccl2 comment now gives the store reason that ShrinkNCCL.cpp:25 doesn't contradict, and the CPU test pins the exact prefixed parent Store — but the new test_merge_group_clones_store_for_uninitialized_child has no GPU gate, so it will fail rather than skip on a NCCL-built, GPU-less machine, and nothing in the suite pins the child's key prefix, which is the one property whose regression would be silent and wire-visible.

Full review

Verification of this round's changes

nccl2/ProcessGroupNCCL.cpp:403-404 now states the discriminating reason. "Do not inherit enable_reconfigure: reconfigure() performs blocking rendezvous on this shared Store connection." I checked it against the case that disproved the previous wording: ShrinkNCCL.cpp:25 does inherit enable_reconfigure for a child that is also already initialized (initFromComm at :109), and it can do so because the shrink child holds store_->clone() (:105). A split child holds the parent's live connection, so the same blocking wait/get in ReconfigureNCCL.cpp:142/175-176 is no longer safe. The comment now separates the two cases correctly. Resolved.

ProcessGroupNCCL.cpp:1360-1361 explains split locally. With this line plus the "Unlike split()" hook at :1380-1382, the split/merge asymmetry resolves without leaving the file. I re-traced the full safety chain and it holds: eagerConnectSingleDevice (:1369) sets eagerInit_ (:1087), and pointToPoint then takes the if (this->eagerInit_) branch (:4166), reuses the parent-derived comm via getKeyFromDevice, and asserts it already exists (:4188-4190) rather than falling through to broadcastUniqueNCCLID. Scalable init is inert too, since the ID exchange sits inside if (!ncclComm) (:3192) and ncclComm is already set from NCCLComm::split. So a legacy split child issues zero Store traffic post-construction, which is the pipeline-parallel path that motivates the PR.

One caveat the comment slightly overstates: the ncclCommSplit path is best-effort. If the parent's entry for that device key is missing or aborted (:3170-3172), eager init falls through to broadcastUniqueNCCLID -> store_->set/get (:2920/:2923) on the shared connection. splitGroup requires isInitialized() upfront (ProcessGroup.cpp:236-239), so reaching it takes an aborted-parent race. Not worth a code change; just don't read "does not need a separate Store connection" as unconditional.

Backend.hpp:697-699 no longer overclaims for merge. Dropping the "and merge()" phrasing fixes last round's inaccuracy: mergeRemoteGroup builds no PrefixStore at all — the caller's raw store goes to store->add("mergeGroupRank", 1) (ProcessGroup.cpp:314) and then unchanged to parentBackend->merge (:336) and the child ProcessGroup (:343). The comment as written is true of split only, which is where it sits. Good.

Residual gap, low priority: merge (Backend.hpp:711) still has no contract note, and its store is un-namespaced — so sibling backends of one merged child share a raw key space, unlike split's. One line there would close the loop, and it also happens to be the most compact justification for the :1384 clone.

ProcessGroup.cpp:245-246 puts the key-isolation invariant where a reader of splitGroup sees it. Minor wording nit: "Therefore, an explicitly supplied group name must be unique among siblings" reads as a new requirement introduced here. It isn't — TCPStore::clone() preserves keyPrefix_ and reconnects to the same server (TCPStore.cpp:361-369), so the old per-child clones never isolated keys either, only connections. "must (as before) be unique" would avoid implying a behavior change.

Key layout is unchanged. PrefixStore::clone() preserves prefix_ and clones the underlying (PrefixStore.cpp:9-10), so removing the clone moves no rendezvous key. Wire-compatible.


1. The new merge test will fail, not skip, without a GPU

test_c10d_nccl.py:1438-1449 is decorated only with @requires_nccl(), which checks c10d.is_nccl_available() — i.e. compiled with NCCL (common_distributed.py:507-511). It says nothing about GPUs being present. The test then calls _create_process_group_nccl, which constructs a ProcessGroupNCCL, whose ctor does TORCH_CHECK(at::cuda::getNumGPUs() != 0, ...) (ProcessGroupNCCL.cpp:945-948). On a NCCL-enabled build with no visible device this is a hard failure inside init_process_group, not a skip.

Every other GPU-touching test in ProcessGroupNCCLGroupTest pairs @requires_nccl() with @skip_if_lt_x_gpu(1) or not TEST_MULTIGPU (e.g. :402-404, :1397-1398). This one is the only exception. @skip_if_lt_x_gpu(1) is already imported (:63). Fix this →

Otherwise the test is sound and I confirmed it pins what it claims: mergeRemoteGroup calls add on the tracking store (implemented), then getBackend(cuda)->merge clones exactly once (ProcessGroupNCCL.cpp:1384), and the child is never initialized so nothing else touches the store. int(b"0") is valid — int() accepts bytes-like — so the add override is correct.

2. Nothing pins the child's key prefix, which is the wire-visible property

The CPU test now checks which object reaches the backends (clone_count == 0, assertIs on underlying_store, assertIs across both backends and the child PG). What it doesn't check is that the store actually namespaces keys under the group name — and since PrefixStore exposes no prefix accessor to Python, "is a PrefixStore over store" is satisfied by a prefix of "" too. A prefix regression would silently move every child's rendezvous keys, which is exactly the thing that must not change.

_CloneTrackingStore already implements add, so this is two lines and needs no new plumbing:

child.get_group_store().add("probe", 1)
self.assertTrue(any(k.startswith("child/") for k in store._values))

(PrefixStore::joinKey is prefix_ + "/" + key and the prefix already ends in /, so the observed key has a double slash — pre-existing and unchanged by this PR, hence the startswith rather than an exact match.)

3. Two lines in the CPU test are now dead

test_c10d_common.py:2990-2991 loops assertIsInstance(backend.split_store, dist.PrefixStore) over both backends. Line 2993 then reads cpu_backend.split_store.underlying_store, an attribute that only exists on PrefixStore (init.cpp:2255-2258), and line 2992 already pins the two backends to the same object. The loop can't fail unless one of the surviving assertions fails first. Dropping it makes the test's three real claims — no clone, one shared store, that store wraps the parent — read directly.

4. The replaced shrink comment states what, not why

distributed_c10d.py:7829 now reads:

# Preserve shrink's existing independent Store ownership for the new group.

That's no longer false (the previous "like split does" was), but it's circular — it describes the code below it rather than the reason. The reason is available and concrete: unlike a split child, the shrunk group is built around a fresh communicator (ProcessGroupNCCL.cpp:6144, ShrinkNCCL.cpp:80) and gets re-registered as a new PG, so it can rendezvous on its Store later; both backend paths clone for the same reason (ProcessGroupNCCL.cpp:6155, ShrinkNCCL.cpp:105). Saying that makes the line useful to someone deciding whether the clone is still needed. Low priority. Fix this →

5. Description

The four boundaries I asked for are all in the body now and all check out: hybrid children still open a connection for the Gloo leg (ProcessGroupGloo.cpp:806, necessary because connectFullMesh at :698 rendezvouses synchronously through TCPStore::wait, which holds activeOpLock_ across doWait at TCPStore.cpp:551); child-Store timeout changes reach parent and siblings (PrefixStore::setTimeout forwards through, PrefixStore.cpp:77-78); TORCH_NCCL_PROPAGATE_ERROR polling shares the connection (ProcessGroupNCCL.cpp:2222/2234, off by default at :2124); nested NCCL splits add namespaces only.

Two optional additions:

  • Shrink also clones (ProcessGroupNCCL.cpp:6155, ShrinkNCCL.cpp:105), so merge isn't the only retained clone in the inventory.
  • The new_group() precedent is still absent and is still the strongest defense of the whole design: _new_process_group_helper has never cloned — PrefixStore(f"{group_name}/", store) (distributed_c10d.py:2874) then PrefixStore(f"{device}/", prefix_store) (:2904) — so hundreds of sibling PGs already share one TCPStore connection in production. That's observed behavior at scale, which beats any code-path argument for why split_group was the outlier.

Minor

  • _make_group(self, store=None) (test_c10d_common.py:2965-2973) is clean now that the defaulting is hoisted out of the constructor call.
  • _CloneTrackingStore still doesn't override the pure virtuals, so if splitGroup ever grows a store op the failure surfaces as pybind's "Not implemented" rather than something diagnosable. Noting only in case it bites later.
  • _CloneTrackingStore.clone() returns self rather than a copy, so the merge test's child shares the same Python object. Harmless for a clone count, but it means the test can't distinguish "cloned" from "cloned into a distinct connection" — fine given the intent.

I could not build or run the suite in this environment, so this pass is static analysis only; I'm relying on your report that the three named tests pass against the rebuilt extension.

Asks

  1. Add @skip_if_lt_x_gpu(1) to test_merge_group_clones_store_for_uninitialized_child.
  2. Assert the child store's prefix contains the group name (two lines via the existing add override).
  3. Drop the now-redundant assertIsInstance loop at test_c10d_common.py:2990-2991.
  4. Optional: give the shrink comment its actual reason; add a contract line above Backend::merge; add shrink and the new_group() precedent to the description.
· branch `gh/sanketpurandare/10/head`

`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 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_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 --skip PYREFLY test/distributed/test_c10d_common.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.

[ghstack-poisoned]
[ghstack-poisoned]
`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.

[ghstack-poisoned]
[ghstack-poisoned]
`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.

[ghstack-poisoned]
`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.

[ghstack-poisoned]
`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.

[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #196706

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

[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
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
sanketpurandare added a commit to pytorch/torchtitan that referenced this pull request Sep 24, 2026
…les"

TorchTitan captures the complete eager pipeline step, but previously rejected
every multi-stage looped schedule. A shared P2P communicator can serialize
logical pipeline edges in incompatible orders during CUDA-graph replay, so
removing that validation without first fixing communicator ownership would make
the expanded support unsafe.

Enable looped-schedule capture after the lower runtime layers establish the
required invariant:

- PyTorch derives one process group for each directed physical-rank edge from
  the finalized schedule topology, initializes and warms those groups before
  capture, and shares one Store connection across split children;
- TorchTitan enables that directed-edge topology automatically whenever PP is
  active; it is not a user-selectable policy;
- existing supported PP feature recipes now exercise full-step capture rather
  than disabling CUDA graphs solely because their schedule is looped.

This change only removes the obsolete blanket validation. It does not rewrite
schedule actions, add polling, require deferred receives, or expose another
pipeline configuration flag. Cases with independent blockers remain explicitly
disabled, including validation that reinitializes the shared schedule and
split-backward schedules with values that are not CUDA-graph inputs.

This supersedes the closed prototype in #4485.

Dependencies:
- pytorch/pytorch#196665
- pytorch/pytorch#196666
- #4540

Test Plan:
- `python -m pytest -q tests/unit_tests/cpu/test_config_manager.py -k cuda_graphs`
- `pre-commit run --files tests/integration_tests/features.py tests/unit_tests/cpu/test_config_manager.py torchtitan/config/configs.py torchtitan/trainer.py torchtitan_recipes/tests/features.py`
- Four-GPU `pp_looped_1f1b_cudagraph` integration test with repeated full-step
  capture and replay.

[ghstack-poisoned]
sanketpurandare added a commit to pytorch/torchtitan that referenced this pull request Sep 24, 2026
TorchTitan captures the complete eager pipeline step, but previously rejected
every multi-stage looped schedule. A shared P2P communicator can serialize
logical pipeline edges in incompatible orders during CUDA-graph replay, so
removing that validation without first fixing communicator ownership would make
the expanded support unsafe.

Enable looped-schedule capture after the lower runtime layers establish the
required invariant:

- PyTorch derives one process group for each directed physical-rank edge from
  the finalized schedule topology, initializes and warms those groups before
  capture, and shares one Store connection across split children;
- TorchTitan enables that directed-edge topology automatically whenever PP is
  active; it is not a user-selectable policy;
- existing supported PP feature recipes now exercise full-step capture rather
  than disabling CUDA graphs solely because their schedule is looped.

This change only removes the obsolete blanket validation. It does not rewrite
schedule actions, add polling, require deferred receives, or expose another
pipeline configuration flag. Cases with independent blockers remain explicitly
disabled, including validation that reinitializes the shared schedule and
split-backward schedules with values that are not CUDA-graph inputs.

This supersedes the closed prototype in #4485.

Dependencies:
- pytorch/pytorch#196665
- pytorch/pytorch#196666
- #4540

Test Plan:
- `python -m pytest -q tests/unit_tests/cpu/test_config_manager.py -k cuda_graphs`
- `pre-commit run --files tests/integration_tests/features.py tests/unit_tests/cpu/test_config_manager.py torchtitan/config/configs.py torchtitan/trainer.py torchtitan_recipes/tests/features.py`
- Four-GPU `pp_looped_1f1b_cudagraph` integration test with repeated full-step
  capture and replay.

[ghstack-poisoned]
sanketpurandare added a commit to pytorch/torchtitan that referenced this pull request Sep 25, 2026
…les"

TorchTitan captures the complete eager pipeline step, but previously rejected
every multi-stage looped schedule. A shared P2P communicator can serialize
logical pipeline edges in incompatible orders during CUDA-graph replay, so
removing that validation without first fixing communicator ownership would make
the expanded support unsafe.

Enable looped-schedule capture after the lower runtime layers establish the
required invariant:

- PyTorch derives one process group for each directed physical-rank edge from
  the finalized schedule topology, initializes and warms those groups before
  capture, and shares one Store connection across split children;
- TorchTitan enables that directed-edge topology automatically whenever PP is
  active; it is not a user-selectable policy;
- existing supported PP feature recipes now exercise full-step capture rather
  than disabling CUDA graphs solely because their schedule is looped.

This change only removes the obsolete blanket validation. It does not rewrite
schedule actions, add polling, require deferred receives, or expose another
pipeline configuration flag. Cases with independent blockers remain explicitly
disabled, including validation that reinitializes the shared schedule and
split-backward schedules with values that are not CUDA-graph inputs.

This supersedes the closed prototype in #4485.

Dependencies:
- pytorch/pytorch#196665
- pytorch/pytorch#196666
- #4540

Test Plan:
- `python -m pytest -q tests/unit_tests/cpu/test_config_manager.py -k cuda_graphs`
- `pre-commit run --files tests/integration_tests/features.py tests/unit_tests/cpu/test_config_manager.py torchtitan/config/configs.py torchtitan/trainer.py torchtitan_recipes/tests/features.py`
- Four-GPU `pp_looped_1f1b_cudagraph` integration test with repeated full-step
  capture and replay.

[ghstack-poisoned]
sanketpurandare added a commit to pytorch/torchtitan that referenced this pull request Sep 25, 2026
TorchTitan captures the complete eager pipeline step, but previously rejected
every multi-stage looped schedule. A shared P2P communicator can serialize
logical pipeline edges in incompatible orders during CUDA-graph replay, so
removing that validation without first fixing communicator ownership would make
the expanded support unsafe.

Enable looped-schedule capture after the lower runtime layers establish the
required invariant:

- PyTorch derives one process group for each directed physical-rank edge from
  the finalized schedule topology, initializes and warms those groups before
  capture, and shares one Store connection across split children;
- TorchTitan enables that directed-edge topology automatically whenever PP is
  active; it is not a user-selectable policy;
- existing supported PP feature recipes now exercise full-step capture rather
  than disabling CUDA graphs solely because their schedule is looped.

This change only removes the obsolete blanket validation. It does not rewrite
schedule actions, add polling, require deferred receives, or expose another
pipeline configuration flag. Cases with independent blockers remain explicitly
disabled, including validation that reinitializes the shared schedule and
split-backward schedules with values that are not CUDA-graph inputs.

This supersedes the closed prototype in #4485.

Dependencies:
- pytorch/pytorch#196665
- pytorch/pytorch#196666
- #4540

Test Plan:
- `python -m pytest -q tests/unit_tests/cpu/test_config_manager.py -k cuda_graphs`
- `pre-commit run --files tests/integration_tests/features.py tests/unit_tests/cpu/test_config_manager.py torchtitan/config/configs.py torchtitan/trainer.py torchtitan_recipes/tests/features.py`
- Four-GPU `pp_looped_1f1b_cudagraph` integration test with repeated full-step
  capture and replay.

[ghstack-poisoned]
sanketpurandare added a commit to pytorch/torchtitan that referenced this pull request Sep 25, 2026
…les"

TorchTitan captures the complete eager pipeline step, but previously rejected
every multi-stage looped schedule. A shared P2P communicator can serialize
logical pipeline edges in incompatible orders during CUDA-graph replay, so
removing that validation without first fixing communicator ownership would make
the expanded support unsafe.

Enable looped-schedule capture after the lower runtime layers establish the
required invariant:

- PyTorch derives one process group for each directed physical-rank edge from
  the finalized schedule topology, initializes and warms those groups before
  capture, and shares one Store connection across split children;
- TorchTitan enables that directed-edge topology automatically whenever PP is
  active; it is not a user-selectable policy;
- existing supported PP feature recipes now exercise full-step capture rather
  than disabling CUDA graphs solely because their schedule is looped.

This change only removes the obsolete blanket validation. It does not rewrite
schedule actions, add polling, require deferred receives, or expose another
pipeline configuration flag. Cases with independent blockers remain explicitly
disabled, including validation that reinitializes the shared schedule and
split-backward schedules with values that are not CUDA-graph inputs.

This supersedes the closed prototype in #4485.

Dependencies:
- pytorch/pytorch#196665
- pytorch/pytorch#196666
- #4540

Test Plan:
- `python -m pytest -q tests/unit_tests/cpu/test_config_manager.py -k cuda_graphs`
- `pre-commit run --files tests/integration_tests/features.py tests/unit_tests/cpu/test_config_manager.py torchtitan/config/configs.py torchtitan/trainer.py torchtitan_recipes/tests/features.py`
- Four-GPU `pp_looped_1f1b_cudagraph` integration test with repeated full-step
  capture and replay.

[ghstack-poisoned]
sanketpurandare added a commit to pytorch/torchtitan that referenced this pull request Sep 25, 2026
TorchTitan captures the complete eager pipeline step, but previously rejected
every multi-stage looped schedule. A shared P2P communicator can serialize
logical pipeline edges in incompatible orders during CUDA-graph replay, so
removing that validation without first fixing communicator ownership would make
the expanded support unsafe.

Enable looped-schedule capture after the lower runtime layers establish the
required invariant:

- PyTorch derives one process group for each directed physical-rank edge from
  the finalized schedule topology, initializes and warms those groups before
  capture, and shares one Store connection across split children;
- TorchTitan enables that directed-edge topology automatically whenever PP is
  active; it is not a user-selectable policy;
- existing supported PP feature recipes now exercise full-step capture rather
  than disabling CUDA graphs solely because their schedule is looped.

This change only removes the obsolete blanket validation. It does not rewrite
schedule actions, add polling, require deferred receives, or expose another
pipeline configuration flag. Cases with independent blockers remain explicitly
disabled, including validation that reinitializes the shared schedule and
split-backward schedules with values that are not CUDA-graph inputs.

This supersedes the closed prototype in #4485.

Dependencies:
- pytorch/pytorch#196665
- pytorch/pytorch#196666
- #4540

Test Plan:
- `python -m pytest -q tests/unit_tests/cpu/test_config_manager.py -k cuda_graphs`
- `pre-commit run --files tests/integration_tests/features.py tests/unit_tests/cpu/test_config_manager.py torchtitan/config/configs.py torchtitan/trainer.py torchtitan_recipes/tests/features.py`
- Four-GPU `pp_looped_1f1b_cudagraph` integration test with repeated full-step
  capture and replay.

[ghstack-poisoned]
@github-actions
github-actions Bot deleted the gh/sanketpurandare/10/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/torchtitan Run TorchTitan integration tests Merged module: c10d Issues/PRs related to collective communications and process groups release notes: distributed (c10d) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants