Repository navigation
Keep saved-activation strides symbolic under dynamic shapes - #194420
laithsakka wants to merge 13 commits into
Conversation
🔗 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 ( 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. |
|
@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 |
Merge failedReason: Command Details for Dev Infra teamRaised by workflow job |
|
@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 |
…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
…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
…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
…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
…#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
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_stridescollapsed them withevaluate_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_shapesthe stride freezes at the first hint (128*112 =14336) and the next call dies in
assert_size_stridewithstride 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 specializedthe placeholder's dynamic dims just by asking and needed
suppress_guards()tohide it; and the
int()cast threw on unbacked symbols.Approach
Keep the stride symbolic. Always use
deserialize_symexpr, which rebuildsthe printed expression as a SymInt still referencing the shape symbols.
Previously only
fakify_first_calldid this.Resolve every symbol that can appear.
deserialize_symexprlooks symbols uplazily via
name_to_symbol, preserving each one's scalar type and using_NO_HINTwhere there is no hint, so unbacked and nested-tensor symbols workinstead of raising
NameError. It creates each symbol's FX placeholder / z3var, hence
@record_shapeenv_event(): translation validation replays onto afresh env and would otherwise fail with
Node sN not found in name_to_node.Print Max/Min symbolically.
SymExprPrinternow emitstorch.sym_max/torch.sym_min. Builtinmax()picks a branch by evaluatinga > b, which installs a guard and collapses the expression this change existsto 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 theint()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
inttoIntLikeType. Drop the stale claim that layout optimization isdisabled 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