Skip to content

[DTensor] Don't trace shard propagation into make_fx graphs - #185865

Closed
SherlockNoMad wants to merge 5 commits into
gh/SherlockNoMad/29/basefrom
gh/SherlockNoMad/29/head
Closed

SherlockNoMad wants to merge 5 commits into
gh/SherlockNoMad/29/basefrom
gh/SherlockNoMad/29/head

Conversation

@SherlockNoMad

@SherlockNoMad SherlockNoMad commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

ShardingPropagator._propagate_tensor_meta_non_cached runs each DTensor
op on fake global-shape tensors purely to derive output metadata
(shape/stride/dtype). It entered FakeTensorMode but did not disable an
enclosing make_fx proxy tracer, so the gen_fake_args() factory calls and
op_schema.op(...) were recorded into the traced graph as dead code:
global-shape "shadow" nodes backed by empty_strided placeholders that no
real (local) output ever consumes.

These dead nodes are mostly harmless, but for bounds-checked ops such as
aten.embedding the uninitialized empty_strided index tensor triggers an
out-of-bounds gather on the (TP-sharded) weight, crashing with a
device-side assert. Any make_fx trace of a model with
tensor_parallel_degree > 1 hits this.

Wrap the fake-tensor metadata inference in disable_proxy_modes_tracing()
so shard propagation stays out of the captured graph entirely.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Jun 1, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure, 2 Unclassified Failures

As of commit 99354af with merge base 789c465 (image):

NEW FAILURE - The following job has failed:

UNCLASSIFIED FAILURES - DrCI could not classify the following jobs because the workflow did not run on the merge base. The failures may be pre-existing on trunk or introduced by this PR:

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 Jun 1, 2026
@aditvenk
aditvenk requested a review from pianpwk June 1, 2026 23:41
[ghstack-poisoned]
@SherlockNoMad
SherlockNoMad requested a review from aorenste as a code owner June 2, 2026 04:45
SherlockNoMad added a commit that referenced this pull request Jun 2, 2026
ShardingPropagator._propagate_tensor_meta_non_cached runs each DTensor
op on fake global-shape tensors purely to derive output metadata
(shape/stride/dtype). It entered FakeTensorMode but did not disable an
enclosing make_fx proxy tracer, so the gen_fake_args() factory calls and
op_schema.op(...) were recorded into the traced graph as dead code:
global-shape "shadow" nodes backed by empty_strided placeholders that no
real (local) output ever consumes.

These dead nodes are mostly harmless, but for bounds-checked ops such as
aten.embedding the uninitialized empty_strided index tensor triggers an
out-of-bounds gather on the (TP-sharded) weight, crashing with a
device-side assert. Any make_fx trace of a model with
tensor_parallel_degree > 1 hits this.

Wrap the fake-tensor metadata inference in disable_proxy_modes_tracing()
so shard propagation stays out of the captured graph entirely.

ghstack-source-id: 47ec6fb
Pull-Request: #185865
[ghstack-poisoned]
SherlockNoMad added a commit that referenced this pull request Jun 2, 2026
ShardingPropagator._propagate_tensor_meta_non_cached runs each DTensor
op on fake global-shape tensors purely to derive output metadata
(shape/stride/dtype). It entered FakeTensorMode but did not disable an
enclosing make_fx proxy tracer, so the gen_fake_args() factory calls and
op_schema.op(...) were recorded into the traced graph as dead code:
global-shape "shadow" nodes backed by empty_strided placeholders that no
real (local) output ever consumes.

These dead nodes are mostly harmless, but for bounds-checked ops such as
aten.embedding the uninitialized empty_strided index tensor triggers an
out-of-bounds gather on the (TP-sharded) weight, crashing with a
device-side assert. Any make_fx trace of a model with
tensor_parallel_degree > 1 hits this.

Wrap the fake-tensor metadata inference in disable_proxy_modes_tracing()
so shard propagation stays out of the captured graph entirely.

ghstack-source-id: 47ee1ef
Pull-Request: #185865

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

Looks reasonable but causing a test failure

[ghstack-poisoned]
SherlockNoMad added a commit that referenced this pull request Jun 2, 2026
ShardingPropagator._propagate_tensor_meta_non_cached runs each DTensor
op on fake global-shape tensors purely to derive output metadata
(shape/stride/dtype). It entered FakeTensorMode but did not disable an
enclosing make_fx proxy tracer, so the gen_fake_args() factory calls and
op_schema.op(...) were recorded into the traced graph as dead code:
global-shape "shadow" nodes backed by empty_strided placeholders that no
real (local) output ever consumes.

These dead nodes are mostly harmless, but for bounds-checked ops such as
aten.embedding the uninitialized empty_strided index tensor triggers an
out-of-bounds gather on the (TP-sharded) weight, crashing with a
device-side assert. Any make_fx trace of a model with
tensor_parallel_degree > 1 hits this.

Wrap the fake-tensor metadata inference in disable_proxy_modes_tracing()
so shard propagation stays out of the captured graph entirely.

ghstack-source-id: 49ea5c3
Pull-Request: #185865
@SherlockNoMad

Copy link
Copy Markdown
Contributor Author

Looks reasonable but causing a test failure

fixed. node name drift only

@SherlockNoMad
SherlockNoMad requested a review from aorenste June 2, 2026 16:48

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

Approving to unblock. Not a regression because minimum/maximum weren't previously handled at all - but should probably be extended/tested to support n-ary inputs.

Comment thread torch/fx/experimental/proxy_tensor.py Outdated
Comment on lines +547 to +550
elif v == "maximum":
handlers[k] = torch.sym_max
elif v == "minimum":
handlers[k] = torch.sym_min

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.

(Claude Review) [blocker] torch.sym_max/torch.sym_min are binary (def sym_max(a, b) in torch/__init__.py), but sympy Max/Min flatten to n-ary: sym_max(sym_max(a, b), c) produces a single Max(u0, u1, u2), not nested binaries. (MinMaxBase.__new__ reshapes Max(a, Max(b, c)) -> Max(a, b, c), and _satisfy_unique_summations_symbols' docstring calls max(max(max(...))) flattening "one common case in some models".) _build_proxy_for_sym_expr does func(*args) over all of expr.args, so a 3+ arg Max/Min reaching here raises TypeError: sym_max() takes 2 positional arguments but 3 were given. Reproduced against this PR's handler dict: binary Max(1, u2) works, 3-ary/4-ary Max/Min crash. This is the identical n-arity hazard the next block already handles for Add via torch.sym_sum -- and which test_build_proxy_for_optimized_add was specifically added to guard. It also regresses the n-ary case from the pre-PR graceful "couldn't build" (returns None) into a hard crash. Fix mirrors the Add case (functools is already imported; verified to handle 2/3/4-ary):

        elif v == "maximum":
            handlers[k] = lambda *a: functools.reduce(torch.sym_max, a)
        elif v == "minimum":
            handlers[k] = lambda *a: functools.reduce(torch.sym_min, a)

Worth a regression test alongside test_build_proxy_for_optimized_add covering n-ary Max/Min.

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.

addressed.

[ghstack-poisoned]
SherlockNoMad added a commit that referenced this pull request Jun 2, 2026
ShardingPropagator._propagate_tensor_meta_non_cached runs each DTensor
op on fake global-shape tensors purely to derive output metadata
(shape/stride/dtype). It entered FakeTensorMode but did not disable an
enclosing make_fx proxy tracer, so the gen_fake_args() factory calls and
op_schema.op(...) were recorded into the traced graph as dead code:
global-shape "shadow" nodes backed by empty_strided placeholders that no
real (local) output ever consumes.

These dead nodes are mostly harmless, but for bounds-checked ops such as
aten.embedding the uninitialized empty_strided index tensor triggers an
out-of-bounds gather on the (TP-sharded) weight, crashing with a
device-side assert. Any make_fx trace of a model with
tensor_parallel_degree > 1 hits this.

Wrap the fake-tensor metadata inference in disable_proxy_modes_tracing()
so shard propagation stays out of the captured graph entirely.

ghstack-source-id: 60e2edb
Pull-Request: #185865
@SherlockNoMad

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -f "flaky tests"

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use -f as last resort and instead consider -i/--ignore-current to continue the merge ignoring current failures. This will allow currently pending tests to finish and report signal before the merge.

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

@github-actions
github-actions Bot deleted the gh/SherlockNoMad/29/head branch July 3, 2026 03:37
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…185865)

ShardingPropagator._propagate_tensor_meta_non_cached runs each DTensor
op on fake global-shape tensors purely to derive output metadata
(shape/stride/dtype). It entered FakeTensorMode but did not disable an
enclosing make_fx proxy tracer, so the gen_fake_args() factory calls and
op_schema.op(...) were recorded into the traced graph as dead code:
global-shape "shadow" nodes backed by empty_strided placeholders that no
real (local) output ever consumes.

These dead nodes are mostly harmless, but for bounds-checked ops such as
aten.embedding the uninitialized empty_strided index tensor triggers an
out-of-bounds gather on the (TP-sharded) weight, crashing with a
device-side assert. Any make_fx trace of a model with
tensor_parallel_degree > 1 hits this.

Wrap the fake-tensor metadata inference in disable_proxy_modes_tracing()
so shard propagation stays out of the captured graph entirely.
Pull Request resolved: pytorch#185865
Approved by: https://github.com/ydwu4, https://github.com/aorenste
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…185865)

ShardingPropagator._propagate_tensor_meta_non_cached runs each DTensor
op on fake global-shape tensors purely to derive output metadata
(shape/stride/dtype). It entered FakeTensorMode but did not disable an
enclosing make_fx proxy tracer, so the gen_fake_args() factory calls and
op_schema.op(...) were recorded into the traced graph as dead code:
global-shape "shadow" nodes backed by empty_strided placeholders that no
real (local) output ever consumes.

These dead nodes are mostly harmless, but for bounds-checked ops such as
aten.embedding the uninitialized empty_strided index tensor triggers an
out-of-bounds gather on the (TP-sharded) weight, crashing with a
device-side assert. Any make_fx trace of a model with
tensor_parallel_degree > 1 hits this.

Wrap the fake-tensor metadata inference in disable_proxy_modes_tracing()
so shard propagation stays out of the captured graph entirely.
Pull Request resolved: pytorch#185865
Approved by: https://github.com/ydwu4, https://github.com/aorenste
aditvenk added a commit that referenced this pull request Oct 30, 2026
Since #185865, DTensor sharding propagation runs under
disable_proxy_modes_tracing(), so the global sizes it produces are
SymNodes that make_fx never tracked. When one is later used with tracing
on, get_proxy_slot() resolves it through tracer.sympy_expr_tracker (a map
from a symbol to a tracked SymInt with that value) or rebuilds it from its
sympy expression with _build_proxy_for_sym_expr(). Two bugs in that
fallback broke torch.compile of tensor-parallel models with dynamic shapes.

1. Infinite recursion in the AOTAutograd joint trace (#201624)

In backward, the contiguity computation calls sym_max(size, 1) on an
untracked global size s50. The result simplifies to s50, so it becomes
sympy_expr_tracker[s50]. Under AOTAutograd its proxy is a lazy thunk that
resolves its untracked input when forced. That lookup returns
sympy_expr_tracker[s50], the thunk being forced, which runs again and
recurses forever. Forward-only compiles are not thunkified, which is why
they worked. The same cycle can also close through other ops and
symbols, e.g. p == s1 computed from an untracked s0 while q == s0 is
computed from an untracked s1.

The fix makes lookups skip providers that are still being computed.
_compute_proxy(), the body of every lazy SymInt proxy, adds its result to
the new tracer.symnodes_being_forced while it resolves its arguments.
Each sympy_expr_tracker entry also records the entry it replaced (prev),
so every symbol keeps a stack of providers, newest first. The new
_lookup_sympy_expr(), used by both get_proxy_slot() and
_build_proxy_for_sym_expr(), walks down that stack past providers in
symnodes_being_forced. In the example above, forcing sym_max(s50, 1) now
resolves s50 to the provider registered before it, such as an input's
sym_size, instead of to itself.

Writes keep main's last-writer-wins behavior, so a lookup only changes
when its newest provider is mid-computation. Everything a lookup returns
in that window is forced on the same stack, and Thunk.force() only marks
a thunk done after it returns, so on main that lookup re-enters the
provider's thunk and recurses forever. Every changed outcome was
therefore a RecursionError on main. If every provider is mid-computation,
the lookup misses and tracing fails with "is not tracked with proxy"
instead of hanging. Cycles that close through a registered thunk rather
than a table lookup are not covered and still recurse, as on main. The
cost is a set add/discard per forced lazy SymInt and one dict read per
symbol registration; the skip loop only runs on the fallback path.

Alternatives considered were rules restricting which SymInts may become
entries, such as first registration wins, or no entries computed from
untracked SymInts. AOTAutograd registers tangent placeholders before the
forward runs, so each such rule either lets a tangent keep a symbol,
making the forward graph depend on tangents_1, or misses cycles that
close after later writes. test_unbacked_global_size_no_tangent_dependency
and test_build_proxy_untracked_symint_no_tangent_dependency cover the
tangent cases.

2. Rebuilt Max/Min nodes that Inductor cannot lower (#201838)

_sympy_handlers() mapped sympy Max/Min to the helpers
_nary_sym_max/_nary_sym_min. When _build_proxy_for_sym_expr() rebuilds a
Max/Min on the get_proxy_slot path (e.g. contiguous strides like
Max(1, u0) of a DTensor with unbacked sizes), the helper becomes an FX
node target, which Inductor rejects as "is not an OpOverload".
_build_proxy_for_sym_expr() already folds n-ary expressions into binary
calls, so map Max/Min directly to torch.sym_max/torch.sym_min and delete
the helpers. The exact #201838 repro already passes on main since
#193416; this fixes the remaining _nary_sym_max failure.

The new DTensor backward tests also run under compiled autograd, where
DTensor's backward graph-breaks, so they are added to
known_graph_breaks_tests in test_compiled_autograd.py.

Fixes #201624
Fixes #201838

Test Plan:

The new tests fail on main and pass with this change. The #201624 and
#201838 repros pass on 2x B200, with gradients matching eager. Compile
time is unchanged (make_fx of ~6000 SymInt ops: median 1.74-1.78 s on
main, 1.72-1.77 s with this change).

```
python test/test_dynamic_shapes.py -k test_build_proxy
python -m pytest test/distributed/tensor/test_dtensor_compile.py
python -m pytest test/inductor/test_compiled_autograd.py -n 8
torchrun --nproc_per_node=2 repro_201624.py
torchrun --nproc_per_node=2 repro_201838.py
```

No new failures in related suites, including:

```
python -m pytest test/test_proxy_tensor.py -n 4
python -m pytest test/functorch/test_aotdispatch.py -n 8
python -m pytest test/dynamo/test_subclasses.py -n 4
python -m pytest test/export/test_export.py -n 8
python -m pytest test/inductor/test_torchinductor_dynamic_shapes.py -k cuda -n 8
```

This PR was authored with the assistance of an AI coding agent.
pytorchmergebot pushed a commit that referenced this pull request Nov 3, 2026
…202428)

## Linked issue or supporting maintainer

Fixes #201624
Fixes #201838

## BC-breaking?

No

## Summary (human written only)

This PR fixes two bugs in DTensor x dynamic shapes.

DTensor shard prop runs under disable_proxy_modes_tracing(), so SymNodes it creates are untracked: make_fx has no proxy for them in symnode_tracker. When one is used later, get_proxy_slot falls back to sympy_expr_tracker[symbol], or to _build_proxy_for_sym_expr, which rebuilds it from its sympy expression.

1) In backward, sym_max(Y, 1) runs on an untracked Y whose expression is s50. The result X simplifies to s50 as well. _sym_register gives X a lazy thunk proxy that depends on Y, and set_proxy_slot overwrote sympy_expr_tracker[s50] with X. Forcing X's thunk resolves Y, which through sympy_expr_tracker is X again and so on recurses.

Fix: Resolving an untracked SymInt through sympy_expr_tracker now skips any SymInt whose lazy proxy is mid-computation, falling back to the provider it replaced. Since writes are unchanged, behavior only differs from main where main recursed forever.

2) _build_proxy_for_sym_expr rebuilt sympy Max/Min as FX nodes with target _nary_sym_max/_nary_sym_min which Inductor cannot lower.

Fix: Substitute to torch.sym_max/torch.sym_min because _build_proxy_for_sym_expr now splits many-arg expression into chain of two-argument calls. So the helpers are not needed anymore.

## Agent details (if applicable)

Since #185865, DTensor sharding propagation runs under disable_proxy_modes_tracing(), so the global sizes it produces are SymNodes that make_fx never tracked. When one is later used with tracing on, get_proxy_slot() resolves it through tracer.sympy_expr_tracker (a map from a symbol to a tracked SymInt with that value) or rebuilds it from its sympy expression with _build_proxy_for_sym_expr(). Two bugs in that fallback broke torch.compile of tensor-parallel models with dynamic shapes.

1. Infinite recursion in the AOTAutograd joint trace (#201624)

In backward, the contiguity computation calls sym_max(size, 1) on an untracked global size s50. The result simplifies to s50, so it becomes sympy_expr_tracker[s50]. Under AOTAutograd its proxy is a lazy thunk that resolves its untracked input when forced. That lookup returns sympy_expr_tracker[s50], the thunk being forced, which runs again and recurses forever. Forward-only compiles are not thunkified, which is why they worked. The same cycle can also close through other ops and symbols, e.g. p == s1 computed from an untracked s0 while q == s0 is computed from an untracked s1.

The fix makes lookups skip providers that are still being computed. _compute_proxy(), the body of every lazy SymInt proxy, adds its result to the new tracer.symnodes_being_forced while it resolves its arguments. Each sympy_expr_tracker entry also records the entry it replaced (prev), so every symbol keeps a stack of providers, newest first. The new _lookup_sympy_expr(), used by both get_proxy_slot() and _build_proxy_for_sym_expr(), walks down that stack past providers in symnodes_being_forced. In the example above, forcing sym_max(s50, 1) now resolves s50 to the provider registered before it, such as an input's sym_size, instead of to itself.

Writes keep main's last-writer-wins behavior, so a lookup only changes when its newest provider is mid-computation. Everything a lookup returns in that window is forced on the same stack, and Thunk.force() only marks a thunk done after it returns, so on main that lookup re-enters the provider's thunk and recurses forever. Every changed outcome was therefore a RecursionError on main. If every provider is mid-computation, the lookup misses and tracing fails with "is not tracked with proxy" instead of hanging. Cycles that close through a registered thunk rather than a table lookup are not covered and still recurse, as on main. The cost is a set add/discard per forced lazy SymInt and one dict read per symbol registration; the skip loop only runs on the fallback path.

Alternatives considered were rules restricting which SymInts may become entries, such as first registration wins, or no entries computed from untracked SymInts. AOTAutograd registers tangent placeholders before the forward runs, so each such rule either lets a tangent keep a symbol, making the forward graph depend on tangents_1, or misses cycles that close after later writes. test_unbacked_global_size_no_tangent_dependency and test_build_proxy_untracked_symint_no_tangent_dependency cover the tangent cases.

2. Rebuilt Max/Min nodes that Inductor cannot lower (#201838)

_sympy_handlers() mapped sympy Max/Min to the helpers _nary_sym_max/_nary_sym_min. When _build_proxy_for_sym_expr() rebuilds a Max/Min on the get_proxy_slot path (e.g. contiguous strides like Max(1, u0) of a DTensor with unbacked sizes), the helper becomes an FX node target, which Inductor rejects as "is not an OpOverload". _build_proxy_for_sym_expr() already folds n-ary expressions into binary calls, so map Max/Min directly to torch.sym_max/torch.sym_min and delete the helpers. The exact #201838 repro already passes on main since #193416; this fixes the remaining _nary_sym_max failure.

The new DTensor backward tests also run under compiled autograd, where DTensor's backward graph-breaks, so they are added to known_graph_breaks_tests in test_compiled_autograd.py.

Test Plan:

The new tests fail on main and pass with this change.

This PR was authored with the assistance of an AI coding agent.

Pull Request resolved: #202428
Approved by: https://github.com/aorenste
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…ytorch#202428)

## Linked issue or supporting maintainer

Fixes pytorch#201624
Fixes pytorch#201838

## BC-breaking?

No

## Summary (human written only)

This PR fixes two bugs in DTensor x dynamic shapes.

DTensor shard prop runs under disable_proxy_modes_tracing(), so SymNodes it creates are untracked: make_fx has no proxy for them in symnode_tracker. When one is used later, get_proxy_slot falls back to sympy_expr_tracker[symbol], or to _build_proxy_for_sym_expr, which rebuilds it from its sympy expression.

1) In backward, sym_max(Y, 1) runs on an untracked Y whose expression is s50. The result X simplifies to s50 as well. _sym_register gives X a lazy thunk proxy that depends on Y, and set_proxy_slot overwrote sympy_expr_tracker[s50] with X. Forcing X's thunk resolves Y, which through sympy_expr_tracker is X again and so on recurses.

Fix: Resolving an untracked SymInt through sympy_expr_tracker now skips any SymInt whose lazy proxy is mid-computation, falling back to the provider it replaced. Since writes are unchanged, behavior only differs from main where main recursed forever.

2) _build_proxy_for_sym_expr rebuilt sympy Max/Min as FX nodes with target _nary_sym_max/_nary_sym_min which Inductor cannot lower.

Fix: Substitute to torch.sym_max/torch.sym_min because _build_proxy_for_sym_expr now splits many-arg expression into chain of two-argument calls. So the helpers are not needed anymore.

## Agent details (if applicable)

Since pytorch#185865, DTensor sharding propagation runs under disable_proxy_modes_tracing(), so the global sizes it produces are SymNodes that make_fx never tracked. When one is later used with tracing on, get_proxy_slot() resolves it through tracer.sympy_expr_tracker (a map from a symbol to a tracked SymInt with that value) or rebuilds it from its sympy expression with _build_proxy_for_sym_expr(). Two bugs in that fallback broke torch.compile of tensor-parallel models with dynamic shapes.

1. Infinite recursion in the AOTAutograd joint trace (pytorch#201624)

In backward, the contiguity computation calls sym_max(size, 1) on an untracked global size s50. The result simplifies to s50, so it becomes sympy_expr_tracker[s50]. Under AOTAutograd its proxy is a lazy thunk that resolves its untracked input when forced. That lookup returns sympy_expr_tracker[s50], the thunk being forced, which runs again and recurses forever. Forward-only compiles are not thunkified, which is why they worked. The same cycle can also close through other ops and symbols, e.g. p == s1 computed from an untracked s0 while q == s0 is computed from an untracked s1.

The fix makes lookups skip providers that are still being computed. _compute_proxy(), the body of every lazy SymInt proxy, adds its result to the new tracer.symnodes_being_forced while it resolves its arguments. Each sympy_expr_tracker entry also records the entry it replaced (prev), so every symbol keeps a stack of providers, newest first. The new _lookup_sympy_expr(), used by both get_proxy_slot() and _build_proxy_for_sym_expr(), walks down that stack past providers in symnodes_being_forced. In the example above, forcing sym_max(s50, 1) now resolves s50 to the provider registered before it, such as an input's sym_size, instead of to itself.

Writes keep main's last-writer-wins behavior, so a lookup only changes when its newest provider is mid-computation. Everything a lookup returns in that window is forced on the same stack, and Thunk.force() only marks a thunk done after it returns, so on main that lookup re-enters the provider's thunk and recurses forever. Every changed outcome was therefore a RecursionError on main. If every provider is mid-computation, the lookup misses and tracing fails with "is not tracked with proxy" instead of hanging. Cycles that close through a registered thunk rather than a table lookup are not covered and still recurse, as on main. The cost is a set add/discard per forced lazy SymInt and one dict read per symbol registration; the skip loop only runs on the fallback path.

Alternatives considered were rules restricting which SymInts may become entries, such as first registration wins, or no entries computed from untracked SymInts. AOTAutograd registers tangent placeholders before the forward runs, so each such rule either lets a tangent keep a symbol, making the forward graph depend on tangents_1, or misses cycles that close after later writes. test_unbacked_global_size_no_tangent_dependency and test_build_proxy_untracked_symint_no_tangent_dependency cover the tangent cases.

2. Rebuilt Max/Min nodes that Inductor cannot lower (pytorch#201838)

_sympy_handlers() mapped sympy Max/Min to the helpers _nary_sym_max/_nary_sym_min. When _build_proxy_for_sym_expr() rebuilds a Max/Min on the get_proxy_slot path (e.g. contiguous strides like Max(1, u0) of a DTensor with unbacked sizes), the helper becomes an FX node target, which Inductor rejects as "is not an OpOverload". _build_proxy_for_sym_expr() already folds n-ary expressions into binary calls, so map Max/Min directly to torch.sym_max/torch.sym_min and delete the helpers. The exact pytorch#201838 repro already passes on main since pytorch#193416; this fixes the remaining _nary_sym_max failure.

The new DTensor backward tests also run under compiled autograd, where DTensor's backward graph-breaks, so they are added to known_graph_breaks_tests in test_compiled_autograd.py.

Test Plan:

The new tests fail on main and pass with this change.

This PR was authored with the assistance of an AI coding agent.

Pull Request resolved: pytorch#202428
Approved by: https://github.com/aorenste
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…ytorch#202428)

## Linked issue or supporting maintainer

Fixes pytorch#201624
Fixes pytorch#201838

## BC-breaking?

No

## Summary (human written only)

This PR fixes two bugs in DTensor x dynamic shapes.

DTensor shard prop runs under disable_proxy_modes_tracing(), so SymNodes it creates are untracked: make_fx has no proxy for them in symnode_tracker. When one is used later, get_proxy_slot falls back to sympy_expr_tracker[symbol], or to _build_proxy_for_sym_expr, which rebuilds it from its sympy expression.

1) In backward, sym_max(Y, 1) runs on an untracked Y whose expression is s50. The result X simplifies to s50 as well. _sym_register gives X a lazy thunk proxy that depends on Y, and set_proxy_slot overwrote sympy_expr_tracker[s50] with X. Forcing X's thunk resolves Y, which through sympy_expr_tracker is X again and so on recurses.

Fix: Resolving an untracked SymInt through sympy_expr_tracker now skips any SymInt whose lazy proxy is mid-computation, falling back to the provider it replaced. Since writes are unchanged, behavior only differs from main where main recursed forever.

2) _build_proxy_for_sym_expr rebuilt sympy Max/Min as FX nodes with target _nary_sym_max/_nary_sym_min which Inductor cannot lower.

Fix: Substitute to torch.sym_max/torch.sym_min because _build_proxy_for_sym_expr now splits many-arg expression into chain of two-argument calls. So the helpers are not needed anymore.

## Agent details (if applicable)

Since pytorch#185865, DTensor sharding propagation runs under disable_proxy_modes_tracing(), so the global sizes it produces are SymNodes that make_fx never tracked. When one is later used with tracing on, get_proxy_slot() resolves it through tracer.sympy_expr_tracker (a map from a symbol to a tracked SymInt with that value) or rebuilds it from its sympy expression with _build_proxy_for_sym_expr(). Two bugs in that fallback broke torch.compile of tensor-parallel models with dynamic shapes.

1. Infinite recursion in the AOTAutograd joint trace (pytorch#201624)

In backward, the contiguity computation calls sym_max(size, 1) on an untracked global size s50. The result simplifies to s50, so it becomes sympy_expr_tracker[s50]. Under AOTAutograd its proxy is a lazy thunk that resolves its untracked input when forced. That lookup returns sympy_expr_tracker[s50], the thunk being forced, which runs again and recurses forever. Forward-only compiles are not thunkified, which is why they worked. The same cycle can also close through other ops and symbols, e.g. p == s1 computed from an untracked s0 while q == s0 is computed from an untracked s1.

The fix makes lookups skip providers that are still being computed. _compute_proxy(), the body of every lazy SymInt proxy, adds its result to the new tracer.symnodes_being_forced while it resolves its arguments. Each sympy_expr_tracker entry also records the entry it replaced (prev), so every symbol keeps a stack of providers, newest first. The new _lookup_sympy_expr(), used by both get_proxy_slot() and _build_proxy_for_sym_expr(), walks down that stack past providers in symnodes_being_forced. In the example above, forcing sym_max(s50, 1) now resolves s50 to the provider registered before it, such as an input's sym_size, instead of to itself.

Writes keep main's last-writer-wins behavior, so a lookup only changes when its newest provider is mid-computation. Everything a lookup returns in that window is forced on the same stack, and Thunk.force() only marks a thunk done after it returns, so on main that lookup re-enters the provider's thunk and recurses forever. Every changed outcome was therefore a RecursionError on main. If every provider is mid-computation, the lookup misses and tracing fails with "is not tracked with proxy" instead of hanging. Cycles that close through a registered thunk rather than a table lookup are not covered and still recurse, as on main. The cost is a set add/discard per forced lazy SymInt and one dict read per symbol registration; the skip loop only runs on the fallback path.

Alternatives considered were rules restricting which SymInts may become entries, such as first registration wins, or no entries computed from untracked SymInts. AOTAutograd registers tangent placeholders before the forward runs, so each such rule either lets a tangent keep a symbol, making the forward graph depend on tangents_1, or misses cycles that close after later writes. test_unbacked_global_size_no_tangent_dependency and test_build_proxy_untracked_symint_no_tangent_dependency cover the tangent cases.

2. Rebuilt Max/Min nodes that Inductor cannot lower (pytorch#201838)

_sympy_handlers() mapped sympy Max/Min to the helpers _nary_sym_max/_nary_sym_min. When _build_proxy_for_sym_expr() rebuilds a Max/Min on the get_proxy_slot path (e.g. contiguous strides like Max(1, u0) of a DTensor with unbacked sizes), the helper becomes an FX node target, which Inductor rejects as "is not an OpOverload". _build_proxy_for_sym_expr() already folds n-ary expressions into binary calls, so map Max/Min directly to torch.sym_max/torch.sym_min and delete the helpers. The exact pytorch#201838 repro already passes on main since pytorch#193416; this fixes the remaining _nary_sym_max failure.

The new DTensor backward tests also run under compiled autograd, where DTensor's backward graph-breaks, so they are added to known_graph_breaks_tests in test_compiled_autograd.py.

Test Plan:

The new tests fail on main and pass with this change.

This PR was authored with the assistance of an AI coding agent.

Pull Request resolved: pytorch#202428
Approved by: https://github.com/aorenste
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 Merged release notes: distributed (dtensor) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants