Repository navigation
Conversation
… 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.
|
Hi @tranle-fw! Thank you for your pull request and welcome to our community. Action RequiredIn 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. ProcessIn 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 If you have received this in error or have any questions, please contact us at [email protected]. Thanks! |
|
|
|
Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks! |
|
Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks! |
|
@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 |
|
Thanks for the response @fegin re: command & parallelism setting, we use normal Bug is triggered only when CP/FSDP span the whole world size which then shares the default pg (communicator). |
|
@claude review this PR |
There was a problem hiding this comment.
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
- 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. 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).- 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_IMPLICITis set, and both measured runs setNCCL_LAUNCH_ORDER_IMPLICIT=1(inline on the script). torchtitan/distributed/parallelism_context.py:77-80-- thedp_replicateandedp_shardoverrides don't address the CP case. Thedp_replicateone adds a world-size communicator under pure DDP; theedp_shardone is a no-op (inline).torchtitan/distributed/fsdp.py:145-150-- the fix depends on FSDP2's private flatten naming and onDeviceMeshcaching by name, with no upstream TODO or issue (inline).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_streaminstead 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.pypre-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
cpaxis still shares WORLD withloss_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.
| 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. |
There was a problem hiding this comment.
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.)
| _FSDP_SINGLE_AXIS_NAMES = ( | ||
| MeshAxisName.DP_REPLICATE.value, | ||
| MeshAxisName.EDP_SHARD.value, | ||
| ) |
There was a problem hiding this comment.
Neither entry addresses the stated CP hazard:
dp_replicatespans every rank only whendp_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/epis active only whenep > 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.
| storage_mesh[shard]._flatten( | ||
| "_".join(shard), | ||
| backend_override=dedicated_pg_backend_override( | ||
| parallelism_context.world_mesh | ||
| ), | ||
| ) |
There was a problem hiding this comment.
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.)
| """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. | ||
| """ |
There was a problem hiding this comment.
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.
| from torch.distributed.fsdp._fully_shard._fsdp_init import ( | ||
| _get_mesh_info, | ||
| _validate_mesh, | ||
| ) |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
Please check claude's review and my review.
| 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 | ||
| ), | ||
| ) |
There was a problem hiding this comment.
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.
dp_replicate,edp_shard, and flatteneddp_shard * cpaxes dedicated process groups, preserving the configured backend and FSDP2 mesh semantics.Reproduction commands and measured setup
Exact tested source:
2d52ccd1, fault at line 56. Both runs used the same four B300 GPUs and PyTorch2.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:
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=1in 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.
Dedicated all-gather group: the same opposite host order completes.
PASSis printed after CUDA synchronization and exact checks of both outputs.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.