Skip to content

[DTensor][BE] redistribute to replicate in from_local backward for partial target type - #173153

Closed
acisseJZhong wants to merge 7 commits into
pytorch:mainfrom
acisseJZhong:from_local_backward
Closed

acisseJZhong wants to merge 7 commits into
pytorch:mainfrom
acisseJZhong:from_local_backward

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Jan 23, 2026 •

Copy link
Copy Markdown
Contributor

follow up per this comment

Motivation: If in from_local forward placement is Partial, user could get either Partial or Replicate gradients depending on what the incoming gradient placement is(if incoming gradient is Replicate, we keep Replicate; if incoming gradient is Partial, we keep Partial). This is not ideal as it's not 1-1 mapping and introduces ambiguity.

Change in this PR: if incoming gradient is Partial, we redistribute the Partial to Replicate. As a result, users will always get Replicate gradient when forward is Partial.

This behavior aligned with our future plan to add Reduced/Unreduced type: If forward is partial, backward is Replicate(now)/Reduced(later).

Also added unit test for from_local backward to cover the 5 possible cases:

from_local forward grad_output grad_input
Shard Shard Shard
Replicate Replicate Replicate
Replicate Partial Replicate
Partial Replicate Replicate(now) / Reduced(later)
Partial Partial Replicate(now) / Reduced(later)
python3 test/distributed/tensor/test_dtensor.py -k test_from_local_backward

@pytorch-bot

pytorch-bot Bot commented Jan 23, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure, 3 Unrelated Failures

As of commit 949026e with merge base 6f0dd26 (image):

NEW FAILURE - The following job has failed:

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

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

Comment thread torch/distributed/tensor/_api.py Outdated
# for backward replicate -> partial, we do replicate -> replicate / skip transformation
# TODO: for backward partial -> partial, right now we keep it unchanged,
# but this might need revisit
# if target gradient placement is partial, we always redistribute to replicate, this means

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.

  1. Can the comment clarify this in-terms of gradient mapping guarantee that this function now provides in the backward? (Shard-Shard, Replicate-Replicate, Partial-Replicate) - maybe even as a table for clarity

  2. It'll be useful to highlight that this particular example will be BC breaking for the case of

OLD: Partial(fwd) - Partial (grad_out) - Partial (grad_in)
NEW: Partial(fwd) - Partial (grad_out) - Replicate (grad_in),

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.

good idea, added a table to clarity in the doc string

.. note:: When ``run_check=False``, it is the user's responsibility to ensure the
local tensor passed in is correct across ranks (i.e. the tensor is sharded for
the ``Shard(dim)`` placement or replicated for the ``Replicate()`` placement).
If not, the behavior of the created DTensor is undefined.

.. note:: ``from_local`` is differentiable, the `requires_grad` of the created
`DTensor` object will depend on if `local_tensor` requires_grad or not.

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 it possible to have some tests for this?

@acisseJZhong acisseJZhong Jan 23, 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.

sure, let me add tests for each case! although according to yesterday's discussion we are unlikely to hit Partial(fwd) - Partial(grad_output) case?

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 test that grad_output correctly gets redistributed to Replicate in this case

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

sgtm, please address remaining comments.

Comment thread test/distributed/tensor/test_dtensor.py Outdated
# Gradient should flow back without redistribution
self.assertEqual(comm_mode.get_total_counts(), 0)

# Test 2: Replicate -> Replicate (no redistribution needed 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.

add a test case where forward is Replicate, backward is Partial -> Replicate

Comment thread test/distributed/tensor/test_dtensor.py Outdated
# Gradient should flow back without redistribution
self.assertEqual(comm_mode.get_total_counts(), 0)

# Test 3: Partial -> Replicate (gradient normalized to 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.

add a test case where forward is Partial, backward is Replicate -> keep Replicate

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.

oh right! now I finally understand the full picture. The 5 test cases should cover all the possibilities.

@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@pytorchmergebot merge -i

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Jan 24, 2026
@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 / unit-test / inductor-halide-test / test (inductor-halide, 1, 1, linux.12xlarge)

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

@wconstab

Copy link
Copy Markdown
Contributor

Lgtm, but for posterity can you add more detail to the pr desc about the motivation and the type of ambiguous situation this helps avoid?

@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@wconstab updated! let me know if you still feel sth missing

@ezyang

ezyang commented Jan 27, 2026

Copy link
Copy Markdown
Contributor

I hope we've tested six against this

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
pytorchmergebot pushed a commit that referenced this pull request Jan 29, 2026
…t` type (#173454)

Fixes #172932, see comment [here](#172932 (comment))

**Problem**: `DTensor.to_local()` followed by `DTensor.from_local()` on `Partial` produces different gradients than pure DTensor operations.

**Root cause:** during from_local backward, we always redistribute gradients to Replicate when forward is Partial. However, this information is [not saved](https://github.com/pytorch/pytorch/blob/635ff65bc517c175360a0a85502488ee341059c1/torch/distributed/tensor/_api.py#L91) in to_local backward, where it take the `Replicated `tensor but still annotate as `Partial`.

**Fix:** Similarly to the fix for `from_local` in #173153, we propose this fix to provide a default `Replicate` gradient for `Partial` input(as we always map forward partial to backward replicate in `from_local`) when `grad_placements` is not provided. However, this fix does not guarantee correctness and might break BC. To guarantee correctness, users are  **strongly recommended** to pass in `grad_placement` type into `to_local`.

Pull Request resolved: #173454
Approved by: https://github.com/wconstab
kapilsh pushed a commit to kapilsh/pytorch that referenced this pull request Feb 2, 2026
…t` type (pytorch#173454)

Fixes pytorch#172932, see comment [here](pytorch#172932 (comment))

**Problem**: `DTensor.to_local()` followed by `DTensor.from_local()` on `Partial` produces different gradients than pure DTensor operations.

**Root cause:** during from_local backward, we always redistribute gradients to Replicate when forward is Partial. However, this information is [not saved](https://github.com/pytorch/pytorch/blob/635ff65bc517c175360a0a85502488ee341059c1/torch/distributed/tensor/_api.py#L91) in to_local backward, where it take the `Replicated `tensor but still annotate as `Partial`.

**Fix:** Similarly to the fix for `from_local` in pytorch#173153, we propose this fix to provide a default `Replicate` gradient for `Partial` input(as we always map forward partial to backward replicate in `from_local`) when `grad_placements` is not provided. However, this fix does not guarantee correctness and might break BC. To guarantee correctness, users are  **strongly recommended** to pass in `grad_placement` type into `to_local`.

Pull Request resolved: pytorch#173454
Approved by: https://github.com/wconstab
pytorchmergebot pushed a commit that referenced this pull request Feb 28, 2026
## Problem
While fixing a MoE numerics bug (pytorch/torchtitan#2416), we discovered the root cause was a lack of strict gradient placement control/strict typing in `from_local`. Specifically, `from_local(Replicate)` in `ColwiseLinear` (used by the shared expert) produced correct forward behavior, but the backward pass performed an unnecessary all-reduce. The desired backward gradient placement was `Partial`, not `Replicate`.

## Solution
To address this, we add a `grad_placements` keyword argument to `from_local`, mirroring the existing `grad_placements` support in `to_local`. When `grad_placements` is `None` (the default), the backward gradient placement follows the original guarantees established in #173153. When specified, it overrides the default and uses the user-provided gradient placements directly.

In the longer term, we hope to address this kind of issues through spmd_types as a type checker.

## Test
```
python3 test/distributed/tensor/test_dtensor.py -k test_from_local_grad_placements
```
Pull Request resolved: #175867
Approved by: https://github.com/wconstab, https://github.com/tianyu-l
EmanueleCoradin pushed a commit to EmanueleCoradin/pytorch that referenced this pull request Mar 30, 2026
## Problem
While fixing a MoE numerics bug (pytorch/torchtitan#2416), we discovered the root cause was a lack of strict gradient placement control/strict typing in `from_local`. Specifically, `from_local(Replicate)` in `ColwiseLinear` (used by the shared expert) produced correct forward behavior, but the backward pass performed an unnecessary all-reduce. The desired backward gradient placement was `Partial`, not `Replicate`.

## Solution
To address this, we add a `grad_placements` keyword argument to `from_local`, mirroring the existing `grad_placements` support in `to_local`. When `grad_placements` is `None` (the default), the backward gradient placement follows the original guarantees established in pytorch#173153. When specified, it overrides the default and uses the user-provided gradient placements directly.

In the longer term, we hope to address this kind of issues through spmd_types as a type checker.

## Test
```
python3 test/distributed/tensor/test_dtensor.py -k test_from_local_grad_placements
```
Pull Request resolved: pytorch#175867
Approved by: https://github.com/wconstab, 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.

6 participants