Skip to content

[distributed] Isolate FSDP communicators from WORLD/CP - #5663

Open
tranle-fw wants to merge 3 commits into
pytorch:mainfrom
tranle-fw:fix-fsdp-communicator-isolation
Open

tranle-fw wants to merge 3 commits into
pytorch:mainfrom
tranle-fw:fix-fsdp-communicator-isolation

Conversation

@tranle-fw

Copy link
Copy Markdown
  • Give FSDP dp_replicate, edp_shard, and flattened dp_shard * cp axes dedicated process groups, preserving the configured backend and FSDP2 mesh semantics.
  • Add pure-CP/pure-DDP communicator-identity tests and an 82-line manual NCCL ordering probe.
  • Four-B300 diagnostic: shared PG 0 / sequence 3 watchdogs; separate communicators complete with exact outputs on all four ranks. This deliberately reverses host submission order; completion is measured here, not a general reversed-order guarantee (NVIDIA contract).
  • Continues [distributed] Isolate FSDP from CP's default-group reuse to prevent a deadlock #5645 under this account; Pei's original commits and authorship are preserved.
Reproduction commands and measured setup

Exact tested source: 2d52ccd1, fault at line 56. Both runs used the same four B300 GPUs and PyTorch 2.13.0a0+8145d630e8.nv26.06, CUDA 13.3, NCCL 2.30.5.

Run each case in a separate process/container with an external deadline. Equivalent local invocations with the recorded communication settings:

export NCCL_LAUNCH_ORDER_IMPLICIT=1
export NCCL_CUMEM_ENABLE=0 NCCL_CUMEM_HOST_ENABLE=0 NCCL_NVLS_ENABLE=0
export NCCL_SOCKET_IFNAME=lo NCCL_DEBUG=WARN TORCH_NCCL_DUMP_ON_TIMEOUT=0

timeout --signal=KILL 150s torchrun --standalone --nproc-per-node=4 scripts/repro_collective_order.py
timeout --signal=KILL 150s torchrun --standalone --nproc-per-node=4 scripts/repro_collective_order.py --separate-group

The measured runs used a container deadline and a CUDA-readiness gate before process-group creation; neither changes the script's fault phase. No GPU delay is injected. Source SHA256: fb0abc0ec4a74a099a8f89125bf71e270cd9092253191f4c7e62aea79f6e88be.

Fresh run of the exact script: sanitized forced-order logs

Four CUDA ranks; PyTorch 2.13.0a0, CUDA 13.3, NCCL 2.30.5; NCCL_LAUNCH_ORDER_IMPLICIT=1 in both runs. After matching AG→A2A warmup, rank 0 deliberately submits A2A→AG while peers submit AG→A2A. This is a host-order negative control, not GPU-only skew or a natural FSDP prefetch reproduction. Host/process identifiers, timestamps, paths and addresses are omitted; retained lines/payloads below are unchanged.

Shared group: all ranks warm up and both asynchronous calls return on every rank, then collective sequence 3 times out.

rank=0 WARMED
rank=0 warmup=False submitted=a2a
rank=0 warmup=False submitted=ag
rank=2 WARMED
rank=3 WARMED
rank=2 warmup=False submitted=ag
rank=3 warmup=False submitted=ag
rank=2 warmup=False submitted=a2a
rank=3 warmup=False submitted=a2a
rank=1 WARMED
rank=1 warmup=False submitted=ag
rank=1 warmup=False submitted=a2a
[Rank 3] Watchdog caught collective operation timeout: WorkNCCL(SeqNum=3, OpType=_ALLGATHER_BASE, NumelIn=1048576, NumelOut=4194304, Timeout(ms)=30000)
[Rank 2] Watchdog caught collective operation timeout: WorkNCCL(SeqNum=3, OpType=_ALLGATHER_BASE, NumelIn=1048576, NumelOut=4194304, Timeout(ms)=30000)
[Rank 0] Watchdog caught collective operation timeout: WorkNCCL(SeqNum=3, OpType=ALLTOALL_BASE, NumelIn=1048576, NumelOut=1048576, Timeout(ms)=30000)
[Rank 1] Watchdog caught collective operation timeout: WorkNCCL(SeqNum=3, OpType=_ALLGATHER_BASE, NumelIn=1048576, NumelOut=4194304, Timeout(ms)=30000)

Dedicated all-gather group: the same opposite host order completes. PASS is printed after CUDA synchronization and exact checks of both outputs.

rank=2 PASS
rank=0 PASS
rank=1 PASS
rank=3 PASS

The shared run recorded the 30-second watchdog, then required its external 150-second container deadline (exit 137). The dedicated run exited 0 in 16.090 seconds. Dedicated completion is an empirical result of this test, not a general guarantee for reversed cross-communicator order.

zpcore and others added 3 commits October 28, 2026 07:39
… deadlock

DeviceMesh._init_one_process_group reuses the default (WORLD) process
group -- instead of creating a dedicated communicator -- for any mesh
dimension (including one produced by DeviceMesh._flatten) whose ranks
span every rank, unless an explicit backend_override is passed.

FSDP shards parameters on dp_shard * cp. When dp_shard == 1 (the common
CP-only configuration), that flattened axis spans every rank, and so
does CPs own cp axis. Both silently collapsed onto the same WORLD
process group / NCCL communicator. dp_replicate (pure DDP) and
edp_shard (EP with no other sparse-region parallelism) have the same
failure mode on their own, single-axis groups.

FSDP issues its all-gather/reduce-scatter from its own dedicated CUDA
streams, while CP's collectives run on the default/compute stream.
Nothing orders those two streams against each other, so the two
collectives can be enqueued in different host-side orders across
ranks. Two collectives sharing one communicator must be posted in the
same order by every rank, so a mismatched order deadlocks NCCL instead
of merely serializing -- this is config-deterministic (whether the
groups collide) but the deadlock itself is a scheduling race, which is
why it does not reproduce on every run.

Fix: give FSDP's shard/replicate axes a dedicated backend_override so
they never alias the default group, whether built directly
(dp_replicate, edp_shard, in ParallelismContext.build_mesh) or
flattened later from multiple axes (dp_shard * cp, in
resolve_fsdp_mesh).

Adds a CPU regression test reproducing the dp_shard=1/cp=world_size
collision and the pure-DDP dp_replicate=world_size collision.
…ten under FSDP2's name

fully_shard validates every shard name against the storage mesh's dim
names, so passing the flattened 'dp_shard_cp' name broke all CP configs.
Keep the ('dp_shard', 'cp') tuple and pre-flatten with the same
'_'.join name FSDP2 uses so its own flatten hits the cached dedicated PG.
The unit test now goes through _validate_mesh/_get_mesh_info.
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 29, 2026
@tranle-fw
tranle-fw requested a review from wconstab as a code owner October 29, 2026 00:25
@meta-cla

meta-cla Bot commented Oct 29, 2026

Copy link
Copy Markdown

Hi @tranle-fw!

Thank you for your pull request and welcome to our community.

Action Required

In order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you.

Process

In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at [email protected]. Thanks!

@pytorch-bot

pytorch-bot Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@meta-cla

meta-cla Bot commented Oct 29, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 29, 2026
@meta-cla

meta-cla Bot commented Oct 29, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

@fegin

fegin commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

@tranle-fw thanks for the mini-repro. I understand order issue so I think the mini-repro script is correct. What I want to understand is what TorchTitan's command, parallelisms setting make you discovered such an issue? I would like to know why we didn't discover this issue even though we have done CP only several times. Thanks!

Also, please sign the CLA

@tranle-fw

tranle-fw commented Oct 29, 2026 •

Copy link
Copy Markdown
Author

Thanks for the response @fegin

re: command & parallelism setting, we use normal torchrun with our internal implementations of CP. From my experience, if the parallelism use p2p collectives, it'll more likely trigger the issue. We have production jobs running for months before triggering this hang, so it's incredibly hard to reproduce.

Bug is triggered only when CP/FSDP span the whole world size which then shares the default pg (communicator).

@fegin

fegin commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

@claude review this PR

@claude

claude Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @fegin's task in 3m 17s —— View job


Request changes: the PR hasn't shown the bug on torchtitan main, and its stream-based root-cause explanation doesn't match how a single NCCL communicator orders work. See the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Request changes -- the PR hasn't shown that the bug exists in torchtitan on main, and its explanation of the root cause doesn't match how a single NCCL communicator orders work. Isolating the groups could also bring in the cross-communicator ordering risk that the NVIDIA doc warns about.

What this PR does. When a mesh axis spans every rank, DeviceMesh reuses the WORLD process group instead of creating a new one. This PR passes an explicit backend_override so that FSDP's dp_replicate, edp_shard, and flattened dp_shard*cp axes get dedicated process groups. It pre-flattens dp_shard_cp under the name FSDP2 will use later, so FSDP2 picks the dedicated group out of the cache. It also adds two CPU tests and a manual NCCL probe script.

Example. cp=4, dp_shard=dp_replicate=tp=pp=1 on 4 GPUs:

main: cp axis -> WORLD; FSDP shard axis dp_shard*cp (size 4) -> WORLD   (one communicator)
PR:   cp axis -> WORLD; FSDP shard axis -> new 4-rank PG                (two communicators)

The repro deadlocks only because rank 0 is forced to submit A2A->AG on the host while the other ranks submit AG->A2A. Torchtitan never does this, because its host order is the same on every rank. @fegin has run CP8 and CP16 with dp_shard=1 many times without a hang. The author's answer is that the hang shows up with an internal CP implementation that uses P2P.

Must fix

  1. The problem isn't shown on main. @fegin's question ("what TorchTitan command / parallelisms") is still open: the only reported trigger is an out-of-tree CP. If that CP issues collectives in a rank-dependent host order (from a thread, data-dependent P2P, or lazily created P2P communicators), the fix belongs there. Please give either a torchtitan config that hangs, or an NCCL/flight-recorder trace from the production hang showing the mismatched sequence numbers across ranks.
  2. torchtitan/distributed/parallelism_context.py:95-100 -- the stream-based rationale is incorrect: the stream a collective is issued from doesn't change its host enqueue order, and one communicator serializes its work in launch order (inline).
  3. The fix may just move the hazard. Once the groups are separate, the GPU order of FSDP and CP kernels really can differ across ranks. The linked NVIDIA doc says that can deadlock unless launch order is consistent or NCCL_LAUNCH_ORDER_IMPLICIT is set, and both measured runs set NCCL_LAUNCH_ORDER_IMPLICIT=1 (inline on the script).
  4. torchtitan/distributed/parallelism_context.py:77-80 -- the dp_replicate and edp_shard overrides don't address the CP case. The dp_replicate one adds a world-size communicator under pure DDP; the edp_shard one is a no-op (inline).
  5. torchtitan/distributed/fsdp.py:145-150 -- the fix depends on FSDP2's private flatten naming and on DeviceMesh caching by name, with no upstream TODO or issue (inline).
  6. scripts/repro_collective_order.py -- remove it; it's a probe of documented NCCL behavior with no consumer in the repo (inline).

Should consider

  • tests/unit_tests/cpu/distributed/test_parallelism_context.py:22-25 -- the test re-derives the FSDP shard group using private FSDP2 helpers (inline).
  • parallelism_context.py:37-44 -- re-sorting __all__ is unrelated to the fix.

Questions

  • In the production hang, which collectives were at the mismatched sequence number on each rank? Were both on PG 0, and was one of them a P2P op from the internal CP?
  • If isolation is still wanted after (1) is answered, should a dedicated FSDP group become an option in FSDP2/DeviceMesh upstream rather than a pre-flatten trick here?
Details
  • Host order within one PG: FSDP2's pre-forward/pre-backward hooks and CP's attention collectives run on the main Python thread in the same program order on every rank. ProcessGroupNCCL launches every op of a PG on that PG's NCCL stream, waiting on the caller's current stream. Issuing from all_gather_stream instead of the compute stream changes the dependency, not the sequence number.
  • If the change is still wanted after the root cause is established, the smallest version is just the fsdp.py pre-flatten with a TODO linking an upstream issue (~10 lines), with no _FSDP_SINGLE_AXIS_NAMES, no DDP test, and no script.
  • After this PR, CP's cp axis still shares WORLD with loss_mesh (dp*cp) and grad-norm reductions. That is fine under same-order host submission, and it is the same argument for why the FSDP/CP share is fine as well.

Not verified: NCCL-internal serialization of one communicator across user streams; DeviceMesh flatten-cache behavior on the pinned torch; no GPU runs. A maintainer still needs to review.

Comment on lines +95 to +100
FSDP issues its all-gather/reduce-scatter from its own dedicated CUDA
streams, while CP's collectives run on the default/compute stream. Nothing
orders those two streams against each other, so the two collectives can be
enqueued in different host-side orders across ranks. Two collectives
sharing one communicator must be posted in the same order by every rank,
so a mismatched order deadlocks NCCL instead of merely serializing.

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.

This explanation doesn't follow. The CUDA stream a collective is issued from has no effect on its host enqueue order. Host order is program order, and in torchtitan that's identical on every rank (FSDP hooks and CP calls run in the same Python sequence everywhere). For a single process group, ProcessGroupNCCL launches every collective on that PG's own NCCL stream, and NCCL serializes the operations of one communicator in launch order. So two collectives on one communicator can't be reordered on the GPU differently per rank. That's why the repro script has to force rank 0 to submit A2A before AG on the host.

If this docstring and the test docstring stay, they will teach a false model of NCCL semantics. Please either show the concrete rank-dependent host ordering that happens in a real run, or restate the rationale. (unverified: the NCCL-internal serialization detail; a NCCL debug trace from the production hang would settle it.)

Comment on lines +77 to +80
_FSDP_SINGLE_AXIS_NAMES = (
MeshAxisName.DP_REPLICATE.value,
MeshAxisName.EDP_SHARD.value,
)

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.

Neither entry addresses the stated CP hazard:

  • dp_replicate spans every rank only when dp_shard == cp == tp == pp == 1. That's pure DDP, where no CP collective exists to collide with. Under pure DDP this adds a dedicated world-size communicator (dense mesh, plus a second one in the sparse-mesh unflatten at L379) on a main-path config, with no hazard identified.
  • edp_shard = dp_shard*cp*tp/ep is active only when ep > 1 (_axis_is_active, L279-282), so it is always strictly smaller than the world and never aliases WORLD. The override there does nothing.

Suggest deleting _FSDP_SINGLE_AXIS_NAMES and the elif at L338, along with test_pure_ddp_dp_replicate_group_is_dedicated. The only case the PR's theory covers is the flattened dp_shard * cp axis in resolve_fsdp_mesh.

Comment on lines +145 to +150
storage_mesh[shard]._flatten(
"_".join(shard),
backend_override=dedicated_pg_backend_override(
parallelism_context.world_mesh
),
)

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.

This only works because two private upstream behaviors happen to line up. FSDP2 internally flattens with exactly "_".join(names), and DeviceMesh._flatten returns the cached flattened mesh by name even though the later call passes no backend_override. If either detail changes upstream, the fix silently turns off and the regression test is the only signal.

Also, the underlying behavior ("a full-world mesh axis silently reuses WORLD unless you pass a backend override") belongs to DeviceMesh/FSDP2. Per CLAUDE.md principle 3, this needs a TODO linking a pytorch/pytorch issue. Better still, upstream should provide an option for FSDP2 or DeviceMesh to request a dedicated PG.

A side effect: resolve_fsdp_mesh is a resolver, and it now mutates the shared root mesh's flatten cache on every call (flux calls it twice, from trainer.py:176 and model.py:294). (unverified: re-flattening an already-flattened name with an override is a no-op on the pinned torch.)

Comment on lines +7 to +17
"""Force a collective-order mismatch on two or more CUDA GPUs.

torchrun --standalone --nproc-per-node=4 scripts/repro_collective_order.py
torchrun --standalone --nproc-per-node=4 scripts/repro_collective_order.py --separate-group

After matching warmup, rank 0 submits A2A then AG; peers submit AG then A2A.
Shared groups should time out. Separate groups remove the matching conflict.
This reversed-order schedule is diagnostic, not a supported application pattern.
This is an intentional ordering-fault test, not a natural FSDP prefetch repro.
Run each case separately with an external deadline; a timeout can abort CUDA.
"""

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.

Please drop this file from the PR. It demonstrates documented NCCL behavior: when ranks submit collectives to one communicator in different host orders, they deadlock. It doesn't demonstrate a torchtitan bug, and its own docstring says it is "not a natural FSDP prefetch repro" and "not a supported application pattern". It also has no consumer in the repo and calls torch.cuda.* directly. A gist linked from the PR description is enough.

Also note the separate-group "PASS" was measured with NCCL_LAUNCH_ORDER_IMPLICIT=1. The NVIDIA doc you link says reversed cross-communicator order can deadlock without implicit launch ordering. So the probe doesn't show that the fix is safe under default NCCL settings.

Comment on lines +22 to +25
from torch.distributed.fsdp._fully_shard._fsdp_init import (
_get_mesh_info,
_validate_mesh,
)

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.

The test imports _get_mesh_info and _validate_mesh, which are private FSDP2 internals, to re-derive the shard group. If the fix stays, a sturdier check is to call fully_shard on a tiny module with the resolved mesh and compare the group of the resulting FSDPParamGroup's mesh_info.shard_process_group against the CP group. Or just assert that storage_mesh[("dp_shard", "cp")]._flatten("dp_shard_cp").get_group() is not the default group. Either way, the docstring above it repeats the stream/host-order rationale, which needs correcting (see the comment on parallelism_context.py).

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

Please check claude's review and my review.

Comment on lines +136 to +150
if len(shard_axes) > 1:
shard = tuple(shard_axes)
# FSDP2 flattens multi-axis shard dims as
# ``mesh[names]._flatten("_".join(names))`` with no backend override.
# ``dp_shard * cp`` spans every rank whenever ``dp_shard == 1``, and
# then ``DeviceMesh`` would reuse the default/WORLD process group --
# the same group CP's own ``cp`` axis reuses in that case (see
# ``dedicated_pg_backend_override``). Flatten under the same name
# first so FSDP2's flatten hits this dedicated group in the cache.
storage_mesh[shard]._flatten(
"_".join(shard),
backend_override=dedicated_pg_backend_override(
parallelism_context.world_mesh
),
)

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.

Instead of exposing this knowledge to fsdp.py, we should be able to do this in parallelism_context.py. The convention is to create every mesh in parallelism_context.py.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants