Repository navigation
[functionalization] Hand _make_wrapper_subclass the storage size it already knows - #193416
anijain2305 wants to merge 19 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/193416
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (1 Unrelated Failure)As of commit bb7599b with merge base 411c2b5 ( BROKEN TRUNK - The following job failed but were present on the merge base:👉 Rebase onto the `viable/strict` branch to avoid these failures
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
…lready knows Every FunctionalTensor wraps an inner tensor by calling _make_wrapper_subclass with the inner tensor's sizes and strides. When the caller does not supply storage_size, that helper computes it with computeStorageNbytes, which walks the dimensions doing symbolic arithmetic - a sub, a mul and an add per dimension - to size a storage that exists only to track aliasing between subclasses; the data pointer is not even valid. The inner tensor already knows its storage size, so pass it. This is the same thing NestedTensor does (torch/nested/_internal/nested_tensor.py passes storage_size=values.untyped_storage().size()), and mirroring elem is if anything the more faithful value: the wrapper is meant to shadow elem, whereas the recomputed number describes only the extent the sizes and strides reach. On a 4d symbolic tensor the call goes from 144us to 21us. Over a UMA cold compile (fairchem uma-s-1p2, 1000 atoms, dynamic=True) with 4268 wrapper creations, time in FunctionalTensor.__new__ drops from 1.04s to 0.11s, and about 30k symbolic operations disappear from the compile. End to end, as the union of top-level chromium events, over interleaved pairs: pair 1: baseline 40.26s with storage_size 39.78s pair 2: baseline 40.05s with storage_size 38.16s pair 3: baseline 39.49s with storage_size 38.07s 39.93s -> 38.67s, -3.2%. Sparse inners keep the old path, as they already do for strides and storage_offset. Test plan: ``` python test/inductor/test_torchinductor_dynamic_shapes.py -k cuda python test/test_functionalization.py ``` Failure sets identical to a run with the change reverted (this aarch64 host has pre-existing failures). This PR was authored with the assistance of an AI coding agent. ghstack-source-id: bf3bf5d Pull-Request: #193416
[ghstack-poisoned]
…lready knows Every FunctionalTensor wraps an inner tensor by calling _make_wrapper_subclass with the inner tensor's sizes and strides. When the caller does not supply storage_size, that helper computes it with computeStorageNbytes, which walks the dimensions doing symbolic arithmetic - a sub, a mul and an add per dimension - to size a storage that exists only to track aliasing between subclasses; the data pointer is not even valid. The inner tensor already knows its storage size, so pass it. This is the same thing NestedTensor does (torch/nested/_internal/nested_tensor.py passes storage_size=values.untyped_storage().size()), and mirroring elem is if anything the more faithful value: the wrapper is meant to shadow elem, whereas the recomputed number describes only the extent the sizes and strides reach. On a 4d symbolic tensor the call goes from 144us to 21us. Over one model's cold compile with dynamic=True, across 4268 wrapper creations, time in FunctionalTensor.__new__ drops from 1.04s to 0.11s, and about 30k symbolic operations disappear from the compile. End to end, as the union of top-level chromium events, over interleaved pairs: pair 1: baseline 40.26s with storage_size 39.78s pair 2: baseline 40.05s with storage_size 38.16s pair 3: baseline 39.49s with storage_size 38.07s 39.93s -> 38.67s, -3.2%. Sparse inners keep the old path, as they already do for strides and storage_offset. Test plan: ``` python test/inductor/test_torchinductor_dynamic_shapes.py -k cuda python test/test_functionalization.py ``` Failure sets identical to a run with the change reverted (this aarch64 host has pre-existing failures). This PR was authored with the assistance of an AI coding agent. ghstack-source-id: 073906b Pull-Request: #193416
…lready knows Every FunctionalTensor wraps an inner tensor by calling _make_wrapper_subclass with the inner tensor's sizes and strides. When the caller does not supply storage_size, that helper computes it with computeStorageNbytes, which walks the dimensions doing symbolic arithmetic - a sub, a mul and an add per dimension - to size a storage that exists only to track aliasing between subclasses; the data pointer is not even valid. The inner tensor already knows its storage size, so pass it. This is the same thing NestedTensor does (torch/nested/_internal/nested_tensor.py passes storage_size=values.untyped_storage().size()), and mirroring elem is if anything the more faithful value: the wrapper is meant to shadow elem, whereas the recomputed number describes only the extent the sizes and strides reach. On a 4d symbolic tensor the call goes from 144us to 21us. Over one model's cold compile with dynamic=True, across 4268 wrapper creations, time in FunctionalTensor.__new__ drops from 1.04s to 0.11s, and about 30k symbolic operations disappear from the compile. End to end, as the union of top-level chromium events, over interleaved pairs: pair 1: baseline 40.26s with storage_size 39.78s pair 2: baseline 40.05s with storage_size 38.16s pair 3: baseline 39.49s with storage_size 38.07s 39.93s -> 38.67s, -3.2%. Sparse inners keep the old path, as they already do for strides and storage_offset. Test plan: ``` python test/inductor/test_torchinductor_dynamic_shapes.py -k cuda python test/test_functionalization.py ``` Failure sets identical to a run with the change reverted (this aarch64 host has pre-existing failures). This PR was authored with the assistance of an AI coding agent. ghstack-source-id: 073906b Pull-Request: #193416
[ghstack-poisoned]
…lready knows Every FunctionalTensor wraps an inner tensor by calling _make_wrapper_subclass with the inner tensor's sizes and strides. When the caller does not supply storage_size, that helper computes it with computeStorageNbytes, which walks the dimensions doing symbolic arithmetic - a sub, a mul and an add per dimension - to size a storage that exists only to track aliasing between subclasses; the data pointer is not even valid. The inner tensor already knows its storage size, so pass it. This is the same thing NestedTensor does (torch/nested/_internal/nested_tensor.py passes storage_size=values.untyped_storage().size()), and mirroring elem is if anything the more faithful value: the wrapper is meant to shadow elem, whereas the recomputed number describes only the extent the sizes and strides reach. On a 4d symbolic tensor the call goes from 144us to 21us. Over one model's cold compile with dynamic=True, across 4268 wrapper creations, time in FunctionalTensor.__new__ drops from 1.04s to 0.11s, and about 30k symbolic operations disappear from the compile. End to end, as the union of top-level chromium events, over interleaved pairs: pair 1: baseline 40.26s with storage_size 39.78s pair 2: baseline 40.05s with storage_size 38.16s pair 3: baseline 39.49s with storage_size 38.07s 39.93s -> 38.67s, -3.2%. Sparse inners keep the old path, as they already do for strides and storage_offset. Test plan: ``` python test/inductor/test_torchinductor_dynamic_shapes.py -k cuda python test/test_functionalization.py ``` Failure sets identical to a run with the change reverted (this aarch64 host has pre-existing failures). This PR was authored with the assistance of an AI coding agent. ghstack-source-id: 14550fc Pull-Request: #193416
[ghstack-poisoned]
…lready knows Every FunctionalTensor wraps an inner tensor by calling _make_wrapper_subclass with the inner tensor's sizes and strides. When the caller does not supply storage_size, that helper computes it with computeStorageNbytes, which walks the dimensions doing symbolic arithmetic - a sub, a mul and an add per dimension - to size a storage that exists only to track aliasing between subclasses; the data pointer is not even valid. The inner tensor already knows its storage size, so pass it. This is the same thing NestedTensor does (torch/nested/_internal/nested_tensor.py passes storage_size=values.untyped_storage().size()), and mirroring elem is if anything the more faithful value: the wrapper is meant to shadow elem, whereas the recomputed number describes only the extent the sizes and strides reach. On a 4d symbolic tensor the call goes from 144us to 21us. Over one model's cold compile with dynamic=True, across 4268 wrapper creations, time in FunctionalTensor.__new__ drops from 1.04s to 0.11s, and about 30k symbolic operations disappear from the compile. End to end, as the union of top-level chromium events, over interleaved pairs: pair 1: baseline 40.26s with storage_size 39.78s pair 2: baseline 40.05s with storage_size 38.16s pair 3: baseline 39.49s with storage_size 38.07s 39.93s -> 38.67s, -3.2%. Sparse inners keep the old path, as they already do for strides and storage_offset. Test plan: ``` python test/inductor/test_torchinductor_dynamic_shapes.py -k cuda python test/test_functionalization.py ``` Failure sets identical to a run with the change reverted (this aarch64 host has pre-existing failures). This PR was authored with the assistance of an AI coding agent. ghstack-source-id: e69fa3a Pull-Request: #193416
Merge failedReason: 2 mandatory check(s) failed. The first few are:
Dig deeper by viewing the failures on hud |
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
Failing jobs: linux-jammy-cuda13.0-py3.10-gcc11 / test (pr_time_benchmarks, 1, 1, mt-l-bx86iavx512-94-344-t4-8) linux-jammy-cuda13.2-py3.10-gcc11 / test (pr_time_benchmarks, 1, 1, mt-l-bx86iavx512-94-344-t4-8) Failing command: python benchmarks/dynamo/pr_time_benchmarks/check_results.py benchmarks/dynamo/pr_time_benchmarks/expected_results.csv /__w/pytorch/pytorch/test/test-reports/pr_time_benchmarks_results.csv /__w/pytorch/pytorch/test/test-reports/new_expected_results.csv Failing benchmarks: (add_loop_inductor_dynamic_gpu, compile_time_instruction_count) (update_hint_regression, compile_time_instruction_count) (mm_loop_inductor_dynamic_gpu, compile_time_instruction_count) Errors: add_loop_inductor_dynamic_gpu was 19.53% lower than expected. update_hint_regression was 10.55% lower than expected. mm_loop_inductor_dynamic_gpu was 22.57% lower than expected. The approved FunctionalTensor change avoids symbolic storage-size arithmetic. These compile instruction reductions reproduced in both CUDA 13.0 and CUDA 13.2 jobs, so refresh the three out-of-tolerance baselines with the CUDA 13.2 generated expected results. Test Plan: ```text lintrunner -a ``` AI assistance: This CI follow-up commit was authored with an AI assistant. [ghstack-poisoned]
…lready knows Every FunctionalTensor wraps an inner tensor by calling _make_wrapper_subclass with the inner tensor's sizes and strides. When the caller does not supply storage_size, that helper computes it with computeStorageNbytes, which walks the dimensions doing symbolic arithmetic - a sub, a mul and an add per dimension - to size a storage that exists only to track aliasing between subclasses; the data pointer is not even valid. The inner tensor already knows its storage size, so pass it. This is the same thing NestedTensor does (torch/nested/_internal/nested_tensor.py passes storage_size=values.untyped_storage().size()), and mirroring elem is if anything the more faithful value: the wrapper is meant to shadow elem, whereas the recomputed number describes only the extent the sizes and strides reach. On a 4d symbolic tensor the call goes from 144us to 21us. Over one model's cold compile with dynamic=True, across 4268 wrapper creations, time in FunctionalTensor.__new__ drops from 1.04s to 0.11s, and about 30k symbolic operations disappear from the compile. End to end, as the union of top-level chromium events, over interleaved pairs: pair 1: baseline 40.26s with storage_size 39.78s pair 2: baseline 40.05s with storage_size 38.16s pair 3: baseline 39.49s with storage_size 38.07s 39.93s -> 38.67s, -3.2%. Sparse inners keep the old path, as they already do for strides and storage_offset. Taking the size from elem rather than deriving it exposed a latent bug in _build_proxy_for_sym_expr, which CI caught. A size derived through SymInt ops picks up proxies for its intermediates on the way; one taken from an existing tensor may not have them, so the expression has to be rebuilt from sympy - and sympy Mul and Add are n-ary while the handlers they map to, operator.mul and operator.add, take exactly two arguments. A product like s0*s1*s2 then failed with "mul expected 2 arguments, got 3". Fold into a chain of binary ops instead. The fold has to happen where the expression is rebuilt, not by registering a variadic wrapper as the handler, because the handler becomes the fx node's target and that has to stay a real operator - inductor rejects anything else with "is not an OpOverload". One more consequence, which CI caught: translation validation runs when guards are produced, but bisection - the diagnostic that says which node introduced a bad guard - was only wired into the tracing side, because until now a contradiction like this always made tracing itself throw. Deriving the storage size was part of what made it throw; without it, tracing succeeds and the contradiction surfaces at guard production, where nothing called bisect, so test_trigger_bisect_on_error got a plain ValidationException. Give build_guards the same treatment the tracing path already has. This is a gap independent of this change - a validation failure found at guard production never got bisected - and fixing it keeps the test passing on its original expected output rather than relaxing what it asserts. Golden graphs also needed updating. Those symbolic operations no longer happen, so fx node name counters land lower (add_3 -> add, sym_size_int_1 -> sym_size_int) and one node moves ahead of another it does not depend on. Same ops, same shapes, same returns; the diffs are renames and one reorder. Test plan: ``` python test/inductor/test_torchinductor_dynamic_shapes.py -k cuda python test/test_functionalization.py python test/test_proxy_tensor.py python test/functorch/test_aotdispatch.py -k test_invalid_dupe_fake python test/dynamo/test_subclasses.py -k test_tensor_subclass_TwoTensor_automatic_dynamic_shapes python test/test_dynamic_shapes.py -k test_unbacked_contiguous python test/inductor/test_auto_functionalize.py -k test_alias2_dynamic ``` The four tests CI flagged now pass. test_proxy_tensor is 3667 tests with the same single pre-existing failure as a run with the change reverted, and no errors. Other failure sets are identical to a reverted run (this aarch64 host has pre-existing failures). This PR was authored with the assistance of an AI coding agent. ghstack-source-id: c97d41a Pull-Request: #193416
|
|
||
|
|
||
| add_loop_inductor_dynamic_gpu,compile_time_instruction_count,46210000000,0.1 | ||
| add_loop_inductor_dynamic_gpu,compile_time_instruction_count,37180000000,0.1 |
There was a problem hiding this comment.
This hunk was LLM-generated by mergedog in commit be5e07cb6065. Review that commit for context and justification.
Note
This PR is being shepherded by mergedog, an automation tool run by a maintainer. It watches CI and may push fixes; the PR author does not need to act unless a maintainer asks.
|
|
||
|
|
||
| update_hint_regression,compile_time_instruction_count,2074000000,0.1 | ||
| update_hint_regression,compile_time_instruction_count,1855000000,0.1 |
There was a problem hiding this comment.
This hunk was LLM-generated by mergedog in commit be5e07cb6065. Review that commit for context and justification.
Note
This PR is being shepherded by mergedog, an automation tool run by a maintainer. It watches CI and may push fixes; the PR author does not need to act unless a maintainer asks.
|
|
||
|
|
||
| mm_loop_inductor_dynamic_gpu,compile_time_instruction_count,10670000000,0.1 | ||
| mm_loop_inductor_dynamic_gpu,compile_time_instruction_count,8262000000,0.1 |
There was a problem hiding this comment.
This hunk was LLM-generated by mergedog in commit be5e07cb6065. Review that commit for context and justification.
Note
This PR is being shepherded by mergedog, an automation tool run by a maintainer. It watches CI and may push fixes; the PR author does not need to act unless a maintainer asks.
|
@pytorchbot merge |
Merge startedYour 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 |
mergedog handoffNote This PR is being shepherded by mergedog, an automation tool run by a maintainer. It watches CI and may push fixes; the PR author does not need to act unless a maintainer asks. All CI is green (or skipped). Ready for human review and Current PR head: Autonomous changes pushed
CI notes at handoffmergedog is treating these still-failing checks as unrelated/spurious. Please verify before merging:
Latest Dr. CI summary## :link: Helpful Links
### :test_tube: See artifacts and rendered test results at [hud.pytorch.org/pr/193416](https://hud.pytorch.org/pr/193416)
* :page_facing_up: Preview [Python docs built from this PR](https://docs-preview.pytorch.org/pytorch/pytorch/193416/index.html)
* :page_facing_up: Preview [C++ docs built from this PR](https://docs-preview.pytorch.org/pytorch/pytorch/193416/cppdocs/index.html)
* :question: Need help or want to give feedback on the CI? Visit the [bot commands wiki](https://github.com/pytorch/pytorch/wiki/Bot-commands)
Note: Links to docs will display an error until the docs builds have been completed.
## :hourglass_flowing_sand: 1 Pending, 1 Unrelated Failure
As of commit bb7599b07cbf5910bdeb6046beae93750cb97ceb with merge base 411c2b585644cd8680d213dbda72a1560cd8fdc5 (<sub><sub><img alt="image" width=70 src="https://img.shields.io/date/1786803931?label=&color=FFFFFF&style=flat-square"></sub></sub>):
<details ><summary><b>BROKEN TRUNK</b> - The following job failed but were present on the merge base:</summary><p>👉 <b>Rebase onto the `viable/strict` branch to avoid these failures</b></p><p>
* [torchtitan-test / torchtitan-x-pytorch-test / test (torchtitan_models_integration, 1, 1, mt-l-x86aavx2-189-704-a10g-8)](https://hud.pytorch.org/pr/pytorch/pytorch/193416#95087736745) ([gh](https://github.com/pytorch/pytorch/actions/runs/31914312600/job/95087736745)) ([trunk failure](https://hud.pytorch.org/pytorch/pytorch/commit/411c2b585644cd8680d213dbda72a1560cd8fdc5#95029901212))
`RuntimeError: 4 integration test(s) failed:`
</p></details>
This comment was automatically generated by Dr. CI and updates every 15 minutes.During shepherding, the configured LLM was invoked 2 times. If any CI shows red, it judged that failure unrelated to this PR's changes — please verify below before merging. Session 1 — fix-CI (2026-08-15T23:14:39+00:00)
LLM transcriptSession 2 — fix-CI (2026-08-16T00:23:28+00:00)
LLM transcript |
…lready knows (pytorch#193416) Every FunctionalTensor wraps an inner tensor by calling _make_wrapper_subclass with the inner tensor's sizes and strides. When the caller does not supply storage_size, that helper computes it with computeStorageNbytes, which walks the dimensions doing symbolic arithmetic - a sub, a mul and an add per dimension - to size a storage that exists only to track aliasing between subclasses; the data pointer is not even valid. The inner tensor already knows its storage size, so pass it. This is the same thing NestedTensor does (torch/nested/_internal/nested_tensor.py passes storage_size=values.untyped_storage().size()), and mirroring elem is if anything the more faithful value: the wrapper is meant to shadow elem, whereas the recomputed number describes only the extent the sizes and strides reach. On a 4d symbolic tensor the call goes from 144us to 21us. Over one model's cold compile with dynamic=True, across 4268 wrapper creations, time in FunctionalTensor.__new__ drops from 1.04s to 0.11s, and about 30k symbolic operations disappear from the compile. End to end, as the union of top-level chromium events, over interleaved pairs: pair 1: baseline 40.26s with storage_size 39.78s pair 2: baseline 40.05s with storage_size 38.16s pair 3: baseline 39.49s with storage_size 38.07s 39.93s -> 38.67s, -3.2%. Sparse inners keep the old path, as they already do for strides and storage_offset. Test plan: ``` python test/inductor/test_torchinductor_dynamic_shapes.py -k cuda python test/test_functionalization.py ``` Failure sets identical to a run with the change reverted (this aarch64 host has pre-existing failures). This PR was authored with the assistance of an AI coding agent. Pull Request resolved: pytorch#193416 Approved by: https://github.com/Skylion007, https://github.com/zou3519 ghstack dependencies: pytorch#193159, pytorch#193161
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.
…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
…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
…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
Stack from ghstack (oldest at bottom):
Every FunctionalTensor wraps an inner tensor by calling
_make_wrapper_subclass with the inner tensor's sizes and strides. When the
caller does not supply storage_size, that helper computes it with
computeStorageNbytes, which walks the dimensions doing symbolic arithmetic - a
sub, a mul and an add per dimension - to size a storage that exists only to
track aliasing between subclasses; the data pointer is not even valid.
The inner tensor already knows its storage size, so pass it. This is the same
thing NestedTensor does (torch/nested/_internal/nested_tensor.py passes
storage_size=values.untyped_storage().size()), and mirroring elem is if anything
the more faithful value: the wrapper is meant to shadow elem, whereas the
recomputed number describes only the extent the sizes and strides reach.
On a 4d symbolic tensor the call goes from 144us to 21us. Over one model's cold
compile with dynamic=True, across 4268 wrapper creations, time in
FunctionalTensor.new drops from 1.04s to 0.11s, and about 30k symbolic
operations disappear from the compile. End to end, as the union of top-level
chromium events, over interleaved pairs:
pair 1: baseline 40.26s with storage_size 39.78s
pair 2: baseline 40.05s with storage_size 38.16s
pair 3: baseline 39.49s with storage_size 38.07s
39.93s -> 38.67s, -3.2%.
Sparse inners keep the old path, as they already do for strides and
storage_offset.
Test plan:
Failure sets identical to a run with the change reverted (this aarch64 host has
pre-existing failures).
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 @azahed98