Skip to content

Fix make_fx rebuild of untracked SymInts from DTensor sharding prop - #202428

Closed
aditvenk wants to merge 2 commits into
mainfrom
fix-dtensor-untracked-symint-rebuild
Closed

aditvenk wants to merge 2 commits into
mainfrom
fix-dtensor-untracked-symint-rebuild

Conversation

@aditvenk

@aditvenk aditvenk commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

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.

  1. _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 ([DTensor][compile] Dynamic shapes + backward on a ColwiseParallel / RowwiseParallel nn.Linear fail with RecursionError in the AOTAutograd joint graph 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.

  1. Rebuilt Max/Min nodes that Inductor cannot lower ([DTensor][compile] view(batch_size, seq_len, -1) feeding a RowwiseParallel linear fails under dynamic=True: mul expected 2 arguments, got 3 #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.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

@pytorch-bot

pytorch-bot Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:

This PR fixes two make_fx bugs that show up with DTensor and dynamic shapes. It
skips a SymNode whose lazy proxy is being forced, falling back through a `prev`
chain on `_SympyExprTrackerValue` (# 201624), and it rebuilds sympy Max/Min as
torch.sym_max/sym_min (# 201838). Recommendation: Needs Discussion. The
description needs updating to match the design, and a forward-side test should
confirm whether the `prev` fallback can create a forward-to-tangent dependency.

Findings (2):

[minor] torch/fx/experimental/proxy_tensor.py:366
The PR description describes a fix that is no longer in the code. It says
`_sym_register` "now passes `derived=True` to `set_proxy_slot`" and that "a
derived SymNode never overwrites an existing `sympy_expr_tracker` entry". At
HEAD there is no `derived` parameter, and every registration still overwrites
the entry. The fix is now the `prev` chain plus `symnodes_being_forced`, skipped
inside `_lookup_sympy_expr`. The "first registration wins" alternatives
paragraph is also written against the old design. PyTorch uses the PR body as
the commit message, so the history would record the wrong mechanism. Rewrite the
"Fix:" and "Agent details" sections to describe the current design.

[minor] torch/fx/experimental/proxy_tensor.py:1620
The fallback in `_lookup_sympy_expr` can pick a tangent's size for a cycle in
the forward graph (low confidence: reasoned through, not run). When the newest
entry is being forced, the lookup walks to `entry.prev`, which is just the
provider registered before it, whatever its source. In an AOTAutograd joint
trace, tangents are tracked after primals but before the forward body, so the
chain for s0 is primal size  tangent size(s)  X. Example: forward `X =
torch.sym_max(m, 1)` (simplifies to s0) on an untracked `m` with expr s0, then
`x.new_zeros(X)`. Forcing X skips X and resolves m to the tangent's sym_size, so
forward `zeros` depends on a tangent and the partitioner fails ("Node  was
invalid, but is output"). Not a regression (main recurses forever), but the fix
only covers the backward-side cycle. Add a forward-side variant to
`test_build_proxy_untracked_symint_no_tangent_dependency` (using `aot_function`,
for the `dedupe_symints` reason in that test's docstring) with `n =
torch.sym_max(m, 1)` passed to `new_zeros`. If it fails, skip tangent-derived
providers, following the "primals get their SymInts set first" rationale at
proxy_tensor.py:338-343, instead of taking `prev` blindly.

Reviewed commit: 2dab055 (NOT the current head 19cbe31)

Review run

🔗 Helpful Links

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

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

❌ 2 New Failures, 10 Unrelated Failures

As of commit 19cbe31 with merge base e68ed49 (image):

🟡 GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:

  • Triviality
    • Changes core make_fx proxy resolution: set_proxy_slot gains derived and skips overwriting tracer.sympy_expr_tracker entries for _sym_register outputs
    • Changes FX node targets for rebuilt Max/Min from _nary_sym_max/_nary_sym_min to torch.sym_max/torch.sym_min in _sympy_handlers
  • Design questions a reviewer would raise
    • Guard only applies when expr in tracer.sympy_expr_tracker; the PR thread already flags a possible remaining recursion when no entry exists yet
    • Which registration wins for a symbol is a tracing-policy choice (PR body notes first-wins regresses tangents), which needs a human call
  • Tests
    • Adds regression tests in test/distributed/tensor/test_dtensor_compile.py and test/test_dynamic_shapes.py, plus three known_graph_breaks_tests entries in test_compiled_autograd.py

reason: not_trivial
Reviewed commit: a2d10e3 (NOT the current head 19cbe31)

Inference job

🐛 Report a wrong verdict

NEW FAILURES - The following jobs have failed:

  • inductor / unit-test / inductor-cpu-test / test (inductor_amx, 5, 7, mt-l-x86iamx-8-64) (gh)
    test/test_ops.py::TestCommonCPU::test_compare_cpu__refs_addcdiv_cpu_float32

    AI verdict: AI verdict: probably not related

    The "failure" is pytest's junitxml reporter crashing with an INTERNALERROR KeyError on node_reporters.pop while finalizing a SKIPPED test. It comes from the PR's stale test/conftest.py (LogXMLReruns.node_reporter builds its keys from string nodeids) running under pytest 9.2.0, which uses NodeId keys. Main has since rewritten node_reporter to let pytest build the key. The suspect changes only make_fx SymInt proxy logic and adds tests, and has no path to the pytest reporting machinery.

    Full reasoning on HUD →

  • inductor / unit-test / inductor-cpu-test / test (inductor_amx, 6, 7, mt-l-x86iamx-8-64) (gh)
    test/test_ops_gradients.py::TestBwdGradientsCPU::test_fn_fail_gradgrad_H_cpu_float64

    AI verdict: AI verdict: infra issue

    The failure is a pytest INTERNALERROR (KeyError in the junitxml plugin's node_reporters.pop, called from conftest's LogXMLReruns) raised on a SKIPPED test. It happens under pytest 9.2.0, while the repo pins pytest==7.3.2, and it hits skipped tests across test_ops and test_ops_gradients in every shard. The suspect only changes make_fx SymInt proxy code and tests, so it cannot affect the pytest version or the XML report writing.

    Full reasoning on HUD →

NEW FAILURES SUPPRESSED BY AI (non-blocking) - The following job failed, but the AI CI Advisor judged the failure not to be evidence against this change:

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

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

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 module: inductor release notes: fx release notes category labels Oct 28, 2026
@aditvenk

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Claude finished @aditvenk's task in 1m 33s —— View job


The fix holds up for both reported failures; there are two small issues, one stale comment and one leftover recursion case I'm not sure about.

PR Review: #202428

Summary

The PR makes derived SymNodes (outputs of _sym_register) stop overwriting existing sympy_expr_tracker entries, which removes the self-referential thunk cycle in #201624. It also maps sympy Max/Min straight to torch.sym_max/torch.sym_min and drops the _nary_* helpers, fixing #201838. No REVIEW.md files apply. I only reviewed the code by reading it: this job's permissions don't allow running Python, so I couldn't try the edge case below.

Code Quality

  • Stale comment drops Add (torch/fx/experimental/proxy_tensor.py:688). The old comment said "sympy Mul and Add are n-ary"; the new one lists only "Mul, Max and Min". Add is still n-ary, still maps to operator.add, and still goes through the same functools.reduce fold. Please write "sympy Add, Mul, Max and Min are n-ary ... (operator.add, operator.mul, torch.sym_max, torch.sym_min)".
  • Recursion may still happen when no entry exists yet (low confidence, not verified) (proxy_tensor.py:375-379). The guard only applies when expr in tracer.sympy_expr_tracker. Suppose an untracked SymNode's symbol was never registered, for example an unbacked u0 created entirely inside disable_proxy_modes_tracing(). A traced op that simplifies back to that symbol (e.g. u // 1) still registers its thunk as sympy_expr_tracker[u0]. Forcing that thunk then resolves the untracked u back to the thunk itself, and you get a RecursionError instead of the clean "is not tracked with proxy" error. This predates the PR and the program has no valid source for u0 anyway, so it isn't a blocker. A tighter rule would cover this case and the one the PR fixes: skip the derived registration whenever one of the op's SymNode args is missing from symnode_tracker, because only an untracked arg can close the cycle. If you'd rather keep the current rule, the new comment should say it only protects an entry that already exists.

Testing

  • New entries are out of order (test/inductor/test_compiled_autograd.py:5577-5582). The three new names sit between test_dtensor_contiguous_... and test_retain_grad. That breaks the alphabetical order for the test_tp_* names, and the shared comment hides which of the three is the odd one out. Please put test_dtensor_unbacked_rebuilt_sym_max_inductor next to the other test_dtensor_* entries and move the two test_tp_* entries to the t position, each with its own inline reason like the neighbouring entries.

Recommendation

Approve, after fixing the stale comment. Regression tests cover both issues, and they also cover the tangent-dependency trap that rules out a simpler "first registration wins" policy. The recursion case above is worth a decision either way but doesn't block.

@aditvenk
aditvenk marked this pull request as ready for review October 28, 2026 19:48
@aditvenk
aditvenk requested a review from aorenste as a code owner October 28, 2026 19:48
@aditvenk
aditvenk requested a review from pianpwk October 28, 2026 19:48
@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Oct 28, 2026
@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Oct 28, 2026
github-actions[bot]

This comment was marked as outdated.

@aditvenk

Copy link
Copy Markdown
Contributor Author

@claude Are the CI failures due to this PR?

@claude

claude Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Claude finished @aditvenk's task in 52s —— View job


No. None of the CI failures come from this PR. Every failing job ran pytest 9.2.0, and pytest crashes inside its own junitxml reporter after the test has already finished, whether the test passed or was skipped.

Details

What the logs show

I downloaded the logs for the 3 jobs Dr. CI lists as "NEW FAILURES". All three fail the same way:

Job Test reported as failing What actually happened
inductor_amx, 3, 7 test_modules.py::TestJitReplaceSubmodule::test_jit_replace_submodule PASSED on all 3 attempts, then INTERNALERROR
inductor_cpp_wrapper, 1, 2 test_torchinductor_opinfo.py::...test_comprehensive_linalg_cross_cuda_uint8 INTERNALERROR after the test
inductor_cpp_wrapper, 2, 2 test_torchinductor_opinfo.py::...test_comprehensive_linalg_cross_cuda_float64 PASSED [27.37s], then INTERNALERROR

Traceback (the same in every job):

platform linux -- Python 3.11.18, pytest-9.2.0, pluggy-1.7.0
...
File "/__w/pytorch/pytorch/test/conftest.py", line 254, in pytest_runtest_logreport
    super().pytest_runtest_logreport(report)
File ".../_pytest/junitxml.py", line 544, in finalize
    reporter = self.node_reporters.pop((node_id, workernode))
INTERNALERROR> KeyError: (NodeId(path='test/inductor/test_torchinductor_opinfo.py', names=('TestInductorOpInfoCUDA', 'test_comprehensive_linalg_cross_cuda_float64'), params=None), None)

test/conftest.py's LogXMLReruns override doesn't work with pytest 9.2.0's junitxml bookkeeping: the first test in each shard triggers the crash, and the run retries it until it is marked "FAILED CONSISTENTLY". Nothing in the logs points to make_fx, proxy_tensor, sym_max or RecursionError. This PR only changes proxy_tensor.py and some tests; it doesn't touch conftest, CI or dependency files.

The 7 inductor_amx failures that the AI advisor already suppressed have the same signature. The inductor_aoti_fallback job is marked unstable on trunk.

What to do

Dr. CI says main fixed this in #202385 by pinning pytest to 9.1.1, but I couldn't confirm that from this checkout. After that fix lands, rebase onto main (or have these jobs re-run on a merge base that includes it) and they should go green. You can also ask for a merge with -i and cite these as infra failures.

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

(Reviewed by me, assisted by AI)


Re-review is opt-in: once you've pushed a fix, click Re-request review next to the reviewer under Reviewers -- new commits alone don't re-notify. Requesting a review

Comment thread torch/fx/experimental/proxy_tensor.py Resolved
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.
@aditvenk
aditvenk force-pushed the fix-dtensor-untracked-symint-rebuild branch from a2d10e3 to 2dab055 Compare October 30, 2026 22:44

@github-actions github-actions Bot 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.

Automated review of 2dab055: nothing blocking; ready for human review.

This PR fixes two make_fx bugs that show up with DTensor and dynamic shapes. It skips a SymNode whose lazy proxy is being forced, falling back through a prev chain on _SympyExprTrackerValue (# 201624), and it rebuilds sympy Max/Min as torch.sym_max/sym_min (# 201838). Recommendation: Needs Discussion. The description needs updating to match the design, and a forward-side test should confirm whether the prev fallback can create a forward-to-tangent dependency.

⚪ 2 non-blocking findings

proxy, obj, tracer.sympy_expr_tracker.get(obj.node.expr)

The PR description describes a fix that is no longer in the code. It says _sym_register "now passes derived=True to set_proxy_slot" and that "a derived SymNode never overwrites an existing sympy_expr_tracker entry". At HEAD there is no derived parameter, and every registration still overwrites the entry. The fix is now the prev chain plus symnodes_being_forced, skipped inside _lookup_sympy_expr. The "first registration wins" alternatives paragraph is also written against the old design. PyTorch uses the PR body as the commit message, so the history would record the wrong mechanism. Rewrite the "Fix:" and "Agent details" sections to describe the current design.


while entry is not None and entry.value.node in tracer.symnodes_being_forced:

The fallback in _lookup_sympy_expr can pick a tangent's size for a cycle in the forward graph (low confidence: reasoned through, not run). When the newest entry is being forced, the lookup walks to entry.prev, which is just the provider registered before it, whatever its source. In an AOTAutograd joint trace, tangents are tracked after primals but before the forward body, so the chain for s0 is primal size tangent size(s) X. Example: forward X = torch.sym_max(m, 1) (simplifies to s0) on an untracked m with expr s0, then x.new_zeros(X). Forcing X skips X and resolves m to the tangent's sym_size, so forward zeros depends on a tangent and the partitioner fails ("Node was invalid, but is output"). Not a regression (main recurses forever), but the fix only covers the backward-side cycle. Add a forward-side variant to test_build_proxy_untracked_symint_no_tangent_dependency (using aot_function, for the dedupe_symints reason in that test's docstring) with n = torch.sym_max(m, 1) passed to new_zeros. If it fails, skip tangent-derived providers, following the "primals get their SymInts set first" rationale at proxy_tensor.py:338-343, instead of taking prev blindly.

This review is AI-generated and advisory. Each new automated review replaces the previous one.

@aditvenk
aditvenk requested a review from aorenste October 30, 2026 22:49
@pytorchgreenlight pytorchgreenlight Bot added GL/superseded GreenLight review is superseded by changes and removed GL/human GreenLight marked as needing human review labels Oct 30, 2026
@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Oct 31, 2026

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

(Reviewed by me, assisted by AI)


Merging is self-service: comment @pytorchbot merge and the bot lands it once required checks pass. Merging your Change | Bot commands

if len(args) == 1 and isinstance(args[0], (list, tuple)):
n_args = (
tuple(
tracer.symnodes_being_forced.add(out.node)

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.

[cleanup] Raise a clear error when a SymInt's proxy computation re-enters itself, instead of recursing until RecursionError:

    if out.node in tracer.symnodes_being_forced:
        raise RuntimeError(f"Cycle while computing the proxy for {out}")
    tracer.symnodes_being_forced.add(out.node)

The fallback can still close a cycle that the skip never sees. When an untracked compound SymInt is resolved outside the forcing window, _build_proxy_for_sym_expr permanently binds it to the newest provider, which can be the derived SymInt computed from it. The cycle then runs through symnode_tracker and never reaches _lookup_sympy_expr:

def f(x):
    with maybe_enable_thunkify():
        with disable_proxy_modes_tracing():
            w = x.shape[0] * 2  # untracked, 2*s0
        X = w // 2  # traced, simplifies to s0
        return x.new_zeros(w), x.new_zeros(X)

make_fx(f, tracing_mode="symbolic")(torch.randn(4))

Resolving w binds it to 2 * X, and X's argument is w, so this recurses forever. Swapping the two new_zeros calls traces fine, so whether tracing succeeds depends on use order. Main recurses in both orders, so this is fine as a follow-up.

A lazy SymInt proxy can still end up depending on itself through
symnode_tracker, where the sympy_expr_tracker skip from the previous
commit never looks. When an untracked compound SymInt is resolved outside
any forcing window, _build_proxy_for_sym_expr() binds it to the newest
provider of its symbols, which can be a SymInt computed from it:

```
w = x.shape[0] * 2  # untracked, 2*s0
half = w // 2       # traced, simplifies to s0
x.new_zeros(w)      # w is rebuilt as 2 * half, and half's operand is w
```

Forcing w forces half, whose operand w is now tracked and mid-force, so
Thunk.force() runs w again and recurses until RecursionError, as on main.
_compute_proxy() now raises "Cycle while computing the proxy for ..." when
it is re-entered for the same SymInt.

This also turns one contrived case that used to finish into this error: a
re-entered computation that resolves further down the provider stack used
to complete by computing the proxy twice, leaving a duplicate graph node.
That case recurses forever on main.

Test Plan:

The new test fails on main and on the previous commit with RecursionError
and passes with this change. Across the DTensor program matrices and the
suites below, the guard fires only in that test.

```
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
python -m pytest test/test_proxy_tensor.py -n 4
python -m pytest test/functorch/test_aotdispatch.py -n 8
```

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

aditvenk commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@claude Are any of the failures on CI caused by this PR?

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Claude finished @aditvenk's task in 50s —— View job


No, none of the CI failures on 19cbe31 come from this PR. Each failing job is pytest 9.2.0 crashing in test/conftest.py's junitxml reporter after a test was SKIPPED, before any of this PR's code runs. Rebasing onto main should fix them, because main has rewritten that reporter.

Details

What the logs show

I downloaded the logs for the 2 jobs Dr. CI lists as "NEW FAILURES", plus one of the cpp_wrapper jobs:

Job Test reported as failing What actually happened
inductor_amx, 5, 7 test_ops.py::TestCommonCPU::test_compare_cpu__refs_addcdiv_cpu_float32 SKIPPED, then INTERNALERROR on all 3 attempts, so it was marked "FAILED CONSISTENTLY"
inductor_amx, 6, 7 test_ops_gradients.py::TestBwdGradientsCPU::test_fn_fail_gradgrad_H_cpu_float64 SKIPPED, then INTERNALERROR (the same thing happens on later test_ops.py skips)
inductor_cpp_wrapper, 1, 2 test_torchinductor_opinfo.py::...test_comprehensive_linalg_cross_cuda_uint8 SKIPPED, then INTERNALERROR

The traceback is the same in every job:

platform linux -- Python 3.11.18, pytest-9.2.0, pluggy-1.7.0
INTERNALERROR>   File "/__w/pytorch/pytorch/test/conftest.py", line 254, in pytest_runtest_logreport
INTERNALERROR> KeyError: (NodeId(path='test/test_ops_gradients.py', names=('TestBwdGradientsCPU', 'test_fn_fail_gradgrad_H_cpu_float64'), params=None), None)

No log mentions proxy_tensor.py, RecursionError, sym_max or "is not tracked with proxy". This PR doesn't touch test/conftest.py, CI files or dependency pins.

Root cause

On this branch, LogXMLReruns.node_reporter in test/conftest.py builds its own (nodeid, workernode) key from a string nodeid. pytest 9.2.0 keys node_reporters by NodeId objects, so finalize()'s pop raises KeyError. Current origin/main has rewritten node_reporter to call super().node_reporter(report), which lets pytest build the key. git diff HEAD origin/main -- test/conftest.py shows the change.

The other failing jobs have the same crash or are known trunk issues: one inductor_amx job was already suppressed by the advisor, the other inductor_amx and cpp_wrapper jobs are marked flaky on trunk, and inductor_aoti_fallback is marked unstable.

What to do

Rebase onto main and re-run CI, or merge with @pytorchbot merge -i and cite these as infra failures.

@aditvenk

aditvenk commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Nov 3, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@aditvenk

aditvenk commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@claude Are these failures due to this PR? #202428 (comment)

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Claude finished @aditvenk's task in 37s —— View job


No. None of the 3 jobs that blocked the merge come from this PR. They are the same pytest 9.2.0 / test/conftest.py junitxml crash I described in my last reply. The merge failed because CI still hasn't re-run on 19cbe31: the only inductor run is 41556944025, from before the fix reached main. Rebase onto current main, or merge with @pytorchbot merge -i.

Details
  • Get CI status for the current head
  • Read the failing job logs
  • Answer

The jobs that blocked the merge

pytorchmergebot named these 3:

  • inductor_amx, 5, 7: test_ops.py::...test_compare_cpu__refs_addcdiv_cpu_float32
  • inductor_amx, 6, 7: test_ops_gradients.py::...test_fn_fail_gradgrad_H_cpu_float64
  • inductor_cpp_wrapper, 1, 2: test_torchinductor_opinfo.py::...test_comprehensive_linalg_cross_cuda_uint8

I re-checked the inductor_cpp_wrapper log. Each of the 3 attempts ends with the same crash, and the run then reports the test as FAILED CONSISTENTLY:

platform linux -- Python 3.11.18, pytest-9.2.0, pluggy-1.7.0
INTERNALERROR> KeyError: (NodeId(path='test/inductor/test_torchinductor_opinfo.py', names=('TestInductorOpInfoCUDA', 'test_comprehensive_linalg_cross_cuda_uint8'), params=None), None)

The log never mentions proxy_tensor, RecursionError or "not tracked with proxy". I didn't re-download the two inductor_amx logs in this run. My previous reply checked them and found the same crash on skipped tests, and Dr. CI's AI verdict for both says the same.

Why it happens

pytest 9.2.0 keys node_reporters by NodeId objects. This branch's LogXMLReruns.node_reporter in test/conftest.py builds the key from a string nodeid, so finalize() fails its lookup. git diff HEAD origin/main shows main has changed both test/conftest.py and .ci/docker/requirements-ci.txt. This PR touches neither file.

What to do

  • Rebase onto main and let CI re-run (needs a push to the branch, which I can't do here), or
  • @pytorchbot merge -i, citing these as the pytest 9.2.0 infra failure. The other failures are already marked flaky, unstable or suppressed by the AI advisor.

@aditvenk

aditvenk commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

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/trunk Trigger trunk jobs on your pull request GL/superseded GreenLight review is superseded by changes Merged module: inductor ready for review Automated review passed, ready for a final review by a maintainer. release notes: fx release notes category

Projects

None yet

4 participants