Repository navigation
[precompile] Implement the dynamo tracer for torch.compiler.precompile - #192379
Closed
bobrenjc93 wants to merge 59 commits into
Closed
bobrenjc93 wants to merge 59 commits into
bobrenjc93 wants to merge 59 commits into
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/192379
Note: Links to docs will display an error until the docs builds have been completed. ❌ 1 New Failure, 1 Unrelated FailureAs of commit 9abd92d with merge base 1b4e490 ( NEW FAILURE - The following job has 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
added a commit
that referenced
this pull request
Aug 6, 2026
…piles
aot_compile produces exactly one graph and rejects graph breaks, so a model
that breaks 50 times and specializes 3 ways per frame cannot be precompiled at
all today. CompilePackage already captures every frame Dynamo produces --
entry, resume continuations, and each recompiled variant -- but it is a low
level component with no API, and assembling it by hand is both awkward and
unsafe in two specific ways this change fixes.
Review the three pieces in this order.
First, convert_frame: when a frame exceeds recompile_limit it is pinned to
RUN_ONLY, so every variant past the limit is never captured. The package was
not told, so it happily serialized a truncated guard set. Nothing failed at
capture or at save; the artifact simply stopped matching partway through
serving. It now marks the entry bypassed, which install() already understands
as "do not serve this frame", and emits the same dynamo_cache_bypass artifact
the other bypass path does. This is easy to hit without meaning to: frames
shared across module instances accumulate one variant per instance per
condition, so fifty blocks of the same class need a hundred and fifty slots on
one code object against a default limit of eight.
Second, package: uninstall() only cleared precompile entries for the entry code
object, leaving them installed on every resume function and on any frame
reached through code_source. Loading an artifact therefore mutated global state
that neither uninstall() nor torch._dynamo.reset() could undo, and a second
load in the same process would silently serve the first artifact's entries.
install() now records the code objects it touches and uninstall() clears all of
them. Relatedly, _install_global appends a name per entry, so a shared import
alias is recorded more than once and the pop raised KeyError on the second
occurrence -- latent until uninstall ran after a real install.
Third, precompile_package: the API. precompile_capture yields the callable to
exercise, save() refuses to write an incomplete artifact, precompile_load does
the order-sensitive attach-then-install in one call and returns something that
can be unloaded, and the default guard filter drops only guard types that
cannot be serialized rather than everything global. recompile_limit defaults to
256 because a precompile deliberately wants one variant per condition, whereas
the usual limit of 8 exists to catch runaway recompilation.
Capture remains by execution -- a resume function only exists once the frame
ahead of it has run -- so callers must exercise every path they want covered.
summary() exposes the counts so a build step can assert coverage instead of
discovering gaps in production, and also reports which guard types the filter
discarded. Dropping a guard is the one failure mode here that is silent by
construction -- it does not raise, it widens what an existing graph gets reused
for -- so the discarded set needs to be inspectable.
Test Plan:
New tests in test/dynamo/test_package.py covering a round trip across two
graph breaks and three specializations on both backends, guards on a global
dict read on both sides of a break, a dict passed as an argument, nested dict
membership and key-set iteration, the save-time refusal when recompile_limit
truncates capture, and the same model succeeding once the limit is raised. The
dict cases assert the guard is load-bearing rather than merely present: an
uncaptured config has to miss every graph instead of quietly reusing one.
```
python test/dynamo/test_package.py TestPrecompilePackage
```
Regressions:
```
python test/dynamo/test_package.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_recompiles.py
python test/dynamo/test_precompile_context.py
```
test_package 65 tests OK, test_recompiles 20 OK, test_precompile_context 3 OK.
test_aot_compile has 3 pre-existing errors (test_aot_compile_with_aoti*) from a
local environment gap where AOTI's generated header cannot find cuda.h; they
fail identically on a clean tree.
Scale was checked out of tree at the target size, 50 graph breaks by 3
specializations, in both layouts:
```
50 breaks in distinct frames : 51 frames, 153 guarded codes, 153 graphs,
12s capture, 2.2 MB, 0.5s load
50 instances sharing a frame : 3 frames, 150 guarded codes, 150 graphs,
12s capture, 2.4 MB, 0.5s load
```
Both replay all three variants under fail_on_recompile with zero recompiles and
reject an uncovered input. Note that guard dispatch is a linear scan over a
frame's guarded codes, so the shared-frame layout costs 1.7ms for the first
variant against 5.2ms for the last, where the distinct-frame layout is flat at
0.9ms. That is a property of the existing dispatch path, not something this
change introduces.
Authored with an AI assistant.
ghstack-source-id: 4e67a63
Pull-Request: #192379
bobrenjc93
added a commit
that referenced
this pull request
Aug 6, 2026
…piles
aot_compile produces exactly one graph and rejects graph breaks, so a model
that breaks 50 times and specializes 3 ways per frame cannot be precompiled at
all today. CompilePackage already captures every frame Dynamo produces --
entry, resume continuations, and each recompiled variant -- but it is a low
level component with no API, and assembling it by hand is unsafe in several
ways this change fixes. The theme throughout is that every failure mode here is
silent by construction: a precompiled artifact that is missing coverage or
missing a guard does not raise, it serves the wrong graph.
Review the three pieces in this order.
First, convert_frame: when a frame exceeds recompile_limit it is pinned to
RUN_ONLY, so every variant past the limit is never captured, and the package
was not told. It now records the frame as truncated. Note this is deliberately
NOT a bypass: install() treats a bypassed entry as "serve nothing", so marking
these frames bypassed would throw away the variants that were captured
successfully and make coverage strictly worse for existing caching_precompile
users, who would rather serve eight variants and recompile for the rest. The
truncation set is runtime-only and is not serialized, both because it describes
a capture session rather than an artifact and because a persisted flag would
poison a DynamoCache entry permanently -- nothing resets it, and raising the
limit on a later run would not recover.
Second, package: uninstall() only cleared precompile entries for the entry code
object, leaving them installed on every resume function and on any frame
reached through code_source, so loading an artifact mutated global state that
neither uninstall() nor torch._dynamo.reset() could undo. install() now records
the code objects it touches, and also records the frames it skip_code()s so
those are restored too. Because precompile entries can only be cleared en masse
and not individually, uninstall() now refuses when another live package is
installed on the same code object rather than silently clearing its entries --
that configuration is unsupported, and a loud error beats a corrupted neighbour.
Third, precompile_package: the API. precompile_capture yields the callable to
exercise, save() refuses to write an artifact that cannot serve what it claims,
precompile_load does the order-sensitive attach-then-install in one call and
returns something that can be unloaded, and recompile_limit defaults to 256
because a precompile deliberately wants one variant per condition whereas the
usual limit of 8 exists to catch runaway recompilation.
The guard filter deserves its own note, because the obvious design is wrong.
The set of guards Dynamo cannot serialize is exactly the IDENTITY guards --
ID_MATCH, FUNCTION_MATCH, CLOSURE_MATCH, MODULE_MATCH and friends -- so
precompiling inherently gives up on noticing that a guarded object was rebound
to a different object of the same shape. Keeping them is not an option, since
serialization then fails for essentially every function; dropping them silently
is how you serve a graph traced against the old value. So every drop is
recorded with its source name, and save() refuses by default when a dropped
guard is on a bare global holding a non-module -- the ACT = some_fn dispatch
switch, which is the shape that actually produces wrong answers. Guards on
modules and on attributes reached through them are noise and are allowed. This
is a heuristic and is documented as one; dropped_guards remains the
authoritative list.
precompile_load also validates that the artifact was captured from the callable
it is being loaded onto. CompilePackage.initialize rebinds stored guards and
bytecode onto whatever function it is given, and the source checksum only
covers the captured function, so loading f's artifact onto g otherwise returns
f's results with no error.
Capture remains by execution -- a resume function only exists once the frame
ahead of it has run -- so callers must exercise every path they want covered.
summary() exposes the counts, the truncated and bypassed frames, and the kept
and dropped guards with their sources, so a build step can assert coverage
instead of discovering gaps in production.
Test Plan:
New tests in test/dynamo/test_package.py. Coverage: a round trip across two
graph breaks and three specializations on both backends; guards on a global
dict read on both sides of a break; a dict passed as an argument; nested dict
membership and key-set iteration, asserting positively that those guards were
kept rather than merely absent from the dropped list; refusal to save a
truncated capture, and that the variants it did capture still serve; refusal to
save a capture that ran nothing; refusal to save when a risky identity guard
was dropped, and that the risk is acknowledgeable; refusal to load an artifact
captured from a different callable; and that unload clears resume-function
entries rather than leaving them installed.
```
python test/dynamo/test_package.py TestPrecompilePackage
```
Regressions:
```
python test/dynamo/test_package.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_recompiles.py
python test/dynamo/test_precompile_context.py
```
test_package 73 OK, test_recompiles 20 OK, test_precompile_context 3 OK.
test_aot_compile has 3 pre-existing errors (test_aot_compile_with_aoti*) from a
local environment gap where AOTI's generated header cannot find cuda.h; they
fail identically on a clean tree.
Scale was checked out of tree at the target size, 50 graph breaks by 3
specializations, in both layouts:
```
50 breaks in distinct frames : 51 frames, 153 guarded codes, 153 graphs,
12s capture, 2.2 MB, 0.5s load
50 instances sharing a frame : 3 frames, 150 guarded codes, 150 graphs,
12s capture, 2.4 MB, 0.5s load
```
Both replay all three variants under fail_on_recompile with zero recompiles and
reject an uncovered input. Note that guard dispatch is a linear scan over a
frame's guarded codes, so the shared-frame layout costs 1.7ms for the first
variant against 5.2ms for the last, where the distinct-frame layout is flat at
0.9ms. That is a property of the existing dispatch path, not something this
change introduces.
Authored with an AI assistant.
ghstack-source-id: 8e52580
Pull-Request: #192379
bobrenjc93
added a commit
that referenced
this pull request
Aug 6, 2026
…piles
aot_compile produces exactly one graph and rejects graph breaks, so a model
that breaks 50 times and specializes 3 ways per frame cannot be precompiled at
all today. CompilePackage already captures every frame Dynamo produces --
entry, resume continuations, and each recompiled variant -- but it is a low
level component with no API, and assembling it by hand is unsafe in several
ways this change fixes. The theme throughout is that every failure mode here is
silent by construction: a precompiled artifact that is missing coverage or
missing a guard does not raise, it serves the wrong graph.
Review the three pieces in this order.
First, convert_frame: when a frame exceeds recompile_limit it is pinned to
RUN_ONLY, so every variant past the limit is never captured, and the package
was not told. It now records the frame as truncated. Note this is deliberately
NOT a bypass: install() treats a bypassed entry as "serve nothing", so marking
these frames bypassed would throw away the variants that were captured
successfully and make coverage strictly worse for existing caching_precompile
users, who would rather serve eight variants and recompile for the rest. The
truncation set is runtime-only and is not serialized, both because it describes
a capture session rather than an artifact and because a persisted flag would
poison a DynamoCache entry permanently -- nothing resets it, and raising the
limit on a later run would not recover.
Second, package: uninstall() only cleared precompile entries for the entry code
object, leaving them installed on every resume function and on any frame
reached through code_source, so loading an artifact mutated global state that
neither uninstall() nor torch._dynamo.reset() could undo. install() now records
the code objects it touches, and also records the frames it skip_code()s so
those are restored too. Because precompile entries can only be cleared en masse
and not individually, uninstall() now refuses when another live package is
installed on the same code object rather than silently clearing its entries --
that configuration is unsupported, and a loud error beats a corrupted neighbour.
Third, precompile_package: the API. precompile_capture yields the callable to
exercise, save() refuses to write an artifact that cannot serve what it claims,
precompile_load does the order-sensitive attach-then-install in one call and
returns something that can be unloaded, and recompile_limit defaults to 256
because a precompile deliberately wants one variant per condition whereas the
usual limit of 8 exists to catch runaway recompilation.
The guard filter deserves its own note, because the obvious design is wrong.
The set of guards Dynamo cannot serialize is exactly the IDENTITY guards --
ID_MATCH, FUNCTION_MATCH, CLOSURE_MATCH, MODULE_MATCH and friends -- so
precompiling inherently gives up on noticing that a guarded object was rebound
to a different object of the same shape. Keeping them is not an option, since
serialization then fails for essentially every function; dropping them silently
is how you serve a graph traced against the old value. So every drop is
recorded with its source name, and save() refuses by default when a dropped
guard is on a bare global holding a non-module -- the ACT = some_fn dispatch
switch, which is the shape that actually produces wrong answers. Guards on
modules and on attributes reached through them are noise and are allowed. This
is a heuristic and is documented as one; dropped_guards remains the
authoritative list.
precompile_load also validates that the artifact was captured from the callable
it is being loaded onto. CompilePackage.initialize rebinds stored guards and
bytecode onto whatever function it is given, and the source checksum only
covers the captured function, so loading f's artifact onto g otherwise returns
f's results with no error.
Capture remains by execution -- a resume function only exists once the frame
ahead of it has run -- so callers must exercise every path they want covered.
summary() exposes the counts, the truncated and bypassed frames, and the kept
and dropped guards with their sources, so a build step can assert coverage
instead of discovering gaps in production.
A second adversarial review pass drove the following, all of which had
reproducers:
The guard-drop lint was rewritten. It classified by matching the guard SOURCE
against a bare-global pattern, which cannot work: guard names have their local
scope stripped, so a guard on self.act arrives as "self.act" and is
indistinguishable from a global. It caught 2 of 11 dispatch shapes and missed
self.act, the way essentially every configurable activation is written, while
also firing on `from torch.nn.functional import relu`. It now classifies by what
the guarded VALUE is: torch-owned and builtin objects are library machinery,
anything else is user code that a serving setup might rebind. That catches 9 of
9 reproducible shapes and stops refusing plain nn.Sequential. The remaining gap
-- capturing with a torch-owned callable and rebinding to another one -- is
documented on the predicate.
The cross-package conflict check raised on uninstall, which deadlocked two
packages sharing a frame: the message said to unload the other first, but
neither could go first, and the failed unload left globals already deleted. It
now warns and proceeds. Its registry also keyed on id(self), so a package
dropped without unloading blocked every later one; it holds weak references now,
and covers the entry code object, which it previously skipped.
save() grew two things the review showed were needed. A forward-only capture
with grad enabled records no backends at all, because AOTAutograd only registers
the bundled artifact once the backward compiles; that surfaced as a RuntimeError
naming an internal symbol, and is now a PackageError saying to capture under
no_grad. And a value crossing a graph break is guarded by equality, so such an
artifact serves only the inputs it was captured with -- summary() now reports
those as wont_generalize, and save() warns.
Truncated frames are keyed by file and line rather than bare co_name, which
collapsed distinct frames both called forward. The trace artifact emitted on
truncation was renamed off dynamo_cache_bypass, since conflating it with a real
bypass misreports a frame that still serves.
The module docstring now states the operational limits up front: capture under
no_grad, expect value-pinned artifacts from data-dependent breaks, identity
guards are not recoverable, the model must be importable, and install() patches
code objects process-globally.
Test Plan:
New tests in test/dynamo/test_package.py. Coverage: a round trip across two
graph breaks and three specializations on both backends; guards on a global
dict read on both sides of a break; a dict passed as an argument; nested dict
membership and key-set iteration, asserting positively that those guards were
kept rather than merely absent from the dropped list; refusal to save a
truncated capture, and that the variants it did capture still serve; refusal to
save a capture that ran nothing; refusal to save when a risky identity guard
was dropped, and that the risk is acknowledgeable; refusal to load an artifact
captured from a different callable; and that unload clears resume-function
entries rather than leaving them installed.
```
python test/dynamo/test_package.py TestPrecompilePackage
```
Regressions:
```
python test/dynamo/test_package.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_recompiles.py
python test/dynamo/test_precompile_context.py
python test/dynamo/test_misc.py
```
test_package 77 OK, test_recompiles 18 OK, test_misc 842 OK, test_precompile_context 3 OK.
test_aot_compile has 3 pre-existing errors (test_aot_compile_with_aoti*) from a
local environment gap where AOTI's generated header cannot find cuda.h; they
fail identically on a clean tree.
Scale was checked out of tree at the target size, 50 graph breaks by 3
specializations, in both layouts:
```
50 breaks in distinct frames : 51 frames, 153 guarded codes, 153 graphs,
12s capture, 2.2 MB, 0.5s load
50 instances sharing a frame : 3 frames, 150 guarded codes, 150 graphs,
12s capture, 2.4 MB, 0.5s load
```
Both replay all three variants under fail_on_recompile with zero recompiles and
reject an uncovered input. Note that guard dispatch is a linear scan over a
frame's guarded codes, so the shared-frame layout costs 1.7ms for the first
variant against 5.2ms for the last, where the distinct-frame layout is flat at
0.9ms. That is a property of the existing dispatch path, not something this
change introduces.
Authored with an AI assistant.
ghstack-source-id: 5a854f5
Pull-Request: #192379
bobrenjc93
added a commit
that referenced
this pull request
Aug 6, 2026
…piles
aot_compile produces exactly one graph and rejects graph breaks, so a model
that breaks 50 times and specializes 3 ways per frame cannot be precompiled at
all today. CompilePackage already captures every frame Dynamo produces --
entry, resume continuations, and each recompiled variant -- but it is a low
level component with no API, and assembling it by hand is unsafe in several
ways this change fixes. The theme throughout is that every failure mode here is
silent by construction: a precompiled artifact that is missing coverage or
missing a guard does not raise, it serves the wrong graph.
Review the three pieces in this order.
First, convert_frame: when a frame exceeds recompile_limit it is pinned to
RUN_ONLY, so every variant past the limit is never captured, and the package
was not told. It now records the frame as truncated. Note this is deliberately
NOT a bypass: install() treats a bypassed entry as "serve nothing", so marking
these frames bypassed would throw away the variants that were captured
successfully and make coverage strictly worse for existing caching_precompile
users, who would rather serve eight variants and recompile for the rest. The
truncation set is runtime-only and is not serialized, both because it describes
a capture session rather than an artifact and because a persisted flag would
poison a DynamoCache entry permanently -- nothing resets it, and raising the
limit on a later run would not recover.
Second, package: uninstall() only cleared precompile entries for the entry code
object, leaving them installed on every resume function and on any frame
reached through code_source, so loading an artifact mutated global state that
neither uninstall() nor torch._dynamo.reset() could undo. install() now records
the code objects it touches, and also records the frames it skip_code()s so
those are restored too. Because precompile entries can only be cleared en masse
and not individually, uninstall() now refuses when another live package is
installed on the same code object rather than silently clearing its entries --
that configuration is unsupported, and a loud error beats a corrupted neighbour.
Third, precompile_package: the API. precompile_capture yields the callable to
exercise, save() refuses to write an artifact that cannot serve what it claims,
precompile_load does the order-sensitive attach-then-install in one call and
returns something that can be unloaded, and recompile_limit defaults to 256
because a precompile deliberately wants one variant per condition whereas the
usual limit of 8 exists to catch runaway recompilation.
The guard filter deserves its own note, because the obvious design is wrong.
The set of guards Dynamo cannot serialize is exactly the IDENTITY guards --
ID_MATCH, FUNCTION_MATCH, CLOSURE_MATCH, MODULE_MATCH and friends -- so
precompiling inherently gives up on noticing that a guarded object was rebound
to a different object of the same shape. Keeping them is not an option, since
serialization then fails for essentially every function; dropping them silently
is how you serve a graph traced against the old value. So every drop is
recorded with its source name, and save() refuses by default when a dropped
guard is on a bare global holding a non-module -- the ACT = some_fn dispatch
switch, which is the shape that actually produces wrong answers. Guards on
modules and on attributes reached through them are noise and are allowed. This
is a heuristic and is documented as one; dropped_guards remains the
authoritative list.
precompile_load also validates that the artifact was captured from the callable
it is being loaded onto. CompilePackage.initialize rebinds stored guards and
bytecode onto whatever function it is given, and the source checksum only
covers the captured function, so loading f's artifact onto g otherwise returns
f's results with no error.
Capture remains by execution -- a resume function only exists once the frame
ahead of it has run -- so callers must exercise every path they want covered.
summary() exposes the counts, the truncated and bypassed frames, and the kept
and dropped guards with their sources, so a build step can assert coverage
instead of discovering gaps in production.
A second adversarial review pass drove the following, all of which had
reproducers:
The guard-drop lint was rewritten. It classified by matching the guard SOURCE
against a bare-global pattern, which cannot work: guard names have their local
scope stripped, so a guard on self.act arrives as "self.act" and is
indistinguishable from a global. It caught 2 of 11 dispatch shapes and missed
self.act, the way essentially every configurable activation is written, while
also firing on `from torch.nn.functional import relu`. It now classifies by what
the guarded VALUE is: torch-owned and builtin objects are library machinery,
anything else is user code that a serving setup might rebind. That catches 9 of
9 reproducible shapes and stops refusing plain nn.Sequential. The remaining gap
-- capturing with a torch-owned callable and rebinding to another one -- is
documented on the predicate.
The cross-package conflict check raised on uninstall, which deadlocked two
packages sharing a frame: the message said to unload the other first, but
neither could go first, and the failed unload left globals already deleted. It
now warns and proceeds. Its registry also keyed on id(self), so a package
dropped without unloading blocked every later one; it holds weak references now,
and covers the entry code object, which it previously skipped.
save() grew two things the review showed were needed. A forward-only capture
with grad enabled records no backends at all, because AOTAutograd only registers
the bundled artifact once the backward compiles; that surfaced as a RuntimeError
naming an internal symbol, and is now a PackageError saying to capture under
no_grad. And a value crossing a graph break is guarded by equality, so such an
artifact serves only the inputs it was captured with -- summary() now reports
those as wont_generalize, and save() warns.
Truncated frames are keyed by file and line rather than bare co_name, which
collapsed distinct frames both called forward. The trace artifact emitted on
truncation was renamed off dynamo_cache_bypass, since conflating it with a real
bypass misreports a frame that still serves.
The module docstring now states the operational limits up front: capture under
no_grad, expect value-pinned artifacts from data-dependent breaks, identity
guards are not recoverable, the model must be importable, and install() patches
code objects process-globally.
The intended deployment is capture on one machine, serve on another, so the
in-process concerns above matter less than divergence between the two. The
guard-drop lint is framed for that: identical source is not sufficient, because
config or an environment variable can select a different object on the serving
machine, and an identity guard on it cannot be serialized. Verified end to end
-- capturing an activation chosen by an env var and serving with that var
changed returns a wrong answer, and save() refuses the artifact unless the risk
is explicitly accepted. The other cross-machine rails were verified too: the
source checksum finds the module by name rather than path, so an artifact moves
between differently laid out checkouts but still refuses to load against
drifted source, and SystemInfo rejects Python, PyTorch, CUDA, Triton and GPU
skew at load.
Test Plan:
New tests in test/dynamo/test_package.py. Coverage: a round trip across two
graph breaks and three specializations on both backends; guards on a global
dict read on both sides of a break; a dict passed as an argument; nested dict
membership and key-set iteration, asserting positively that those guards were
kept rather than merely absent from the dropped list; refusal to save a
truncated capture, and that the variants it did capture still serve; refusal to
save a capture that ran nothing; refusal to save when a risky identity guard
was dropped, and that the risk is acknowledgeable; refusal to load an artifact
captured from a different callable; that unload clears resume-function
entries rather than leaving them installed; and, for the cross-machine case, that
a drifted source module is refused at load and that version skew is rejected.
```
python test/dynamo/test_package.py TestPrecompilePackage
```
Regressions:
```
python test/dynamo/test_package.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_recompiles.py
python test/dynamo/test_precompile_context.py
python test/dynamo/test_misc.py
```
test_package 79 OK, test_recompiles 18 OK, test_misc 842 OK, test_precompile_context 3 OK.
test_aot_compile has 3 pre-existing errors (test_aot_compile_with_aoti*) from a
local environment gap where AOTI's generated header cannot find cuda.h; they
fail identically on a clean tree.
Scale was checked out of tree at the target size, 50 graph breaks by 3
specializations, in both layouts:
```
50 breaks in distinct frames : 51 frames, 153 guarded codes, 153 graphs,
12s capture, 2.2 MB, 0.5s load
50 instances sharing a frame : 3 frames, 150 guarded codes, 150 graphs,
12s capture, 2.4 MB, 0.5s load
```
Both replay all three variants under fail_on_recompile with zero recompiles and
reject an uncovered input. Note that guard dispatch is a linear scan over a
frame's guarded codes, so the shared-frame layout costs 1.7ms for the first
variant against 5.2ms for the last, where the distinct-frame layout is flat at
0.9ms. That is a property of the existing dispatch path, not something this
change introduces.
Authored with an AI assistant.
ghstack-source-id: 7a93d4a
Pull-Request: #192379
bobrenjc93
added a commit
that referenced
this pull request
Aug 7, 2026
…piles
aot_compile produces exactly one graph and rejects graph breaks, so a model
that breaks 50 times and specializes 3 ways per frame cannot be precompiled at
all today. CompilePackage already captures every frame Dynamo produces --
entry, resume continuations, and each recompiled variant -- but it is a low
level component with no API, and assembling it by hand is unsafe in several
ways this change fixes. The theme throughout is that every failure mode here is
silent by construction: a precompiled artifact that is missing coverage or
missing a guard does not raise, it serves the wrong graph.
Review the three pieces in this order.
First, convert_frame: when a frame exceeds recompile_limit it is pinned to
RUN_ONLY, so every variant past the limit is never captured, and the package
was not told. It now records the frame as truncated. Note this is deliberately
NOT a bypass: install() treats a bypassed entry as "serve nothing", so marking
these frames bypassed would throw away the variants that were captured
successfully and make coverage strictly worse for existing caching_precompile
users, who would rather serve eight variants and recompile for the rest. The
truncation set is runtime-only and is not serialized, both because it describes
a capture session rather than an artifact and because a persisted flag would
poison a DynamoCache entry permanently -- nothing resets it, and raising the
limit on a later run would not recover.
Second, package: uninstall() only cleared precompile entries for the entry code
object, leaving them installed on every resume function and on any frame
reached through code_source, so loading an artifact mutated global state that
neither uninstall() nor torch._dynamo.reset() could undo. install() now records
the code objects it touches, and also records the frames it skip_code()s so
those are restored too. Because precompile entries can only be cleared en masse
and not individually, uninstall() now refuses when another live package is
installed on the same code object rather than silently clearing its entries --
that configuration is unsupported, and a loud error beats a corrupted neighbour.
Third, precompile_package: the API. precompile_capture yields the callable to
exercise, save() refuses to write an artifact that cannot serve what it claims,
precompile_load does the order-sensitive attach-then-install in one call and
returns something that can be unloaded, and recompile_limit defaults to 256
because a precompile deliberately wants one variant per condition whereas the
usual limit of 8 exists to catch runaway recompilation.
The guard filter deserves its own note, because the obvious design is wrong.
The set of guards Dynamo cannot serialize is exactly the IDENTITY guards --
ID_MATCH, FUNCTION_MATCH, CLOSURE_MATCH, MODULE_MATCH and friends -- so
precompiling inherently gives up on noticing that a guarded object was rebound
to a different object of the same shape. Keeping them is not an option, since
serialization then fails for essentially every function; dropping them silently
is how you serve a graph traced against the old value. So every drop is
recorded with its source name, and save() refuses by default when a dropped
guard is on a bare global holding a non-module -- the ACT = some_fn dispatch
switch, which is the shape that actually produces wrong answers. Guards on
modules and on attributes reached through them are noise and are allowed. This
is a heuristic and is documented as one; dropped_guards remains the
authoritative list.
precompile_load also validates that the artifact was captured from the callable
it is being loaded onto. CompilePackage.initialize rebinds stored guards and
bytecode onto whatever function it is given, and the source checksum only
covers the captured function, so loading f's artifact onto g otherwise returns
f's results with no error.
Capture remains by execution -- a resume function only exists once the frame
ahead of it has run -- so callers must exercise every path they want covered.
summary() exposes the counts, the truncated and bypassed frames, and the kept
and dropped guards with their sources, so a build step can assert coverage
instead of discovering gaps in production.
A second adversarial review pass drove the following, all of which had
reproducers:
The guard-drop lint was rewritten. It classified by matching the guard SOURCE
against a bare-global pattern, which cannot work: guard names have their local
scope stripped, so a guard on self.act arrives as "self.act" and is
indistinguishable from a global. It caught 2 of 11 dispatch shapes and missed
self.act, the way essentially every configurable activation is written, while
also firing on `from torch.nn.functional import relu`. It now classifies by what
the guarded VALUE is: torch-owned and builtin objects are library machinery,
anything else is user code that a serving setup might rebind. That catches 9 of
9 reproducible shapes and stops refusing plain nn.Sequential. The remaining gap
-- capturing with a torch-owned callable and rebinding to another one -- is
documented on the predicate.
The cross-package conflict check raised on uninstall, which deadlocked two
packages sharing a frame: the message said to unload the other first, but
neither could go first, and the failed unload left globals already deleted. It
now warns and proceeds. Its registry also keyed on id(self), so a package
dropped without unloading blocked every later one; it holds weak references now,
and covers the entry code object, which it previously skipped.
save() grew two things the review showed were needed. A forward-only capture
with grad enabled records no backends at all, because AOTAutograd only registers
the bundled artifact once the backward compiles; that surfaced as a RuntimeError
naming an internal symbol, and is now a PackageError saying to capture under
no_grad. And a value crossing a graph break is guarded by equality, so such an
artifact serves only the inputs it was captured with -- summary() now reports
those as wont_generalize, and save() warns.
Truncated frames are keyed by file and line rather than bare co_name, which
collapsed distinct frames both called forward. The trace artifact emitted on
truncation was renamed off dynamo_cache_bypass, since conflating it with a real
bypass misreports a frame that still serves.
The module docstring now states the operational limits up front: capture under
no_grad, expect value-pinned artifacts from data-dependent breaks, identity
guards are not recoverable, the model must be importable, and install() patches
code objects process-globally.
The intended deployment is capture on one machine, serve on another, so the
in-process concerns above matter less than divergence between the two. The
guard-drop lint is framed for that: identical source is not sufficient, because
config or an environment variable can select a different object on the serving
machine, and an identity guard on it cannot be serialized. Verified end to end
-- capturing an activation chosen by an env var and serving with that var
changed returns a wrong answer, and save() refuses the artifact unless the risk
is explicitly accepted. The other cross-machine rails were verified too: the
source checksum finds the module by name rather than path, so an artifact moves
between differently laid out checkouts but still refuses to load against
drifted source, and SystemInfo rejects Python, PyTorch, CUDA, Triton and GPU
skew at load.
Test Plan:
New tests in test/dynamo/test_package.py. Coverage: a round trip across two
graph breaks and three specializations on both backends; guards on a global
dict read on both sides of a break; a dict passed as an argument; nested dict
membership and key-set iteration, asserting positively that those guards were
kept rather than merely absent from the dropped list; refusal to save a
truncated capture, and that the variants it did capture still serve; refusal to
save a capture that ran nothing; refusal to save when a risky identity guard
was dropped, and that the risk is acknowledgeable; refusal to load an artifact
captured from a different callable; that unload clears resume-function
entries rather than leaving them installed; and, for the cross-machine case, that
a drifted source module is refused at load and that version skew is rejected.
```
python test/dynamo/test_package.py TestPrecompilePackage
```
Regressions:
```
python test/dynamo/test_package.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_recompiles.py
python test/dynamo/test_precompile_context.py
python test/dynamo/test_misc.py
```
test_package 79 OK, test_recompiles 18 OK, test_misc 842 OK, test_precompile_context 3 OK.
test_aot_compile has 3 pre-existing errors (test_aot_compile_with_aoti*) from a
local environment gap where AOTI's generated header cannot find cuda.h; they
fail identically on a clean tree.
Scale was checked out of tree at the target size, 50 graph breaks by 3
specializations, in both layouts:
```
50 breaks in distinct frames : 51 frames, 153 guarded codes, 153 graphs,
12s capture, 2.2 MB, 0.5s load
50 instances sharing a frame : 3 frames, 150 guarded codes, 150 graphs,
12s capture, 2.4 MB, 0.5s load
```
Both replay all three variants under fail_on_recompile with zero recompiles and
reject an uncovered input. Note that guard dispatch is a linear scan over a
frame's guarded codes, so the shared-frame layout costs 1.7ms for the first
variant against 5.2ms for the last, where the distinct-frame layout is flat at
0.9ms. That is a property of the existing dispatch path, not something this
change introduces.
Authored with an AI assistant.
ghstack-source-id: 7a93d4a
Pull-Request: #192379
bobrenjc93
added a commit
that referenced
this pull request
Aug 7, 2026
…piles
aot_compile produces exactly one graph and rejects graph breaks, so a model
that breaks 50 times and specializes 3 ways per frame cannot be precompiled at
all today. CompilePackage already captures every frame Dynamo produces --
entry, resume continuations, and each recompiled variant -- but it is a low
level component with no API, and assembling it by hand is unsafe in several
ways this change fixes. The theme throughout is that every failure mode here is
silent by construction: a precompiled artifact that is missing coverage or
missing a guard does not raise, it serves the wrong graph.
Review the three pieces in this order.
First, convert_frame: when a frame exceeds recompile_limit it is pinned to
RUN_ONLY, so every variant past the limit is never captured, and the package
was not told. It now records the frame as truncated. Note this is deliberately
NOT a bypass: install() treats a bypassed entry as "serve nothing", so marking
these frames bypassed would throw away the variants that were captured
successfully and make coverage strictly worse for existing caching_precompile
users, who would rather serve eight variants and recompile for the rest. The
truncation set is runtime-only and is not serialized, both because it describes
a capture session rather than an artifact and because a persisted flag would
poison a DynamoCache entry permanently -- nothing resets it, and raising the
limit on a later run would not recover.
Second, package: uninstall() only cleared precompile entries for the entry code
object, leaving them installed on every resume function and on any frame
reached through code_source, so loading an artifact mutated global state that
neither uninstall() nor torch._dynamo.reset() could undo. install() now records
the code objects it touches, and also records the frames it skip_code()s so
those are restored too. Because precompile entries can only be cleared en masse
and not individually, uninstall() now refuses when another live package is
installed on the same code object rather than silently clearing its entries --
that configuration is unsupported, and a loud error beats a corrupted neighbour.
Third, precompile_package: the API. precompile_capture yields the callable to
exercise, save() refuses to write an artifact that cannot serve what it claims,
precompile_load does the order-sensitive attach-then-install in one call and
returns something that can be unloaded, and recompile_limit defaults to 256
because a precompile deliberately wants one variant per condition whereas the
usual limit of 8 exists to catch runaway recompilation.
The guard filter deserves its own note, because the obvious design is wrong.
The set of guards Dynamo cannot serialize is exactly the IDENTITY guards --
ID_MATCH, FUNCTION_MATCH, CLOSURE_MATCH, MODULE_MATCH and friends -- so
precompiling inherently gives up on noticing that a guarded object was rebound
to a different object of the same shape. Keeping them is not an option, since
serialization then fails for essentially every function; dropping them silently
is how you serve a graph traced against the old value. So every drop is
recorded with its source name, and save() refuses by default when a dropped
guard is on a bare global holding a non-module -- the ACT = some_fn dispatch
switch, which is the shape that actually produces wrong answers. Guards on
modules and on attributes reached through them are noise and are allowed. This
is a heuristic and is documented as one; dropped_guards remains the
authoritative list.
precompile_load also validates that the artifact was captured from the callable
it is being loaded onto. CompilePackage.initialize rebinds stored guards and
bytecode onto whatever function it is given, and the source checksum only
covers the captured function, so loading f's artifact onto g otherwise returns
f's results with no error.
Capture remains by execution -- a resume function only exists once the frame
ahead of it has run -- so callers must exercise every path they want covered.
summary() exposes the counts, the truncated and bypassed frames, and the kept
and dropped guards with their sources, so a build step can assert coverage
instead of discovering gaps in production.
A second adversarial review pass drove the following, all of which had
reproducers:
The guard-drop lint was rewritten. It classified by matching the guard SOURCE
against a bare-global pattern, which cannot work: guard names have their local
scope stripped, so a guard on self.act arrives as "self.act" and is
indistinguishable from a global. It caught 2 of 11 dispatch shapes and missed
self.act, the way essentially every configurable activation is written, while
also firing on `from torch.nn.functional import relu`. It now classifies by what
the guarded VALUE is: torch-owned and builtin objects are library machinery,
anything else is user code that a serving setup might rebind. That catches 9 of
9 reproducible shapes and stops refusing plain nn.Sequential. The remaining gap
-- capturing with a torch-owned callable and rebinding to another one -- is
documented on the predicate.
The cross-package conflict check raised on uninstall, which deadlocked two
packages sharing a frame: the message said to unload the other first, but
neither could go first, and the failed unload left globals already deleted. It
now warns and proceeds. Its registry also keyed on id(self), so a package
dropped without unloading blocked every later one; it holds weak references now,
and covers the entry code object, which it previously skipped.
save() grew two things the review showed were needed. A forward-only capture
with grad enabled records no backends at all, because AOTAutograd only registers
the bundled artifact once the backward compiles; that surfaced as a RuntimeError
naming an internal symbol, and is now a PackageError saying to capture under
no_grad. And a value crossing a graph break is guarded by equality, so such an
artifact serves only the inputs it was captured with -- summary() now reports
those as wont_generalize, and save() warns.
Truncated frames are keyed by file and line rather than bare co_name, which
collapsed distinct frames both called forward. The trace artifact emitted on
truncation was renamed off dynamo_cache_bypass, since conflating it with a real
bypass misreports a frame that still serves.
The module docstring now states the operational limits up front: capture under
no_grad, expect value-pinned artifacts from data-dependent breaks, identity
guards are not recoverable, the model must be importable, and install() patches
code objects process-globally.
The intended deployment is capture on one machine, serve on another, so the
in-process concerns above matter less than divergence between the two. The
guard-drop lint is framed for that: identical source is not sufficient, because
config or an environment variable can select a different object on the serving
machine, and an identity guard on it cannot be serialized. Verified end to end
-- capturing an activation chosen by an env var and serving with that var
changed returns a wrong answer, and save() refuses the artifact unless the risk
is explicitly accepted. The other cross-machine rails were verified too: the
source checksum finds the module by name rather than path, so an artifact moves
between differently laid out checkouts but still refuses to load against
drifted source, and SystemInfo rejects Python, PyTorch, CUDA, Triton and GPU
skew at load.
Test Plan:
New tests in test/dynamo/test_package.py. Coverage: a round trip across two
graph breaks and three specializations on both backends; guards on a global
dict read on both sides of a break; a dict passed as an argument; nested dict
membership and key-set iteration, asserting positively that those guards were
kept rather than merely absent from the dropped list; refusal to save a
truncated capture, and that the variants it did capture still serve; refusal to
save a capture that ran nothing; refusal to save when a risky identity guard
was dropped, and that the risk is acknowledgeable; refusal to load an artifact
captured from a different callable; that unload clears resume-function
entries rather than leaving them installed; and, for the cross-machine case, that
a drifted source module is refused at load and that version skew is rejected.
```
python test/dynamo/test_package.py TestPrecompilePackage
```
Regressions:
```
python test/dynamo/test_package.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_recompiles.py
python test/dynamo/test_precompile_context.py
python test/dynamo/test_misc.py
```
test_package 79 OK, test_recompiles 18 OK, test_misc 842 OK, test_precompile_context 3 OK.
test_aot_compile has 3 pre-existing errors (test_aot_compile_with_aoti*) from a
local environment gap where AOTI's generated header cannot find cuda.h; they
fail identically on a clean tree.
Scale was checked out of tree at the target size, 50 graph breaks by 3
specializations, in both layouts:
```
50 breaks in distinct frames : 51 frames, 153 guarded codes, 153 graphs,
12s capture, 2.2 MB, 0.5s load
50 instances sharing a frame : 3 frames, 150 guarded codes, 150 graphs,
12s capture, 2.4 MB, 0.5s load
```
Both replay all three variants under fail_on_recompile with zero recompiles and
reject an uncovered input. Note that guard dispatch is a linear scan over a
frame's guarded codes, so the shared-frame layout costs 1.7ms for the first
variant against 5.2ms for the last, where the distinct-frame layout is flat at
0.9ms. That is a property of the existing dispatch path, not something this
change introduces.
Authored with an AI assistant.
ghstack-source-id: 7a93d4a
Pull-Request: #192379
bobrenjc93
added a commit
that referenced
this pull request
Aug 7, 2026
…piles
aot_compile produces exactly one graph and rejects graph breaks, so a model
that breaks 50 times and specializes 3 ways per frame cannot be precompiled at
all today. CompilePackage already captures every frame Dynamo produces --
entry, resume continuations, and each recompiled variant -- but it is a low
level component with no API, and assembling it by hand is unsafe in several
ways this change fixes. The theme throughout is that every failure mode here is
silent by construction: a precompiled artifact that is missing coverage or
missing a guard does not raise, it serves the wrong graph.
Review the three pieces in this order.
First, convert_frame: when a frame exceeds recompile_limit it is pinned to
RUN_ONLY, so every variant past the limit is never captured, and the package
was not told. It now records the frame as truncated. Note this is deliberately
NOT a bypass: install() treats a bypassed entry as "serve nothing", so marking
these frames bypassed would throw away the variants that were captured
successfully and make coverage strictly worse for existing caching_precompile
users, who would rather serve eight variants and recompile for the rest. The
truncation set is runtime-only and is not serialized, both because it describes
a capture session rather than an artifact and because a persisted flag would
poison a DynamoCache entry permanently -- nothing resets it, and raising the
limit on a later run would not recover.
Second, package: uninstall() only cleared precompile entries for the entry code
object, leaving them installed on every resume function and on any frame
reached through code_source, so loading an artifact mutated global state that
neither uninstall() nor torch._dynamo.reset() could undo. install() now records
the code objects it touches, and also records the frames it skip_code()s so
those are restored too. Because precompile entries can only be cleared en masse
and not individually, uninstall() now refuses when another live package is
installed on the same code object rather than silently clearing its entries --
that configuration is unsupported, and a loud error beats a corrupted neighbour.
Third, precompile_package: the API. precompile_capture yields the callable to
exercise, save() refuses to write an artifact that cannot serve what it claims,
precompile_load does the order-sensitive attach-then-install in one call and
returns something that can be unloaded, and recompile_limit defaults to 256
because a precompile deliberately wants one variant per condition whereas the
usual limit of 8 exists to catch runaway recompilation.
The guard filter deserves its own note, because the obvious design is wrong.
The set of guards Dynamo cannot serialize is exactly the IDENTITY guards --
ID_MATCH, FUNCTION_MATCH, CLOSURE_MATCH, MODULE_MATCH and friends -- so
precompiling inherently gives up on noticing that a guarded object was rebound
to a different object of the same shape. Keeping them is not an option, since
serialization then fails for essentially every function; dropping them silently
is how you serve a graph traced against the old value. So every drop is
recorded with its source name, and save() refuses by default when a dropped
guard is on a bare global holding a non-module -- the ACT = some_fn dispatch
switch, which is the shape that actually produces wrong answers. Guards on
modules and on attributes reached through them are noise and are allowed. This
is a heuristic and is documented as one; dropped_guards remains the
authoritative list.
precompile_load also validates that the artifact was captured from the callable
it is being loaded onto. CompilePackage.initialize rebinds stored guards and
bytecode onto whatever function it is given, and the source checksum only
covers the captured function, so loading f's artifact onto g otherwise returns
f's results with no error.
Capture remains by execution -- a resume function only exists once the frame
ahead of it has run -- so callers must exercise every path they want covered.
summary() exposes the counts, the truncated and bypassed frames, and the kept
and dropped guards with their sources, so a build step can assert coverage
instead of discovering gaps in production.
A second adversarial review pass drove the following, all of which had
reproducers:
The guard-drop lint was rewritten. It classified by matching the guard SOURCE
against a bare-global pattern, which cannot work: guard names have their local
scope stripped, so a guard on self.act arrives as "self.act" and is
indistinguishable from a global. It caught 2 of 11 dispatch shapes and missed
self.act, the way essentially every configurable activation is written, while
also firing on `from torch.nn.functional import relu`. It now classifies by what
the guarded VALUE is: torch-owned and builtin objects are library machinery,
anything else is user code that a serving setup might rebind. That catches 9 of
9 reproducible shapes and stops refusing plain nn.Sequential. The remaining gap
-- capturing with a torch-owned callable and rebinding to another one -- is
documented on the predicate.
The cross-package conflict check raised on uninstall, which deadlocked two
packages sharing a frame: the message said to unload the other first, but
neither could go first, and the failed unload left globals already deleted. It
now warns and proceeds. Its registry also keyed on id(self), so a package
dropped without unloading blocked every later one; it holds weak references now,
and covers the entry code object, which it previously skipped.
save() grew two things the review showed were needed. A forward-only capture
with grad enabled records no backends at all, because AOTAutograd only registers
the bundled artifact once the backward compiles; that surfaced as a RuntimeError
naming an internal symbol, and is now a PackageError saying to capture under
no_grad. And a value crossing a graph break is guarded by equality, so such an
artifact serves only the inputs it was captured with -- summary() now reports
those as wont_generalize, and save() warns.
Truncated frames are keyed by file and line rather than bare co_name, which
collapsed distinct frames both called forward. The trace artifact emitted on
truncation was renamed off dynamo_cache_bypass, since conflating it with a real
bypass misreports a frame that still serves.
The module docstring now states the operational limits up front: capture under
no_grad, expect value-pinned artifacts from data-dependent breaks, identity
guards are not recoverable, the model must be importable, and install() patches
code objects process-globally.
The intended deployment is capture on one machine, serve on another, so the
in-process concerns above matter less than divergence between the two. The
guard-drop lint is framed for that: identical source is not sufficient, because
config or an environment variable can select a different object on the serving
machine, and an identity guard on it cannot be serialized. Verified end to end
-- capturing an activation chosen by an env var and serving with that var
changed returns a wrong answer, and save() refuses the artifact unless the risk
is explicitly accepted. The other cross-machine rails were verified too: the
source checksum finds the module by name rather than path, so an artifact moves
between differently laid out checkouts but still refuses to load against
drifted source, and SystemInfo rejects Python, PyTorch, CUDA, Triton and GPU
skew at load.
Test Plan:
New tests in test/dynamo/test_package.py. Coverage: a round trip across two
graph breaks and three specializations on both backends; guards on a global
dict read on both sides of a break; a dict passed as an argument; nested dict
membership and key-set iteration, asserting positively that those guards were
kept rather than merely absent from the dropped list; refusal to save a
truncated capture, and that the variants it did capture still serve; refusal to
save a capture that ran nothing; refusal to save when a risky identity guard
was dropped, and that the risk is acknowledgeable; refusal to load an artifact
captured from a different callable; that unload clears resume-function
entries rather than leaving them installed; and, for the cross-machine case, that
a drifted source module is refused at load and that version skew is rejected.
```
python test/dynamo/test_package.py TestPrecompilePackage
```
Regressions:
```
python test/dynamo/test_package.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_recompiles.py
python test/dynamo/test_precompile_context.py
python test/dynamo/test_misc.py
```
test_package 79 OK, test_recompiles 18 OK, test_misc 842 OK, test_precompile_context 3 OK.
test_aot_compile has 3 pre-existing errors (test_aot_compile_with_aoti*) from a
local environment gap where AOTI's generated header cannot find cuda.h; they
fail identically on a clean tree.
Scale was checked out of tree at the target size, 50 graph breaks by 3
specializations, in both layouts:
```
50 breaks in distinct frames : 51 frames, 153 guarded codes, 153 graphs,
12s capture, 2.2 MB, 0.5s load
50 instances sharing a frame : 3 frames, 150 guarded codes, 150 graphs,
12s capture, 2.4 MB, 0.5s load
```
Both replay all three variants under fail_on_recompile with zero recompiles and
reject an uncovered input. Note that guard dispatch is a linear scan over a
frame's guarded codes, so the shared-frame layout costs 1.7ms for the first
variant against 5.2ms for the last, where the distinct-frame layout is flat at
0.9ms. That is a property of the existing dispatch path, not something this
change introduces.
Authored with an AI assistant.
ghstack-source-id: 7a93d4a
Pull-Request: #192379
bobrenjc93
added a commit
that referenced
this pull request
Aug 7, 2026
…piles
aot_compile produces exactly one graph and rejects graph breaks, so a model
that breaks 50 times and specializes 3 ways per frame cannot be precompiled at
all today. CompilePackage already captures every frame Dynamo produces --
entry, resume continuations, and each recompiled variant -- but it is a low
level component with no API, and assembling it by hand is unsafe in several
ways this change fixes. The theme throughout is that every failure mode here is
silent by construction: a precompiled artifact that is missing coverage or
missing a guard does not raise, it serves the wrong graph.
Review the three pieces in this order.
First, convert_frame: when a frame exceeds recompile_limit it is pinned to
RUN_ONLY, so every variant past the limit is never captured, and the package
was not told. It now records the frame as truncated. Note this is deliberately
NOT a bypass: install() treats a bypassed entry as "serve nothing", so marking
these frames bypassed would throw away the variants that were captured
successfully and make coverage strictly worse for existing caching_precompile
users, who would rather serve eight variants and recompile for the rest. The
truncation set is runtime-only and is not serialized, both because it describes
a capture session rather than an artifact and because a persisted flag would
poison a DynamoCache entry permanently -- nothing resets it, and raising the
limit on a later run would not recover.
Second, package: uninstall() only cleared precompile entries for the entry code
object, leaving them installed on every resume function and on any frame
reached through code_source, so loading an artifact mutated global state that
neither uninstall() nor torch._dynamo.reset() could undo. install() now records
the code objects it touches, and also records the frames it skip_code()s so
those are restored too. Because precompile entries can only be cleared en masse
and not individually, uninstall() now refuses when another live package is
installed on the same code object rather than silently clearing its entries --
that configuration is unsupported, and a loud error beats a corrupted neighbour.
Third, precompile_package: the API. precompile_capture yields the callable to
exercise, save() refuses to write an artifact that cannot serve what it claims,
precompile_load does the order-sensitive attach-then-install in one call and
returns something that can be unloaded, and recompile_limit defaults to 256
because a precompile deliberately wants one variant per condition whereas the
usual limit of 8 exists to catch runaway recompilation.
The guard filter deserves its own note, because the obvious design is wrong.
The set of guards Dynamo cannot serialize is exactly the IDENTITY guards --
ID_MATCH, FUNCTION_MATCH, CLOSURE_MATCH, MODULE_MATCH and friends -- so
precompiling inherently gives up on noticing that a guarded object was rebound
to a different object of the same shape. Keeping them is not an option, since
serialization then fails for essentially every function; dropping them silently
is how you serve a graph traced against the old value. So every drop is
recorded with its source name, and save() refuses by default when a dropped
guard is on a bare global holding a non-module -- the ACT = some_fn dispatch
switch, which is the shape that actually produces wrong answers. Guards on
modules and on attributes reached through them are noise and are allowed. This
is a heuristic and is documented as one; dropped_guards remains the
authoritative list.
precompile_load also validates that the artifact was captured from the callable
it is being loaded onto. CompilePackage.initialize rebinds stored guards and
bytecode onto whatever function it is given, and the source checksum only
covers the captured function, so loading f's artifact onto g otherwise returns
f's results with no error.
Capture remains by execution -- a resume function only exists once the frame
ahead of it has run -- so callers must exercise every path they want covered.
summary() exposes the counts, the truncated and bypassed frames, and the kept
and dropped guards with their sources, so a build step can assert coverage
instead of discovering gaps in production.
A second adversarial review pass drove the following, all of which had
reproducers:
The guard-drop lint was rewritten. It classified by matching the guard SOURCE
against a bare-global pattern, which cannot work: guard names have their local
scope stripped, so a guard on self.act arrives as "self.act" and is
indistinguishable from a global. It caught 2 of 11 dispatch shapes and missed
self.act, the way essentially every configurable activation is written, while
also firing on `from torch.nn.functional import relu`. It now classifies by what
the guarded VALUE is: torch-owned and builtin objects are library machinery,
anything else is user code that a serving setup might rebind. That catches 9 of
9 reproducible shapes and stops refusing plain nn.Sequential. The remaining gap
-- capturing with a torch-owned callable and rebinding to another one -- is
documented on the predicate.
The cross-package conflict check raised on uninstall, which deadlocked two
packages sharing a frame: the message said to unload the other first, but
neither could go first, and the failed unload left globals already deleted. It
now warns and proceeds. Its registry also keyed on id(self), so a package
dropped without unloading blocked every later one; it holds weak references now,
and covers the entry code object, which it previously skipped.
save() grew two things the review showed were needed. A forward-only capture
with grad enabled records no backends at all, because AOTAutograd only registers
the bundled artifact once the backward compiles; that surfaced as a RuntimeError
naming an internal symbol, and is now a PackageError saying to capture under
no_grad. And a value crossing a graph break is guarded by equality, so such an
artifact serves only the inputs it was captured with -- summary() now reports
those as wont_generalize, and save() warns.
Truncated frames are keyed by file and line rather than bare co_name, which
collapsed distinct frames both called forward. The trace artifact emitted on
truncation was renamed off dynamo_cache_bypass, since conflating it with a real
bypass misreports a frame that still serves.
The module docstring now states the operational limits up front: capture under
no_grad, expect value-pinned artifacts from data-dependent breaks, identity
guards are not recoverable, the model must be importable, and install() patches
code objects process-globally.
The intended deployment is capture on one machine, serve on another, so the
in-process concerns above matter less than divergence between the two. The
guard-drop lint is framed for that: identical source is not sufficient, because
config or an environment variable can select a different object on the serving
machine, and an identity guard on it cannot be serialized. Verified end to end
-- capturing an activation chosen by an env var and serving with that var
changed returns a wrong answer, and save() refuses the artifact unless the risk
is explicitly accepted. The other cross-machine rails were verified too: the
source checksum finds the module by name rather than path, so an artifact moves
between differently laid out checkouts but still refuses to load against
drifted source, and SystemInfo rejects Python, PyTorch, CUDA, Triton and GPU
skew at load.
A third review pass, run as an adversarial PR review, drove these corrections.
Two upstream regression tests had been dropped from test_package.py by an
earlier rebase and are restored, along with the gc and CleanupManager imports
they need: test_reset_clears_installed_package and
test_install_survives_stale_cleanup_hooks, which cover code four lines from
what this change touches. An entry frame with no compiled code now counts
against completeness rather than only warning -- install() skip_code()s such a
frame, so the model runs eager and, because a skipped frame never compiles,
serving() cannot report the gap; that is legitimate for a frame that only
dispatches to submodules, so the error says so and require_complete=False
accepts it. The grad-mode caveat was overstated and is now scoped to the case
that actually fails, inductor with parameters that require grad. And the
docstring records that SystemInfo does not check the CPU vector ISA: inductor
bakes the vector width into generated CPU code, so an AVX-512 capture served on
an AVX2 host can produce wrong numbers with no error, which matters for a
feature whose deployment model is capture here and serve there.
Test Plan:
New tests in test/dynamo/test_package.py. Coverage: a round trip across two
graph breaks and three specializations on both backends; guards on a global
dict read on both sides of a break; a dict passed as an argument; nested dict
membership and key-set iteration, asserting positively that those guards were
kept rather than merely absent from the dropped list; refusal to save a
truncated capture, and that the variants it did capture still serve; refusal to
save a capture that ran nothing; refusal to save when a risky identity guard
was dropped, and that the risk is acknowledgeable; refusal to load an artifact
captured from a different callable; that unload clears resume-function
entries rather than leaving them installed; and, for the cross-machine case, that
a drifted source module is refused at load and that version skew is rejected.
```
python test/dynamo/test_package.py TestPrecompilePackage
```
Regressions:
```
python test/dynamo/test_package.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_recompiles.py
python test/dynamo/test_precompile_context.py
python test/dynamo/test_misc.py
```
test_package 79 OK, test_recompiles 18 OK, test_misc 842 OK, test_precompile_context 3 OK.
test_aot_compile has 3 pre-existing errors (test_aot_compile_with_aoti*) from a
local environment gap where AOTI's generated header cannot find cuda.h; they
fail identically on a clean tree.
Scale was checked out of tree at the target size, 50 graph breaks by 3
specializations, in both layouts:
```
50 breaks in distinct frames : 51 frames, 153 guarded codes, 153 graphs,
12s capture, 2.2 MB, 0.5s load
50 instances sharing a frame : 3 frames, 150 guarded codes, 150 graphs,
12s capture, 2.4 MB, 0.5s load
```
Both replay all three variants under fail_on_recompile with zero recompiles and
reject an uncovered input. Note that guard dispatch is a linear scan over a
frame's guarded codes, so the shared-frame layout costs 1.7ms for the first
variant against 5.2ms for the last, where the distinct-frame layout is flat at
0.9ms. That is a property of the existing dispatch path, not something this
change introduces.
Authored with an AI assistant.
ghstack-source-id: 290ed63
Pull-Request: #192379
bobrenjc93
added a commit
that referenced
this pull request
Aug 8, 2026
…piles
aot_compile produces exactly one graph and rejects graph breaks, so a model
that breaks 50 times and specializes 3 ways per frame cannot be precompiled at
all today. CompilePackage already captures every frame Dynamo produces --
entry, resume continuations, and each recompiled variant -- but it is a low
level component with no API, and assembling it by hand is unsafe in several
ways this change fixes. The theme throughout is that every failure mode here
is silent by construction: an artifact that is missing coverage, missing a
guard, or installed next to another artifact does not raise, it serves the
wrong graph.
Review the three pieces in this order.
First, convert_frame, which is the smallest: when a frame exceeds
recompile_limit it is pinned to RUN_ONLY, so every variant past the limit is
never captured, and the package was not told. It now records the frame as
truncated. This is deliberately NOT a bypass: install() treats a bypassed
entry as "serve nothing", so marking these frames bypassed would throw away
the variants that were captured successfully and make coverage strictly worse
for existing caching_precompile users, who would rather serve eight variants
and recompile for the rest. The truncation set is runtime-only and is not
serialized, both because it describes a capture session rather than an
artifact and because a persisted flag would poison a DynamoCache entry
permanently -- nothing resets it, and raising the limit on a later run would
not recover. It is also a lower bound rather than a list: RUN_ONLY is
recursive, so frames called beneath the offender stop capturing without ever
re-entering Dynamo to report it, and the summary and the save() refusal both
say so.
Second, package.py, which is where the process-global state lives. uninstall()
only cleared precompile entries for the entry code object, leaving them
installed on every resume function and on any frame reached through
code_source, so loading an artifact mutated global state that neither
uninstall() nor torch._dynamo.reset() could undo. install() now records the
code objects it touches and the frames it skip_code()s, and takes both back --
with a skip revoked only by the last package holding it, since the strategy a
frame had before install() skipped it cannot be read back. A global install()
wrote is removed only while it is still bound to the value install() put
there; one that something else has rebound since belongs to that writer, and
popping it would leave live consumers with a NameError, because the namespace
is shared with plain torch.compile. It deliberately does not put back what it
displaced: the only writer that ever displaces one of these names is a second
package installing the same artifact, whose load already orphaned the first
package's value, so restoring it on the later unload leaves a compiled backend
bound in the module for the life of the process -- one set per load cycle,
which is exactly the shape a serving process that reloads models has. The
generated builtins-dict global is recorded too, since its name carries the
capture process's counter and leaving it behind makes the first local compile
that mints the same name die in CleanupHook.create; import aliases are
deliberately not recorded, because every writer of an alias writes the same
module object and plain torch.compile installs it permanently. install() also
rolls itself back if it raises, because a half-installed package serves some
frames and not others with no handle left to undo it.
Two more things in that file are about several artifacts coexisting, which is
the serving-process shape. Resume functions are bound under
__resume_at_<offset>_<n>, from a counter that restarts in every capture
process, so two artifacts captured separately both claim __resume_at_16_3; a
serving process installs both into one module dict, the second write wins, and
the first model silently runs the second's continuation -- right shape, wrong
numbers. They are now installed under a name suffixed with a digest of the
code they name, with co_names rewritten so the dynamo bytecode follows the
renamed binding. And because precompile entries can only be cleared en masse,
uninstall() warns when another live package installed on the same code object
rather than clearing its entries silently. The warning says what actually
happens next, which is not what the first version of it claimed: the evicted
package's callers do not simply recompile, they fall through to whatever
entries remain, and a surviving package whose guards accept the call serves it
that package's graph with no error at all. That is the normal case rather than
a corner, because the guard that would have told two instances apart is
usually an identity guard precompile had to drop. It warns rather than
refuses: the first version raised, which deadlocked two packages sharing a
frame since neither could go first, and left globals already deleted behind.
The registry holds weak references so a package dropped without unloading does
not block a later one, covers the entry code object -- __init__ calls
uninstall() before this package has installed anything, which is exactly the
second-artifact path -- and stays quiet when there is nothing left to take.
The device_type field belongs to the same file and is easy to miss. It is one
string per package and it gates every GPU check in
SystemInfo.check_compatibility, while a package now holds many graphs, so the
cpu epilogue after an .item() break used to erase the "cuda" an earlier graph
recorded. It only widens cpu -> accelerator now, is restored from the artifact
on load rather than recomputed from whatever this process happens to
recompile, and is reset when a package is re-initialized: a failed load is
retried on the same object, and because the field only widens, a value the
failed load left behind could never be corrected and would be re-saved as the
next capture's.
Third, precompile_package.py: the API. precompile_capture yields the callable
to exercise, save() refuses to write an artifact that cannot serve what it
claims, precompile_load does the order-sensitive attach-then-install in one
call and returns something that can be unloaded, serving() forbids compilation
so an uncovered call raises instead of quietly recompiling, and
recompile_limit defaults to 256 because a precompile deliberately wants one
variant per condition whereas the usual limit of 8 exists to catch runaway
recompilation. Capture remains by execution -- a resume function only exists
once the frame ahead of it has run -- so callers must exercise every path they
want covered, and summary() exposes the counts, the truncated, bypassed and
uncovered frames, the value-pinned sources, and the kept and dropped guards
with their sources, so a build step can assert coverage instead of discovering
gaps in production. An entry frame with no compiled code counts against
completeness rather than only warning, because install() skip_code()s such a
frame, so the model runs eager and, a skipped frame never compiling, serving()
cannot report the gap; that is legitimate for a frame that only dispatches to
submodules, so the error says so and require_complete=False accepts it. A
forward-only capture with grad enabled records no backends at all -- with
inductor and parameters that require grad, AOTAutograd only registers the
bundled artifact once the backward compiles -- which surfaced as a
RuntimeError naming an internal symbol and is now a PackageError saying to
capture under no_grad.
precompile_load also validates that the artifact was captured from the
callable it is being loaded onto. CompilePackage.initialize rebinds stored
guards and bytecode onto whatever function it is given, and the source
checksum only covers the captured function, so loading f's artifact onto g
otherwise returns f's results with no error. Identity is (defining module,
qualname, co_name, first line). co_filename is deliberately excluded: the
capture and serving machines check out to different absolute paths, and the
module name already carries what the path would say. The first line is what
separates two definitions of one name in one module -- the class under an `if`
that a config flag picks -- which agrees on every other field and which the
source checksum passes, since both branches sit in the line range it hashes.
The guard filter deserves the most attention, because it is the part that has
been wrong the most times. The set of guards Dynamo cannot serialize is
exactly the IDENTITY guards -- ID_MATCH, FUNCTION_MATCH, CLOSURE_MATCH,
MODULE_MATCH and friends -- so precompiling inherently gives up on noticing
that a guarded object was rebound to a different object of the same shape.
Keeping them is not an option, since serialization then fails for essentially
every function; dropping them silently is how you serve a graph traced against
the old value. So every drop is recorded with its source name, and save()
refuses by default when a drop looks load-bearing.
Four versions of that predicate have now been written, and each of the first
three passed its own tests while failing open on a shape nobody had thought
of. Matching the guard SOURCE against a bare-global pattern cannot work at
all: guard names have their local scope stripped, so a guard on self.act
arrives as "self.act" and is indistinguishable from a global. Classifying by
who OWNS the value waves through `self.act = getattr(F, cfg.activation)`,
because F.gelu is torch-owned, and that is the exact divergence the check
exists for. Intersecting the two fixed those but trusted anything read off a
module namespace it had decided was trustworthy, which laundered every
module-level dispatch there is -- `cconf.ACT`, `dispatch.op`, a re-export
through a package __init__, a dispatch inside an inlined helper -- and it
handed a submodule its parent's trust without looking at the name, so
`from . import impl_b as impl` in a package __init__ made `mypkg.impl.op`
benign. What ships is the intersection with both of those holes closed: the
binding SITE, read off the structured Source that survives the name stripping,
decides what can be repointed without a source edit, and who OWNS the value
decides whether the thing at that site has plug points at all -- but trusting
a namespace is no longer trusting everything read off it. A read off a
namespace clears only when torch or the stdlib owns the namespace, or the
namespace owns the value being read. A submodule is trusted only under a name
its parent already owns, its own __name__ or the parent's plus the attribute.
And the builtins exemption was narrowed the same way: `len` reached through
Dynamo's builtins dict clears, while `self.act = abs` -- a builtin out of an
ACT2FN-style table -- does not, because the value being unrepointable says
nothing about the slot holding it.
Given that history, the shapes live in a table in the test file rather than in
prose. _RISKY_DROP_CORPUS has nineteen entries that must always be flagged and
_BENIGN_DROP_CORPUS has nine that must never be, and the two are paired so
that widening the predicate cannot satisfy both: `cpkg.impl.op` against
`cpkg.cimpl.op`, `cconf.ACT` against `cown.call`, `import math as alias`
against a user module under an alias. Both run as parametrized tests, one per
shape.
What it still does NOT catch is worth stating plainly, because the refusal is
on by default and users will read it as a guarantee. Every waiver judges the
object capture happened to bind, not the statement that bound it, so any name
bound conditionally is waived whenever the branch taken on the capture machine
is one of the waived shapes. This is not specific to one arm. On the def-name
arm, `if HAVE_FAST: from fastops import gelu` / `else: from
torch.nn.functional import gelu`, captured without the flag, drops G['gelu'],
reports nothing, saves clean, and returns torch's gelu on a machine that has
fastops. On the namespace-owns-the-value arm, a module that binds a name under
an `if` and is read through an ordinary `import mod` elsewhere is waived too,
because at capture time that module genuinely does own whichever def the
branch produced -- and there the reading file binds nothing conditionally, so
it looks covered and is not. Both were reproduced end to end, not reasoned
about. An allow_in_graph callable passes as well. Nothing at capture time
distinguishes a conditional bind from an unconditional one, only the resulting
object is visible, so this is a limit of the approach rather than a missing
check. dropped_guards remains the authoritative list; this predicate is a lint
over it.
The cost of the strictness is one real refusal in stock torch, and it is
deliberate. Sweeping 23 stock nn layers flags exactly two,
TransformerEncoderLayer and TransformerEncoder, both on the same slot: the
activation is a constructor keyword parked in an attribute, which is torch's
own spelling of `self.act = getattr(F, cfg.activation)`. Capturing one with
activation="relu" and serving it with activation="gelu" loads clean and
returns the relu answer, so it is a true positive, and exempting it would need
a "library-owned callable in a library-owned nn.Module attribute" rule that
reintroduces exactly that wrong answer. Transformer users pass
require_no_risky_drops=False once. Everything else in the sweep -- Conv/BN,
LSTM/GRU/RNN, MultiheadAttention, Sequential, LayerNorm, Embedding, pooling,
builtins-heavy code -- is clean.
wont_generalize got the same treatment. It keyed on the ___stackN name Dynamo
gives a value crossing a graph break, which both misses and overcounts: a
non-tensor argument is equality-pinned with no ___stackN name, while a tensor
crossing a break gets a ___stackN source under TENSOR_MATCH and generalizes
fine. It now requires a value-equality guard type AND a bare source name, so
model config reached through an argument -- a LayerNorm's eps, a Dropout's p --
does not flag every model. Both CONSTANT_MATCH and EQUALS_MATCH count, since
which one Dynamo emits depends on the value's type rather than on whether it
pins anything. A constant inside a container argument is guarded on a
subscripted source and is still missed; kept_guards is the authoritative list.
The intended deployment is capture on one machine and serve on another, so the
in-process concerns above matter less than divergence between the two, and the
cross-machine rails were checked end to end rather than argued. The source
checksum finds the module by name rather than by path, so an artifact moves
between differently laid out checkouts but still refuses to load against
drifted source, and SystemInfo rejects Python, PyTorch, CUDA, Triton and GPU
skew at load. It does not check the CPU vector ISA -- inductor bakes the
vector width into generated CPU code, so an AVX-512 capture served on an AVX2
host can produce wrong numbers with no error -- and the module docstring
records that along with the rest of the operational limits: capture under
no_grad, expect value-pinned artifacts from data-dependent breaks, identity
guards are not recoverable, the model must be importable, install() patches
code objects process-globally, a second artifact for one class silently
substitutes the survivor's graph for the evicted one, and a plain
torch.compile in a module that has an artifact loaded can hit a
__builtins_dict__ name collision until the artifact is unloaded. That last one
is disclosed rather than fixed: the real fix is not minting the name off a
process-local counter, which is output_graph's call, and rewriting the name at
load time would mean rewriting source trees inside serialized guard state,
where a mistake is a guard that silently stops discriminating.
Test Plan:
New tests in test/dynamo/test_package.py, in TestPrecompilePackage. Coverage:
a round trip across two graph breaks and three specializations on both
backends; guards on a global dict read on both sides of a break, a dict passed
as an argument, and nested dict membership and key-set iteration, asserting
positively that those guards were kept rather than merely absent from the
dropped list; the save() refusals, each with the acknowledging flag exercised
-- a truncated capture (and that the variants it did capture still serve), a
capture that ran nothing, an entry frame with no compiled code, and a risky
dropped identity guard; the risky-drop corpus, nineteen shapes that must be
flagged and nine that must not, each parametrized, plus the individual cases
that pin one clause of the predicate apiece -- a builtin read through the
builtins dict versus a builtin in an attribute versus a user table shaped like
the builtins dict, torch.nn.functional.gelu spelled out in full, a submodule
of a self-named package, and four library spellings that only the ownership
test can clear; the value-pinning report -- a plain int argument, a dict_keys
argument that arrives as EQUALS_MATCH rather than CONSTANT_MATCH, both the
stack slot and the resume frame's local from an .item(), a tensor crossing a
break that must not count, and LayerNorm/Dropout/attribute config constants
that must not count; artifact identity at load -- a different callable, a
same-named class from another module, a different definition of the same name
in one module, a functools.wraps wrapper sharing the qualname, an artifact
with no code entries at all, a module whose forward has no __code__, a
__code__ present but None, and a checkout at a different absolute path that
must still load; the process-global state -- unload clearing resume-function
entries, restoring a skipped frame, keeping a skip another package still
holds, keeping globals a bystander compile needs, removing the builtins key
install() added, leaving alone a global a later package rebound while still
leaving the namespace empty once both packages have unloaded, a failed install
leaving nothing installed, and resume names from two separate captures not
colliding; eviction -- the second artifact for a shared frame warning before
it evicts the first, that the warning says the substitution is silent, and
that it warns exactly once and not when there is nothing left to evict;
device_type surviving a cpu graph, a load and re-save, and a failed load; and
the cross-machine refusals, drifted source and version skew.
```
python test/dynamo/test_package.py TestPrecompilePackage
```
Regressions:
```
python test/dynamo/test_package.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_recompiles.py
python test/dynamo/test_precompile_context.py
python test/dynamo/test_guard_serialization.py
```
test_package 151 OK (23 skipped, 1 expected failure), test_recompiles 18 OK,
test_precompile_context 3 OK, test_guard_serialization 60 OK.
test_aot_compile runs 49 with 3 pre-existing errors
(test_aot_compile_with_aoti*) from a local environment gap where AOTI's
generated header cannot find cuda.h; they fail identically on a clean tree.
The predicate and the uninstall change were each checked by reverting them
under the new tests, which is how the corpus earns its keep:
```
# restore the "any read off a trusted namespace is fine" waiver
python test/dynamo/test_package.py -k risky_drop_corpus
# -> 4 failures: module_level_global, package_reexport,
# sibling_module, dispatch_in_inlined_helper
# restore "any builtins-owned value is fine"
python test/dynamo/test_package.py TestPrecompilePackage
# -> 3 failures: attribute_builtin_fn, owner_builtin,
# a_builtin_shaped_read_that_is_still_a_slot_is_risky
# let a submodule inherit its parent's trust unconditionally
python test/dynamo/test_package.py TestPrecompilePackage
# -> 1 failure: package_submodule_alias
# restore uninstall()'s put-back-what-we-displaced loop
python test/dynamo/test_package.py TestPrecompilePackage
# -> 1 failure: test_unload_leaves_a_global_a_later_package_rebound
```
Scale was checked out of tree at the target size, 50 graph breaks on the eager
backend, in both layouts -- one function breaking 50 times and specializing 3
ways, and 50 ModuleList instances whose 50 variants all pile onto one shared
frame:
```
50 breaks in one function : 51 frames, 151 guarded codes,
5.9s capture, 0.9 MB, 0.36s load
50 instances sharing one frame : 3 frames, 51 guarded codes,
2.2s capture, 0.4 MB, 0.13s load
```
Both replay every captured variant under fail_on_recompile with zero
recompiles and reject an uncovered input. Neither reports a risky drop. The
first saves with every rail on; the second is refused until
require_complete=False, because the loop over the ModuleList compiles nothing
of its own and lands in uncovered_frames, which is the case that refusal is
written for. Guard dispatch is a linear scan over one frame's guarded codes,
so the shared-frame layout costs 2.4 ms per call against 0.85 ms for the
distinct-frame layout. That is a property of the existing dispatch path, not
something this change introduces.
Authored with an AI assistant.
ghstack-source-id: 5eb8ec9
Pull-Request: #192379
bobrenjc93
added a commit
that referenced
this pull request
Aug 8, 2026
…piles
aot_compile produces exactly one graph and rejects graph breaks, so a model
that breaks 50 times and specializes 3 ways per frame cannot be precompiled at
all today. CompilePackage already captures every frame Dynamo produces --
entry, resume continuations, and each recompiled variant -- but it is a low
level component with no API, and assembling it by hand is unsafe in several
ways this change fixes. The theme throughout is that every failure mode here
is silent by construction: an artifact that is missing coverage, missing a
guard, or installed next to another artifact does not raise, it serves the
wrong graph.
Review the three pieces in this order.
First, convert_frame, which is the smallest: when a frame exceeds
recompile_limit it is pinned to RUN_ONLY, so every variant past the limit is
never captured, and the package was not told. It now records the frame as
truncated. This is deliberately NOT a bypass: install() treats a bypassed
entry as "serve nothing", so marking these frames bypassed would throw away
the variants that were captured successfully and make coverage strictly worse
for existing caching_precompile users, who would rather serve eight variants
and recompile for the rest. The truncation set is runtime-only and is not
serialized, both because it describes a capture session rather than an
artifact and because a persisted flag would poison a DynamoCache entry
permanently -- nothing resets it, and raising the limit on a later run would
not recover. It is also a lower bound rather than a list: RUN_ONLY is
recursive, so frames called beneath the offender stop capturing without ever
re-entering Dynamo to report it, and the summary and the save() refusal both
say so.
Second, package.py, which is where the process-global state lives. uninstall()
only cleared precompile entries for the entry code object, leaving them
installed on every resume function and on any frame reached through
code_source, so loading an artifact mutated global state that neither
uninstall() nor torch._dynamo.reset() could undo. install() now records the
code objects it touches and the frames it skip_code()s, and takes both back --
with a skip revoked only by the last package holding it, since the strategy a
frame had before install() skipped it cannot be read back. A global install()
wrote is removed only while it is still bound to the value install() put
there; one that something else has rebound since belongs to that writer, and
popping it would leave live consumers with a NameError, because the namespace
is shared with plain torch.compile. It deliberately does not put back what it
displaced: the only writer that ever displaces one of these names is a second
package installing the same artifact, whose load already orphaned the first
package's value, so restoring it on the later unload leaves a compiled backend
bound in the module for the life of the process -- one set per load cycle,
which is exactly the shape a serving process that reloads models has. The
generated builtins-dict global is recorded too, since its name carries the
capture process's counter and leaving it behind makes the first local compile
that mints the same name die in CleanupHook.create; import aliases are
deliberately not recorded, because every writer of an alias writes the same
module object and plain torch.compile installs it permanently. install() also
rolls itself back if it raises, because a half-installed package serves some
frames and not others with no handle left to undo it.
Two more things in that file are about several artifacts coexisting, which is
the serving-process shape. Resume functions are bound under
__resume_at_<offset>_<n>, from a counter that restarts in every capture
process, so two artifacts captured separately both claim __resume_at_16_3; a
serving process installs both into one module dict, the second write wins, and
the first model silently runs the second's continuation -- right shape, wrong
numbers. They are now installed under a name suffixed with a digest of the
code they name, with co_names rewritten so the dynamo bytecode follows the
renamed binding. And because precompile entries can only be cleared en masse,
uninstall() warns when another live package installed on the same code object
rather than clearing its entries silently. The warning says what actually
happens next, which is not what the first version of it claimed: the evicted
package's callers do not simply recompile, they fall through to whatever
entries remain, and a surviving package whose guards accept the call serves it
that package's graph with no error at all. That is the normal case rather than
a corner, because the guard that would have told two instances apart is
usually an identity guard precompile had to drop. It warns rather than
refuses: the first version raised, which deadlocked two packages sharing a
frame since neither could go first, and left globals already deleted behind.
The registry holds weak references so a package dropped without unloading does
not block a later one, covers the entry code object -- __init__ calls
uninstall() before this package has installed anything, which is exactly the
second-artifact path -- and stays quiet when there is nothing left to take.
The device_type field belongs to the same file and is easy to miss. It is one
string per package and it gates every GPU check in
SystemInfo.check_compatibility, while a package now holds many graphs, so the
cpu epilogue after an .item() break used to erase the "cuda" an earlier graph
recorded. It only widens cpu -> accelerator now, is restored from the artifact
on load rather than recomputed from whatever this process happens to
recompile, and is reset when a package is re-initialized: a failed load is
retried on the same object, and because the field only widens, a value the
failed load left behind could never be corrected and would be re-saved as the
next capture's.
Third, precompile_package.py: the API. precompile_capture yields the callable
to exercise, save() refuses to write an artifact that cannot serve what it
claims, precompile_load does the order-sensitive attach-then-install in one
call and returns something that can be unloaded, serving() forbids compilation
so an uncovered call raises instead of quietly recompiling, and
recompile_limit defaults to 256 because a precompile deliberately wants one
variant per condition whereas the usual limit of 8 exists to catch runaway
recompilation. Capture remains by execution -- a resume function only exists
once the frame ahead of it has run -- so callers must exercise every path they
want covered, and summary() exposes the counts, the truncated, bypassed and
uncovered frames, the value-pinned sources, and the kept and dropped guards
with their sources, so a build step can assert coverage instead of discovering
gaps in production. An entry frame with no compiled code counts against
completeness rather than only warning, because install() skip_code()s such a
frame, so the model runs eager and, a skipped frame never compiling, serving()
cannot report the gap; that is legitimate for a frame that only dispatches to
submodules, so the error says so and require_complete=False accepts it. A
forward-only capture with grad enabled records no backends at all -- with
inductor and parameters that require grad, AOTAutograd only registers the
bundled artifact once the backward compiles -- which surfaced as a
RuntimeError naming an internal symbol and is now a PackageError saying to
capture under no_grad.
precompile_load also validates that the artifact was captured from the
callable it is being loaded onto. CompilePackage.initialize rebinds stored
guards and bytecode onto whatever function it is given, and the source
checksum only covers the captured function, so loading f's artifact onto g
otherwise returns f's results with no error. Identity is (defining module,
qualname, co_name, first line). co_filename is deliberately excluded: the
capture and serving machines check out to different absolute paths, and the
module name already carries what the path would say. The first line is what
separates two definitions of one name in one module -- the class under an `if`
that a config flag picks -- which agrees on every other field and which the
source checksum passes, since both branches sit in the line range it hashes.
The guard filter deserves the most attention, because it is the part that has
been wrong the most times. The set of guards Dynamo cannot serialize is
exactly the IDENTITY guards -- ID_MATCH, FUNCTION_MATCH, CLOSURE_MATCH,
MODULE_MATCH and friends -- so precompiling inherently gives up on noticing
that a guarded object was rebound to a different object of the same shape.
Keeping them is not an option, since serialization then fails for essentially
every function; dropping them silently is how you serve a graph traced against
the old value. So every drop is recorded with its source name, and save()
refuses by default when a drop looks load-bearing.
Four versions of that predicate have now been written, and each of the first
three passed its own tests while failing open on a shape nobody had thought
of. Matching the guard SOURCE against a bare-global pattern cannot work at
all: guard names have their local scope stripped, so a guard on self.act
arrives as "self.act" and is indistinguishable from a global. Classifying by
who OWNS the value waves through `self.act = getattr(F, cfg.activation)`,
because F.gelu is torch-owned, and that is the exact divergence the check
exists for. Intersecting the two fixed those but trusted anything read off a
module namespace it had decided was trustworthy, which laundered every
module-level dispatch there is -- `cconf.ACT`, `dispatch.op`, a re-export
through a package __init__, a dispatch inside an inlined helper -- and it
handed a submodule its parent's trust without looking at the name, so
`from . import impl_b as impl` in a package __init__ made `mypkg.impl.op`
benign. What ships is the intersection with both of those holes closed: the
binding SITE, read off the structured Source that survives the name stripping,
decides what can be repointed without a source edit, and who OWNS the value
decides whether the thing at that site has plug points at all -- but trusting
a namespace is no longer trusting everything read off it. A read off a
namespace clears only when torch or the stdlib owns the namespace, or the
namespace owns the value being read. A submodule is trusted only under a name
its parent already owns, its own __name__ or the parent's plus the attribute.
And the builtins exemption was narrowed the same way: `len` reached through
Dynamo's builtins dict clears, while `self.act = abs` -- a builtin out of an
ACT2FN-style table -- does not, because the value being unrepointable says
nothing about the slot holding it.
Given that history, the shapes live in a table in the test file rather than in
prose. _RISKY_DROP_CORPUS has nineteen entries that must always be flagged and
_BENIGN_DROP_CORPUS has nine that must never be, and the two are paired so
that widening the predicate cannot satisfy both: `cpkg.impl.op` against
`cpkg.cimpl.op`, `cconf.ACT` against `cown.call`, `import math as alias`
against a user module under an alias. Both run as parametrized tests, one per
shape.
What it still does NOT catch is worth stating plainly, because the refusal is
on by default and users will read it as a guarantee. Every waiver judges the
object capture happened to bind, not the statement that bound it, so any name
bound conditionally is waived whenever the branch taken on the capture machine
is one of the waived shapes. This is not specific to one arm. On the def-name
arm, `if HAVE_FAST: from fastops import gelu` / `else: from
torch.nn.functional import gelu`, captured without the flag, drops G['gelu'],
reports nothing, saves clean, and returns torch's gelu on a machine that has
fastops. On the namespace-owns-the-value arm, a module that binds a name under
an `if` and is read through an ordinary `import mod` elsewhere is waived too,
because at capture time that module genuinely does own whichever def the
branch produced -- and there the reading file binds nothing conditionally, so
it looks covered and is not. Both were reproduced end to end, not reasoned
about. An allow_in_graph callable passes as well. Nothing at capture time
distinguishes a conditional bind from an unconditional one, only the resulting
object is visible, so this is a limit of the approach rather than a missing
check. dropped_guards remains the authoritative list; this predicate is a lint
over it.
The cost of the strictness is one real refusal in stock torch, and it is
deliberate. Sweeping 23 stock nn layers flags exactly two,
TransformerEncoderLayer and TransformerEncoder, both on the same slot: the
activation is a constructor keyword parked in an attribute, which is torch's
own spelling of `self.act = getattr(F, cfg.activation)`. Capturing one with
activation="relu" and serving it with activation="gelu" loads clean and
returns the relu answer, so it is a true positive, and exempting it would need
a "library-owned callable in a library-owned nn.Module attribute" rule that
reintroduces exactly that wrong answer. Transformer users pass
require_no_risky_drops=False once. Everything else in the sweep -- Conv/BN,
LSTM/GRU/RNN, MultiheadAttention, Sequential, LayerNorm, Embedding, pooling,
builtins-heavy code -- is clean.
wont_generalize got the same treatment. It keyed on the ___stackN name Dynamo
gives a value crossing a graph break, which both misses and overcounts: a
non-tensor argument is equality-pinned with no ___stackN name, while a tensor
crossing a break gets a ___stackN source under TENSOR_MATCH and generalizes
fine. It now requires a value-equality guard type AND a bare source name, so
model config reached through an argument -- a LayerNorm's eps, a Dropout's p --
does not flag every model. Both CONSTANT_MATCH and EQUALS_MATCH count, since
which one Dynamo emits depends on the value's type rather than on whether it
pins anything. A constant inside a container argument is guarded on a
subscripted source and is still missed; kept_guards is the authoritative list.
The intended deployment is capture on one machine and serve on another, so the
in-process concerns above matter less than divergence between the two, and the
cross-machine rails were checked end to end rather than argued. The source
checksum finds the module by name rather than by path, so an artifact moves
between differently laid out checkouts but still refuses to load against
drifted source, and SystemInfo rejects Python, PyTorch, CUDA, Triton and GPU
skew at load. It does not check the CPU vector ISA -- inductor bakes the
vector width into generated CPU code, so an AVX-512 capture served on an AVX2
host can produce wrong numbers with no error -- and the module docstring
records that along with the rest of the operational limits: capture under
no_grad, expect value-pinned artifacts from data-dependent breaks, identity
guards are not recoverable, the model must be importable, install() patches
code objects process-globally, a second artifact for one class silently
substitutes the survivor's graph for the evicted one, and a plain
torch.compile in a module that has an artifact loaded can hit a
__builtins_dict__ name collision until the artifact is unloaded. That last one
is disclosed rather than fixed: the real fix is not minting the name off a
process-local counter, which is output_graph's call, and rewriting the name at
load time would mean rewriting source trees inside serialized guard state,
where a mistake is a guard that silently stops discriminating.
A confirmation round added three corrections, all found by writing the test
rather than by reading. Dynamo's own synthesized resume locals,
__nested_resume_fns and __nested_frame_values, were being reported as risky
drops: they name generated code rather than a slot config chooses, so an
identity guard lost on one cannot diverge, and flagging them would refuse
models whose resume functions nest. The check keys on the scope-stripped guard
name, since that is the form the reporting path already normalizes to.
The other two are disclosure. _is_library_module trusts the OWNER of a value,
not the binding, so a third party that rebinds a torch or stdlib attribute at
import -- F.gelu = _fast_gelu from a package installed only on the serving host
-- is waived even though the model reads F.gelu unconditionally, and
functools.wraps reaches the same waiver by copying __name__ and __module__ off
the function it wraps. That is now a third KNOWN GAP bullet rather than being
implied by the two conditional-bind ones.
And the shared-frame paragraph was wrong in the direction that matters. Two
artifacts for one class do collide, on the entry frame, and evict each other
with a warning. Two artifacts for different models that merely share an inner
frame -- two models containing the same library block -- were assumed to
collide too, and measurably do not: entries accumulate on the shared code
object and the guards pick the right one. Both serve correctly, which
test_two_artifacts_sharing_an_inner_frame_both_serve now pins. That holds only
while the guards can tell the models apart, so the paragraph now says what
happens when require_no_risky_drops=False removes the discriminating guard:
the first matching entry wins, one model is served the other's graph, and
nothing warns because the eviction warning covers entry frames only.
Test Plan:
New tests in test/dynamo/test_package.py, in TestPrecompilePackage. Coverage:
a round trip across two graph breaks and three specializations on both
backends; guards on a global dict read on both sides of a break, a dict passed
as an argument, and nested dict membership and key-set iteration, asserting
positively that those guards were kept rather than merely absent from the
dropped list; the save() refusals, each with the acknowledging flag exercised
-- a truncated capture (and that the variants it did capture still serve), a
capture that ran nothing, an entry frame with no compiled code, and a risky
dropped identity guard; the risky-drop corpus, nineteen shapes that must be
flagged and nine that must not, each parametrized, plus the individual cases
that pin one clause of the predicate apiece -- a builtin read through the
builtins dict versus a builtin in an attribute versus a user table shaped like
the builtins dict, torch.nn.functional.gelu spelled out in full, a submodule
of a self-named package, and four library spellings that only the ownership
test can clear; the value-pinning report -- a plain int argument, a dict_keys
argument that arrives as EQUALS_MATCH rather than CONSTANT_MATCH, both the
stack slot and the resume frame's local from an .item(), a tensor crossing a
break that must not count, and LayerNorm/Dropout/attribute config constants
that must not count; artifact identity at load -- a different callable, a
same-named class from another module, a different definition of the same name
in one module, a functools.wraps wrapper sharing the qualname, an artifact
with no code entries at all, a module whose forward has no __code__, a
__code__ present but None, and a checkout at a different absolute path that
must still load; the process-global state -- unload clearing resume-function
entries, restoring a skipped frame, keeping a skip another package still
holds, keeping globals a bystander compile needs, removing the builtins key
install() added, leaving alone a global a later package rebound while still
leaving the namespace empty once both packages have unloaded, a failed install
leaving nothing installed, and resume names from two separate captures not
colliding; eviction -- the second artifact for a shared frame warning before
it evicts the first, that the warning says the substitution is silent, and
that it warns exactly once and not when there is nothing left to evict;
device_type surviving a cpu graph, a load and re-save, and a failed load; and
the cross-machine refusals, drifted source and version skew.
```
python test/dynamo/test_package.py TestPrecompilePackage
```
Regressions:
```
python test/dynamo/test_package.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_recompiles.py
python test/dynamo/test_precompile_context.py
python test/dynamo/test_guard_serialization.py
```
test_package 152 OK (23 skipped, 1 expected failure), test_recompiles 18 OK,
test_precompile_context 3 OK, test_guard_serialization 60 OK.
test_aot_compile runs 49 with 3 pre-existing errors
(test_aot_compile_with_aoti*) from a local environment gap where AOTI's
generated header cannot find cuda.h; they fail identically on a clean tree.
The predicate and the uninstall change were each checked by reverting them
under the new tests, which is how the corpus earns its keep:
```
# restore the "any read off a trusted namespace is fine" waiver
python test/dynamo/test_package.py -k risky_drop_corpus
# -> 4 failures: module_level_global, package_reexport,
# sibling_module, dispatch_in_inlined_helper
# restore "any builtins-owned value is fine"
python test/dynamo/test_package.py TestPrecompilePackage
# -> 3 failures: attribute_builtin_fn, owner_builtin,
# a_builtin_shaped_read_that_is_still_a_slot_is_risky
# let a submodule inherit its parent's trust unconditionally
python test/dynamo/test_package.py TestPrecompilePackage
# -> 1 failure: package_submodule_alias
# restore uninstall()'s put-back-what-we-displaced loop
python test/dynamo/test_package.py TestPrecompilePackage
# -> 1 failure: test_unload_leaves_a_global_a_later_package_rebound
```
Scale was checked out of tree at the target size, 50 graph breaks on the eager
backend, in both layouts -- one function breaking 50 times and specializing 3
ways, and 50 ModuleList instances whose 50 variants all pile onto one shared
frame:
```
50 breaks in one function : 51 frames, 151 guarded codes,
5.9s capture, 0.9 MB, 0.36s load
50 instances sharing one frame : 3 frames, 51 guarded codes,
2.2s capture, 0.4 MB, 0.13s load
```
Both replay every captured variant under fail_on_recompile with zero
recompiles and reject an uncovered input. Neither reports a risky drop. The
first saves with every rail on; the second is refused until
require_complete=False, because the loop over the ModuleList compiles nothing
of its own and lands in uncovered_frames, which is the case that refusal is
written for. Guard dispatch is a linear scan over one frame's guarded codes,
so the shared-frame layout costs 2.4 ms per call against 0.85 ms for the
distinct-frame layout. That is a property of the existing dispatch path, not
something this change introduces.
Authored with an AI assistant.
ghstack-source-id: 4fea838
Pull-Request: #192379
bobrenjc93
added a commit
that referenced
this pull request
Aug 8, 2026
…piles
aot_compile produces exactly one graph and rejects graph breaks, so a model
that breaks 50 times and specializes 3 ways per frame cannot be precompiled at
all today. CompilePackage already captures every frame Dynamo produces --
entry, resume continuations, and each recompiled variant -- but it is a low
level component with no API, and assembling it by hand is unsafe in several
ways this change fixes. The theme throughout is that every failure mode here
is silent by construction: an artifact that is missing coverage, missing a
guard, or installed next to another artifact does not raise, it serves the
wrong graph.
Review the three pieces in this order.
First, convert_frame, which is the smallest: when a frame exceeds
recompile_limit it is pinned to RUN_ONLY, so every variant past the limit is
never captured, and the package was not told. It now records the frame as
truncated. This is deliberately NOT a bypass: install() treats a bypassed
entry as "serve nothing", so marking these frames bypassed would throw away
the variants that were captured successfully and make coverage strictly worse
for existing caching_precompile users, who would rather serve eight variants
and recompile for the rest. The truncation set is runtime-only and is not
serialized, both because it describes a capture session rather than an
artifact and because a persisted flag would poison a DynamoCache entry
permanently -- nothing resets it, and raising the limit on a later run would
not recover. It is also a lower bound rather than a list: RUN_ONLY is
recursive, so frames called beneath the offender stop capturing without ever
re-entering Dynamo to report it, and the summary and the save() refusal both
say so.
Second, package.py, which is where the process-global state lives. uninstall()
only cleared precompile entries for the entry code object, leaving them
installed on every resume function and on any frame reached through
code_source, so loading an artifact mutated global state that neither
uninstall() nor torch._dynamo.reset() could undo. install() now records the
code objects it touches and the frames it skip_code()s, and takes both back --
with a skip revoked only by the last package holding it, since the strategy a
frame had before install() skipped it cannot be read back. A global install()
wrote is removed only while it is still bound to the value install() put
there; one that something else has rebound since belongs to that writer, and
popping it would leave live consumers with a NameError, because the namespace
is shared with plain torch.compile. It deliberately does not put back what it
displaced: the only writer that ever displaces one of these names is a second
package installing the same artifact, whose load already orphaned the first
package's value, so restoring it on the later unload leaves a compiled backend
bound in the module for the life of the process -- one set per load cycle,
which is exactly the shape a serving process that reloads models has. The
generated builtins-dict global is recorded too, since its name carries the
capture process's counter and leaving it behind makes the first local compile
that mints the same name die in CleanupHook.create; import aliases are
deliberately not recorded, because every writer of an alias writes the same
module object and plain torch.compile installs it permanently. install() also
rolls itself back if it raises, because a half-installed package serves some
frames and not others with no handle left to undo it.
Two more things in that file are about several artifacts coexisting, which is
the serving-process shape. Resume functions are bound under
__resume_at_<offset>_<n>, from a counter that restarts in every capture
process, so two artifacts captured separately both claim __resume_at_16_3; a
serving process installs both into one module dict, the second write wins, and
the first model silently runs the second's continuation -- right shape, wrong
numbers. They are now installed under a name suffixed with a digest of the
code they name, with co_names rewritten so the dynamo bytecode follows the
renamed binding. And because precompile entries can only be cleared en masse,
uninstall() warns when another live package installed on the same code object
rather than clearing its entries silently. The warning says what actually
happens next, which is not what the first version of it claimed: the evicted
package's callers do not simply recompile, they fall through to whatever
entries remain, and a surviving package whose guards accept the call serves it
that package's graph with no error at all. That is the normal case rather than
a corner, because the guard that would have told two instances apart is
usually an identity guard precompile had to drop. It warns rather than
refuses: the first version raised, which deadlocked two packages sharing a
frame since neither could go first, and left globals already deleted behind.
The registry holds weak references so a package dropped without unloading does
not block a later one, covers the entry code object -- __init__ calls
uninstall() before this package has installed anything, which is exactly the
second-artifact path -- and stays quiet when there is nothing left to take.
The device_type field belongs to the same file and is easy to miss. It is one
string per package and it gates every GPU check in
SystemInfo.check_compatibility, while a package now holds many graphs, so the
cpu epilogue after an .item() break used to erase the "cuda" an earlier graph
recorded. It only widens cpu -> accelerator now, is restored from the artifact
on load rather than recomputed from whatever this process happens to
recompile, and is reset when a package is re-initialized: a failed load is
retried on the same object, and because the field only widens, a value the
failed load left behind could never be corrected and would be re-saved as the
next capture's.
Third, precompile_package.py: the API. precompile_capture yields the callable
to exercise, save() refuses to write an artifact that cannot serve what it
claims, precompile_load does the order-sensitive attach-then-install in one
call and returns something that can be unloaded, serving() forbids compilation
so an uncovered call raises instead of quietly recompiling, and
recompile_limit defaults to 256 because a precompile deliberately wants one
variant per condition whereas the usual limit of 8 exists to catch runaway
recompilation. Capture remains by execution -- a resume function only exists
once the frame ahead of it has run -- so callers must exercise every path they
want covered, and summary() exposes the counts, the truncated, bypassed and
uncovered frames, the value-pinned sources, and the kept and dropped guards
with their sources, so a build step can assert coverage instead of discovering
gaps in production. An entry frame with no compiled code counts against
completeness rather than only warning, because install() skip_code()s such a
frame, so the model runs eager and, a skipped frame never compiling, serving()
cannot report the gap; that is legitimate for a frame that only dispatches to
submodules, so the error says so and require_complete=False accepts it. A
forward-only capture with grad enabled records no backends at all -- with
inductor and parameters that require grad, AOTAutograd only registers the
bundled artifact once the backward compiles -- which surfaced as a
RuntimeError naming an internal symbol and is now a PackageError saying to
capture under no_grad.
precompile_load also validates that the artifact was captured from the
callable it is being loaded onto. CompilePackage.initialize rebinds stored
guards and bytecode onto whatever function it is given, and the source
checksum only covers the captured function, so loading f's artifact onto g
otherwise returns f's results with no error. Identity is (defining module,
qualname, co_name, first line). co_filename is deliberately excluded: the
capture and serving machines check out to different absolute paths, and the
module name already carries what the path would say. The first line is what
separates two definitions of one name in one module -- the class under an `if`
that a config flag picks -- which agrees on every other field and which the
source checksum passes, since both branches sit in the line range it hashes.
The guard filter deserves the most attention, because it is the part that has
been wrong the most times. The set of guards Dynamo cannot serialize is
exactly the IDENTITY guards -- ID_MATCH, FUNCTION_MATCH, CLOSURE_MATCH,
MODULE_MATCH and friends -- so precompiling inherently gives up on noticing
that a guarded object was rebound to a different object of the same shape.
Keeping them is not an option, since serialization then fails for essentially
every function; dropping them silently is how you serve a graph traced against
the old value. So every drop is recorded with its source name, and save()
refuses by default when a drop looks load-bearing.
Four versions of that predicate have now been written, and each of the first
three passed its own tests while failing open on a shape nobody had thought
of. Matching the guard SOURCE against a bare-global pattern cannot work at
all: guard names have their local scope stripped, so a guard on self.act
arrives as "self.act" and is indistinguishable from a global. Classifying by
who OWNS the value waves through `self.act = getattr(F, cfg.activation)`,
because F.gelu is torch-owned, and that is the exact divergence the check
exists for. Intersecting the two fixed those but trusted anything read off a
module namespace it had decided was trustworthy, which laundered every
module-level dispatch there is -- `cconf.ACT`, `dispatch.op`, a re-export
through a package __init__, a dispatch inside an inlined helper -- and it
handed a submodule its parent's trust without looking at the name, so
`from . import impl_b as impl` in a package __init__ made `mypkg.impl.op`
benign. What ships is the intersection with both of those holes closed: the
binding SITE, read off the structured Source that survives the name stripping,
decides what can be repointed without a source edit, and who OWNS the value
decides whether the thing at that site has plug points at all -- but trusting
a namespace is no longer trusting everything read off it. A read off a
namespace clears only when torch or the stdlib owns the namespace, or the
namespace owns the value being read. A submodule is trusted only under a name
its parent already owns, its own __name__ or the parent's plus the attribute.
And the builtins exemption was narrowed the same way: `len` reached through
Dynamo's builtins dict clears, while `self.act = abs` -- a builtin out of an
ACT2FN-style table -- does not, because the value being unrepointable says
nothing about the slot holding it.
Given that history, the shapes live in a table in the test file rather than in
prose. _RISKY_DROP_CORPUS has nineteen entries that must always be flagged and
_BENIGN_DROP_CORPUS has nine that must never be, and the two are paired so
that widening the predicate cannot satisfy both: `cpkg.impl.op` against
`cpkg.cimpl.op`, `cconf.ACT` against `cown.call`, `import math as alias`
against a user module under an alias. Both run as parametrized tests, one per
shape.
What it still does NOT catch is worth stating plainly, because the refusal is
on by default and users will read it as a guarantee. Every waiver judges the
object capture happened to bind, not the statement that bound it, so any name
bound conditionally is waived whenever the branch taken on the capture machine
is one of the waived shapes. This is not specific to one arm. On the def-name
arm, `if HAVE_FAST: from fastops import gelu` / `else: from
torch.nn.functional import gelu`, captured without the flag, drops G['gelu'],
reports nothing, saves clean, and returns torch's gelu on a machine that has
fastops. On the namespace-owns-the-value arm, a module that binds a name under
an `if` and is read through an ordinary `import mod` elsewhere is waived too,
because at capture time that module genuinely does own whichever def the
branch produced -- and there the reading file binds nothing conditionally, so
it looks covered and is not. Both were reproduced end to end, not reasoned
about. An allow_in_graph callable passes as well. Nothing at capture time
distinguishes a conditional bind from an unconditional one, only the resulting
object is visible, so this is a limit of the approach rather than a missing
check. dropped_guards remains the authoritative list; this predicate is a lint
over it.
The cost of the strictness is one real refusal in stock torch, and it is
deliberate. Sweeping 23 stock nn layers flags exactly two,
TransformerEncoderLayer and TransformerEncoder, both on the same slot: the
activation is a constructor keyword parked in an attribute, which is torch's
own spelling of `self.act = getattr(F, cfg.activation)`. Capturing one with
activation="relu" and serving it with activation="gelu" loads clean and
returns the relu answer, so it is a true positive, and exempting it would need
a "library-owned callable in a library-owned nn.Module attribute" rule that
reintroduces exactly that wrong answer. Transformer users pass
require_no_risky_drops=False once. Everything else in the sweep -- Conv/BN,
LSTM/GRU/RNN, MultiheadAttention, Sequential, LayerNorm, Embedding, pooling,
builtins-heavy code -- is clean.
wont_generalize got the same treatment. It keyed on the ___stackN name Dynamo
gives a value crossing a graph break, which both misses and overcounts: a
non-tensor argument is equality-pinned with no ___stackN name, while a tensor
crossing a break gets a ___stackN source under TENSOR_MATCH and generalizes
fine. It now requires a value-equality guard type AND a bare source name, so
model config reached through an argument -- a LayerNorm's eps, a Dropout's p --
does not flag every model. Both CONSTANT_MATCH and EQUALS_MATCH count, since
which one Dynamo emits depends on the value's type rather than on whether it
pins anything. A constant inside a container argument is guarded on a
subscripted source and is still missed; kept_guards is the authoritative list.
The intended deployment is capture on one machine and serve on another, so the
in-process concerns above matter less than divergence between the two, and the
cross-machine rails were checked end to end rather than argued. The source
checksum finds the module by name rather than by path, so an artifact moves
between differently laid out checkouts but still refuses to load against
drifted source, and SystemInfo rejects Python, PyTorch, CUDA, Triton and GPU
skew at load. It does not check the CPU vector ISA -- inductor bakes the
vector width into generated CPU code, so an AVX-512 capture served on an AVX2
host can produce wrong numbers with no error -- and the module docstring
records that along with the rest of the operational limits: capture under
no_grad, expect value-pinned artifacts from data-dependent breaks, identity
guards are not recoverable, the model must be importable, install() patches
code objects process-globally, a second artifact for one class silently
substitutes the survivor's graph for the evicted one, and a plain
torch.compile in a module that has an artifact loaded can hit a
__builtins_dict__ name collision until the artifact is unloaded. That last one
is disclosed rather than fixed: the real fix is not minting the name off a
process-local counter, which is output_graph's call, and rewriting the name at
load time would mean rewriting source trees inside serialized guard state,
where a mistake is a guard that silently stops discriminating.
A confirmation round added three corrections, all found by writing the test
rather than by reading. Dynamo's own synthesized resume locals,
__nested_resume_fns and __nested_frame_values, were being reported as risky
drops: they name generated code rather than a slot config chooses, so an
identity guard lost on one cannot diverge, and flagging them would refuse
models whose resume functions nest. The check keys on the scope-stripped guard
name, since that is the form the reporting path already normalizes to.
The other two are disclosure. _is_library_module trusts the OWNER of a value,
not the binding, so a third party that rebinds a torch or stdlib attribute at
import -- F.gelu = _fast_gelu from a package installed only on the serving host
-- is waived even though the model reads F.gelu unconditionally, and
functools.wraps reaches the same waiver by copying __name__ and __module__ off
the function it wraps. That is now a third KNOWN GAP bullet rather than being
implied by the two conditional-bind ones.
And the shared-frame paragraph was wrong in the direction that matters. Two
artifacts for one class do collide, on the entry frame, and evict each other
with a warning. Two artifacts for different models that merely share an inner
frame -- two models containing the same library block -- were assumed to
collide too, and measurably do not: entries accumulate on the shared code
object and the guards pick the right one. Both serve correctly, which
test_two_artifacts_sharing_an_inner_frame_both_serve now pins. That holds only
while the guards can tell the models apart, so the paragraph now says what
happens when require_no_risky_drops=False removes the discriminating guard:
the first matching entry wins, one model is served the other's graph, and
nothing warns because the eviction warning covers entry frames only.
Validating against real OSS models rather than synthetic fixtures changed three
things, and is the reason the risky-drop lint no longer refuses by default.
Two capture-blocking bugs surfaced immediately. SourceInfo.add_code trusted
inspect.getmodule to name the module a code object came from, but that returns
whichever module re-exports it -- collections.abc is three lines of "from
_collections_abc import *" -- so hashing the code's line range read lines that
module does not have, and any model inlining through collections.abc, which
transformers does, failed capture outright with "Source mismatch". It now
resolves the module whose file actually holds the code, and records the
sys.modules KEY rather than __name__, because _collections_abc sets its own
__name__ to "collections.abc" and load-time revalidation re-imports that name
to the wrong object. Separately, _module_namespaces only recognised a namespace
if some guard entry happened to hold the module, and Dynamo guards the
attributes it reads off an import alias but never the bare alias, so a real
model produced G['__import_torch'].Tensor with nothing anchoring it and
torch.Tensor was reported as a config-swappable slot. The alias name encodes
its module, so it is decoded instead.
The measurements those unblocked are why the lint is now advisory. On stock
models: torchvision resnet18 and mobilenet_v3 report no risky drops and save
with every default on; timm's ViT reports one, a re-exported torch._assert;
transformers' Qwen2 reports 33, nearly all library internals -- output
dataclasses, deprecation enum members, decorator closure cells -- with only the
attention-implementation registry looking genuinely config-selected. A default
that refuses stock ViT teaches users to pass require_no_risky_drops=False
unconditionally, which removes the true positives along with the noise, so the
default reports and enforcement is opt-in once you have audited your model.
That is the outcome the predicate's own history argues for: it failed open
three times while being tuned for precision, and precision is not reachable
from capture-time values alone.
The same exercise found a blocker this stack cannot fix. A transformers model
captures and saves but does not load: building guards dies with AttributeError
'_Missing' object has no attribute '__defaults__', because a SEQUENCE_LENGTH
guard on a function's __defaults__ outlives the dropped identity guard on the
function, which is then absent from the reloaded scope. Plain
torch._dynamo.config.caching_precompile reproduces it on the same model, so it
belongs to guard serialization rather than here; it is disclosed in the module
docstring instead of being papered over. Vision models round trip end to end:
captured and served in separate processes, outputs match eager, and an
instrumented convert_frame._compile counts zero compilations while serving.
Test Plan:
New tests in test/dynamo/test_package.py, in TestPrecompilePackage. Coverage:
a round trip across two graph breaks and three specializations on both
backends; guards on a global dict read on both sides of a break, a dict passed
as an argument, and nested dict membership and key-set iteration, asserting
positively that those guards were kept rather than merely absent from the
dropped list; the save() refusals, each with the acknowledging flag exercised
-- a truncated capture (and that the variants it did capture still serve), a
capture that ran nothing, an entry frame with no compiled code, and a risky
dropped identity guard; the risky-drop corpus, nineteen shapes that must be
flagged and nine that must not, each parametrized, plus the individual cases
that pin one clause of the predicate apiece -- a builtin read through the
builtins dict versus a builtin in an attribute versus a user table shaped like
the builtins dict, torch.nn.functional.gelu spelled out in full, a submodule
of a self-named package, and four library spellings that only the ownership
test can clear; the value-pinning report -- a plain int argument, a dict_keys
argument that arrives as EQUALS_MATCH rather than CONSTANT_MATCH, both the
stack slot and the resume frame's local from an .item(), a tensor crossing a
break that must not count, and LayerNorm/Dropout/attribute config constants
that must not count; artifact identity at load -- a different callable, a
same-named class from another module, a different definition of the same name
in one module, a functools.wraps wrapper sharing the qualname, an artifact
with no code entries at all, a module whose forward has no __code__, a
__code__ present but None, and a checkout at a different absolute path that
must still load; the process-global state -- unload clearing resume-function
entries, restoring a skipped frame, keeping a skip another package still
holds, keeping globals a bystander compile needs, removing the builtins key
install() added, leaving alone a global a later package rebound while still
leaving the namespace empty once both packages have unloaded, a failed install
leaving nothing installed, and resume names from two separate captures not
colliding; eviction -- the second artifact for a shared frame warning before
it evicts the first, that the warning says the substitution is silent, and
that it warns exactly once and not when there is nothing left to evict;
device_type surviving a cpu graph, a load and re-save, and a failed load; and
the cross-machine refusals, drifted source and version skew.
```
python test/dynamo/test_package.py TestPrecompilePackage
```
Regressions:
```
python test/dynamo/test_package.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_recompiles.py
python test/dynamo/test_precompile_context.py
python test/dynamo/test_guard_serialization.py
```
test_package 152 OK (23 skipped, 1 expected failure), test_recompiles 18 OK,
test_precompile_context 3 OK, test_guard_serialization 60 OK.
test_aot_compile runs 49 with 3 pre-existing errors
(test_aot_compile_with_aoti*) from a local environment gap where AOTI's
generated header cannot find cuda.h; they fail identically on a clean tree.
The predicate and the uninstall change were each checked by reverting them
under the new tests, which is how the corpus earns its keep:
```
# restore the "any read off a trusted namespace is fine" waiver
python test/dynamo/test_package.py -k risky_drop_corpus
# -> 4 failures: module_level_global, package_reexport,
# sibling_module, dispatch_in_inlined_helper
# restore "any builtins-owned value is fine"
python test/dynamo/test_package.py TestPrecompilePackage
# -> 3 failures: attribute_builtin_fn, owner_builtin,
# a_builtin_shaped_read_that_is_still_a_slot_is_risky
# let a submodule inherit its parent's trust unconditionally
python test/dynamo/test_package.py TestPrecompilePackage
# -> 1 failure: package_submodule_alias
# restore uninstall()'s put-back-what-we-displaced loop
python test/dynamo/test_package.py TestPrecompilePackage
# -> 1 failure: test_unload_leaves_a_global_a_later_package_rebound
```
Scale was checked out of tree at the target size, 50 graph breaks on the eager
backend, in both layouts -- one function breaking 50 times and specializing 3
ways, and 50 ModuleList instances whose 50 variants all pile onto one shared
frame:
```
50 breaks in one function : 51 frames, 151 guarded codes,
5.9s capture, 0.9 MB, 0.36s load
50 instances sharing one frame : 3 frames, 51 guarded codes,
2.2s capture, 0.4 MB, 0.13s load
```
Both replay every captured variant under fail_on_recompile with zero
recompiles and reject an uncovered input. Neither reports a risky drop. The
first saves with every rail on; the second is refused until
require_complete=False, because the loop over the ModuleList compiles nothing
of its own and lands in uncovered_frames, which is the case that refusal is
written for. Guard dispatch is a linear scan over one frame's guarded codes,
so the shared-frame layout costs 2.4 ms per call against 0.85 ms for the
distinct-frame layout. That is a property of the existing dispatch path, not
something this change introduces.
Authored with an AI assistant.
ghstack-source-id: c550d0d
Pull-Request: #192379
bobrenjc93
added a commit
that referenced
this pull request
Aug 9, 2026
…piles
aot_compile produces exactly one graph and rejects graph breaks, so a model
that breaks 50 times and specializes 3 ways per frame cannot be precompiled at
all today. CompilePackage already captures every frame Dynamo produces --
entry, resume continuations, and each recompiled variant -- but it is a low
level component with no API, and assembling it by hand is unsafe in several
ways this change fixes. The theme throughout is that every failure mode here
is silent by construction: an artifact that is missing coverage, missing a
guard, or installed next to another artifact does not raise, it serves the
wrong graph.
Review the four pieces in this order.
First, convert_frame, which is the smallest: when a frame exceeds
recompile_limit it is pinned to RUN_ONLY, so every variant past the limit is
never captured, and the package was not told. It now records the frame as
truncated, and logs a dynamo_cache_truncated structured-trace artifact so the
gap is visible in a tlparse of a production capture. This is deliberately NOT
a bypass: install() treats a bypassed entry as "serve nothing", so marking
these frames bypassed would throw away the variants that were captured
successfully and make coverage strictly worse for existing caching_precompile
users, who would rather serve eight variants and recompile for the rest. The
truncation set is runtime-only and is not serialized, both because it
describes a capture session rather than an artifact and because a persisted
flag would poison a DynamoCache entry permanently -- nothing resets it, and
raising the limit on a later run would not recover. It is also a lower bound
rather than a list: RUN_ONLY is recursive, so frames called beneath the
offender stop capturing without ever re-entering Dynamo to report it, and the
summary and the save() refusal both say so.
Second, package.py, which is where the process-global state lives. uninstall()
only cleared precompile entries for the entry code object, leaving them
installed on every resume function and on any frame reached through
code_source, so unloading a package left it half-installed with no handle to
finish the job. A process-wide torch._dynamo.reset() did clear those entries,
since install() adds every target code object to convert_frame.input_codes,
but reset() does not remove the globals install() wrote into the module
namespace at all, so even the big hammer left the package half-uninstalled.
install() now records the code objects it touches and the frames it
skip_code()s, and takes both back -- with a skip revoked only by the last
package holding it, since the strategy a frame had before install() skipped it
cannot be read back. A global install() wrote is removed only while it is
still bound to the value install() put there; one that something else has
rebound since belongs to that writer, and popping it would leave live
consumers with a NameError, because the namespace is shared with plain
torch.compile. It deliberately does not put back what it displaced: the only
writer that ever displaces one of these names is a second package installing
the same artifact, whose load already orphaned the first package's value, so
restoring it on the later unload leaves a compiled backend bound in the module
for the life of the process -- one set per load cycle, which is exactly the
shape a serving process that reloads models has. The generated builtins-dict
global is recorded too, since its name carries the capture process's counter
and leaving it behind makes the first local compile that mints the same name
die in CleanupHook.create; import aliases are deliberately not recorded,
because every writer of an alias writes the same module object and plain
torch.compile installs it permanently. install() also rolls itself back if it
raises, because a half-installed package serves some frames and not others
with no handle left to undo it.
Two more things in that file are about several artifacts coexisting, which is
the serving-process shape. Resume functions are bound under
__resume_at_<offset>_<n>, from a counter that restarts in every capture
process, so two artifacts captured separately both claim __resume_at_16_3; a
serving process installs both into one module dict, the second write wins, and
the first model silently runs the second's continuation -- right shape, wrong
numbers. They are now installed under a name suffixed with a digest of the
code they name, with co_names rewritten so the dynamo bytecode follows the
renamed binding. And because precompile entries can only be cleared en masse,
uninstall() warns when another live package installed on the same code object
rather than clearing its entries silently. The warning says what actually
happens next, which is not what the first version of it claimed: the evicted
package's callers do not simply recompile, they fall through to whatever
entries remain, and a surviving package whose guards accept the call serves it
that package's graph with no error at all. That is the normal case rather than
a corner, because the guard that would have told two instances apart is
usually an identity guard precompile had to drop. It warns rather than
refuses: the first version raised, which deadlocked two packages sharing a
frame since neither could go first, and left globals already deleted behind.
The registry holds weak references so a package dropped without unloading does
not block a later one, covers the entry code object -- __init__ calls
uninstall() before this package has installed anything, which is exactly the
second-artifact path -- and stays quiet when there is nothing left to take.
The device_type field belongs to the same file and is easy to miss. It is one
string per package and it gates every GPU check in
SystemInfo.check_compatibility, while a package now holds many graphs, so the
cpu epilogue after an .item() break used to erase the "cuda" an earlier graph
recorded. It only widens cpu -> accelerator now, is restored from the artifact
on load rather than recomputed from whatever this process happens to
recompile, and is reset when a package is re-initialized: a failed load is
retried on the same object, and because the field only widens, a value the
failed load left behind could never be corrected and would be re-saved as the
next capture's.
Third, precompile_package.py: the API. precompile_capture yields the callable
to exercise, save() refuses to write an artifact that cannot serve what it
claims, precompile_load does the order-sensitive attach-then-install in one
call and returns something that can be unloaded, serving() forbids compilation
so an uncovered call raises instead of quietly recompiling, and
recompile_limit defaults to 256 because a precompile deliberately wants one
variant per condition whereas Dynamo's usual limit of 8 exists to catch
runaway recompilation. Capture remains by execution -- a resume function only
exists once the frame ahead of it has run -- so callers must exercise every
path they want covered, and summary() exposes the counts, the truncated,
bypassed and uncovered frames, the value-pinned sources, and the kept and
dropped guards with their sources, so a build step can assert coverage instead
of discovering gaps in production. An entry frame with no compiled code counts
against completeness rather than only warning, because install() skip_code()s
such a frame, so the model runs eager and, a skipped frame never compiling,
serving() cannot report the gap; that is legitimate for a frame that only
dispatches to submodules, so the error says so and require_complete=False
accepts it. A forward-only capture with grad enabled records no backends at
all -- with inductor and parameters that require grad, AOTAutograd only
registers the bundled artifact once the backward compiles -- which surfaced as
a RuntimeError naming an internal symbol and is now a PackageError saying to
capture under no_grad.
save() ends up with three rails carrying two dispositions, and they are
deliberately not symmetric. require_complete is on and gates exactly
PrecompileSummary.complete; the two guard rails are orthogonal to it, because
a dropped guard is a wrong answer rather than a gap in coverage, and both are
off. The risky-drop lint in particular REPORTS through log.warning and
enforcement is opt-in -- see the guard-filter discussion below for why -- so
the report is the whole default safety surface and has to be readable: it
prints at most eight names, and because the sort is by guard type rather than
by severity, a truncated report now says how many it cut and where the rest
are. Report and enforcement are one if/elif over one predicate rather than two
ifs over complementary halves of it, so a save cannot both warn and raise.
precompile_load also validates that the artifact was captured from the
callable it is being loaded onto. CompilePackage.initialize rebinds stored
guards and bytecode onto whatever function it is given, and the source
checksum only covers the captured function, so loading f's artifact onto g
otherwise returns f's results with no error. Identity is (defining module,
qualname, co_name, first line). co_filename is deliberately excluded: the
capture and serving machines check out to different absolute paths, and the
module name already carries what the path would say. The first line is what
separates two definitions of one name in one module -- the class under an `if`
that a config flag picks -- which agrees on every other field and which the
source checksum passes, since both branches sit in the line range it hashes.
The guard filter deserves the most attention, because it is the part that has
been wrong the most times. The set of guards Dynamo cannot serialize is
exactly the IDENTITY guards -- ID_MATCH, FUNCTION_MATCH, CLOSURE_MATCH,
MODULE_MATCH and friends -- so precompiling inherently gives up on noticing
that a guarded object was rebound to a different object of the same shape.
Keeping them is not an option, since serialization then fails for essentially
every function; dropping them silently is how you serve a graph traced against
the old value. So every drop is recorded with its source name, and save()
reports the ones that look load-bearing.
Four versions of that predicate have now been written, and each of the first
three passed its own tests while failing open on a shape nobody had thought
of. Matching the guard SOURCE against a bare-global pattern cannot work at
all: guard names have their local scope stripped, so a guard on self.act
arrives as "self.act" and is indistinguishable from a global. Classifying by
who OWNS the value waves through `self.act = getattr(F, cfg.activation)`,
because F.gelu is torch-owned, and that is the exact divergence the check
exists for. Intersecting the two fixed those but trusted anything read off a
module namespace it had decided was trustworthy, which laundered every
module-level dispatch there is -- `cconf.ACT`, `dispatch.op`, a re-export
through a package __init__, a dispatch inside an inlined helper -- and it
handed a submodule its parent's trust without looking at the name, so
`from . import impl_b as impl` in a package __init__ made `mypkg.impl.op`
benign. What ships is the intersection with both of those holes closed: the
binding SITE, read off the structured Source that survives the name stripping,
decides what can be repointed without a source edit, and who OWNS the value
decides whether the thing at that site has plug points at all -- but trusting
a namespace is no longer trusting everything read off it. A read off a
namespace clears only when torch or the stdlib owns the namespace, or the
namespace owns the value being read. A submodule is trusted only under a name
its parent already owns, its own __name__ or the parent's plus the attribute.
And the builtins exemption was narrowed the same way: `len` reached through
Dynamo's builtins dict clears, while `self.act = abs` -- a builtin out of an
ACT2FN-style table -- does not, because the value being unrepointable says
nothing about the slot holding it.
Given that history, the shapes live in a table in the test file rather than in
prose. _RISKY_DROP_CORPUS has nineteen entries that must always be flagged and
_BENIGN_DROP_CORPUS has nine that must never be, and the two are paired so
that widening the predicate cannot satisfy both: `cpkg.impl.op` against
`cpkg.cimpl.op`, `cconf.ACT` against `cown.call`, `import math as alias`
against a user module under an alias. Both run as parametrized tests, one per
shape.
What it still does NOT catch is worth stating plainly, because users will read
the report as a guarantee. Every waiver judges the object capture happened to
bind, not the statement that bound it, so any name bound conditionally is
waived whenever the branch taken on the capture machine is one of the waived
shapes. This is not specific to one arm. On the def-name arm, `if HAVE_FAST:
from fastops import gelu` / `else: from torch.nn.functional import gelu`,
captured without the flag, drops G['gelu'], reports nothing, saves clean, and
returns torch's gelu on a machine that has fastops. On the
namespace-owns-the-value arm, a module that binds a name under an `if` and is
read through an ordinary `import mod` elsewhere is waived too, because at
capture time that module genuinely does own whichever def the branch produced
-- and there the reading file binds nothing conditionally, so it looks covered
and is not. Both were reproduced end to end, not reasoned about. An
allow_in_graph callable passes as well. And the library-namespace arm needs no
conditional at all: the waiver trusts the OWNER of a value rather than the
binding, so a third party that rebinds a torch or stdlib attribute at import --
F.gelu = _fast_gelu from a package installed only on the serving host -- is
waived even though the model reads F.gelu unconditionally, and functools.wraps
reaches the same waiver by copying __name__ and __module__ off the function it
wraps. Nothing at capture time distinguishes a conditional bind from an
unconditional one, only the resulting object is visible, so this is a limit of
the approach rather than a missing check. dropped_guards remains the
authoritative list; this predicate is a lint over it.
On stock torch the predicate is quiet. Sweeping 23 stock nn layers -- Conv/BN,
LSTM/GRU/RNN, MultiheadAttention, Sequential, LayerNorm, Embedding, pooling,
the activations, Bilinear, ConvTranspose2d -- flags exactly two,
TransformerEncoderLayer and TransformerEncoder, and only in training mode:
under eval() the fused encoder fast path never reads self.activation, so no
guard is emitted and nothing is flagged at all. Both flags are the same slot,
an activation that is a constructor keyword parked in an attribute, which is
torch's own spelling of `self.act = getattr(F, cfg.activation)`. Capturing one
with activation="relu" and serving it with activation="gelu" loads clean and
returns the relu answer, so it is a true positive, and exempting it would need
a "library-owned callable in a library-owned nn.Module attribute" rule that
reintroduces exactly that wrong answer.
wont_generalize got the same treatment. It keyed on the ___stackN name Dynamo
gives a value crossing a graph break, which both misses and overcounts: a
non-tensor argument is equality-pinned with no ___stackN name, while a tensor
crossing a break gets a ___stackN source under TENSOR_MATCH and generalizes
fine. It now requires a value-equality guard type AND a bare source name, so
model config reached through an argument -- a LayerNorm's eps, a Dropout's p --
does not flag every model. Both CONSTANT_MATCH and EQUALS_MATCH count, since
which one Dynamo emits depends on the value's type rather than on whether it
pins anything. A constant inside a container argument is guarded on a
subscripted source and is still missed; kept_guards is the authoritative list.
The intended deployment is capture on one machine and serve on another, so the
in-process concerns above matter less than divergence between the two, and the
cross-machine rails were checked end to end rather than argued. The source
checksum finds the module by name rather than by path, so an artifact moves
between differently laid out checkouts but still refuses to load against
drifted source, and SystemInfo rejects Python, PyTorch, CUDA, Triton and GPU
skew at load. It does not check the CPU vector ISA -- inductor bakes the
vector width into generated CPU code, so an AVX-512 capture served on an AVX2
host can produce wrong numbers with no error -- and the module docstring
records that along with the rest of the operational limits: capture under
no_grad, expect value-pinned artifacts from data-dependent breaks, identity
guards are not recoverable, the model must be importable, install() patches
code objects process-globally, a second artifact for one class silently
substitutes the survivor's graph for the evicted one, and a plain
torch.compile in a module that has an artifact loaded can hit a
__builtins_dict__ name collision until the artifact is unloaded. That last one
is disclosed rather than fixed: the real fix is not minting the name off a
process-local counter, which is output_graph's call, and rewriting the name at
load time would mean rewriting source trees inside serialized guard state,
where a mistake is a guard that silently stops discriminating.
One correction from a confirmation round is worth keeping in the history.
Dynamo's own synthesized resume locals, __nested_resume_fns and
__nested_frame_values, were being reported as risky drops: they name generated
code rather than a slot config chooses, so an identity guard lost on one
cannot diverge, and flagging them would refuse models whose resume functions
nest. The check keys on the scope-stripped guard name, since that is the form
the reporting path already normalizes to.
The shared-frame paragraph was also wrong in the direction that matters. Two
artifacts for one class do collide, on the entry frame, and evict each other
with a warning. Two artifacts for different models that merely share an inner
frame -- two models containing the same library block -- were assumed to
collide too, and measurably do not: entries accumulate on the shared code
object and the guards pick the right one. Both serve correctly, which
test_two_artifacts_sharing_an_inner_frame_both_serve now pins. That holds only
while the guards can tell the models apart, so the docstring now says what
happens once an artifact ships with the discriminating guard dropped, which
the default allows since the lint only reports: the first matching entry wins,
one model is served the other's graph, and nothing warns at load, because the
load-time eviction check only looks at the entry frame.
Fourth, guards.py, which is a fix to shared guard serialization rather than to
this module, found by pointing all of the above at real OSS models. Validating
against them rather than against synthetic fixtures is also the reason the
risky-drop lint reports by default instead of refusing.
Two capture-blocking bugs surfaced immediately. SourceInfo.add_code trusted
inspect.getmodule to name the module a code object came from, but that returns
whichever module re-exports it -- collections.abc is three lines of "from
_collections_abc import *" -- so hashing the code's line range read lines that
module does not have, and any model inlining through collections.abc, which
transformers does, failed capture outright with "Source mismatch for
collections.abc". It now resolves the module whose file actually holds the
code, and records the sys.modules KEY rather than __name__, because
_collections_abc sets its own __name__ to "collections.abc" and load-time
revalidation re-imports that name to the wrong object. Separately,
_module_namespaces only recognised a namespace if some guard entry happened to
hold the module, and Dynamo guards the attributes it reads off an import alias
but never the bare alias, so a real model produced G['__import_torch'].Tensor
and G['__import_torch'].is_autocast_enabled with nothing anchoring them and
both were reported as config-swappable slots. The alias name encodes its
module, so it is decoded instead; on a Qwen2 capture that is the difference
between 35 reported drops and 33.
Past those, transformers models captured and saved but did not load:
GuardsStatePickler.reducer_override replaced Qwen2ForCausalLM.forward with
_Missing because the class attribute is a functools.wraps decorator rather
than the function being pickled, so the __module__/__qualname__ round trip
fails -- and that branch fired without consulting the guard tree, dropping a
value the surviving guards still read, which then died at load with
"AttributeError: '_Missing' object has no attribute '__defaults__'". The
branch now falls back to _unpickle_nested_function, which already exists for
<locals> functions and rebuilds the function from code, module globals,
defaults and closure, but only when the final guard tree actually has a node
for the value. guard_tree_values is filled by get_guard_manager_from_source on
the post-filter builder, so membership means exactly "a source rooted here is
re-evaluated at load", i.e. the new branch fires only on artifacts that crash
today. The alternative -- dropping the guards rooted at an unresolvable source
-- would have silently deleted nine live guards including a TYPE_MATCH and
seven equality guards on that function's defaults, which under capture-here /
serve-there is the worst outcome available.
With that, transformers models load. They still do not round trip, and the
next failure is different and loud: the first served call recompiles, so
serving() raises. The entry frame is a functools.wraps decorator defined in
transformers/utils/generic.py (can_return_tuple for Qwen2), whose
code object lives in transformers/utils/generic.py, but
CompilePackage.initialize records python_module as the decorated callable's
__module__ -- functools.wraps copied it onto the wrapper -- so _install_codes
hands the guards transformers.models.qwen2.modeling_qwen2 as the global scope
and every G[...] guard misses, first on KeyError on G['_is_torch_available'].
Plain torch._dynamo.config.caching_precompile records the same mapping, so
this belongs to the loader rather than here, and fixing it means splitting
python_module in two -- the frame's defining module for the global scope, the
loading callable's module for the artifact-identity check -- which is a change
to the serialized entry rather than a surgical patch. It is disclosed in the
module docstring. Vision models round trip end to end.
The measurements those unblocked are why the lint is advisory. On stock
models, captured and served in separate processes on the eager backend:
torchvision resnet18 reports no risky drops, saves with every default on, and
serves all three captured batch sizes matching eager with zero compilations at
serve; mobilenet_v3 is the same over two batch sizes; timm's ViT reports one
drop, a re-exported torch._assert, plus one value-pinned argument, and still
saves with the defaults and serves two batch sizes with zero compilations.
transformers' Qwen2 reports 33 over three sequence lengths when built from a
two-layer config and 55 for the pretrained 24-layer Qwen2.5-0.5B, the extra
twenty-two being one per additional decoder layer; nearly all of them are
library internals -- output dataclasses, deprecation enum members, decorator
closure cells -- with only the attention-implementation registry entries
looking genuinely config-selected. A default that refuses stock ViT teaches
users to pass require_no_risky_drops=False unconditionally, which removes the
true positives along with the noise, so save() logs the list and
require_no_risky_drops=True turns it into a refusal once you have audited your
model. That is the outcome the predicate's own history argues for: it failed
open three times while being tuned for precision, and precision is not
reachable from capture-time values alone.
Test Plan:
Most of the new tests are in a new TestPrecompilePackage in
test/dynamo/test_package.py: 64 test methods, 94 cases once the four
parametrized ones expand. Coverage: a round trip across two graph breaks and
three specializations on both backends; guards on a global dict read on both
sides of a break, a dict passed as an argument, and nested dict membership and
key-set iteration, asserting positively that those guards were kept rather
than merely absent from the dropped list; the save() refusals, each with the
acknowledging flag exercised -- a truncated capture (and that the variants it
did capture still serve), a capture that ran nothing, and an entry frame with
no compiled code; the risky-drop corpus, nineteen shapes that must be flagged
and nine that must not, each parametrized and each asserting both halves of
the default (save() accepts, save(require_no_risky_drops=True) refuses), plus
the individual cases that pin one clause of the predicate apiece -- a builtin
read through the builtins dict versus a builtin in an attribute versus a user
table shaped like the builtins dict, torch.nn.functional.gelu spelled out in
full, a submodule of a self-named package, and four library spellings that
only the ownership test can clear; the advisory report itself, that a default
save() warns exactly once naming the source and how to enforce, stays silent
on a clean capture, and raises instead of warning under enforcement; the
value-pinning report -- a plain int argument, a dict_keys argument that
arrives as EQUALS_MATCH rather than CONSTANT_MATCH, both the stack slot and
the resume frame's local from an .item(), a tensor crossing a break that must
not count, and LayerNorm/Dropout/attribute config constants that must not
count; artifact identity at load -- a different callable, a same-named class
from another module, a different definition of the same name in one module, a
functools.wraps wrapper sharing the qualname, an artifact with no code entries
at all, a module whose forward has no __code__, a __code__ present but None,
and a checkout at a different absolute path that must still load; the
process-global state -- unload clearing resume-function entries, restoring a
skipped frame, keeping a skip another package still holds, keeping globals a
bystander compile needs, removing the builtins key install() added, leaving
alone a global a later package rebound while still leaving the namespace empty
once both packages have unloaded, a failed install leaving nothing installed,
and resume names from two separate captures not colliding; eviction -- the
second artifact for a shared frame warning before it evicts the first, that
the warning says the substitution is silent, and that it warns exactly once
and not when there is nothing left to evict; device_type surviving a cpu
graph, a load and re-save, and a failed load; and the cross-machine refusals,
drifted source and version skew.
The two capture-blocking bugs get tests of their own in the same class, built
on a two-file fixture that reproduces the collections.abc trap exactly (a
private file spoofing __name__ back to the public name, re-exported by a shim
that is three lines of `from _shim_impl import *`): one at the resolver, that
_defining_module_name returns the sys.modules key naming the file that holds
the code and that inspect.getmodule does not, and one end to end, that
capturing through the shim records the private name, saves, reloads and
serves. The alias anchoring gets three: a function-scoped `import torch`, the
shape a real model produces, whose G['__import_torch'].Tensor read must not be
risky; the same shape for a user module, which clears on the other arm of the
namespace rule; and the decode itself, including the _dot_ form.
The guards.py fix gets a regression test in test/dynamo/test_guard_serialization.py
built on a module-scope class whose forward is a decorator's wrapper -- the
shape transformers' generic.py decorators produce -- so the undecorated
function shares the wrapper's __qualname__ and is unreachable from the module.
It must be module scope: a <locals> qualname takes the already-working nested
function branch instead.
```
python test/dynamo/test_package.py TestPrecompilePackage
python test/dynamo/test_guard_serialization.py \
TestGuardSerialization.test_guard_rooted_at_fqn_mismatched_function
```
Regressions:
```
python test/dynamo/test_package.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_recompiles.py
python test/dynamo/test_precompile_context.py
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_decorators.py
python test/inductor/test_codecache.py -k caching_precompile
```
test_package 158 OK (23 skipped, 1 expected failure), test_recompiles 18 OK,
test_precompile_context 3 OK, test_guard_serialization 61 OK (1 skipped),
test_decorators 100 OK (2 skipped), the codecache caching_precompile subset
9 OK. test_aot_compile runs 49 with 3 pre-existing errors
(test_aot_compile_with_aoti*) from a local environment gap where AOTI's
generated header cannot find cuda.h; they fail identically on a clean tree.
The predicate, the uninstall change and the guards.py branch were each checked
by reverting them under the new tests, which is how the corpus earns its keep.
Each revert was applied on its own, and the failures listed are the complete
set:
```
# restore the "any read off a trusted namespace is fine" waiver
python test/dynamo/test_package.py -k risky_drop_corpus
# -> 4 failures: module_level_global, package_reexport,
# sibling_module, dispatch_in_inlined_helper
# restore "any builtins-owned value is fine"
python test/dynamo/test_package.py TestPrecompilePackage
# -> 3 failures: attribute_builtin_fn,
# test_risky_drop_detected_through_a_module_attribute_owner_builtin,
# test_a_builtin_shaped_read_that_is_still_a_slot_is_risky
# let a submodule inherit its parent's trust unconditionally
python test/dynamo/test_package.py TestPrecompilePackage
# -> 1 failure: package_submodule_alias
# restore uninstall()'s put-back-what-we-displaced loop
python test/dynamo/test_package.py TestPrecompilePackage
# -> 1 failure: test_unload_leaves_a_global_a_later_package_rebound
# restore SourceInfo.add_code's inspect.getmodule(code).__name__
python test/dynamo/test_package.py TestPrecompilePackage
# -> 2 failures: test_inlined_code_is_named_by_the_file_that_holds_it
# ('shim_abc' != '_shim_impl') and
# test_inlining_through_a_re_exporting_shim_round_trips
# ("AssertionError: Source mismatch for shim_abc (line 5-7)" at capture)
# make _dynamo_alias_module recover nothing
python test/dynamo/test_package.py TestPrecompilePackage
# -> 2 failures: test_reads_off_an_import_alias_are_anchored_to_its_module,
# test_reads_off_a_user_module_import_alias_are_anchored
# take the guards.py fqn-mismatch fallback back out
python test/dynamo/test_guard_serialization.py
# -> 1 error: test_guard_rooted_at_fqn_mismatched_function, with
# "AttributeError: '_Missing' object has no attribute '__defaults__'"
```
The real-model claims were reproduced with a capture process and a separate
serve process per model. resnet18, mobilenet_v3 and timm ViT all save with the
defaults and serve every captured variant against eager with zero compilations
at serve. Qwen2 from a two-layer config reports 33 risky drops and the
pretrained 24-layer model reports 55; turning off the __import_ alias decoding
takes the two-layer number to 35, the extras being G['__import_torch'].Tensor
and G['__import_torch'].is_autocast_enabled. The stock-layer sweep was rerun
in both modes: 23 layers, 0 flagged under eval(), 2 flagged in training mode.
Scale was checked out of tree at the target size, 50 graph breaks on the eager
backend, in both layouts -- one function breaking 50 times and specializing 3
ways, and 50 ModuleList instances whose 50 variants all pile onto one shared
frame:
```
50 breaks in one function : 51 frames, 153 guarded codes,
5.9s capture, 0.9 MB, 0.36s load
50 instances sharing one frame : 3 frames, 51 guarded codes,
2.1s capture, 0.35 MB, 0.19s load
```
Both replay every captured variant under fail_on_recompile with zero
recompiles and reject an uncovered input. Neither reports a risky drop. The
first saves with every rail on; the second is refused until
require_complete=False, because the loop over the ModuleList compiles nothing
of its own and lands in uncovered_frames, which is the case that refusal is
written for. Guard dispatch is a linear scan over one frame's guarded codes,
so the shared-frame layout costs 2.5 ms per call against 0.9 ms for the
distinct-frame layout. That is a property of the existing dispatch path, not
something this change introduces.
Authored with an AI assistant.
ghstack-source-id: 0565904
Pull-Request: #192379
This was referenced Aug 22, 2026
Closed
Contributor
Author
|
@bobrenjc93 has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator. |
Contributor
Author
|
@bobrenjc93 has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator. |
1 similar comment
Contributor
Author
|
@bobrenjc93 has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator. |
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):
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 withtorch.compiler.precompile.load. One contract for every capture shape.torch.compiler.precompileand its(python_code, cache)contract alreadyexist;
tracer="dynamo"is the value the API declares as planned and rejectswith NotImplementedError. This implements it.
It also makes
example_inputsthe ONLY calling convention, which is the otherhalf of what makes the tracer legible. precompile on main takes the example call
positionally -- and names that varargs parameter
example_inputs-- so addinga real
example_inputslist beside it left two things with one name and atracerargument that was load-bearing in one spelling and rejected in theother. Now there is one convention and
traceris the only thing that selectsa front-end:
"make_fx"(the default) is one non-strict ATen trace and takesexactly one call,
"dynamo"takes as many as you give it. A positional callraises 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_inputscalls so it pickedno_grad. precompile now always makes the call, sotrainingdecides forboth tracers --
no_gradunlesstraining=True. For make_fx that is ano-op on inference (the artifact is byte-identical either way, measured) and a
fix otherwise:
trainingwas previously accepted and silently ignored there.The dynamo tracer mirrors
torch.compile. Where they used to differ it wasbecause 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 runs the examples twice: once to learn, then again
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.
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 isinvolved, 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
installedinstead: thedriver rebuilds the package and hands the frames to the frame evaluator, which
reaches them by code object.
loadstill installs nothing; entering theresult, or calling it, installs, and
unload/exit takes it back out, so themutation is attributable to a point in the caller's control flow.
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
calllooks up_runtime_wrapperand_inner_call, itsRunnerlooks up the kernels. Left alone, the batch-2variant 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 nestedbinding (
def callinsideclass Runner) and a dotted import path(
torch._inductor.async_compile) out of the rewrite, each of which broke aregex 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 examplesitself and returns the pair;
precompile.load()reads it back. There is nocapture object the caller drives by hand: with
training=Truecovering thecase 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.
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.
training=Truemakes it a drop-in for a training step. The examples then runwith 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 isasked 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 onerecords 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.
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.
Test Plan:
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=Trueexplicitly.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.
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.
Differential Revision: D116222523