Repository navigation
[aot_autograd] Opt-in undefined-tangent backward specialization and compile_to_python training support - #195689
Closed
bobrenjc93 wants to merge 9 commits into
Closed
bobrenjc93 wants to merge 9 commits into
bobrenjc93 wants to merge 9 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/195689
Note: Links to docs will display an error until the docs builds have been completed. ❌ 3 New Failures, 3 Cancelled Jobs, 19 PendingAs of commit d788f17 with merge base 3d3d3f4 ( NEW FAILURES - The following jobs have failed:
CANCELLED JOBS - The following jobs were cancelled. Please retry:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This was referenced Sep 2, 2026
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
This was referenced Sep 3, 2026
Closed
Contributor
Author
|
@pytorchbot label "release notes: aot autograd" |
Contributor
Author
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):
This adds two related capabilities, both gated behind the new
config.aot_autograd_prune_unused_outputs flag (default False):
(the caller passes no tangent for them), AOTAutograd can specialize the
backward to the observed mask of defined tangents instead of always
materializing zeros. Specialized backwards are cached per mask.
(backward) path, not just inference.
The flag is captured into AOTConfig at compile time
(AOTConfig.prune_unused_outputs, defaulted from the config) so behavior is
fixed for an already-compiled function even if the global config later changes;
runtime code reads the AOTConfig field, never the live config. With the flag
off, every path is a no-op and the captured graph is byte-for-byte the previous
default (the restored aot0_tangents_2 / aot0_add_1 golden nodes assert this).
Backward specialization first tries to retrace a backward for the observed
mask; the three retrace sites (live runtime, compiled autograd, standalone
codegen) share graph_compile.retrace_backward_handling_errors, which propagates
PrecompileError (a precompiled artifact cannot retrace at runtime) and declines
to structural specialization on any other exception. When retrace declines and
no grad-output prototypes are available to materialize zeros, the run raises
only under precompile (precompile_backend_id set); otherwise it falls through to
the zero-tangent path.
Structural decisions worth calling out for review: differentiability of a
generated graph is now decided by scanning call nodes' operator names
(to_standalone_python._graph_differentiates), not by substring-matching graph
names; the forward-output ABI comparison keys off the structural
_backward_placeholder_key rather than the codegen-assigned node.name, which
diverges across otherwise-identical retraces. The forward->backward handoff
still rides on ctx.aot* attributes (ctx is a C++ autograd node we cannot
subclass) and the source-capture sink still rides on a thread-local (build()
runs deep inside compile_fx with no return path); both are documented at their
definitions as the only available channels.
Retrace binding. The retraced (partial) backward keeps a subset of the original
backward's inputs, and its codegen renumbers nodes, so saved activations are
bound to the compiled forward's by a structural fingerprint of what the
forward node computes (indexed across all name-keyed originals), never by node
name; an activation matching none, or several, of the originals declines the
retrace (binding a guess would silently feed one branch's mask to another).
fw_metadata.bw_donated_idxs are positions in the original input list that
inductor applies positionally, so every backward compile runs under a
per-TracingContext lock with its own copy of fw_metadata installed and the
donated indices remapped through kept_arg_indices (this also gives each
DDPOptimizer bucket its own metadata for lazy recompiles). The retrace itself
runs under that lock too, since it re-runs the joint trace under the shared
fake mode. Zero-folding of backward ops is restricted to the aten namespace: a
custom op merely named *_backward is not linear in its tangent.
Thread safety and caching. Each compiled backward is a _CompiledBackward entry
carrying its donation status and kept inputs; get_or_compile returns that
status with the backward, and the retain_graph check uses it instead of
re-reading shared metadata. A donated entry is published under _prepare_lock
only if bw_donated_idxs still equals the snapshot the compile used, so a
concurrent retain_graph clear cannot be followed by a donated last write that
would wedge every later retained backward. The AOTAutograd cache entry is
gated by the same decision and pickles a copy of fw_metadata fixed at that
snapshot (the save runs after the lock is released, when the live list may
already be cleared, and a loading process derives donation status from what
was pickled). Only the base backward is cached; a process whose first backward
is always partial never saves the entry, a known trade-off. CacheableAOTConfig
carries prune_unused_outputs because the cache-loaded autograd.Function reads
it at runtime. serialize_graph_module is non-mutating (GraphModule.reduce
never pickles node.meta, so only gm.meta is dropped, on the reduce copy): the
lazy backward info keeps the same bw_module for the retrace and structural
pruning, which need node.meta intact; the cost is that node.meta FakeTensors
stay alive with bw_module for the compiled function's lifetime, flag on or off.
A retrace that raises AssertionError declines to the fallbacks (logged) rather
than failing the user's backward.
Compiled autograd emits the grad-output prototype getattr node only when
pruning is on, so the flag-off graph is unchanged, and takes the same
per-context lock for its retrace.
Standalone artifacts. compile_to_python training artifacts import AOTAutograd
only through standalone_runtime: source_emit redirects every re-exported object
there by identity, and the surface holds the runtime helpers, the metadata
types, the whole closed set of descriptor classes, FunctionalTensor (the
raw_type baked into output metadata) and SymIntEqByExpr (baked MetadataKey
entries); BackwardState is bound into the forward only when the graph has
backward state, and the surface test matches every private torch path an
artifact could reach internals through. The direct compile_to_python path
captures under aot_autograd_prune_unused_outputs, matching the flag the emitted
glue bakes on, so the exact retrace is available and a declined retrace warns
instead of silently falling back to structural pruning; the standalone mask
compiler follows the live runtime's fallback policy and always serves mask 0.
standalone_compile marks user-visible outputs under keep_output_stride as
compile_fx does; module renaming converts ast byte offsets to str offsets; the
module names shared with torch._precompile are constants; the passthrough
backward consumes its argument list; a corrupt cache bundle does not discard
the good ones in a merge.
Suggested review order: torch/_functorch/config.py and schemas.py (the flag and
its capture), graph_compile.py (retrace helper), runtime_wrappers.py (live
path), compiled_autograd.py and to_standalone_python.py (the other two paths).
Test Plan:
New tests: retrace structural binding, ambiguous-fingerprint decline and
donated-buffer remapping (inductor), custom *_backward op preservation and a
unit test of the aten-only fold, concurrent partial backwards,
torch.autograd.grad on an output subset, cache save with the retrace still
binding, a training artifact loading in a fresh subprocess, the stable-surface
import assertion for training artifacts across private paths, non-ASCII module
renaming, passthrough argument release, and cache-merge tolerance.
Authored with an AI assistant.
Co-Authored-By: Claude Fable 5.1 [email protected]
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo @azahed98 @xmfan @aditvenk