Repository navigation
Fix SimpleFSDP metadata for uneven composed sharding - #4593
Conversation
|
Warning: Unknown label
Please add the new label to .github/pytorch-probot.yml |
|
Claude finished @tianyu-l's task in 4m 30s —— View job Verification: SimpleFSDP metadata for uneven composed sharding
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. 2. Re-wrapping via The Which backend is affected:
|
| 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_dtensorruns whenever the parameter is aDTensor(simple_fsdp.py:471-472). Underpartial_dtensor, TP/EP params are already DTensors fromparallelize_module/distribute_tensor. Underspmd_types,_prepare_spmd_parameter_for_fsdp(:113-114) wraps the annotated plain tensor into aDTensor.from_local(...)onnon_dp_meshbefore theisinstance(p, DTensor)check — so it takes the same branch. Both reach the buggy code.- The
sharded_dtensorre-wrap at:329sits before the backend branch inreplicate_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
|
|
|
@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
|
|
Claude finished @tianyu-l's task in 5m 37s —— View job
|
| 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 onfrom_localfor 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. strideis load-bearing, not decorative. For a transposed parameterx.stride()is non-contiguous;compute_local_strideprojects that layout onto the local shape. Without it, an explicitshapealone would assume a contiguous stride and mislabel transposed params. This is covered bytest_uneven_sharding_transposed_parameter[_compiled].- Recompute vs. stash.
_distribute_dtensoralready knew the TP-local shape at construction (inner_spec.tensor_meta.shape). The fix re-derives it at runtime viacompute_local_shape_and_global_offsetinstead 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, andfrom_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 standingTODO: 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_typesgoes 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( | |||
There was a problem hiding this comment.
Would you prefer that I drop the changes to this branch from this PR?
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
@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), |
There was a problem hiding this comment.
what about TP / EP uneven sharding?
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
e51201a to
31c456c
Compare
pianpwk
left a comment
There was a problem hiding this comment.
looks good, thank you for the fix
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.
… 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.
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:
requires_gradwhen recreating parameters, so frozen parameters remain frozen.Adds 14 component regression cases to the existing
TestSimpleFSDPclass, covering uneven and empty shards, FSDP/HSDP with TP, EP+TP composition, transposed parameters, compilation, meta initialization, thespmd_typesbackend, and frozen parameters. The shared numerical checks compare outputs, losses, accumulated gradients, parameter updates, and AdamW state against an unsharded reference.Validation: