Skip to content

Fix SimpleFSDP metadata for uneven composed sharding - #4593

Merged
tianyu-l merged 1 commit into
pytorch:mainfrom
sorenzzio:simplefsdp-fix
Sep 16, 2026
Merged

tianyu-l merged 1 commit into
pytorch:mainfrom
sorenzzio:simplefsdp-fix

Conversation

@sorenzzio

Copy link
Copy Markdown
Contributor

SimpleFSDP uses full global tensor metadata when applying DP sharding to a TP/EP-local tensor. It also relies on implicit shape inference when rewrapping DTensors, which cannot recover uneven shard sizes correctly. For example, a TP-local dimension of size 5 split across two DP ranks produces shards of size 3 and 2; inferring the global size from either shard gives 6 or 4 instead of 5.

This change:

  • Uses the TP/EP-local tensor's shape and stride for the temporary DP redistribution specs.
  • Derives the DP-only logical shape and stride from the input DTensor metadata and passes them explicitly during rewrapping.
  • Restores the input's global shape and stride when wrapping the gathered tensor on the TP/EP mesh.
  • Preserves requires_grad when recreating parameters, so frozen parameters remain frozen.

Adds 14 component regression cases to the existing TestSimpleFSDP class, covering uneven and empty shards, FSDP/HSDP with TP, EP+TP composition, transposed parameters, compilation, meta initialization, the spmd_types backend, and frozen parameters. The shared numerical checks compare outputs, losses, accumulated gradients, parameter updates, and AdamW state against an unsharded reference.

Validation:

  • All 14 added cases passed using an 8-process CPU/Gloo launcher adapter running the original test methods.
  • File-scoped pre-commit checks passed, excluding Pyrefly due to existing repository-wide failures.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 11, 2026
@tianyu-l tianyu-l added the ciflow/graph-trainer Run GraphTrainer CI label Sep 11, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 11, 2026

Copy link
Copy Markdown

Warning: Unknown label ciflow/graph-trainer.
Currently recognized labels are

  • ciflow/b200
  • ciflow/h100.8
  • ciflow/rl

Please add the new label to .github/pytorch-probot.yml

@tianyu-l
tianyu-l requested a review from pianpwk September 11, 2026 06:59
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude please verify if this is a legit problem. If so, does it happen with spmd_backend being "partial_dtensor" or "spmd_types" (introduced in #4325) or both?

@claude

claude Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 4m 30s —— View job


Verification: SimpleFSDP metadata for uneven composed sharding

  • Read the changed code and git diff
  • Determine whether the uneven-shard metadata problem is real
  • Determine which spmd_backend is affected

Is this a legit problem?

Yes. There are two distinct metadata bugs here, both on the composed DP + TP/EP path, and both are real:

1. _distribute_dtensor used the global tensor meta to redistribute a local tensor (simple_fsdp.py:179-193, before the fix tensor_meta=inner_spec.tensor_meta).
redistribute_local_tensor is handed tensor._local_tensor (the TP/EP-local shard), but current_spec/target_spec described the full global shape/stride. Passing a local tensor with a spec that claims the global shape is inconsistent — the fix builds a local_meta from tensor._local_tensor.shape/stride() instead. The added check_outer_spec hook in the test asserts exactly this invariant (spec.shape == local.shape).

2. Re-wrapping via DTensor.from_local relied on implicit shape inference (simple_fsdp.py:329 and simple_fsdp.py:367).
from_local infers the global size as local_size * num_shards, which assumes even sharding. For a TP-local dim of 5 split across 2 DP ranks (shards 3 and 2), inference yields 6 or 4, not 5. The PR's example is accurate. The fix derives the true local shape via compute_local_shape_and_global_offset(..., skip_offset=True) and the stride via compute_local_stride, then passes shape=/stride= explicitly.

The requires_grad=p.requires_grad addition (simple_fsdp.py:474-479) is a separate, clearly correct fix: nn.Parameter(...) defaults to requires_grad=True, so a frozen input parameter would silently become trainable.

Which backend is affected: partial_dtensor, spmd_types, or both?

Both — for the shared portions of the bug. Here's the breakdown by callsite:

Fixed callsite partial_dtensor spmd_types
_distribute_dtensor local_meta (:175-193) affected affected
sharded_dtensor DP re-wrap shape/stride (:329-335) affected affected
final output TP re-wrap shape/stride (:367-373) affected n/a (uses spmd.convert branch)
requires_grad preservation (:474-479) affected affected

Why both hit the first two:

  • _distribute_dtensor runs whenever the parameter is a DTensor (simple_fsdp.py:471-472). Under partial_dtensor, TP/EP params are already DTensors from parallelize_module/distribute_tensor. Under spmd_types, _prepare_spmd_parameter_for_fsdp (:113-114) wraps the annotated plain tensor into a DTensor.from_local(...) on non_dp_mesh before the isinstance(p, DTensor) check — so it takes the same branch. Both reach the buggy code.
  • The sharded_dtensor re-wrap at :329 sits before the backend branch in replicate_compute, so both backends execute it.

The only backend-specific fix is the final output re-wrap at :367: it lives in the else branch, reached only when non_dp_mesh_types is None, i.e. partial_dtensor. Under spmd_types the corresponding code takes the spmd.convert branch (:353-365) and returns a plain local tensor, so that specific line is inapplicable there — not because the metadata is correct under spmd_types, but because it doesn't rebuild a DTensor at that point.

Precondition: the bug only manifests when DP is composed with TP/EP (pure-DP params go through distribute_tensor, not _distribute_dtensor, and hit no inference gap). The numerically-wrong cases are the uneven ones (TP/EP-local dim not divisible by the DP shard degree), which the new test_uneven_* cases cover for both backends (test_uneven_fsdp_with_tp on partial_dtensor, test_uneven_fsdp_with_spmd_types on spmd_types, plus test_uneven_fsdp_with_ep_tp for composed EP+TP).

Summary

The problem is legitimate and affects both partial_dtensor and spmd_types for the shared metadata paths (init-time _distribute_dtensor and the DP re-wrap in replicate_compute); only the final TP/EP re-wrap fix is partial_dtensor-specific, because spmd_types takes a different (plain-local + spmd.convert) branch there. I was unable to execute the tests in this environment (Python execution is sandbox-restricted here), so this is a code-level verification; the added regression tests exercise both backends and the uneven/empty/composed cases.
• branch simplefsdp-fix

@pytorch-bot

pytorch-bot Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude partial_dtensor backend is being deprecated so I don't care about that at all. For spmd_types, provide a simple example to showcase where the bug happens, and how this PR would fix it, to help me

  1. understand the nature of the bug
  2. evaluate if this is the best fix possible

@claude

claude Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 5m 37s —— View job


spmd_types: a concrete example of the bug and the fix

Focusing only on spmd_types (ignoring partial_dtensor as requested).

Setup (smallest case that triggers it)

  • Mesh fsdp=2 x tp=2 (4 ranks), mode="fully_shard", shard_dim=0.
  • A Linear weight, logical shape (10, 8), sharded on dim 0 by TP.
  • Under spmd_types, each TP rank starts with a plain local tensor of shape (5, 8) annotated S(0)@tp.

Now FSDP shards that TP-local dim of 5 across 2 DP ranks -> 3 and 2. That uneven 3/2 split is the whole problem.

What happens today (the numerically-wrong path)

Both callsites below run for spmd_types (they sit before the backend-specific branch), so both matter.

1. Init time - _distribute_dtensor (simple_fsdp.py:175-193).
_prepare_spmd_parameter_for_fsdp first wraps the (5,8) local tensor into a DTensor on the TP mesh (simple_fsdp.py:113-114), so isinstance(p, DTensor) is true and _distribute_dtensor runs. It then calls redistribute_local_tensor(tensor._local_tensor, ...) - i.e. it hands over the (5,8) local shard - but the current_spec/target_spec carried inner_spec.tensor_meta, which describes the global (10,8) shape. So the spec claims shape 10 while the tensor it wraps is 5. In this Replicate->Shard direction the split is a local slice on the actual tensor, so the values survive - but it is an internally inconsistent spec, and it is exactly what the new check_outer_spec hook asserts against (spec.shape == local.shape). The fix builds local_meta from tensor._local_tensor.shape/stride() so the spec matches the tensor it redistributes.

2. Runtime - the DP re-wrap in replicate_compute (simple_fsdp.py:329-335). This is the one that produces wrong numbers.

At runtime x is the full-mesh DTensor, global (10,8), and x.to_local() is the doubly-sharded shard: (3,8) on dp_rank 0, (2,8) on dp_rank 1. The code re-wraps this as a 1-D DTensor on dp_mesh so FSDP can all-gather it. Before the fix:

sharded_dtensor = DTensor.from_local(sharded_local_tensor, dp_mesh, self.param_sharding)

from_local infers the global size as local_size * num_dp_shards:

dp_rank local shape inferred DP-global shape correct
0 (3,8) (6,8) (5,8)
1 (2,8) (4,8) (5,8)

The two ranks disagree (6 vs 4) and both are wrong (should be 5). That bogus logical shape flows into the FSDP all-gather (Shard(0)->Replicate), so the reconstructed TP-local weight has the wrong logical size - the compute, gradients, and optimizer state all inherit it.

The fix derives the true TP-local shape from the global metadata and passes it explicitly:

local_shape, _ = compute_local_shape_and_global_offset(
    x.shape, non_dp_mesh, non_dp_placements, skip_offset=True
)                                        # -> (5, 8), independent of dp_rank
local_stride = compute_local_stride(x.stride(), local_shape)
sharded_dtensor = DTensor.from_local(
    sharded_local_tensor, dp_mesh, self.param_sharding,
    shape=torch.Size(local_shape), stride=local_stride,
)

Now every DP rank agrees the DP-global (= TP-local) shape is (5,8), and the uneven 3/2 split is carried correctly by the Shard placement + offset. All-gather reconstructs (5,8) exactly.

(The final :367 re-wrap fix is inside the else branch that only partial_dtensor reaches - under spmd_types replicate_compute returns a plain local tensor via spmd.convert, so it's irrelevant here.)

Nature of the bug, in one line

DTensor.from_local reconstructs the global size as local * num_shards, which is only valid for even sharding. Composing DP on top of a TP/EP-local dim that isn't divisible by the DP degree is inherently uneven, so the inference is wrong. The fix stops relying on inference and states the shape/stride explicitly.

Is this the best fix?

I think it's the right shape of fix, with a couple of things worth confirming:

  • Correct and general. Passing shape=/stride= is the sanctioned escape hatch on from_local for precisely the uneven case, and this path is shared by both backends, so one fix covers both (matches the repo's "reuse over duplication" rule). Good.
  • stride is load-bearing, not decorative. For a transposed parameter x.stride() is non-contiguous; compute_local_stride projects that layout onto the local shape. Without it, an explicit shape alone would assume a contiguous stride and mislabel transposed params. This is covered by test_uneven_sharding_transposed_parameter[_compiled].
  • Recompute vs. stash. _distribute_dtensor already knew the TP-local shape at construction (inner_spec.tensor_meta.shape). The fix re-derives it at runtime via compute_local_shape_and_global_offset instead of stashing it on the parametrization. Recomputing is stateless and robust to any later re-wrap, so I'd keep it - just flagging it as the one place a reader might wonder "why not reuse what we already had."
  • Private-API reliance. compute_local_shape_and_global_offset, compute_local_stride, and from_local(shape=, stride=) are internal torch APIs. That's already the norm in this file (redistribute_local_tensor, _StridedShard, DTensorSpec) and acceptable in an experiment, but it's the fragile surface if torch changes. The standing TODO: DTensor should support this mesh collapsing operation (simple_fsdp.py:346) is the real long-term fix; this is a reasonable workaround until then.

Suggested extra assertion (optional): the check_outer_spec hook validates the init-time redistribute spec. Consider asserting the reconstructed sharded_dtensor.shape == local_shape (the TP-local shape) at runtime too, so a future regression in the from_local inference is caught directly rather than only via the downstream loss/grad comparison.

Net: legitimate bug, correct fix, well-targeted tests. Only real reservation is the private-API surface, which is pre-existing.


  • Read the changed code and diff
  • Build a concrete uneven-shard example
  • Trace where spmd_types goes wrong today
  • Show the fix and assess whether it's the best option

Note: I verified this at the code/diff level; Python execution is sandboxed in this environment, so I did not run the added tests.
• branch simplefsdp-fix

@@ -346,7 +365,11 @@
)
else:
output = DTensor.from_local(

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 branch is removed in #4419

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.

Would you prefer that I drop the changes to this branch from this PR?

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.

Rebased onto the latest main and dropped the changes to the branch removed by #4419.

# Preserve the input's logical dimension order when projecting its
# layout onto the TP/EP-local shape.
local_stride = compute_local_stride(x.stride(), local_shape)
sharded_dtensor = DTensor.from_local(

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.

@pianpwk this seems a legit bug for DP-uneven sharding, assuming TP / EP-even sharding.

for axis_name in non_dp_mesh.mesh_dim_names
)
return (
DTensor.from_local(tensor, non_dp_mesh, placements, run_check=False),

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 about TP / EP uneven sharding?

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.

The current spmd_types path still has a gap for uneven TP/EP sharding. The input here is already a local tensor, so the original global shape is unavailable. Supporting this would require broader changes to preserve and pass that metadata.

I also found that Module.parallelize() already rejects uneven TP/EP parameter sharding.

Would you prefer to address this separately, or extend this PR beyond the uneven-DP fix?

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.

Module.parallelize() already rejects uneven TP/EP parameter sharding

sounds good -- as long as it is rejected, it's good enough

Use TP/EP-local metadata for DP sharding and derive explicit DP rewrap shapes and strides from input DTensors. Preserve frozen parameter state.

Add 13 component regression cases on the current SPMD path, including uneven and empty DP shards, HSDP, EP+TP composition, transposed parameters, compilation, and meta initialization. Use contiguous reference gradient buffers for NCCL reduction.

@pianpwk pianpwk 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.

looks good, thank you for the fix

@tianyu-l
tianyu-l merged commit e4fdd2f into pytorch:main Sep 16, 2026
7 checks passed
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Sep 17, 2026
Second, separate sync: sync 84 landed and was verified on three
machines first, so if one of these 22 breaks something it is isolated
against a known-good baseline rather than tangled with 148 commits.

Audited as inert for ezpz before merging:
  - decoder_sharding.py renames RowParallelLinear ->
    AsyncRowParallelLinear and DistGEMMFeedForward -> a w13 check.
    ezpz has ZERO references to either (positive-controlled grep).
  - common/moe.py adds an OPTIONAL padding_mask_T to the router. ezpz
    configures the router rather than subclassing it and defines no
    forward that receives it. Unlike pytorch#4594's padding_mask, which is
    passed positionally to every block, this one defaults to None.
  - overrides/fused_swiglu.py is a Triton int64 cast fixing an
    infinite grad_norm on interleaved gate/up -- same w13 structure we
    just fixed -- but it lives in an override no ezpz config enables.
  - pytorch#4593 is graph_trainer/simple_fsdp, not our FSDP path.

Upstream touches 0 files under experiments/ezpz in this delta.
AlbedoWang added a commit to AlbedoWang/torchtitan that referenced this pull request Oct 7, 2026
… fix (pytorch#4593)

Cherry-pick of upstream e4fdd2f (simple_fsdp.py only). Pass the TP/EP-local
shape and stride explicitly when rewrapping on the DP mesh, so uneven DP
shards (e.g. DSv3 dense w1 1368 TP-local rows over dp_shard 16) no longer
infer a wrong global size. The fork still rewraps the gathered tensor on the
TP/EP mesh with DTensor.from_local, so that call also gets the input's global
shape and stride.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/graph-trainer Run GraphTrainer CI 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.

3 participants