Skip to content

[aot_autograd] Compose a training graph's forward and backward into standalone source - #195361

Closed
bobrenjc93 wants to merge 72 commits into
gh/bobrenjc93/1101/basefrom
gh/bobrenjc93/1101/head
Closed

bobrenjc93 wants to merge 72 commits into
gh/bobrenjc93/1101/basefrom
gh/bobrenjc93/1101/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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.

[no ci]

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

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

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
…tandalone source

``aot_autograd.compile_to_python`` renders a graph as a self-contained module by
splicing AOTAutograd's OWN codegen'd runtime-wrapper source around the inner
Inductor call. Until now it did that only for inference: a graph whose inputs
require grad makes AOTAutograd emit a joint forward+backward, and the composer
refused it -- "cannot yet compose these runtime wrappers into standalone
source". Consequently ``torch.compiler.precompile(..., training=True)`` fell
back to a pickled bundle and shipped an artifact that was almost entirely
base64. This composes the training case, so a training artifact carries readable
kernels and readable glue like an inference one, and the served output's
``.backward()`` runs compiled code.

Very little of the backward is new source. AOTAutograd already codegens
``backward_prologue``, ``backward_epilogue`` and ``compiled_function_backward``
through the same PySourceBuilder as the forward wrappers -- the composer simply
filtered them out. What it does NOT codegen is the ``torch.autograd.Function``
that holds them, so that class is emitted here. The emitted ``_CompiledFunction``
mirrors the runtime ``CompiledFunction`` class body rather than being a minimal
stand-in: ``compiled_fw``/``compiled_bw``, ``metadata``,
``maybe_subclass_metadata`` (None, since the compose refuses subclasses),
``num_symints_saved_for_bw``, ``_aot_id``, ``_lazy_backward_info`` (a
descriptor that raises NotImplementedError: the real class holds an
AutogradLazyBackwardCompileInfo on a fresh compile and None only when loaded
from the AOTAutograd cache, and compiled autograd reads this attribute first,
so a None here would surface the cache's TORCHINDUCTOR_AUTOGRAD_CACHE advice
for an artifact that has nothing to do with it), the
``_bw_prologue_fn``/``_bw_epilogue_fn``/``_fwd_fn``/``_bwd_fn`` attributes,
``boxed_grads_call``, and ``_compiled_autograd_key``, ``_backward_impl`` and
``_double_backward`` as staticmethods. Anything the runtime or compiled
autograd reads off the class exists on the emitted one, and a test compares
the two attribute sets. ``_backward_impl`` is ``ctx.maybe_clear_saved_tensors()``,
the donated-buffer check torch.compile makes -- ``retain_graph=True`` against a
backward compiled with donated buffers raises the same message -- the external
object weakref refresh, and a boxed call into the backward graph; the
double-backward trampoline carries the ``_aot_id`` and the compiled-autograd
key like the real one.

The spec the compose needs (fw_metadata, RNG state, disable_amp, the
saved/symint counts) is built during the capture pass and not otherwise
reachable. ``_capture_autograd_specs`` records every spec
``_AOTDispatchAutogradFunctionFactory.build`` sees while active, tagged with
the TracingContext identity the codegen'd wrappers carry as
``GeneratedSource.origin_id``, and ``_select_training_spec`` picks the one
built under the same context as the captured orchestration. A re-entrant
lowering during the capture window builds its own autograd Function under a
distinct TracingContext; its spec is told apart the same way its wrappers are
and ignored, and anything other than exactly one match refuses rather than
guesses. The composer takes only the spec: the placeholder call objects it
used to be handed were unused.

The ordering is the part that carries real risk, and it is not incidental.
Inductor's layout optimization lets a compiled forward return channels-last
saved activations, so the backward must be lowered against the strides the
forward ACTUALLY chose -- which only exist once the forward has lowered.
torch.compile gets this from TracingContext.report_output_strides around its
forward compile and restrides the backward's placeholders in
_aot_stage2b_bw_compile. The capture pass here never lowered, so it never had
those strides, and two independently-lowered graphs disagreed: on a conv net
that is a loud AssertionError by default and SILENTLY WRONG GRADIENTS with size
asserts off. inductor's compile_to_python already computed the strides on its
CompiledFxGraph and discarded them; it now reports them, and this lowers the
forward first, restrides, then lowers the backward with is_backward=True,
matching torch.compile's backward compile -- without it, GraphLowering's
backward-only require_contiguous safeguard for untagged implicit-fallback aten
ops (#140452) is lost, and such a fallback handed a non-contiguous input can
silently compute wrong gradients.

Two details in that restride are worth knowing before touching it. It rewrites
``node.meta["val"]``, not an example-inputs list, because
``inductor.compile_to_python`` rebuilds its fakes from placeholder metadata and
ignores the inputs it is handed -- restriding a list is a silent no-op through
that entry point. And it maps saved activations by
``fw_metadata.tensors_saved_for_backwards_slice`` offset by
``num_symints_saved_for_bw``; guessing positionally restrides the wrong
placeholder, which asserts on a Linear and would otherwise miscompute.
CompiledFxGraph.output_strides entries are PRINTED stride expressions, symbolic
under dynamic shapes, so a symbolic stride refuses with NotImplementedError
rather than lowering the backward against strides other than the forward's
actual choices. ``is_inference`` is also no longer hardcoded true, since it
selects a different layout-optimization heuristic and a different
user-visible-output slice.

On that classification: "is this inference?" cannot be answered by asking
whether AOTAutograd emitted a joint. Whether there is a JOINT decides what to
compose; whether the computation DIFFERENTIATES decides what to tell Inductor.
A graph traced through a ``.backward()`` -- what the make_fx tracer produces
for a train step, and what ``torch.compile(torch.func.grad(...))`` produces --
has its backward inlined and no joint at all, so joint-ness would lower it as
inference. That is not cosmetic: ``GraphLowering.decide_layout_opt`` takes a
different branch for inference (torch/_inductor/graph.py:856), converts the
conv to channels-last, and cuDNN then serves an NHWC TF32 kernel where the
same model under torch.compile gets an NCHW ffma one -- gradients off by ~2e-4
RELATIVE with nothing to indicate it. Differentiation is therefore detected by
the presence of a ``convolution_backward`` CALL node (a placeholder or
attribute whose name merely contains "backward", which a wrapped tracer can
mint, does not count), which is enough because the only thing ``is_inference``
changes on this path is the layout decision, and decide_layout_opt returns
early unless the graph has convolutions. Scope worth stating: the
inline-backward misclassification is NOT precompile-specific --
``torch.compile(torch.func.grad(loss))`` shows the identical ~2e-4 error and
is untouched here. Fixing it properly belongs in decide_layout_opt, which
would change torch.compile's own behaviour and wants its own discussion.

The forward and backward Inductor modules are spliced into one namespace and
both define ``call``, ``Runner`` and their kernels, which a module resolves as
late-bound globals when INVOKED. Renaming per module (``namespace_module_names``)
is what keeps the forward from running the backward's kernels; the same helper
now serves the dynamo tracer's per-subgraph renaming, which had grown its own
copy.

The composed module's imports are arranged for a process that has imported
nothing but torch. ``import torch`` is emitted first, and the runtime helpers
the glue needs (``_AutogradRngStateTracker``, ``_AutogradSavedState``,
``_snapshot_external_objects``, ``index_to_external_object_weakref``,
``normalize_as_list``) come through the ``standalone_runtime`` surface rather
than from ``runtime_wrappers`` directly, and ``import torch`` is the first
statement of the artifact: a ``from ...runtime_wrappers import`` that runs
before torch itself is imported trips a circular import with ``_dynamo``
(the metadata types the artifact spells out still reference the
``runtime_wrappers`` module by attribute, which is fine once torch is up). A
test execs a generated training artifact in a fresh subprocess to hold that
invariant. The RNG tracker is emitted as a constructor call with
only its real arguments rather than by value-reduction: its default state
includes an itertools.count, whose pickle support is gone on Python 3.12+, and
that state is per-process anyway, so a load must start it fresh.

Which captured wrappers the compose accepts is decided explicitly, the same way
the inference composer already did: it filters to the target orchestration's
TracingContext origin, requires exactly one orchestration, verifies the
orchestration's positional signature (factored out and shared), and refuses
any wrapper it does not model -- synthetic base, dedup, functionalized RNG --
rather than dropping it. Dropping was the previous behaviour, and a training
graph with two mutated aliased views composed "successfully" and crashed at
first call because the inner forward was compiled for the merged
synthetic-base calling convention, replacing a working pickled-bundle fallback
with a broken artifact. ``debug_assert_wrapper`` is the one wrapper dropped
deliberately: functorch's debug_assert (on in the CI environment) captures it
for every training graph, and it is a metadata diagnostic with no effect on
numerics, so it is treated like the profiler prologue. ``compiled_fn_wrapper``
is required, not optional: AOTAutograd codegens it unconditionally and the glue
calls ``_transform_raw_returns`` unguarded, so its absence is a malformed
capture. A capture made under inlineable saved_tensors_hooks is refused too:
the runtime disables the ambient hooks around a trace_joint call (they were
traced INTO the joint), and that wrapper is plain Python the compose cannot
splice, so serving would apply pack() a second time to already-packed
activations.

Not covered, and refused rather than mis-rendered: tensor subclasses and
BackwardState. A served training artifact's ``.backward()`` cannot run under
compiled autograd: a source artifact carries no fx bw_module for compiled
autograd to proxy, so the emitted class refuses with a NotImplementedError
naming the standalone artifact the moment compiled autograd reads
``_lazy_backward_info``; a test pins that message.
cudagraphs remain off (compile_to_python hardcodes them off). Unverified on
this path: functionalized RNG and dynamic shapes.

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_guard_serialization.py
```

The composition is covered directly: the served output carries grad_fn and its
gradients equal eager's; the two spliced modules share no top-level name (that
one fails with a bare arity error, "requires 4 args", if the renaming
regresses, which is how the bug was found); a forward-only capture does not
classify as differentiating while a make_fx trace through .backward() does,
detected via convolution_backward; a spy pins the [forward=False,
backward=True] lowering flags; the saved_tensors_hooks refusal is tested. The
emitted class is checked against the real one
(test_training_compiled_function_mirrors_runtime_class_attributes), the
donated-buffer retain_graph refusal is compared message-for-message against
torch.compile's, ``_select_training_spec`` is pinned to ignore a spec built
under a foreign TracingContext and to refuse two candidates, and the artifact
is exec'd in a fresh subprocess that imports only torch and runs forward and
backward (test_training_artifact_execs_in_fresh_process). The conv restride
test forces layout optimization (verified failing with the restride no-op'd;
at default heuristics Conv2d(16, 32, 3) never triggers it), disables cuDNN
TF32 so gradients compare at default tolerance, and gates on HAS_GPU/GPU_TYPE.
The two end-to-end training tests skip under PYTORCH_TEST_WITH_DYNAMO because
that harness enables compiled autograd, which the served backward refuses
(see above); the two that call make_fx
inline skip because make_fx of a grad-enabled closure cannot trace under an
outer dynamo (error_on_nested_fx_trace).

Conv nets are the case the stride coupling exists for, so they were checked
end-to-end with layout_optimization at its default: Conv2d(16,32), (3,16),
(8,8), (3,64) and (32,64) all land within 1.5e-7 relative of eager, against
torch.compile's own 9.5e-8, where before the restride they raised
AssertionError. Gradients on conv train steps, against eager: Conv2d(16,32)
1.997e-04 before the differentiation classification, 9.497e-08 after
(torch.compile: 9.497e-08); Conv2d(32,64) 6.996e-04 before, 1.908e-07 after
(torch.compile: 1.908e-07).

Authored with an AI assistant.

ghstack-source-id: 208d277
Pull-Request: #195361
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
…tandalone source

``aot_autograd.compile_to_python`` renders a graph as a self-contained module by
splicing AOTAutograd's OWN codegen'd runtime-wrapper source around the inner
Inductor call. Until now it did that only for inference: a graph whose inputs
require grad makes AOTAutograd emit a joint forward+backward, and the composer
refused it -- "cannot yet compose these runtime wrappers into standalone
source". Consequently ``torch.compiler.precompile(..., training=True)`` fell
back to a pickled bundle and shipped an artifact that was almost entirely
base64. This composes the training case, so a training artifact carries readable
kernels and readable glue like an inference one, and the served output's
``.backward()`` runs compiled code.

Very little of the backward is new source. AOTAutograd already codegens
``backward_prologue``, ``backward_epilogue`` and ``compiled_function_backward``
through the same PySourceBuilder as the forward wrappers -- the composer simply
filtered them out. What it does NOT codegen is the ``torch.autograd.Function``
that holds them, so that class is emitted here. The emitted
``_CompiledFunction`` mirrors the runtime ``CompiledFunction`` class body
rather than being a minimal stand-in: ``compiled_fw``/``compiled_bw``,
``metadata``, ``maybe_subclass_metadata`` (None, since the compose refuses
subclasses), ``num_symints_saved_for_bw``, ``_aot_id``, ``_lazy_backward_info``
(a descriptor that raises a NotImplementedError which is also an
AttributeError, so hasattr/getattr-with-default read the attribute as absent:
the real class holds an AutogradLazyBackwardCompileInfo on a fresh compile and
None only when loaded from the AOTAutograd cache, and compiled autograd reads
this attribute first, so a None here would surface the cache's
TORCHINDUCTOR_AUTOGRAD_CACHE advice for an artifact that has nothing to do with
it), the ``_bw_prologue_fn``/``_bw_epilogue_fn``/``_fwd_fn``/``_bwd_fn``
attributes, ``boxed_grads_call``, and ``_compiled_autograd_key``,
``_backward_impl`` and ``_double_backward`` as staticmethods. Anything the
runtime or compiled autograd reads off the class exists on the emitted one, and
a test compares the two attribute sets. ``_backward_impl`` is
``ctx.maybe_clear_saved_tensors()``, the donated-buffer check torch.compile
makes -- ``retain_graph=True`` against a backward compiled with donated buffers
raises the same message -- the external object weakref refresh, and a boxed
call into the backward graph; the double-backward trampoline carries the
``_aot_id`` and the compiled-autograd key like the real one.

The spec the compose needs (fw_metadata, RNG state, disable_amp, the
saved/symint counts) is built during the capture pass and not otherwise
reachable. ``_capture_autograd_specs`` records every spec
``_AOTDispatchAutogradFunctionFactory.build`` sees while active, tagged with
the TracingContext identity the codegen'd wrappers carry as
``GeneratedSource.origin_id``, and ``_select_training_spec`` picks the one
built under the same context as the captured orchestration. A re-entrant
lowering during the capture window builds its own autograd Function under a
distinct TracingContext; its spec is told apart the same way its wrappers are
and ignored, and anything other than exactly one match refuses rather than
guesses. The composer takes only the spec: the placeholder call objects it
used to be handed were unused.

The ordering is the part that carries real risk, and it is not incidental.
Inductor's layout optimization lets a compiled forward return channels-last
saved activations, so the backward must be lowered against the strides the
forward ACTUALLY chose -- which only exist once the forward has lowered.
torch.compile gets this from TracingContext.report_output_strides around its
forward compile and restrides the backward's placeholders in
_aot_stage2b_bw_compile. The capture pass here never lowered, so it never had
those strides, and two independently-lowered graphs disagreed: on a conv net
that is a loud AssertionError by default and SILENTLY WRONG GRADIENTS with size
asserts off. inductor's compile_to_python already computed the strides on its
CompiledFxGraph and discarded them; it now reports them, and this lowers the
forward first, restrides, then lowers the backward with is_backward=True,
matching torch.compile's backward compile -- without it, GraphLowering's
backward-only require_contiguous safeguard for untagged implicit-fallback aten
ops (#140452) is lost, and such a fallback handed a non-contiguous input can
silently compute wrong gradients.

Two details in that restride are worth knowing before touching it. It rewrites
``node.meta["val"]``, not an example-inputs list, because
``inductor.compile_to_python`` rebuilds its fakes from placeholder metadata and
ignores the inputs it is handed -- restriding a list is a silent no-op through
that entry point. And it maps saved activations by
``fw_metadata.tensors_saved_for_backwards_slice`` offset by
``num_symints_saved_for_bw``; guessing positionally restrides the wrong
placeholder, which asserts on a Linear and would otherwise miscompute.
CompiledFxGraph.output_strides entries are PRINTED stride expressions, symbolic
under dynamic shapes, so a symbolic stride refuses with NotImplementedError
rather than lowering the backward against strides other than the forward's
actual choices. ``is_inference`` is also no longer hardcoded true, since it
selects a different layout-optimization heuristic and a different
user-visible-output slice.

On that classification: "is this inference?" cannot be answered by asking
whether AOTAutograd emitted a joint. Whether there is a JOINT decides what to
compose; whether the computation DIFFERENTIATES decides what to tell Inductor.
A graph traced through a ``.backward()`` -- what the make_fx tracer produces
for a train step, and what ``torch.compile(torch.func.grad(...))`` produces --
has its backward inlined and no joint at all, so joint-ness would lower it as
inference. That is not cosmetic: ``GraphLowering.decide_layout_opt`` takes a
different branch for inference (torch/_inductor/graph.py:856), converts the
conv to channels-last, and cuDNN then serves an NHWC TF32 kernel where the
same model under torch.compile gets an NCHW ffma one -- gradients off by ~2e-4
RELATIVE with nothing to indicate it. Differentiation is therefore detected by
the presence of a ``convolution_backward`` CALL node (a placeholder or
attribute whose name merely contains "backward", which a wrapped tracer can
mint, does not count), which is enough because the only thing ``is_inference``
changes on this path is the layout decision, and decide_layout_opt returns
early unless the graph has convolutions. Scope worth stating: the
inline-backward misclassification is NOT precompile-specific --
``torch.compile(torch.func.grad(loss))`` shows the identical ~2e-4 error and
is untouched here. Fixing it properly belongs in decide_layout_opt, which
would change torch.compile's own behaviour and wants its own discussion.

The forward and backward Inductor modules are spliced into one namespace and
both define ``call``, ``Runner`` and their kernels, which a module resolves as
late-bound globals when INVOKED. Renaming per module
(``namespace_module_names``) is what keeps the forward from running the
backward's kernels; the same helper now serves the dynamo tracer's per-subgraph
renaming, which had grown its own copy.

The composed module's imports are arranged for a process that has imported
nothing but torch. ``import torch`` is emitted first, and the runtime helpers
the glue needs (``_AutogradRngStateTracker``, ``_AutogradSavedState``,
``_snapshot_external_objects``, ``index_to_external_object_weakref``,
``normalize_as_list``) come through the ``standalone_runtime`` surface rather
than from ``runtime_wrappers`` directly, and ``import torch`` is the first
statement of the artifact: a ``from ...runtime_wrappers import`` that runs
before torch itself is imported trips a circular import with ``_dynamo``
(the metadata types the artifact spells out, and
``AOTDispatchAutograd.process_runtime_tangent``, still reference the
``runtime_wrappers`` module by attribute, which is fine once torch is up, so
the invariant the fresh-subprocess test holds is import order, not the
absence of that module). The RNG tracker is emitted as a constructor call with
only its real arguments rather than by value-reduction: its default state
includes an itertools.count, whose pickle support is gone on Python 3.12+, and
that state is per-process anyway, so a load must start it fresh.

Which captured wrappers the compose accepts is decided explicitly, the same way
the inference composer already did: it filters to the target orchestration's
TracingContext origin, requires exactly one orchestration, verifies the
orchestration's positional signature (factored out and shared), and refuses
any wrapper it does not model -- synthetic base, dedup, functionalized RNG --
rather than dropping it. Dropping was the previous behaviour, and a training
graph with two mutated aliased views composed "successfully" and crashed at
first call because the inner forward was compiled for the merged
synthetic-base calling convention, replacing a working pickled-bundle fallback
with a broken artifact. ``debug_assert_wrapper`` is the one wrapper dropped
deliberately: functorch's debug_assert (on in the CI environment) captures it
for every training graph, and it is a metadata diagnostic with no effect on
numerics, so it is treated like the profiler prologue. ``compiled_fn_wrapper``
is required, not optional: AOTAutograd codegens it unconditionally and the glue
calls ``_transform_raw_returns`` unguarded, so its absence is a malformed
capture. A capture made under inlineable saved_tensors_hooks is refused too:
the runtime disables the ambient hooks around a trace_joint call (they were
traced INTO the joint), and that wrapper is plain Python the compose cannot
splice, so serving would apply pack() a second time to already-packed
activations.

Not covered, and refused rather than mis-rendered: tensor subclasses and
BackwardState. A served training artifact's ``.backward()`` cannot run under
compiled autograd: a source artifact carries no fx bw_module for compiled
autograd to proxy, so the emitted class refuses with a NotImplementedError
naming the standalone artifact the moment compiled autograd reads
``_lazy_backward_info``; a test pins that message.
cudagraphs remain off (compile_to_python hardcodes them off). Unverified on
this path: functionalized RNG and dynamic shapes.

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_guard_serialization.py
```

The composition is covered directly: the served output carries grad_fn and its
gradients equal eager's; the two spliced modules share no top-level name (that
one fails with a bare arity error, "requires 4 args", if the renaming
regresses, which is how the bug was found); a forward-only capture does not
classify as differentiating while a make_fx trace through .backward() does,
detected via convolution_backward; a spy pins the [forward=False,
backward=True] lowering flags; the saved_tensors_hooks refusal is tested. The
emitted class is checked against the real one
(test_training_compiled_function_mirrors_runtime_class_attributes), the
donated-buffer retain_graph refusal is compared message-for-message against
torch.compile's, ``_select_training_spec`` is pinned to ignore a spec built
under a foreign TracingContext and to refuse two candidates, and the artifact
is exec'd in a fresh subprocess that imports only torch and runs forward and
backward (test_training_artifact_execs_in_fresh_process). The conv restride
test forces layout optimization (verified failing with the restride no-op'd;
at default heuristics Conv2d(16, 32, 3) never triggers it), disables cuDNN
TF32 so gradients compare at default tolerance, and gates on HAS_GPU/GPU_TYPE.
The two end-to-end training tests skip under PYTORCH_TEST_WITH_DYNAMO because
that harness enables compiled autograd, which the served backward refuses
(see above); the two that call make_fx
inline skip because make_fx of a grad-enabled closure cannot trace under an
outer dynamo (error_on_nested_fx_trace).

Conv nets are the case the stride coupling exists for, so they were checked
end-to-end with layout_optimization at its default: Conv2d(16,32), (3,16),
(8,8), (3,64) and (32,64) all land within 1.5e-7 relative of eager, against
torch.compile's own 9.5e-8, where before the restride they raised
AssertionError. Gradients on conv train steps, against eager: Conv2d(16,32)
1.997e-04 before the differentiation classification, 9.497e-08 after
(torch.compile: 9.497e-08); Conv2d(32,64) 6.996e-04 before, 1.908e-07 after
(torch.compile: 1.908e-07).

Authored with an AI assistant.

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

``aot_autograd.compile_to_python`` renders a graph as a self-contained module by
splicing AOTAutograd's OWN codegen'd runtime-wrapper source around the inner
Inductor call. Until now it did that only for inference: a graph whose inputs
require grad makes AOTAutograd emit a joint forward+backward, and the composer
refused it -- "cannot yet compose these runtime wrappers into standalone
source". Consequently ``torch.compiler.precompile(..., training=True)`` fell
back to a pickled bundle and shipped an artifact that was almost entirely
base64. This composes the training case, so a training artifact carries readable
kernels and readable glue like an inference one, and the served output's
``.backward()`` runs compiled code.

Very little of the backward is new source. AOTAutograd already codegens
``backward_prologue``, ``backward_epilogue`` and ``compiled_function_backward``
through the same PySourceBuilder as the forward wrappers -- the composer simply
filtered them out. What it does NOT codegen is the ``torch.autograd.Function``
that holds them, so that class is emitted here. The emitted
``_CompiledFunction`` mirrors the runtime ``CompiledFunction`` class body
rather than being a minimal stand-in: ``compiled_fw``/``compiled_bw``,
``metadata``, ``maybe_subclass_metadata`` (None, since the compose refuses
subclasses), ``num_symints_saved_for_bw``, ``_aot_id``, ``_lazy_backward_info``
(a descriptor that raises a NotImplementedError which is also an
AttributeError, so hasattr/getattr-with-default read the attribute as absent:
the real class holds an AutogradLazyBackwardCompileInfo on a fresh compile and
None only when loaded from the AOTAutograd cache, and compiled autograd reads
this attribute first, so a None here would surface the cache's
TORCHINDUCTOR_AUTOGRAD_CACHE advice for an artifact that has nothing to do with
it), the ``_bw_prologue_fn``/``_bw_epilogue_fn``/``_fwd_fn``/``_bwd_fn``
attributes, ``boxed_grads_call``, and ``_compiled_autograd_key``,
``_backward_impl`` and ``_double_backward`` as staticmethods. Anything the
runtime or compiled autograd reads off the class exists on the emitted one, and
a test compares the two attribute sets. ``_backward_impl`` is
``ctx.maybe_clear_saved_tensors()``, the donated-buffer check torch.compile
makes -- ``retain_graph=True`` against a backward compiled with donated buffers
raises the same message -- the external object weakref refresh, and a boxed
call into the backward graph; the double-backward trampoline carries the
``_aot_id`` and the compiled-autograd key like the real one.

The spec the compose needs (fw_metadata, RNG state, disable_amp, the
saved/symint counts) is built during the capture pass and not otherwise
reachable. ``_capture_autograd_specs`` records every spec
``_AOTDispatchAutogradFunctionFactory.build`` sees while active, tagged with
the TracingContext identity the codegen'd wrappers carry as
``GeneratedSource.origin_id``, and ``_select_training_spec`` picks the one
built under the same context as the captured orchestration. A re-entrant
lowering during the capture window builds its own autograd Function under a
distinct TracingContext; its spec is told apart the same way its wrappers are
and ignored, and anything other than exactly one match refuses rather than
guesses. The composer takes only the spec: the placeholder call objects it
used to be handed were unused.

The ordering is the part that carries real risk, and it is not incidental.
Inductor's layout optimization lets a compiled forward return channels-last
saved activations, so the backward must be lowered against the strides the
forward ACTUALLY chose -- which only exist once the forward has lowered.
torch.compile gets this from TracingContext.report_output_strides around its
forward compile and restrides the backward's placeholders in
_aot_stage2b_bw_compile. The capture pass here never lowered, so it never had
those strides, and two independently-lowered graphs disagreed: on a conv net
that is a loud AssertionError by default and SILENTLY WRONG GRADIENTS with size
asserts off. inductor's compile_to_python already computed the strides on its
CompiledFxGraph and discarded them; it now reports them, and this lowers the
forward first, restrides, then lowers the backward with is_backward=True,
matching torch.compile's backward compile -- without it, GraphLowering's
backward-only require_contiguous safeguard for untagged implicit-fallback aten
ops (#140452) is lost, and such a fallback handed a non-contiguous input can
silently compute wrong gradients.

Two details in that restride are worth knowing before touching it. It rewrites
``node.meta["val"]``, not an example-inputs list, because
``inductor.compile_to_python`` rebuilds its fakes from placeholder metadata and
ignores the inputs it is handed -- restriding a list is a silent no-op through
that entry point. And it maps saved activations by
``fw_metadata.tensors_saved_for_backwards_slice`` offset by
``num_symints_saved_for_bw``; guessing positionally restrides the wrong
placeholder, which asserts on a Linear and would otherwise miscompute.
CompiledFxGraph.output_strides entries are PRINTED stride expressions, symbolic
under dynamic shapes, so a symbolic stride refuses with NotImplementedError
rather than lowering the backward against strides other than the forward's
actual choices. ``is_inference`` is also no longer hardcoded true, since it
selects a different layout-optimization heuristic and a different
user-visible-output slice.

On that classification: "is this inference?" cannot be answered by asking
whether AOTAutograd emitted a joint. Whether there is a JOINT decides what to
compose; whether the computation DIFFERENTIATES decides what to tell Inductor.
A graph traced through a ``.backward()`` -- what the make_fx tracer produces
for a train step, and what ``torch.compile(torch.func.grad(...))`` produces --
has its backward inlined and no joint at all, so joint-ness would lower it as
inference. That is not cosmetic: ``GraphLowering.decide_layout_opt`` takes a
different branch for inference (torch/_inductor/graph.py:856), converts the
conv to channels-last, and cuDNN then serves an NHWC TF32 kernel where the
same model under torch.compile gets an NCHW ffma one -- gradients off by ~2e-4
RELATIVE with nothing to indicate it. Differentiation is therefore detected by
the presence of a ``convolution_backward`` CALL node (a placeholder or
attribute whose name merely contains "backward", which a wrapped tracer can
mint, does not count), which is enough because the only thing ``is_inference``
changes on this path is the layout decision, and decide_layout_opt returns
early unless the graph has convolutions. Scope worth stating: the
inline-backward misclassification is NOT precompile-specific --
``torch.compile(torch.func.grad(loss))`` shows the identical ~2e-4 error and
is untouched here. Fixing it properly belongs in decide_layout_opt, which
would change torch.compile's own behaviour and wants its own discussion.

The forward and backward Inductor modules are spliced into one namespace and
both define ``call``, ``Runner`` and their kernels, which a module resolves as
late-bound globals when INVOKED. Renaming per module
(``namespace_module_names``) is what keeps the forward from running the
backward's kernels; the same helper now serves the dynamo tracer's per-subgraph
renaming, which had grown its own copy.

The composed module's imports are arranged for a process that has imported
nothing but torch. ``import torch`` is emitted first, and the runtime helpers
the glue needs (``_AutogradRngStateTracker``, ``_AutogradSavedState``,
``_snapshot_external_objects``, ``index_to_external_object_weakref``,
``normalize_as_list``) come through the ``standalone_runtime`` surface rather
than from ``runtime_wrappers`` directly, and ``import torch`` is the first
statement of the artifact: a ``from ...runtime_wrappers import`` that runs
before torch itself is imported trips a circular import with ``_dynamo``
(the metadata types the artifact spells out, and
``AOTDispatchAutograd.process_runtime_tangent``, still reference the
``runtime_wrappers`` module by attribute, which is fine once torch is up, so
the invariant the fresh-subprocess test holds is import order, not the
absence of that module). The RNG tracker is emitted as a constructor call with
only its real arguments rather than by value-reduction: its default state
includes an itertools.count, whose pickle support is gone on Python 3.12+, and
that state is per-process anyway, so a load must start it fresh.

Which captured wrappers the compose accepts is decided explicitly, the same way
the inference composer already did: it filters to the target orchestration's
TracingContext origin, requires exactly one orchestration, verifies the
orchestration's positional signature (factored out and shared), and refuses
any wrapper it does not model -- synthetic base, dedup, functionalized RNG --
rather than dropping it. Dropping was the previous behaviour, and a training
graph with two mutated aliased views composed "successfully" and crashed at
first call because the inner forward was compiled for the merged
synthetic-base calling convention, replacing a working pickled-bundle fallback
with a broken artifact. ``debug_assert_wrapper`` is the one wrapper dropped
deliberately: functorch's debug_assert (on in the CI environment) captures it
for every training graph, and it is a metadata diagnostic with no effect on
numerics, so it is treated like the profiler prologue. ``compiled_fn_wrapper``
is required, not optional: AOTAutograd codegens it unconditionally and the glue
calls ``_transform_raw_returns`` unguarded, so its absence is a malformed
capture. A capture made under inlineable saved_tensors_hooks is refused too:
the runtime disables the ambient hooks around a trace_joint call (they were
traced INTO the joint), and that wrapper is plain Python the compose cannot
splice, so serving would apply pack() a second time to already-packed
activations.

Not covered, and refused rather than mis-rendered: tensor subclasses and
BackwardState. A served training artifact's ``.backward()`` cannot run under
compiled autograd: a source artifact carries no fx bw_module for compiled
autograd to proxy, so the emitted class refuses with a NotImplementedError
naming the standalone artifact the moment compiled autograd reads
``_lazy_backward_info``; a test pins that message.
cudagraphs remain off (compile_to_python hardcodes them off). Unverified on
this path: functionalized RNG and dynamic shapes.

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_guard_serialization.py
```

The composition is covered directly: the served output carries grad_fn and its
gradients equal eager's; the two spliced modules share no top-level name (that
one fails with a bare arity error, "requires 4 args", if the renaming
regresses, which is how the bug was found); a forward-only capture does not
classify as differentiating while a make_fx trace through .backward() does,
detected via convolution_backward; a spy pins the [forward=False,
backward=True] lowering flags; the saved_tensors_hooks refusal is tested. The
emitted class is checked against the real one
(test_training_compiled_function_mirrors_runtime_class_attributes), the
donated-buffer retain_graph refusal is compared message-for-message against
torch.compile's, ``_select_training_spec`` is pinned to ignore a spec built
under a foreign TracingContext and to refuse two candidates, and the artifact
is exec'd in a fresh subprocess that imports only torch and runs forward and
backward (test_training_artifact_execs_in_fresh_process). The conv restride
test forces layout optimization (verified failing with the restride no-op'd;
at default heuristics Conv2d(16, 32, 3) never triggers it), disables cuDNN
TF32 so gradients compare at default tolerance, and gates on HAS_GPU/GPU_TYPE.
The two end-to-end training tests skip under PYTORCH_TEST_WITH_DYNAMO because
that harness enables compiled autograd, which the served backward refuses
(see above); the two that call make_fx
inline skip because make_fx of a grad-enabled closure cannot trace under an
outer dynamo (error_on_nested_fx_trace).

Conv nets are the case the stride coupling exists for, so they were checked
end-to-end with layout_optimization at its default: Conv2d(16,32), (3,16),
(8,8), (3,64) and (32,64) all land within 1.5e-7 relative of eager, against
torch.compile's own 9.5e-8, where before the restride they raised
AssertionError. Gradients on conv train steps, against eager: Conv2d(16,32)
1.997e-04 before the differentiation classification, 9.497e-08 after
(torch.compile: 9.497e-08); Conv2d(32,64) 6.996e-04 before, 1.908e-07 after
(torch.compile: 1.908e-07).

Authored with an AI assistant.

ghstack-source-id: 8f2dd3d
Pull-Request: #195361
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93 bobrenjc93 closed this Oct 16, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1101/head branch November 17, 2026 01:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant