Skip to content

[DTensor] Make loss parallel support multi-dimensional mesh - #180936

Closed
fegin wants to merge 19 commits into
gh/fegin/345/basefrom
gh/fegin/345/head
Closed

fegin wants to merge 19 commits into
gh/fegin/345/basefrom
gh/fegin/345/head

Conversation

@fegin

@fegin fegin commented Apr 20, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Extend loss_parallel() from 1D-only to N-D mesh. The TP dim is now any
single mesh dim that shards the class dimension (not necessarily last);
the remaining mesh dims may be Shard (DP/CP) or Replicate.

Output placements by reduction:

  • "none": inherits target placements (Shard on batch dims, Replicate on TP).
  • "sum": Replicate on TP (custom all-reduce makes each rank's value
    globally correct), Partial("sum") on other Shard dims so the cross-rank
    reduction happens lazily on materialization/redistribution.
  • "mean": rejected on N-D mesh — total_weight is a per-rank local count,
    so aggregation across non-TP dims would not yield the correct global
    mean; use "sum"/"none" and divide by the global count.

For reduction="none", the backward handler redistributes grad_output to
the forward output placements, since autograd may deliver it replicated
even when the forward output was batch-sharded.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Apr 20, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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), 2 Unclassified Failures

As of commit 99315bc with merge base 9c77719 (image):

UNCLASSIFIED FAILURES - DrCI could not classify the following jobs because the workflow did not run on the merge base. The failures may be pre-existing on trunk or introduced by this PR:

FLAKY - The following job failed but was likely due to flakiness present on trunk:

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

@pytorch-bot pytorch-bot Bot added ciflow/dtensor Run DTensor specific tests ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (dtensor) release notes category labels Apr 20, 2026
@fegin
fegin requested a review from tianyu-l April 21, 2026 00:08
@fegin
fegin marked this pull request as ready for review April 21, 2026 00:08
[ghstack-poisoned]
[ghstack-poisoned]
@joecummings

Copy link
Copy Markdown

Ignore review: thought this was in torchtitan, not pytorch/pytorch

@tianyu-l tianyu-l 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.

For reduction="none", the backward handler redistributes grad_output to
the forward output placements, since autograd may deliver it replicated
even when the forward output was batch-sharded.

would like to see an example on this

Comment on lines +547 to +549
# For reduction="none", autograd may deliver grad_output with different
# placements than the forward output (e.g. Replicate on a batch-sharded dim),
# causing a shape mismatch with the local batch. Redistribute it to match

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.

wait how is this possible ... do you have an example?

@fegin fegin Apr 23, 2026 •

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.

With DP in the sharding spec:

with loss_parallel():
    loss = F.cross_entropy(dist_logits, dist_target, reduction="none")  # [DP, TP] == [Shard(0), Shard(1)]
    loss.sum().backward()

DTensor will propagate the Replicate (it will always choose Replicate along this particular backward path), so grad_output will be [Replicate, Replicate] and will mismatch with the target_placements, [Shard(0), Replicate] and cause local_tensor shape mismatch.

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.

It sounds not the root cause. The root cause seems happening before this nll_loss_backward -- grad_out shouldn't be created as Replicate in the first place, given a Shard(0) inputs. Please leave a TODO for further investigation.

@fegin
fegin requested a review from tianyu-l April 23, 2026 22:30
fegin added a commit to pytorch/torchtitan that referenced this pull request Apr 30, 2026
…ama3

Add full DTensor mode where all params, buffers, and inputs are DTensors on a multi-dimensional SPMD mesh (``dp_replicate`` x ``dp_shard`` x ``cp`` x ``tp``). Enabled via ``--training.full_dtensor``. CP is handled declaratively via ``LocalMapSpec`` (K/V ``Replicate`` on CP dim for all-gather) instead of ``apply_cp_to_forward`` hooks. FSDP2 uses ``DataParallelMeshDims`` to identify ``dp_shard`` and ``cp`` as data-parallel dims on the multi-D mesh.

**Verified parallelisms:**

FSDP + TP
FSDP
HSDP
FSDP + TP
HSDP + TP
FSDP + CP + TP
PP + FSDP + TP
PP + FSDP + CP
PP + CP + TP

**Caveats:**

- CP + full_dtensor requires FlexAttention. After K/V all-gather on CP, Q and K/V have asymmetric sequence lengths, which SDPA/varlen cannot handle with ``is_causal=True``. ``validate_config`` enforces this.

- FSDP + TP requires a [PyTorch-side fix, PR180936](pytorch/pytorch#180936) to ``_find_all_reduce_mesh_dim``and ``_nll_loss_forward_handler`` in ``torch/distributed/tensor/parallel/loss.py`` so ``loss_parallel`` works on multi-D meshes.

- PP requires a [PyTorch-side fix, PR180937](pytorch/pytorch#180937) to use ``_split_tensor`` instead of  ``torch.tensor_split`` for the target microbatch split in``torch/distributed/pipelining/schedules.py``; the raw split goes through DTensor dispatch and turns ``Shard(0)`` into ``Replicate()``  via an implicit all-gather.

- FlexAttention needs ``max_autotune=True`` for compilation under TP + CP + FSDP.

- ``cross_entropy_loss`` uses ``pred.permute(0, 2, 1)`` (3D form) instead of ``pred.flatten(0, 1)`` when pred is a DTensor. Flattening merges differently-sharded dims (e.g. batch on ``dp_shard`` and seq on ``cp``) and produces ``_StridedShard``, which breaks downstream scalar loss dispatch. The permute avoids the merge and is functionally equivalent.

- EP is not supported with full_dtensor yet.

- Currently only llama3 has the full_dtensor sharding spec; other models  raise ``NotImplementedError`` from ``validate_config``.

ghstack-source-id: fe6cc5a
Pull-Request: #3159
fegin added a commit to pytorch/torchtitan that referenced this pull request Apr 30, 2026
…ama3

Add full DTensor mode where all params, buffers, and inputs are DTensors on a multi-dimensional SPMD mesh (``dp_replicate`` x ``dp_shard`` x ``cp`` x ``tp``). Enabled via ``--training.full_dtensor``. CP is handled declaratively via ``LocalMapSpec`` (K/V ``Replicate`` on CP dim for all-gather) instead of ``apply_cp_to_forward`` hooks. FSDP2 uses ``DataParallelMeshDims`` to identify ``dp_shard`` and ``cp`` as data-parallel dims on the multi-D mesh.

**Verified parallelisms:**

FSDP + TP
FSDP
HSDP
FSDP + TP
HSDP + TP
FSDP + CP + TP
PP + FSDP + TP
PP + FSDP + CP
PP + CP + TP

**Caveats:**

- CP + full_dtensor requires FlexAttention. After K/V all-gather on CP, Q and K/V have asymmetric sequence lengths, which SDPA/varlen cannot handle with ``is_causal=True``. ``validate_config`` enforces this.

- FSDP + TP requires a [PyTorch-side fix, PR180936](pytorch/pytorch#180936) to ``_find_all_reduce_mesh_dim``and ``_nll_loss_forward_handler`` in ``torch/distributed/tensor/parallel/loss.py`` so ``loss_parallel`` works on multi-D meshes.

- PP requires a [PyTorch-side fix, PR180937](pytorch/pytorch#180937) to use ``_split_tensor`` instead of  ``torch.tensor_split`` for the target microbatch split in``torch/distributed/pipelining/schedules.py``; the raw split goes through DTensor dispatch and turns ``Shard(0)`` into ``Replicate()``  via an implicit all-gather.

- FlexAttention needs ``max_autotune=True`` for compilation under TP + CP + FSDP.

- ``cross_entropy_loss`` uses ``pred.permute(0, 2, 1)`` (3D form) instead of ``pred.flatten(0, 1)`` when pred is a DTensor. Flattening merges differently-sharded dims (e.g. batch on ``dp_shard`` and seq on ``cp``) and produces ``_StridedShard``, which breaks downstream scalar loss dispatch. The permute avoids the merge and is functionally equivalent.

- EP is not supported with full_dtensor yet.

- Currently only llama3 has the full_dtensor sharding spec; other models  raise ``NotImplementedError`` from ``validate_config``.

ghstack-source-id: fe6cc5a
Pull-Request: #3159
fegin added a commit to pytorch/torchtitan that referenced this pull request Apr 30, 2026
…ama3

Add full DTensor mode where all params, buffers, and inputs are DTensors on a multi-dimensional SPMD mesh (``dp_replicate`` x ``dp_shard`` x ``cp`` x ``tp``). Enabled via ``--training.full_dtensor``. CP is handled declaratively via ``LocalMapConfig`` (K/V ``Replicate`` on CP dim for all-gather) instead of ``apply_cp_to_forward`` hooks. FSDP2 uses ``DataParallelMeshDims`` to identify ``dp_shard`` and ``cp`` as data-parallel dims on the multi-D mesh.

**Mesh Design:**

``ParallelDims`` precomputes one ``DeviceMesh`` per SPMD partition in ``_spmd_meshes`` (dense: ``(dp_replicate, dp_shard, cp, tp)``). Each ``Module`` self-resolves its mesh: ``_needed_axes(sharding_config)`` collects axes referenced by its ``NamedPlacement``s, then ``parallel_dims.get_module_mesh(axes)`` returns the cached submesh. Under ``full_dtensor``, all axes participate; under the legacy path, axes are filtered to ``{tp, ep, etp}`` so DP/CP stay out-of-band. ``Module.parallelize`` asserts the resolved mesh is one of ``spmd_meshes()`` (identity check) - out-of-order axes resolve to a different submesh and fail the check, enforcing the canonical axis order.

The same mechanism extends to sparse: a second SPMD partition ``(dp_replicate, efsdp, ep, etp)`` lives alongside dense in ``_spmd_meshes``, so MoE modules whose ``sharding_config`` references sparse axes resolve to the sparse submesh through the exact same ``get_module_mesh`` call - no model-side branching.

**Verified parallelisms:**

FSDP + TP
FSDP
HSDP
FSDP + TP
HSDP + TP
FSDP + CP + TP
PP + FSDP + TP
PP + FSDP + CP
PP + CP + TP

**Caveats:**

- CP + full_dtensor requires FlexAttention. After K/V all-gather on CP, Q and K/V have asymmetric sequence lengths, which SDPA/varlen cannot handle with ``is_causal=True``. ``validate_config`` enforces this.

- FSDP + TP requires a [PyTorch-side fix, PR180936](pytorch/pytorch#180936) to ``_find_all_reduce_mesh_dim``and ``_nll_loss_forward_handler`` in ``torch/distributed/tensor/parallel/loss.py`` so ``loss_parallel`` works on multi-D meshes.

- PP requires a [PyTorch-side fix, PR180937](pytorch/pytorch#180937) to use ``_split_tensor`` instead of  ``torch.tensor_split`` for the target microbatch split in``torch/distributed/pipelining/schedules.py``; the raw split goes through DTensor dispatch and turns ``Shard(0)`` into ``Replicate()``  via an implicit all-gather.

- ``full_dtensor + CP + --compile.enable`` (model compile) hangs. Root cause is an upstream PyTorch limitation: ``placement_types.py:1169`` ``.tolist()`` triggers a symint storm during compilation. ``max_autotune`` does not help. Workaround: disable ``--compile.enable`` when running CP under full_dtensor.

- ``cross_entropy_loss`` uses ``pred.permute(0, 2, 1)`` (3D form) instead of ``pred.flatten(0, 1)`` when pred is a DTensor. Flattening merges differently-sharded dims (e.g. batch on ``dp_shard`` and seq on ``cp``) and produces ``_StridedShard``, which breaks downstream scalar loss dispatch. The permute avoids the merge and is functionally equivalent.

- EP is not supported with full_dtensor yet.

- Currently only llama3 has the full_dtensor sharding config; other models  raise ``NotImplementedError`` from ``validate_config``.

ghstack-source-id: b356f6b
Pull-Request: #3159
fegin added a commit to pytorch/torchtitan that referenced this pull request Apr 30, 2026
…ama3

Add full DTensor mode where all params, buffers, and inputs are DTensors on a multi-dimensional SPMD mesh (``dp_replicate`` x ``dp_shard`` x ``cp`` x ``tp``). Enabled via ``--training.full_dtensor``. CP is handled declaratively via ``LocalMapConfig`` (K/V ``Replicate`` on CP dim for all-gather) instead of ``apply_cp_to_forward`` hooks. FSDP2 uses ``DataParallelMeshDims`` to identify ``dp_shard`` and ``cp`` as data-parallel dims on the multi-D mesh.

**Mesh Design:**

``ParallelDims`` precomputes one ``DeviceMesh`` per SPMD partition in ``_spmd_meshes`` (dense: ``(dp_replicate, dp_shard, cp, tp)``). Each ``Module`` self-resolves its mesh: ``_needed_axes(sharding_config)`` collects axes referenced by its ``NamedPlacement``s, then ``parallel_dims.get_module_mesh(axes)`` returns the cached submesh. Under ``full_dtensor``, all axes participate; under the legacy path, axes are filtered to ``{tp, ep, etp}`` so DP/CP stay out-of-band. ``Module.parallelize`` asserts the resolved mesh is one of ``spmd_meshes()`` (identity check) - out-of-order axes resolve to a different submesh and fail the check, enforcing the canonical axis order.

The same mechanism extends to sparse: a second SPMD partition ``(dp_replicate, efsdp, ep, etp)`` lives alongside dense in ``_spmd_meshes``, so MoE modules whose ``sharding_config`` references sparse axes resolve to the sparse submesh through the exact same ``get_module_mesh`` call - no model-side branching.

**Verified parallelisms:**

FSDP + TP
FSDP
HSDP
FSDP + TP
HSDP + TP
FSDP + CP + TP
PP + FSDP + TP
PP + FSDP + CP
PP + CP + TP

**Caveats:**

- CP + full_dtensor requires FlexAttention. After K/V all-gather on CP, Q and K/V have asymmetric sequence lengths, which SDPA/varlen cannot handle with ``is_causal=True``. ``validate_config`` enforces this.

- FSDP + TP requires a [PyTorch-side fix, PR180936](pytorch/pytorch#180936) to ``_find_all_reduce_mesh_dim``and ``_nll_loss_forward_handler`` in ``torch/distributed/tensor/parallel/loss.py`` so ``loss_parallel`` works on multi-D meshes.

- PP requires a [PyTorch-side fix, PR180937](pytorch/pytorch#180937) to use ``_split_tensor`` instead of  ``torch.tensor_split`` for the target microbatch split in``torch/distributed/pipelining/schedules.py``; the raw split goes through DTensor dispatch and turns ``Shard(0)`` into ``Replicate()``  via an implicit all-gather.

- ``full_dtensor + CP + --compile.enable`` (model compile) hangs. Root cause is an upstream PyTorch limitation: ``placement_types.py:1169`` ``.tolist()`` triggers a symint storm during compilation. ``max_autotune`` does not help. Workaround: disable ``--compile.enable`` when running CP under full_dtensor.

- ``cross_entropy_loss`` uses ``pred.permute(0, 2, 1)`` (3D form) instead of ``pred.flatten(0, 1)`` when pred is a DTensor. Flattening merges differently-sharded dims (e.g. batch on ``dp_shard`` and seq on ``cp``) and produces ``_StridedShard``, which breaks downstream scalar loss dispatch. The permute avoids the merge and is functionally equivalent.

- EP is not supported with full_dtensor yet.

- Currently only llama3 has the full_dtensor sharding config; other models  raise ``NotImplementedError`` from ``validate_config``.

ghstack-source-id: b356f6b
Pull-Request: #3159
fegin added a commit to pytorch/torchtitan that referenced this pull request Apr 30, 2026
…ama3

Add full DTensor mode where all params, buffers, and inputs are DTensors on a multi-dimensional SPMD mesh (``dp_replicate`` x ``dp_shard`` x ``cp`` x ``tp``). Enabled via ``--training.full_dtensor``. CP is handled declaratively via ``LocalMapConfig`` (K/V ``Replicate`` on CP dim for all-gather) instead of ``apply_cp_to_forward`` hooks. FSDP2 uses ``DataParallelMeshDims`` to identify ``dp_shard`` and ``cp`` as data-parallel dims on the multi-D mesh.

**Mesh Design:**

``ParallelDims`` precomputes one ``DeviceMesh`` per SPMD partition in ``_spmd_meshes`` (dense: ``(dp_replicate, dp_shard, cp, tp)``). Each ``Module`` self-resolves its mesh: ``_needed_axes(sharding_config)`` collects axes referenced by its ``NamedPlacement``s, then ``parallel_dims.get_module_mesh(axes)`` returns the cached submesh. Under ``full_dtensor``, all axes participate; under the legacy path, axes are filtered to ``{tp, ep, etp}`` so DP/CP stay out-of-band. ``Module.parallelize`` asserts the resolved mesh is one of ``spmd_meshes()`` (identity check) - out-of-order axes resolve to a different submesh and fail the check, enforcing the canonical axis order.

The same mechanism extends to sparse: a second SPMD partition ``(dp_replicate, efsdp, ep, etp)`` lives alongside dense in ``_spmd_meshes``, so MoE modules whose ``sharding_config`` references sparse axes resolve to the sparse submesh through the exact same ``get_module_mesh`` call - no model-side branching.

**Verified parallelisms:**

FSDP + TP
FSDP
HSDP
FSDP + TP
HSDP + TP
FSDP + CP + TP
PP + FSDP + TP
PP + FSDP + CP
PP + CP + TP

**Caveats:**

- CP + full_dtensor requires FlexAttention. After K/V all-gather on CP, Q and K/V have asymmetric sequence lengths, which SDPA/varlen cannot handle with ``is_causal=True``. ``validate_config`` enforces this.

- FSDP + TP requires a [PyTorch-side fix, PR180936](pytorch/pytorch#180936) to ``_find_all_reduce_mesh_dim``and ``_nll_loss_forward_handler`` in ``torch/distributed/tensor/parallel/loss.py`` so ``loss_parallel`` works on multi-D meshes.

- PP requires a [PyTorch-side fix, PR180937](pytorch/pytorch#180937) to use ``_split_tensor`` instead of  ``torch.tensor_split`` for the target microbatch split in``torch/distributed/pipelining/schedules.py``; the raw split goes through DTensor dispatch and turns ``Shard(0)`` into ``Replicate()``  via an implicit all-gather.

- ``full_dtensor + CP + --compile.enable`` (model compile) hangs. Root cause is an upstream PyTorch limitation: ``placement_types.py:1169`` ``.tolist()`` triggers a symint storm during compilation. ``max_autotune`` does not help. Workaround: disable ``--compile.enable`` when running CP under full_dtensor.

- ``cross_entropy_loss`` uses ``pred.permute(0, 2, 1)`` (3D form) instead of ``pred.flatten(0, 1)`` when pred is a DTensor. Flattening merges differently-sharded dims (e.g. batch on ``dp_shard`` and seq on ``cp``) and produces ``_StridedShard``, which breaks downstream scalar loss dispatch. The permute avoids the merge and is functionally equivalent.

- EP is not supported with full_dtensor yet.

- Currently only llama3 has the full_dtensor sharding config; other models  raise ``NotImplementedError`` from ``validate_config``.

ghstack-source-id: bdfe093
Pull-Request: #3159
fegin added a commit to pytorch/torchtitan that referenced this pull request Apr 30, 2026
…ama3

Add full DTensor mode where all params, buffers, and inputs are DTensors on a multi-dimensional SPMD mesh (``dp_replicate`` x ``dp_shard`` x ``cp`` x ``tp``). Enabled via ``--training.full_dtensor``. CP is handled declaratively via ``LocalMapConfig`` (K/V ``Replicate`` on CP dim for all-gather) instead of ``apply_cp_to_forward`` hooks. FSDP2 uses ``DataParallelMeshDims`` to identify ``dp_shard`` and ``cp`` as data-parallel dims on the multi-D mesh.

**Mesh Design:**

``ParallelDims`` precomputes one ``DeviceMesh`` per SPMD partition in ``_spmd_meshes`` (dense: ``(dp_replicate, dp_shard, cp, tp)``). Each ``Module`` self-resolves its mesh: ``_needed_axes(sharding_config)`` collects axes referenced by its ``NamedPlacement``s, then ``parallel_dims.get_module_mesh(axes)`` returns the cached submesh. Under ``full_dtensor``, all axes participate; under the legacy path, axes are filtered to ``{tp, ep, etp}`` so DP/CP stay out-of-band. ``Module.parallelize`` asserts the resolved mesh is one of ``spmd_meshes()`` (identity check) - out-of-order axes resolve to a different submesh and fail the check, enforcing the canonical axis order.

The same mechanism extends to sparse: a second SPMD partition ``(dp_replicate, efsdp, ep, etp)`` lives alongside dense in ``_spmd_meshes``, so MoE modules whose ``sharding_config`` references sparse axes resolve to the sparse submesh through the exact same ``get_module_mesh`` call - no model-side branching.

**Verified parallelisms:**

FSDP + TP
FSDP
HSDP
FSDP + TP
HSDP + TP
FSDP + CP + TP
PP + FSDP + TP
PP + FSDP + CP
PP + CP + TP

**Caveats:**

- CP + full_dtensor requires FlexAttention. After K/V all-gather on CP, Q and K/V have asymmetric sequence lengths, which SDPA/varlen cannot handle with ``is_causal=True``. ``validate_config`` enforces this.

- FSDP + TP requires a [PyTorch-side fix, PR180936](pytorch/pytorch#180936) to ``_find_all_reduce_mesh_dim``and ``_nll_loss_forward_handler`` in ``torch/distributed/tensor/parallel/loss.py`` so ``loss_parallel`` works on multi-D meshes.

- PP requires a [PyTorch-side fix, PR180937](pytorch/pytorch#180937) to use ``_split_tensor`` instead of  ``torch.tensor_split`` for the target microbatch split in``torch/distributed/pipelining/schedules.py``; the raw split goes through DTensor dispatch and turns ``Shard(0)`` into ``Replicate()``  via an implicit all-gather.

- ``full_dtensor + CP + --compile.enable`` (model compile) hangs. Root cause is an upstream PyTorch limitation: ``placement_types.py:1169`` ``.tolist()`` triggers a symint storm during compilation. ``max_autotune`` does not help. Workaround: disable ``--compile.enable`` when running CP under full_dtensor.

- ``cross_entropy_loss`` uses ``pred.permute(0, 2, 1)`` (3D form) instead of ``pred.flatten(0, 1)`` when pred is a DTensor. Flattening merges differently-sharded dims (e.g. batch on ``dp_shard`` and seq on ``cp``) and produces ``_StridedShard``, which breaks downstream scalar loss dispatch. The permute avoids the merge and is functionally equivalent.

- EP is not supported with full_dtensor yet.

- Currently only llama3 has the full_dtensor sharding config; other models  raise ``NotImplementedError`` from ``validate_config``.

ghstack-source-id: d6c3c24
Pull-Request: #3159
fegin added a commit to pytorch/torchtitan that referenced this pull request Apr 30, 2026
…ama3

Add full DTensor mode where all params, buffers, and inputs are DTensors on a multi-dimensional SPMD mesh (``dp_replicate`` x ``dp_shard`` x ``cp`` x ``tp``). Enabled via ``--training.full_dtensor``. CP is handled declaratively via ``LocalMapConfig`` (K/V ``Replicate`` on CP dim for all-gather) instead of ``apply_cp_to_forward`` hooks. FSDP2 uses ``DataParallelMeshDims`` to identify ``dp_shard`` and ``cp`` as data-parallel dims on the multi-D mesh.

**Mesh Design:**

``ParallelDims`` precomputes one ``DeviceMesh`` per SPMD partition in ``_spmd_meshes`` (dense: ``(dp_replicate, dp_shard, cp, tp)``). Each ``Module`` self-resolves its mesh: ``_needed_axes(sharding_config)`` collects axes referenced by its ``NamedPlacement``s, then ``parallel_dims.get_module_mesh(axes)`` returns the cached submesh. Under ``full_dtensor``, all axes participate; under the legacy path, axes are filtered to ``{tp, ep, etp}`` so DP/CP stay out-of-band. ``Module.parallelize`` asserts the resolved mesh is one of ``spmd_meshes()`` (identity check) - out-of-order axes resolve to a different submesh and fail the check, enforcing the canonical axis order.

The same mechanism extends to sparse: a second SPMD partition ``(dp_replicate, efsdp, ep, etp)`` lives alongside dense in ``_spmd_meshes``, so MoE modules whose ``sharding_config`` references sparse axes resolve to the sparse submesh through the exact same ``get_module_mesh`` call - no model-side branching.

**Verified parallelisms:**

FSDP + TP
FSDP
HSDP
FSDP + TP
HSDP + TP
FSDP + CP + TP
PP + FSDP + TP
PP + FSDP + CP
PP + CP + TP

**Caveats:**

- CP + full_dtensor requires FlexAttention. After K/V all-gather on CP, Q and K/V have asymmetric sequence lengths, which SDPA/varlen cannot handle with ``is_causal=True``. ``validate_config`` enforces this.

- FSDP + TP requires a [PyTorch-side fix, PR180936](pytorch/pytorch#180936) to ``_find_all_reduce_mesh_dim``and ``_nll_loss_forward_handler`` in ``torch/distributed/tensor/parallel/loss.py`` so ``loss_parallel`` works on multi-D meshes.

- PP requires a [PyTorch-side fix, PR180937](pytorch/pytorch#180937) to use ``_split_tensor`` instead of  ``torch.tensor_split`` for the target microbatch split in``torch/distributed/pipelining/schedules.py``; the raw split goes through DTensor dispatch and turns ``Shard(0)`` into ``Replicate()``  via an implicit all-gather.

- ``full_dtensor + CP + --compile.enable`` (model compile) hangs. Root cause is an upstream PyTorch limitation: ``placement_types.py:1169`` ``.tolist()`` triggers a symint storm during compilation. ``max_autotune`` does not help. Workaround: disable ``--compile.enable`` when running CP under full_dtensor.

- ``cross_entropy_loss`` uses ``pred.permute(0, 2, 1)`` (3D form) instead of ``pred.flatten(0, 1)`` when pred is a DTensor. Flattening merges differently-sharded dims (e.g. batch on ``dp_shard`` and seq on ``cp``) and produces ``_StridedShard``, which breaks downstream scalar loss dispatch. The permute avoids the merge and is functionally equivalent.

- EP is not supported with full_dtensor yet.

- Currently only llama3 has the full_dtensor sharding config; other models  raise ``NotImplementedError`` from ``validate_config``.

ghstack-source-id: e45b545
Pull-Request: #3159
fegin added a commit to pytorch/torchtitan that referenced this pull request Apr 30, 2026
…ama3

Add full DTensor mode where all params, buffers, and inputs are DTensors on a multi-dimensional SPMD mesh (``dp_replicate`` x ``dp_shard`` x ``cp`` x ``tp``). Enabled via ``--training.full_dtensor``. CP is handled declaratively via ``LocalMapConfig`` (K/V ``Replicate`` on CP dim for all-gather) instead of ``apply_cp_to_forward`` hooks. FSDP2 uses ``DataParallelMeshDims`` to identify ``dp_shard`` and ``cp`` as data-parallel dims on the multi-D mesh.

**Mesh Design:**

``ParallelDims`` precomputes one ``DeviceMesh`` per SPMD partition in ``_spmd_meshes`` (dense: ``(dp_replicate, dp_shard, cp, tp)``). Each ``Module`` self-resolves its mesh: ``_needed_axes(sharding_config)`` collects axes referenced by its ``NamedPlacement``s, then ``parallel_dims.get_module_mesh(axes)`` returns the cached submesh. Under ``full_dtensor``, all axes participate; under the legacy path, axes are filtered to ``{tp, ep, etp}`` so DP/CP stay out-of-band. ``Module.parallelize`` asserts the resolved mesh is one of ``spmd_meshes()`` (identity check) - out-of-order axes resolve to a different submesh and fail the check, enforcing the canonical axis order.

The same mechanism extends to sparse: a second SPMD partition ``(dp_replicate, efsdp, ep, etp)`` lives alongside dense in ``_spmd_meshes``, so MoE modules whose ``sharding_config`` references sparse axes resolve to the sparse submesh through the exact same ``get_module_mesh`` call - no model-side branching.

**Verified parallelisms:**

FSDP + TP
FSDP
HSDP
FSDP + TP
HSDP + TP
FSDP + CP + TP
PP + FSDP + TP
PP + FSDP + CP
PP + CP + TP

**Caveats:**

- CP + full_dtensor requires FlexAttention. After K/V all-gather on CP, Q and K/V have asymmetric sequence lengths, which SDPA/varlen cannot handle with ``is_causal=True``. ``validate_config`` enforces this.

- FSDP + TP requires a [PyTorch-side fix, PR180936](pytorch/pytorch#180936) to ``_find_all_reduce_mesh_dim``and ``_nll_loss_forward_handler`` in ``torch/distributed/tensor/parallel/loss.py`` so ``loss_parallel`` works on multi-D meshes.

- PP requires a [PyTorch-side fix, PR180937](pytorch/pytorch#180937) to use ``_split_tensor`` instead of  ``torch.tensor_split`` for the target microbatch split in``torch/distributed/pipelining/schedules.py``; the raw split goes through DTensor dispatch and turns ``Shard(0)`` into ``Replicate()``  via an implicit all-gather.

- ``full_dtensor + CP + --compile.enable`` (model compile) hangs. Root cause is an upstream PyTorch limitation: ``placement_types.py:1169`` ``.tolist()`` triggers a symint storm during compilation. ``max_autotune`` does not help. Workaround: disable ``--compile.enable`` when running CP under full_dtensor.

- ``cross_entropy_loss`` uses ``pred.permute(0, 2, 1)`` (3D form) instead of ``pred.flatten(0, 1)`` when pred is a DTensor. Flattening merges differently-sharded dims (e.g. batch on ``dp_shard`` and seq on ``cp``) and produces ``_StridedShard``, which breaks downstream scalar loss dispatch. The permute avoids the merge and is functionally equivalent.

- EP is not supported with full_dtensor yet.

- Currently only llama3 has the full_dtensor sharding config; other models  raise ``NotImplementedError`` from ``validate_config``.

ghstack-source-id: 041f592
Pull-Request: #3159
fegin added a commit to pytorch/torchtitan that referenced this pull request Apr 30, 2026
…ama3

Add full DTensor mode where all params, buffers, and inputs are DTensors on a multi-dimensional SPMD mesh (``dp_replicate`` x ``dp_shard`` x ``cp`` x ``tp``). Enabled via ``--training.full_dtensor``. CP is handled declaratively via ``LocalMapConfig`` (K/V ``Replicate`` on CP dim for all-gather) instead of ``apply_cp_to_forward`` hooks. FSDP2 uses ``DataParallelMeshDims`` to identify ``dp_shard`` and ``cp`` as data-parallel dims on the multi-D mesh.

**Mesh Design:**

``ParallelDims`` precomputes one ``DeviceMesh`` per SPMD partition in ``_spmd_meshes`` (dense: ``(dp_replicate, dp_shard, cp, tp)``). Each ``Module`` self-resolves its mesh: ``_needed_axes(sharding_config)`` collects axes referenced by its ``NamedPlacement``s, then ``parallel_dims.get_module_mesh(axes)`` returns the cached submesh. Under ``full_dtensor``, all axes participate; under the legacy path, axes are filtered to ``{tp, ep, etp}`` so DP/CP stay out-of-band. ``Module.parallelize`` asserts the resolved mesh is one of ``spmd_meshes()`` (identity check) - out-of-order axes resolve to a different submesh and fail the check, enforcing the canonical axis order.

The same mechanism extends to sparse: a second SPMD partition ``(dp_replicate, efsdp, ep, etp)`` lives alongside dense in ``_spmd_meshes``, so MoE modules whose ``sharding_config`` references sparse axes resolve to the sparse submesh through the exact same ``get_module_mesh`` call - no model-side branching.

**Verified parallelisms:**

FSDP + TP
FSDP
HSDP
FSDP + TP
HSDP + TP
FSDP + CP + TP
PP + FSDP + TP
PP + FSDP + CP
PP + CP + TP

**Caveats:**

- CP + full_dtensor requires FlexAttention. After K/V all-gather on CP, Q and K/V have asymmetric sequence lengths, which SDPA/varlen cannot handle with ``is_causal=True``. ``validate_config`` enforces this.

- FSDP + TP requires a [PyTorch-side fix, PR180936](pytorch/pytorch#180936) to ``_find_all_reduce_mesh_dim``and ``_nll_loss_forward_handler`` in ``torch/distributed/tensor/parallel/loss.py`` so ``loss_parallel`` works on multi-D meshes.

- PP requires a [PyTorch-side fix, PR180937](pytorch/pytorch#180937) to use ``_split_tensor`` instead of  ``torch.tensor_split`` for the target microbatch split in``torch/distributed/pipelining/schedules.py``; the raw split goes through DTensor dispatch and turns ``Shard(0)`` into ``Replicate()``  via an implicit all-gather.

- ``full_dtensor + CP + --compile.enable`` (model compile) hangs. Root cause is an upstream PyTorch limitation: ``placement_types.py:1169`` ``.tolist()`` triggers a symint storm during compilation. ``max_autotune`` does not help. Workaround: disable ``--compile.enable`` when running CP under full_dtensor.

- ``cross_entropy_loss`` uses ``pred.permute(0, 2, 1)`` (3D form) instead of ``pred.flatten(0, 1)`` when pred is a DTensor. Flattening merges differently-sharded dims (e.g. batch on ``dp_shard`` and seq on ``cp``) and produces ``_StridedShard``, which breaks downstream scalar loss dispatch. The permute avoids the merge and is functionally equivalent.

- EP is not supported with full_dtensor yet.

- Currently only llama3 has the full_dtensor sharding config; other models  raise ``NotImplementedError`` from ``validate_config``.

ghstack-source-id: 559d546
Pull-Request: #3159
fegin added a commit to pytorch/torchtitan that referenced this pull request Apr 30, 2026
…ama3

Add full DTensor mode where all params, buffers, and inputs are DTensors on a multi-dimensional SPMD mesh (``dp_replicate`` x ``dp_shard`` x ``cp`` x ``tp``). Enabled via ``--training.full_dtensor``. CP is handled declaratively via ``LocalMapConfig`` (K/V ``Replicate`` on CP dim for all-gather) instead of ``apply_cp_to_forward`` hooks. FSDP2 uses ``DataParallelMeshDims`` to identify ``dp_shard`` and ``cp`` as data-parallel dims on the multi-D mesh.

**Mesh Design:**

``ParallelDims`` precomputes one ``DeviceMesh`` per SPMD partition in ``_spmd_meshes`` (dense: ``(dp_replicate, dp_shard, cp, tp)``). Each ``Module`` self-resolves its mesh: ``_needed_axes(sharding_config)`` collects axes referenced by its ``NamedPlacement``s, then ``parallel_dims.get_module_mesh(axes)`` returns the cached submesh. Under ``full_dtensor``, all axes participate; under the legacy path, axes are filtered to ``{tp, ep, etp}`` so DP/CP stay out-of-band. ``Module.parallelize`` asserts the resolved mesh is one of ``spmd_meshes()`` (identity check) - out-of-order axes resolve to a different submesh and fail the check, enforcing the canonical axis order.

The same mechanism extends to sparse: a second SPMD partition ``(dp_replicate, efsdp, ep, etp)`` lives alongside dense in ``_spmd_meshes``, so MoE modules whose ``sharding_config`` references sparse axes resolve to the sparse submesh through the exact same ``get_module_mesh`` call - no model-side branching.

**Verified parallelisms:**

FSDP + TP
FSDP
HSDP
FSDP + TP
HSDP + TP
FSDP + CP + TP
PP + FSDP + TP
PP + FSDP + CP
PP + CP + TP

**Caveats:**

- CP + full_dtensor requires FlexAttention. After K/V all-gather on CP, Q and K/V have asymmetric sequence lengths, which SDPA/varlen cannot handle with ``is_causal=True``. ``validate_config`` enforces this.

- FSDP + TP requires a [PyTorch-side fix, PR180936](pytorch/pytorch#180936) to ``_find_all_reduce_mesh_dim``and ``_nll_loss_forward_handler`` in ``torch/distributed/tensor/parallel/loss.py`` so ``loss_parallel`` works on multi-D meshes.

- PP requires a [PyTorch-side fix, PR180937](pytorch/pytorch#180937) to use ``_split_tensor`` instead of  ``torch.tensor_split`` for the target microbatch split in``torch/distributed/pipelining/schedules.py``; the raw split goes through DTensor dispatch and turns ``Shard(0)`` into ``Replicate()``  via an implicit all-gather.

- ``full_dtensor + CP + --compile.enable`` (model compile) hangs. Root cause is an upstream PyTorch limitation: ``placement_types.py:1169`` ``.tolist()`` triggers a symint storm during compilation. ``max_autotune`` does not help. Workaround: disable ``--compile.enable`` when running CP under full_dtensor.

- ``cross_entropy_loss`` uses ``pred.permute(0, 2, 1)`` (3D form) instead of ``pred.flatten(0, 1)`` when pred is a DTensor. Flattening merges differently-sharded dims (e.g. batch on ``dp_shard`` and seq on ``cp``) and produces ``_StridedShard``, which breaks downstream scalar loss dispatch. The permute avoids the merge and is functionally equivalent.

- EP is not supported with full_dtensor yet.

- Currently only llama3 has the full_dtensor sharding config; other models  raise ``NotImplementedError`` from ``validate_config``.

ghstack-source-id: b53e6e2
Pull-Request: #3159
fegin added a commit to pytorch/torchtitan that referenced this pull request Apr 30, 2026
…ama3

Add full DTensor mode where all params, buffers, and inputs are DTensors on a multi-dimensional SPMD mesh (``dp_replicate`` x ``dp_shard`` x ``cp`` x ``tp``). Enabled via ``--training.full_dtensor``. CP is handled declaratively via ``LocalMapConfig`` (K/V ``Replicate`` on CP dim for all-gather) instead of ``apply_cp_to_forward`` hooks. FSDP2 uses ``DataParallelMeshDims`` to identify ``dp_shard`` and ``cp`` as data-parallel dims on the multi-D mesh.

**Mesh Design:**

``ParallelDims`` precomputes one ``DeviceMesh`` per SPMD partition in ``_spmd_meshes`` (dense: ``(dp_replicate, dp_shard, cp, tp)``). Each ``Module`` self-resolves its mesh: ``_needed_axes(sharding_config)`` collects axes referenced by its ``NamedPlacement``s, then ``parallel_dims.get_module_mesh(axes)`` returns the cached submesh. Under ``full_dtensor``, all axes participate; under the legacy path, axes are filtered to ``{tp, ep, etp}`` so DP/CP stay out-of-band. ``Module.parallelize`` asserts the resolved mesh is one of ``spmd_meshes()`` (identity check) - out-of-order axes resolve to a different submesh and fail the check, enforcing the canonical axis order.

The same mechanism extends to sparse: a second SPMD partition ``(dp_replicate, efsdp, ep, etp)`` lives alongside dense in ``_spmd_meshes``, so MoE modules whose ``sharding_config`` references sparse axes resolve to the sparse submesh through the exact same ``get_module_mesh`` call - no model-side branching.

**Verified parallelisms:**

FSDP + TP
FSDP
HSDP
FSDP + TP
HSDP + TP
FSDP + CP + TP
PP + FSDP + TP
PP + FSDP + CP
PP + CP + TP

**Caveats:**

- CP + full_dtensor requires FlexAttention. After K/V all-gather on CP, Q and K/V have asymmetric sequence lengths, which SDPA/varlen cannot handle with ``is_causal=True``. ``validate_config`` enforces this.

- FSDP + TP requires a [PyTorch-side fix, PR180936](pytorch/pytorch#180936) to ``_find_all_reduce_mesh_dim``and ``_nll_loss_forward_handler`` in ``torch/distributed/tensor/parallel/loss.py`` so ``loss_parallel`` works on multi-D meshes.

- PP requires a [PyTorch-side fix, PR180937](pytorch/pytorch#180937) to use ``_split_tensor`` instead of  ``torch.tensor_split`` for the target microbatch split in``torch/distributed/pipelining/schedules.py``; the raw split goes through DTensor dispatch and turns ``Shard(0)`` into ``Replicate()``  via an implicit all-gather.

- ``full_dtensor + CP + --compile.enable`` (model compile) hangs. Root cause is an upstream PyTorch limitation: ``placement_types.py:1169`` ``.tolist()`` triggers a symint storm during compilation. ``max_autotune`` does not help. Workaround: disable ``--compile.enable`` when running CP under full_dtensor.

- ``cross_entropy_loss`` uses ``pred.permute(0, 2, 1)`` (3D form) instead of ``pred.flatten(0, 1)`` when pred is a DTensor. Flattening merges differently-sharded dims (e.g. batch on ``dp_shard`` and seq on ``cp``) and produces ``_StridedShard``, which breaks downstream scalar loss dispatch. The permute avoids the merge and is functionally equivalent.

- EP is not supported with full_dtensor yet.

- Currently only llama3 has the full_dtensor sharding config; other models  raise ``NotImplementedError`` from ``validate_config``.

ghstack-source-id: caf2ac5
Pull-Request: #3159
fegin added a commit to pytorch/torchtitan that referenced this pull request Apr 30, 2026
…ama3

Add full DTensor mode where all params, buffers, and inputs are DTensors on a multi-dimensional SPMD mesh (``dp_replicate`` x ``dp_shard`` x ``cp`` x ``tp``). Enabled via ``--training.full_dtensor``. CP is handled declaratively via ``LocalMapConfig`` (K/V ``Replicate`` on CP dim for all-gather) instead of ``apply_cp_to_forward`` hooks. FSDP2 uses ``DataParallelMeshDims`` to identify ``dp_shard`` and ``cp`` as data-parallel dims on the multi-D mesh.

**Mesh Design:**

``ParallelDims`` precomputes one ``DeviceMesh`` per SPMD partition in ``_spmd_meshes`` (dense: ``(dp_replicate, dp_shard, cp, tp)``). Each ``Module`` self-resolves its mesh: ``_needed_axes(sharding_config)`` collects axes referenced by its ``NamedPlacement``s, then ``parallel_dims.get_module_mesh(axes)`` returns the cached submesh. Under ``full_dtensor``, all axes participate; under the legacy path, axes are filtered to ``{tp, ep, etp}`` so DP/CP stay out-of-band. ``Module.parallelize`` asserts the resolved mesh is one of ``spmd_meshes()`` (identity check) - out-of-order axes resolve to a different submesh and fail the check, enforcing the canonical axis order.

The same mechanism extends to sparse: a second SPMD partition ``(dp_replicate, efsdp, ep, etp)`` lives alongside dense in ``_spmd_meshes``, so MoE modules whose ``sharding_config`` references sparse axes resolve to the sparse submesh through the exact same ``get_module_mesh`` call - no model-side branching.

**Verified parallelisms:**

FSDP + TP
FSDP
HSDP
FSDP + TP
HSDP + TP
FSDP + CP + TP
PP + FSDP + TP
PP + FSDP + CP
PP + CP + TP

**Caveats:**

- CP + full_dtensor requires FlexAttention. After K/V all-gather on CP, Q and K/V have asymmetric sequence lengths, which SDPA/varlen cannot handle with ``is_causal=True``. ``validate_config`` enforces this.

- FSDP + TP requires a [PyTorch-side fix, PR180936](pytorch/pytorch#180936) to ``_find_all_reduce_mesh_dim``and ``_nll_loss_forward_handler`` in ``torch/distributed/tensor/parallel/loss.py`` so ``loss_parallel`` works on multi-D meshes.

- PP requires a [PyTorch-side fix, PR180937](pytorch/pytorch#180937) to use ``_split_tensor`` instead of  ``torch.tensor_split`` for the target microbatch split in``torch/distributed/pipelining/schedules.py``; the raw split goes through DTensor dispatch and turns ``Shard(0)`` into ``Replicate()``  via an implicit all-gather.

- ``full_dtensor + CP + --compile.enable`` (model compile) hangs. Root cause is an upstream PyTorch limitation: ``placement_types.py:1169`` ``.tolist()`` triggers a symint storm during compilation. ``max_autotune`` does not help. Workaround: disable ``--compile.enable`` when running CP under full_dtensor.

- ``cross_entropy_loss`` uses ``pred.permute(0, 2, 1)`` (3D form) instead of ``pred.flatten(0, 1)`` when pred is a DTensor. Flattening merges differently-sharded dims (e.g. batch on ``dp_shard`` and seq on ``cp``) and produces ``_StridedShard``, which breaks downstream scalar loss dispatch. The permute avoids the merge and is functionally equivalent.

- EP is not supported with full_dtensor yet.

- Currently only llama3 has the full_dtensor sharding config; other models  raise ``NotImplementedError`` from ``validate_config``.

ghstack-source-id: a3191cc
Pull-Request: #3159
fegin added 2 commits April 30, 2026 23:00
[ghstack-poisoned]
[ghstack-poisoned]
fegin added 2 commits May 14, 2026 17:56
[ghstack-poisoned]
[ghstack-poisoned]
Alokksinha00 pushed a commit to Alokksinha00/pytorch that referenced this pull request May 15, 2026
…180936)

Extend loss_parallel() from 1D-only to N-D mesh. The TP dim is now any
single mesh dim that shards the class dimension (not necessarily last);
the remaining mesh dims may be Shard (DP/CP) or Replicate.

Output placements by reduction:
  - "none": inherits target placements (Shard on batch dims, Replicate on TP).
  - "sum": Replicate on TP (custom all-reduce makes each rank's value
    globally correct), Partial("sum") on other Shard dims so the cross-rank
    reduction happens lazily on materialization/redistribution.
  - "mean": rejected on N-D mesh — total_weight is a per-rank local count,
    so aggregation across non-TP dims would not yield the correct global
    mean; use "sum"/"none" and divide by the global count.

For reduction="none", the backward handler redistributes grad_output to
the forward output placements, since autograd may deliver it replicated
even when the forward output was batch-sharded.
Pull Request resolved: pytorch#180936
Approved by: https://github.com/tianyu-l
ghstack dependencies: pytorch#180937
Alokksinha00 pushed a commit to Alokksinha00/pytorch that referenced this pull request May 15, 2026
…ytorch#180936)"

This reverts commit d016a8c.

Reverted pytorch#180936 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](pytorch#180937 (comment)))
@fegin

fegin commented May 15, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team Raised by workflow job

Failing merge rule: Core Maintainers

@fegin

fegin commented May 15, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -f "The failing test is not related."

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use -f as last resort and instead consider -i/--ignore-current to continue the merge ignoring current failures. This will allow currently pending tests to finish and report signal before the merge.

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

pytorchmergebot pushed a commit that referenced this pull request May 15, 2026
When fully_shard receives multiple DP shard dimensions via DataParallelMeshDims (e.g. dp_shard + cp), _get_mesh_info_from_named_dims already flattens them into a single process group for the all-gather and reduce-scatter. However, _init_sharding_spec_spmd was building the sharding spec on the original SPMD mesh with separate axes, so the parameter and gradient DTensors exposed N separate Shard axes instead of one.

This caused two problems for downstream consumers like clip_grad_norm_:
- DTensor's _NormPartial reduction happened per-axis sequentially, producing different float32 summation order than the legacy path (which has a single flattened fsdp axis).
- The Shard(0) on cp and dp_shard is actually not correct. It should be _StridedShard

Fix: add _build_spmd_sharding_spec which reuses mesh_info.mesh (the already-flattened DP mesh from _get_mesh_info_from_named_dims) and concatenates it with non-DP submeshes following spmd_mesh.mesh_dim_names order. When there is only one DP shard dim, the method is a no-op.

Verified bit-identical loss and grad_norm between legacy and full_dtensor at 500 steps across FSDP+CP+TP, HSDP+CP, and HSDP+TP configurations with TorchTitan.
Pull Request resolved: #183629
Approved by: https://github.com/weifengpy
ghstack dependencies: #180937, #180936
fegin added a commit to pytorch/torchtitan that referenced this pull request May 17, 2026
…ama3

Add full DTensor mode where all params, buffers, and inputs are DTensors on a multi-dimensional SPMD mesh (``dp_replicate`` x ``dp_shard`` x ``cp`` x ``tp``). Enabled via ``--training.full_dtensor``. CP is handled declaratively via ``LocalMapConfig`` (K/V ``Replicate`` on CP dim for all-gather) instead of ``apply_cp_to_forward`` hooks. FSDP2 uses ``DataParallelMeshDims`` to identify ``dp_shard`` and ``cp`` as data-parallel dims on the multi-D mesh.

**Mesh Design:**

``ParallelDims`` precomputes one ``DeviceMesh`` per SPMD partition in ``_spmd_meshes`` (dense: ``(dp_replicate, dp_shard, cp, tp)``). Each ``Module`` self-resolves its mesh: ``_needed_axes(sharding_config)`` collects axes referenced by its ``NamedPlacement``s, then ``parallel_dims.get_module_mesh(axes)`` returns the cached submesh. Under ``full_dtensor``, all axes participate; under the legacy path, axes are filtered to ``{tp, ep, etp}`` so DP/CP stay out-of-band. ``Module.parallelize`` asserts the resolved mesh is one of ``spmd_meshes()`` (identity check) - out-of-order axes resolve to a different submesh and fail the check, enforcing the canonical axis order.

The same mechanism extends to sparse: a second SPMD partition ``(dp_replicate, efsdp, ep, etp)`` lives alongside dense in ``_spmd_meshes``, so MoE modules whose ``sharding_config`` references sparse axes resolve to the sparse submesh through the exact same ``get_module_mesh`` call - no model-side branching.

**Loss and grad-norm parity:**

Two coordinated fixes close the legacy<->full_dtensor parity gap on ``FSDP + CP (+ TP)`` and unblock ``--debug.deterministic`` under CP:

- ``cross_entropy_loss`` routes through ``_cross_entropy_via_local_map`` when batch and seq are both sharded (the StridedShard combo). It consumes all mesh axes inside ``local_map``, flattens locally, re-wraps with a sum-invariant placement relabel, and dispatches under ``loss_parallel`` when V is sharded. Both V-sharded and V-replicated paths route to the 1D ``aten.nll_loss_forward`` kernel, which has a deterministic CUDA implementation. The caller (trainer ``train_context``, or tests) owns the ``loss_parallel`` context; the inner code asserts handlers are installed rather than nesting, since upstream ``loss_parallel`` is not reentrant-safe.

- ``clip_grad_norm_`` computes per-rank local p-norm sums and does a single flat ``all_reduce`` over ``mesh._flatten(...)``, bypassing ``torch.nn.utils.get_total_norm``'s ``_NormPartial -> Replicate`` reduction (one ``all_reduce`` per SPMD axis). The flat reduce is decomposition-invariant, so legacy 2-axis and full_dtensor 3-axis produce the same ``total_norm`` in fp32. Replicate axes are scaled by ``1/replicate_factor`` to avoid double-counting.

Verified 10-step bit-identical loss + grad_norm on 8xH100 (``llama3_debugmodel_flex_attn``, ``FSDP=2 + CP=2 + TP=2``, ``--debug.deterministic``, seed checkpoint) between legacy and full_dtensor.

**Verified parallelisms:**

FSDP + TP
FSDP
HSDP
FSDP + TP
HSDP + TP
FSDP + CP + TP
PP + FSDP + TP
PP + FSDP + CP
PP + CP + TP

**Caveats:**

- CP + full_dtensor requires FlexAttention. After K/V all-gather on CP, Q and K/V have asymmetric sequence lengths, which SDPA/varlen cannot handle with ``is_causal=True``. ``validate_config`` enforces this.

- FSDP + TP requires a [PyTorch-side fix, PR180936](pytorch/pytorch#180936) to ``_find_all_reduce_mesh_dim``and ``_nll_loss_forward_handler`` in ``torch/distributed/tensor/parallel/loss.py`` so ``loss_parallel`` works on multi-D meshes.

- PP requires a [PyTorch-side fix, PR180937](pytorch/pytorch#180937) to use ``_split_tensor`` instead of  ``torch.tensor_split`` for the target microbatch split in``torch/distributed/pipelining/schedules.py``; the raw split goes through DTensor dispatch and turns ``Shard(0)`` into ``Replicate()``  via an implicit all-gather.

- ``full_dtensor + CP + --compile.enable`` (model compile) hangs. Root cause is an upstream PyTorch limitation: ``placement_types.py:1169`` ``.tolist()`` triggers a symint storm during compilation. ``max_autotune`` does not help. Workaround: disable ``--compile.enable`` when running CP under full_dtensor.

- EP is not supported with full_dtensor yet.

- Currently only llama3 has the full_dtensor sharding config; other models  raise ``NotImplementedError`` from ``validate_config``.

ghstack-source-id: c374519
Pull-Request: #3159
fegin added a commit to pytorch/torchtitan that referenced this pull request May 17, 2026
…ama3

Add full DTensor mode where all params, buffers, and inputs are DTensors on a multi-dimensional SPMD mesh (``dp_replicate`` x ``dp_shard`` x ``cp`` x ``tp``). Enabled via ``--training.full_dtensor``. CP is handled declaratively via ``LocalMapConfig`` (K/V ``Replicate`` on CP dim for all-gather) instead of ``apply_cp_to_forward`` hooks. FSDP2 uses ``DataParallelMeshDims`` to identify ``dp_shard`` and ``cp`` as data-parallel dims on the multi-D mesh.

**Mesh Design:**

``ParallelDims`` precomputes one ``DeviceMesh`` per SPMD partition in ``_spmd_meshes`` (dense: ``(dp_replicate, dp_shard, cp, tp)``). Each ``Module`` self-resolves its mesh: ``_needed_axes(sharding_config)`` collects axes referenced by its ``NamedPlacement``s, then ``parallel_dims.get_module_mesh(axes)`` returns the cached submesh. Under ``full_dtensor``, all axes participate; under the legacy path, axes are filtered to ``{tp, ep, etp}`` so DP/CP stay out-of-band. ``Module.parallelize`` asserts the resolved mesh is one of ``spmd_meshes()`` (identity check) - out-of-order axes resolve to a different submesh and fail the check, enforcing the canonical axis order.

The same mechanism extends to sparse: a second SPMD partition ``(dp_replicate, efsdp, ep, etp)`` lives alongside dense in ``_spmd_meshes``, so MoE modules whose ``sharding_config`` references sparse axes resolve to the sparse submesh through the exact same ``get_module_mesh`` call - no model-side branching.

**Loss and grad-norm parity:**

Two coordinated fixes close the legacy<->full_dtensor parity gap on ``FSDP + CP (+ TP)`` and unblock ``--debug.deterministic`` under CP:

- ``cross_entropy_loss`` routes through ``_cross_entropy_via_local_map`` when batch and seq are both sharded (the StridedShard combo). It consumes all mesh axes inside ``local_map``, flattens locally, re-wraps with a sum-invariant placement relabel, and dispatches under ``loss_parallel`` when V is sharded. Both V-sharded and V-replicated paths route to the 1D ``aten.nll_loss_forward`` kernel, which has a deterministic CUDA implementation. The caller (trainer ``train_context``, or tests) owns the ``loss_parallel`` context; the inner code asserts handlers are installed rather than nesting, since upstream ``loss_parallel`` is not reentrant-safe.

- ``clip_grad_norm_`` computes per-rank local p-norm sums and does a single flat ``all_reduce`` over ``mesh._flatten(...)``, bypassing ``torch.nn.utils.get_total_norm``'s ``_NormPartial -> Replicate`` reduction (one ``all_reduce`` per SPMD axis). The flat reduce is decomposition-invariant, so legacy 2-axis and full_dtensor 3-axis produce the same ``total_norm`` in fp32. Replicate axes are scaled by ``1/replicate_factor`` to avoid double-counting.

Verified 10-step bit-identical loss + grad_norm on 8xH100 (``llama3_debugmodel_flex_attn``, ``FSDP=2 + CP=2 + TP=2``, ``--debug.deterministic``, seed checkpoint) between legacy and full_dtensor.

**Verified parallelisms:**

FSDP + TP
FSDP
HSDP
FSDP + TP
HSDP + TP
FSDP + CP + TP
PP + FSDP + TP
PP + FSDP + CP
PP + CP + TP

**Caveats:**

- CP + full_dtensor requires FlexAttention. After K/V all-gather on CP, Q and K/V have asymmetric sequence lengths, which SDPA/varlen cannot handle with ``is_causal=True``. ``validate_config`` enforces this.

- FSDP + TP requires a [PyTorch-side fix, PR180936](pytorch/pytorch#180936) to ``_find_all_reduce_mesh_dim``and ``_nll_loss_forward_handler`` in ``torch/distributed/tensor/parallel/loss.py`` so ``loss_parallel`` works on multi-D meshes.

- PP requires a [PyTorch-side fix, PR180937](pytorch/pytorch#180937) to use ``_split_tensor`` instead of  ``torch.tensor_split`` for the target microbatch split in``torch/distributed/pipelining/schedules.py``; the raw split goes through DTensor dispatch and turns ``Shard(0)`` into ``Replicate()``  via an implicit all-gather.

- ``full_dtensor + CP + --compile.enable`` (model compile) hangs. Root cause is an upstream PyTorch limitation: ``placement_types.py:1169`` ``.tolist()`` triggers a symint storm during compilation. ``max_autotune`` does not help. Workaround: disable ``--compile.enable`` when running CP under full_dtensor.

- EP is not supported with full_dtensor yet.

- Currently only llama3 has the full_dtensor sharding config; other models  raise ``NotImplementedError`` from ``validate_config``.

ghstack-source-id: fa7b705
Pull-Request: #3159
fegin added a commit to pytorch/torchtitan that referenced this pull request May 17, 2026
…ama3

Add full DTensor mode where all params, buffers, and inputs are DTensors on a multi-dimensional SPMD mesh (``dp_replicate`` x ``dp_shard`` x ``cp`` x ``tp``). Enabled via ``--training.full_dtensor``. CP is handled declaratively via ``LocalMapConfig`` (K/V ``Replicate`` on CP dim for all-gather) instead of ``apply_cp_to_forward`` hooks. FSDP2 uses ``DataParallelMeshDims`` to identify ``dp_shard`` and ``cp`` as data-parallel dims on the multi-D mesh.

**Mesh Design:**

``ParallelDims`` precomputes one ``DeviceMesh`` per SPMD partition in ``_spmd_meshes`` (dense: ``(dp_replicate, dp_shard, cp, tp)``). Each ``Module`` self-resolves its mesh: ``_needed_axes(sharding_config)`` collects axes referenced by its ``NamedPlacement``s, then ``parallel_dims.get_module_mesh(axes)`` returns the cached submesh. Under ``full_dtensor``, all axes participate; under the legacy path, axes are filtered to ``{tp, ep, etp}`` so DP/CP stay out-of-band. ``Module.parallelize`` asserts the resolved mesh is one of ``spmd_meshes()`` (identity check) - out-of-order axes resolve to a different submesh and fail the check, enforcing the canonical axis order.

The same mechanism extends to sparse: a second SPMD partition ``(dp_replicate, efsdp, ep, etp)`` lives alongside dense in ``_spmd_meshes``, so MoE modules whose ``sharding_config`` references sparse axes resolve to the sparse submesh through the exact same ``get_module_mesh`` call - no model-side branching.

**Loss and grad-norm parity:**

Two coordinated fixes close the legacy<->full_dtensor parity gap on ``FSDP + CP (+ TP)`` and unblock ``--debug.deterministic`` under CP:

- ``cross_entropy_loss`` routes through ``_cross_entropy_via_local_map`` when batch and seq are both sharded (the StridedShard combo). It consumes all mesh axes inside ``local_map``, flattens locally, re-wraps with a sum-invariant placement relabel, and dispatches under ``loss_parallel`` when V is sharded. Both V-sharded and V-replicated paths route to the 1D ``aten.nll_loss_forward`` kernel, which has a deterministic CUDA implementation. The caller (trainer ``train_context``, or tests) owns the ``loss_parallel`` context; the inner code asserts handlers are installed rather than nesting, since upstream ``loss_parallel`` is not reentrant-safe.

- ``clip_grad_norm_`` computes per-rank local p-norm sums and does a single flat ``all_reduce`` over ``mesh._flatten(...)``, bypassing ``torch.nn.utils.get_total_norm``'s ``_NormPartial -> Replicate`` reduction (one ``all_reduce`` per SPMD axis). The flat reduce is decomposition-invariant, so legacy 2-axis and full_dtensor 3-axis produce the same ``total_norm`` in fp32. Replicate axes are scaled by ``1/replicate_factor`` to avoid double-counting.

Verified 10-step bit-identical loss + grad_norm on 8xH100 (``llama3_debugmodel_flex_attn``, ``FSDP=2 + CP=2 + TP=2``, ``--debug.deterministic``, seed checkpoint) between legacy and full_dtensor.

**Verified parallelisms:**

FSDP + TP
FSDP
HSDP
FSDP + TP
HSDP + TP
FSDP + CP + TP
PP + FSDP + TP
PP + FSDP + CP
PP + CP + TP

**Caveats:**

- CP + full_dtensor requires FlexAttention. After K/V all-gather on CP, Q and K/V have asymmetric sequence lengths, which SDPA/varlen cannot handle with ``is_causal=True``. ``validate_config`` enforces this.

- FSDP + TP requires a [PyTorch-side fix, PR180936](pytorch/pytorch#180936) to ``_find_all_reduce_mesh_dim``and ``_nll_loss_forward_handler`` in ``torch/distributed/tensor/parallel/loss.py`` so ``loss_parallel`` works on multi-D meshes.

- PP requires a [PyTorch-side fix, PR180937](pytorch/pytorch#180937) to use ``_split_tensor`` instead of  ``torch.tensor_split`` for the target microbatch split in``torch/distributed/pipelining/schedules.py``; the raw split goes through DTensor dispatch and turns ``Shard(0)`` into ``Replicate()``  via an implicit all-gather.

- ``full_dtensor + CP + --compile.enable`` (model compile) hangs. Root cause is an upstream PyTorch limitation: ``placement_types.py:1169`` ``.tolist()`` triggers a symint storm during compilation. ``max_autotune`` does not help. Workaround: disable ``--compile.enable`` when running CP under full_dtensor.

- EP is not supported with full_dtensor yet.

- Currently only llama3 has the full_dtensor sharding config; other models  raise ``NotImplementedError`` from ``validate_config``.

ghstack-source-id: 2e0e7ec
Pull-Request: #3159
fegin added a commit to pytorch/torchtitan that referenced this pull request May 17, 2026
…ama3

Add full DTensor mode where all params, buffers, and inputs are DTensors on a multi-dimensional SPMD mesh (``dp_replicate`` x ``dp_shard`` x ``cp`` x ``tp``). Enabled via ``--training.full_dtensor``. CP is handled declaratively via ``LocalMapConfig`` (K/V ``Replicate`` on CP dim for all-gather) instead of ``apply_cp_to_forward`` hooks. FSDP2 uses ``DataParallelMeshDims`` to identify ``dp_shard`` and ``cp`` as data-parallel dims on the multi-D mesh.

**Mesh Design:**

``ParallelDims`` precomputes one ``DeviceMesh`` per SPMD partition in ``_spmd_meshes`` (dense: ``(dp_replicate, dp_shard, cp, tp)``). Each ``Module`` self-resolves its mesh: ``_needed_axes(sharding_config)`` collects axes referenced by its ``NamedPlacement``s, then ``parallel_dims.get_module_mesh(axes)`` returns the cached submesh. Under ``full_dtensor``, all axes participate; under the legacy path, axes are filtered to ``{tp, ep, etp}`` so DP/CP stay out-of-band. ``Module.parallelize`` asserts the resolved mesh is one of ``spmd_meshes()`` (identity check) - out-of-order axes resolve to a different submesh and fail the check, enforcing the canonical axis order.

The same mechanism extends to sparse: a second SPMD partition ``(dp_replicate, efsdp, ep, etp)`` lives alongside dense in ``_spmd_meshes``, so MoE modules whose ``sharding_config`` references sparse axes resolve to the sparse submesh through the exact same ``get_module_mesh`` call - no model-side branching.

**Loss and grad-norm parity:**

Two coordinated fixes close the legacy<->full_dtensor parity gap on ``FSDP + CP (+ TP)`` and unblock ``--debug.deterministic`` under CP:

- ``cross_entropy_loss`` routes through ``_cross_entropy_via_local_map`` when batch and seq are both sharded (the StridedShard combo). It consumes all mesh axes inside ``local_map``, flattens locally, re-wraps with a sum-invariant placement relabel, and dispatches under ``loss_parallel`` when V is sharded. Both V-sharded and V-replicated paths route to the 1D ``aten.nll_loss_forward`` kernel, which has a deterministic CUDA implementation. The caller (trainer ``train_context``, or tests) owns the ``loss_parallel`` context; the inner code asserts handlers are installed rather than nesting, since upstream ``loss_parallel`` is not reentrant-safe.

- ``clip_grad_norm_`` computes per-rank local p-norm sums and does a single flat ``all_reduce`` over ``mesh._flatten(...)``, bypassing ``torch.nn.utils.get_total_norm``'s ``_NormPartial -> Replicate`` reduction (one ``all_reduce`` per SPMD axis). The flat reduce is decomposition-invariant, so legacy 2-axis and full_dtensor 3-axis produce the same ``total_norm`` in fp32. Replicate axes are scaled by ``1/replicate_factor`` to avoid double-counting.

Verified 10-step bit-identical loss + grad_norm on 8xH100 (``llama3_debugmodel_flex_attn``, ``FSDP=2 + CP=2 + TP=2``, ``--debug.deterministic``, seed checkpoint) between legacy and full_dtensor.

**Verified parallelisms:**

FSDP + TP
FSDP
HSDP
FSDP + TP
HSDP + TP
FSDP + CP + TP
PP + FSDP + TP
PP + FSDP + CP
PP + CP + TP

**Caveats:**

- CP + full_dtensor requires FlexAttention. After K/V all-gather on CP, Q and K/V have asymmetric sequence lengths, which SDPA/varlen cannot handle with ``is_causal=True``. ``validate_config`` enforces this.

- FSDP + TP requires a [PyTorch-side fix, PR180936](pytorch/pytorch#180936) to ``_find_all_reduce_mesh_dim``and ``_nll_loss_forward_handler`` in ``torch/distributed/tensor/parallel/loss.py`` so ``loss_parallel`` works on multi-D meshes.

- PP requires a [PyTorch-side fix, PR180937](pytorch/pytorch#180937) to use ``_split_tensor`` instead of  ``torch.tensor_split`` for the target microbatch split in``torch/distributed/pipelining/schedules.py``; the raw split goes through DTensor dispatch and turns ``Shard(0)`` into ``Replicate()``  via an implicit all-gather.

- ``full_dtensor + CP + --compile.enable`` (model compile) hangs. Root cause is an upstream PyTorch limitation: ``placement_types.py:1169`` ``.tolist()`` triggers a symint storm during compilation. ``max_autotune`` does not help. Workaround: disable ``--compile.enable`` when running CP under full_dtensor.

- EP is not supported with full_dtensor yet.

- Currently only llama3 has the full_dtensor sharding config; other models  raise ``NotImplementedError`` from ``validate_config``.

ghstack-source-id: 3033d86
Pull-Request: #3159
@github-actions
github-actions Bot deleted the gh/fegin/345/head branch June 15, 2026 02:29
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…180936)

Extend loss_parallel() from 1D-only to N-D mesh. The TP dim is now any
single mesh dim that shards the class dimension (not necessarily last);
the remaining mesh dims may be Shard (DP/CP) or Replicate.

Output placements by reduction:
  - "none": inherits target placements (Shard on batch dims, Replicate on TP).
  - "sum": Replicate on TP (custom all-reduce makes each rank's value
    globally correct), Partial("sum") on other Shard dims so the cross-rank
    reduction happens lazily on materialization/redistribution.
  - "mean": rejected on N-D mesh — total_weight is a per-rank local count,
    so aggregation across non-TP dims would not yield the correct global
    mean; use "sum"/"none" and divide by the global count.

For reduction="none", the backward handler redistributes grad_output to
the forward output placements, since autograd may deliver it replicated
even when the forward output was batch-sharded.
Pull Request resolved: pytorch#180936
Approved by: https://github.com/tianyu-l
ghstack dependencies: pytorch#180937
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…ytorch#180936)"

This reverts commit d016a8c.

Reverted pytorch#180936 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](pytorch#180937 (comment)))
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…180936)

Extend loss_parallel() from 1D-only to N-D mesh. The TP dim is now any
single mesh dim that shards the class dimension (not necessarily last);
the remaining mesh dims may be Shard (DP/CP) or Replicate.

Output placements by reduction:
  - "none": inherits target placements (Shard on batch dims, Replicate on TP).
  - "sum": Replicate on TP (custom all-reduce makes each rank's value
    globally correct), Partial("sum") on other Shard dims so the cross-rank
    reduction happens lazily on materialization/redistribution.
  - "mean": rejected on N-D mesh — total_weight is a per-rank local count,
    so aggregation across non-TP dims would not yield the correct global
    mean; use "sum"/"none" and divide by the global count.

For reduction="none", the backward handler redistributes grad_output to
the forward output placements, since autograd may deliver it replicated
even when the forward output was batch-sharded.
Pull Request resolved: pytorch#180936
Approved by: https://github.com/tianyu-l
ghstack dependencies: pytorch#180937
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
When fully_shard receives multiple DP shard dimensions via DataParallelMeshDims (e.g. dp_shard + cp), _get_mesh_info_from_named_dims already flattens them into a single process group for the all-gather and reduce-scatter. However, _init_sharding_spec_spmd was building the sharding spec on the original SPMD mesh with separate axes, so the parameter and gradient DTensors exposed N separate Shard axes instead of one.

This caused two problems for downstream consumers like clip_grad_norm_:
- DTensor's _NormPartial reduction happened per-axis sequentially, producing different float32 summation order than the legacy path (which has a single flattened fsdp axis).
- The Shard(0) on cp and dp_shard is actually not correct. It should be _StridedShard

Fix: add _build_spmd_sharding_spec which reuses mesh_info.mesh (the already-flattened DP mesh from _get_mesh_info_from_named_dims) and concatenates it with non-DP submeshes following spmd_mesh.mesh_dim_names order. When there is only one DP shard dim, the method is a no-op.

Verified bit-identical loss and grad_norm between legacy and full_dtensor at 500 steps across FSDP+CP+TP, HSDP+CP, and HSDP+TP configurations with TorchTitan.
Pull Request resolved: pytorch#183629
Approved by: https://github.com/weifengpy
ghstack dependencies: pytorch#180937, pytorch#180936
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…180936)

Extend loss_parallel() from 1D-only to N-D mesh. The TP dim is now any
single mesh dim that shards the class dimension (not necessarily last);
the remaining mesh dims may be Shard (DP/CP) or Replicate.

Output placements by reduction:
  - "none": inherits target placements (Shard on batch dims, Replicate on TP).
  - "sum": Replicate on TP (custom all-reduce makes each rank's value
    globally correct), Partial("sum") on other Shard dims so the cross-rank
    reduction happens lazily on materialization/redistribution.
  - "mean": rejected on N-D mesh — total_weight is a per-rank local count,
    so aggregation across non-TP dims would not yield the correct global
    mean; use "sum"/"none" and divide by the global count.

For reduction="none", the backward handler redistributes grad_output to
the forward output placements, since autograd may deliver it replicated
even when the forward output was batch-sharded.
Pull Request resolved: pytorch#180936
Approved by: https://github.com/tianyu-l
ghstack dependencies: pytorch#180937
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…ytorch#180936)"

This reverts commit d016a8c.

Reverted pytorch#180936 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](pytorch#180937 (comment)))
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…180936)

Extend loss_parallel() from 1D-only to N-D mesh. The TP dim is now any
single mesh dim that shards the class dimension (not necessarily last);
the remaining mesh dims may be Shard (DP/CP) or Replicate.

Output placements by reduction:
  - "none": inherits target placements (Shard on batch dims, Replicate on TP).
  - "sum": Replicate on TP (custom all-reduce makes each rank's value
    globally correct), Partial("sum") on other Shard dims so the cross-rank
    reduction happens lazily on materialization/redistribution.
  - "mean": rejected on N-D mesh — total_weight is a per-rank local count,
    so aggregation across non-TP dims would not yield the correct global
    mean; use "sum"/"none" and divide by the global count.

For reduction="none", the backward handler redistributes grad_output to
the forward output placements, since autograd may deliver it replicated
even when the forward output was batch-sharded.
Pull Request resolved: pytorch#180936
Approved by: https://github.com/tianyu-l
ghstack dependencies: pytorch#180937
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
When fully_shard receives multiple DP shard dimensions via DataParallelMeshDims (e.g. dp_shard + cp), _get_mesh_info_from_named_dims already flattens them into a single process group for the all-gather and reduce-scatter. However, _init_sharding_spec_spmd was building the sharding spec on the original SPMD mesh with separate axes, so the parameter and gradient DTensors exposed N separate Shard axes instead of one.

This caused two problems for downstream consumers like clip_grad_norm_:
- DTensor's _NormPartial reduction happened per-axis sequentially, producing different float32 summation order than the legacy path (which has a single flattened fsdp axis).
- The Shard(0) on cp and dp_shard is actually not correct. It should be _StridedShard

Fix: add _build_spmd_sharding_spec which reuses mesh_info.mesh (the already-flattened DP mesh from _get_mesh_info_from_named_dims) and concatenates it with non-DP submeshes following spmd_mesh.mesh_dim_names order. When there is only one DP shard dim, the method is a no-op.

Verified bit-identical loss and grad_norm between legacy and full_dtensor at 500 steps across FSDP+CP+TP, HSDP+CP, and HSDP+TP configurations with TorchTitan.
Pull Request resolved: pytorch#183629
Approved by: https://github.com/weifengpy
ghstack dependencies: pytorch#180937, pytorch#180936
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-no-td Do not run TD on this PR ciflow/dtensor Run DTensor specific tests ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged release notes: distributed (dtensor) release notes category Reverted

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants