Repository navigation
[Full DTensor] Config-based Full DTensor for Llama3 - #3159
Merged
Merged
Conversation
[ghstack-poisoned]
This was referenced Apr 29, 2026
fegin
commented
Apr 29, 2026
fegin
added a commit
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
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
marked this pull request as ready for review
April 30, 2026 06:37
fegin
requested review from
SherlockNoMad,
aditvenk,
sanketpurandare,
tianyu-l,
wconstab,
wwwjn,
xmfan and
yiming0416
as code owners
April 30, 2026 06:37
[ghstack-poisoned]
fegin
added a commit
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
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
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
tianyu-l
approved these changes
May 13, 2026
[ghstack-poisoned]
fegin
added a commit
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
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
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
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
saforem2
added a commit
to saforem2/torchtitan
that referenced
this pull request
May 20, 2026
Upstream pytorch#3159 (Full DTensor for Llama3) changed Module.parallelize from taking a bare tp_mesh to taking ParallelDims, so each Module can self-resolve its SPMD submesh from the axes referenced in its NamedPlacements. Update the ezpz callsites in agpt/parallelize.py and moe/parallelize.py; keep parallel_dims.get_mesh("tp") for the async-TP plumbing on the line below. apply_moe_ep_tp is untouched — it takes per-axis meshes directly and does not route through Module.parallelize. ShardingConfig gained optional fields (out_src_shardings, local_input_grad_placements, local_output_grad_placements) that all default None; ezpz's set_{agpt,moe}_sharding_config construct unchanged shapes. No production behavior change since full_dtensor defaults False.
saforem2
added a commit
to saforem2/torchtitan
that referenced
this pull request
May 20, 2026
…ch#3159) Pulled 22 commits from upstream/main (ee4e91a..52a292d, merge a149871). Document the Module.parallelize signature change from pytorch#3159 in upstream-sync.md and the resync session in journal.md. Two ezpz callsites replayed (agpt + moe); all other 20 commits in the batch have no ezpz impact (mostly graph_trainer/RL/CI churn).
saforem2
added a commit
to saforem2/torchtitan
that referenced
this pull request
May 20, 2026
Validates the 35th upstream sync (PR pytorch#3159 Module.parallelize signature change replay) on Sunspot 2N (job 12467124) across 5 configs: agpt_debugmodel LBS=2 loss 10.81 → 6.77 ~37,500 TPS / ~2.9% MFU agpt_2b LBS=1 loss 12.93 → 6.01 ~6,100 TPS / ~22.8% MFU agpt_2b LBS=2 loss 12.91 → 6.12 ~7,200 TPS / ~27.0% MFU moe_debugmodel LBS=2 loss 12.96 → 7.01 ~13,000 TPS / ~9.0% MFU moe_2b LBS=1 loss 12.91 → 6.16 ~2,900 TPS / ~8.4% MFU agpt_2b LBS=2 matches the 2026-04-25 n=2 baseline (7,142 TPS / 27.6% MFU) within noise; resync introduces no throughput regression. The for_loop MoE expert backend (PR #13) still fires correctly on XPU under the new parallelize signature. Default moe_2b() LBS=16 OOMs on Max 1550 (single 62.53 GiB allocation, likely the fused activation for all experts × full-batch-tokens); LBS=1 documented as the safe XPU baseline. Adds two new reports under docs/experiments/{agpt,moe}/sunspot/ and indexes them in the parent READMEs.
saforem2
added a commit
to saforem2/torchtitan
that referenced
this pull request
May 22, 2026
Adds docs/summaries/2026-05-08_to_2026-05-22.md (51 commits over ~2 weeks, organized by theme): - Upstream PyTorch PR for xccl _set_pg_timeout dispatch (pytorch/pytorch#184767, under review) - 4 upstream torchtitan syncs (34th–37th), two with non-trivial replays (PR pytorch#3159 Full DTensor signature change, PR pytorch#3386 MoE refactor) - 80B bad-node failover wrapper for production training; the e216a25 silent-hang detection fix closes the 8479579 incident class where the wrapper saw shell exit 0 while the inner trainer had died - agpt_{2b,20b,80b}_real configs with cos_sin RoPE for v1 lm-eval alignment - Sunspot 2N smoke campaigns post-resync - MoE EP=2 step-41 hang investigation (reclassified transient on retry; surfaced the xccl-timeout-never-fires gap that kicked off the upstream PR thread) - TPC26 MAPE talk prep (outline + §9 engineer-hours data) - Docs hygiene (TREE.md, Date columns on production tables, unstaled "Last updated" markers, lychee link fixes) Adds the corresponding row to docs/summaries/README.md and a journal entry for today summarizing the PR filing + this writeup.
saforem2
added a commit
to saforem2/torchtitan
that referenced
this pull request
Jun 12, 2026
…ytorch#3159) Upstream `_dist_reduce` switched from `full_tensor()` to `x.to_local()` for DTensor inputs in commit d64eabc (PR pytorch#3159, merged 2026-05-18), which is the same end-state our trainer.py + validator.py were forcing locally with `loss = loss.full_tensor()` before `dist_sum`. With the upstream fix in our `ezpz` branch via the 50th-54th syncs, the local workaround is now redundant. Validated against agpt_2b TP=2 (2N, job 12468704): step-1 loss 12.885, matching the known-good ~12.94 from the bug doc. The bug value (no fix anywhere) would have been ~1.07. The EzpzValidator subclass is preserved for its other responsibilities (dataloader caching, job_config pass-through to the blendcorpus loader).
saforem2
added a commit
to saforem2/torchtitan
that referenced
this pull request
Jun 12, 2026
…rker Reflects that upstream PR pytorch#3159 (commit d64eabc, 2026-05-18) landed the `to_local()` fix and PR pytorch#3204 was closed as superseded. - guides/loss-reporting-tp-dist-reduce.md: rewritten as resolved doc with the historical window, the symptom table, the as-shipped fix shape, and the affected-window-only advice for 80B W&B traces. - upstream-issues/dist_reduce_dtensor_skip.md: status header flipped to resolved with the upstream commit/PR link and the disposition of PR pytorch#3204. - docs/README.md: status column updated for both linked docs. - .claude/CLAUDE.md: Recent Findings entry rewritten as past-tense with the fix commit; Known Bugs entry removed entirely. - summaries/2026-06-05_to_2026-06-12.md: bump four→five upstream syncs, add 54th-sync row to the syncs table, and replace bullet-list-marker "+ cherry-picks" with "and cherry-picks" to fix a markdown reflow that broke the opening paragraph.
saforem2
added a commit
to saforem2/torchtitan
that referenced
this pull request
Jun 13, 2026
Two test harnesses generalized from one-off scratch scripts written during the PR #14 investigation and the TP-loss-reporting cleanup. moe_ab_check.sh Generic A/B diff for any MoE config across two git commits. Uses ephemeral worktrees, shared .venv via symlink, extracts loss + grad_norm per step, reports BIT-IDENTICAL or DRIFT. Required env vars: BASELINE_COMMIT, HEAD_COMMIT, CONFIG. Optional: STEPS, EP, PADDING. smoke_agpt_tp2.sh Small TP=2 sanity smoke for agpt_${MODEL}. Useful for catching TP-related regressions (e.g. the off-by-dp_world_size loss bug the upstream PR pytorch#3159 fix resolved). Step-1 loss ~12.94 for agpt_2b on the known-good path.
saforem2
added a commit
to saforem2/torchtitan
that referenced
this pull request
Aug 11, 2026
torch 2.10 (frameworks/2025.3.1) cannot import DataParallelMeshDims from torch.distributed.fsdp, so core torchtitan/distributed/fsdp.py fails on import and every rank dies. Reached via agpt/parallelize.py; landed upstream with pytorch#3159. Verified on Aurora 2026-08-11: torch 2.13.0.dev20260428+xpu -> DataParallelMeshDims present torch 2.10.0a0+git449b176 -> absent The README advertised 'PyTorch >= 2.10', which sent a user down a torch-2.10 path. ConfigManager._load_config masks the real ImportError behind the generic "Cannot import config_registry", so the cause is not discoverable from the failure -- document the direct import probe that surfaces it.
jialei777
pushed a commit
to jialei777/torchtitan
that referenced
this pull request
Oct 19, 2026
… commit `659a0d`). This CL imports TorchTitan head and stabilizes the build. Supporting feature gaps to be done in follow-up CLs. **For a summary of major changes and disabled tests see [internal link]** In this CL, we bypass the [ban](https://github.com/pytorch/torchtitan/blob/1c40dd26a91b0489249011a53d1da69061b03d38/torchtitan/models/common/config_utils.py#L85) of SDPA backend for language models in `models/common/config_utils.py` so our monkey patch to apply splash attention kernel works. Deprecation of sdpa backend on TPU and supporting document packing in the SplashAttention kernel is handled in child cl/954755047 In OSS, torch>=2.12 is **required**. After this update several files import `DataParallelMeshDims` from `torch.distributed.fsdp` which is only available in torch >=2.12 It disables the following tests: b/540005818 Disabled for numerical divergences: - test_train_minimal_distributed llama3_fsdp - test_train_minimal_distributed llama3_simplefsdp - test_train_minimal_distributed qwen3_simplefsdp - test_flux_qkv_split TestFluxSingleStreamUnbind Disabled for other reasons: - b/540119277 test_fused_swiglu_override - circular import issue with spmd_type - b/540048441 graph trainer tests (upstream refactored trace_train_step into minimal_fx_tracer API): - b/540049946 deepseek_v3_tp_dtensor - Linear: output DTensor has placements (Shard(dim=1),), but out_src_shardings expects (Shard(dim=2),) Tested on OSS with image built from torch 2.12: - redacted SimpleFSDP Compiled: [10,925 TPS]([internal link]) (10,0922 at head) - FLUX SimpleFSDP Compiled (F32 + BF16 MP): [3,737 TPS]([internal link]) (3652 at head) - Llama3 SimpleFSDP Compiled: [5,444 TPS]([internal link]) (5384 at head) See the list of commits: pytorch/torchtitan@627126f...659a0d2 #MIGRATION_3P_PY_TORCHTITAN__DEFAULT - 95ae6a0 ci: regenerate qwen3_moe_rocm_mi350x.txt baseline with ac... by Rishi Sinha <[email protected]> - db5da4b Refactor pipeline parallel helpers for graph PP reuse (#2... by sanketpurandare <[email protected]> - 6065055 Revert precompile PRs (pytorch#3107, pytorch#3178) to fix CI (pytorch#3212) by Bob Ren <[email protected]> - 179d9e1 CP AllGather on the wrong dimension (pytorch#3206) by francesco-bertolotti <[email protected]> - f522db0 Fix commands in DSV3 readme (pytorch#3116) by Daniel Vega-Myhre <[email protected]> - 0b148a2 [CI] Run integration tests in parallel (pytorch#3144) by Yuankai Chen <[email protected]> - 080c1d4 [GraphTrainer] Annotate loss region with module_fqn (pytorch#3207) by Sherlock Huang <[email protected]> - b2cd149 Observability: structured logging + training instrumentat... by Felipe Mello <[email protected]> - 706ed8d [GraphTrainer] Annotate generated FX code with user sourc... by Aditya Venkataraman <[email protected]> - af8d243 [GraphTrainer] Skip identity-slice rewrite when start/end... by Aditya Venkataraman <[email protected]> - d3c96e8 [mxfp8] Fix MXFP8GroupedExpertsConverter to actually swap... by Aditya Venkataraman <[email protected]> - d341407 [MoE] Pad token count to a multiple of sp_size in AllToAl... by Jiani Wang <[email protected]> - 2ae1340 [rl] add import torch to provisioner bootstrap to avoid c... by Shuhua Yu <[email protected]> - 0b6a29e [rl] Set PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True... by Felipe Mello <[email protected]> - 2c237ae refactor get_attention_masks to use positions instead of ... by liangel-02 <[email protected]> - 74bac7e [graph_trainer] FSDP AG RS overlap (pytorch#3156) by Yiming Zhou <[email protected]> - b6830b2 Upgrades torchtitan-ubuntu docker image to 22.04 and CTK ... by Syed Tousif Ahmed <[email protected]> - 5fa7af6 [float8] Quantize GroupedExperts params during conversion... by Aditya Venkataraman <[email protected]> - e62ab09 [rl] Fix CI loss=0 and logprob=NaN (pytorch#3232) by Jiani Wang <[email protected]> - f32a5bb [GraphTrainer] Overhaul README for accuracy and clarity (... by Sherlock Huang <[email protected]> - e425316 [rl] Remove VLLMGenerator.__del__ cleanup method (pytorch#3224) by Danielle Pintz <[email protected]> - ef54395 [graph_trainer] Move all FSDP-specific passes to fsdp_pas... by Yiming Zhou <[email protected]> - 301384b [GraphTrainer] Register BlockMask pytree node in aot_fx_t... by Bob Ren <[email protected]> - a24b247 [graph_trainer] Disable cpu_offload_all CI test for upstr... by Sherlock Huang <[email protected]> - 2dfee86 [GraphTrainer] Update manifesto: hardware heterogeneity, ... by Sherlock Huang <[email protected]> - c6cfaa2 Re-land "Enable bucketing pass in precompile path" (pytorch#3107... by Bob Ren <[email protected]> - ae5ff10 [cpu-offloading] Implement prefetching for cpu offloading... by Michael Lazos <[email protected]> - 046fdbb Support mark_unbacked in minimal_fx_tracer (pytorch#3046) by Tugsbayasgalan Manlaibaatar <[email protected]> - 8599818 [rl] Add a tag to trigger RL CI runs (pytorch#3230) by Jiani Wang <[email protected]> - 466da8c [graph_trainer] Port remat_using_tags_for_fwd_loss_bwd_gr... by Sherlock Huang <[email protected]> - 94d5f59 Re-land "Fix FlexAttention precompile bitwise determinist... by Bob Ren <[email protected]> - e2fea3f Wrong token count in validation when CP>1 (pytorch#3257) by francesco-bertolotti <[email protected]> - 1d392ca [torchtitan][llama4_parallelize] fixing fsdp_mesh_info bu... by anshul-si <[email protected]> - d91a9fc [Qwen3VL] remove local_map for dtensor interpolation (pytorch#29... by Shuhua Yu <[email protected]> - 19f88a3 profiler: drop duplicate dataclass fields (pytorch#3227) by Felipe Mello <[email protected]> - 52f3142 [GraphTrainer] Log graph pass names and total time (pytorch#3261) by Sherlock Huang <[email protected]> - bf2842d [GraphTrainer] Add memory policy registry and extra graph... by Syed Tousif Ahmed <[email protected]> - 4ebb089 Tests HybridEP integration with GraphTrainer (pytorch#3184) by Syed Tousif Ahmed <[email protected]> - da6ff79 [rl] Graceful shutdown GRPO (pytorch#3238) by Felipe Mello <[email protected]> - 54887a3 [GraphTrainer] Add compile.disable_passes to selectively ... by Sherlock Huang <[email protected]> - 4ed3c53 [codex] Fix weight tying parameter accounting (pytorch#3225) by 岛石 <[email protected]> - 5638c49 [codex] Fix shared BOS and EOS token inference (pytorch#3279) by 岛石 <[email protected]> - ecd117e [graph_trainer] Pass global_valid_tokens into loss_fn ins... by Yidi Wu <[email protected]> - 0fae167 [graph_trainer] AutoParallel AOT FX Trace Integration (#2... by sanketpurandare <[email protected]> - 74181b1 [LoRA] Add LoRA converter and rename quantization to conv... by Yifan Mao <[email protected]> - 0d8f57c Remove unnecessary clone from ChunkedCELoss (pytorch#3272) by Jiani Wang <[email protected]> - 28b83bd Merge lora and float8 tests (pytorch#3310) by Yifan Mao <[email protected]> - e917ff4 Avoid repeat_interleave output-size sync (pytorch#3274) by Simon Fan <[email protected]> - acece3b [graph_trainer] Disable flexattn integration test due to ... by Sherlock Huang <[email protected]> - 8ba1c6b Support kwargs in minimal_fx_tracer (pytorch#3262) by Tugsbayasgalan Manlaibaatar <[email protected]> - d107aa4 [Quantization] Use class factory for MXFP8/Float8 Grouped... by Yifan Mao <[email protected]> - ca4c7f2 [rl] Register customized config parser to vllm + less vll... by Jiani Wang <[email protected]> - 0b5e899 Fix precompile tests (pytorch#3316) by Tugsbayasgalan Manlaibaatar <[email protected]> - 0fadde3 [graph_trainer] Fix AutoParallel input_fn to include posi... by Ivan Kobzarev <[email protected]> - 2ceff82 [graph_trainer] Add log_timer utility for tracing step ti... by Sherlock Huang <[email protected]> - e9dbff6 [graph_trainer] Refactor selective activation remat to in... by Tugsbayasgalan Manlaibaatar <[email protected]> - b301dfa Remove MoE expert for-loop fallback (pytorch#3308) by sanketpurandare <[email protected]> - 1a0fe3e [graph_trainer] Refactor passes.py into focused modules (... by Sherlock Huang <[email protected]> - d57df09 Make ChunkedCELoss support torch.autograd.grad (pytorch#3249) by Yidi Wu <[email protected]> - 5ca23a5 [GraphTrainer] Add Context Parallel support (pytorch#3305) by Aditya Venkataraman <[email protected]> - 7f070c9 Enhance Lychee Link Checker (Resiliency & Performance) (#... by Andrei-Aksionov <[email protected]> - 7f602b9 Add AGENTS.md symlinks for Codex usage (pytorch#3326) by sanketpurandare <[email protected]> - 34801c0 [graph_trainer] Improve SAC tagging and CPU offload pass ... by Sherlock Huang <[email protected]> - 1a22c2d [graph_trainer] Remove deprecated AOT compile mode (pytorch#3327) by Sherlock Huang <[email protected]> - 7b418ab Revert "Avoid repeat_interleave output-size sync (pytorch#3274)"... by Simon Fan <[email protected]> - 6f2fa2f [rl] switch to vllm v2 engine (pytorch#3330) by Jiani Wang <[email protected]> - 1690e0a [cpu-offloading] Encode last consumer as dep arg in ao.wa... by Michael Lazos <[email protected]> - cee4982 [graph_trainer] Fix SAC remat to produce fresh FakeTensor... by Ivan Kobzarev <[email protected]> - d4a3c63 [graph_trainer] Generalize minimal_fx_tracer to module + ... by Tugsbayasgalan Manlaibaatar <[email protected]> - 4614e30 [graph_trainer] Support multiple FSDP PGs in overlap_fsdp... by Sherlock Huang <[email protected]> - 3781d1d Back out "[graph_trainer] Fix SAC remat to produce fresh ... by Sherlock Huang <[email protected]> - a2a0d99 RL: observability spans across trainer/generator/controll... by Felipe Mello <[email protected]> - 8cdfdc2 [rl] Better initial weight loading (pytorch#3318) by Jiani Wang <[email protected]> - f0795f0 [RL] - Enable experiment metrics (pytorch#3237) by Felipe Mello <[email protected]> - b64292b [graph_trainer] Remove fsdp_reshard_after_fwd_pass (pytorch#3370) by Sherlock Huang <[email protected]> - a670699 [graph_trainer] Skip dense numerics tests due to upstream... by Sherlock Huang <[email protected]> - cb7bf09 ci: declare workflow-level `contents: read` on 2 workflow... by Arpit Jain <[email protected]> - d64eabc [Full DTensor] Config-based Full DTensor for Llama3 (pytorch#3159) by Chien-Chin Huang <[email protected]> - a866d04 Fix memory snapshot pickle protocol for compatibility wit... by francesco-bertolotti <[email protected]> - 9f9ae4d [graph_trainer] Fix H100 CI failure from DeepEP compilati... by Sherlock Huang <[email protected]> - c9126af [graph_trainer] Add bucketing ops to precompile serializa... by Ivan Kobzarev <[email protected]> - 013890b [graph_trainer] Defer cudagraph compatibility check to pa... by Ivan Kobzarev <[email protected]> - 6a1b334 Fix optimizer state and module state coupling (pytorch#3356) by Tugsbayasgalan Manlaibaatar <[email protected]> - 4238c35 Re-enable compile for gpt-oss integration tests (pytorch#3373) by Aditya Venkataraman <[email protected]> - ebfceeb [rl] Add TITO generator and gen metrics (pytorch#3391) by Felipe Mello <[email protected]> - cf3c431 [graph_trainer] Re-enable FlexAttention tests after upstr... by Sherlock Huang <[email protected]> - 8aa96ac [graph_trainer] Fix eager SAC policy mm counter to reset ... by Ivan Kobzarev <[email protected]> - 52a292d [graph_trainer] Gate overlap_fsdp_ag_rs_pass behind a con... by Yiming Zhou <[email protected]> - 2057b56 [rl] fix CI timeout issue by properly tear down for vllm ... by Jiani Wang <[email protected]> - cfe97c6 [rl] use wandb=False in CI (pytorch#3408) by Felipe Mello <[email protected]> - 83e4904 [graph_trainer] Rework full_inductor_compilation_pass via... by Tugsbayasgalan Manlaibaatar <[email protected]> - 963c20c [MoE][5/n] Refactor MoE to clean DTensor boundaries for s... by Jessica Zhong <[email protected]> - da38566 [MoE][6/n] Extract local_reorder, split DeepEP/HybridEP d... by Jessica Zhong <[email protected]> - 3f721b4 [graph_trainer] Fix fsdp_passes compat with BitsetAncesto... by Ivan Kobzarev <[email protected]> - b585282 Fix imports for latest DeepEP (pytorch#3414) by Steffen Hirschmann <[email protected]> - c2a3771 [loss] Fix ChunkedCELoss + TP gradient placement mismatch... by Chien-Chin Huang <[email protected]> - 19c567f Debug Numerics with DebugMode (pytorch#3323) by Shangdi Yu <[email protected]> - 78b08dd [graph_trainer] Add DeepSeek V3 16B SDPA config (pytorch#3361) by sanketpurandare <[email protected]> - af33f76 [Module] Replace from_nn_module with native Module subcla... by Chien-Chin Huang <[email protected]> - 58b0344 Add FSDP symmetric memory configuration and related tests... by Masaki <[email protected]> (And 259 more changes) PiperOrigin-RevId: 956923721
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):
Add full DTensor mode where all params, buffers, and inputs are DTensors on a multi-dimensional SPMD mesh (
dp_replicatexdp_shardxcpxtp). Enabled via--training.full_dtensor. CP is handled declaratively viaLocalMapSpec(K/VReplicateon CP dim for all-gather) instead ofapply_cp_to_forwardhooks. FSDP2 usesDataParallelMeshDimsto identifydp_replicate,dp_shardandcpas data-parallel dims on the multi-D mesh.Mesh Design:
ParallelDimsprecomputes oneDeviceMeshper SPMD partition in_spmd_meshes(dense and sparse). EachModuleself-resolves its mesh:_needed_axes(sharding_config)collects axes referenced by itsNamedPlacements, thenparallel_dims.get_module_mesh(axes)returns the cached submesh. Underfull_dtensor, all axes participate; under the legacy, non-full-dtensor path, axes are filtered to{tp, ep, etp}so DP and CP stay out-of-band.Module.parallelizeasserts the resolved mesh is one ofspmd_meshes()- 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 lives alongside dense in
_spmd_meshes, so MoE modules whosesharding_configreferences sparse axes resolve to the sparse submesh through the exact sameget_module_meshcall - 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
Note that: DP + CP + torch.compile fail.
Issues
view()rejectsShard()on a size-1 tensor dim: Hit by PP-only and TP-only with bs=1 because we keepdp_shardin the mesh; this PR convertsShard()toReplicate()on size-1 mesh axes inresolve_placements.loss_parallelonly supports 1D mesh upstream: Hit by FSDP+TP under full_dtensor. Needs PyTorch PR #180936; local checkout has it.PP's
torch.tensor_splitimplicitly all-gathersShard()toReplicate(): Hit by any PP+full_dtensor microbatch split. Needs PyTorch PR #180937 to switch to_split_tensor.full_dtensor + CP + SDPA/Varlenis unsupported. K/V all-gather on CP makes q vs kv lengths asymmetric, and causal SDPA can't handle that.validate_configrejects these combinations.flattenacross differently-sharded dims emits_StridedShardbreaks loss: Hit when pred is sharded on dp_shard (batch) and cp (seq) andcross_entropy_lossdidpred.flatten(0,1). Switched topermute(0,2,1)to avoid the merge. (Origin of the_StridedShardplacement that surfaces in items 6 and 7.)full_dtensor + CP + model compilehangs:_StridedShard.local_shard_size_and_offsetsymint storm during strategy enumeration. Disable model compile under CP.nll_loss2d_forwardhas no deterministic kernel: Hit by--debug.deterministic+ 3D-DTensor cross-entropy. Don't do--debug.deterministicfor these configs.DeviceMeshequality is by object identity: Hit becauseresolve_mesh()validatesmesh in parallel_dims.spmd_meshes()— recreating a mesh fails the check. Forces to cache created meshes in ParallelDimsaten.clone.default doesn't preserve Partial placement: Auto-registered as pointwise (only enumerates Replicate/Shard), silently redistributes Partial inputs. Hit by FSDP+TP loss bit-wise parity via
loss.detach().clone(). Fixed by PyTorch PR #182730.Our _dist_reduce under-reports loss for non full tensor:
full_tensor()reduces only over the DTensor's own mesh (TP-only in legacy), skipping DP. Loss was under-reported bydp_shard × cp. Switched toto_local()then mesh all_reduce over loss_mesh.CP+FSDP cannot achieve bit-wise parity with legacy under the 3D cross_entropy_loss path: Multi-axis sharding on batch and sequence axes forces to use 3D
cross_entropy_losspath. legacy stays onaten.nll_loss_forward. Different float32 reduction order yields bounded drift ~0.015 at step 1. Related to items 5 and 7.)clip_grad_norm_'s multi-axis _NormPartial -> Replicate reduction cause loss difference: The reduction does one all_reduce per SPMD axis. With full_dtensor there are multiple all_reduces (one per SPMD axis); non-full_dtensor does only one. The differing fp32 sum-order causes loss difference between modes.