Skip to content

[spmd_types] spmd infra - #3253

Merged
pianpwk merged 68 commits into
gh/pianpwk/5/basefrom
gh/pianpwk/5/head
Jun 11, 2026
Merged

pianpwk merged 68 commits into
gh/pianpwk/5/basefrom
gh/pianpwk/5/head

Conversation

@pianpwk

@pianpwk pianpwk commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Main infra PR for spmd_types + titan.

spmd_types.py:

  • Adds a thread-local DeviceMesh stack, and current_mesh(), set_current_mesh() helpers, to be set and accessed at model init (weight parallelize) and runtime (PG access for collectives)
  • Various helpers for spmd_types : module-boundary redistributions, spmd -> DTensor placement translation (for full_dtensor backend), mesh_size(axis_name) helper that returns > 1 when mesh is set & axis is active. Some of this will be moved to spmd_types in near-term, see comments.

parallel_dims.py:

  • For spmd backend, we need 2 views over the world mesh: [pp, dp, cp, tp] for typechecking, and [pp, dp_replicate, dp_shard, cp, tp] to pass the unfolded fsdp axes to fully_shard, via DataParallelMeshDims. So we hold both the full-DTensor-style dense mesh, as well as the "typechecking" mesh.

module.py: module.parallelize() paths for spmd backend: weight init, local SPMD drop in, input/output redistribution.

trainer.py/utils.py: typechecking context, input annotation, spmd set_current_spmd_mesh, PP + typechecking raises a hard error.

Stack from ghstack (oldest at bottom):

[ghstack-poisoned]
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label May 6, 2026
This was referenced May 6, 2026
pianpwk added 4 commits May 6, 2026 16:07
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
pianpwk added 3 commits May 7, 2026 23:04
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
pianpwk added 3 commits May 10, 2026 12:11
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@pianpwk pianpwk changed the title [draft][spmd_llama3] ParallelDims, ShardingConfig, parallelize_spmd [spmd_llama3] ParallelDims, ShardingConfig, parallelize_spmd May 11, 2026
[ghstack-poisoned]
Comment thread torchtitan/protocols/module.py Resolved
Comment thread torchtitan/protocols/sharding.py Resolved
Comment thread torchtitan/distributed/spmd_state.py Outdated

Populated once during ``ParallelDims.build_mesh()`` when
``full_spmd_types=True``. Provides forward-time access to mesh axes
and process groups.

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.

Is this because torchtitan doesn't have a concept of a global mesh? I think @tianyu-l has stated he's amenable to adding this idea to torchtitan? But what I hear from RL land is that it is annoying if the mesh is global as it makes it difficult to have multiple meshes coexisting together in weird RL setup. Why isn't spmd type's concept of current mesh enough?

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.

ParallelDims is required for Module. We cannot kill it without killing the existing workflow. We can switch to MeshAxes and ditch DeviceMesh once we kill the legacy path. But for now, we have to keep DeviceMesh alive.

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.

Concretely, I would like torchtitan to keep DeviceMesh. Perhaps I just don't understand the lifecycle of DeviceMesh in torchtitan today.

Comment thread torchtitan/distributed/spmd_state.py Resolved
Comment thread torchtitan/distributed/spmd_state.py Resolved
Comment thread torchtitan/distributed/spmd_state.py Resolved
Comment thread torchtitan/distributed/spmd_state.py Resolved
Comment thread torchtitan/distributed/spmd_state.py Resolved
Comment thread torchtitan/protocols/sharding.py Outdated
# Value is either a DTensor Placement (Shard, Replicate, Partial) or an
# spmd_types type (R, I, V, P, S(dim)). parallelize() duck-types on the
# value to dispatch DTensor vs SPMD paths.
NamedPlacement = dict[MeshAxisName, Placement | spmd.PerMeshAxisSpmdType]

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.

So, what exactly is the checkpointing plan? I know we talked about it on Friday and it has escaped my memory again. (I am wondering about it here because I'm not sure if this is going to work here, depending on where NamedPlacement is used in torchtitan?)

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.

NamedPlacement is used for TorchTitan config system only to support both DTensor and spmd_types. Shouldn't be a checkpointing issue.

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.

@ezyang One way is to let state_dict create a DTensor on the full storage mesh, so that DCP can communicate with. The pro is that it will work regardless of fully_shard applied or not, e.g. not applied in RL's generator.

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.

Ah yes, I remember this constraint. So if we have DTensor on all the at rest tensors (non compute), then post FSDP we have a DTensor that we need to turn into a plain tensor and put spmd types annotation on. So it's mostly about making sure we do the TP type translation correctly here (since DTensor doesn't specify if it was expecting to handle the TP all-reduce as part of the DP all-reduce or not).

Comment thread torchtitan/protocols/sharding.py Resolved
pianpwk added a commit that referenced this pull request Jun 9, 2026
Adding this to allow both spmd types specs, and DTensor-style
placements. We're adding something like D107576760 in spmd_types, but in
the meantime, because non-llama3 models are still in DTensor placement
form, I think we have 2 options:

1) keep this as a hybrid spmd/DTensor container (e.g. moe_sharding.py
calls `dense_activation_placement(tp=Replicate())`, and migrate to
SpmdLayout once all models are off full_dtensor.
2) since we're adding a spmd->DTensor translation shim anyways, migrate
all models from `Replicate/Shard/Partial` to `spmd.R/S/P` immediately,
use SpmdLayout, and go deal with I/R distinctions later. This should be
ok because non-llama3 models won't support spmd backend yet.

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.12.0)
(oldest at bottom):
* #3278
* #3472
* #3468
* #3471
* #3253
* #3587
* #3586
* __->__ #3501
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Jun 9, 2026
[ghstack-poisoned]
Comment thread torchtitan/distributed/full_dtensor.py Outdated
Comment on lines +106 to +108
# This means fully_shard() has no spmd annotations -> DTensor param translation,
# and we shouldn't be passing a DataParallelMeshDims object to FSDP.
return storage_mesh, None

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.

oh, you mean both functions are short? Sure, collapsing sounds good.

tuple(["pp"] + candidate_spmd_dense_axes),
(self.pp, batch, self.cp, self.tp),
)
spmd_dense_mesh_for_fwdbwd = full_dense_mesh_for_fwdbwd["dp", "cp", "tp"]

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.

shall we add a TODO:
after migration is done, we let spmd_types handle all the size 1 processing (maybe except for fully_shard call with DP dim info)

Comment thread torchtitan/protocols/module.py Outdated

self.forward = forward_with_redistribution

def _register_spmd_state(

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.

Suggested change
def _register_spmd_state(
def _spmd_register_state(

Comment thread torchtitan/protocols/module.py Outdated
device_mesh=resolved_mesh,
)

def _apply_local_spmd(

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.

Suggested change
def _apply_local_spmd(
def _spmd_apply_local_map(

After migration is done, we can remove all spmd prefixes

Comment on lines +524 to +525
src_spmd_layout.per_axis_spmd_types(),
dst_spmd_layout.per_axis_spmd_types(),

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 can allow subtle bugs?
e.g. what if src: (DP, CP), dst: (CP, DP)

may need some additional guardrail

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.

check the validation helper in the previous PR, that should handle it

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.

OK, cool. Maybe
_validate_spmd_redistributions -> spmd_validate_redistributions
since it's public

Comment on lines +600 to +601
out_src.per_axis_spmd_types(),
out_dst.per_axis_spmd_types(),

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.

similar

Comment thread torchtitan/trainer.py
loss = self.loss_fn(pred, labels, global_valid_tokens)
del pred
loss.backward()
with spmd.no_typecheck():

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.

so without adding this no_typecheck context

the backward would also attempt to propagate spmd_types, intercepted by torch_function?

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.

adding a comment would be good to readers

pianpwk added 2 commits June 9, 2026 14:09
[ghstack-poisoned]
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Jun 9, 2026
Splitting up infra PR. This adds:
- _shard_spmd_state: util for distributing param/buffer onto mesh in
SpmdLayout format, supporting PartitionSpec shard order
- redistribute_spmd_per_axis: module boundary, SpmdLayout-based
redistribution handler
- _validate_spmd_redistributions: helper for validating it resolves to
just one spmd.redistribute call - that's all titan will support

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.12.0)
(oldest at bottom):
* #3278
* #3472
* #3468
* #3471
* #3253
* __->__ #3587

@tianyu-l tianyu-l 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.

final nits 🦖

Comment thread torchtitan/trainer.py
loss = self.loss_fn(pred, labels, global_valid_tokens)
del pred
loss.backward()
with spmd.no_typecheck():

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.

adding a comment would be good to readers

Comment thread torchtitan/distributed/spmd_types.py Outdated
return stack


def current_mesh() -> DeviceMesh | None:

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.

Suggested change
def current_mesh() -> DeviceMesh | None:
def current_spmd_mesh() -> DeviceMesh | None:

Comment thread torchtitan/distributed/spmd_types.py Outdated
_spmd_backend = spmd_backend


def _mesh_stack() -> list[DeviceMesh | None]:

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.

Suggested change
def _mesh_stack() -> list[DeviceMesh | None]:
def _spmd_mesh_stack() -> list[DeviceMesh | None]:

Comment thread torchtitan/distributed/spmd_types.py Outdated
return stack[-1]


def mesh_size(axis_name: str) -> int:

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.

Suggested change
def mesh_size(axis_name: str) -> int:
def spmd_mesh_size(axis_name: str) -> int:

Comment thread torchtitan/distributed/spmd_types.py Outdated


@contextlib.contextmanager
def preserve_buffers_spmd(model: nn.Module) -> Iterator[None]:

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.

Suggested change
def preserve_buffers_spmd(model: nn.Module) -> Iterator[None]:
def spmd_preserve_buffers(model: nn.Module) -> Iterator[None]:

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.

Can we put this into Module, as Module._preserve_buffer_spmd_types()

Comment thread torchtitan/protocols/module.py Outdated
layout.partition_spec,
)

def _shard_states(self, parallel_dims: ParallelDims) -> None:

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.

Suggested change
def _shard_states(self, parallel_dims: ParallelDims) -> None:
def _distribute_states(self, parallel_dims: ParallelDims) -> None:

to not confuse with spmd.Shard

Comment thread torchtitan/protocols/module.py Outdated

self.forward = forward_with_redistribution

def _spmd_register_state(

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.

Suggested change
def _spmd_register_state(
def _spmd_distribute_state(

sorry for the back-n-forth

Comment thread torchtitan/distributed/spmd_types.py Outdated
return

saved = {
fqn: (dict(spmd.get_local_type(buf)), spmd.get_partition_spec(buf))

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.

could you use an SpmdLayout object here?

wwwjn pushed a commit that referenced this pull request Jun 10, 2026
Adding this to allow both spmd types specs, and DTensor-style
placements. We're adding something like D107576760 in spmd_types, but in
the meantime, because non-llama3 models are still in DTensor placement
form, I think we have 2 options:

1) keep this as a hybrid spmd/DTensor container (e.g. moe_sharding.py
calls `dense_activation_placement(tp=Replicate())`, and migrate to
SpmdLayout once all models are off full_dtensor.
2) since we're adding a spmd->DTensor translation shim anyways, migrate
all models from `Replicate/Shard/Partial` to `spmd.R/S/P` immediately,
use SpmdLayout, and go deal with I/R distinctions later. This should be
ok because non-llama3 models won't support spmd backend yet.

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.12.0)
(oldest at bottom):
* #3278
* #3472
* #3468
* #3471
* #3253
* #3587
* #3586
* __->__ #3501
wwwjn pushed a commit that referenced this pull request Jun 10, 2026
wwwjn pushed a commit that referenced this pull request Jun 10, 2026
Splitting up infra PR. This adds:
- _shard_spmd_state: util for distributing param/buffer onto mesh in
SpmdLayout format, supporting PartitionSpec shard order
- redistribute_spmd_per_axis: module boundary, SpmdLayout-based
redistribution handler
- _validate_spmd_redistributions: helper for validating it resolves to
just one spmd.redistribute call - that's all titan will support

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.12.0)
(oldest at bottom):
* #3278
* #3472
* #3468
* #3471
* #3253
* __->__ #3587
saforem2 pushed a commit to saforem2/torchtitan that referenced this pull request Jun 10, 2026
Splitting up infra PR. This adds:
- _shard_spmd_state: util for distributing param/buffer onto mesh in
SpmdLayout format, supporting PartitionSpec shard order
- redistribute_spmd_per_axis: module boundary, SpmdLayout-based
redistribution handler
- _validate_spmd_redistributions: helper for validating it resolves to
just one spmd.redistribute call - that's all titan will support

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.12.0)
(oldest at bottom):
* pytorch#3278
* pytorch#3472
* pytorch#3468
* pytorch#3471
* pytorch#3253
* __->__ pytorch#3587
[ghstack-poisoned]
pianpwk added 6 commits June 10, 2026 22:22
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@pianpwk
pianpwk merged commit 62bb07d into gh/pianpwk/5/base Jun 11, 2026
10 of 15 checks passed
@pianpwk pianpwk mentioned this pull request Jun 11, 2026
pianpwk added a commit that referenced this pull request Jun 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants