Skip to content

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

Closed
bobrenjc93 wants to merge 2 commits into
gh/bobrenjc93/999/basefrom
gh/bobrenjc93/999/head
Closed

bobrenjc93 wants to merge 2 commits into
gh/bobrenjc93/999/basefrom
gh/bobrenjc93/999/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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, along with _backward_impl
(which is just ctx.maybe_clear_saved_tensors() plus a boxed call into the
backward graph) and the double-backward trampoline.

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.

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.
is_inference is also no longer hardcoded true, since it selects a different
layout-optimization heuristic and a different user-visible-output slice.

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

Not covered, and refused rather than mis-rendered: tensor subclasses and
BackwardState. 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

Two new tests cover the composition directly: one asserts the served output
carries grad_fn and that its gradients equal eager's, and one asserts 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.

Conv nets are the case the stride coupling exists for, so they were checked
end-to-end with layout_optimization at its default and TF32 off: 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. One caveat that is NOT precompile's: with TF32 left on, the
rendered path selects a TF32 conv where torch.compile does not, which is 2.1e-4
relative rather than 3.4e-7 -- an algorithm-selection difference affecting any
consumer of this lowering, worth chasing separately.

Authored with an AI assistant.

Differential Revision: D116728727

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 20, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 10 New Failures, 1 Unrelated Failure

As of commit 6a925ed with merge base 1b4e490 (image):

NEW FAILURES - The following jobs have failed:

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.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@bobrenjc93 has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

This was referenced Aug 22, 2026
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@bobrenjc93 has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@bobrenjc93 has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

1 similar comment
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@bobrenjc93 has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Superseded by the canonical precompile stack #195353-#195362; this change lives in #195361. Closing to consolidate review there. The branch is kept on GitHub.

@bobrenjc93 bobrenjc93 closed this Sep 3, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/999/head branch November 11, 2026 01:44
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 module: dynamo module: inductor topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant