Repository navigation
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/181519
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: ✅ You can merge normally! (5 Unrelated Failures)As of commit cf76705 with merge base 1f8b8fc ( FLAKY - The following job failed but was likely due to flakiness present on trunk:
BROKEN TRUNK - The following jobs failed but was present on the merge base:👉 Rebase onto the `viable/strict` branch to avoid these failures
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
…ave-restore Approach 1: FSDP keeps sharded params as DTensors, saving original spmd_types annotations before sharding and restoring them on unsharded params for compute. Key changes in _fsdp_param.py: - Detect spmd_types-annotated plain tensors via has_local_type() - _spmd_types_to_dtensor: translate spmd_types annotations to DTensor placements (I/R -> Replicate, S(dim) -> Shard(dim)) and wrap as DTensor on the SPMD mesh - _restore_spmd_types: re-apply saved annotations (I normalized to R) on the unsharded param in to_unsharded() - init_unsharded_param: skip DTensor wrapping for spmd_types params (keep plain) - _get_grad_inner_tensor: return plain grad directly for spmd_types params Benefits over the pure-spmd_types approach: - Optimizer state gets DTensor sharding for free via zeros_like(DTensor) - No changes needed to _fsdp_collectives.py (standard DTensor grad path) - FSDP internals remain unchanged ghstack-source-id: 5e27ccb Pull Request resolved: #181519
…ave-restore Approach 1: FSDP keeps sharded params as DTensors, saving original spmd_types annotations before sharding and restoring them on unsharded params for compute. Key changes in _fsdp_param.py: - Detect spmd_types-annotated plain tensors via has_local_type() - _spmd_types_to_dtensor: translate spmd_types annotations to DTensor placements (I/R -> Replicate, S(dim) -> Shard(dim)) and wrap as DTensor on the SPMD mesh - _restore_spmd_types: re-apply saved annotations (I normalized to R) on the unsharded param in to_unsharded() - init_unsharded_param: skip DTensor wrapping for spmd_types params (keep plain) - _get_grad_inner_tensor: return plain grad directly for spmd_types params Benefits over the pure-spmd_types approach: - Optimizer state gets DTensor sharding for free via zeros_like(DTensor) - No changes needed to _fsdp_collectives.py (standard DTensor grad path) - FSDP internals remain unchanged ghstack-source-id: 8c13b59 Pull Request resolved: #181519
…ave-restore Approach 1: FSDP keeps sharded params as DTensors, saving original spmd_types annotations before sharding and restoring them on unsharded params for compute. Key changes in _fsdp_param.py: - Detect spmd_types-annotated plain tensors via has_local_type() - _spmd_types_to_dtensor: translate spmd_types annotations to DTensor placements (I/R -> Replicate, S(dim) -> Shard(dim)) and wrap as DTensor on the SPMD mesh - _restore_spmd_types: re-apply saved annotations (I normalized to R) on the unsharded param in to_unsharded() - init_unsharded_param: skip DTensor wrapping for spmd_types params (keep plain) - _get_grad_inner_tensor: return plain grad directly for spmd_types params Benefits over the pure-spmd_types approach: - Optimizer state gets DTensor sharding for free via zeros_like(DTensor) - No changes needed to _fsdp_collectives.py (standard DTensor grad path) - FSDP internals remain unchanged ghstack-source-id: f75ba8d Pull Request resolved: #181519
…ave-restore Approach 1: FSDP keeps sharded params as DTensors, saving original spmd_types annotations before sharding and restoring them on unsharded params for compute. Key changes in _fsdp_param.py: - Detect spmd_types-annotated plain tensors via has_local_type() - _spmd_types_to_dtensor: translate spmd_types annotations to DTensor placements (I/R -> Replicate, S(dim) -> Shard(dim)) and wrap as DTensor on the SPMD mesh - _restore_spmd_types: re-apply saved annotations (I normalized to R) on the unsharded param in to_unsharded() - init_unsharded_param: skip DTensor wrapping for spmd_types params (keep plain) - _get_grad_inner_tensor: return plain grad directly for spmd_types params Benefits over the pure-spmd_types approach: - Optimizer state gets DTensor sharding for free via zeros_like(DTensor) - No changes needed to _fsdp_collectives.py (standard DTensor grad path) - FSDP internals remain unchanged ghstack-source-id: 7c473ee Pull Request resolved: #181519
…ave-restore Approach 1: FSDP keeps sharded params as DTensors, saving original spmd_types annotations before sharding and restoring them on unsharded params for compute. Key changes in _fsdp_param.py: - Detect spmd_types-annotated plain tensors via has_local_type() - _spmd_types_to_dtensor: translate spmd_types annotations to DTensor placements (I/R -> Replicate, S(dim) -> Shard(dim)) and wrap as DTensor on the SPMD mesh - _restore_spmd_types: re-apply saved annotations (I normalized to R) on the unsharded param in to_unsharded() - init_unsharded_param: skip DTensor wrapping for spmd_types params (keep plain) - _get_grad_inner_tensor: return plain grad directly for spmd_types params Benefits over the pure-spmd_types approach: - Optimizer state gets DTensor sharding for free via zeros_like(DTensor) - No changes needed to _fsdp_collectives.py (standard DTensor grad path) - FSDP internals remain unchanged ghstack-source-id: 0ff2360 Pull Request resolved: #181519
…pmd_types save-restore" Approach 1: FSDP keeps sharded params as DTensors, saving original spmd_types annotations before sharding and restoring them on unsharded params for compute. Key changes in _fsdp_param.py: - Detect spmd_types-annotated plain tensors via has_local_type() - _spmd_types_to_dtensor: translate spmd_types annotations to DTensor placements (I/R -> Replicate, S(dim) -> Shard(dim)) and wrap as DTensor on the SPMD mesh - _restore_spmd_types: re-apply saved annotations (I normalized to R) on the unsharded param in to_unsharded() - init_unsharded_param: skip DTensor wrapping for spmd_types params (keep plain) - _get_grad_inner_tensor: return plain grad directly for spmd_types params Benefits over the pure-spmd_types approach: - Optimizer state gets DTensor sharding for free via zeros_like(DTensor) - No changes needed to _fsdp_collectives.py (standard DTensor grad path) - FSDP internals remain unchanged [ghstack-poisoned]
…pmd_types save-restore" Approach 1: FSDP keeps sharded params as DTensors, saving original spmd_types annotations before sharding and restoring them on unsharded params for compute. Key changes in _fsdp_param.py: - Detect spmd_types-annotated plain tensors via has_local_type() - _spmd_types_to_dtensor: translate spmd_types annotations to DTensor placements (I/R -> Replicate, S(dim) -> Shard(dim)) and wrap as DTensor on the SPMD mesh - _restore_spmd_types: re-apply saved annotations (I normalized to R) on the unsharded param in to_unsharded() - init_unsharded_param: skip DTensor wrapping for spmd_types params (keep plain) - _get_grad_inner_tensor: return plain grad directly for spmd_types params Benefits over the pure-spmd_types approach: - Optimizer state gets DTensor sharding for free via zeros_like(DTensor) - No changes needed to _fsdp_collectives.py (standard DTensor grad path) - FSDP internals remain unchanged [ghstack-poisoned]
| axis_type = local_type.get(axis) | ||
| if axis_type is None or axis_type is I or axis_type is R: | ||
| placements.append(Replicate()) | ||
| elif isinstance(axis_type, S): |
There was a problem hiding this comment.
I think axis_type won't be S. It's V + PartitionSpec.
| raise ValueError( | ||
| f"Parameter '{self._module_info.param_name}' has spmd_types " | ||
| "annotations on axes that are not in the resolved " | ||
| f"typechecking mesh. Annotated axes: {unknown_axes}. " |
There was a problem hiding this comment.
What is a "resolved typechecking mesh". I doubt a user will understand what to do in this situation
| ) | ||
| local_type: dict[Any, Any] = dict(self._spmd_init_local_type) | ||
| if self._spmd_partition_spec is not None: | ||
| local_type.update(partition_spec_to_shard_types(self._spmd_partition_spec)) |
There was a problem hiding this comment.
I don't understand why we have to do this. Shouldn't we have an invariant in spmd types that every mesh axis in partition spec is specified in the local spmd type? This seems like a good invariant to have if we don't have it.
There was a problem hiding this comment.
ah this is more for spmd.S -> Shard translation, less about missing axes
| compute. The later DTensor conversion validates that the annotations | ||
| are compatible with FSDP storage. | ||
| """ | ||
| spmd_mesh = self.mesh_info.spmd_mesh |
There was a problem hiding this comment.
spmd_mesh is a very unfortunate name, as it seems to imply it is the mesh for spmd types, but actually it is emphatically not! We can fix the local naming though!
| raise AssertionError( | ||
| "spmd_types storage mesh should have been validated before " | ||
| "_spmd_types_to_dtensor" | ||
| ) |
There was a problem hiding this comment.
Instead of repeatedly checking the invariant on the inside of these functions, check it once outside and pass spmd_mesh in as an argument.
| ) | ||
| spmd_mesh_dim_names = spmd_mesh.mesh_dim_names | ||
| storage_mesh_axes = tuple( | ||
| spmd.MeshAxis.of(spmd_mesh.get_group(name)) for name in spmd_mesh_dim_names |
There was a problem hiding this comment.
spmd_types should likely have a dedicated function (or maybe class concept?) for this. Basically take a DeviceMesh to a dict of string name to MeshAxis. We probably have a helper like this squirreled away. Not sure if you actually want to have a more fancy type for the "mesh but only containing MeshAxis".
| self, | ||
| spmd_mesh: DeviceMesh, | ||
| mesh_info: DataParallelMeshInfo, | ||
| ) -> dict[Any, Any]: |
| mesh_info.dp_mesh_dims.replicate_names, | ||
| ) | ||
| ) | ||
| fsdp_axis = spmd.MeshAxis.of(mesh_info.mesh._flatten().get_group(0)) |
There was a problem hiding this comment.
This seems sus. Because you're just trying to get a MeshAxis, you shouldn't ask for the flattened PG, you can do the flatten in pure MeshAxis land. I think that we are going to need the flattened PG anyway, but it's much safer to not use APIs that can potentially create communicators.
| ) | ||
| non_fsdp_spmd_mesh_axes = { | ||
| axis for name, axis in spmd_mesh_axes if name not in dp_names | ||
| } |
There was a problem hiding this comment.
Codex suggests that maybe we should add some helpers on mesh_info. Seems like a good place to centralize to me.
| storage_axis_types = { | ||
| axis: spmd.R for name, axis in spmd_mesh_axes if name in dp_names | ||
| } | ||
| local_type: dict[Any, Any] = dict(self._spmd_init_local_type) |
There was a problem hiding this comment.
Why do you have to dict'ify it here. Also would be helpful to have a type annotation on the _spmd_init_local_type field and other fields so it's clear what it's type is.
| } | ||
| local_type: dict[Any, Any] = dict(self._spmd_init_local_type) | ||
| if self._spmd_partition_spec is not None: | ||
| local_type.update(partition_spec_to_shard_types(self._spmd_partition_spec)) |
There was a problem hiding this comment.
Same invariant comment here. Also, the fact that you're doing this thing twice is a smell, and evidence (for me) that the function splits here are not factored correctly.
ezyang
left a comment
There was a problem hiding this comment.
This seems functionally correct and low risk now but I don't really like the code structure.
|
@claude look at ezyang's recent stylistic comments and see if you agree with them. Also, is there anything you would add, given this context? |
|
Claude finished @ezyang's task in 2m 35s —— View job Review of @ezyang's recent stylistic commentsI read through the 2026-06-23 batch against Strong agreement (and these reinforce each other)
Lower priority / I'd not block on
Things I'd add
Net: your comments are well-calibrated and I wouldn't drop any of them. If I were prioritizing for a follow-up, it's (a) one resolver function returning one spmd-state dataclass, (b) canonicalize-then-validate, (c) the |
|
@claude Suppose there are no spmd types. Evaluate the risk of this change in that context for preexisting production FSDP usage. Check each site carefully |
|
Claude finished @ezyang's task in 7m 2s —— View job Risk assessment: preexisting (non-spmd-types) FSDP usageI checked every touched site for the path taken when there are no spmd types — meaning either The gate
self.is_spmd_types = (
dist._is_spmd_types_available() # cached bool
and bool(spmd.get_local_type(param))
and not isinstance(param, DTensor)
)
Site-by-site
The two genuinely-new things in the hot path (still no-ops, but worth naming)
This also resolves the earlier "this will severely slow down fsdp2 in normal hotpath" concern: Notes
Verdict: Low risk to preexisting production FSDP. All new logic is behind |
FSDP now recognizes spmd_types-annotated plain parameters on a named full SPMD mesh, translates their compute-time metadata into DTensor storage placements before sharding, and restores local spmd_types metadata on the unsharded plain parameter for module compute. This version supports partial parameter annotations by resolving the compute mesh at init time. FSDP uses ShardPlacementResult.spmd_compute_mesh when provided, falls back to the per-param storage mesh for shard_placement_fn paths, and otherwise uses the ambient spmd.set_current_mesh() around fully_shard(). Missing FSDP-managed compute axes are restored as spmd.R, so dense params can annotate only TP while sparse params can annotate only EP without relying on the runtime current mesh during FSDP pre-forward. Gradient handling derives backward placements from the forward SPMD type, wraps plain gradients as DTensors, and then uses the existing DTensor/FSDP gradient path so non-DP redistributions happen in DTensor form while DP reduction stays with FSDP. Test Plan: ```bash lintrunner -a python -m py_compile torch/distributed/fsdp/_fully_shard/_fsdp_common.py torch/distributed/fsdp/_fully_shard/_fully_shard.py torch/distributed/fsdp/_fully_shard/_fsdp_param.py torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py torch/distributed/fsdp/_fully_shard/_fsdp_state.py test/distributed/_composable/fsdp/test_fully_shard_spmd_types.py python test/distributed/_composable/fsdp/test_fully_shard_spmd_types.py ``` lintrunner -a did not complete because PYREFLY and FLAKE8 attempted to fetch dependencies from PyPI and DNS resolution failed in this environment. Authored with the assistance of an AI assistant. ghstack-source-id: ddc3b31 Pull Request resolved: #181519
|
@pytorchbot merge |
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 |
…rch#181519) Supports fully_shard on spmd_types-annotated tensors, by translating to DTensor placements (storage-time representation is DTensor), restoring the annotations at compute time. At init time, FSDP reads the parameter’s SPMD type dict and optional PartitionSpec. It normalizes S(dim) into the global representation V + PartitionSpec, then builds DTensor placements from that metadata: R@DP/CP axes is enforced as FSDP owns DP gradient reduction, TP has more flexibility. A local-only V without PartitionSpec is rejected. The .md file I ended up writing for the flow, to get the later iterations of the PR: ``` We call fully_shard with a DeviceMesh + parameters + likely DataParallelMeshDims object. The parameters are spmd type-annotated on the mesh, and fully_shard is responsible for translating this to DTensor placements when it recognizes them. e.g. if we're working with FSDP+TP, the params are TP-sharded & annotated as S(dim)@tp before fully_shard sees them; the end-state DTensor should have Shard on both FSDP&TP axes. For the DP&CP axes (i.e. FSDP axis), we should assert DP:R, CP:R (or FSDP:R) annotations on those params, given that FSDP will perform a all-reduce across the FSDP axis. The FSDP internals are under no_typecheck. The DP:R, CP:R are re-annotated on the unsharded plain tensors at compute time. For TP axis, we have 2 types of parameters: 1) S(*)@tp - sharded params on TP, e.g. TP colwise/rowwise matmuls. The P->S(*) reduce scatter should be handled before FSDP sees them, so no big deal here. 2) unsharded params on TP, e.g. router gate weight, RMSNorm weights. These have the global shape, but may see different gradients (if seq-parallel SP is on) if SP is on, the compute-state gradient will be Partial, meaning an spmd FWD type of R@TP. fully_shard + DTensor currently handles the all-reduce (and potentially merges the AR w/ the DP/CP axis AR), with if placements != grad.placements: grad = grad.redistribute(placements=placements) if SP is off, then we don't need an allreduce and life is fine. In the case where we do need AR (R@TP FWD), the handling should be: - at init time, we already do the spmd->DTensor placement translation and wrapping (where I->R becomes Replicate). - we should also do spmd->placement translation for the SPMD BWD TYPE (e.g. R@TP FWD -> P@TP BWD -> Partial@TP BWD placement; I@TP FWD -> I@TP BWD -> Replicate@TP BWD placement). - since the point of spmd_types is runtime erasure, we do not rely on gradients have spmd types annotated at all, and instead just wrap the incoming gradient with the inferred BWD placement. - if the placement is different for translated storage-time placement, we optionally redistirbute. - this should give the correct behavior that I and S(*) @tp placements in FWD do not redistribute (gradient placements are Replicate, Shard, respectively). - but R@TP FWD placements will require FSDP to perform an allreduce@TP - note: we should ban P@TP FWD placements for now (not required, and we could technically support, but I don't know who's doing this?) Add or extend the test cases to have params unsharded on TP, run with SP on and off, and checking that the BWD allreduce happens only for the SP on case. ``` This PR intentionally keeps restore-mesh resolution narrow: 1. Fully annotated parameters are self-contained for restore-mesh resolution. If the annotated axes span the same rank set as the FSDP storage mesh, FSDP restores on the annotated mesh directly. 2. Partially annotated parameters require one ambient typechecking mesh. Wrap `fully_shard()` in `spmd.set_current_mesh(...)` when all parameters in the FSDP unit share that mesh. Storage placement still has to be valid. Any annotated FSDP-owned axes must be contained in the FSDP DP submesh and must be `spmd.R`. Any annotated non-FSDP axes must map 1:1 to non-FSDP storage axes, and non-FSDP storage axes cannot be omitted. Mixed per-parameter typechecking meshes are supported only when each parameter is fully annotated. Mixed per-parameter partial annotations are not supported; use full annotations or split the `fully_shard()` calls. ## Behavior FSDP-owned DP axes must be `spmd.R`, because FSDP performs the DP gradient reduction. Non-FSDP storage axes must be explicitly annotated so FSDP can translate them to DTensor placements. Local-only `spmd.V` without a `PartitionSpec` is rejected because FSDP cannot choose a DTensor `Shard(dim)` from plain Varying. Forward annotations also determine expected backward DTensor placements. For example, `R` becomes `P` in backward and maps to `Partial`, while `I` and `S(dim)` remain `Replicate` and `Shard(dim)`. This lets FSDP wrap incoming gradients with the inferred placement and redistribute only when the gradient placement differs from the storage placement. ## Calling Conventions Fully annotated parameters: ```python spmd.assert_type( param, {dp_axis: spmd.R, cp_axis: spmd.R, tp_axis: spmd.S(0)}, ) fully_shard( module, mesh=storage_mesh, dp_mesh_dims=DataParallelMeshDims( shard=("dp_shard", "cp"), replicate="dp_replicate", ), ) ``` Partial annotations with one shared typechecking mesh: ```python with spmd.set_current_mesh(type_mesh): spmd.assert_type(param, {tp_axis: spmd.S(0)}) fully_shard( module, mesh=storage_mesh, dp_mesh_dims=DataParallelMeshDims( shard=("dp_shard", "cp"), replicate="dp_replicate", ), ) ``` Mixed dense/sparse parameter groups in one FSDP unit, w/ full annotations (`torchtitan/fsdp.py` calling convention for MoE): ```python dense_mesh_info = _get_mesh_info( dense_storage_mesh, # [dp_replicate, dp_shard, cp, tp] DataParallelMeshDims(shard=("dp_shard", "cp"), replicate="dp_replicate"), ) sparse_mesh_info = _get_mesh_info( sparse_mesh, # [dp_replicate, efsdp, ep] DataParallelMeshDims(shard="efsdp", replicate="dp_replicate"), ) spmd.assert_type( dense_param, {dp_axis: spmd.R, cp_axis: spmd.R, tp_axis: spmd.S(0)}, ) spmd.assert_type( sparse_param, {dp_replicate_axis: spmd.R, efsdp_axis: spmd.R, ep_axis: spmd.S(0)}, ) def shard_placement_fn(param): if param is sparse_param: return ShardPlacementResult(placement=Shard(0), mesh_info=sparse_mesh_info) return ShardPlacementResult(placement=Shard(0), mesh_info=dense_mesh_info) fully_shard( module, mesh=dense_storage_mesh, dp_mesh_dims=DataParallelMeshDims( shard=("dp_shard", "cp"), replicate="dp_replicate", ), shard_placement_fn=shard_placement_fn, ) ``` The dense parameter above is fully annotated on `[dp, cp, tp]`, even though its FSDP storage mesh is `[dp_replicate, dp_shard, cp, tp]`. The sparse parameter is fully annotated on `[dp_replicate, efsdp, ep]`. Since both are fully annotated, FSDP can restore each parameter on its own annotated mesh without per-parameter compute-mesh metadata. ## Invalid Cases Partial annotation without an ambient typechecking mesh: ```python spmd.assert_type(param, {ep_axis: spmd.S(0)}) fully_shard( module, mesh=dense_storage_mesh, dp_mesh_dims=DataParallelMeshDims( shard=("dp_shard", "cp"), replicate="dp_replicate", ), ) ``` This errors because the partial annotation cannot be restored from the dense FSDP storage mesh, and there is no shared `spmd.current_mesh()` to fill omitted axes. Non-FSDP axis mismatch: ```python spmd.assert_type( param, {dp_replicate_axis: spmd.R, efsdp_axis: spmd.R, ep_axis: spmd.S(0)}, ) fully_shard( module, mesh=dense_storage_mesh, dp_mesh_dims=DataParallelMeshDims( shard=("dp_shard", "cp"), replicate="dp_replicate", ), ) ``` This errors because `ep` is neither part of the dense FSDP DP mesh nor a non-FSDP storage axis in the dense storage mesh. Missing non-FSDP storage axis: ```python with spmd.set_current_mesh(dense_type_mesh): spmd.assert_type(param, {dp_axis: spmd.R, cp_axis: spmd.R}) fully_shard( module, mesh=dense_storage_mesh, dp_mesh_dims=DataParallelMeshDims( shard=("dp_shard", "cp"), replicate="dp_replicate", ), ) ``` This errors because FSDP can infer omitted FSDP-managed axes as `spmd.R`, but non-FSDP storage axes like TP must be annotated. FSDP-owned axis not annotated as `spmd.R`: ```python with spmd.set_current_mesh(dense_type_mesh): spmd.assert_type( param, {dp_axis: spmd.I, cp_axis: spmd.R, tp_axis: spmd.I}, ) fully_shard( module, mesh=dense_storage_mesh, dp_mesh_dims=DataParallelMeshDims( shard=("dp_shard", "cp"), replicate="dp_replicate", ), ) ``` This errors because FSDP owns gradient reduction across the DP submesh, so FSDP-managed axes must be `spmd.R`. ## Tests The new FSDP SPMD tests cover: - preserving compute-time annotations through FSDP all-gather/reshard, - rejecting local-only `V` parameters without `PartitionSpec`, - partial annotations resolved from ambient `spmd.current_mesh()`, - folded storage mesh `[dp_replicate, fsdp, tp]` with typechecking mesh `[dp, cp, tp]`, - mixed dense/sparse fully annotated params with per-param storage meshes, - invalid partial mixed-mesh annotations, and - expected DP gradient communication behavior for sequence parallel on/off. Pull Request resolved: pytorch#181519 Approved by: https://github.com/zpcore, https://github.com/weifengpy, https://github.com/ezyang
…rch#181519) Supports fully_shard on spmd_types-annotated tensors, by translating to DTensor placements (storage-time representation is DTensor), restoring the annotations at compute time. At init time, FSDP reads the parameter’s SPMD type dict and optional PartitionSpec. It normalizes S(dim) into the global representation V + PartitionSpec, then builds DTensor placements from that metadata: R@DP/CP axes is enforced as FSDP owns DP gradient reduction, TP has more flexibility. A local-only V without PartitionSpec is rejected. The .md file I ended up writing for the flow, to get the later iterations of the PR: ``` We call fully_shard with a DeviceMesh + parameters + likely DataParallelMeshDims object. The parameters are spmd type-annotated on the mesh, and fully_shard is responsible for translating this to DTensor placements when it recognizes them. e.g. if we're working with FSDP+TP, the params are TP-sharded & annotated as S(dim)@tp before fully_shard sees them; the end-state DTensor should have Shard on both FSDP&TP axes. For the DP&CP axes (i.e. FSDP axis), we should assert DP:R, CP:R (or FSDP:R) annotations on those params, given that FSDP will perform a all-reduce across the FSDP axis. The FSDP internals are under no_typecheck. The DP:R, CP:R are re-annotated on the unsharded plain tensors at compute time. For TP axis, we have 2 types of parameters: 1) S(*)@tp - sharded params on TP, e.g. TP colwise/rowwise matmuls. The P->S(*) reduce scatter should be handled before FSDP sees them, so no big deal here. 2) unsharded params on TP, e.g. router gate weight, RMSNorm weights. These have the global shape, but may see different gradients (if seq-parallel SP is on) if SP is on, the compute-state gradient will be Partial, meaning an spmd FWD type of R@TP. fully_shard + DTensor currently handles the all-reduce (and potentially merges the AR w/ the DP/CP axis AR), with if placements != grad.placements: grad = grad.redistribute(placements=placements) if SP is off, then we don't need an allreduce and life is fine. In the case where we do need AR (R@TP FWD), the handling should be: - at init time, we already do the spmd->DTensor placement translation and wrapping (where I->R becomes Replicate). - we should also do spmd->placement translation for the SPMD BWD TYPE (e.g. R@TP FWD -> P@TP BWD -> Partial@TP BWD placement; I@TP FWD -> I@TP BWD -> Replicate@TP BWD placement). - since the point of spmd_types is runtime erasure, we do not rely on gradients have spmd types annotated at all, and instead just wrap the incoming gradient with the inferred BWD placement. - if the placement is different for translated storage-time placement, we optionally redistirbute. - this should give the correct behavior that I and S(*) @tp placements in FWD do not redistribute (gradient placements are Replicate, Shard, respectively). - but R@TP FWD placements will require FSDP to perform an allreduce@TP - note: we should ban P@TP FWD placements for now (not required, and we could technically support, but I don't know who's doing this?) Add or extend the test cases to have params unsharded on TP, run with SP on and off, and checking that the BWD allreduce happens only for the SP on case. ``` This PR intentionally keeps restore-mesh resolution narrow: 1. Fully annotated parameters are self-contained for restore-mesh resolution. If the annotated axes span the same rank set as the FSDP storage mesh, FSDP restores on the annotated mesh directly. 2. Partially annotated parameters require one ambient typechecking mesh. Wrap `fully_shard()` in `spmd.set_current_mesh(...)` when all parameters in the FSDP unit share that mesh. Storage placement still has to be valid. Any annotated FSDP-owned axes must be contained in the FSDP DP submesh and must be `spmd.R`. Any annotated non-FSDP axes must map 1:1 to non-FSDP storage axes, and non-FSDP storage axes cannot be omitted. Mixed per-parameter typechecking meshes are supported only when each parameter is fully annotated. Mixed per-parameter partial annotations are not supported; use full annotations or split the `fully_shard()` calls. ## Behavior FSDP-owned DP axes must be `spmd.R`, because FSDP performs the DP gradient reduction. Non-FSDP storage axes must be explicitly annotated so FSDP can translate them to DTensor placements. Local-only `spmd.V` without a `PartitionSpec` is rejected because FSDP cannot choose a DTensor `Shard(dim)` from plain Varying. Forward annotations also determine expected backward DTensor placements. For example, `R` becomes `P` in backward and maps to `Partial`, while `I` and `S(dim)` remain `Replicate` and `Shard(dim)`. This lets FSDP wrap incoming gradients with the inferred placement and redistribute only when the gradient placement differs from the storage placement. ## Calling Conventions Fully annotated parameters: ```python spmd.assert_type( param, {dp_axis: spmd.R, cp_axis: spmd.R, tp_axis: spmd.S(0)}, ) fully_shard( module, mesh=storage_mesh, dp_mesh_dims=DataParallelMeshDims( shard=("dp_shard", "cp"), replicate="dp_replicate", ), ) ``` Partial annotations with one shared typechecking mesh: ```python with spmd.set_current_mesh(type_mesh): spmd.assert_type(param, {tp_axis: spmd.S(0)}) fully_shard( module, mesh=storage_mesh, dp_mesh_dims=DataParallelMeshDims( shard=("dp_shard", "cp"), replicate="dp_replicate", ), ) ``` Mixed dense/sparse parameter groups in one FSDP unit, w/ full annotations (`torchtitan/fsdp.py` calling convention for MoE): ```python dense_mesh_info = _get_mesh_info( dense_storage_mesh, # [dp_replicate, dp_shard, cp, tp] DataParallelMeshDims(shard=("dp_shard", "cp"), replicate="dp_replicate"), ) sparse_mesh_info = _get_mesh_info( sparse_mesh, # [dp_replicate, efsdp, ep] DataParallelMeshDims(shard="efsdp", replicate="dp_replicate"), ) spmd.assert_type( dense_param, {dp_axis: spmd.R, cp_axis: spmd.R, tp_axis: spmd.S(0)}, ) spmd.assert_type( sparse_param, {dp_replicate_axis: spmd.R, efsdp_axis: spmd.R, ep_axis: spmd.S(0)}, ) def shard_placement_fn(param): if param is sparse_param: return ShardPlacementResult(placement=Shard(0), mesh_info=sparse_mesh_info) return ShardPlacementResult(placement=Shard(0), mesh_info=dense_mesh_info) fully_shard( module, mesh=dense_storage_mesh, dp_mesh_dims=DataParallelMeshDims( shard=("dp_shard", "cp"), replicate="dp_replicate", ), shard_placement_fn=shard_placement_fn, ) ``` The dense parameter above is fully annotated on `[dp, cp, tp]`, even though its FSDP storage mesh is `[dp_replicate, dp_shard, cp, tp]`. The sparse parameter is fully annotated on `[dp_replicate, efsdp, ep]`. Since both are fully annotated, FSDP can restore each parameter on its own annotated mesh without per-parameter compute-mesh metadata. ## Invalid Cases Partial annotation without an ambient typechecking mesh: ```python spmd.assert_type(param, {ep_axis: spmd.S(0)}) fully_shard( module, mesh=dense_storage_mesh, dp_mesh_dims=DataParallelMeshDims( shard=("dp_shard", "cp"), replicate="dp_replicate", ), ) ``` This errors because the partial annotation cannot be restored from the dense FSDP storage mesh, and there is no shared `spmd.current_mesh()` to fill omitted axes. Non-FSDP axis mismatch: ```python spmd.assert_type( param, {dp_replicate_axis: spmd.R, efsdp_axis: spmd.R, ep_axis: spmd.S(0)}, ) fully_shard( module, mesh=dense_storage_mesh, dp_mesh_dims=DataParallelMeshDims( shard=("dp_shard", "cp"), replicate="dp_replicate", ), ) ``` This errors because `ep` is neither part of the dense FSDP DP mesh nor a non-FSDP storage axis in the dense storage mesh. Missing non-FSDP storage axis: ```python with spmd.set_current_mesh(dense_type_mesh): spmd.assert_type(param, {dp_axis: spmd.R, cp_axis: spmd.R}) fully_shard( module, mesh=dense_storage_mesh, dp_mesh_dims=DataParallelMeshDims( shard=("dp_shard", "cp"), replicate="dp_replicate", ), ) ``` This errors because FSDP can infer omitted FSDP-managed axes as `spmd.R`, but non-FSDP storage axes like TP must be annotated. FSDP-owned axis not annotated as `spmd.R`: ```python with spmd.set_current_mesh(dense_type_mesh): spmd.assert_type( param, {dp_axis: spmd.I, cp_axis: spmd.R, tp_axis: spmd.I}, ) fully_shard( module, mesh=dense_storage_mesh, dp_mesh_dims=DataParallelMeshDims( shard=("dp_shard", "cp"), replicate="dp_replicate", ), ) ``` This errors because FSDP owns gradient reduction across the DP submesh, so FSDP-managed axes must be `spmd.R`. ## Tests The new FSDP SPMD tests cover: - preserving compute-time annotations through FSDP all-gather/reshard, - rejecting local-only `V` parameters without `PartitionSpec`, - partial annotations resolved from ambient `spmd.current_mesh()`, - folded storage mesh `[dp_replicate, fsdp, tp]` with typechecking mesh `[dp, cp, tp]`, - mixed dense/sparse fully annotated params with per-param storage meshes, - invalid partial mixed-mesh annotations, and - expected DP gradient communication behavior for sequence parallel on/off. Pull Request resolved: pytorch#181519 Approved by: https://github.com/zpcore, https://github.com/weifengpy, https://github.com/ezyang
…aParallelMeshDims import; align prepare_environment to xtuner-style torchtitan v0.3.0 (released 2026-09-03, commit 086bf6c) hard-depends on torch.distributed.fsdp.DataParallelMeshDims at module top-level in torchtitan/distributed/full_dtensor.py:16 and fsdp.py:13-18; trainer / components/validate.py trigger the import unconditionally on entry. DataParallelMeshDims was added to torch in 2.12.0 (PR pytorch/pytorch#181519, commit da19cbd7, 2026-06-23). The doc + test prep had pinned torch 2.10.0 + torch_npu 2.10.0.post4, so any v0.3.0 checkout crashed with ImportError at import time before reaching the training loop (23s into the smoke). Three changes: 1. projects/torchtitan/docs/Quick-start-Ascend.md — version table bumps torch/torch_npu to 2.12.0; new #test-setup install block (Aliyun, xtuner-style) added between check-py and check-torch so the install runs before the import probe. Prereq bullet about pre-installed torch+torch_npu dropped (CANN 9.x base layer does not ship torch). 2. projects/torchtitan/tests/test_quick_start_ascend.py — prepare_environment slimmed to mirror xtuner's: CANN env + CUDA exclusion list + uv install only. Removed dead probe code (_PROBE_SCRIPT / _VERSIONS_SCRIPT / _CLUSTER_INDEX / _ASCEND_EXTRA); that code only mattered when the image was assumed to ship torch 2.10, which it never did — the probe always failed with ModuleNotFoundError and the fallback install always ran. All section headers + docstring + comments updated to reflect that torch / torch_npu / torchtitan install are owned by the doc body. 3. Order of doc body blocks matches xtuner: check-py -> install torch + torch_npu (#test-setup) -> check-torch (probe verifies install) -> install modelscope / triton / torchtitan. Unverified: torch_npu 2.12.0 cp312 aarch64 wheel is listed on PyPI but needs unzip -l + coder smoke before next CI run to confirm ABI matches the CANN 9.1.0 base image.
Stack from ghstack (oldest at bottom):
Supports fully_shard on spmd_types-annotated tensors, by translating to DTensor placements (storage-time representation is DTensor), restoring the annotations at compute time.
At init time, FSDP reads the parameter’s SPMD type dict and optional PartitionSpec. It normalizes S(dim) into the global representation V + PartitionSpec, then builds DTensor placements from that metadata: R@DP/CP axes is enforced as FSDP owns DP gradient reduction, TP has more flexibility. A local-only V without PartitionSpec is rejected.
The .md file I ended up writing for the flow, to get the later iterations of the PR:
This PR intentionally keeps restore-mesh resolution narrow:
fully_shard()inspmd.set_current_mesh(...)when all parameters in the FSDP unit share that mesh.Storage placement still has to be valid. Any annotated FSDP-owned axes must be contained in the FSDP DP submesh and must be
spmd.R. Any annotated non-FSDP axes must map 1:1 to non-FSDP storage axes, and non-FSDP storage axes cannot be omitted.Mixed per-parameter typechecking meshes are supported only when each parameter is fully annotated. Mixed per-parameter partial annotations are not supported; use full annotations or split the
fully_shard()calls.Behavior
FSDP-owned DP axes must be
spmd.R, because FSDP performs the DP gradient reduction. Non-FSDP storage axes must be explicitly annotated so FSDP can translate them to DTensor placements. Local-onlyspmd.Vwithout aPartitionSpecis rejected because FSDP cannot choose a DTensorShard(dim)from plain Varying.Forward annotations also determine expected backward DTensor placements. For example,
RbecomesPin backward and maps toPartial, whileIandS(dim)remainReplicateandShard(dim). This lets FSDP wrap incoming gradients with the inferred placement and redistribute only when the gradient placement differs from the storage placement.Calling Conventions
Fully annotated parameters:
Partial annotations with one shared typechecking mesh:
Mixed dense/sparse parameter groups in one FSDP unit, w/ full annotations (
torchtitan/fsdp.pycalling convention for MoE):The dense parameter above is fully annotated on
[dp, cp, tp], even though its FSDP storage mesh is[dp_replicate, dp_shard, cp, tp]. The sparse parameter is fully annotated on[dp_replicate, efsdp, ep]. Since both are fully annotated, FSDP can restore each parameter on its own annotated mesh without per-parameter compute-mesh metadata.Invalid Cases
Partial annotation without an ambient typechecking mesh:
This errors because the partial annotation cannot be restored from the dense FSDP storage mesh, and there is no shared
spmd.current_mesh()to fill omitted axes.Non-FSDP axis mismatch:
This errors because
epis neither part of the dense FSDP DP mesh nor a non-FSDP storage axis in the dense storage mesh.Missing non-FSDP storage axis:
This errors because FSDP can infer omitted FSDP-managed axes as
spmd.R, but non-FSDP storage axes like TP must be annotated.FSDP-owned axis not annotated as
spmd.R:This errors because FSDP owns gradient reduction across the DP submesh, so FSDP-managed axes must be
spmd.R.Tests
The new FSDP SPMD tests cover:
Vparameters withoutPartitionSpec,spmd.current_mesh(),[dp_replicate, fsdp, tp]with typechecking mesh[dp, cp, tp],