Skip to content

[DTensor][BE] remove is_backward from redistribute_local_tensor - #170147

Closed
acisseJZhong wants to merge 4 commits into
pytorch:mainfrom
acisseJZhong:redistribute_local_tensor
Closed

acisseJZhong wants to merge 4 commits into
pytorch:mainfrom
acisseJZhong:redistribute_local_tensor

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Dec 11, 2025 •

Copy link
Copy Markdown
Contributor
  1. remove the is_backward parameter from redistribute_local_tensor, instead, do the backward conversion before we call redistribute_local_tensor.

Specifically, during backward, if we want to redistribute from

shard -> partial: replace with shard -> replicated
replicate -> partial: replace with replicate -> replicate(no-op)
  1. Also fix a bug when redistribute forward is partial -> partial, during backward we annotate it the output partial to replicate. Added a unit test to catch this bug.

before this PR

AssertionError: Object comparison failed: Replicate() != Partial(sum)

after this PR, the test will pass.

Test plan:

python3 test/distributed/tensor/test_redistribute.py

@pytorch-bot

pytorch-bot Bot commented Dec 11, 2025 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (2 Unrelated Failures)

As of commit a30d76f with merge base dd1f0f8 (image):

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

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

@linux-foundation-easycla

linux-foundation-easycla Bot commented Dec 11, 2025 •

Copy link
Copy Markdown

CLA Signed

The committers listed above are authorized under a signed CLA.

@acisseJZhong acisseJZhong changed the title [DTensor][BE} remove backward from redistribute_local_tensor [DTensor][BE] remove backward from redistribute_local_tensor Dec 11, 2025
@acisseJZhong acisseJZhong changed the title [DTensor][BE] remove backward from redistribute_local_tensor [DTensor][BE] remove is_backward from redistribute_local_tensor Dec 11, 2025
# for backward replicate -> partial, we skip the transformation
normalized_placements: list[Placement] = []
for current, target in zip(current_spec.placements, previous_spec.placements):
if (current.is_shard() or current.is_replicate()) and target.is_partial():

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 may not fully reproduces the old behavior, as is_shard, is_replicate, is_partial may not be completely covering all cases (although it may sound strange).

I suggest we just do exactly the same as before, to be safe for now.

@acisseJZhong acisseJZhong Dec 12, 2025 •

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.

is_shard, is_replicate, is_partial may not be completely covering all cases

got it, but I think this condition current.is_shard() or current.is_replicate() is strictly equal to the old conditions where is_backward is used?


# for backward shard -> partial, we just do shard -> replicate
# for backward replicate -> partial, we skip the transformation
normalized_placements: list[Placement] = []

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.

we should remove normalized_placements creation below output = redistribute_local_tensor

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 two normalized_placements have slight differences. The second creation of normalized_placements will convert partial -> partial to partial -> replicate, which we didn't do in the first one.

Comment thread torch/distributed/tensor/_api.py Outdated
Comment on lines +222 to +228
for current, target in zip(current_spec.placements, previous_placement):
if (
current.is_shard() or current.is_replicate()
) and target.is_partial():
normalized_placements.append(Replicate())
else:
normalized_placements.append(target)

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.

@tianyu-l , do we still need this part if we decide to remove is_backward? We can remove those tests that check for Partial->Replicate in backward.

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.

@zpcore
Actually I'm not sure:

In the other change (redistribute backward), it's OK to have either Partial or Replicate from correctness perspective, because we are always in DTensor region, but here we are transitioning between DTensor and plain Tensor.

Here, if we do DTensor.from_local(Partial), the gradient here could be Partial or Replicate, depending on the gradout placement. This sounds problematic as users have no idea if they need to perform reduction or not.

What's worse, it seems they don't even know if the reduce_op of Partial grad is the same as the reduce_op of input (although most of the time it should be the same "sum").

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.

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.

In case of redistribute call from _FromTorchTensor::backward

  1. For BC, I believe we should keep it in Replicate() for is_backward=True

  2. For correctness, I believe we should always redistribute grad to Replicate() when tensor is Partial() in from_local

This is mainly for two reasons:

  • If we accept Partial() grad placement, we need to introduce an all_reduce later in the backward appropriately (unless there was appropriate differentiable introduced or the input parameter is also trivially Partial()) - currently there is no such check/feature
  • Although the incoming gradient is Partial(), there isn't a guarantee that the Partial() resulting from a backward DTensor operation that is a strict transpose of the local tensor operations (Ex: case of 'pseudo-Partial')

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.

For BC, I believe we should keep it in Replicate() for is_backward=True

Before this PR, if original tensor is Partial, grad is Partial -> Partial grad will be kept. What you said is not always BC.

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.

Before this PR, if original tensor is Partial, grad is Partial -> Partial grad will be kept. What you said is not always BC

I was referring to the case where we were effectively skipping redistribute if it was already in Replicate() (with is_backwards=True)

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.

If we accept Partial() grad placement, we need to introduce an all_reduce later in the backward appropriately (unless there was appropriate differentiable introduced or the input parameter is also trivially Partial()) - currently there is no such check/feature

This feel a bit "trying to decide for user". If I were a user, I would expect a differentiable from_local call to return grad with the same placement as input -- similar to to_local. Plus, I would like to have a chance to do some optimization (specifying what grad placement should be).

Although the incoming gradient is Partial(), there isn't a guarantee that the Partial() resulting from a backward DTensor operation that is a strict transpose of the local tensor operations (Ex: case of 'pseudo-Partial')

sorry didn't understand this argument.

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 is tricky...

from first principles, if a user gave me a plain tensor and said make a DTensor with Partial(sum) placement, then it's very tempting to say that we should always return back a grad in Partial(sum) placement. Optionally, the user can also pass a kwarg saying grad_in_placement= and we can respect that. Inside DTensor, we can always convert any partial (norm, max, etc) back to replicate, and then scale it if needed to generate a Partial Sum.

i also understand that adhering to this principle is likely to introduce extra comms. If we start with a R grad, it is a bummer to scale it and then allreduce it again.

finally, we have a BC issue, where currently we do this optimization by default, and changing it could break existing code.

note: i haven't even finished reading this PR yet.. so take this with a grain of salt

but, could we just add a new kwarg to DTensor.from_local grad_in_placements=Replicate() which defaults to replicate, but can be overridden? We can then document this optimization and the reasoning behind defaulting it to R in the docstring for the method.

@vishal9-team vishal9-team Dec 13, 2025 •

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 feel a bit "trying to decide for user"

  1. Can you give an example of when user would like to keep the [out, out.grad] in [Partial(), Partial()]? Intuitively, it seems to me like when out is Partial(), out.grad will be Replicate() for most optimized backward implementations

  2. For example: Consider the Megatron TP use case below - specifically the case where local_map calculates the attention block and returns Z1/Z2 - DTensor Z with placement Partial(). In the backward, DTensor Z could theoretically postpone it's autograd all_reduce (g()) for Z.grad and have Partial() placements for the gradients. In this case, allowing Partial() gradients to flow through the local_map backwards without all_reduce would be wrong

megatron_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.

see my other comments #170147 (comment). I'm not advocating for any of them, but we should have a documented default / default mapping function. Right now it's not well documented and confusing to users.

@tianyu-l tianyu-l added ciflow/trunk Trigger trunk jobs on your pull request release notes: distributed (dtensor) release notes category labels Dec 13, 2025
Comment thread torch/distributed/tensor/_api.py Outdated
Comment on lines +211 to +217
# skip the replicate to partial transformation when we are in backward pass
# In this case we keep the grad as replicate, this is because we don't
# want to convert the replicated gradients back to partial, although
# that's logically conform with the same layout, converting the gradients
# back to partial is actually useless as you would have to do reduce later
# which would be more expensive than keeping it replicate! For this reason,
# we keep the replicate grad here.

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 we should put this comment to redistribute backward.

Here the behavior is not only about efficiency but can also have correctness issue, as this is transitioning between plain Tensor and DTensor and there are multiple possibilities if we from_local(Partial) --> the gradient can be either Partial / Replicate and then lose DTensor metadata, which is clearly problematic.

I would suggest we add comment here and merge this PR, and then have a plan to fix it. cc @vishal9-team

For correctness, we can go with any predictable behavior and document it. We don't have the variance tracking headache because it's always DTensor.
For flexibility, we can also provide grad_placement for users to decide what to do with the grad_output placement before exiting backward.

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 gradient can be either Partial / Replicate and then lose DTensor metadata, which is clearly problematic.

to clarify: during from_local backward, input gradient is partial and we keep output gradient as partial, only in this case it's problematic? (as we lose the reduce op info). And this is the case even before this PR.

For correctness we should convert output grad to replicate even when input gradient is partial? And this will be different from what we did in redistribute backward.

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.

The biggest problem is ambiguity. As a user, you call from_local(placement = Partial), but you don't even know what your gradient would be, Partial or Replicate.
Personally I'm not sure which one should be the default, but there should be one. There could be tradeoffs:

  • always Partial won't be efficient in some cases, as DTensor may need to do Replicate -> Partial conversion and then user may need to reduce it again
  • always Replicate may be not efficient in other cases, where user just needs Partial, but DTensor would do Partial -> Replicate

Apart from ambiguity and the potential correctness problem, the above two points are the same argument we use for redistribute backward (for efficiency). But over there we don't need to force into one choice, because the placement info would flow together with the gradient back to user.

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.

if we keep it always Partial, wouldn't it lose the reduce op info after from_local backward finishes? (sry if I misunderstood anything above).

For BC, I added a comment right now without changing anything(still keep output gradient partial if input gradient is partial)

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.

See my other comment on another section of code- I think adding a kwarg to control this would be best. That way the kwarg's default value along with do string clearly indicates to users what to expect, but they can also override if they want. Unlike my previous comment, I wonder if grad_in_placements is not the only kwarg we need.

  1. grad_in_placements: default to none, means we follow in_placements, if a value is provided we use it
  2. optimize_grad_in_partial=true: if true, when grad-in-placement is unspecified, if in-placement is partial, we return grad-in-placement replicate for the following reasons ...
    Wdyt?

@acisseJZhong acisseJZhong Dec 14, 2025 •

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.

that makes sense. Shall we do that in the next PR, as it will introduced new code changes?

I think the main decision to make is that for 2, when grad_in_placement is unspecified, if in-placement is partial, shall we keep it as partial or replicate?

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 is what people suggested for redistribtue.backward, which could also work for from_local backward:

we can write a custom autograd function if we want to control the backward behavior? Specifically, we may want to do some of the following

  • Unconstrained: keep the gradient placements unchanged;
  • Specific grad_placements: similar to to_local;
  • p3 = grad_placement_fn(p2), where p2 is the current placements of the gradients.

@acisseJZhong acisseJZhong Dec 14, 2025 •

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.

yup let me put it in the next PR, to properly add this desired grad_placements argument to both from_local and redistribute backward, also as what Will suggested.

partial_tensor = distribute_tensor(partial_local, device_mesh, partial_spec)

with comm_mode:
reshard_partial_tensor = partial_tensor.redistribute(

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, so the bug was that Redistribute.backward was doing 'if the target is P, pretend it's R' and our no-op turned into an op?

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.

yes the bug is that during redistribute backward, we were doing 'if target is P, annotate it to R, without any redistribute_local_tensor happening`.

Comment thread torch/distributed/tensor/_api.py Outdated
# for backward shard -> partial, we just do shard -> replicate
# for backward replicate -> partial, we skip the transformation
normalized_placements: list[Placement] = []
for current, target in zip(current_spec.placements, previous_placement):

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: would it be clearer to rename previous_placement to forward_input_placement?

@acisseJZhong
acisseJZhong force-pushed the redistribute_local_tensor branch from 52a3aa7 to 2ae1c4f Compare December 14, 2025 00:36

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

seems you need to sign CLA

@acisseJZhong

Copy link
Copy Markdown
Contributor Author

not sure why the CLA check is failing, I've signed it multiple times 😢
image

@acisseJZhong

Copy link
Copy Markdown
Contributor Author

/easycla

@acisseJZhong
acisseJZhong force-pushed the redistribute_local_tensor branch from 2ae1c4f to a6ec4f1 Compare December 15, 2025 01:11
@acisseJZhong
acisseJZhong force-pushed the redistribute_local_tensor branch from a6ec4f1 to f7bf727 Compare December 15, 2025 01:24
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@pytorchmergebot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 0 checks:

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: HTTP Error 502: Bad Gateway

Details for Dev Infra team Raised by workflow job

@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@pytorchmergebot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 2 checks: inductor / unit-test / inductor-pallas-cpu-test / test (inductor-pallas-cpu, 1, 1, linux.12xlarge), inductor / inductor-test / test (inductor_torchbench, 2, 2, linux.g5.4xlarge.nvidia.gpu)

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

vishalgoyal316 pushed a commit to vishalgoyal316/pytorch that referenced this pull request Dec 17, 2025
…rch#170147)

1. remove the `is_backward` parameter from `redistribute_local_tensor`, instead, do the backward conversion before we call `redistribute_local_tensor`.

Specifically, during backward, if we want to redistribute from
```
shard -> partial: replace with shard -> replicated
replicate -> partial: replace with replicate -> replicate(no-op)
```

2. Also fix a bug when redistribute forward is `partial -> partial`, during backward we annotate it the output `partial` to `replicate`. Added a unit test to catch this bug.

before this PR
```
AssertionError: Object comparison failed: Replicate() != Partial(sum)
```
after this PR, the test will pass.

## Test plan:

```
python3 test/distributed/tensor/test_redistribute.py
```
Pull Request resolved: pytorch#170147
Approved by: https://github.com/tianyu-l
krastogi-in pushed a commit to krastogi-in/pytorch that referenced this pull request Jan 9, 2026
…rch#170147)

1. remove the `is_backward` parameter from `redistribute_local_tensor`, instead, do the backward conversion before we call `redistribute_local_tensor`.

Specifically, during backward, if we want to redistribute from
```
shard -> partial: replace with shard -> replicated
replicate -> partial: replace with replicate -> replicate(no-op)
```

2. Also fix a bug when redistribute forward is `partial -> partial`, during backward we annotate it the output `partial` to `replicate`. Added a unit test to catch this bug.

before this PR
```
AssertionError: Object comparison failed: Replicate() != Partial(sum)
```
after this PR, the test will pass.

## Test plan:

```
python3 test/distributed/tensor/test_redistribute.py
```
Pull Request resolved: pytorch#170147
Approved by: https://github.com/tianyu-l
pytorchmergebot pushed a commit that referenced this pull request Jan 24, 2026
…rtial target type (#173153)

follow up per this [comment](#170147 (comment))

If incoming gradient is partial and target gradient placement is partial, we now redistribute partial -> duplicate(originally we let partial to propagate through). Otherwise, when user specified target gradient to be partial, they could get either partial or replicate gradient, which introduces ambiguity.

This also aligned with our future plan to add reduced/unreduced type: If forward is partial, backward is replicate/reduced.

Also added unit test for `from_local` backward:
```
python3 test/distributed/tensor/test_dtensor.py -k test_from_local_backward
```
Pull Request resolved: #173153
Approved by: https://github.com/tianyu-l
riccardofelluga pushed a commit to riccardofelluga/pytorch that referenced this pull request Jan 27, 2026
…rtial target type (pytorch#173153)

follow up per this [comment](pytorch#170147 (comment))

If incoming gradient is partial and target gradient placement is partial, we now redistribute partial -> duplicate(originally we let partial to propagate through). Otherwise, when user specified target gradient to be partial, they could get either partial or replicate gradient, which introduces ambiguity.

This also aligned with our future plan to add reduced/unreduced type: If forward is partial, backward is replicate/reduced.

Also added unit test for `from_local` backward:
```
python3 test/distributed/tensor/test_dtensor.py -k test_from_local_backward
```
Pull Request resolved: pytorch#173153
Approved by: https://github.com/tianyu-l
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor 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.

7 participants