Skip to content

Keep saved-activation strides symbolic under dynamic shapes - #194420

Closed
laithsakka wants to merge 13 commits into
gh/laithsakka/484/basefrom
gh/laithsakka/484/head
Closed

laithsakka wants to merge 13 commits into
gh/laithsakka/484/basefrom
gh/laithsakka/484/head

Conversation

@laithsakka

@laithsakka laithsakka commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Problem

Inductor can give a saved activation a different layout than the backward
graph's placeholder carries (layout optimization, comprehensive padding), so
AOTAutograd restrides the placeholder to match what the forward will produce.

Inductor reports those strides as sympy expressions, but
set_tracing_context_output_strides collapsed them with evaluate_symexpr,
substituting the current hints. The resulting constant got baked into the
placeholder via as_strided, so it was only valid for the first call's sizes:
with pad_dynamic_shapes the stride freezes at the first hint (128*112 =
14336) and the next call dies in assert_size_stride with
stride 24576==14336 at dim=0.

Two smaller problems in the same block: the comparison was hint-based
(guard_or_true(ph_arg.stride()[k] != int(real_stride[k]))), which specialized
the placeholder's dynamic dims just by asking and needed suppress_guards() to
hide it; and the int() cast threw on unbacked symbols.

Approach

Keep the stride symbolic. Always use deserialize_symexpr, which rebuilds
the printed expression as a SymInt still referencing the shape symbols.
Previously only fakify_first_call did this.

Resolve every symbol that can appear. deserialize_symexpr looks symbols up
lazily via name_to_symbol, preserving each one's scalar type and using
_NO_HINT where there is no hint, so unbacked and nested-tensor symbols work
instead of raising NameError. It creates each symbol's FX placeholder / z3
var, hence @record_shapeenv_event(): translation validation replays onto a
fresh env and would otherwise fail with Node sN not found in name_to_node.

Print Max/Min symbolically. SymExprPrinter now emits
torch.sym_max/torch.sym_min. Builtin max() picks a branch by evaluating
a > b, which installs a guard and collapses the expression this change exists
to keep symbolic. Shared with ShapeGuardPythonPrinter, which already did it.

Compare proof-only. not statically_known_true(ph_stride == inductor_stride[k])
— restride unless equality is provable. Hints are only ever used to disprove, so
no guard is installed and an incidental match at the current sizes is not
mistaken for equality. This removes both suppress_guards() and the int() cast.

Cleanups. Delete evaluate_symexpr, dead once nothing collapses strides.
Rename real_stride → inductor_stride: it is inductor's IR layout expression,
and this path runs at compile time over FakeTensors. Widen stride annotations
from int to IntLikeType. Drop the stale claim that layout optimization is
disabled for dynamic shapes.

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 21, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (2 Unrelated Failures)

As of commit dbbea53 with merge base cdd22ad (image):

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

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

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

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

@laithsakka
laithsakka marked this pull request as draft August 21, 2026 23:30
[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added the release notes: fx release notes category label Aug 21, 2026
laithsakka added a commit that referenced this pull request Aug 21, 2026
[ghstack-poisoned]
laithsakka added a commit that referenced this pull request Aug 22, 2026
@laithsakka
laithsakka marked this pull request as ready for review August 24, 2026 16:41
@laithsakka
laithsakka marked this pull request as draft August 24, 2026 19:04
@laithsakka laithsakka added the keep-going Don't stop on first failure, keep running tests until the end label Aug 24, 2026
[ghstack-poisoned]
laithsakka added a commit that referenced this pull request Aug 24, 2026
[ghstack-poisoned]
laithsakka added a commit that referenced this pull request Aug 24, 2026
[ghstack-poisoned]
laithsakka added a commit that referenced this pull request Aug 25, 2026
[ghstack-poisoned]
laithsakka added a commit that referenced this pull request Aug 25, 2026
laithsakka added a commit that referenced this pull request Aug 25, 2026
laithsakka added a commit that referenced this pull request Aug 26, 2026
laithsakka added a commit that referenced this pull request Aug 26, 2026
@laithsakka

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 Aug 27, 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

Merge failed

Reason: Command git -C /home/runner/work/pytorch/pytorch cherry-pick -x 4b35b29eba5a88e44adb1e914be6062e37479cd3 returned non-zero exit code 1

Auto-merging test/test_dynamic_shapes.py
CONFLICT (content): Merge conflict in test/test_dynamic_shapes.py
Auto-merging torch/_functorch/_aot_autograd/runtime_wrappers.py
error: could not apply 4b35b29eba5...  Keep saved-activation strides symbolic under dynamic shapes
hint: After resolving the conflicts, mark them with
hint: "git add/rm <pathspec>", then run
hint: "git cherry-pick --continue".
hint: You can instead skip this commit with "git cherry-pick --skip".
hint: To abort and get back to the state before "git cherry-pick",
hint: run "git cherry-pick --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
Details for Dev Infra team Raised by workflow job

[ghstack-poisoned]
laithsakka added a commit that referenced this pull request Aug 29, 2026
[ghstack-poisoned]
laithsakka added a commit that referenced this pull request Aug 31, 2026
[ghstack-poisoned]
laithsakka added a commit that referenced this pull request Sep 1, 2026
@laithsakka

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

bobrenjc93 added a commit that referenced this pull request Sep 4, 2026
…tandalone source

`aot_autograd.compile_to_python` splices AOTAutograd's codegen'd runtime-wrapper
source around the inner Inductor call, but refused a joint forward+backward, so
`torch.compiler.precompile(..., training=True)` fell back to a pickled bundle.
This composes the training case: `compile_to_python` gains a `grad_enabled`
flag that runs the capture pass under `enable_grad` so requires-grad inputs
produce the joint, and `torch.compiler.precompile` passes its `training` flag
through.

AOTAutograd already codegens the backward prologue, epilogue and
`compiled_function_backward` but not the `torch.autograd.Function` holding
them, so the composer emits a `_CompiledFunction` mirroring the runtime class's
attributes; its `_lazy_backward_info` raises so compiled autograd refuses a
source artifact loudly. `_capture_autograd_specs` records the spec during
capture, tagged with the wrappers' TracingContext `origin_id`;
`_select_training_spec` refuses anything but one match.

Ordering matters: layout optimization may return channels-last saved
activations, so the backward must lower against the strides the forward chose.
The forward lowers first, `_restride_backward_placeholders` rewrites the saved
activations' `node.meta["val"]` from the forward's `output_strides` (a
symbolic stride is rebuilt over the shape symbols with `deserialize_symexpr`
and compared proof-only, as `_aot_stage2b_bw_compile` does since #194420; a
symbol the shape env never created refuses), then the backward lowers with
`is_backward=True`. `is_inference` is no longer hardcoded:
`_graph_differentiates` looks for a `convolution_backward` call node, since a
make_fx trace through `.backward()` has no joint but is not inference.

`namespace_module_names` renames each spliced module's top-level names and
replaces the dynamo tracer's copy; helpers come through `standalone_runtime`; baked metadata types are
imported from their defining modules.
`output_alias_wrapper` and `mutation_epilogue` are spliced,
`debug_assert_wrapper` is dropped, and synthetic base, dedup, functionalized
RNG, tensor subclasses, BackwardState, an interposed InductorWrapper,
inlineable saved_tensors_hooks, and a forward output stride naming a symbol
the shape env never minted, are refused rather than mis-rendered.

User-visible: a refused subgraph now warns with the reason, and the artifact
header names each subgraph that stays pickled and why.

Test Plan:

```
python test/functorch/test_compile_to_python.py
python test/inductor/test_compile_to_python.py
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_precompile_package.py
python test/dynamo/test_guard_serialization.py
```

Tests check served gradients against eager (aliased outputs, input mutation,
dynamic dims, a conv net under forced layout optimization), the restride, each
refusal, and an exec in a fresh process importing only torch.

Authored with an AI assistant.

ghstack-source-id: 2be1803
Pull-Request: #195361
bobrenjc93 added a commit that referenced this pull request Sep 5, 2026
…tandalone source

`aot_autograd.compile_to_python` splices AOTAutograd's codegen'd runtime-wrapper
source around the inner Inductor call, but refused a joint forward+backward, so
`torch.compiler.precompile(..., training=True)` fell back to a pickled bundle.
This composes the training case: `compile_to_python` gains a `grad_enabled`
flag that runs the capture pass under `enable_grad` so requires-grad inputs
produce the joint, and `torch.compiler.precompile` passes its `training` flag
through.

AOTAutograd already codegens the backward prologue, epilogue and
`compiled_function_backward` but not the `torch.autograd.Function` holding
them, so the composer emits a `_CompiledFunction` mirroring the runtime class's
attributes; its `_lazy_backward_info` raises so compiled autograd refuses a
source artifact loudly. `_capture_autograd_specs` records the spec during
capture, tagged with the wrappers' TracingContext `origin_id`;
`_select_training_spec` refuses anything but one match.

Ordering matters: layout optimization may return channels-last saved
activations, so the backward must lower against the strides the forward chose.
The forward lowers first, `_restride_backward_placeholders` rewrites the saved
activations' `node.meta["val"]` from the forward's `output_strides` (a
symbolic stride is rebuilt over the shape symbols with `deserialize_symexpr`
and compared proof-only, as `_aot_stage2b_bw_compile` does since #194420; a
symbol the shape env never created refuses), then the backward lowers with
`is_backward=True`. `is_inference` is no longer hardcoded:
`_graph_differentiates` looks for a `convolution_backward` call node, since a
make_fx trace through `.backward()` has no joint but is not inference.

`namespace_module_names` renames each spliced module's top-level names and
replaces the dynamo tracer's copy; helpers come through `standalone_runtime`; baked metadata types are
imported from their defining modules.
`output_alias_wrapper` and `mutation_epilogue` are spliced,
`debug_assert_wrapper` is dropped, and synthetic base, dedup, functionalized
RNG, tensor subclasses, BackwardState, an interposed InductorWrapper,
inlineable saved_tensors_hooks, and a forward output stride naming a symbol
the shape env never minted, are refused rather than mis-rendered.

User-visible: a refused subgraph now warns with the reason, and the artifact
header names each subgraph that stays pickled and why.

Test Plan:

```
python test/functorch/test_compile_to_python.py
python test/inductor/test_compile_to_python.py
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_precompile_package.py
python test/dynamo/test_guard_serialization.py
```

Tests check served gradients against eager (aliased outputs, input mutation,
dynamic dims, a conv net under forced layout optimization), the restride, each
refusal, and an exec in a fresh process importing only torch.

Authored with an AI assistant.

ghstack-source-id: abfea07
Pull-Request: #195361
bobrenjc93 added a commit that referenced this pull request Sep 5, 2026
…tandalone source

`aot_autograd.compile_to_python` splices AOTAutograd's codegen'd runtime-wrapper
source around the inner Inductor call, but refused a joint forward+backward, so
`torch.compiler.precompile(..., training=True)` fell back to a pickled bundle.
This composes the training case: `compile_to_python` gains a `grad_enabled`
flag that runs the capture pass under `enable_grad` so requires-grad inputs
produce the joint, and `torch.compiler.precompile` passes its `training` flag
through.

AOTAutograd already codegens the backward prologue, epilogue and
`compiled_function_backward` but not the `torch.autograd.Function` holding
them, so the composer emits a `_CompiledFunction` mirroring the runtime class's
attributes; its `_lazy_backward_info` raises so compiled autograd refuses a
source artifact loudly. `_capture_autograd_specs` records the spec during
capture, tagged with the wrappers' TracingContext `origin_id`;
`_select_training_spec` refuses anything but one match.

Ordering matters: layout optimization may return channels-last saved
activations, so the backward must lower against the strides the forward chose.
The forward lowers first, `_restride_backward_placeholders` rewrites the saved
activations' `node.meta["val"]` from the forward's `output_strides` (a
symbolic stride is rebuilt over the shape symbols with `deserialize_symexpr`
and compared proof-only, as `_aot_stage2b_bw_compile` does since #194420; a
symbol the shape env never created refuses), then the backward lowers with
`is_backward=True`. `is_inference` is no longer hardcoded:
`_graph_differentiates` looks for a `convolution_backward` call node, since a
make_fx trace through `.backward()` has no joint but is not inference.

`namespace_module_names` renames each spliced module's top-level names and
replaces the dynamo tracer's copy; helpers come through `standalone_runtime`; baked metadata types are
imported from their defining modules.
`output_alias_wrapper` and `mutation_epilogue` are spliced,
`debug_assert_wrapper` is dropped, and synthetic base, dedup, functionalized
RNG, tensor subclasses, BackwardState, an interposed InductorWrapper,
inlineable saved_tensors_hooks, and a forward output stride naming a symbol
the shape env never minted, are refused rather than mis-rendered.

User-visible: a refused subgraph now warns with the reason, and the artifact
header names each subgraph that stays pickled and why.

Test Plan:

```
python test/functorch/test_compile_to_python.py
python test/inductor/test_compile_to_python.py
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_precompile_package.py
python test/dynamo/test_guard_serialization.py
```

Tests check served gradients against eager (aliased outputs, input mutation,
dynamic dims, a conv net under forced layout optimization), the restride, each
refusal, and an exec in a fresh process importing only torch.

Authored with an AI assistant.

ghstack-source-id: 906ea3c
Pull-Request: #195361
bobrenjc93 added a commit that referenced this pull request Sep 6, 2026
…tandalone source

`aot_autograd.compile_to_python` splices AOTAutograd's codegen'd runtime-wrapper
source around the inner Inductor call, but refused a joint forward+backward, so
`torch.compiler.precompile(..., training=True)` fell back to a pickled bundle.
This composes the training case: `compile_to_python` gains a `grad_enabled`
flag that runs the capture pass under `enable_grad` so requires-grad inputs
produce the joint, and `torch.compiler.precompile` passes its `training` flag
through.

AOTAutograd already codegens the backward prologue, epilogue and
`compiled_function_backward` but not the `torch.autograd.Function` holding
them, so the composer emits a `_CompiledFunction` mirroring the runtime class's
attributes; its `_lazy_backward_info` raises so compiled autograd refuses a
source artifact loudly. `_capture_autograd_specs` records the spec during
capture, tagged with the wrappers' TracingContext `origin_id`;
`_select_training_spec` refuses anything but one match.

Ordering matters: layout optimization may return channels-last saved
activations, so the backward must lower against the strides the forward chose.
The forward lowers first, `_restride_backward_placeholders` rewrites the saved
activations' `node.meta["val"]` from the forward's `output_strides` (a
symbolic stride is rebuilt over the shape symbols with `deserialize_symexpr`
and compared proof-only, as `_aot_stage2b_bw_compile` does since #194420; a
symbol the shape env never created refuses), then the backward lowers with
`is_backward=True`. `is_inference` is no longer hardcoded:
`_graph_differentiates` looks for a `convolution_backward` call node, since a
make_fx trace through `.backward()` has no joint but is not inference.

`namespace_module_names` renames each spliced module's top-level names and
replaces the dynamo tracer's copy; helpers come through `standalone_runtime`; baked metadata types are
imported from their defining modules.
`output_alias_wrapper` and `mutation_epilogue` are spliced,
`debug_assert_wrapper` is dropped, and synthetic base, dedup, functionalized
RNG, tensor subclasses, BackwardState, an interposed InductorWrapper,
inlineable saved_tensors_hooks, and a forward output stride naming a symbol
the shape env never minted, are refused rather than mis-rendered.

User-visible: a refused subgraph now warns with the reason, and the artifact
header names each subgraph that stays pickled and why.

Test Plan:

```
python test/functorch/test_compile_to_python.py
python test/inductor/test_compile_to_python.py
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_precompile_package.py
python test/dynamo/test_guard_serialization.py
```

Tests check served gradients against eager (aliased outputs, input mutation,
dynamic dims, a conv net under forced layout optimization), the restride, each
refusal, and an exec in a fresh process importing only torch.

Authored with an AI assistant.

ghstack-source-id: e56636c
Pull-Request: #195361
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…#194420)

## Problem

Inductor can give a saved activation a different layout than the backward
graph's placeholder carries (layout optimization, comprehensive padding), so
AOTAutograd restrides the placeholder to match what the forward will produce.

Inductor reports those strides as sympy expressions, but
`set_tracing_context_output_strides` collapsed them with `evaluate_symexpr`,
substituting the current hints. The resulting constant got baked into the
placeholder via `as_strided`, so it was only valid for the first call's sizes:
with `pad_dynamic_shapes` the stride freezes at the first hint (128*112 =
14336) and the next call dies in `assert_size_stride` with
`stride 24576==14336 at dim=0`.

Two smaller problems in the same block: the comparison was hint-based
(`guard_or_true(ph_arg.stride()[k] != int(real_stride[k]))`), which specialized
the placeholder's dynamic dims just by asking and needed `suppress_guards()` to
hide it; and the `int()` cast threw on unbacked symbols.

## Approach

**Keep the stride symbolic.** Always use `deserialize_symexpr`, which rebuilds
the printed expression as a SymInt still referencing the shape symbols.
Previously only `fakify_first_call` did this.

**Resolve every symbol that can appear.** `deserialize_symexpr` looks symbols up
lazily via `name_to_symbol`, preserving each one's scalar type and using
`_NO_HINT` where there is no hint, so unbacked and nested-tensor symbols work
instead of raising `NameError`. It creates each symbol's FX placeholder / z3
var, hence `@record_shapeenv_event()`: translation validation replays onto a
fresh env and would otherwise fail with `Node sN not found in name_to_node`.

**Print Max/Min symbolically.** `SymExprPrinter` now emits
`torch.sym_max`/`torch.sym_min`. Builtin `max()` picks a branch by evaluating
`a > b`, which installs a guard and collapses the expression this change exists
to keep symbolic. Shared with `ShapeGuardPythonPrinter`, which already did it.

**Compare proof-only.** `not statically_known_true(ph_stride == inductor_stride[k])`
— restride unless equality is provable. Hints are only ever used to disprove, so
no guard is installed and an incidental match at the current sizes is not
mistaken for equality. This removes both `suppress_guards()` and the `int()` cast.

**Cleanups.** Delete `evaluate_symexpr`, dead once nothing collapses strides.
Rename `real_stride` → `inductor_stride`: it is inductor's IR layout expression,
and this path runs at compile time over FakeTensors. Widen stride annotations
from `int` to `IntLikeType`. Drop the stale claim that layout optimization is
disabled for dynamic shapes.

Pull Request resolved: pytorch#194420
Approved by: https://github.com/bobrenjc93
@github-actions
github-actions Bot deleted the gh/laithsakka/484/head branch November 12, 2026 01:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request keep-going Don't stop on first failure, keep running tests until the end Merged module: dynamo module: inductor release notes: fx release notes category suppress-bc-linter Suppresses the failures of API backward-compatibility linter (Lint/bc_linter)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants