Repository navigation
Conversation
🔗 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 SEVsThere are 1 currently active SEVs. If your PR is affected, please view them below: ❌ 2 Unclassified FailuresAs of commit c820965 with merge base 9c77719 ( 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. |
…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
…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
…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
…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
…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
…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
…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
…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
…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
…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
…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
…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
…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
…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
…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
Merge startedYour 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 |
Merge failedReason: 1 mandatory check(s) failed. The first few are: Dig deeper by viewing the failures on hud |
|
@pytorchbot merge -f "The failing test is not related." |
Merge startedYour change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
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
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
…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
…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
…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
…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
…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
…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
…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)))
…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)))
…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
…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
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
…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
…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
…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)))
…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)))
…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
…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
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
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):
implicitly all-gathered to Replicate() by the default dispatch path.
retain_grad() called on them (inherited from _split_tensor).
AssertionError instead of silently returning fewer chunks.
Authored-with: Claude [email protected]