Skip to content

[DTensor] Add Dijkstra-based single-dim strategy search - #169438

Closed
wconstab wants to merge 16 commits into
gh/wconstab/465/basefrom
gh/wconstab/465/head
Closed

wconstab wants to merge 16 commits into
gh/wconstab/465/basefrom
gh/wconstab/465/head

Conversation

@wconstab

@wconstab wconstab commented Dec 3, 2025 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Add _dijkstra_expand_single_dim_strategy_to_mesh, a priority-queue search
over input placement states that finds the lowest-cost sharding for an op
without enumerating all S^N strategy combinations (S = single-dim strategies,
N = mesh dimensions). The search uses _PreparedSingleDimStrategy (from the
previous commit) to materialize single-dim rules and try_propagate() to
test whether a candidate state matches on every mesh dimension.

Each search state is a tuple of per-input placement tuples. Neighbors are
generated by changing one placement on one mesh dimension for one input,
using _get_neighbor_placements which encodes DTensor redistribute transition
rules (Replicate <-> Shard, Partial -> Replicate/Shard). Cost computation
uses _compute_redistribute_cost which calls _compute_placement_transition_cost
directly per mesh dimension, avoiding DTensorSpec construction and
_gen_transform_infos planning overhead.

Returns None for _StridedShard inputs, signaling the caller to fall back to
full expansion.

Authored with Claude.

very WIP

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Dec 3, 2025 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure, 3 Unrelated Failures

As of commit 3fc7285 with merge base 9774102 (image):

NEW FAILURE - The following job has failed:

FLAKY - The following job failed but was likely due to flakiness present on trunk:

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

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

UNSTABLE - The following job is marked as unstable, possibly due to flakiness on trunk:

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

@github-actions

github-actions Bot commented Dec 3, 2025

Copy link
Copy Markdown
Contributor

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

Comment thread torch/distributed/tensor/_ops/utils.py Outdated
)

# we only consider redistributing to the types of shardings allowed by the expanded rules for each input
def is_sharding(p: Placement):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just TypeIs return type, it's easy here.

Comment thread torch/distributed/tensor/_ops/utils.py Outdated
)
return OpStrategy([op_spec])

def can_chunk(placements: tuple[Placement, ...]) -> bool:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These also should return TypeIs with Tuple args

tiendatngcs pushed a commit to tiendatngcs/pytorch-Dec25 that referenced this pull request Dec 9, 2025
very WIP

ghstack-source-id: 110b024
Pull Request resolved: pytorch/pytorch#169438
heapq.heappush(
pq,
(
new_total_cost,

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 using some notion of "breadth"/# of redistributes required helps here, otherwise for ops like pointwise, we might now unnecessarily chunk as it's no cost difference (e.g. RR + S(0)R -> S(0)R vs. RR + S(0)R -> S(0)S(0))?

I haven't verified but just (new_total_cost, n_comms + 1)?

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.

i definitely want to keep pointwise decoupled from this logic. I would like to solve each group of inputs+output separately with caching. So if we have 1k foreach inputs and likely some similar input placements patterns, we just do the graph search for each unique pattern once

[ghstack-poisoned]
SergeyTyshkevich pushed a commit to SergeyTyshkevich/chart2 that referenced this pull request Jan 19, 2026
very WIP

ghstack-source-id: 75d04e4
Pull Request resolved: pytorch/pytorch#169438
@github-actions

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

@github-actions github-actions Bot added the Stale label Feb 15, 2026
@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Mar 7, 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

placements: tuple[tuple[Placement, ...], ...] = field(compare=False)
# History of (input_idx, mesh_dim, old_placement, new_placement) transitions
# from the initial state to this state, used for debugging.
transitions: list[tuple[int, int, Placement, Placement]] = field(compare=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.

Not only for debugging, I think after the strategy generation, we can skip redistribution trace computation for src args and use transitions directly.

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.

yea, i was planning to do this, but then i got lazy. even claude was lazy- it kept telling me 'its not worth it, do you really want me to disrupt a bunch of callsites by passing this info around, or are you happy with just making the redistribution cost itself cheap inside the pq search? so i relented. but we can add this later.

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.

Yes, I think it's fine to keep the transitions for debugging instead of making a big refactor to skip the follow up redistribution related computation. Also regarding #169438 (review), we can fix this later since our default redistribution cost computation also doesn't honor the device order. That maybe the reason why those tests in the PR can pass.

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

My current understanding is that when do graph search, the code will change one placement at a time as in _get_neighbor_placements. The thing is that it didn't consider the device order.
E.g., for 2D tensor matmul on 2D mesh, if we begin with lhs=(S(0), R), rhs=(R, S(0)), which doesn't fit into a valid matmul single dim strategy. So we will find neighbors. One neighbor for rhs is (S(0), S(0)), but this should be invalid because we can't go (R, S(0)) --> (S(0), S(0)) with one collective. I think we can add a test by only using the transitions to redistribute the input args and do the matmul, instead of calling redistribute separately after strategy generation. We may see numerical error of the matmul result due to incorrect distribution.

I think the transition should be: try all possible collective/chunk op on the current state and we can get the next state, then we check if the next state fits a valid single dim strategy.

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

The merge job was canceled or timed out. This most often happen if two merge requests were issued for the same PR, or if merge job was waiting for more than 6 hours for tests to finish. In later case, please do not hesitate to reissue the merge command
For more information see pytorch-bot wiki.

Add _dijkstra_expand_single_dim_strategy_to_mesh, a priority-queue search
over input placement states that finds the lowest-cost sharding for an op
without enumerating all S^N strategy combinations (S = single-dim strategies,
N = mesh dimensions). The search uses _PreparedSingleDimStrategy (from the
previous commit) to materialize single-dim rules and try_propagate() to
test whether a candidate state matches on every mesh dimension.

Each search state is a tuple of per-input placement tuples. Neighbors are
generated by changing one placement on one mesh dimension for one input,
using _get_neighbor_placements which encodes DTensor redistribute transition
rules (Replicate <-> Shard, Partial -> Replicate/Shard). Cost computation
uses _compute_redistribute_cost which calls _compute_placement_transition_cost
directly per mesh dimension, avoiding DTensorSpec construction and
_gen_transform_infos planning overhead.

Returns None for _StridedShard inputs, signaling the caller to fall back to
full expansion.

Authored with Claude.

[ghstack-poisoned]
@wconstab

wconstab commented Mar 9, 2026

Copy link
Copy Markdown
Contributor Author

@zpcore - thanks for catching that! My original version had organized things by collective but it got lost along the way. I have added a new helper for proposing neighbor placements honoring L to R shard order. wdyt?

@zpcore

zpcore commented Mar 9, 2026

Copy link
Copy Markdown
Contributor

@zpcore - thanks for catching that! My original version had organized things by collective but it got lost along the way. I have added a new helper for proposing neighbor placements honoring L to R shard order. wdyt?

Oh, I see you have fixed the neighbor search to honor the order. LGTM! I also checked our redistribute cost computation and noticed that it is already using the correct cost based on transforms info, which aligns with the cost computation in this PR. Those tests should pass as expected!

@wconstab

wconstab commented Mar 9, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@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: trunk / macos-py3-arm64 / test (default, 1, 3, macos-m1-stable)

Details for Dev Infra team Raised by workflow job

@wconstab

wconstab commented Mar 9, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

pytorchmergebot pushed a commit that referenced this pull request Mar 10, 2026
Wire _dijkstra_expand_single_dim_strategy_to_mesh into the sharding
propagation path. For ops with single-dim strategies, try the PQ search
first; fall back to full O(S^N) expansion when it returns None
(StridedShard, symbolic shapes, or TupleStrategy inputs).

Authored with Claude.
Pull Request resolved: #175999
Approved by: https://github.com/Skylion007
ghstack dependencies: #169438
sandy-gags pushed a commit to sandy-gags/pytorch that referenced this pull request Mar 12, 2026
very WIP

ghstack-source-id: bbd81da
Pull Request resolved: pytorch/pytorch#169438

[DTensor] PQ search: fast path, cost cache, and reachability tests

Add three optimizations to _find_lowest_cost_sharding and two
reachability tests that prove the PQ transition graph covers all valid
strategies.

The fast path checks whether the initial input placements already match
a strategy rule on every mesh dim, returning immediately without
constructing MeshTopoInfo or the PQ. The per-input cost cache avoids
redundant _compute_redistribute_cost calls by keying on destination
placement tuples (at most 64 unique keys per input on a 3D mesh).
_build_output_spec is extracted as a shared helper between the fast path
and PQ match block.

_collect_all_matches is a testing-only parameter that forces the PQ to
exhaustively explore the full transition graph, collecting every
shardable match into a set while still returning the optimal result.

Authored with Claude.

ghstack-source-id: bbd81da
Pull Request resolved: pytorch/pytorch#175313
sandy-gags pushed a commit to sandy-gags/pytorch that referenced this pull request Mar 12, 2026
Add _dijkstra_expand_single_dim_strategy_to_mesh, a priority-queue search
over input placement states that finds the lowest-cost sharding for an op
without enumerating all S^N strategy combinations (S = single-dim strategies,
N = mesh dimensions). The search uses _PreparedSingleDimStrategy (from the
previous commit) to materialize single-dim rules and try_propagate() to
test whether a candidate state matches on every mesh dimension.

Each search state is a tuple of per-input placement tuples. Neighbors are
generated by changing one placement on one mesh dimension for one input,
using _get_neighbor_placements which encodes DTensor redistribute transition
rules (Replicate <-> Shard, Partial -> Replicate/Shard). Cost computation
uses _compute_redistribute_cost which calls _compute_placement_transition_cost
directly per mesh dimension, avoiding DTensorSpec construction and
_gen_transform_infos planning overhead.

Returns None for _StridedShard inputs, signaling the caller to fall back to
full expansion.

[DTensor] Bail out of dijkstra for kwargs tensor inputs

The PQ search only tracks positional tensor args. If any kwargs contain
OpStrategy or TupleStrategy (tensor inputs), fall back to full expansion
to avoid missing their redistribute costs.

Authored with Claude.

ghstack-source-id: c12cf5a
Pull Request resolved: pytorch/pytorch#169438

[DTensor] Use incremental per-step costs in dijkstra search

Replace _compute_redistribute_cost (which computed initial→target cost
using the greedy transform ordering) with incremental per-step costs via
_compute_placement_transition_cost. Each PQ transition now computes only
the cost of the single changed placement, and per_input_comm_bytes_gb is
tracked per PQ entry so it reflects the current shard state rather than
the initial state.

This makes dijkstra's cost model find the globally optimal ordering of
per-dim transitions (accounting for comm_bytes updates from
reduce-scatter, allgather, etc.). For example, doing reduce-scatter
before allreduce on a different dim is cheaper because reduce-scatter
shrinks the data first — dijkstra discovers this naturally.

The resulting costs can be strictly lower than both the greedy and
graph-based redistribute planners, since those use fixed orderings that
don't optimize for comm_bytes minimization across dims. The test
reference now uses graph-based (min-cost) planning and asserts
pq_cost <= ref_cost.

Authored with Claude.
sandy-gags pushed a commit to sandy-gags/pytorch that referenced this pull request Mar 12, 2026
Add _dijkstra_expand_single_dim_strategy_to_mesh, a priority-queue search
over input placement states that finds the lowest-cost sharding for an op
without enumerating all S^N strategy combinations (S = single-dim strategies,
N = mesh dimensions). The search uses _PreparedSingleDimStrategy (from the
previous commit) to materialize single-dim rules and try_propagate() to
test whether a candidate state matches on every mesh dimension.

Each search state is a tuple of per-input placement tuples. Neighbors are
generated by changing one placement on one mesh dimension for one input,
using _get_neighbor_placements which encodes DTensor redistribute transition
rules (Replicate <-> Shard, Partial -> Replicate/Shard). Cost computation
uses _compute_redistribute_cost which calls _compute_placement_transition_cost
directly per mesh dimension, avoiding DTensorSpec construction and
_gen_transform_infos planning overhead.

Returns None for _StridedShard inputs, signaling the caller to fall back to
full expansion.

[DTensor] Bail out of dijkstra for kwargs tensor inputs

The PQ search only tracks positional tensor args. If any kwargs contain
OpStrategy or TupleStrategy (tensor inputs), fall back to full expansion
to avoid missing their redistribute costs.

Authored with Claude.

ghstack-source-id: add4ea1
Pull Request resolved: pytorch/pytorch#169438

[DTensor] Use incremental per-step costs in dijkstra search

Replace _compute_redistribute_cost (which computed initial→target cost
using the greedy transform ordering) with incremental per-step costs via
_compute_placement_transition_cost. Each PQ transition now computes only
the cost of the single changed placement, and per_input_comm_bytes_gb is
tracked per PQ entry so it reflects the current shard state rather than
the initial state.

This makes dijkstra's cost model find the globally optimal ordering of
per-dim transitions (accounting for comm_bytes updates from
reduce-scatter, allgather, etc.). For example, doing reduce-scatter
before allreduce on a different dim is cheaper because reduce-scatter
shrinks the data first — dijkstra discovers this naturally.

The resulting costs can be strictly lower than both the greedy and
graph-based redistribute planners, since those use fixed orderings that
don't optimize for comm_bytes minimization across dims. The test
reference now uses graph-based (min-cost) planning and asserts
pq_cost <= ref_cost.

Authored with Claude.
EmanueleCoradin pushed a commit to EmanueleCoradin/pytorch that referenced this pull request Mar 30, 2026
Add _dijkstra_expand_single_dim_strategy_to_mesh, a priority-queue search
over input placement states that finds the lowest-cost sharding for an op
without enumerating all S^N strategy combinations (S = single-dim strategies,
N = mesh dimensions). The search uses _PreparedSingleDimStrategy (from the
previous commit) to materialize single-dim rules and try_propagate() to
test whether a candidate state matches on every mesh dimension.

Each search state is a tuple of per-input placement tuples. Neighbors are
generated by changing one placement on one mesh dimension for one input,
using _get_neighbor_placements which encodes DTensor redistribute transition
rules (Replicate <-> Shard, Partial -> Replicate/Shard). Cost computation
uses _compute_redistribute_cost which calls _compute_placement_transition_cost
directly per mesh dimension, avoiding DTensorSpec construction and
_gen_transform_infos planning overhead.

Returns None for _StridedShard inputs, signaling the caller to fall back to
full expansion.

Authored with Claude.
Pull Request resolved: pytorch#169438
Approved by: https://github.com/anshul-si, https://github.com/zpcore

Co-authored-by: Pian Pawakapan <[email protected]>
EmanueleCoradin pushed a commit to EmanueleCoradin/pytorch that referenced this pull request Mar 30, 2026
)

Wire _dijkstra_expand_single_dim_strategy_to_mesh into the sharding
propagation path. For ops with single-dim strategies, try the PQ search
first; fall back to full O(S^N) expansion when it returns None
(StridedShard, symbolic shapes, or TupleStrategy inputs).

Authored with Claude.
Pull Request resolved: pytorch#175999
Approved by: https://github.com/Skylion007
ghstack dependencies: pytorch#169438
@github-actions
github-actions Bot deleted the gh/wconstab/465/head branch April 9, 2026 02:23
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
Add _dijkstra_expand_single_dim_strategy_to_mesh, a priority-queue search
over input placement states that finds the lowest-cost sharding for an op
without enumerating all S^N strategy combinations (S = single-dim strategies,
N = mesh dimensions). The search uses _PreparedSingleDimStrategy (from the
previous commit) to materialize single-dim rules and try_propagate() to
test whether a candidate state matches on every mesh dimension.

Each search state is a tuple of per-input placement tuples. Neighbors are
generated by changing one placement on one mesh dimension for one input,
using _get_neighbor_placements which encodes DTensor redistribute transition
rules (Replicate <-> Shard, Partial -> Replicate/Shard). Cost computation
uses _compute_redistribute_cost which calls _compute_placement_transition_cost
directly per mesh dimension, avoiding DTensorSpec construction and
_gen_transform_infos planning overhead.

Returns None for _StridedShard inputs, signaling the caller to fall back to
full expansion.

Authored with Claude.
Pull Request resolved: pytorch#169438
Approved by: https://github.com/anshul-si, https://github.com/zpcore

Co-authored-by: Pian Pawakapan <[email protected]>
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
)

Wire _dijkstra_expand_single_dim_strategy_to_mesh into the sharding
propagation path. For ops with single-dim strategies, try the PQ search
first; fall back to full O(S^N) expansion when it returns None
(StridedShard, symbolic shapes, or TupleStrategy inputs).

Authored with Claude.
Pull Request resolved: pytorch#175999
Approved by: https://github.com/Skylion007
ghstack dependencies: pytorch#169438
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