Skip to content

[DTensor][PP] Correctly shard the input to preserve the DTensor placements - #180937

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

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

Conversation

@fegin

@fegin fegin commented Apr 20, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

If we use torch.split to shard the input tensors, DTensor may change the
placements. PP already has a util function to split a DTensor along the
batch dimension. This PR changes schedules.py to use it.

Behavior deltas for the target-splitting path (both PipelineScheduleSingle
and PipelineScheduleMulti):

  • DTensor targets with Shard(0) now preserve Shard(0) instead of being
    implicitly all-gathered to Replicate() by the default dispatch path.
  • If target.requires_grad and target.is_leaf, the split chunks now have
    retain_grad() called on them (inherited from _split_tensor).
  • Under-sized batches (target.size(0) < n_microbatches) now raise
    AssertionError instead of silently returning fewer chunks.

Authored-with: Claude [email protected]

[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/180937

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:

❌ 2 Unclassified Failures

As of commit c820965 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:

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

@pytorch-bot pytorch-bot Bot added the ciflow/torchtitan Run TorchTitan integration tests label Apr 20, 2026
@fegin
fegin requested a review from sanketpurandare April 21, 2026 00:08
@fegin
fegin marked this pull request as ready for review April 21, 2026 00:08
@fegin fegin added the ciflow/dtensor Run DTensor specific tests label Apr 21, 2026
[ghstack-poisoned]
fegin added a commit that referenced this pull request Apr 21, 2026
…ments

If we use torch.split to shard the input tensors, DTensor may change the
placements. PP already has a util function to split a DTensor along the
batch dimension. This PR changes schedules.py to use it.

Behavior deltas for the target-splitting path (both PipelineScheduleSingle
and PipelineScheduleMulti):
- DTensor targets with Shard(0) now preserve Shard(0) instead of being
  implicitly all-gathered to Replicate() by the default dispatch path.
- If target.requires_grad and target.is_leaf, the split chunks now have
  retain_grad() called on them (inherited from _split_tensor).
- Under-sized batches (target.size(0) < n_microbatches) now raise
  AssertionError instead of silently returning fewer chunks.

Authored-with: Claude <[email protected]>
ghstack-source-id: d7469fd
Pull-Request: #180937
@fegin fegin added the topic: not user facing topic category label Apr 21, 2026
[ghstack-poisoned]
fegin added a commit that referenced this pull request Apr 21, 2026
…ments

If we use torch.split to shard the input tensors, DTensor may change the
placements. PP already has a util function to split a DTensor along the
batch dimension. This PR changes schedules.py to use it.

Behavior deltas for the target-splitting path (both PipelineScheduleSingle
and PipelineScheduleMulti):
- DTensor targets with Shard(0) now preserve Shard(0) instead of being
  implicitly all-gathered to Replicate() by the default dispatch path.
- If target.requires_grad and target.is_leaf, the split chunks now have
  retain_grad() called on them (inherited from _split_tensor).
- Under-sized batches (target.size(0) < n_microbatches) now raise
  AssertionError instead of silently returning fewer chunks.

Authored-with: Claude <[email protected]>
ghstack-source-id: f2bcfde
Pull-Request: #180937
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
[ghstack-poisoned]
fegin added a commit that referenced this pull request May 1, 2026
…ments

If we use torch.split to shard the input tensors, DTensor may change the
placements. PP already has a util function to split a DTensor along the
batch dimension. This PR changes schedules.py to use it.

Behavior deltas for the target-splitting path (both PipelineScheduleSingle
and PipelineScheduleMulti):
- DTensor targets with Shard(0) now preserve Shard(0) instead of being
  implicitly all-gathered to Replicate() by the default dispatch path.
- If target.requires_grad and target.is_leaf, the split chunks now have
  retain_grad() called on them (inherited from _split_tensor).
- Under-sized batches (target.size(0) < n_microbatches) now raise
  AssertionError instead of silently returning fewer chunks.

Authored-with: Claude <[email protected]>
ghstack-source-id: bffd63c
Pull-Request: #180937
[ghstack-poisoned]
@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
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: #180936
Approved by: https://github.com/tianyu-l
ghstack dependencies: #180937
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/346/head branch June 15, 2026 02:29
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…ments (pytorch#180937)

If we use torch.split to shard the input tensors, DTensor may change the
placements. PP already has a util function to split a DTensor along the
batch dimension. This PR changes schedules.py to use it.

Behavior deltas for the target-splitting path (both PipelineScheduleSingle
and PipelineScheduleMulti):
- DTensor targets with Shard(0) now preserve Shard(0) instead of being
  implicitly all-gathered to Replicate() by the default dispatch path.
- If target.requires_grad and target.is_leaf, the split chunks now have
  retain_grad() called on them (inherited from _split_tensor).
- Under-sized batches (target.size(0) < n_microbatches) now raise
  AssertionError instead of silently returning fewer chunks.

Authored-with: Claude <[email protected]>
Pull Request resolved: pytorch#180937
Approved by: https://github.com/sanketpurandare
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
…or placements (pytorch#180937)"

This reverts commit 17fafb1.

Reverted pytorch#180937 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
…ments (pytorch#180937)

If we use torch.split to shard the input tensors, DTensor may change the
placements. PP already has a util function to split a DTensor along the
batch dimension. This PR changes schedules.py to use it.

Behavior deltas for the target-splitting path (both PipelineScheduleSingle
and PipelineScheduleMulti):
- DTensor targets with Shard(0) now preserve Shard(0) instead of being
  implicitly all-gathered to Replicate() by the default dispatch path.
- If target.requires_grad and target.is_leaf, the split chunks now have
  retain_grad() called on them (inherited from _split_tensor).
- Under-sized batches (target.size(0) < n_microbatches) now raise
  AssertionError instead of silently returning fewer chunks.

Authored-with: Claude <[email protected]>
Pull Request resolved: pytorch#180937
Approved by: https://github.com/sanketpurandare
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
…ments (pytorch#180937)

If we use torch.split to shard the input tensors, DTensor may change the
placements. PP already has a util function to split a DTensor along the
batch dimension. This PR changes schedules.py to use it.

Behavior deltas for the target-splitting path (both PipelineScheduleSingle
and PipelineScheduleMulti):
- DTensor targets with Shard(0) now preserve Shard(0) instead of being
  implicitly all-gathered to Replicate() by the default dispatch path.
- If target.requires_grad and target.is_leaf, the split chunks now have
  retain_grad() called on them (inherited from _split_tensor).
- Under-sized batches (target.size(0) < n_microbatches) now raise
  AssertionError instead of silently returning fewer chunks.

Authored-with: Claude <[email protected]>
Pull Request resolved: pytorch#180937
Approved by: https://github.com/sanketpurandare
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
…or placements (pytorch#180937)"

This reverts commit 17fafb1.

Reverted pytorch#180937 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
…ments (pytorch#180937)

If we use torch.split to shard the input tensors, DTensor may change the
placements. PP already has a util function to split a DTensor along the
batch dimension. This PR changes schedules.py to use it.

Behavior deltas for the target-splitting path (both PipelineScheduleSingle
and PipelineScheduleMulti):
- DTensor targets with Shard(0) now preserve Shard(0) instead of being
  implicitly all-gathered to Replicate() by the default dispatch path.
- If target.requires_grad and target.is_leaf, the split chunks now have
  retain_grad() called on them (inherited from _split_tensor).
- Under-sized batches (target.size(0) < n_microbatches) now raise
  AssertionError instead of silently returning fewer chunks.

Authored-with: Claude <[email protected]>
Pull Request resolved: pytorch#180937
Approved by: https://github.com/sanketpurandare
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/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged Reverted topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants