Repository navigation
[precompile] Implement torch.compiler.precompile(tracer="dynamo") and load - #195360
Closed
bobrenjc93 wants to merge 20 commits into
Closed
bobrenjc93 wants to merge 20 commits into
bobrenjc93 wants to merge 20 commits into
Conversation
[ghstack-poisoned]
This was referenced Aug 30, 2026
Closed
[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
Ahead-of-time capture of a compiled computation into an artifact you can ship:
a self-contained Python source string plus a companion cache, the
``(python_code, cache)`` pair, reloaded with
``torch.compiler.precompile.load``. One contract for every capture shape.
code, cache = torch.compiler.precompile(fn, example_inputs=[(model, x)])
code, cache = torch.compiler.precompile( # graph breaks, recompiles
fn, example_inputs=[(model, x1), (model, x2)], tracer="dynamo")
served = torch.compiler.precompile.load(code, cache)
served(model, x)
``torch.compiler.precompile`` and its ``(python_code, cache)`` contract already
exist; ``tracer="dynamo"`` is the value the API declares as planned and rejects
with NotImplementedError. This implements it. The whole surface -- the call,
``load``, and the objects they return -- is marked as a prototype API in the
docs and docstrings: signatures, error types and the artifact format may change
between releases without a deprecation cycle.
It also makes ``example_inputs`` the ONLY calling convention, which is the other
half of what makes the tracer legible. precompile on main takes the example call
positionally -- and names that varargs parameter ``example_inputs`` -- so adding
a real ``example_inputs`` list beside it left two things with one name and a
``tracer`` argument that was load-bearing in one spelling and rejected in the
other. Now there is one convention and ``tracer`` is the only thing that selects
a front-end: ``"make_fx"`` (the default) is one non-strict ATen trace and takes
exactly one call, ``"dynamo"`` takes as many as you give it. A positional call
raises a TypeError naming the replacement. This is a BC break to an API that is
already on main; precompile is new enough that the blast radius is the tests.
The dynamo tracer keeps real guards and records every frame Dynamo compiled --
the entry frame plus each graph-break continuation, and every recompiled variant
of each -- into one artifact format. That is the shape aot_compile cannot express
at all: it produces exactly one graph and rejects graph breaks, so a model that
breaks 50 times and specializes 3 ways per frame cannot be precompiled today.
Collapsing the two spellings also settles the grad mode, which they used to
answer differently: the caller wrote the positional call so it ran in the
ambient mode, while precompile makes the ``example_inputs`` calls so it picked
``no_grad``. precompile now always makes the call, so ``training`` decides for
both tracers -- ``no_grad`` unless ``training=True``. For make_fx that is a
no-op on inference (the artifact is byte-identical either way, measured) and a
fix otherwise: ``training`` was previously accepted and silently ignored there.
The dynamo tracer mirrors ``torch.compile``. Where they used to differ it was
because a single-graph emitter worked around torch.compile locally -- an ambient
torch_function mode, for instance, which torch.compile applies twice and that
emitter applied once. Parity is the contract now, so those divergences are gone
and the make_fx path keeps the stronger guarantees.
Only the guards that DISCRIMINATE are serialized, and that is most of what makes
a real model viable rather than an optimization on top. Most guards cannot be
serialized at all -- identity guards on modules, callables, closure cells -- and
of those that can, the overwhelming majority are invariant: on a 62-frame
ranking model, 738 of its 1207 guard slots held the same fact in every captured
variant. Such a guard selects nothing. The contract precompile already asks for
is what licenses dropping it: the environment is identical at capture and at
runtime, and every variation in computation comes from the inputs, so an
invariant guard is either environment, pinned by that assumption, or an input
dimension the examples deliberately did not vary. The cost is real and is stated
in the code: a call outside the captured domain is served by a captured graph
rather than refused. Guards Dynamo never models -- SHAPE_ENV, GLOBAL_STATE and
the rest of _UNMODELLED_GUARD_TYPES -- are exempt, since they were never shown
to be constant, only never analyzed.
A slot is (guard_type, normalized source), and it is kept when two variants of
its frame recorded different facts for it OR when it is present in some variants
and absent in others. That second case is not a refinement, it is most of the
answer: 225 of the 274 slots kept, because a guard only one variant carries is
exactly what tells that variant apart. Which guards discriminate is knowable
only once every variant exists, and guards are serialized per compilation as
each is produced, so capture at this commit runs the examples twice: a probe
pass to learn, then ``torch._dynamo.reset()``, then a second pass keeping only
what varied. The passes agree by construction rather than by luck, since
PrecompileSession gives each session a fresh PGO state and enters under
_use_code_state, so the second cannot inherit the first's automatic-dynamic
learning.
Two properties of that policy are known to be wrong at this commit and are
fixed by the PR directly above, where the machinery to fix them lands, rather
than here. A capture is not free of side effects, so running every example
twice doubles a training step's accumulated gradients and guards a mutating
region (BatchNorm running stats, a step counter) on state the probe already
advanced past; the PR above captures once and applies the policy by
re-serializing from the pickle. And the drop policy here is fail-open: any
guard type outside _UNMODELLED_GUARD_TYPES that held invariant across the
examples is dropped, which includes guards whose loss changes the answer --
with a single example nothing can discriminate, so even the shape guard on the
input goes; the PR above introduces the never-drop set. Likewise the installed
driver's _entry_function does not yet apply _ENTRY_BINDING, so an installed
entry's defaults are restored only from the hardening PR at the top of the
stack.
How the multi-graph artifact serves depends on what it can reach, and the
artifact says which in its header. A source driver dispatches the entry frame
and the continuations the entry's bytecode names. When that covers every
captured frame -- the whole computation is one function that breaks a few times
-- the artifact is ``standalone``: it installs nothing, no frame evaluator is
involved, and the driver rebuilds each frame's guard trees and dispatches by
evaluating guards against the call.
A model that breaks inside nested module forwards is the other case, and it is
the common one. Those frames are entered by an ordinary call, so no name in the
entry reaches them and a source driver would run them eager -- correct, but with
every compiled variant unused. Such a capture is ``installed`` instead: the
driver rebuilds the package and hands the frames to the frame evaluator, which
reaches them by code object. The split keys on FRAME REACHABILITY, not on
whether the capture graph-broke: an entry-frame-only break is standalone.
``load`` still installs nothing; entering the result, or calling it, installs,
and ``unload``/exit takes it back out, so the mutation is attributable to a
point in the caller's control flow. Install, rebind and unload synchronize on a
lock, so two threads making the first call cannot both install the package
onto the same live code objects; serving is multi-thread safe. Calling an
installed artifact after ``unload()`` raises PrecompileError instead of
silently re-installing (and a call racing ``unload()`` cannot reinstall after
it returns); re-entering the handle as a context manager is the explicit way
to install again. ``unload()`` also takes back out of PrecompileContext exactly
the backend artifacts its install recorded, so an install/unload cycle does
not leak them for the life of the process. ``load(fn=...)`` installs onto
whatever function it is given, so it runs the same ``_check_artifact_matches``
check the path form does and refuses, as PrecompileError, a function the
artifact was not captured from.
Either way a call no captured variant covers RAISES rather than silently
compiling a new one, and reachability is computed as a closure: a continuation
counts as covered only once something that is itself reachable names it.
The emitted file is labelled, and the split is by what actually has a source
form. What was captured -- the frames, their variant counts, the guards that
could not be serialized, the values pinned to what capture saw -- is emitted as
readable literals. The compiled subgraphs are RENDERED AS SOURCE, kernels and
all, through the same aot_autograd.compile_to_python the make_fx tracer uses:
they are Inductor output, not Dynamo state, so pickling them was a default
rather than a constraint, and it was most of the file. On a graph-breaking model
with two shape variants that is 379,657 chars -> 102,950 with 8 readable
triton.jit kernels; on a two-variant toy, 197,843 -> 54,632. Only the guard
trees and the transformed bytecode, which genuinely have no source form, remain
under an OPAQUE banner.
Rendering is per subgraph and the blocks share one namespace, which is the whole
difficulty. Two variants of one frame are the same computation at different
shapes, so they render the SAME top-level names, and a block resolves its
siblings as late-bound globals -- its ``call`` looks up ``_runtime_wrapper`` and
``_inner_call``, its ``Runner`` looks up the kernels. Left alone, the batch-2
variant silently runs the batch-4 variant's code. Every top-level name a block
defines is therefore suffixed per subgraph, driven by AST positions rather than
a text match: that is what keeps an attribute (``runner.call``), a nested
binding (``def call`` inside ``class Runner``) and a dotted import path
(``torch._inductor.async_compile``) out of the rewrite, each of which broke a
regex first.
A training capture keeps the bundle instead, and that is refused up front rather
than caught: compile_to_python pins AOTAutograd to the inference path, so a
training graph RENDERS SUCCESSFULLY with the backward silently gone and the
served output missing its grad_fn. The eager backend keeps it too (its backends
are fx graphs with nothing to render), as does any single subgraph whose
lowering fails; the header reports how many fell back.
The public surface is deliberately two calls. ``precompile()`` runs the examples
itself and returns the pair; ``precompile.load()`` reads it back. There is no
capture object the caller drives by hand: with ``training=True`` covering the
case that used to need one, a session would only be a second way to say the same
thing, and it would be the way that requires a loss.
``training=True`` makes it a drop-in for a training step. The examples then run
with grad enabled and the backward is lowered eagerly, so the artifact carries
one: a served output arrives with grad_fn=CompiledFunctionBackward and
``.backward()`` runs precompiled code. No loss is required for that, and none is
asked for -- AOTAutograd's joint trace already synthesizes tangents from the
forward outputs' own metadata, and already wraps the result in a
torch.autograd.Function. All that was missing is that it lowers the backward
lazily, on the first ``.backward()`` call, so a capture that never makes one
records a forward and nothing else. Two serialization bugs sat on that path and
are fixed here, both reachable only once there are grads to serialize: a
parameter's .grad is read by no guard, so it is pruned to the _Missing sentinel
and _unpickle_tensor then assigned the sentinel and raised at LOAD, and the
reducer read .grad off non-leaf tensors, which is always None and warns.
One fix in guards.py is required rather than incidental. Value pruning keys off
the guard tree: anything the tree does not reach is replaced by a placeholder.
Dropping a guard therefore dropped the VALUE it named while the rest of the
state still referred to it, and the artifact failed to load with
"empty_strided(): argument 'dtype' must be torch.dtype, not _Missing". Pruning
now follows the unfiltered tree. Note this only masks the underlying issue:
missing_values is keyed by id, so one unguarded attribute holding torch.bfloat16
can stand in for every reference to that dtype in the pickle. That is a latent
bug of its own and wants a separate fix.
Explicit capture and serve are a distinct mode from the ambient
caching_precompile cache -- guards are built strictly, only the filtered copy
is recorded, and the package is never auto-persisted -- and that mode is a
``CompilePackage.explicit_capture`` attribute, threaded through
``DynamoOutput.build_guards`` into ``CheckFunctionManager``. It used to be
inferred from ``serialization_guard_filter_fn is not None``, which made the
filter double as a mode flag; convert_frame's bypass and DynamoCache paths,
the caching_precompile guard-filter override and the strict-error selection
all read the attribute now. Relatedly, ``PrecompileContext.create_cache_entries``
deep-copies each dynamo cache entry before ``PrecompileCacheEntry.from_cache_entry``,
because from_cache_entry marks a code whose backend it cannot find as bypassed
on the entry it is handed: saving must not flip the LIVE entry that keeps
serving this process.
A CPU codegen-target drift mid-capture is recorded with a warning rather than
raised from inside update_device_type -- i.e. from inside EVERY compile,
including the ambient caching_precompile path an ordinary torch.compile user
is on. The refusal lives in an explicit ``refuse_unserializable()`` invoked
only at serialization boundaries (record_package, path saves, artifact
builds), not in ``cache_entry()``, which introspection and teardown also call:
a drifted package still builds a cache_entry for ``summary()`` while every
serialization path refuses, and the ambient recorder downgrades that to a
skipped save. The dynamo driver's Python-version lock and a missing captured
module raise the PrecompileError the docs promise rather than a bare
ValueError/ModuleNotFoundError, and GuardFact/FrameInvariants/PrecompileSummary
are ordinary picklable classes (they no longer claim a ``torch.compiler``
``__module__`` that nothing exports).
Three things worth knowing before relying on an artifact. Capture is by
execution, so an unexercised path is simply absent and a complete summary means
complete for the calls that ran. A bare nn.Module is refused: Dynamo compiles
its own wrapper frame, which closes over the module, so the entry frame holds no
graph and no artifact can rebuild that closure -- capture the function that
calls the model instead, which the error says. And an installed artifact
rebuilds its entry from that entry's code object, which cannot restore a
closure, so a closure entry is likewise refused at capture, where the closure is
visible, rather than on the serving machine.
Review it in five pieces: the programming-model contract in Note [precompile
programming model]; the make_fx emitter and its drivers; the multi-graph
capture session, its two passes and its gates; the standalone dispatcher; and
the public surface in torch/compiler with its docs, which describe the shipped
multigraph tracer (training serves through the live autograd engine after a
graph break at .backward(), graph breaks are preserved rather than refused,
decompositions= is rejected with tracer='dynamo', mark_unbacked(strict=True)
is read by Dynamo as a backed dynamic dim, the driver re-evaluates each
variant's serialized guards, and load()'s fn= keyword and its two return
shapes are documented).
Test Plan:
```
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_recompile_ux.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_misc.py
```
297 precompile tests. The API rework rewrote 171 call sites mechanically; 34
tests then failed with "no captured variant matches", which is the grad-mode
change above surfacing -- those captures had been relying on the ambient mode --
and they now say ``training=True`` explicitly. Tests that need Triton gate on
HAS_CUDA_AND_TRITON rather than cuda.is_available(), and the device-generic
numerics class instantiates only its CPU variants when no GPU is present.
Automatic dynamic is covered across graph breaks: a dim that varies is detected
per frame, so a continuation whose input varied is promoted to dynamic while an
entry frame whose input never did stays specialized, and unseen shapes then
serve. The graph-break suite runs each of six break shapes -- a disabled callee,
a disabled method, explicit breaks, a data-dependent break, a break in a child
module, a break inside a loop -- on both backends and asserts the served result
equals what torch.compile returns for the same call. The installed mode is
pinned for load(fn=) refusing a foreign function, unload() releasing the
recorded backends, a call after unload raising, and a version-skewed artifact
raising PrecompileError from an exec'd driver; test_package.py pins that
saving does not bypass the live cache entry.
On the 62-frame ranking model that motivated this: 738 of 1207 guard slots
dropped, all five captured calls exact with zero graphs compiled while serving,
capture 5.6s for one pass and 10.3s for the two.
Authored with an AI assistant.
ghstack-source-id: 78ac1c0
Pull-Request: #195360
[ghstack-poisoned]
bobrenjc93
added a commit
that referenced
this pull request
Sep 2, 2026
Ahead-of-time capture of a compiled computation into an artifact you can ship:
a self-contained Python source string plus a companion cache, the
``(python_code, cache)`` pair, reloaded with
``torch.compiler.precompile.load``. One contract for every capture shape.
code, cache = torch.compiler.precompile(fn, example_inputs=[(model, x)])
code, cache = torch.compiler.precompile( # graph breaks, recompiles
fn, example_inputs=[(model, x1), (model, x2)], tracer="dynamo")
served = torch.compiler.precompile.load(code, cache)
served(model, x)
``torch.compiler.precompile`` and its ``(python_code, cache)`` contract already
exist; ``tracer="dynamo"`` is the value the API declares as planned and rejects
with NotImplementedError. This implements it. The whole surface -- the call,
``load``, and the objects they return -- is marked as a prototype API in the
docs and docstrings: signatures, error types and the artifact format may change
between releases without a deprecation cycle.
It also makes ``example_inputs`` the ONLY calling convention, which is the other
half of what makes the tracer legible. precompile on main takes the example call
positionally -- and names that varargs parameter ``example_inputs`` -- so adding
a real ``example_inputs`` list beside it left two things with one name and a
``tracer`` argument that was load-bearing in one spelling and rejected in the
other. Now there is one convention and ``tracer`` is the only thing that selects
a front-end: ``"make_fx"`` (the default) is one non-strict ATen trace and takes
exactly one call, ``"dynamo"`` takes as many as you give it. A positional call
raises a TypeError naming the replacement. This is a BC break to an API that is
already on main; precompile is new enough that the blast radius is the tests.
The dynamo tracer keeps real guards and records every frame Dynamo compiled --
the entry frame plus each graph-break continuation, and every recompiled variant
of each -- into one artifact format. That is the shape aot_compile cannot express
at all: it produces exactly one graph and rejects graph breaks, so a model that
breaks 50 times and specializes 3 ways per frame cannot be precompiled today.
Collapsing the two spellings also settles the grad mode, which they used to
answer differently: the caller wrote the positional call so it ran in the
ambient mode, while precompile makes the ``example_inputs`` calls so it picked
``no_grad``. precompile now always makes the call, so ``training`` decides for
both tracers -- ``no_grad`` unless ``training=True``. For make_fx that is a
no-op on inference (the artifact is byte-identical either way, measured) and a
fix otherwise: ``training`` was previously accepted and silently ignored there.
The dynamo tracer mirrors ``torch.compile``. Where they used to differ it was
because a single-graph emitter worked around torch.compile locally -- an ambient
torch_function mode, for instance, which torch.compile applies twice and that
emitter applied once. Parity is the contract now, so those divergences are gone
and the make_fx path keeps the stronger guarantees.
Only the guards that DISCRIMINATE are serialized, and that is most of what makes
a real model viable rather than an optimization on top. Most guards cannot be
serialized at all -- identity guards on modules, callables, closure cells -- and
of those that can, the overwhelming majority are invariant: on a 62-frame
ranking model, 738 of its 1207 guard slots held the same fact in every captured
variant. Such a guard selects nothing. The contract precompile already asks for
is what licenses dropping it: the environment is identical at capture and at
runtime, and every variation in computation comes from the inputs, so an
invariant guard is either environment, pinned by that assumption, or an input
dimension the examples deliberately did not vary. The cost is real and is stated
in the code: a call outside the captured domain is served by a captured graph
rather than refused. Guards Dynamo never models -- SHAPE_ENV, GLOBAL_STATE and
the rest of _UNMODELLED_GUARD_TYPES -- are exempt, since they were never shown
to be constant, only never analyzed.
A slot is (guard_type, normalized source), and it is kept when two variants of
its frame recorded different facts for it OR when it is present in some variants
and absent in others. That second case is not a refinement, it is most of the
answer: 225 of the 274 slots kept, because a guard only one variant carries is
exactly what tells that variant apart. Which guards discriminate is knowable
only once every variant exists, and guards are serialized per compilation as
each is produced, so capture at this commit runs the examples twice: a probe
pass to learn, then ``torch._dynamo.reset()``, then a second pass keeping only
what varied. The passes agree by construction rather than by luck, since
PrecompileSession gives each session a fresh PGO state and enters under
_use_code_state, so the second cannot inherit the first's automatic-dynamic
learning.
Two properties of that policy are known to be wrong at this commit and are
fixed by the PR directly above, where the machinery to fix them lands, rather
than here. A capture is not free of side effects, so running every example
twice doubles a training step's accumulated gradients and guards a mutating
region (BatchNorm running stats, a step counter) on state the probe already
advanced past; the PR above captures once and applies the policy by
re-serializing from the pickle. And the drop policy here is fail-open: any
guard type outside _UNMODELLED_GUARD_TYPES that held invariant across the
examples is dropped, which includes guards whose loss changes the answer --
with a single example nothing can discriminate, so even the shape guard on the
input goes; the PR above introduces the never-drop set. Likewise the installed
driver's _entry_function does not yet apply _ENTRY_BINDING, so an installed
entry's defaults are restored only from the hardening PR at the top of the
stack.
How the multi-graph artifact serves depends on what it can reach, and the
artifact says which in its header. A source driver dispatches the entry frame
and the continuations the entry's bytecode names. When that covers every
captured frame -- the whole computation is one function that breaks a few times
-- the artifact is ``standalone``: it installs nothing, no frame evaluator is
involved, and the driver rebuilds each frame's guard trees and dispatches by
evaluating guards against the call.
A model that breaks inside nested module forwards is the other case, and it is
the common one. Those frames are entered by an ordinary call, so no name in the
entry reaches them and a source driver would run them eager -- correct, but with
every compiled variant unused. Such a capture is ``installed`` instead: the
driver rebuilds the package and hands the frames to the frame evaluator, which
reaches them by code object. The split keys on FRAME REACHABILITY, not on
whether the capture graph-broke: an entry-frame-only break is standalone.
``load`` still installs nothing; entering the result, or calling it, installs,
and ``unload``/exit takes it back out, so the mutation is attributable to a
point in the caller's control flow. Install, rebind and unload synchronize on a
lock, so two threads making the first call cannot both install the package
onto the same live code objects; serving is multi-thread safe. Calling an
installed artifact after ``unload()`` raises PrecompileError instead of
silently re-installing (and a call racing ``unload()`` cannot reinstall after
it returns); re-entering the handle as a context manager is the explicit way
to install again. ``unload()`` also takes back out of PrecompileContext exactly
the backend artifacts its install recorded, so an install/unload cycle does
not leak them for the life of the process. ``load(fn=...)`` installs onto
whatever function it is given, so it runs the same ``_check_artifact_matches``
check the path form does and refuses, as PrecompileError, a function the
artifact was not captured from.
Either way a call no captured variant covers RAISES rather than silently
compiling a new one, and reachability is computed as a closure: a continuation
counts as covered only once something that is itself reachable names it.
The emitted file is labelled, and the split is by what actually has a source
form. What was captured -- the frames, their variant counts, the guards that
could not be serialized, the values pinned to what capture saw -- is emitted as
readable literals. The compiled subgraphs are RENDERED AS SOURCE, kernels and
all, through the same aot_autograd.compile_to_python the make_fx tracer uses:
they are Inductor output, not Dynamo state, so pickling them was a default
rather than a constraint, and it was most of the file. On a graph-breaking model
with two shape variants that is 379,657 chars -> 102,950 with 8 readable
triton.jit kernels; on a two-variant toy, 197,843 -> 54,632. Only the guard
trees and the transformed bytecode, which genuinely have no source form, remain
under an OPAQUE banner.
Rendering is per subgraph and the blocks share one namespace, which is the whole
difficulty. Two variants of one frame are the same computation at different
shapes, so they render the SAME top-level names, and a block resolves its
siblings as late-bound globals -- its ``call`` looks up ``_runtime_wrapper`` and
``_inner_call``, its ``Runner`` looks up the kernels. Left alone, the batch-2
variant silently runs the batch-4 variant's code. Every top-level name a block
defines is therefore suffixed per subgraph, driven by AST positions rather than
a text match: that is what keeps an attribute (``runner.call``), a nested
binding (``def call`` inside ``class Runner``) and a dotted import path
(``torch._inductor.async_compile``) out of the rewrite, each of which broke a
regex first.
A training capture keeps the bundle instead, and that is refused up front rather
than caught: compile_to_python pins AOTAutograd to the inference path, so a
training graph RENDERS SUCCESSFULLY with the backward silently gone and the
served output missing its grad_fn. The eager backend keeps it too (its backends
are fx graphs with nothing to render), as does any single subgraph whose
lowering fails; the header reports how many fell back.
The public surface is deliberately two calls. ``precompile()`` runs the examples
itself and returns the pair; ``precompile.load()`` reads it back. There is no
capture object the caller drives by hand: with ``training=True`` covering the
case that used to need one, a session would only be a second way to say the same
thing, and it would be the way that requires a loss.
``training=True`` makes it a drop-in for a training step. The examples then run
with grad enabled and the backward is lowered eagerly, so the artifact carries
one: a served output arrives with grad_fn=CompiledFunctionBackward and
``.backward()`` runs precompiled code. No loss is required for that, and none is
asked for -- AOTAutograd's joint trace already synthesizes tangents from the
forward outputs' own metadata, and already wraps the result in a
torch.autograd.Function. All that was missing is that it lowers the backward
lazily, on the first ``.backward()`` call, so a capture that never makes one
records a forward and nothing else. Two serialization bugs sat on that path and
are fixed here, both reachable only once there are grads to serialize: a
parameter's .grad is read by no guard, so it is pruned to the _Missing sentinel
and _unpickle_tensor then assigned the sentinel and raised at LOAD, and the
reducer read .grad off non-leaf tensors, which is always None and warns.
One fix in guards.py is required rather than incidental. Value pruning keys off
the guard tree: anything the tree does not reach is replaced by a placeholder.
Dropping a guard therefore dropped the VALUE it named while the rest of the
state still referred to it, and the artifact failed to load with
"empty_strided(): argument 'dtype' must be torch.dtype, not _Missing". Pruning
now follows the unfiltered tree. Note this only masks the underlying issue:
missing_values is keyed by id, so one unguarded attribute holding torch.bfloat16
can stand in for every reference to that dtype in the pickle. That is a latent
bug of its own and wants a separate fix.
Explicit capture and serve are a distinct mode from the ambient
caching_precompile cache -- guards are built strictly, only the filtered copy
is recorded, and the package is never auto-persisted -- and that mode is a
``CompilePackage.explicit_capture`` attribute, threaded through
``DynamoOutput.build_guards`` into ``CheckFunctionManager``. It used to be
inferred from ``serialization_guard_filter_fn is not None``, which made the
filter double as a mode flag; convert_frame's bypass and DynamoCache paths,
the caching_precompile guard-filter override and the strict-error selection
all read the attribute now. Relatedly, ``PrecompileContext.create_cache_entries``
deep-copies each dynamo cache entry before ``PrecompileCacheEntry.from_cache_entry``,
because from_cache_entry marks a code whose backend it cannot find as bypassed
on the entry it is handed: saving must not flip the LIVE entry that keeps
serving this process.
A CPU codegen-target drift mid-capture is recorded with a warning rather than
raised from inside update_device_type -- i.e. from inside EVERY compile,
including the ambient caching_precompile path an ordinary torch.compile user
is on. The refusal lives in an explicit ``refuse_unserializable()`` invoked
only at serialization boundaries (record_package, path saves, artifact
builds), not in ``cache_entry()``, which introspection and teardown also call:
a drifted package still builds a cache_entry for ``summary()`` while every
serialization path refuses, and the ambient recorder downgrades that to a
skipped save. The dynamo driver's Python-version lock and a missing captured
module raise the PrecompileError the docs promise rather than a bare
ValueError/ModuleNotFoundError, and GuardFact/FrameInvariants/PrecompileSummary
are ordinary picklable classes (they no longer claim a ``torch.compiler``
``__module__`` that nothing exports).
Three things worth knowing before relying on an artifact. Capture is by
execution, so an unexercised path is simply absent and a complete summary means
complete for the calls that ran. A bare nn.Module is refused: Dynamo compiles
its own wrapper frame, which closes over the module, so the entry frame holds no
graph and no artifact can rebuild that closure -- capture the function that
calls the model instead, which the error says. And an installed artifact
rebuilds its entry from that entry's code object, which cannot restore a
closure, so a closure entry is likewise refused at capture, where the closure is
visible, rather than on the serving machine.
Review it in five pieces: the programming-model contract in Note [precompile
programming model]; the make_fx emitter and its drivers; the multi-graph
capture session, its two passes and its gates; the standalone dispatcher; and
the public surface in torch/compiler with its docs, which describe the shipped
multigraph tracer (training serves through the live autograd engine after a
graph break at .backward(), graph breaks are preserved rather than refused,
decompositions= is rejected with tracer='dynamo', mark_unbacked(strict=True)
is read by Dynamo as a backed dynamic dim, the driver re-evaluates each
variant's serialized guards, and load()'s fn= keyword and its two return
shapes are documented).
Test Plan:
```
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_recompile_ux.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_misc.py
```
297 precompile tests. The API rework rewrote 171 call sites mechanically; 34
tests then failed with "no captured variant matches", which is the grad-mode
change above surfacing -- those captures had been relying on the ambient mode --
and they now say ``training=True`` explicitly. Tests that need Triton gate on
HAS_CUDA_AND_TRITON rather than cuda.is_available(), and the device-generic
numerics class instantiates only its CPU variants when no GPU is present.
Automatic dynamic is covered across graph breaks: a dim that varies is detected
per frame, so a continuation whose input varied is promoted to dynamic while an
entry frame whose input never did stays specialized, and unseen shapes then
serve. The graph-break suite runs each of six break shapes -- a disabled callee,
a disabled method, explicit breaks, a data-dependent break, a break in a child
module, a break inside a loop -- on both backends and asserts the served result
equals what torch.compile returns for the same call. The installed mode is
pinned for load(fn=) refusing a foreign function, unload() releasing the
recorded backends, a call after unload raising, and a version-skewed artifact
raising PrecompileError from an exec'd driver; test_package.py pins that
saving does not bypass the live cache entry.
On the 62-frame ranking model that motivated this: 738 of 1207 guard slots
dropped, all five captured calls exact with zero graphs compiled while serving,
capture 5.6s for one pass and 10.3s for the two.
Authored with an AI assistant.
ghstack-source-id: 65715d0
Pull-Request: #195360
bobrenjc93
added a commit
that referenced
this pull request
Sep 2, 2026
Ahead-of-time capture of a compiled computation into an artifact you can ship:
a self-contained Python source string plus a companion cache, the
``(python_code, cache)`` pair, reloaded with
``torch.compiler.precompile.load``. One contract for every capture shape.
code, cache = torch.compiler.precompile(fn, example_inputs=[(model, x)])
code, cache = torch.compiler.precompile( # graph breaks, recompiles
fn, example_inputs=[(model, x1), (model, x2)], tracer="dynamo")
served = torch.compiler.precompile.load(code, cache)
served(model, x)
``torch.compiler.precompile`` and its ``(python_code, cache)`` contract already
exist; ``tracer="dynamo"`` is the value the API declares as planned and rejects
with NotImplementedError. This implements it. The whole surface -- the call,
``load``, and the objects they return -- is marked as a prototype API in the
docs and docstrings: signatures, error types and the artifact format may change
between releases without a deprecation cycle.
It also makes ``example_inputs`` the ONLY calling convention, which is the other
half of what makes the tracer legible. precompile on main takes the example call
positionally -- and names that varargs parameter ``example_inputs`` -- so adding
a real ``example_inputs`` list beside it left two things with one name and a
``tracer`` argument that was load-bearing in one spelling and rejected in the
other. Now there is one convention and ``tracer`` is the only thing that selects
a front-end: ``"make_fx"`` (the default) is one non-strict ATen trace and takes
exactly one call, ``"dynamo"`` takes as many as you give it. A positional call
raises a TypeError naming the replacement. This is a BC break to an API that is
already on main; precompile is new enough that the blast radius is the tests.
The dynamo tracer keeps real guards and records every frame Dynamo compiled --
the entry frame plus each graph-break continuation, and every recompiled variant
of each -- into one artifact format. That is the shape aot_compile cannot express
at all: it produces exactly one graph and rejects graph breaks, so a model that
breaks 50 times and specializes 3 ways per frame cannot be precompiled today.
Collapsing the two spellings also settles the grad mode, which they used to
answer differently: the caller wrote the positional call so it ran in the
ambient mode, while precompile makes the ``example_inputs`` calls so it picked
``no_grad``. precompile now always makes the call, so ``training`` decides for
both tracers -- ``no_grad`` unless ``training=True``. For make_fx that is a
no-op on inference (the artifact is byte-identical either way, measured) and a
fix otherwise: ``training`` was previously accepted and silently ignored there.
The dynamo tracer mirrors ``torch.compile``. Where they used to differ it was
because a single-graph emitter worked around torch.compile locally -- an ambient
torch_function mode, for instance, which torch.compile applies twice and that
emitter applied once. Parity is the contract now, so those divergences are gone
and the make_fx path keeps the stronger guarantees.
Only the guards that DISCRIMINATE are serialized, and that is most of what makes
a real model viable rather than an optimization on top. Most guards cannot be
serialized at all -- identity guards on modules, callables, closure cells -- and
of those that can, the overwhelming majority are invariant: on a 62-frame
ranking model, 738 of its 1207 guard slots held the same fact in every captured
variant. Such a guard selects nothing. The contract precompile already asks for
is what licenses dropping it: the environment is identical at capture and at
runtime, and every variation in computation comes from the inputs, so an
invariant guard is either environment, pinned by that assumption, or an input
dimension the examples deliberately did not vary. The cost is real and is stated
in the code: a call outside the captured domain is served by a captured graph
rather than refused. Guards Dynamo never models -- SHAPE_ENV, GLOBAL_STATE and
the rest of _UNMODELLED_GUARD_TYPES -- are exempt, since they were never shown
to be constant, only never analyzed.
A slot is (guard_type, normalized source), and it is kept when two variants of
its frame recorded different facts for it OR when it is present in some variants
and absent in others. That second case is not a refinement, it is most of the
answer: 225 of the 274 slots kept, because a guard only one variant carries is
exactly what tells that variant apart. Which guards discriminate is knowable
only once every variant exists, and guards are serialized per compilation as
each is produced, so capture at this commit runs the examples twice: a probe
pass to learn, then ``torch._dynamo.reset()``, then a second pass keeping only
what varied. The passes agree by construction rather than by luck, since
PrecompileSession gives each session a fresh PGO state and enters under
_use_code_state, so the second cannot inherit the first's automatic-dynamic
learning.
Two properties of that policy are known to be wrong at this commit and are
fixed by the PR directly above, where the machinery to fix them lands, rather
than here. A capture is not free of side effects, so running every example
twice doubles a training step's accumulated gradients and guards a mutating
region (BatchNorm running stats, a step counter) on state the probe already
advanced past; the PR above captures once and applies the policy by
re-serializing from the pickle. And the drop policy here is fail-open: any
guard type outside _UNMODELLED_GUARD_TYPES that held invariant across the
examples is dropped, which includes guards whose loss changes the answer --
with a single example nothing can discriminate, so even the shape guard on the
input goes; the PR above introduces the never-drop set. Likewise the installed
driver's _entry_function does not yet apply _ENTRY_BINDING, so an installed
entry's defaults are restored only from the hardening PR at the top of the
stack.
How the multi-graph artifact serves depends on what it can reach, and the
artifact says which in its header. A source driver dispatches the entry frame
and the continuations the entry's bytecode names. When that covers every
captured frame -- the whole computation is one function that breaks a few times
-- the artifact is ``standalone``: it installs nothing, no frame evaluator is
involved, and the driver rebuilds each frame's guard trees and dispatches by
evaluating guards against the call.
A model that breaks inside nested module forwards is the other case, and it is
the common one. Those frames are entered by an ordinary call, so no name in the
entry reaches them and a source driver would run them eager -- correct, but with
every compiled variant unused. Such a capture is ``installed`` instead: the
driver rebuilds the package and hands the frames to the frame evaluator, which
reaches them by code object. The split keys on FRAME REACHABILITY, not on
whether the capture graph-broke: an entry-frame-only break is standalone.
``load`` still installs nothing; entering the result, or calling it, installs,
and ``unload``/exit takes it back out, so the mutation is attributable to a
point in the caller's control flow. Install, rebind and unload synchronize on a
lock, so two threads making the first call cannot both install the package
onto the same live code objects; serving is multi-thread safe. Calling an
installed artifact after ``unload()`` raises PrecompileError instead of
silently re-installing (and a call racing ``unload()`` cannot reinstall after
it returns); re-entering the handle as a context manager is the explicit way
to install again. ``unload()`` also takes back out of PrecompileContext exactly
the backend artifacts its install recorded, so an install/unload cycle does
not leak them for the life of the process. ``load(fn=...)`` installs onto
whatever function it is given, so it runs the same ``_check_artifact_matches``
check the path form does and refuses, as PrecompileError, a function the
artifact was not captured from.
Either way a call no captured variant covers RAISES rather than silently
compiling a new one, and reachability is computed as a closure: a continuation
counts as covered only once something that is itself reachable names it.
The emitted file is labelled, and the split is by what actually has a source
form. What was captured -- the frames, their variant counts, the guards that
could not be serialized, the values pinned to what capture saw -- is emitted as
readable literals. The compiled subgraphs are RENDERED AS SOURCE, kernels and
all, through the same aot_autograd.compile_to_python the make_fx tracer uses:
they are Inductor output, not Dynamo state, so pickling them was a default
rather than a constraint, and it was most of the file. On a graph-breaking model
with two shape variants that is 379,657 chars -> 102,950 with 8 readable
triton.jit kernels; on a two-variant toy, 197,843 -> 54,632. Only the guard
trees and the transformed bytecode, which genuinely have no source form, remain
under an OPAQUE banner.
Rendering is per subgraph and the blocks share one namespace, which is the whole
difficulty. Two variants of one frame are the same computation at different
shapes, so they render the SAME top-level names, and a block resolves its
siblings as late-bound globals -- its ``call`` looks up ``_runtime_wrapper`` and
``_inner_call``, its ``Runner`` looks up the kernels. Left alone, the batch-2
variant silently runs the batch-4 variant's code. Every top-level name a block
defines is therefore suffixed per subgraph, driven by AST positions rather than
a text match: that is what keeps an attribute (``runner.call``), a nested
binding (``def call`` inside ``class Runner``) and a dotted import path
(``torch._inductor.async_compile``) out of the rewrite, each of which broke a
regex first.
A training capture keeps the bundle instead, and that is refused up front rather
than caught: compile_to_python pins AOTAutograd to the inference path, so a
training graph RENDERS SUCCESSFULLY with the backward silently gone and the
served output missing its grad_fn. The eager backend keeps it too (its backends
are fx graphs with nothing to render), as does any single subgraph whose
lowering fails; the header reports how many fell back.
The public surface is deliberately two calls. ``precompile()`` runs the examples
itself and returns the pair; ``precompile.load()`` reads it back. There is no
capture object the caller drives by hand: with ``training=True`` covering the
case that used to need one, a session would only be a second way to say the same
thing, and it would be the way that requires a loss.
``training=True`` makes it a drop-in for a training step. The examples then run
with grad enabled and the backward is lowered eagerly, so the artifact carries
one: a served output arrives with grad_fn=CompiledFunctionBackward and
``.backward()`` runs precompiled code. No loss is required for that, and none is
asked for -- AOTAutograd's joint trace already synthesizes tangents from the
forward outputs' own metadata, and already wraps the result in a
torch.autograd.Function. All that was missing is that it lowers the backward
lazily, on the first ``.backward()`` call, so a capture that never makes one
records a forward and nothing else. Two serialization bugs sat on that path and
are fixed here, both reachable only once there are grads to serialize: a
parameter's .grad is read by no guard, so it is pruned to the _Missing sentinel
and _unpickle_tensor then assigned the sentinel and raised at LOAD, and the
reducer read .grad off non-leaf tensors, which is always None and warns.
One fix in guards.py is required rather than incidental. Value pruning keys off
the guard tree: anything the tree does not reach is replaced by a placeholder.
Dropping a guard therefore dropped the VALUE it named while the rest of the
state still referred to it, and the artifact failed to load with
"empty_strided(): argument 'dtype' must be torch.dtype, not _Missing". Pruning
now follows the unfiltered tree. Note this only masks the underlying issue:
missing_values is keyed by id, so one unguarded attribute holding torch.bfloat16
can stand in for every reference to that dtype in the pickle. That is a latent
bug of its own and wants a separate fix.
Explicit capture and serve are a distinct mode from the ambient
caching_precompile cache -- guards are built strictly, only the filtered copy
is recorded, and the package is never auto-persisted -- and that mode is a
``CompilePackage.explicit_capture`` attribute, threaded through
``DynamoOutput.build_guards`` into ``CheckFunctionManager``. It used to be
inferred from ``serialization_guard_filter_fn is not None``, which made the
filter double as a mode flag; convert_frame's bypass and DynamoCache paths,
the caching_precompile guard-filter override and the strict-error selection
all read the attribute now. Relatedly, ``PrecompileContext.create_cache_entries``
deep-copies each dynamo cache entry before ``PrecompileCacheEntry.from_cache_entry``,
because from_cache_entry marks a code whose backend it cannot find as bypassed
on the entry it is handed: saving must not flip the LIVE entry that keeps
serving this process.
A CPU codegen-target drift mid-capture is recorded with a warning rather than
raised from inside update_device_type -- i.e. from inside EVERY compile,
including the ambient caching_precompile path an ordinary torch.compile user
is on. The refusal lives in an explicit ``refuse_unserializable()`` invoked
only at serialization boundaries (record_package, path saves, artifact
builds), not in ``cache_entry()``, which introspection and teardown also call:
a drifted package still builds a cache_entry for ``summary()`` while every
serialization path refuses, and the ambient recorder downgrades that to a
skipped save. The dynamo driver's Python-version lock and a missing captured
module raise the PrecompileError the docs promise rather than a bare
ValueError/ModuleNotFoundError, and GuardFact/FrameInvariants/PrecompileSummary
are ordinary picklable classes (they no longer claim a ``torch.compiler``
``__module__`` that nothing exports).
Three things worth knowing before relying on an artifact. Capture is by
execution, so an unexercised path is simply absent and a complete summary means
complete for the calls that ran. A bare nn.Module is refused: Dynamo compiles
its own wrapper frame, which closes over the module, so the entry frame holds no
graph and no artifact can rebuild that closure -- capture the function that
calls the model instead, which the error says. And an installed artifact
rebuilds its entry from that entry's code object, which cannot restore a
closure, so a closure entry is likewise refused at capture, where the closure is
visible, rather than on the serving machine.
Review it in five pieces: the programming-model contract in Note [precompile
programming model]; the make_fx emitter and its drivers; the multi-graph
capture session, its two passes and its gates; the standalone dispatcher; and
the public surface in torch/compiler with its docs, which describe the shipped
multigraph tracer (training serves through the live autograd engine after a
graph break at .backward(), graph breaks are preserved rather than refused,
decompositions= is rejected with tracer='dynamo', mark_unbacked(strict=True)
is read by Dynamo as a backed dynamic dim, the driver re-evaluates each
variant's serialized guards, and load()'s fn= keyword and its two return
shapes are documented).
Test Plan:
```
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_recompile_ux.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_misc.py
```
297 precompile tests. The API rework rewrote 171 call sites mechanically; 34
tests then failed with "no captured variant matches", which is the grad-mode
change above surfacing -- those captures had been relying on the ambient mode --
and they now say ``training=True`` explicitly. Tests that need Triton gate on
HAS_CUDA_AND_TRITON rather than cuda.is_available(), and the device-generic
numerics class instantiates only its CPU variants when no GPU is present.
Automatic dynamic is covered across graph breaks: a dim that varies is detected
per frame, so a continuation whose input varied is promoted to dynamic while an
entry frame whose input never did stays specialized, and unseen shapes then
serve. The graph-break suite runs each of six break shapes -- a disabled callee,
a disabled method, explicit breaks, a data-dependent break, a break in a child
module, a break inside a loop -- on both backends and asserts the served result
equals what torch.compile returns for the same call. The installed mode is
pinned for load(fn=) refusing a foreign function, unload() releasing the
recorded backends, a call after unload raising, and a version-skewed artifact
raising PrecompileError from an exec'd driver; test_package.py pins that
saving does not bypass the live cache entry.
On the 62-frame ranking model that motivated this: 738 of 1207 guard slots
dropped, all five captured calls exact with zero graphs compiled while serving,
capture 5.6s for one pass and 10.3s for the two.
Authored with an AI assistant.
ghstack-source-id: 65715d0
Pull-Request: #195360
bobrenjc93
added a commit
that referenced
this pull request
Sep 2, 2026
Ahead-of-time capture of a compiled computation into an artifact you can ship:
a self-contained Python source string plus a companion cache, the
``(python_code, cache)`` pair, reloaded with
``torch.compiler.precompile.load``. One contract for every capture shape.
code, cache = torch.compiler.precompile(fn, example_inputs=[(model, x)])
code, cache = torch.compiler.precompile( # graph breaks, recompiles
fn, example_inputs=[(model, x1), (model, x2)], tracer="dynamo")
served = torch.compiler.precompile.load(code, cache)
served(model, x)
``torch.compiler.precompile`` and its ``(python_code, cache)`` contract already
exist; ``tracer="dynamo"`` is the value the API declares as planned and rejects
with NotImplementedError. This implements it. The whole surface -- the call,
``load``, and the objects they return -- is marked as a prototype API in the
docs and docstrings: signatures, error types and the artifact format may change
between releases without a deprecation cycle.
It also makes ``example_inputs`` the ONLY calling convention, which is the other
half of what makes the tracer legible. precompile on main takes the example call
positionally -- and names that varargs parameter ``example_inputs`` -- so adding
a real ``example_inputs`` list beside it left two things with one name and a
``tracer`` argument that was load-bearing in one spelling and rejected in the
other. Now there is one convention and ``tracer`` is the only thing that selects
a front-end: ``"make_fx"`` (the default) is one non-strict ATen trace and takes
exactly one call, ``"dynamo"`` takes as many as you give it. A positional call
raises a TypeError naming the replacement. This is a BC break to an API that is
already on main; precompile is new enough that the blast radius is the tests.
The dynamo tracer keeps real guards and records every frame Dynamo compiled --
the entry frame plus each graph-break continuation, and every recompiled variant
of each -- into one artifact format. That is the shape aot_compile cannot express
at all: it produces exactly one graph and rejects graph breaks, so a model that
breaks 50 times and specializes 3 ways per frame cannot be precompiled today.
Collapsing the two spellings also settles the grad mode, which they used to
answer differently: the caller wrote the positional call so it ran in the
ambient mode, while precompile makes the ``example_inputs`` calls so it picked
``no_grad``. precompile now always makes the call, so ``training`` decides for
both tracers -- ``no_grad`` unless ``training=True``. For make_fx that is a
no-op on inference (the artifact is byte-identical either way, measured) and a
fix otherwise: ``training`` was previously accepted and silently ignored there.
The dynamo tracer mirrors ``torch.compile``. Where they used to differ it was
because a single-graph emitter worked around torch.compile locally -- an ambient
torch_function mode, for instance, which torch.compile applies twice and that
emitter applied once. Parity is the contract now, so those divergences are gone
and the make_fx path keeps the stronger guarantees.
Only the guards that DISCRIMINATE are serialized, and that is most of what makes
a real model viable rather than an optimization on top. Most guards cannot be
serialized at all -- identity guards on modules, callables, closure cells -- and
of those that can, the overwhelming majority are invariant: on a 62-frame
ranking model, 738 of its 1207 guard slots held the same fact in every captured
variant. Such a guard selects nothing. The contract precompile already asks for
is what licenses dropping it: the environment is identical at capture and at
runtime, and every variation in computation comes from the inputs, so an
invariant guard is either environment, pinned by that assumption, or an input
dimension the examples deliberately did not vary. The cost is real and is stated
in the code: a call outside the captured domain is served by a captured graph
rather than refused. Guards Dynamo never models -- SHAPE_ENV, GLOBAL_STATE and
the rest of _UNMODELLED_GUARD_TYPES -- are exempt, since they were never shown
to be constant, only never analyzed.
A slot is (guard_type, normalized source), and it is kept when two variants of
its frame recorded different facts for it OR when it is present in some variants
and absent in others. That second case is not a refinement, it is most of the
answer: 225 of the 274 slots kept, because a guard only one variant carries is
exactly what tells that variant apart. Which guards discriminate is knowable
only once every variant exists, and guards are serialized per compilation as
each is produced, so capture at this commit runs the examples twice: a probe
pass to learn, then ``torch._dynamo.reset()``, then a second pass keeping only
what varied. The passes agree by construction rather than by luck, since
PrecompileSession gives each session a fresh PGO state and enters under
_use_code_state, so the second cannot inherit the first's automatic-dynamic
learning.
Two properties of that policy are known to be wrong at this commit and are
fixed by the PR directly above, where the machinery to fix them lands, rather
than here. A capture is not free of side effects, so running every example
twice doubles a training step's accumulated gradients and guards a mutating
region (BatchNorm running stats, a step counter) on state the probe already
advanced past; the PR above captures once and applies the policy by
re-serializing from the pickle. And the drop policy here is fail-open: any
guard type outside _UNMODELLED_GUARD_TYPES that held invariant across the
examples is dropped, which includes guards whose loss changes the answer --
with a single example nothing can discriminate, so even the shape guard on the
input goes; the PR above introduces the never-drop set. Likewise the installed
driver's _entry_function does not yet apply _ENTRY_BINDING, so an installed
entry's defaults are restored only from the hardening PR at the top of the
stack.
How the multi-graph artifact serves depends on what it can reach, and the
artifact says which in its header. A source driver dispatches the entry frame
and the continuations the entry's bytecode names. When that covers every
captured frame -- the whole computation is one function that breaks a few times
-- the artifact is ``standalone``: it installs nothing, no frame evaluator is
involved, and the driver rebuilds each frame's guard trees and dispatches by
evaluating guards against the call.
A model that breaks inside nested module forwards is the other case, and it is
the common one. Those frames are entered by an ordinary call, so no name in the
entry reaches them and a source driver would run them eager -- correct, but with
every compiled variant unused. Such a capture is ``installed`` instead: the
driver rebuilds the package and hands the frames to the frame evaluator, which
reaches them by code object. The split keys on FRAME REACHABILITY, not on
whether the capture graph-broke: an entry-frame-only break is standalone.
``load`` still installs nothing; entering the result, or calling it, installs,
and ``unload``/exit takes it back out, so the mutation is attributable to a
point in the caller's control flow. Install, rebind and unload synchronize on a
lock, so two threads making the first call cannot both install the package
onto the same live code objects; serving is multi-thread safe. Calling an
installed artifact after ``unload()`` raises PrecompileError instead of
silently re-installing (and a call racing ``unload()`` cannot reinstall after
it returns); re-entering the handle as a context manager is the explicit way
to install again. ``unload()`` also takes back out of PrecompileContext exactly
the backend artifacts its install recorded, so an install/unload cycle does
not leak them for the life of the process. ``load(fn=...)`` installs onto
whatever function it is given, so it runs the same ``_check_artifact_matches``
check the path form does and refuses, as PrecompileError, a function the
artifact was not captured from.
Either way a call no captured variant covers RAISES rather than silently
compiling a new one, and reachability is computed as a closure: a continuation
counts as covered only once something that is itself reachable names it.
The emitted file is labelled, and the split is by what actually has a source
form. What was captured -- the frames, their variant counts, the guards that
could not be serialized, the values pinned to what capture saw -- is emitted as
readable literals. The compiled subgraphs are RENDERED AS SOURCE, kernels and
all, through the same aot_autograd.compile_to_python the make_fx tracer uses:
they are Inductor output, not Dynamo state, so pickling them was a default
rather than a constraint, and it was most of the file. On a graph-breaking model
with two shape variants that is 379,657 chars -> 102,950 with 8 readable
triton.jit kernels; on a two-variant toy, 197,843 -> 54,632. Only the guard
trees and the transformed bytecode, which genuinely have no source form, remain
under an OPAQUE banner.
Rendering is per subgraph and the blocks share one namespace, which is the whole
difficulty. Two variants of one frame are the same computation at different
shapes, so they render the SAME top-level names, and a block resolves its
siblings as late-bound globals -- its ``call`` looks up ``_runtime_wrapper`` and
``_inner_call``, its ``Runner`` looks up the kernels. Left alone, the batch-2
variant silently runs the batch-4 variant's code. Every top-level name a block
defines is therefore suffixed per subgraph, driven by AST positions rather than
a text match: that is what keeps an attribute (``runner.call``), a nested
binding (``def call`` inside ``class Runner``) and a dotted import path
(``torch._inductor.async_compile``) out of the rewrite, each of which broke a
regex first.
A training capture keeps the bundle instead, and that is refused up front rather
than caught: compile_to_python pins AOTAutograd to the inference path, so a
training graph RENDERS SUCCESSFULLY with the backward silently gone and the
served output missing its grad_fn. The eager backend keeps it too (its backends
are fx graphs with nothing to render), as does any single subgraph whose
lowering fails; the header reports how many fell back.
The public surface is deliberately two calls. ``precompile()`` runs the examples
itself and returns the pair; ``precompile.load()`` reads it back. There is no
capture object the caller drives by hand: with ``training=True`` covering the
case that used to need one, a session would only be a second way to say the same
thing, and it would be the way that requires a loss.
``training=True`` makes it a drop-in for a training step. The examples then run
with grad enabled and the backward is lowered eagerly, so the artifact carries
one: a served output arrives with grad_fn=CompiledFunctionBackward and
``.backward()`` runs precompiled code. No loss is required for that, and none is
asked for -- AOTAutograd's joint trace already synthesizes tangents from the
forward outputs' own metadata, and already wraps the result in a
torch.autograd.Function. All that was missing is that it lowers the backward
lazily, on the first ``.backward()`` call, so a capture that never makes one
records a forward and nothing else. Two serialization bugs sat on that path and
are fixed here, both reachable only once there are grads to serialize: a
parameter's .grad is read by no guard, so it is pruned to the _Missing sentinel
and _unpickle_tensor then assigned the sentinel and raised at LOAD, and the
reducer read .grad off non-leaf tensors, which is always None and warns.
One fix in guards.py is required rather than incidental. Value pruning keys off
the guard tree: anything the tree does not reach is replaced by a placeholder.
Dropping a guard therefore dropped the VALUE it named while the rest of the
state still referred to it, and the artifact failed to load with
"empty_strided(): argument 'dtype' must be torch.dtype, not _Missing". Pruning
now follows the unfiltered tree. Note this only masks the underlying issue:
missing_values is keyed by id, so one unguarded attribute holding torch.bfloat16
can stand in for every reference to that dtype in the pickle. That is a latent
bug of its own and wants a separate fix.
Explicit capture and serve are a distinct mode from the ambient
caching_precompile cache -- guards are built strictly, only the filtered copy
is recorded, and the package is never auto-persisted -- and that mode is a
``CompilePackage.explicit_capture`` attribute, threaded through
``DynamoOutput.build_guards`` into ``CheckFunctionManager``. It used to be
inferred from ``serialization_guard_filter_fn is not None``, which made the
filter double as a mode flag; convert_frame's bypass and DynamoCache paths,
the caching_precompile guard-filter override and the strict-error selection
all read the attribute now. Relatedly, ``PrecompileContext.create_cache_entries``
deep-copies each dynamo cache entry before ``PrecompileCacheEntry.from_cache_entry``,
because from_cache_entry marks a code whose backend it cannot find as bypassed
on the entry it is handed: saving must not flip the LIVE entry that keeps
serving this process.
A CPU codegen-target drift mid-capture is recorded with a warning rather than
raised from inside update_device_type -- i.e. from inside EVERY compile,
including the ambient caching_precompile path an ordinary torch.compile user
is on. The refusal lives in an explicit ``refuse_unserializable()`` invoked
only at serialization boundaries (record_package, path saves, artifact
builds), not in ``cache_entry()``, which introspection and teardown also call:
a drifted package still builds a cache_entry for ``summary()`` while every
serialization path refuses, and the ambient recorder downgrades that to a
skipped save. The dynamo driver's Python-version lock and a missing captured
module raise the PrecompileError the docs promise rather than a bare
ValueError/ModuleNotFoundError, and GuardFact/FrameInvariants/PrecompileSummary
are ordinary picklable classes (they no longer claim a ``torch.compiler``
``__module__`` that nothing exports).
Three things worth knowing before relying on an artifact. Capture is by
execution, so an unexercised path is simply absent and a complete summary means
complete for the calls that ran. A bare nn.Module is refused: Dynamo compiles
its own wrapper frame, which closes over the module, so the entry frame holds no
graph and no artifact can rebuild that closure -- capture the function that
calls the model instead, which the error says. And an installed artifact
rebuilds its entry from that entry's code object, which cannot restore a
closure, so a closure entry is likewise refused at capture, where the closure is
visible, rather than on the serving machine.
Review it in five pieces: the programming-model contract in Note [precompile
programming model]; the make_fx emitter and its drivers; the multi-graph
capture session, its two passes and its gates; the standalone dispatcher; and
the public surface in torch/compiler with its docs, which describe the shipped
multigraph tracer (training serves through the live autograd engine after a
graph break at .backward(), graph breaks are preserved rather than refused,
decompositions= is rejected with tracer='dynamo', mark_unbacked(strict=True)
is read by Dynamo as a backed dynamic dim, the driver re-evaluates each
variant's serialized guards, and load()'s fn= keyword and its two return
shapes are documented).
Test Plan:
```
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_recompile_ux.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_misc.py
```
297 precompile tests. The API rework rewrote 171 call sites mechanically; 34
tests then failed with "no captured variant matches", which is the grad-mode
change above surfacing -- those captures had been relying on the ambient mode --
and they now say ``training=True`` explicitly. Tests that need Triton gate on
HAS_CUDA_AND_TRITON rather than cuda.is_available(), and the device-generic
numerics class instantiates only its CPU variants when no GPU is present.
Automatic dynamic is covered across graph breaks: a dim that varies is detected
per frame, so a continuation whose input varied is promoted to dynamic while an
entry frame whose input never did stays specialized, and unseen shapes then
serve. The graph-break suite runs each of six break shapes -- a disabled callee,
a disabled method, explicit breaks, a data-dependent break, a break in a child
module, a break inside a loop -- on both backends and asserts the served result
equals what torch.compile returns for the same call. The installed mode is
pinned for load(fn=) refusing a foreign function, unload() releasing the
recorded backends, a call after unload raising, and a version-skewed artifact
raising PrecompileError from an exec'd driver; test_package.py pins that
saving does not bypass the live cache entry.
On the 62-frame ranking model that motivated this: 738 of 1207 guard slots
dropped, all five captured calls exact with zero graphs compiled while serving,
capture 5.6s for one pass and 10.3s for the two.
Authored with an AI assistant.
ghstack-source-id: 65715d0
Pull-Request: #195360
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
This was referenced Sep 3, 2026
Closed
Closed
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
bobrenjc93
added a commit
that referenced
this pull request
Sep 4, 2026
… load ``tracer="dynamo"`` is the value the API declares as planned and rejects with NotImplementedError. This wires it up: ``precompile()`` drives one capture session over ``example_inputs``, runs the artifact gates and returns the same ``(python_code, cache)`` pair the make_fx tracer returns, and ``precompile.load`` reads either back, returning a ``torch.compiler.PrecompiledRunnable`` -- a plain callable for a standalone artifact, a ``PrecompiledCallable`` with ``with``/``unload()`` for one that serves by installing, with ``installed`` telling them apart and ``fn=`` to install onto a function that is not importable where it was captured. ``example_inputs`` becomes the ONLY calling convention. precompile on main takes the example call positionally and names that varargs parameter ``example_inputs``, so adding a real ``example_inputs`` list beside it left two things with one name and a ``tracer`` argument that was load-bearing in one spelling and rejected in the other. Now ``tracer`` alone selects a front-end: ``"make_fx"`` takes exactly one call, ``"dynamo"`` as many as you give it. The positional spelling shipped in 2.14, so it keeps working behind a FutureWarning (giving both is a ValueError). Collapsing the two spellings also settles the grad mode: precompile makes the call, so ``training`` decides for both tracers, no_grad unless ``training=True``. For make_fx that is a real fix rather than a no-op -- ``training`` was accepted and silently ignored because ``_capture`` wrapped make_fx in an unconditional ``enable_grad()`` -- so the make_fx tests whose ``fn`` runs a backward now say ``training=True``, and a forward-only capture no longer builds autograd graph nodes it never uses. A 2.14 caller still spelling a training step positionally therefore needs ``training=True`` too; the FutureWarning and the deprecation note say so, since otherwise the capture dies inside make_fx with autograd's raw "does not require grad" error. A dynamo training capture snapshots and restores the example tensors' ``.grad`` around the example calls, as make_fx does, so the documented warmup-step-then-capture flow does not double the gradients it finds (``keep_example_grads`` opts out for a caller whose example IS their training step). The API reference is updated in the same change: the ``example_inputs`` signature, ``load(..., fn=)``, ``ExampleInput``, the two ``PrecompiledRunnable`` shapes, which parameters are ``tracer="dynamo"`` only, what raises ``ValueError``, and what ``load`` executes and writes. Test Plan: ``` python test/test_precompile.py python test/dynamo/test_precompile_package.py python test/dynamo/test_package.py ``` Authored with an AI assistant. ghstack-source-id: c423ae2 Pull-Request: #195360
[ghstack-poisoned]
[ghstack-poisoned]
bobrenjc93
added a commit
that referenced
this pull request
Sep 5, 2026
… load ``tracer="dynamo"`` is the value the API declares as planned and rejects with NotImplementedError. This wires it up: ``precompile()`` drives one capture session over ``example_inputs``, runs the artifact gates and returns the same ``(python_code, cache)`` pair the make_fx tracer returns, and ``precompile.load`` reads either back, returning a ``torch.compiler.PrecompiledRunnable`` -- a plain callable for a standalone artifact, a ``PrecompiledCallable`` with ``with``/``unload()`` for one that serves by installing, with ``installed`` telling them apart and ``fn=`` to install onto a function that is not importable where it was captured. ``example_inputs`` becomes the ONLY calling convention. precompile on main takes the example call positionally and names that varargs parameter ``example_inputs``, so adding a real ``example_inputs`` list beside it left two things with one name and a ``tracer`` argument that was load-bearing in one spelling and rejected in the other. Now ``tracer`` alone selects a front-end: ``"make_fx"`` takes exactly one call, ``"dynamo"`` as many as you give it. The positional spelling shipped in 2.14, so it keeps working behind a FutureWarning (giving both is a ValueError). Collapsing the two spellings also settles the grad mode: precompile makes the call, so ``training`` decides for both tracers, no_grad unless ``training=True``. For make_fx that is a real fix rather than a no-op -- ``training`` was accepted and silently ignored because ``_capture`` wrapped make_fx in an unconditional ``enable_grad()`` -- so the make_fx tests whose ``fn`` runs a backward now say ``training=True``, and a forward-only capture no longer builds autograd graph nodes it never uses. A 2.14 caller still spelling a training step positionally therefore needs ``training=True`` too; the FutureWarning and the deprecation note say so, since otherwise the capture dies inside make_fx with autograd's raw "does not require grad" error. A dynamo training capture snapshots and restores the example tensors' ``.grad`` around the example calls, as make_fx does, so the documented warmup-step-then-capture flow does not double the gradients it finds (``keep_example_grads`` opts out for a caller whose example IS their training step). The API reference is updated in the same change: the ``example_inputs`` signature, ``load(..., fn=)``, ``ExampleInput``, the two ``PrecompiledRunnable`` shapes, which parameters are ``tracer="dynamo"`` only, what raises ``ValueError``, and what ``load`` executes and writes. Test Plan: ``` python test/test_precompile.py python test/dynamo/test_precompile_package.py python test/dynamo/test_package.py ``` Authored with an AI assistant. ghstack-source-id: 0bdeb4e Pull-Request: #195360
Contributor
Author
|
/easycla |
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):
tracer="dynamo"is the value the API declares as planned and rejects withNotImplementedError. This wires it up:
precompile()drives one capturesession over
example_inputs, runs the artifact gates and returns the same(python_code, cache)pair the make_fx tracer returns, andprecompile.loadreads either back, returning atorch.compiler.PrecompiledRunnable-- a plain callable for a standaloneartifact, a
PrecompiledCallablewithwith/unload()for one thatserves by installing, with
installedtelling them apart andfn=toinstall onto a function that is not importable where it was captured.
example_inputsbecomes the ONLY calling convention. precompile on maintakes the example call positionally and names that varargs parameter
example_inputs, so adding a realexample_inputslist beside it left twothings with one name and a
tracerargument that was load-bearing in onespelling and rejected in the other. Now
traceralone selects a front-end:"make_fx"takes exactly one call,"dynamo"as many as you give it. Thepositional spelling shipped in 2.14, so it keeps working behind a
FutureWarning (giving both is a ValueError). Collapsing the two spellings also
settles the grad mode: precompile makes the call, so
trainingdecides forboth tracers, no_grad unless
training=True. For make_fx that is a real fixrather than a no-op --
trainingwas accepted and silently ignored because_capturewrapped make_fx in an unconditionalenable_grad()-- so themake_fx tests whose
fnruns a backward now saytraining=True, and aforward-only capture no longer builds autograd graph nodes it never uses. A
2.14 caller still spelling a training step positionally therefore needs
training=Truetoo; the FutureWarning and the deprecation note say so,since otherwise the capture dies inside make_fx with autograd's raw
"does not require grad" error.
A dynamo training capture snapshots and restores the example tensors'
.gradaround the example calls, as make_fx does, so the documentedwarmup-step-then-capture flow does not double the gradients it finds
(
keep_example_gradsopts out for a caller whose example IS their trainingstep). The API reference is updated in the same change: the
example_inputssignature,
load(..., fn=),ExampleInput, the twoPrecompiledRunnableshapes, which parameters are
tracer="dynamo"only, what raisesValueError, and whatloadexecutes and writes.Test Plan:
Authored with an AI assistant.