Skip to content

support DTensor S(1) -> Partial("sum") - #191828

Closed
acisseJZhong wants to merge 1 commit into
pytorch:mainfrom
acisseJZhong:s2p
Closed

acisseJZhong wants to merge 1 commit into
pytorch:mainfrom
acisseJZhong:s2p

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add DTensor support for Shard(dim) -> Partial("sum") redistribution
using local zero-fill. This enables the S(1) -> P transition required
by TorchTitan's new MoE sharding
(pytorch/torchtitan#3996).

Testing

Added forward, backward, uneven-sharding, and graph-planner coverage.

python test/distributed/tensor/test_redistribute.py -k shard_to_partial

@pytorch-bot

pytorch-bot Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/191828

Note: Links to docs will display an error until the docs builds have been completed.

❌ 1 Cancelled Job

As of commit 383f0b6 with merge base d2f6cf4 (image):

CANCELLED JOB - The following job was cancelled. Please retry:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added ciflow/dtensor Run DTensor specific tests ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (dtensor) release notes category labels Aug 1, 2026
@acisseJZhong
acisseJZhong marked this pull request as ready for review August 1, 2026 06:15
@acisseJZhong
acisseJZhong requested a review from weifengpy as a code owner August 1, 2026 06:15
@tianyu-l
tianyu-l requested a review from pianpwk August 1, 2026 06:18
@weifengpy

weifengpy commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

I support the motivation. From DTensor perspective, is your intention to gate Shard-to-Partial to avoid changing exsting callsite? current this PR changes _StridedShard behavior. Repro as below

here is my prompt "code review code-reivew/pytorch 4356b41 . identify if it breaks existing callsite because the commit allowed Shard to Partial redistribution"

_StridedShard is the exercised path for FSDP2 + TP and FSDP2 + EP when they shard on the same dim

import os
import torch
import torch.distributed as dist
from torch.distributed.device_mesh import init_device_mesh
from torch.distributed.tensor import distribute_tensor, Partial, Shard
from torch.distributed.tensor.placement_types import _StridedShard
torch.cuda.set_device(int(os.environ["LOCAL_RANK"]))
dist.init_process_group("nccl")
mesh = init_device_mesh("cuda", (2, 2))
ss = _StridedShard(0, split_factor=2)
source = distribute_tensor(torch.arange(8, device="cuda"), mesh, (ss, Shard(0)))
result = source.redistribute(mesh, (ss, Partial("sum")))

@acisseJZhong

acisseJZhong commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor Author

is your intention to gate Shard-to-Partial to avoid changing exsting callsite?

My intention was to avoid the planner exposes S -> P, the planer considers S -> P only when it is the final requested destination.

regarding to the breakage: instead of (SS(0, split_factor=2), Shard(0)) -> (SS(0, split_factor=2), Partial("sum")), I think the correct behavior should be (SS(0, split_factor=2), Shard(0)) -> (Shard(0), Partial('sum'))?

However I checked that before this PR, (SS(0), S(0)) ->(SS(0), R) will raise error.
https://github.com/acisseJZhong/pytorch/blob/d2f6cf4c3c76f6043523f442550d2c8e91fa1d9f/torch/distributed/tensor/_redistribute.py#L1410, we should also raise error if we ever have (SS(0), S(0)) ->(SS(0), P) rather than silently breaking numerics?

Updated the code with the added check torch._check(local_tensor.size(self.dim) == local_shard_size) during zero padding, so it will explicitly fail, similarly to how we fail with (SS(0), S(0)) ->(SS(0), R).

@wconstab

wconstab commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Remembering the context..

X->Partial("sum") can be numerically dangerous if you do it by scaling, or can be SPMD-dangerous if you do it by padding (different ranks have different paddings, which means your graphs are non-spmd).

IIUC your PR is taking the latter approach, padding different sized chunks per rank as prefix/suffix.

I would prefer not to support this in the current form, as we want DTensor to produce SPMD code. I am not familiar with the current MoE sharding situation though. A few thoughts

  • if we're going to lift the ->Partial ban, we should probably lift it for all source placements to avoid the API being confusing. And I suspect there could be further implications to the cost planner etc.
  • I don't know if we can find a way to do the numerically safe zero pad trick in a compiler-friendly way. I guess using torch.cond is a possibility, although it adds other complexity. What about starting with a zeros tensor of the fixed/global shape on every rank, then using index_add to write the local shard data into the correct offset? This needs the offset to be a device-tensor though, i think

@pianpwk

pianpwk commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

X->Partial("sum") can be numerically dangerous if you do it by scaling, or can be SPMD-dangerous if you do it by padding (different ranks have different paddings, which means your graphs are non-spmd).

IIUC your PR is taking the latter approach, padding different sized chunks per rank as prefix/suffix.

fwiw, spmd_types did decide to accomodate the padding version, having a varying_to_partial method that takes rank as argument: https://github.com/meta-pytorch/spmd_types/blob/60705234a3ebb7a2ddd423cb3259f80985d270b2/spmd_types/_local.py#L980-L998

though it doesn't support uneven S yet

@wconstab

wconstab commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Ok, if we are doing the padding approach for spmd_types we may as well do it here too. It's a separate question of being spmd-friendly for graphs. I wonder how much we care about that e.g for compile-on-one-rank compatibility- cc @aorenste

I also wonder if it is inconsistent to prevent the planner from doing s->p if we claim it is a supported operation. I think we should at least have a clear story here.

@pianpwk

pianpwk commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Ok, if we are doing the padding approach for spmd_types we may as well do it here too. It's a separate question of being spmd-friendly for graphs. I wonder how much we care about that e.g for compile-on-one-rank compatibility- cc @aorenste

I vaguely remember one of the approaches to CooR spmd-ness was to hide non-spmd-ness behind custom ops, e.g.

@torch.library.register_fake("_dtensor::shard_dim_alltoall")
def _shard_dim_alltoall_meta(
input, gather_dim, shard_dim, group_name: GroupName | ProcessGroup
):
if isinstance(group_name, str):
# pyrefly: ignore[bad-argument-type] # pyrefly bug
group_name = _resolve_process_group(group_name)
group_size = group_name.size()
stacked_list = [torch.empty_like(input) for _ in range(group_size)]
group_rank = get_group_rank(group_name, get_rank())
cat_tensor = torch.cat(stacked_list, dim=gather_dim)
# pyrefly: ignore [unsupported-operation]
chunk_size = cat_tensor.size(shard_dim) // group_size
chunk = torch.narrow(cat_tensor, shard_dim, group_rank * chunk_size, chunk_size)
return chunk.contiguous()

@wconstab just wondering how that works for your concerns? I imagine it delegates more work to lowering, but could also be easier to catch?

@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@wconstab I applied your suggestion to change to the fixed/global -> index_add approach, would compiler compile same graph with this approach?

if it is inconsistent to prevent the planner from doing s->p if we claim it is a supported operation

I initially added s->p into the planner and it broke a bunch of tests as it changes the planner's decision? Therefore I banned it from the planner as I don't want the planner to do s->p(kind of meaningless?). Do you have a better idea in mind?

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

I think this is OK. But we should document our reasoning at least (the design, in code comment block), and make sure our API docs are clear too.

The important caveat is: “valid explicit redistribution” and “eligible implicit planner move” are different sets. The reason we prefer this rather than having the sets be equal is partly due to a weakness in our cost model- it models comm cost only, not memory usage or computation (copy) time. If we put S->P as zero cost, we'd over-prefer it in the planner, and that would be worse than skipping it as an option.

For completeness sake, do we have an argument for supporting only explicit S->P rather than also R->P?

We should also check the reasoning between the transform-planner and the strategy-planner.
transform-planner implements S->P with zero cost now, while strategy planner has inf cost. Is this inconsistency a problem? We could argue that as long as the transform planner DOES implement every finite cost transition in the strategy planner, we're good. A more extreme guarantee would be, they both follow the same paths always with the same costs.

output_shape[self.dim] = logical_dim_size
output = local_tensor.new_zeros(output_shape)
offset = torch.scalar_tensor(
local_offset, dtype=torch.int64, device=local_tensor.device

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.

Just checking, is local_offset a device tensor or a host scalar? I still think structurally this index_add framing is cleaner as it produces structurally identical graphs, but I'm not sure if it literally solves the rank-identical graphs problem without validating whether we bake per-rank constants (Scalars) into the graph. I'd be curious to know what happens, but I wouldn't block this PR over it. cc @IvanKobzarev @aorenste

@acisseJZhong acisseJZhong Aug 9, 2026 •

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.

local_offset is host-side shape metadata represented as an int or SymInt

@acisseJZhong

Copy link
Copy Markdown
Contributor Author

Added doc string to clarify that every transition selected by the strategy planner must be executable by the transform planner, while the transform planner may support additional transitions used only by explicit redistribution.

For completeness sake, do we have an argument for supporting only explicit S->P rather than also R->P?

I assume user would never want to explicitly redistribute R->P? Also codex told me that `Replicate -> Partial("sum") divides by the mesh size and may introduce floating-point error, so keep this lossy conversion out of the public API.

@acisseJZhong
acisseJZhong force-pushed the s2p branch 2 times, most recently from 9bc8c99 to 4dee73e Compare August 9, 2026 07:33
@tianyu-l

tianyu-l commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

I assume user would never want to explicitly redistribute R->P? Also codex told me that `Replicate -> Partial("sum") divides by the mesh size and may introduce floating-point error, so keep this lossy conversion out of the public API.

The proper way probably should be only keeping value on rank 0, i.e. Owned-style Partial(sum).

With that I don't see the value of putting S->P as an intermediate step where either S is not original source or P is not final destination.

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

lgtm. thanks for making those changes!

Shard -> Partial("sum") is intentionally absent. Although explicit
redistribution supports it, the conversion materializes a logical-shape
local tensor. The communication-only strategy cost model cannot represent
that memory and copy cost, so implicit planning must not select 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.

nit: logical-shape -> global-shape

must not select it -> we avoid selecting it based only on comm cost without considering other costs

@acisseJZhong

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 Aug 10, 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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: inductor / unit-test / inductor-cpu-test / test (inductor_amx, 1, 2, mt-l-x86iamx-8-64)

Details for Dev Infra team Raised by workflow job

@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 1 checks: inductor / unit-test / inductor-cpu-test / test (inductor_amx, 1, 2, mt-l-x86iamx-8-64)

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

ankitbhrdwj pushed a commit to ankitbhrdwj/pytorch that referenced this pull request Aug 12, 2026
## Summary

  Add DTensor support for Shard(dim) -> Partial("sum") redistribution
  using local zero-fill. This enables the S(1) -> P transition required
  by TorchTitan's new MoE sharding
  (pytorch/torchtitan#3996).

  ## Testing

  Added forward, backward, uneven-sharding, and graph-planner coverage.
```
python test/distributed/tensor/test_redistribute.py -k shard_to_partial
```

Pull Request resolved: pytorch#191828
Approved by: https://github.com/wconstab
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants