Skip to content

[spmd_types] fully_shard in DTensor and spmd_types save-restore - #181519

Closed
pianpwk wants to merge 52 commits into
gh/pianpwk/138/basefrom
gh/pianpwk/138/head
Closed

pianpwk wants to merge 52 commits into
gh/pianpwk/138/basefrom
gh/pianpwk/138/head

Conversation

@pianpwk

@pianpwk pianpwk commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

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:

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:

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:

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):

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:

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:

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:

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:

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.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Apr 26, 2026 •

Copy link
Copy Markdown

🔗 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 SEVs

There 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 (image):

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.

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (fsdp) release notes category labels Apr 26, 2026
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Apr 27, 2026
…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
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Apr 27, 2026
…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
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Apr 27, 2026
…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
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Apr 27, 2026
…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
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Apr 27, 2026
…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
pianpwk added 2 commits April 28, 2026 11:45
…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]
@pianpwk
pianpwk marked this pull request as ready for review April 28, 2026 19:51
@pianpwk
pianpwk requested a review from weifengpy as a code owner April 28, 2026 19:51
@pianpwk pianpwk changed the title [spmd_types] fully_shard with DTensor-based sharding and spmd_types save-restore [spmd_types] fully_shard in DTensor and spmd_types save-restore Apr 28, 2026
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):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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}. "

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

better type plz

mesh_info.dp_mesh_dims.replicate_names,
)
)
fsdp_axis = spmd.MeshAxis.of(mesh_info.mesh._flatten().get_group(0))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ezyang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems functionally correct and low risk now but I don't really like the code structure.

@ezyang

ezyang commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

@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

claude Bot commented Jun 23, 2026 •

Copy link
Copy Markdown

Claude finished @ezyang's task in 2m 35s —— View job


Review of @ezyang's recent stylistic comments

I read through the 2026-06-23 batch against _fsdp_param.py and largely agree with them. The dominant theme — code structure around the spmd-types init path — is the right thing to be pushing on, and the individual comments are consistent with what I see in the file. Below is where I agree, where I'd prioritize, and a few things I'd add.

Strong agreement (and these reinforce each other)

  • Recomputing local_type three times is the clearest smell. The merge of _spmd_init_local_type with partition_spec_to_shard_types(self._spmd_partition_spec) appears at lines 405-408, 454-456, and 542-544. Your "doing this thing twice is a smell, evidence the function splits are not factored correctly" comment (line 544) is dead on — this is the concrete evidence for it. Compute the merged local type once and thread it through.

  • self is left in a partially-initialized state across helpers. _resolve_spmd_restore_mesh() sets self._spmd_restore_mesh, then _spmd_types_to_dtensor() sets self._spmd_restore_type and self._spmd_grad_placements. Your line-299 comments (pass values in; avoid leaving self invalid on raised exceptions) are correct, and they compound: most of these helpers raise partway through, so a failure leaves a half-populated object. The fix you're gesturing at — pass spmd_mesh/partition spec/local type in as args, return the results, assign once — resolves the invalid-state concern and the redundant-recompute concern at the same time.

  • Merging _resolve_spmd_restore_mesh + _spmd_types_to_dtensor (line 299, Codex note). Agreed it's review-hostile as split. The invariants genuinely span both (spmd_mesh is None is re-checked at both 398 and 444; the same-mesh span check is relevant to both). A single _resolve_spmd_types_for_storage() that does canonicalize → validate → produce (restore_mesh, restore_type, placements, grad_placements) would be much easier to audit.

  • Canonicalize-first, then validate (line 458). Agreed. The _spans_same_mesh early-return at 459-462 short-circuits before the partial-annotation validation at 478-499, so the two branches establish different invariant sets. Pulling validation out so it runs unconditionally on the resolved mesh is clearer.

  • mesh._flatten().get_group(0) to get a MeshAxis (line 531). This is the most substantive correctness-adjacent one. Materializing a flattened process group purely to derive a MeshAxis can have the side effect of creating a communicator. Doing the flatten in pure MeshAxis space is safer; agreed.

  • spmd_mesh naming (line 444). Agreed and worth fixing — it reads as "the spmd-types mesh" but it's the FSDP storage mesh, which is precisely the opposite of where types live. This name has tripped up reviewers in this very thread (tianyu-l's repeated "compute vs storage mesh" questions).

  • Private-API imports (lines 20-21). Agreed these are a smell. flatten_axes is used solely for the "spans same mesh" test, which is a good candidate to live in spmd_types directly (e.g. a public spans_same_mesh), and get_partition_spec being importable from spmd_types.runtime but not as spmd.get_partition_spec is an inconsistency worth fixing upstream rather than reaching into submodules here.

  • Nits I agree with and are cheap: better type annotations (454, 505, 542), error-message guidance for dp_mesh_dims (448), "resolved typechecking mesh" is jargon a user won't action (485), examples in the 395 docblock.

Lower priority / I'd not block on

  • Helpers on mesh_info (line 538) and a DeviceMesh -> dict[str, MeshAxis] helper in spmd_types (line 452). Both are good centralizations, but they're cross-module API additions. I'd treat them as follow-ups rather than gating this PR, consistent with your APPROVED.

Things I'd add

  1. The _spmd_* fields violate the repo's explicit-state rule. _spmd_partition_spec, _spmd_init_local_type, _spmd_restore_mesh, _spmd_restore_type, _spmd_grad_placements are only ever assigned inside the is_spmd_types branch and scattered across three methods — they don't appear in any class/dataclass definition. CLAUDE.md is explicit here: "there should be a clear class definition that has all of the members: don't dynamically setattr a field and then getattr it." This is the single change that would address the most of your comments at once: collapse all of them into one Optional[_SpmdMetadata] dataclass field, populated by the single resolver above and assigned once. A reader then has one place to see what spmd state exists and one place where it's produced.

  2. The axis <= fsdp_axis containment test (line 546) is clever but undocumented. It relies on MeshAxis ordering/containment semantics to decide "is this annotation inside the FSDP submesh." That's load-bearing and non-obvious; it deserves a one-line comment, and it's another argument for the mesh_info helper you suggested (e.g. mesh_info.contains_axis(axis)).

  3. _get_grad_inner_tensor asserts is_dtensor must be true on the spmd path (line 1200). pianpwk confirmed that's the intended happy path (the wrap-then-redistribute relies on it), but the assertion message reads like an internal invariant rather than documenting why spmd implies dtensor here. Given your earlier "early exit is almost certainly wrong" concern on this function, a short note tying the two branches together would help future readers not re-derive it.

  4. On the broader load-bearing-types tension (your line-295 thread with tianyu-l): that debate looks resolved for this PR, and I agree it shouldn't reopen here. But the resolution — spmd types are now load-bearing for generating the storage DTensor — is exactly why the structural cleanup above matters more than usual: when types drive correctness rather than just detection, the init path that translates them needs to be unusually easy to audit. So I'd weight the "merge + canonicalize + single state object" refactor as the highest-value change, above the naming/type/message nits.

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 _flatten().get_group() side-effect fix — in that order.

@ezyang

ezyang commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

@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

claude Bot commented Jun 23, 2026 •

Copy link
Copy Markdown

Claude finished @ezyang's task in 7m 2s —— View job


Risk assessment: preexisting (non-spmd-types) FSDP usage

I checked every touched site for the path taken when there are no spmd types — meaning either spmd_types is not installed, or it's installed but no parameter carries a local type. Bottom line: for preexisting production FSDP, this change is behaviorally a no-op. The gating is clean. Below is the per-site walk-through.

The gate

is_spmd_types is computed once in FSDPParam.__init__ (_fsdp_param.py:291):

self.is_spmd_types = (
    dist._is_spmd_types_available()          # cached bool
    and bool(spmd.get_local_type(param))
    and not isinstance(param, DTensor)
)

_is_spmd_types_available() memoizes an importlib.util.find_spec check. When the package isn't installed it returns False and short-circuits, so spmd.get_local_type is never called (and spmd is never imported — the top-level import is itself gated). When it is installed but the param is unannotated, get_local_type(param) is falsy. Either way is_spmd_types is False, and it's the discriminator for every new branch. It is always assigned, so no AttributeError risk on the read paths.

Site-by-site

Site Non-spmd behavior Risk
__init__ rename shard_result → shard_placement_result + = None init (:255) Pure rename; the new local is only consumed inside the same if callable(...) block. Identical control flow. None
__init__ spmd block (:296) is_spmd_types is False → entire block skipped, param unchanged. None
init_unsharded_param (:921) New if self.is_spmd_types: pass falls through to the original elif self._unsharded_dtensor_spec is not None: — same code as base. None
_get_grad_inner_tensor (:1189) New leading if self.is_spmd_types: block skipped; falls into the unchanged if self.is_dtensor: path. None
_fsdp_param.py top-level imports (:16) All spmd_types imports under if dist._is_spmd_types_available(). Not imported. None
_fsdp_param_group.py module-level register_local_autograd_function (:1158) Gated; skipped at import. None

The two genuinely-new things in the hot path (still no-ops, but worth naming)

  1. New per-param loop in FSDPParamGroup.pre_forward (:555):

    for fsdp_param in self.fsdp_params:
        fsdp_param._restore_spmd_types(fsdp_param.unsharded_param)

    This runs unconditionally on every forward. For non-spmd params _restore_spmd_types returns on its first clause — not self.is_spmd_types short-circuits before spmd.is_type_checking(), so the (possibly unimported) spmd is never touched. The only residual cost is the Python loop itself plus eager evaluation of the fsdp_param.unsharded_param property (a bare attribute return). This is O(params-per-group) of trivial work added to the hotpath. Negligible in practice, but it's the one new unconditional cost; if you wanted it strictly zero-cost you could guard the loop with if dist._is_spmd_types_available(): or a group-level any(p.is_spmd_types ...) flag computed at init.

  2. _pre_forward restructuring in _fsdp_state.py (:290): the single with _spmd_no_typecheck() was split into three blocks so that _root_pre_forward/prefetch stay inside no_typecheck while _cast_forward_inputs and pre_forward move outside it. I traced the statement order against base — it is identical; only the typecheck-context boundaries moved. Since _spmd_no_typecheck() is a no-op contextmanager when the package is absent, which statements sit inside vs. outside it is irrelevant for non-spmd users. The only cost is constructing ~3 no-op context managers per forward instead of 1 (a cached-bool check + a generator each). Negligible.

This also resolves the earlier "this will severely slow down fsdp2 in normal hotpath" concern: _cast_forward_inputs is no longer re-entering typechecking, and there is no per-tensor traversal added to the non-spmd path.

Notes

  • The fsdp2_mem_tracker.py "line fuzz" flagged earlier is no longer in the changeset (4 files now), so nothing to assess there.
  • No public FSDP signatures change for non-spmd callers; is_spmd_types defaults to False for ordinary nn.Parameter and DTensor params (the not isinstance(param, DTensor) clause keeps the existing FSDP-on-DTensor path on its original branches).

Verdict: Low risk to preexisting production FSDP. All new logic is behind is_spmd_types, which is False for every existing usage; control flow and numerics on those paths are unchanged. The single thing I'd actually flag is the unconditional per-param _restore_spmd_types loop in pre_forward — correct and cheap, but it's the one piece of new work that executes for everyone. Cheap to make it strictly zero-cost →

[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Jun 23, 2026
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
@pianpwk

pianpwk commented Jun 23, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Jun 23, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…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
@github-actions
github-actions Bot deleted the gh/pianpwk/138/head branch July 24, 2026 02:26
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…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
Devin-DC-Huang added a commit to cosdt-ci-test/workflows that referenced this pull request Sep 4, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged release notes: distributed (fsdp) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants