Skip to content

[dynamo] Region-owned precompile install and the concurrency stress suite - #195911

Closed
bobrenjc93 wants to merge 54 commits into
gh/bobrenjc93/1113/basefrom
gh/bobrenjc93/1113/head
Closed

bobrenjc93 wants to merge 54 commits into
gh/bobrenjc93/1113/basefrom
gh/bobrenjc93/1113/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Put the region/owner bindings from the previous commit to work from Python.
CompilePackage stamps every precompile entry it installs with a fresh
per-install _install_owner token and renames the artifact's resume functions
to per-package token-suffixed names (_resume_name_token,
_resume_global_renames, _rename_globals, which rewrites co_names recursively
through co_consts). A __resume_at name carries only a per-capture counter that
restarts every process, so two artifacts collide on it; the rename makes it
unique to the loaded package. The __compiled_fn backend globals already carry a
per-capture uuid and are left as-is. So two packages loaded from one artifact
coexist on a shared frame -- their precompile entries told apart by owner, their
resume functions by per-package name -- and unload in either order for
everything scoped that way. Before,
init and install() both called uninstall(), which reset EVERY precompile
entry on the code object, a neighbouring package's included, and the
fixed-name resume globals were overwritten by the next load. Neither reset
happens now: install() registers a weakref.finalize
(_uninstall_abandoned_package, atexit=False) before it installs anything, so a
failed install is torn down too; it pops only globals still
holding the dead package's own values and tears entries down through
_reset_precompile_entries_for_owner, which parks rather than blocks since
finalize can fire mid-guard-evaluation. An explicit uninstall() applies the
same identity check, so a name the user rebound keeps the user's value.
install() and DynamoCache.load_and_install_package take a keyword-only
isolate_recompiles_id, and _TorchDynamoContext installs the cached package
into its own region, since precompile entries match their region exactly.

Known limit at this commit, closed higher in the stack (#195915): a global two
loads genuinely share -- a __compiled_fn both install under its per-capture uuid,
an import alias bound to the same module object, or a resume/backend global
shared between a loaded package and a plain torch.compile of a different function
in the same module (not only the two-loads-of-one-artifact case) -- is popped by
whichever unloads first here, and "unload" includes GC: no explicit uninstall()
is needed. On the default caching_precompile path a transient torch.compile
wrapper being garbage-collected strips a name a still-live wrapper's installed
bytecode LOAD_GLOBALs, and the live one then raises NameError from inside user
code at an arbitrary later call. #195915 adds the owner-counted teardown that
pops a shared name only with its last owner, which is what makes the default
path safe -- so this commit must not land as the stack tip without #195915.

Test Plan:

python test/dynamo/test_recompile_ux.py
python test/dynamo/test_package.py
python test/test_precompile.py

test_recompile_ux.py adds the package-driven parking tests: a reinstall
surviving an eviction parked by uninstall, and a precompile reset run from
inside a lookup (the binding-only concurrency cases live with the previous
commit). test_package.py pins the finalizer, the co_consts recursion, two
loads of one artifact coexisting and unloading in either order, the
identity-checked uninstall (reading the installed name from the package's
bookkeeping, since a free-threaded build may not have popped the capture-time
global yet), and caching_precompile serving an isolate_recompiles context.

Authored with an AI assistant.

FAQ

Q: The shared _compiled_fn* backend globals are not part of the per-install
renames, so if two packages load from one artifact and the one loaded second
uninstalls first, it pops a name the live package still reads and NameErrors it.
Shouldn't those globals be renamed or ref-counted?

A: Correct that they are not renamed here -- only the resume functions are. A
_compiled_fn* name already carries the uuid minted when its graph was
captured; a _resume_at* name carries only a per-capture counter that restarts
every process, so the resume names alone get a per-package token suffix ({name}_{_resume_name_token}, the uuid minted once in __init__).
The hazard you describe -- two loads of one artifact sharing a _compiled_fn*
name, the second-loaded uninstalling first -- is real at this commit, and it is
addressed by ref-counting rather than more renaming. #195915, higher in this
stack, adds a per-module registry (_GLOBAL_BINDINGS) that keeps, per name, a
stack of value-keyed bindings each owning a WeakSet[CompilePackage]; a binding
is popped only when its last owner uninstalls, and the binding beneath it is
restored, so a second-loaded package uninstalling first cannot strip a name the
first still owns. That same registry subsumes the import-alias case this message
lists as a known limit. At this commit uninstall is identity-checked -- a
package removes a name only while it still holds the value it wrote -- which
keeps a user's rebind and non-overlapping installs correct; the cross-package
ref-counting for shared names is what #195915 adds.

Q: test_two_packages_from_one_artifact_coexist serves both packages while both
are live but never serves pkg_b AFTER pkg_a.uninstall(). Wouldn't serving it
then be a stronger test?

A: It would, but it cannot pass at this commit -- it is the known limitation
above. pkg_a.uninstall() pops the import-alias and __compiled_fn globals both
loads share, so serving pkg_b afterwards NameErrors on a stripped global. That
is exactly the behaviour the in-test note and #195915 describe; the test serves
both while co-installed (the coverage this commit does deliver) and documents
that after-unload serving is #195915's to add.

Q: DynamoCache.load_and_install_package's new isolate_recompiles_id keyword is
only ever called with its default in the tests. Why not cover a non-default
region through the wrapper?

A: The region-scoped path IS covered, through the production entry point that
motivates it: _TorchDynamoContext calls package.install(isolate_recompiles_id=...)
directly (eval_frame.py), which
test_automatic_dynamo_serves_an_isolate_recompiles_context exercises under
fail_on_recompile for both the default and isolated context. The public wrapper
forwards the keyword to that same install(), so a separate non-default call
through it would re-test the forward, not new behaviour.

Q: The tests call uninstall() without a try/finally or addCleanup, so a
mid-test failure leaves per-install globals and entries behind for the next
test.

A: The suite's base class (torch._inductor.test_case.TestCase) runs
torch._dynamo.reset() and clears DynamoCache/PrecompileContext in setUp, and the
per-test path() is unique, so leaked cache state does not cross into another
test. addCleanup would tidy the module dict sooner but changes no outcome; the
one place it matters -- a user rebinding that must survive -- already uses it.

Q: test_abandoned_package_uninstalls_on_gc relies on a single gc.collect()
firing the finalizer promptly, which a free-threaded build may defer. Shouldn't
it retry the collection?

A: On refcounted CPython the del drops the last reference and the collection is
synchronous, which is what CI runs today. A bounded gc retry is the right
hardening for a free-threaded build and is worth adding when that build gates
these tests; it is orthogonal to what this commit changes and is deferred rather
than pre-empted here.

Q: install() now scopes its precompile entries to isolate_recompiles_id, but the
len(guarded_codes) == 0 skip (a trivial entry compiles to an empty graph) calls
skip_code unconditionally: it writes the code object's GLOBAL exec strategy via
set_code_exec_strategy for EVERY install, region-scoped or not, and isolated
regions inherit that SKIP per field when they hold no entry of their own. So one
package installing a trivial entry turns dynamo off for that code in every
region, including an install into an isolate_recompiles region -- not just the
-1 default bucket.

A: Correct, and an earlier draft of this answer claimed mitigations that do not
exist at this commit. To set the record straight: skip_code is the plain, un-
refcounted set_code_exec_strategy (there is no _SKIP_INSTALLERS registry); the
branch has no region-scoped path, so an isolate_recompiles_id >= 0 install writes
the global strategy just like the default bucket; and the comment there is the
generic "Dynamo generates empty graph for trivial functions" note, not a scoping
caveat. It is not a regression in that the skip_code CALL was already unconditional
before this commit, and pre-commit install() wiped every entry anyway -- but what
making install() region-aware newly introduces is the REACH: a region-N install of
a trivial entry now writes a GLOBAL SKIP that every other region (the -1 default
included) inherits, so on the success path a later torch.compile of the same
function in the default region silently becomes a no-op until torch._dynamo.reset().
So it is not a new call, but it is a newly cross-region effect. The honest fix is to
route the id >= 0 case through set_code_region_exec_strategy (the same shape as the
precompile-entry handling this commit adds, so uninstall's region reset also drops
the skip) and record which codes were skipped so uninstall() can restore them; that
is genuine follow-up work, not yet done here; #195915 lands the region-scoped
branch (set_code_region_exec_strategy for id >= 0) and the record-and-restore
bookkeeping (_SKIP_INSTALLERS refcount, compare_and_set on uninstall), leaving
only the default bucket's write global there, refcounted so the prior strategy is
restored once.

Q: The RuntimeError fallback calls initialize(fn, None), which does not reset the
package, so the "fresh" package keeps the failed load's _codes/_device_types; the
next compile appends onto those stale entries and save_to_dynamo_cache() writes
the merged result, so the on-disk artifact grows one duplicate guarded code +
backend id per install failure, forever. This is NOT covered by
reset_after_failed_install() (which only handles _initialized); the growth comes
from _codes surviving.

A: Real at this commit, and the reproduction is correct: here the handler pokes
_initialized = False and re-initializes, and at this commit initialize() does not
clear _codes/_device_types, so the load-derived entries survive and the artifact
grows across warm serves. It is fixed higher in this same stack at #195915, and
-- as the finding correctly points out -- not by reset_after_failed_install()
alone. #195915 does two things together: it replaces the cross-module
_initialized poke with self._package.reset_after_failed_install() (assert nothing
installed, then _initialized = False), AND it makes initialize() reset the
load-derived fields up front -- self._codes = {} and self._device_types = set()
with a comment that "every field a load writes has to be reset here rather than
trusted to still hold its init value." So in the shipped stack the handler's
reset_after_failed_install() followed by initialize(fn, None) clears _codes and
_device_types, and the artifact does not grow. Because the stack merges
atomically, main never sees this commit as tip without #195915's reset; the
field-clearing lands next to the fields it has to know about, which is the shape
this finding recommends.

Correction: the consequence is worse than benign growth. Once _codes survives
and the load-derived resume entry is re-appended, function_names carries a
duplicate name, and on the next load _resume_global_renames raises on it. Until
this revision that raise was an AssertionError, which escapes the
except RuntimeError fallback this stack adds in eval_frame.py -- so one transient
failed install could poison the artifact into a hard crash at torch.compile()
decoration time, not merely grow it. This commit closes that off at the source:
_add_function now skips a function_name already in code.function_names (so the
failed-install path never re-appends the same code's name), install() reserves
the counter values behind a loaded artifact's __resume_at_<offset>_<n> names so
a compile in this process cannot mint one of them for a different code object
(the cross-entry collision _resume_global_renames rejects), and
_resume_global_renames raises RuntimeError rather than AssertionError so any
residual duplicate from a corrupt on-disk artifact is caught by the failed-install
fallback and degrades to a cold compile instead of taking working user code down.
the two fixes here make the failure mode recoverable regardless of route.
One more mechanism worth naming, since it decides how urgent #195915's reset is:
create_cache_entries stores the surviving _codes entries BY REFERENCE
(PrecompileContext.record_dynamo_cache_entry, unlike the deepcopying
record_artifact) and sets code.bypassed = True on them, after which
add_guarded_code / _add_backend_id / add_import_source all early-return on bypassed
-- so the affected frame is permanently dropped from every future load and cannot
be re-captured. That unrecoverable bypassed write, not per-load growth, is the real
harm: the carried-over set is the artifact's own entries, so it does not grow one
duplicate per install as the Q frames it; #195915's up-front _codes reset is what
prevents the bypassed write from ever happening.

Q: Dropping the wholesale _reset_precompile_entries lets precompile entries on a
shared code object grow with the number of live compiled callables on the
automatic caching_precompile path: N retained wrappers over one code object each
hold a full copy of the artifact's entries in region -1 under their own owner
(measured 1,2,3,4 vs a parent's 1,1,1,1). Isn't that unbounded growth?

A: It is bounded by the number of LIVE wrappers, and the duplication is intended,
not a leak. Each retained callable owns its own region -1 entries because each is
an independent install with its own owner token; a lookup must find the entry
belonging to the wrapper it is dispatching, so collapsing them across owners would
be wrong. The dedup in install() (_installed_precompile_codes keyed by id) is
per-package by design -- it stops one package re-installing the same code twice,
not two packages sharing a code object. Transient wrappers are GC-collected and
their entries torn down by the weakref finalizer (_uninstall_abandoned_package), so
the count tracks live instances rather than growing without bound. The growth is
O(live callables), the correct accounting for per-owner region entries;
test_two_packages_from_one_artifact_coexist pins the co-installed count, and a
dedicated per-owner count assertion would document the same intended
1-per-live-owner shape.

Q: In _uninstall(), the pop-globals loop runs unconditionally, but entry teardown
(_reset_precompile_entries_for_owner) can park when the cache lock is unavailable
or cache_python_depth > 0. So an entry can stay matchable after its
_resume_at/_compiled_fn globals are gone -- a served entry would NameError.
Shouldn't the two halves land atomically?

A: The asymmetry is real; the earlier version of this answer defended it with two
mitigations that do not exist at this commit, and both were wrong. There is one
shared teardown, _uninstall_abandoned_package, used by both uninstall() and the
weakref.finalize registration -- it did NOT reset entries first, it popped
globals first and reset entries three lines down, so the window was on the GC path
too. And there is no _PACKAGE_INSTALL_LOCK held across it (grep finds none); two
threads calling install() both run the teardown and both rebind the install owner.
This commit fixes the non-parked window on both paths at once by swapping the two
loops so the precompile entries are reset FIRST and the globals are popped after.
The remaining parked sub-case (reset defers to a later depth-zero drain while the
globals are already gone) needs the pops attached to the parked eviction so both
halves drain together -- the same "accepted parked residual" class the
extra_state.h lock-ordering note documents for the C++ side, tracked with
#196394. That both-halves-atomic change is deferred rather than
done blind here because its only observable consequence is unreproduced, but the
swap is strictly better than the status quo whether or not it lands.

Q: The finalizer teardown loop does module.dict.get(name) is value then
del module.dict[name] -- not atomic. From a weakref.finalize callback (which
GC can fire at any bytecode boundary) a concurrent removal between the check and
the del raises KeyError, CPython swallows it as an unraisable, and the rest of
the loop is abandoned, leaking every remaining global this package installed.
Shouldn't it be module.dict.pop(name, None)?

A: Real at this commit, and closed by #195915 higher in the same stack: that
commit rewrites this teardown -- uninstall() gets its own global-popping loop and
the finalizer defers to a _DEAD_PACKAGES drain -- and every removal there is
module.dict.pop(name, None), which has no check-then-del window. Because the
stack merges atomically, main never runs this commit's del; the pop-based
teardown lands with it. The one-line del->pop here would be strictly correct too,
but it is superseded by #195915's rewrite of the whole function, so it is not
applied to this intermediate in isolation.

Q: _uninstall_abandoned_package is the shared teardown for both paths at this
commit -- uninstall() calls it directly -- but its name and its comment's first
line describe only the weakref.finalize/GC path, so a reader greps it to
understand uninstall() and has to unlearn the name.

A: Accurate at this commit, and resolved higher in the stack rather than renamed
here. #195915 gives uninstall() its own teardown loop and leaves
_uninstall_abandoned_package registered only as the weakref.finalize callback,
so at the landed tip the name and comment describe exactly what the function
does. Renaming it to something path-neutral here would be inaccurate at the
endpoint, where it really is the abandoned-package (GC) callback again, so the
naming is left to track the endpoint shape.

Q: _resume_global_renames's RuntimeError branch (and the _add_function dedup
that removes its trigger) is load-bearing -- eval_frame.py's fallback only
catches RuntimeError, so a refactor back to AssertionError silently restores a
hard crash at torch.compile() decoration -- yet neither has a test in this
commit's diff.

A: The type IS pinned, so a refactor back to AssertionError fails CI:
test_resume_global_renames_rejects_duplicate_name asserts _resume_global_renames
raises RuntimeError("duplicate resume-function name") on two install_to_global
entries sharing a name, and test_add_function_dedups_function_name asserts
function_names stays length 1 after a double _add_function. Both live in #195913,
higher in the stack, co-located with the package-lifecycle tests their fixtures
share, rather than in this commit's diff; because the stack lands atomically, the
anti-poisoning contract is regression-protected in CI. The end-to-end fallback
(a corrupt artifact degrading to a cold compile through the except RuntimeError
handler) is exercised by the failed-install tests rather than pinned as its own
case.

Q: Dropping self.uninstall() from __init__ regresses a CAPTURING package
constructed while another package is installed on the same code object: lookup is
region-exact but not owner-exact, so the new package is served the installed
entry, records nothing, and save_package then overwrites the good artifact with
one that has zero guarded codes -- whose install skip_code()s the frame, making
a later torch.compile of that function a silent no-op until reset().

A: Confirmed (backend never invoked, zero guarded codes, poisoned artifact) and
fixed on the capture side: _TorchDynamoContext.__call__ now refuses up front
when its package does not own the precompile entries already serving the frame in
its region (CompilePackage.owns_install_on + _has_precompile_entries), with an
error naming the function and the two ways out (uninstall first, or
isolate_recompiles=True). Refusing rather than auto-minting a region keeps
optimize(package=)'s recompile accounting unchanged for users who did not ask
for isolation. The refusal fires only for a USER-SUPPLIED package (a CompilePackage(fn)
arrives initialized; the transparent cache hands _optimize an uninitialized
fn=None package) that has RECORDED NOTHING for the frame
(has_guarded_codes_for): a package that already holds guarded code for it saves a
valid artifact, and being served by a neighbour is then legitimate -- the manual
DynamoCache flow (test_dynamo_cache_manual_load) calls an old wrapper whose
package captured earlier while a freshly loaded package serves. The transparent
package is exempt because a cache hit installs its own entries and a miss records
and writes nothing. The check runs at decoration AND on every call of the wrapper,
so the neighbour can arrive in either order, and it is bound to the frame Dynamo
intercepts (resolved after wrap_inline may have rebound fn; for an nn.Module,
forward rather than the skipfile _wrapped_call_impl that OptimizedModule hands
the context). Cost: nothing without a user package; once the package has recorded
the frame the Python check short-circuits before the C++ scan.
test_capturing_package_refuses_a_frame_another_package_serves pins both orders
(including decoration alone) under both configs, that the installed package keeps
serving, and that an isolated region captures normally; the module variant pins
the nn.Module path.

Q: The warm-load fallback handler in _TorchDynamoContext.__call__ (except RuntimeError -> uninstall() -> re-init) is not exercised by any test; deleting
the uninstall() line leaves a per-install resume global and a live region entry
behind and nothing fails.

A: Added test_failed_warm_load_is_torn_down_before_the_cold_fallback: a
caching_precompile warm serve whose SECOND entry's load_guards_state raises, so
the first entry's precompile entry and renamed resume global are bound when the
handler runs; it asserts the cold compile returns the right answer, the warning is
logged, no precompile entry survives and no token-suffixed __resume_at_* global
is left. Injecting on the second load_guards_state call (rather than wrapping
install() to raise after completing) keeps the test valid at #195915, where
install() rolls back its own partial state and a post-install raise would leave
nothing partial.

Q: _installed_globals now holds the installed VALUE, so a package whose name a
later load displaced pins its dead backend wrapper for its whole lifetime.
Shouldn't it hold a weakref.ref?

A: At this commit a weakref would work and the pin is bounded (one displaced set
per live package that was overwritten; uninstall() drops it). But #195915 makes
the strong reference load-bearing: its per-name binding stack REBINDS a name to
the surviving owner's value when the top owner unloads -- two loads of one
artifact, second-loaded unloading first, put the first package's __compiled_fn_*
wrapper back so it keeps serving (measured: after the second package's
uninstall() the module holds the first package's original object and it serves
under fail_on_recompile). A weakref to the displaced value is dead exactly when
that rebind needs it. The registry also records globals a compile inside the
region installs (claim_region_global), whose values are not all weakref-able. So
the value is held strongly by design at the endpoint; the retention it costs is
O(live displaced packages).

Q: The finalizer's identity check is only tested through uninstall(), never on
the GC path; and test_reinstall_survives_an_eviction_parked_by_uninstall passes
even if its backend __eq__ hook never fires.

A: Both fixed: test_finalizer_leaves_a_users_rebinding_alone drops the package,
collects, drives an unrelated install/uninstall (so a finalizer that defers its
pop to the next install, as #195915's does, has run) and asserts the user's
rebinding is intact; the eviction test now asserts the hook list is empty after
the second call.

Q: test_failed_install_is_torn_down_when_the_package_dies deletes a backend by
hand, but on a disk load from_cache_entry pre-marks missing backends bypassed,
so after_deserialization is the real source of a mid-install RuntimeError.

A: The by-hand deletion is deliberate: it is the one failure that fires AFTER
earlier entries are bound at both this commit and #195915 (where
after_deserialization moves before any install and so can no longer produce a
partial install). The test pins teardown of a PARTIAL install, not the loader's
bypass path; production-shaped coverage of a failing rebuild is the new
fallback-handler test above.

Q: The extra_state.cpp comment "(every install at this commit still passes the
default id -1)" becomes false once this commit lands.

A: That comment is #195355's; it is reworded there to name #195911 as the commit
that registers each region under its own id, so it stays true at every point in
the stack.

Q: The refusal gates on not config.caching_precompile, but that is a global
config, not "this package came from the transparent cache": a user-supplied
CompilePackage(fn) with the config on is not refused and reproduces the full
poisoning chain -- a regression against the parent on the config this stack
targets.

A: Confirmed and fixed: the gate is now "the package is user-supplied" (a
CompilePackage(fn) is initialized at construction; the transparent cache's
package is built with fn=None and initialized later by the context), so the
config no longer matters. Both measurements in the comment hold: on a hit the
context's own install makes owns_install_on true, and on a miss with a
neighbour installed the auto package records nothing and save_to_dynamo_cache()
writes no dynamo entry. The test is parametrized over the config.

Q: The check runs at decoration, so decorate -> neighbour installs -> call slips
through and poisons the same way (pre-existing, but the refusal is then a partial
fix, and @optimize(package=) at import time is exactly the missed order).

A: Fixed: the check is a closure bound to the code object, run at decoration and
again at the top of every call of the wrapper (before the enter/exit hooks, inside
the try that restores eval-frame state). It costs nothing when no user package is
set; for a serving package the Python-side owns_install_on short-circuits before
the C++ _has_precompile_entries scan, so only a capturing user package pays one
lock-scoped scan per call. The test now exercises the reverse order too.

Q: test_two_packages_region_scoped_serves_its_own_entries asserts only
resume_b; if resume_a were empty the poison loop would be vacuous.

A: Added self.assertTrue(resume_a) alongside it.

Q: linux-jammy-py3.14t-clang21 is red on this PR and every PR above it.

A: One test, test_finalizer_leaves_a_users_rebinding_alone, found the installed
__compiled_fn_N name by diffing the module dict; under free-threading the
capture-time CleanupHook pops the previous compile's name late (deferred
refcounting), so the install rebinds a key already present and the diff is empty.
It now reads the name from the package's own bookkeeping, as the sibling uninstall
test already did (and #195915 adapts it to its _InstalledGlobal list the same
way it adapted the sibling).

Q: The per-call refusal breaks test_dynamo_cache_manual_load: the documented
manual DynamoCache flow decorates with a capture-time CompilePackage(fn) and is
then served by a separately loaded package, which the check calls "another
package".

A: Fixed: the refusal now requires that the user package has recorded nothing for
the frame. The old wrapper's package holds a guarded code for fn (it captured
before the save), so it is served without complaint; a fresh package that never
saw Dynamo run on the frame is still refused, which is the only shape that can
poison an artifact. This also bounds the cost the review measured: the C++ scan
runs only until the first compile of the frame.

Q: TestCase.enterContext is 3.11+, but the project supports 3.10 and CI runs
it; both parametrizations hard-error there.

A: Fixed: the test body runs under with torch._dynamo.config.patch(...).

Q: The refusal is dead on the nn.Module path (getattr(fn, "__code__") is None
for a module; OptimizedModule then re-enters with the bound __call__, a
skipfile, so the closure checks a code object Dynamo never intercepts), and code
was captured before wrap_inline rebinds fn. Also, that getattr probe runs a
user nn.Module.__getattr__ (CI: test_custom_getattr_hasattr_no_recursion).

A: Fixed: the frame code is resolved once fn is final, without a getattr probe
(isinstance(fn, (FunctionType, MethodType))), and a module's bound __call__
resolves to innermost_fn(module.forward).__code__, where the entries live.
test_capturing_package_refuses_a_module_frame_another_package_serves pins it,
including that an isolated region still captures the module normally.

Q: install() records _installed_precompile_codes[id(code)] before the
zero-guarded check, so a skipped frame is "owned" although no entry was installed,
contradicting owns_install_on's docstring.

A: Fixed: the code is recorded only when the entry has guarded codes; a
zero-guarded entry writes the skip and owns nothing.

Q: The dedup in _add_function is within one entry; the collision
_resume_global_renames rejects is across entries (two code objects claiming one
__resume_at_<offset>_<n> after a reload plus a branch-divergent recompile, since
the counter restarts per process), and a re-record persists the duplicate.

A: Correct, and the commit message wording is fixed. install() now reserves the
counter values behind every loaded __resume_at_<offset>_<n> name
(_reserve_unique_id_through, moved down from #195915 where it reserved the
builtins-dict index), so a compile in this process cannot mint a loaded name for a
different code object; the rejection becomes unreachable by construction rather
than by the builtins-index coincidence.

Q: Two threads calling install() on one package both pass uninstall() and both
register a finalizer; only the last is detachable, so a stale finalizer survives
and fires at package death.

A: Real at this commit and closed by #195915, whose install() holds
_PACKAGE_INSTALL_LOCK across the uninstall and the finalizer registration, so the
detach-then-register pair is atomic and exactly one finalizer is live per package.
ghstack lands PRs individually, so that window exists on main between the two
merges; two concurrent installs of one package are a data race on every other
field too, so the window changes nothing a correct program observes.

Q: The decoration-time check site is not covered (both test cases decorate and
call in one expression); the region half of owns_install_on is untested; the
finalizer test's entries == 0 assertion is self-fulfilling because
_save_eager_package ends with torch._dynamo.reset().

A: All three fixed: the refusal test now decorates after the neighbour installs
and asserts the raise before any call; the region-scoped test asserts
owns_install_on for both packages in both regions; the finalizer test saves the
unrelated package up front so no reset runs after the install (verified that the
assertion now fails with the finalizer neutered). The -1 sentinel is the same
default-region id the C++ side uses (set_eval_frame_isolate_recompiles_id), so it
is kept rather than switched to None.

Q: The install docstring says "dropping it undoes these updates", but the
skip_code a zero-guarded entry writes is never undone by uninstall() or the
finalizer at this commit.

A: Docstring now carries the caveat until #195915's record-and-restore
bookkeeping lands.

Q: refuse_if_another_package_serves runs has_guarded_codes_for (a dict walk)
on every call of the compiled function.

A: Latched: once the package has recorded on the frame it is the server there,
and the closure stores that in a nonlocal bool, so the steady state is one bool
read per call.

Q: refusal_code is not unique to the callable being decorated: every
wrap_inline'd frame in the process shares one inner code object, so a
package serving one built-in nn.Module makes decorating a second built-in module
with another package refuse at decoration.

A: Real; fixed. _refusal_frame_code returns None for wrap_inline's shared
inner code (_WRAP_INLINE_INNER_CODE), since entries on that frame are
multi-owner by design and say nothing about who serves a particular module.
test_two_packages_share_a_built_in_modules_wrap_inline_frame saves a bare
nn.Linear package, loads it and install()s it (which is what puts a precompile
entry on the shared inner code; a package that merely records under
caching_precompile installs nothing), then decorates a bare nn.ReLU with a fresh
package and checks it is not refused and records its own entry. With the inner
exemption removed the test raises the refusal at decoration. The mirror half (a
second package on the same shared frame is not refused when it perhaps should be)
cannot be decided per owner on a shared frame: lookup is by guard, so a second
module whose guards match the first package's entry (a same-shape Linear) is
served by it and records nothing, exactly as a second torch.compile(Linear)
shares the first's cache entry today, and one whose guards miss records its own.

Q: The __resume_at counter reservation has no unit test at this commit, the
prefix is spelled twice (symbolic_convert.py and the install regex), and
nothing shows install() actually moving the counter past a loaded artifact's
names.

A: test_reserve_unique_id_through_skips_past_a_loaded_artifacts_counter moved
down from #195915 (it depends only on bytecode_transformation);
RESUME_FN_PREFIX is now the one spelling (precedent: COMPILED_FN_PREFIX), used
by the resume-function minting and the install regex; and
test_install_moves_the_counter_past_a_loaded_artifacts_resume_names loads an
artifact with a graph break, resets the counter to simulate a fresh serving
process, installs, and checks the next minted id is past every loaded name.

Q: test_resume_function_with_freevars_reinstalls_its_closure has one resume
entry, so the per-iteration default-argument capture in _make_fn is unpinned.

A: The closure now graph-breaks twice, so two resume functions are rebuilt
through the factory and a late-binding regression would fail the numeric check.

Q: test_two_packages_share_a_built_in_modules_wrap_inline_frame cannot fail
with the _WRAP_INLINE_INNER_CODE fix reverted.

A: Confirmed and fixed. CompilePackage(lin.forward) is initialized at
construction, so the first package only RECORDED an entry on inner and never
installed one; _has_precompile_entries(inner, -1) stayed False and the refusal
short-circuited regardless of the fix. The test now saves, loads and installs the
first package (verified: passes with the fix, raises the refusal at decoration
without it).

Q: The _WRAP_INLINE_INNER_CODE comment understates the blast radius: more than
built-in modules route through wrap_inline.

A: Comment now lists them: skipfile functions and built-in module forwards,
top-level in-graph and polyfilled functions, and any module under
config.wrap_top_frame (the debug_force_nested_calls route .replace()s the
code, so it is not shared and the refusal still applies there).

Q: The extra_state.cpp comment "every install at this commit still passes the
default" is falsified by this commit.

A: That text no longer exists: #195355 (which owns the line) reworded it to
"Installs below #195911 in this stack pass the default id -1; that commit's
region-owned install registers each region under its id" (extra_state.cpp:759-760
on this PR's base branch). The quote is from an earlier round.

[no ci]

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

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

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 3, 2026
This was referenced Sep 3, 2026
Comment thread torch/_dynamo/eval_frame.py Resolved
Comment thread torch/_dynamo/eval_frame.py Resolved
Comment thread test/dynamo/test_package.py Resolved
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Claude encountered an error —— View job


I'll analyze this and get back to you.

[ghstack-poisoned]
Comment thread torch/_dynamo/eval_frame.py Resolved
Comment thread test/dynamo/test_package.py Resolved
Comment thread torch/_dynamo/eval_frame.py Resolved
Comment thread torch/_dynamo/package.py Resolved
Comment thread torch/_dynamo/package.py Resolved
Comment thread torch/_dynamo/package.py Resolved
Comment thread test/dynamo/test_package.py Resolved
Comment thread torch/_dynamo/package.py Resolved
Comment thread test/dynamo/test_package.py Resolved
Comment thread torch/_dynamo/package.py Resolved
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 41m 10s —— View job


Re-reviewed at 4cb1fc2f: this round's delta is real work (+1002/-23, and a fifth file), and most of it lands — but the new capture-side refusal is code-object-granular, and every wrap_inline'd frame in the process shares one code object, so it both false-refuses and false-permits across unrelated callables.

Full review of #195911 (twentieth pass)

PR Review: #195911

Summary

Adds a per-install owner token, per-package resume-global renaming, isolate_recompiles_id plumbing into install(), and a new capture-side refusal so a fresh CompilePackage cannot silently capture nothing while a neighbour serves the frame. The refusal is the right idea, but it keys on a code object that wrap_inline shares process-wide, which makes it fire on unrelated frames — and, in the other direction, suppress itself on the frames it exists to protect.

Verified fixed

Recorded so they are not re-litigated. I re-derived each rather than taking the summary.

  • The failed-install fallback is now torn down. eval_frame.py:1062 calls uninstall() before re-initializing, and it cannot itself raise: uninstall()'s precondition is _innermost_fn is not None (package.py:1416), assigned at package.py:1242 ahead of every RuntimeError source in the try (check_versions() at :1248, the source-checksum raise at :1254); the only earlier raises are AssertionError (:1240) and ImportError (:1251), neither caught by except RuntimeError.
  • test_failed_warm_load_is_torn_down_before_the_cold_fallback (test_package.py:1002) covers the production-shaped trigger. Injecting on the second load_guards_state is the right choice: the first entry's precompile entry and renamed resume global are bound when the handler runs, so the assertions at :1039-1042 (zero entries, no token-suffixed __resume_at_*) are non-vacuous.
  • test_failed_install_is_torn_down_when_the_package_dies now pins the partial state before the GC (test_package.py:966-967), and the ordering it relies on holds: the main entry is first in _codes (package.py:1261) and gets its _load_precompile_entry (:1653), then the resume entry binds its renamed global (:1547-1572) and only afterwards raises on the missing backend (:1600-1603).
  • test_reinstall_survives_an_eviction_parked_by_uninstall is no longer vacuous — self.assertFalse(hook, "the backend __eq__ hook never fired") (test_recompile_ux.py:1220) closes the pass-without-firing hole I flagged.
  • _uninstall_abandoned_package resets entries first, then pops globals (package.py:1134-1141), which closes the non-parked half of the ordering window the FAQ describes.
  • self.assertTrue(resume_a) is present in the region-scoped test (test_package.py:1174), and owns_install_on is now asserted for both packages in both regions (:1187-1190), so the region half of that predicate is covered.
  • test_finalizer_leaves_a_users_rebinding_alone saves the unrelated package to its own path up front (test_package.py:1121-1124), so no torch._dynamo.reset() runs after the install — the entries == 0 assertion is no longer self-fulfilling.
  • The nn.Module refusal path is real and probe-free. _refusal_frame_code (eval_frame.py:782-792) gates on fn.__func__ is torch.nn.Module.__call__, which holds because Module.__call__ is _wrapped_call_impl (torch/nn/modules/module.py:1926), and mod.forward resolves as a class attribute, so no user __getattr__ runs. The earlier CI failure in test_custom_getattr_hasattr_no_recursion is genuinely addressed.
  • _reserve_unique_id_through (bytecode_transformation.py:1997-2002) is correct, which I checked because a subagent claimed otherwise. It consumes one value and rebuilds the counter at max(current, index + 1): when index + 1 <= current the new itertools.count(current) re-issues current as its first value, so nothing is lost; when index + 1 > current that one value is skipped, which is harmless. The lock makes the read-modify-write atomic, so no index is ever handed out twice. And the reservation runs at install(), ahead of any compile served through the loaded package, which is the ordering the guarantee needs.

Code Quality

  • refusal_code is not unique to the callable being decorated: every wrap_inline'd frame in the process shares one code object, so the refusal fires across unrelated functions and suppresses itself across unrelated packages. _refusal_frame_code returns fn.__code__ (eval_frame.py:790-791) after fn may have been rebound by external_utils.wrap_inline(fn) (eval_frame.py:1226, and OptimizedModule._initialize at :547). wrap_inline returns a nested inner (external_utils.py:62-71) whose code object is a constant of wrap_inline's own code, compiled once — so every wrap_inline(...) in the process yields the same __code__. This is not inference: the repo documents it at eval_frame.py:1210-1212 ("wrapping collapses them onto wrap_inline's shared inner code (Function's created via exec() raise recompilation warning and cache_size_limit error #124269)") and works around it at :1207, but only under config.debug_force_nested_calls.

    Both directions break:

    • False refuse. A user package loaded for model A installs a precompile entry on the shared inner code (capture records _add_user_function(inner.__code__), and _lookup_code resolves the code_source back to that same object). A fresh CompilePackage(B) for an unrelated B then has has_guarded_codes_for false, owns_install_on false, and _has_precompile_entries(inner_code, region) true (extra_state.cpp:1425-1427 filters on region only) — so eval_frame.py:1098 raises. The message reads another CompilePackage is installed on inner, since functools.wraps copies __name__ onto the function, not co_name onto the code.
    • False permit. Symmetrically, a package that installed on some other wrap_inline'd frame satisfies owns_install_on(inner_code, region) (package.py:1218-1223, id(code) in _installed_precompile_codes), so the check short-circuits exactly where it is needed.

    Reachability is not exotic: _forward_has_skip_rule is true for built-in modules, since torch.nn is in MOD_SKIPLIST, so torch.compile(nn.Linear(3, 3)) takes the wrap_inline branch — two bare built-in modules under the manual optimize(package=...) flow is enough. And for those, A's entry keeps a TYPE_MATCH on the closure freevar (serializable, not in the caching_precompile drop list), so B would have missed and compiled normally: the refusal converts a working flow into a hard RuntimeError at decoration. Cheapest fix is to skip the check when refusal_code is the shared inner code (it is reachable as a const of wrap_inline.__code__), and say why in the comment; a decorated-frame-granular identity would be better but is a larger change. Fix this →

  • uninstall() still does not revert skip_code, and the new fallback now depends on it doing so. install() calls torch._dynamo.eval_frame.skip_code(target_code) for any zero-guarded entry (package.py:1614-1617), which writes the global exec strategy; extra_state_get_region_exec_strategy deliberately inherits SKIP into every region holding no strategy of its own. Neither uninstall() (package.py:1418-1439) nor _uninstall_abandoned_package reverts it, and the package records no skipped codes, so only torch._dynamo.reset() clears it. Two consequences: the fallback's own comment says "Undo it before re-init" (eval_frame.py:1057-1061) but a SKIP that landed before the raise survives, so the intended cold compile is a silent no-op; and on the success path a region-N install of a trivial entry now writes a global SKIP every other region inherits. The FAQ concedes both and names set_code_region_exec_strategy plus record-and-restore as the fix at [dynamo] Region-scoped install ownership and skip-strategy bookkeeping #195915, and the docstring carries the caveat (package.py:1156-1159) — so this is a note on a named follow-up, not a new ask. Worth knowing the restore side is already bound in the base (set_code_exec_strategy_with_token, compare_and_set_code_exec_strategy), so it is a Python-only change.

  • The fallback's re-initialize leaves _codes populated, and the harm is a permanently poisoned artifact. initialize() assigns _codes/_device_types only under if dynamo is not None: (package.py:1260-1265), while _source_info is reset (:1241) — so the surviving state is internally inconsistent too. The production save path stores entries by reference (PrecompileContext.record_dynamo_cache_entry, unlike the deepcopying record_artifact), so from_cache_entry mutates the same live entries and sets code.bypassed = True; from then on install() skips them (package.py:1576-1579) and add_guarded_code/_add_backend_id/add_import_source early-return, dropping the frame from every future load. The FAQ's "Correction" paragraph now names this correctly, and [dynamo] Region-scoped install ownership and skip-strategy bookkeeping #195915 lands the reset — no disagreement with the deferral.

  • _uninstall_abandoned_package still uses module.__dict__.get(name) is value then del module.__dict__[name] (package.py:1138-1141). From a weakref.finalize callback a concurrent removal between the two raises KeyError, which CPython swallows as unraisable and abandons the rest of the loop, leaking every remaining global. pop(name, None) is a one-line fix; the FAQ says [dynamo] Region-scoped install ownership and skip-strategy bookkeeping #195915 rewrites the whole function that way. Fine to defer, but it is one line and strictly correct today.

Testing

  • The refusal's two sites are covered but its granularity is not. test_capturing_package_refuses_a_frame_another_package_serves (test_package.py:1229) pins both orders, both configs, the still-serving neighbour and the isolated-region escape; the module variant (:1281) pins the forward resolution. What no test covers is two different functions mapping to one refusal_code, which is the finding above — decorating two bare built-in nn modules with two separate user packages is the shape.
  • The _make_fn per-iteration pinning is uncovered. The default-argument capture at package.py:1557-1565 exists to defeat late binding across loop iterations, but test_resume_function_with_freevars_reinstalls_its_closure's fn has exactly one resume entry, so reverting to closure capture would still pass. A closure with two graph breaks covers it. (Worth knowing what the test does pin: deleting the if code.co_freevars: branch fails at install, since types.FunctionType(code, globals, name) rejects non-empty co_freevars — the numeric check is a bonus.)
  • test_abandoned_package_uninstalls_on_gc (test_package.py:891) and the two failed-install tests all stake correctness on a single gc.collect(). The count equality, the zero-entry checks and the leaked diffs all fail if weakref.finalize runs one collection late, which a free-threaded build permits. A bounded retry would be sturdier; the precedent is one commit down, where the base replaced the thread tests' per-join timeouts with a shared deadline plus a liveness assertion.
  • test_failed_install_is_torn_down_when_the_package_dies still drives a raise the loader cannot produce — it deletes a backend by hand to hit package.py:1600, but from_cache_entry pre-marks missing-backend codes bypassed and install() skips them first. The FAQ argues the by-hand deletion is deliberate (the one failure that fires after earlier entries are bound at both this commit and [dynamo] Region-scoped install ownership and skip-strategy bookkeeping #195915), which I accept now that test_failed_warm_load_is_torn_down_before_the_cold_fallback covers the production-shaped path.
  • No try/finally/addCleanup around uninstall() at test_package.py:945, 1073, 1077; test_recompile_ux.py:1222, 1223, 1444. _install_eager_package (test_recompile_ux.py:1158) registers cleanup for the tempdir (:1165) but not for the install it returns. Note the refusal tests do use addCleanup(pkg1.uninstall), so the pattern is in the file.
  • DynamoCache.load_and_install_package's isolate_recompiles_id kwarg is still never called with a non-default region — lower priority now that the region path is covered end-to-end through install().

Recommendation

Request Changes — narrowly, for one line.

Everything else in this round holds up under checking: the fallback teardown is correct and cannot itself raise, the warm-load fallback test is well-targeted, the reinstall test's hook gate closes a real vacuity, and _reserve_unique_id_through is sound (I verified the counter arithmetic directly after a subagent claimed a duplicate-id bug — there is none). What blocks is that the refusal is code-object-granular while wrap_inline collapses every wrapped callable onto one shared code object, so it can hard-fail a working optimize(package=) flow on bare built-in nn modules and can also silently short-circuit on exactly the frames it protects. Skipping the check for that one known-shared code object is a line plus a comment.

CI at 4cb1fc2f: 0 failures, 6 passed, 4 pending (pull and torchtitan-test in progress, trunk and inductor queued), with three runs cancelled and superseded by the push. TSan is green, which is the check that matters most for the parked-eviction layer under this commit; Lint (both), BC Lint, docs-build and ghstack mergeability are also green. I could not run the test files locally (no built torch in this checkout), so all verification above is static reading; the wrap_inline finding was re-derived through two independent agents against external_utils.py, eval_frame.py, trace_rules.py, package.py, guards.py and extra_state.cpp, and I dropped a subagent's _reserve_unique_id_through claim after checking the arithmetic myself.

Previously investigated and dismissed

Recorded so they need not be re-litigated: the stale-finalizer window on reinstall (uninstall() detaches and rebinds the containers before install() re-registers); the -1 region sentinel being overloaded; dropping uninstall() from __init__ (now compensated by the refusal); the zip early-return in _rename_globals; co_consts recursion sufficiency (pinned by test_rename_globals_rewrites_nested_code); resume-global name length; the co_names retargeting concern (rename keys come only from entry.function_names of install_to_global entries, so no user LOAD_ATTR/IMPORT_NAME operand can collide, and package.py:551-558 documents the invariant); the identity-based dedup at package.py:1582-1598; input_codes.add (a weakref Tracker, so not a leak); _add_function's dedup and the AssertionError → RuntimeError change (both correct and narrow, though neither has a test in this commit's diff — the FAQ places them at #195913); the region-scoped test's poison (unreachable today, but the only assertion that would catch a -1 fallback regression); the strong reference in _installed_globals (load-bearing at #195915's binding stack); the parked-reset ordering hazard (documented build-agnostically as a lifecycle contract); the earlier FAQ dispute over whether __compiled_fn_* globals are renamed (they are not, and the body says so).

· branch `gh/bobrenjc93/1113/head`

bobrenjc93 added a commit that referenced this pull request Sep 9, 2026
ExtraState's cache had no lock, and lookup() walks it while evaluating
guards, which run Python, so the GIL can drop mid-iteration and another
thread can clear the list being walked. Once precompile artifacts are
installed and unloaded on live code objects at runtime this is no longer
survivable. ExtraState now has a recursive cache_mutex taken through
CacheLock, which try-locks first and releases the GIL only when it must
wait, so a waiter holding the GIL cannot wedge the owner that needs it. lookup() and try_lookup_without_guard_eval() hand back a
new reference to the cached code and copy trace_annotation out under the
lock, and the frame evaluator holds that reference before anything that can
drop the GIL.

Evictions that arrive under a live lookup park instead of splicing the list
being walked: invalidate() (reached from weakref.finalize) never blocks and
re-locates its entry by guard-manager identity, so its binding no longer
takes the raw CacheEntry pointer, and reset_code and the region/precompile
resets park on the state when cache_python_depth is non-zero, applied by the
next depth-zero holder. reset_code empties the state in place
(clear_in_place) rather than destroying a mutex another thread may be parked
on. The default exec strategy moves into a lock-free std::atomic with a
generation token behind get/set_with_token/compare_and_set bindings, the
current isolate_recompiles_id becomes thread-local, precompile entries carry
a region and an owner token, and get_backend honours a backend's
_torchdynamo_cache_key behind a one-way gate. The Python side of the
region/owner bindings follows in the next commit; guards.py only adopts the
new invalidate() signature.

Every path that hands cache state out does so under the lock: create_cache_entry
fills the new entry's code (owned) and trace annotation for its caller before
releasing, so the frame evaluator never dereferences the entry once a
concurrent clear could destroy it; _load_precompile_entry builds its
PrecompileEntry (which runs Python) before taking the lock and drains parked
evictions before appending, so a parked CLEAR_ALL cannot eat the install; and
_debug_get_precompile_entries raises the Python depth around its casts, so a
package finalizer reached from GC parks its eviction instead of splicing the
list being walked. remove_from_cache takes compile_lock like
torch._dynamo.reset(), which is the contract reset_extra_state's header states.

Test Plan:

This is the C++ locking change; it carries no tests of its own. Its
concurrency/contract coverage is added one commit up in #196120 (see the FAQ),
which adds ~787 lines to test/dynamo/test_recompile_ux.py. Verified at the stack
head by:

```
python test/dynamo/test_recompile_ux.py
python test/dynamo/test_package.py
python test/test_precompile.py
```

Authored with an AI assistant.

FAQ

Q: update_diff_guard_root_manager is a Python-reachable mutator that reassigns
diff_guard_root_mgr as a raw pointer, and the lock-free lookup() window
dereferences that field. Isn't that an unlocked write racing a lock-free read?

A: Reachable only under skip_guard_eval_unsafe with two threads recompiling one
code object concurrently, and it predates this PR -- base lookup() held no lock
at all. The lock added here reasons about node lifetime during guard evaluation,
not about this field's stability under concurrent recompile; closing that window
means taking cache_mutex in the binding (it runs at compile time, so the cost is
irrelevant) and is tracked as a follow-up. The comment scope is narrowed to say
so rather than implying the field mutation is already covered.

Q: Six sites still hold cache_mutex across arbitrary Python (create_cache_entry's
py::cast, the debug enumerators, drain_pending_invalidations), so the
lock-ordering invariant the header claims holds only for guard evaluation. Isn't
the header over-claiming?

A: The mitigation this commit lands does cover the hot path -- guard evaluation
under lookup() -- with one named residual on the frame-eval path: the
parked-invalidation drain lookup() runs at cache_python_depth 0, whose decrefs of
the old guard_manager can fire a user __del__ under the lock (extra_state.h says
exactly this); every other Python-under-cache_mutex site runs only at
compile/debug time. Rather than the full snapshot-release/park treatment of all six
(which needs care around user __del__ and backend __eq__), the header claim is
narrowed to state the mitigation covers guard evaluation and to name the
knowingly-exempt sites.

Q: This locking commit ships no tests of its own. Where is the coverage?

A: Added in the sibling commit, not missing. This ghstack splits the C++
locking change from its concurrency/contract suite so each reviews on its own;
the 14 tests (~787 lines) are added in "[dynamo] Concurrency and contract tests
for the ExtraState lock" (#196120), later on this same stack, in
test/dynamo/test_recompile_ux.py. This commit's own diff touches no test files;
the stack head has the full coverage. The deterministic (single-threaded) pin a reviewer would want for the park/drain path is there too: test_region_clear_from_inside_a_lookup_is_parked drives a CLEAR_ALL from inside a live lookup via a backend __eq__ hook and asserts the next depth-zero lookup drains the parked clear before it scans candidates, with no TORCH_CHECK fired; and the drain-before-read contract on _get_total_cache_entry_count / _debug_get_cache_entry_list is asserted across that suite.

Q: The region/ownership bindings this commit adds (14 of them, plus
_torchdynamo_cache_key / _torchdynamo_force_callback_on_cache_miss) have no
caller anywhere. Why add dead surface?

A: The consumers are higher in this stack, in the commits the reslice split
these bindings away from. Concretely, _get_cache_entry_count_for_region is
imported and called in convert_frame.py by #195913's capture/serve accounting
(total_count -= _get_cache_entry_count_for_region(code, region_id)), and the
region/owner install bindings by the precompile install/package layer above
that. The reslice deliberately keeps the C++ bindings with the locking change
they belong to rather than splitting a binding from its lock, and the stack
merges atomically, so no released commit ships a binding with no consumer. They
read as unused only in this PR's isolated diff.

Q: get_backend treats _torchdynamo_force_callback_on_cache_miss = False as still
forcing, because it only tests presence. Isn't False surprising?

A: Presence-only is intended and matches the hasattr convention these markers
use; the attribute is set to opt in and absent to opt out, and its value is not
read. Documented as presence-only.

Q: reset_code now empties the state in place instead of nulling the extra
pointer, so the run-only empty-cache fast path is gone on every reset. Isn't that
a permanent hot-path regression?

A: The null-out is unsafe once the mutex must outlive parked waiters: freeing the
extra state (and its mutex) under a thread parked on that mutex is a
use-after-free, so reset drains and clears in place instead. The lost fast path
is narrow (an empty cache after reset) and the correctness of not destroying a
mutex another thread holds is not negotiable. Correcting the cost
characterization from an earlier draft: it is per-frame and permanent, not
per-reset. The husk stays attached, so callback.is(Py_False) && extra == nullptr
never fires again for that code object; every subsequent run-only frame pays the
region-id lookup, the strategy read, get_backend, the callback set, and a
CacheLock acquire in try_lookup_without_guard_eval. Measured on this checkout
that is ~88 ns/frame over a NULL-extra-state frame (run-only, trivial body, best
of 7 x 200k). Small, and it does not outweigh refusing to free a mutex under a
parked waiter -- but a pr_time benchmark measures compile time and will never see
it, so tracking it needs a run-only-after-reset runtime benchmark, not pr_time.

Q: Every intercepted frame with a guarded cache entry now pays two full cache
snapshots and two cache_mutex acquisitions (try_lookup_without_guard_eval then
lookup, each snapshotting every entry in both buckets) where base held no lock
and allocated nothing. Bound the snapshot to the first backend match, and skip
building it when a precompile candidate was found.

A: The doubled snapshot+acquire on the guarded-hit path is real and structural
(distinct from the ~88 ns run-only-after-reset figure above, which does not cover
this path). The bounded-prefix half of the suggestion is unsound as stated:
backend_match runs lock-free after cache_mutex releases (that release before
guard/backend evaluation is the whole point of the snapshot), so the code cannot
know which entry is the first backend match while still holding the lock -- it
must capture a complete, stable snapshot and decide hit-vs-fallback afterward.
Stopping the snapshot loop early would require running backend_match under
cache_mutex, reintroducing exactly the Python-under-the-lock the design removes.
The precompile-skip half is a valid micro-optimization (the precompile branch
returns before cache_candidates is read), but both narrowings are subsumed by the
deferred RAII snapshot refactor tracked for this locking work, which collapses
the two acquisitions into one and is where the snapshot's shape should be tuned
with a runtime benchmark -- not guessed at here, since this checkout cannot build
to measure it.

Q: The per-region frame_state split changes CompileId.frame_id numbering -- each
region now allocates its own frame id for the same code object, shifting
tlparse/TORCH_LOGS labels and graph_id_filter's frame_id matching -- and the old
comment justified the split by dynamic-shape generalization, which frame_state no
longer drives. Why is it here, untested, in a locking commit?

A: The comment was stale and is corrected in this pass: the ExtraState
frame_state holds only "_id" (the frame-id counter); dynamic-shape generalization
moved to PGO's process-global code state, so the split does not touch it. The
split is kept deliberately -- an isolated region must number its compiles
independently so its tlparse/TORCH_LOGS labels stay coherent instead of
interleaving with the default scope. The renumbering is the intended observable;
a dedicated test for per-region numbering is worth adding and is tracked, but the
behavior is label/id bookkeeping, not guard or cache correctness.

Q: When reset() races a lookup on another thread, it parks a CLEAR_ALL (because
that lookup holds cache_python_depth > 0) and returns with the cache entries still
present and servable. Doesn't that break reset()'s clean-slate contract?

A: Yes, reset() becomes asynchronous under this specific race, and this is new
with releasing cache_mutex during guard evaluation (the old recursive mutex would
have blocked the peer instead). The window is bounded: every reader that matters
(lookup, _get_total_cache_entry_count, _debug_get_cache_entry_list) drains parked
evictions before it reads, so the first depth-zero holder wipes the entries and
the stale state is never observable from Python afterward. This is documented on
clear_in_place where the park happens.

Q: `apply_pending_evictions` has a thirteen-fold preamble -- all 13 call sites
repeat the same four lines declaring `reaped_precompile`/`reaped_cache`/
`reaped_evictions` before taking `CacheLock`, and `lookup()` now layers a fourth
ordering constraint (`reaped_*` before `python_depth`) enforced only by
declaration order, which a reformat could break silently. Why not an RAII holder?

A: An RAII holder owning the three containers and the lock, draining in its
destructor after unlocking, is the right structural fix and would replace the
comment-repeated-thirteen-times invariant with something the compiler enforces.
It is deferred deliberately: it touches all 13 sites and the drain ordering is
subtle enough that folding it into this locking commit would enlarge the diff
and the review surface without changing behavior. It is tracked as a follow-up
refactor; the current declaration-order discipline is correct, just not
structural.

Q: `torch/_dynamo/CLAUDE.md:274` still describes `ExtraState` as holding
"`frame_state` (dynamic shapes detection)", the same stale claim fixed in
`extra_state.h`. Why leave the doc twin stale?

A: Out of scope for this commit for a mechanical reason: a `.md` file under
`torch/_dynamo/` cannot be included in a commit here without crashing the
IMPORT_LINTER CI lint, so the doc twin cannot be touched from this stack. It is
noted so a maintainer can correct it in a separate, lint-safe change; the
load-bearing description in `extra_state.h` is already fixed.

Q: The region-exact lookup has no fallback to the default -1 bucket. Isn't that
a lost entry?

A: The region-exact lookup is the target end-state; the region-owned install
that passes a real id lands one PR up (#195911). At this commit every install
still passes the default id -1 (the region-owned install is #195911, higher in this stack), so the common precompile path is unaffected.
The one honest gap is transitional and not covered by "the stack merges
atomically": because ghstack lands PRs one at a time, in the window between this
PR and #195911 a frame under torch.compile(..., isolate_recompiles=True) gets a
region id >= 0 and a loaded CompilePackage on that code object matches nothing,
so it falls through to a normal compile (or is rejected under a serving stance
that forbids recompiles). This is deliberate -- keeping a -1 fallback here only
to delete it in #195911 would churn the exact bytes this PR establishes -- and
in that window (TORCH_CACHING_PRECOMPILE=1 plus isolate_recompiles=True, both
public knobs, so the combination IS reachable) the consequence is a recompile
instead of a served entry, or a fail_on_recompile error -- whose message, until
this round, listed precompiled guards the region-exact lookup never evaluated.
That message now filters the entries it prints by the frame's region (the filter
#195915 lands, pulled forward), so it blames the miss on nothing; rejecting the
combination outright was rejected because a hard error where base worked is worse
than a recompile. #195911 closes the window by installing into the context's
region. A permanent test cannot pin the miss, since by the stack head the same
frame is a hit.

Q: drain_pending_invalidations does a Py_INCREF on orig_code. Can that resurrect
a freed code object?

A: No. drain runs only at cache_python_depth 0, and every caller holds orig_code
alive for the duration -- the intercepted frame or the pybind handle owns a
reference -- so the INCREF always sees a live object. The invariant is
documented above drain_pending_invalidations.

Q: The cache counter (and use_lru) is a plain integer/bool, not an atomic. Isn't
that a race?

A: No, though the earlier phrasing of this answer overreached. It holds for
total_cache_entry_count, which is only ever touched under cache_mutex. use_lru
is looser: its setter takes no lock while the reads (create_cache_entry, both
move_to_front sites) are under cache_mutex. It is still safe -- a tearing-free
bool set once from a config knob -- so a plain type is correct, but the
justification is "benign unsynchronized publish of a config flag", not "always
under the lock".

Q: eval_frame_cpp.cpp does not check the PyUnicode intern for NULL. Bug?

A: It degrades safe: a NULL intern falls back to the slow lookup rather than
crashing, so it is a nit, not a correctness hazard.

Q: The PyThread_tss_set return value is ignored.

A: Intentional. The only failure mode is TSS-key-not-created, which cannot
happen after module init creates the key, and there is no meaningful recovery on
a per-frame hot path.

Q: compare_and_set_code_exec_strategy returns False when the code object has no
ExtraState, but get_code_exec_strategy_token reports generation 0 for an absent
state and set_code_exec_strategy_with_token creates one on demand. Can't a
read-then-CAS sequence then never succeed on a code object Dynamo has not
intercepted yet?

A: In the abstract yes, but no real caller hits it, and auto-creating the state
inside the CAS is worse. Every installer establishes state through
set_code_exec_strategy_with_token (which bumps the generation above 0) BEFORE it
ever calls compare_and_set, so the token it reads is never the absent-state 0.
Making the CAS create-on-absent was tried and reverted: init_and_set_extra_state
aborts if state already exists (a TOCTOU under concurrent first-touch), and
creating an ExtraState during a CAS resurrects state on a code object mid-
teardown. The absent-state case is genuinely "nothing to compare against", so
returning False -- caller re-reads, sees generation 0, and installs via
set_code_exec_strategy_with_token -- is the correct contract, not a lost race.

Q: The deferred-drain caveat's FAQ scopes the freed-snapshot window to "a third
thread", but ConvertFrameAssert.__call__ reaches it with the compiling thread
itself doing the freeing: it calls _get_cache_entries_for_region (twice, in the
isolate_recompiles_id >= 0 branch) and _get_total_cache_entry_count back to back,
each running apply_pending_evictions, while holding non-owning py::cast wrappers
from the first call; a parked CLEAR_ALL applied by the second call at depth 0
then frees the nodes behind those wrappers, and compute_cache_size reads a freed
node. compile_lock does not cover this prologue.

A: Correct, and the self-inflicted variant sharpens the caveat: the freeing
thread is the caller, not a third one, and the isolate_recompiles_id >= 0 branch
is the shortest path because it puts two drain-on-read calls in one statement
with the first result still live. The durable fix is the one the header already
names -- hand back owning references from _get_cache_entries_for_region the way
lookup()/create_cache_entry now do -- which closes both the third-thread and the
self-inflicted forms; short of that, draining once per __call__ or raising
cache_python_depth across the whole prologue removes the self-inflicted variant.
The finding is latent (no in-tree caller drives concurrent region reads against a
parked CLEAR_ALL yet) and the fix is C++ on the cache-lifetime path, which cannot
be authored or validated without a build here, so the caveat text is corrected to
drop the "third thread" scoping and the owning-reference fix is tracked as
follow-up.

Q: install() can finish with zero precompile entries: it drains then pushes, so if
a concurrent lookup holds cache_python_depth raised, install()'s own uninstall
parks a PRECOMPILE_ALL that the drain cannot apply, the pushed entry lands behind
it, and the next depth-zero holder splices it away -- the package installs and
serves nothing. The install-park comment also pointed at a PR FAQ that did not
exist.

A: Real. The comment is corrected to describe it precisely (install defeating its
own install under a concurrent lookup) and to drop the dead FAQ pointer. It is the
same non-owning / deferred-drain class as the caveats below: the durable fix is
C++ on the cache-lifetime path -- park the install behind the parked eviction, or
stamp installs with a sequence so a drained PRECOMPILE_ALL only removes entries
older than itself -- and cannot be authored or validated without a build here.
Latent: no in-tree caller drives a concurrent lookup against a self-parked
PRECOMPILE_ALL yet. Tracked with the owning-reference follow-up,
#196394.

Q: Parked evictions get no candidate-side filter. drop_pending_invalidated_candidates
keeps a parked invalidation from serving, but there is no equivalent for parked
evictions, so _reset_precompile_entries / _clear_cache_entries_for_region can
return having removed nothing while in-flight lookups keep serving -- and since
uninstall() pops the installed globals first, a stale serve LOAD_GLOBALs a name
that is gone (NameError).

A: Real, and not a regression (base cleared the list under the iterating thread, a
UAF). The symmetric one-line candidate-side eviction filter is the right fix and
is the same C++ cache-lifetime change deferred above. The uninstall() global-pop
ordering is separately addressed on the Python side by resetting entries before
popping globals (see #195911's teardown-loop swap). Deferred here because the only
observable consequence is unreproduced and the filter cannot be built or validated
in this environment. Tracked with #196394.

Q: extract_cache_entry is the one remaining borrowed-CacheEntry* handout: it
returns &it->second.front() after the reaped_* locals (whose destructors run
Python) go out of scope, and dynamo__custom_eval_frame hands that pointer to
dynamo_call_callback, which ConvertFrameAssert.__call__ carries through the whole
_compile at depth 0 with cache_mutex unheld. The header caveat and the FAQ name
only _get_cache_entries_for_region.

A: Correct -- same shape, same fix. The extra_state.h caveat now names
extract_cache_entry alongside _get_cache_entries_for_region as needing owning
references. The fix is C++ on the cache-lifetime path and is deferred with the
rest of that class; it cannot be authored or validated without a build here.
Tracked with #196394.

Q: _has_precompile_entries is the one region-taking binding without a
`region_id >= -1` TORCH_CHECK_VALUE, while every sibling got one -- and it runs on
every served call. Isn't it the odd one out?

A: Yes, and the omission is benign. An out-of-range id (say -5) simply fails the
`entry.isolate_recompiles_id ==` comparison and the function returns false, the
same result as any valid id with no matching entry -- there is no buffer indexing
or negative-index hazard behind it, unlike the paths that guard. Adding the check
to match the sibling sweep is correct and belongs with the other C++ range-check
hardening tracked in #196394 (this stack cannot build C++ to verify a behavioral
C++ change in isolation); it is a consistency nit, not a correctness gap, and the
hot-path comment already notes the function does no Python and takes no lock.

Q: `_load_precompile_entry`'s comment calls the install-defeats-itself race "a
tracked follow-up" with no link, and it reproduces: under a concurrent lookup a
raw `_reset_precompile_entries` + `_load_precompile_entry` sequence parks a
PRECOMPILE_ALL that the pushed entry then lands behind, so the install serves
nothing.

A: Real at this commit for that raw sequence, and closed for the only production
caller one PR up: #195911 keys `CompilePackage.uninstall()`'s eviction by owner
token and mints a fresh token per install, so the parked owner eviction cannot eat
the reinstall (`test_reinstall_survives_an_eviction_parked_by_uninstall` in
#196120 pins it). The raw sequence still loses and is now listed in
#196394 (sequence-stamping evictions is a C++ change that needs a
build to verify); the comment now says both.

Q: This diff introduces a parked-eviction state machine, a GIL-releasing
recursive cache lock, thread-local region ids, per-region frame state and 12 new
bindings, and its only test change is a docstring. Nothing here exercises any of
it.

A: The coverage is one PR up, in #196120, one test per bullet of the ask: eviction
parked behind a live lookup then applied by the next depth-zero holder
(`test_region_clear_from_inside_a_lookup_is_parked`,
`test_precompile_reset_from_inside_a_lookup_is_parked`); reset_code from Python
run by a guard (`test_reset_code_from_python_run_by_lookup_is_safe`, plus the
skipped racing variant tracked in #196394); invalidate mid-lookup
(`test_invalidation_racing_an_in_flight_lookup_parks_and_drains`,
`test_invalidate_targets_the_entry_by_guard_manager_identity`); install after a
parked reset (`test_reinstall_survives_an_eviction_parked_by_uninstall`); the
thread-local id (`test_isolate_recompiles_id_is_thread_local`); and the CAS's
stale generation across reset_code
(`test_exec_strategy_token_and_compare_and_set`). They live in the next PR so this
one stays a reviewable C++ change under the size gate.

Q: `torch._dynamo.reset()` now returns with a code object's cache entries still
present and servable whenever any thread is inside a lookup on it. That changes a
public API's contract; it should be an explicit decision, not only a C++ comment.

A: Agreed, and now stated where users read it: `torch._dynamo.reset()`'s docstring
carries an NB describing the asynchronous clear under a concurrent lookup and
pointing at `clear_in_place`. Making the clear synchronous (wait for depth zero,
or gate the Python-side clear on the C++ clear having applied) stays deferred in
#196394.

Q: Per-region `frame_state` makes the `frame_compile_id >=
accumulated_recompile_limit` fallback per-region, removing the only backstop for
non-growing recompiles (invalidated guard managers), and grows `FRAME_COUNTER` /
`FRAME_COMPILE_COUNTER` per (code object, region) -- measured +20/+20 for 20
`isolate_recompiles=True` wrappers of one function.

A: Correct, and the header comment says so verbatim. The growing case stays capped
globally by `total_cache_entries_all_regions`; the escape is exactly
region-minting loop plus invalidated guard managers. A per-code-object limit
counter kept separate from the per-region display id is the fix; it is filed as
#196495 and cited from the comment rather than folded into this
locking change.

Q: `_torchdynamo_force_callback_on_cache_miss`, `_torchdynamo_cache_key` and
`_enable_precompile_cache_keys` have no producer at this commit, so the marker
lookup, the run_only override and the recursive_callback demotion skip on the
per-frame hot path are unreachable here.

A: Their producers are higher in the stack: `_torchdynamo_force_callback_on_cache_miss`
is set by `eval_frame.py`'s fail_callback under the serving stance (#195915);
`_enable_precompile_cache_keys()` and `_torchdynamo_cache_key` are set by
`precompile_package.py` (#195917); and #196120 pins them
(`test_force_callback_on_cache_miss_marker_overrides_run_only`,
`..._reaches_a_recursive_frame`,
`test_cache_key_lookup_is_off_until_a_cache_key_backend_exists`). The C++ lands
first so each consumer is a Python-only change.

Q: The `compile_lock` requirement is enforced on one of three spellings of
`reset_code`: the raw `torch._C._dynamo.eval_frame.reset_code` and
`torch._dynamo.decorators.reset_code` (re-exported by the `dir()` loop) bypass it.

A: Fixed for the trap that mattered: `decorators.py` no longer re-exports the raw
binding (its TYPE_CHECKING import is gone and the loop skips the name), so
`torch._dynamo.reset_code` -- the wrapper that takes the lock -- is the one
Python-level spelling. Renaming the C binding to `_reset_code_unlocked` is the
structural version and touches init.cpp/.pyi; nothing in-tree calls the raw
spelling, so it is left for a build-verified follow-up.

Q: `_reset_precompile_entries_for_owner` uses `PyCode_Check` "matching the sibling
bindings added in this commit", but `_clear_cache_entries_for_region` and
`_reset_precompile_entries_for_region`, added in the same commit, use the
`py::module::import("types")` form.

A: Fixed: both now use `PyCode_Check`, and the comment says the pre-existing
bindings keep the import form (converting them would add lines for no behavior).

Q: The `drop_pending_invalidated_candidates` comment reads as if it closes the
wrong-graph hazard, but an `invalidate()` that arrives after `lookup()` releases
`cache_mutex` parks and the in-flight lookup can still serve the entry it named.

A: Comment fixed to say exactly that: the filter covers invalidations parked
BEFORE the snapshot; a later one rides to the next lookup.

Q: `lookup_optional`'s NULL-name branch returns without `PyErr_Clear()` although a
failed `PyUnicode_InternFromString` leaves a MemoryError set, breaking the "WITHOUT
raising" contract, and its comment says the statics are initialized "at module
init" when they are function-local.

A: Both fixed: the branch clears the error and the comment says "on its first
call".

Q: `CacheCandidate` is defined twice (`lookup` and `try_lookup_without_guard_eval`);
`fullgraph_compiled_frame_count` is consulted per frame with no comment on its
process-global scope; three readers skip the parked-invalidation filter.

A: The duplicate struct is a mechanical hoist that changes no behavior; it is left
for the owning-reference follow-up (#196394) that reworks the same two functions,
since C++ cannot be compiled here. The frame-count comment is a one-line nit left
as is. The three readers (`_get_cache_entries_for_region`,
`_get_total_cache_entry_count`, `_debug_get_cache_entry_list`) feed recompile
reporting, accounting and the collective gate, never serving, so a parked
invalidation cannot make them serve a wrong graph.

Q: pr-sanity-checks is red -- this commit is 2027 lines.

A: Trimmed under the gate by condensing the longest added comment blocks (same
facts, fewer lines) and by the `PyCode_Check` conversion above, while absorbing the
reset() docstring, the decorators.py fix and the two comment additions this round
asked for.

Q: Once `_enable_precompile_cache_keys()` fires, `get_backend()` returns the cache
key, so `CacheEntry::backend` holds the key while Python's `innermost_backend` only
follows `_torchdynamo_orig_backend`; `get_guard_fail_reason_helper` then reports
"different backend callables. Cached backend: str ..." with functools.partial
advice. A lying diagnostic?

A: Yes, for the description only: the classification is right (a key mismatch IS
a backend mismatch) and the C++ `backend_match` compares key-to-key, so no wrong
graph is served. Fixed here at the site named: `describe_backend` renders a
non-callable cached side as its `_torchdynamo_cache_key`, the reason says
"backend cache keys" instead of "callables", and `_CacheEntry.backend` is typed
`object` in the .pyi to match the header's "must not assume callable". Rendering
the NEW side as a key needs the un-unwrapped callback chain (a Python twin of
`get_backend`), which lands with the only producer, `_PrecompileBackend` in
#195917, together with a recompiles-log test; it has no producer at this commit.

Q: The `_has_precompile_entries` comment says no Python runs and the CacheLock
wait is the only place the GIL can drop, but the drained nodes' destructors
(`~CacheEntry` sets `guard_manager.cache_entry`, `~PrecompileEntry` drops three
py::objects) run Python once the lock releases, and the read-looking predicate
drains a parked CLEAR_ALL as a side effect on every served call.

A: Comment corrected on both counts: no Python UNDER the lock; the call drains
parked evictions first (a parked CLEAR_ALL empties the cache there, the
drain-before-read contract every reader follows) and the reaped nodes die after
the lock releases, where their destructors can run arbitrary Python.

Q: `drain_pending_invalidations` destroys its drained py::objects under
`cache_mutex` (a parked entry's old guard_manager can be the last reference, so
arbitrary user `__del__` runs under the lock), unlike its two siblings that hand
their records out to die after the lock. Unintentional asymmetry?

A: The hazard is the one the lock-ordering comment in extra_state.h already names
and accepts (a hot-path drain is rare); the asymmetry is real and the
`dead_invalidations` out-param at the eight call sites is the right symmetric fix
-- it belongs with the RAII reaper-holder rework tracked in #196394
(C++ that cannot be built or verified here). A `CachePythonDepth` spanning
`pending` would not fix the ABBA (Python still runs under the lock); it only turns
a re-entrant reset from apply into park, unnecessary at depth 0 with no live
iteration.

Q: On the guard-error returns, `e.restore()` runs before the `reaped_*`
containers die, so their Python destructors run with an exception set.

A: Real and latent (it needs a parked region/precompile eviction drained in the
same lookup plus a raising guard in a surviving bucket). The mechanism differs
from the review's: `cache_entry`/`extra_state` are plain instance attributes of
`GuardManagerWrapper`, not pybind setters, so nothing terminates; the risk is that
a generic setattr's `_PyType_Lookup` can clear the pending exception on a
method-cache miss, so `lookup()` returns NULL without an exception set and the
frame raises SystemError instead of the guard's error. The fix (restore after the
reaped nodes die, or clear them before `e.restore()`) is C++ and is tracked in
#196394; the comment above the declarations now records it.

Q: `id + 2` in `int64_t` is signed-overflow UB for `INT64_MAX`, reachable through
the private binding; the ASAN job builds with `-fno-sanitize-recover`.

A: Fixed on both sides of the TSS round trip with unsigned arithmetic
(`(uint64_t)id + 2` on the write, `(uint64_t)(uintptr_t)value - 2` on the read);
cast-only C99, unreachable from torch.compile.

ghstack-source-id: 971bf56
Pull-Request: #195355
bobrenjc93 added a commit that referenced this pull request Sep 9, 2026
Guards on globals resolve against the traced function's global scope.
`AOTCompiledFunction.deserialize` takes `f_globals` for this, but
`AOTCompiledModel.deserialize` never passed one, so a reloaded module artifact
rebuilt its guards against only what the serialized bytecode reconstructs, and
a global Dynamo specialized away failed every call with "KeyError on G['...']".

`AOTCompiledModel.deserialize` now resolves the scope from
`model.forward.__globals__` and passes it through a new keyword-only
`guard_globals`, kept apart from `_extra_globals`, which feeds the bytecode.
Guards read the live dict by reference: a rebind after load redirects dispatch,
and a missing global fails the guard with no fallback to serialized values. A
`forward` without `__globals__` warns and uses the reconstructed scope. Since
Dynamo roots guards at `__import_*` aliases it mints into the tracing
process's globals, loading inserts the recorded `__import_*` aliases and the
`__builtins_dict___N` key into the live dict without overwriting existing keys. A baked-in `__builtins_dict___N` would otherwise collide with the identical name a later compile in that module regenerates -- `unique_id` is a fresh per-process counter a load never advances -- so `install_global` now skips any name already bound in the global scope. Both public docstrings document this.

It also adds the CPU codegen target the precompile package layer needs.
`SystemInfo` records `(machine, vec_isa, vec_isa_width, vec_isa_macro, simdlen,
march)` for an artifact holding generated CPU code, and the load gate compares
the *resolved* target `(machine, vec_isa, vec_isa_width, vec_isa_macro)` against
what `pick_vec_isa()` picks on the host: the artifact's kernel source was tiled
for the capture ISA and the host recompiles it with its own. `pick_vec_isa()`
already folds the raw knobs (`cpp.simdlen` and `ATEN_CPU_CAPABILITY`; `march` never reaches it) into the
ISA it returns, so the resolved triple is the complete key; simdlen and march
stay in the recorded tuple for diagnostics but do not gate. The sample is taken
under the backend's own inductor config: `torch.compile(options={...})` builds a
`_TorchCompileInductorWrapper` that patches config such as `cpp.simdlen` only for
the duration of `backend()`, which has already returned by the time we sample, so
we re-apply that config while reading `SystemInfo.current()`; otherwise the
fingerprint would record the ambient ISA rather than the one the kernels were
tiled for. `emits_native_code(backend_name)` exempts eager-family artifacts from
the toolchain probe and the comparison.
`_graph_device_types` scans the whole graph instead of reading the first meta
value's device, which misreported a SymInt placeholder as "cpu" and let a mixed
cpu+accelerator graph skip the check.

The Triton-version and GPU-model checks now exempt off the artifact (the
receiver), not the loading host: an artifact built with Triton is rejected on a
Triton-less host, where before the host-side exemption let it load and then fail
later at kernel load.

User-visible: `AOTCompiledModel.__call__` raises `RuntimeError("No AOT compiled
graph matched ...")` listing why each input was rejected instead of running
graph 0's guards, and a result opted out via `disable_guard_check()` is
consulted only after every guarded result was rejected.
`CompilePackage.__init__`'s `requires_native_backend_compatibility` is
keyword-only.

Test Plan:

```
python test/dynamo/test_aot_compile.py
python test/dynamo/test_package.py
python test/test_precompile.py
```

The scope tests fail on the pre-change tree with the KeyError. Codegen-target
tests patch `_current_cpu_codegen_target` instead of
depending on host hardware.

Authored with an AI assistant.

FAQ

Q: Why does the gate compare only the resolved ISA (machine, vec_isa,
vec_isa_width, vec_isa_macro) and not simdlen and march too? An earlier version
compared all of them exactly.

A: Because pick_vec_isa() already folds simdlen and ATEN_CPU_CAPABILITY (march never reaches pick_vec_isa; it only changes how the same tiled source is compiled)
into the ISA it resolves -- a simdlen that caps the width picks a narrower ISA,
so the recorded width and macros already reflect it -- the resolved triple is
the complete correctness key. Comparing the raw simdlen/march knobs on top of it
is not merely redundant, it is wrong in two ways. First, it rejects an artifact
this host can reproduce: an artifact captured under cpp.simdlen=256 is loadable
on any host that resolves to the same 256-bit ISA, whether the host gets there by
default or via ATEN_CPU_CAPABILITY, yet a raw-simdlen comparison rejects the
default-knob host. Second, it makes the documented escape hatch ineffective --
setting cpp.simdlen to fix an ISA mismatch would only trade the ISA error for a
simdlen error. A related bug the exact comparison hid: the sample was read after
backend() returned, so the _TorchCompileInductorWrapper's config patch (e.g.
cpp.simdlen) had already exited and the fingerprint recorded the ambient ISA,
not the one the kernels were tiled for -- so an artifact could reject its own
build host and accept a wider one. This commit re-applies the wrapper's config
while sampling so the recorded ISA is the one the kernels were actually built
for, and gates on that resolved ISA. The gate is still fail-closed: a genuine
ISA/width/macro mismatch is refused, and the caller can fix it with
ATEN_CPU_CAPABILITY or cpp.simdlen.

Q: A wider host ISA (AVX-512 loading an AVX2 artifact) is a superset, so why
reject it instead of running the narrower kernels?

A: A wider ISA is not a superset here. The kernels were tiled for the narrower
width, so the wider host's masked loads zero-fill the lanes the narrow tiling
never wrote and its unmasked reductions then read them, changing the result.
The comparison is exact -- and it compares the recorded ISA name, its bit
width, and its build macros together -- because
VecSVE(128), VecSVE(256), and VecNEON overlap in name and/or width and only the
full fingerprint tells them apart.

Q: When the loading host has no usable CPU codegen target at all (no C++
toolchain), the check hard-refuses rather than loading best-effort. Isn't that
too aggressive?

A: Fail-closed on purpose. An artifact that recorded a CPU codegen target holds
vectorized CPU kernels that must be compiled to run, and a host with no
toolchain cannot build them, so there is nothing to run best-effort; refusing
with a clear message beats failing deep in compilation. Eager-family artifacts,
which bake no native code, are exempted up front by emits_native_code(), so this
refuses only artifacts that genuinely need a compiler.

Q: The CPU codegen fingerprint records tuple(vec_isa.build_macro()), but for
AVX-512 that macro is the constant CPU_CAPABILITY_AVX512 and does not encode the
bf16/fp16 probe. Two x86 hosts that differ only in AVX-512-BF16 / AMX-FP16
support then produce an identical fingerprint, yet build_arch_flags() appends
-mavx512bf16 / -mamx-fp16 only where supported -- so a capture host bakes bf16
intrinsics and a loading host without them recompiles wrong. Isn't that a
collision?

A: Correct, and a real gap: build_macro() captures the ISA family but not the
bf16/fp16 arch-flag suffixes, so the fingerprint is coarser than the code the
recompile actually emits. The fix is to record build_arch_flags() -- which
subsumes the macros and the -mavx512bf16 / -mamx-fp16 / SVE -msve-vector-bits
suffixes -- rather than build_macro(). That changes the recorded fingerprint
semantics and can only be validated by exercising the codegen path across ISAs,
so it is tracked as a follow-up rather than folded into this commit unverified;
until then the check is correct on ISA family and width and misses only the
same-family bf16/fp16 sub-variant. When that follow-up records build_arch_flags(), note the ordering trap: VecAVX512/VecAMX set _arch_flags as a side effect of their __bool__ probe, so the recorder must read build_arch_flags() only after bool() has run on the instance.

Q: An artifact saved under one backend and loaded under another disagrees on
whether the ISA gate applies (an inductor-saved entry loaded in an eager
session, or the reverse). How is that reconciled?

A: initialize() no longer clobbers _requires_native_backend_compatibility with
the loaded entry's value, so the constructor value -- taken from the backend the
caller is loading under -- stands. That fixes the load gate: an eager
constructor can no longer disarm the ISA check an inductor entry needs, so the
load never relaxes a host. The mirror direction is subtler: an inductor-saved
entry loaded in an eager-family (e.g. aot_eager) session and then re-saved
(literal "eager" records no bundled artifact, so only aot_eager reaches this)
would strip the fingerprint.
That is closed by the monotone OR-accumulate in #195913
(self._requires_native_backend_compatibility |= dynamo.requires...), which
neither the entry nor the constructor can relax; this commit removes only the
clobber the load gate needed.

Q: _graph_device_types walks the FX graph with its own heuristic instead of
reading V.graph.device_types, so it both over-reports (a false "cpu" for unused
placeholders arms the toolchain probe) and under-reports (string device= specs
are invisible). Why reimplement it?

A: The FX-level walk runs before inductor lowering, where V.graph.device_types
is not yet populated, so it cannot be read here; the heuristic is deliberately a
superset because arming the CPU toolchain probe for an artifact that turns out
to hold no CPU code only costs a load-time ISA check the caller can satisfy,
which is the fail-closed direction. String device= kwargs and a .to() device
argument are read, but only in those device positions -- not from any flat arg
-- because an autocast device type is a plain string positional of
_enter_autocast, and trusting every string leaf would inject a phantom "cuda"
into a CPU-only graph (unloadable on the very host that saved it) or a phantom
"cpu" from torch.utils.checkpoint's unconditional autocast("cpu") (arming the
ISA gate on an accelerator-only artifact). Device-carrying method calls beyond
.to()/.cuda()/.xpu() are still narrowing work tracked separately.

Q: A `functools.wraps` wrapper assigned to `forward` silently yields the wrong
guard scope: `get_traced_fn` never unwraps `__wrapped__` and `_get_signature`
uses `follow_wrapped=False`, so a wrapper defined in a different module resolves
guards against the decorator's module with no warning -- the very failure this PR
fixes, in a shape the fix does not cover. Why leave it?

A: The silent case is asymmetric wrapping only: `functools.wraps` copies
`__module__`/`__name__`/`__qualname__` but not `__globals__`, so when the same
wrapper is present at both save and load the scopes agree and the artifact is
correct. It breaks only if the capture and the runtime wrap `forward` in
different modules, which is not a shape any real serve path produces (the loaded
callable installs onto the recorded code object). Unwrapping `__wrapped__` and
comparing `original_code` against `traced_fn.__code__` to warn on the mismatch is
the right hardening and is tracked as follow-up; it is a detection improvement,
not a correctness fix for the paths this PR serves.

Q: Seeding `__builtins_dict___N` into the live module globals makes a later
`torch.compile` in that same module crash. `unique_id()` is a process-global monotonic
counter that a load-only process never advances, so the artifact bakes in the capture
process's `__builtins_dict___0`, deserialize writes that key into the module `__dict__`,
and the next `OutputGraph.__init__` there regenerates `__builtins_dict___0` and hits
`CleanupHook.create`, which raises because the name is already in scope. This is every
caller of the default `guard_filter_fn`, not just those who keep global guards.

A: Correct, and it was a real crash -- reproduced with the default filter. Fixed here in
`OutputGraph.install_global`: after minting a name from `unique_id`, it now skips any
name already bound in `self.global_scope` (`while name in self.global_scope: name =
unique_id(prefix)`) before installing, so a later compile that regenerates a baked-in
`__builtins_dict___N`/`__import_*` name transparently picks the next id instead of
colliding in `CleanupHook.create`. `unique_id` is monotonic, so the loop always
terminates. The seeding itself stays -- guards rooted at those names must resolve -- and
the collision it could cause on the next compile is what this fix removes.

Q: The AOT path inserts the `__import_*` aliases and the `__builtins_dict___N`
key straight into the caller's dict, without the `CleanupHook.disown` the
precompile path does first and without any `_installed_globals`/`uninstall`/
`__del__` bookkeeping -- and because the default `guard_filter_fn` drops every
`is_global` guard, the common path mutates a torch namespace for guards that were
filtered out. Isn't the missing cleanup a hazard?

A: The insertions are bounded and idempotent (`if name not in scope`), so this is
permanent-and-untracked, not unbounded growth, and it mirrors what tracing itself
already does into the same namespace at `symbolic_convert`. The precompile path
needs `disown` and `_installed_globals` because it supports `unload()`; the AOT
artifact has no uninstall surface by design (it is a load-and-run function, not an
installer), so there is nothing to take back out. Seeding a torch namespace when
the filter dropped the global guards is wasteful but harmless -- the keys are
inert if unread, and the one active hazard, a later compile colliding on a baked-in
name, is closed by `install_global` skipping already-bound names (see the collision
FAQ below). A cleanup API on `AOTCompiledFunction`/`AOTCompiledModel` and
gating the seed on whether global guards survived are both reasonable follow-ups;
neither changes a result today.

Q: `_backend_emits_native_code` classifies the same backend differently by
entrypoint and never classifies instance backends: `torch.compile(backend=eager)`
correctly yields `False` (the wrapper stamps `compiler_name`), but
`torch._dynamo.optimize(eager)` stringifies the raw callable to native, an
instance like `CompileCounter` has no `__name__`, and the aot path reads
`"unknown"` after `get_compiler_fn` erased the string. Worse, a user backend
whose function is named `eager` is silently exempted from the ISA gate. Why is
this acceptable?

A: The classifier is fail-closed by construction: an unrecognized backend is
assumed to emit native code and pays the ISA check, which only ever refuses a
load the caller can satisfy. The two "misclassified as native" cases
(`optimize(eager)`, instance backends) therefore cost a spurious toolchain probe,
never a wrong result. The one genuinely fail-open direction -- a user callable
coincidentally named `eager`/`aot_eager` tripping the name blacklist -- requires a
user to name their own inductor-lowering backend after an eager builtin, which is
not a shape that occurs in practice; a name-based blacklist is the only signal
available before `get_compiler_fn` runs, and tightening it (identity match rather
than name, and stamping `compiler_name` on `register_backend`) is tracked
separately. The `"unknown"` the aot path records is the same fail-closed default.

Q: `_NO_NATIVE_CODE_BACKENDS` omits every non-inductor backend that is not
eager-family -- `ts`/`aot_ts`, `invoke_subgraph`, `cudagraphs`, `openxla`, `tvm`,
the `*_TESTING_ONLY` gm-passthrough backends and the minifier backends -- so all
of them are now gated on host ISA even though none emit inductor CPU kernels.
Shouldn't they be exempt?

A: Same fail-closed rationale: these backends are rare enough that the exemption
list intentionally enumerates only the eager family (the common no-codegen path),
and everything else pays a host ISA check. (Correction: that check is NOT
satisfiable on every host -- ATEN_CPU_CAPABILITY / cpp.simdlen can only lower a
host's resolved ISA, never raise it, and a toolchain-less host resolves no target
at all -- so a user backend that bakes no native code now has an opt-out on the
aot_compile path too: declare `emits_native_code = False` on the backend callable
and the artifact records no codegen target and skips the gate, mirroring the
package's requires_native_backend_compatibility.)
Enumerating each additional no-native-code backend is a pure widening of the
exemption with no correctness stake and is deferred; the current list is
conservative in the safe direction.

Q: The mixed cpu+accelerator device change is a load-time behavior change on
existing artifacts that neither the description nor the FAQ mentions: pre-PR a
mixed graph whose first meta value was a CPU tensor recorded `device_type="cpu"`
and skipped the GPU check, so it loaded on a host lacking the accelerator;
post-PR the device set is unioned and every device is checked, so it now
hard-fails there. Isn't that a BC break?

A: It is an intentional correctness fix, and the new answer is the right one: an
artifact that genuinely uses an accelerator must not load on a host without it,
and the pre-PR behavior (silently skipping the GPU check because a CPU tensor
happened to be first) was the bug. The only wrinkle is message ordering -- when
both the accelerator is absent and the ISA differs, the user sees the ISA message
first because `sorted({"cpu","cuda"})` puts codegen first -- and that is
deliberate (ISA skew is fixable via `ATEN_CPU_CAPABILITY`/`cpp.simdlen`, device
absence is not, so leading with the fixable one is the better default). The
behavior change is called out here for the record.

Q: `check_codegen=False` returns early inside the GPU block, so for an
eager-family artifact carrying a cuda device the `toolkit_version`,
`triton_version` and `gpu_name` checks are all skipped -- and `gpu_name` is not a
"describes generated code" check the way the gate's comment justifies. Isn't
skipping `gpu_name` for an eager artifact wrong?

A: Intentional. An eager-family artifact bakes no device-specific code -- no
Triton kernels, no toolkit-versioned cubins, nothing pinned to a particular GPU
model -- so it is portable across accelerators of the same family, and all three
GPU checks exist to protect generated code that an eager artifact does not carry.
Gating them together under `check_codegen` is therefore correct for what the
artifact actually contains; `gpu_name` guarding an eager artifact would refuse a
load that is in fact safe. The comment's "describes generated code" framing is
about why the gate exists, not a per-check taxonomy.

Q: When the loading host reports no CPU codegen target at all,
`_cpu_codegen_target_problem` returns a message that does not name the machine
the artifact was built for. Shouldn't the message name it?

A: The enclosing `RuntimeError` already prints the full cached tuple
(`cached={self.cpu_codegen_target}`, machine included) next to `current=...`, so
the machine is named at the call site. The per-branch string only supplies the
component-level reason for the mismatch, and a `None` host has no component to
compare against -- duplicating the machine there would be redundant.

Q: pick_vec_isa() at save is expensive (seen around 18s cold). Why pay it there?

A: It is gated on needs_cpu_codegen, so only artifacts that will emit native
CPU code reach it, and pick_vec_isa() caches its result -- the probe runs once
per process, not once per save. Recording the resolved ISA at save is what lets
load fail closed against a host that would pick a different ISA; deferring the
probe to load would move the cost, not remove it.

Q: An artifact captured under options={'cpp.simdlen': N} loads only on a host
that resolves to N. Doesn't passing the same options={'cpp.simdlen': N} on the
loading side fix it?

A: No, and this is worth stating explicitly -- including the sharp corner that it
fails even on the very machine that built it, in the same process. On load there is
no backend wrapper, so check_compatibility() samples SystemInfo.current() ambiently
-- outside any torch.compile(options=...) patch, which only takes effect once
tracing begins. simdlen lived only in the per-compile options, never in the global
config, so nothing re-applies it at load and the build host re-resolves to its
native (wider) ISA and rejects its own artifact. The documented escape hatch on the
loading host is therefore the *global* torch._inductor.config.cpp.simdlen (or the
ATEN_CPU_CAPABILITY env var), set before the load, not the options= form. The
capture-time half is fixed here by widening the config.patch context to cover
CompileArtifacts / AOTCompiledFunction construction, so __post_init__'s self-check
samples under the same ISA the fingerprint recorded. Auto-re-applying the recorded
simdlen at load (so the round-trip needs no env/config) is a real improvement, but it
belongs with the load-side recompile-config plumbing that lands with the store-reload
work in #195913, not this commit's gate; the AOT load path deserializes bundled
kernels rather than recompiling from source, so the gate is a run-safety check and the
escape hatch is the supported reload path until then.

Q: The codegen fingerprint is armed from the backend and device
(emits_native_code(backend_name) and "cpu" in device_types), not from whether
inductor actually emitted a cpp kernel. An artifact whose CPU output is all
extern calls (torch.mm lowering to BLAS) still records a target, so the
load-time gate pays the full pick_vec_isa() dry-compile (~19s measured) for
nothing. Arm it from whether a cpp kernel was emitted.

A: The over-arming is deliberate and errs toward correctness. The gate rejects a
host whose resolved ISA differs from the one the kernels were tiled for; if we
under-arm -- record no target when a cpp kernel WAS emitted -- the gate accepts
an ISA-incompatible host and runs a mistiled kernel, a silent-wrong-result/crash
hazard that is strictly worse than a slow load. Arming on "the backend can emit
native CPU code" is the conservative superset that never under-arms. Precisely
detecting "inductor emitted zero cpp kernels for this graph" means introspecting
the compiled artifact's kernel sources, which is not reliably available at this
call site and, per the measurement's own method, needs a built inductor to
validate that the narrower signal never drops a real target; narrowing the arming
to it (and skipping the dry-compile when no cpp kernel exists) is the right
optimization but is tracked as follow-up rather than attempted without a build.
The one-time load cost is also amortized by TORCHINDUCTOR_CACHE_DIR.

Q: The remedy sentence points the user at ATEN_CPU_CAPABILITY /
torch._inductor.config.cpp.simdlen, but on fbcode/x86 pick_vec_isa()
short-circuits to VecAVX2() before reading either knob, so neither can move the
resolved ISA and _current_cpu_codegen_target() can never return None there. The
hint is inert in fbcode.

A: Correct that on fbcode/x86 pick_vec_isa() returns VecAVX2() unconditionally,
so the two knobs the hint names cannot change the resolved ISA and the escape
hatch is a no-op there. The hint is advisory and accurate off fbcode (OSS x86,
where valid_vec_isa_list()/cpp.simdlen/ATEN_CPU_CAPABILITY do resolve the ISA),
which is where an ISA-mismatch rejection is actually reachable; on fbcode the
fixed AVX2 target means two builds on the same machine class agree and the gate
does not fire in the first place. Conditioning the message on config.is_fbcode()
to drop the inert knob suggestion is a reasonable message-only refinement that
changes no gate behavior, deferred with the other fbcode-specific paths that
cannot be validated in this environment.

Q: The two store reload APIs -- DynamoStore.load_package and
DynamoCache.load_and_install_package -- construct CompilePackage(fn,
entry.dynamo) with the constructor default requires_native_backend_compatibility=True
and no backend to derive it from, and initialize() restores _device_types but
not the flag. So an eager package round-tripped through a store upgrades to
native on re-save: cache_entry() pays the pick_vec_isa() probe and stamps a
cpu_codegen_target onto an artifact that bakes no native code, which then
hard-refuses on an ISA-different host. Restore the flag from the entry here (it
records the value), or thread the kwarg through the store APIs.

A: Correct that at this commit the harm is real: the two store paths pass the
bare default True (the eval_frame path is the only one that derives the
constructor value from the backend, so the existing "the constructor value,
taken from the backend, stands" FAQ does not cover the store paths), and this
commit's cache_entry() probes eagerly, so a store round-trip of an eager package
re-saves as native. But the suggested entry-authoritative fix is the wrong
resolution, because at this commit the flag has no compile-path accumulation: it
is written once at construction and never OR'd by a later native compile. Making
the reloaded entry authoritative would fail OPEN in the mirror direction -- a
native session that reloads an eager entry (flag False) would then run native
compiles with the ISA gate disarmed and load a kernel built for another target
on an incompatible host, a silent-wrong-result hazard strictly worse than the
wasteful-but-safe over-arm this comment describes. The correct resolution lands
higher in this same stack (#195913): the flag is made monotone
(self._requires_native_backend_compatibility = self._requires_native_backend_compatibility
or dynamo.requires_native_backend_compatibility, which neither a reload nor a new
compile can relax), and the pick_vec_isa() probe is deferred out of cache_entry
-- the reload path stamps _system_info via SystemInfo.current(cpu_codegen=False)
carrying the entry's recorded target (None for an eager artifact) straight
through re-save, and the probe fires only in update_device_type during an actual
cpu-bearing compile. At the stack tip the store-reloaded eager package therefore
pays no probe and stamps no target on re-save -- exactly the harm this comment
asks for -- while a genuinely native new compile still arms the gate fail-closed.
The eager over-arm visible here is an intermediate-state artifact removed by that
deferred-probe change above it, not a shape the stack ships; adopting a local
entry-authoritative fix here would have to be reverted to reach the safe design.

Q: The CPU-codegen half of this commit -- SystemInfo, emits_native_code, the
check_compatibility rework, the fingerprint gate and roughly half the new tests
-- is an independent feature from the AOTCompiledModel.deserialize guard-scope
fix in the title, and it is the part that can newly hard-refuse a load. Split it
into (1) the guard-scope fix, (2) the _graph_device_types rewrite, and (3) the
CPU codegen fingerprint and gate so each lands on its own evidence.

A: Agreed on the logical separation, and in a fresh stack these would be three
commits. This commit sits deep in a 24-PR ghstack whose upper commits (the
capture session, save() entry point, and the monotone OR-accumulate /
deferred-probe changes that this very FAQ leans on) already depend on the
SystemInfo and emits_native_code surface introduced here; splitting it now
reindexes every PR above it and restarts their in-flight CI, which is a real cost
the reviewer explicitly flagged as "your call". The three parts are individually
reviewable in place: the guard-scope fix is the first three paragraphs and its
KeyError-reproducing tests, _graph_device_types is self-contained, and the
codegen gate is the part the FAQ scrutinizes. Keeping them together is the
smaller net change given the stack's current depth; the split is noted as the
right shape for any future reland.

Q: install_global's collision retry (the `while name in self.global_scope` loop)
lives only in install_global, not install_global_unsafe, which
install_resume_function_global calls directly. Doesn't the resume-name collision
class the retry closes survive for resume functions?

A: The durable separator lands higher in this stack, in #195911, not at this
commit -- `_resume_global_renames`, `package_token` and the per-package uuid are
all absent from package.py at this revision, so this answer describes where the
collision is closed, not code present here. #195911 renames a loaded package's
resume globals to `{name}_{package_token}` (uuid minted once in __init__) while a
fresh compile installs the bare `__resume_at_<offset>_<n>`, so the two can never
collide and install_global_unsafe's assert-only behavior is correct on the resume
path. `__builtins_dict___N` carries no such distinguisher, which is why the retry
loop was added to install_global for it here and now. Until #195911 the resume-name
collision class is pre-existing and open; ghstack lands each PR individually, so
main can carry this commit without #195911's separator for a window; the
resume-name collision in that window is pre-existing, not introduced here. (#195911 also makes an
intra-package duplicate resume name raise loudly, closing the last silent route.)

Q: load_compiled_function passes guard_globals=f_globals, conflating the globals
the function runs in with the globals guards evaluate against, despite the
docstring distinguishing them. Shouldn't they be separate?

A: They are intentionally the same here. A compiled function's guards check the
very globals that function will read at runtime -- that is the point of a global
guard -- so evaluating them against a different dict would guard state the
function never sees. deserialize() keeps guard_globals as a distinct parameter for
callers that genuinely have two dicts (a guard tree rooted in one module served
into another), but load_compiled_function is the common single-module entry point
and binds both to f_globals deliberately. Exposing a second kwarg on it would add
API surface for a split that this entry point, by construction, does not have. The
docstring describes the general deserialize() contract; the narrowing to one dict
at this call site is intended, not an oversight.

Q: The module path auto-resolves its guard scope, but
torch.compiler.load_compiled_function(f) with no f_globals still lands on the
function path and fails any surviving global guard with a bare KeyError on
G['...']. Why not record fn.__module__ at capture and resolve sys.modules[...] the
way AOTCompiledModel does?

A: This commit takes the cheaper of the two remedies the finding offers. When
_guard_globals is None and the guard fails on a KeyError on G[...],
AOTCompiledFunction.__call__ now appends a pointer telling the user to pass
f_globals to load_compiled_function, so the degraded mode names its own fix
instead of surfacing a bare KeyError; AOTCompiledModel's no-match footer gets the
same missing-global branch. Recording the defining module at capture and
resolving sys.modules[...] is the durable version and a reasonable follow-up, but
it is a capture-time schema change, whereas the pointer hint closes the
diagnosability gap without one. The condition is pre-existing, not a regression
introduced here.

Q: SystemInfo.current defaults cpu_codegen to True, which runs the expensive
pick_vec_isa() probe, yet every call site passes cpu_codegen=False explicitly.
Shouldn't the default be False so the probe is opt-in?

A: The default is deliberately the complete value, not the cheap one.
check_compatibility only compares cpu_codegen_target when it is not None, so a
SystemInfo built without the probe silently carries no codegen fingerprint and a
later load on a mismatched ISA is not caught -- a correctness hole. Building one
with the probe is merely slower. Every current call site already passes the flag
explicitly, so the default governs only a future caller that omits it;
defaulting to True means such a caller gets a correct-but-slower artifact rather
than a fast-but-silently-incompatible one. The False overrides sit exactly where
codegen is known to be irrelevant -- the field factory's placeholder and the no-
graph-captured case -- so the expensive probe is opt-OUT there, not opt-in
everywhere.

Q: AOTCompiledModel._no_match_message picks one footer via an exclusive
`if missing_global / else`, so when two results fail and only one lacks a global
the ModelInput hint on the other is dropped; and the two branches test "is a global
missing" with different predicates (`"G['"` over-matches, `"KeyError on G["`
under-matches). Shouldn't the hint be per-result and the predicate shared?

A: Both are real refinements and neither changes a report a user sees today. The
per-result `[i]` lines already print every failure with its own reason; only the
trailing hint is a single footer, so the mixed-cause pair loses advice, not
diagnosis -- and attaching the hint to the `[i]` line that triggered it is the
right shape (it also keeps the len(splitlines)==4 assertions intact), but that is
a message-layout change, not a correctness one. The predicate divergence is a
wording inconsistency: both predicates only gate whether the "pass f_globals / add
a ModelInput" hint is appended, so an over-match appends it spuriously and an
under-match omits it -- in both cases the load still fails with the same error and
the same per-result reasons. Consolidating on `"KeyError on G["` in both places is
the clean fix and is safe to fold; it is called out so the mismatch is not read as
two intentionally different checks.

Q: AOTCompiledFunction.__call__ appends a hint saying the guard scope "was
reconstructed from the serialized bytecode ... pass f_globals to
load_compiled_function", gated on `self._guard_globals is None` -- but that is also
true of every in-process capture that never serialized (the capture path passes
only _extra_globals), so a user who never saved can be told to pass f_globals.
Shouldn't it gate on an explicit "was deserialized" flag?

A: The hint is appended only when a guard actually FAILS on an absent global (a
KeyError reaching G['NAME']), not on every in-process run. A never-serialized
capture reaches it only if its live guards genuinely reference a global that was
deleted after capture -- in which case supplying the missing global (via f_globals
on a reload, or simply keeping it defined) is the correct remedy, so the advice is
directionally right even when the exact API name does not apply to an in-process
object. The predicate is broader than "was deserialized", and gating on an explicit
flag (or reusing _no_match_message's always-true phrasing) is a fair follow-up, but
the message only ever fires on a real missing-global failure, so it does not
misdirect a healthy in-process capture.

Q: `AOTCompiledModel.__call__`'s dispatch loop lets a raising `guard_check`
propagate, while `_no_match_message` tolerates a raising guard. Shouldn't the two
agree?

A: Fixed: the scan now treats a raising guard TREE as "did not match" and moves
on, and the report names the raiser as before. Binding errors are not tolerated:
`prepare_f_locals` runs outside the guarded region, so a call the signature
cannot accept still raises `bind_locals`' TypeError as the plain module would
(pinned by `test_aot_compile_module_wrong_arity_raises_type_error`) instead of a
no-match report telling the user to add a ModelInput. (The C++ guard tree never propagates --
`check_nopybind` clears and returns false -- so today's raisers are Python-side,
`prepare_f_locals` / `bind_locals`, which would fail the call for the same input
anyway; the fix is about the two paths agreeing.) `RaisingGuardManager.check` in
the existing test now raises too, so the scan loop is covered.

Q: `cache_entry()` samples `SystemInfo.current()` ambiently, so a package
compiled under `torch.compile(options={"cpp.simdlen": 256})` on an AVX-512 host
records the 512-bit ISA its kernels were not tiled for -- the bug the AOT half
fixes here. Which commit closes this?

A: Correct at this revision: `cache_entry()` runs from record_package/save_package
after the `_TorchCompileInductorWrapper`'s config_patches scope has exited, and
nothing on the package carries that config here. #195913 closes it directly: it
moves the probe out of `cache_entry` into `update_device_type(graph,
codegen_config=...)`, and convert_frame recovers the wrapper's config from the
compiler_fn chain (`_inductor_codegen_config`) and re-applies it with
`torch._inductor.config.patch` around the sample -- the same re-application
`aot_compile_fullgraph` does here. A local fix would have to stash the config on
the package and re-apply it in `cache_entry`, code #195913 deletes when it
relocates the probe, so the fix lands with the commit that owns the probe's new
home. The load side is unchanged (ambient, with the global cpp.simdlen /
ATEN_CPU_CAPABILITY escape hatch).

Q: The `test_save_guidance_when_a_locals_class_default_cannot_pickle` comment says
the shared "local object" substring covers the pure-Python pickler too, but that
pickler's message ("Can't pickle <class ...>: it's not found as ...") has no such
substring.

A: Right on the parenthetical (the headline -- that AttributeError never escapes --
is wrong: the C pickler `AOTCompilePickler` subclasses raises it unwrapped through
3.13, and 3.14 raises PicklingError "Can't pickle local object"). The pure-Python
pickler is unreachable from `AOTCompilePickler(pickle.Pickler)`, so the comment now
names the two versions' wordings and drops the pure-Python clause. The test moved
to #196454 with the code it pins, so the reword lives there.

Q: `test_eager_backend_entry_is_exempt_from_the_codegen_target`'s native half only
asserts `requires_native_backend_compatibility`; the target the probe recorded is
never checked, and asserting it directly would need a host toolchain.

A: Fixed: the native half patches `_current_cpu_codegen_target` to a sentinel
target and asserts the entry recorded exactly that, so it needs no toolchain.

Q: No test drives the `options=`-patched capture path in `aot_compile_fullgraph`;
the footer branch selection in `_no_match_message` is unpinned; the `__call__`
missing-global hint is unasserted; the ISA table is a hand-rolled loop rather than
`@parametrize`; `check_codegen=False` on cuda is untested.

A: Added: `test_aot_compile_samples_the_codegen_target_under_the_wrappers_config`
(the recorded simdlen is the wrapper's, the ambient config is untouched after),
`assertIn` on each footer in the two no-match tests,
`test_aot_compile_fn_missing_global_hint_names_f_globals`, the ISA table as named
`@parametrize` subtests, and a `check_codegen=False` GPU case in the Triton/GPU
exemption test.

Q: `(line,) = logs.output` plus a `functools.partial(` substring in the
partial-forward fallback test is brittle; the seeds test "sanitizes rather than
cleans up" by filtering `__import_*` names; the mixed-device test depends on
`check_versions` ordering.

A: The single-record unpacking is deliberate -- any extra deserialize warning
should fail the test, that is the contract -- and `functools.partial(` is the repr
Python has emitted for decades. The `__import_*` filter isolates from earlier
tests: any compile writes those aliases into the tracing module's globals
(symbolic_convert's `install_global`) and `CleanupHook` removes them on reset, so
the filter is scoping, not a cleanup leak. The ordering dependence is documented
at `check_versions` ("cpu first ..."); left as is.

Q: The `except (RuntimeError, AttributeError)` arm around `get_traced_fn` in
`aot_compile_module` has no test.

A: Reachable (`mod.forward = torch.add` has `__self__` but no `__func__`) but low
value: it only selects the warning text for an unresolvable guard scope, which the
existing scope tests already exercise on the resolvable side. Left to follow-up
rather than pinned here.

Q: pr-sanity-checks is red -- this commit grew to 2058 lines.

A: The AOT-pickler tests (five `TestAOTCompile` cases plus the whole
`TestAOTCompilePickler` class) exercise code that #196454 introduces, so they
moved down to that commit; this commit is now ~1700 lines and the combined tree is
unchanged.

Q: The AOT-compile page documents the new `f_globals` contract but not the other
new user-visible load failure: an inductor artifact recorded a CPU codegen target
and is refused on a host that resolves a different one, with `ATEN_CPU_CAPABILITY`
/ the global `cpp.simdlen` as the escape hatch.

A: Added to "Choosing a backend" (the section that already contrasts inductor and
eager): what is recorded, the exact error, why a wider ISA is not a superset, how
to make the host resolve the recorded ISA before loading, that `options=` does
not apply at load time, and that eager/aot_eager artifacts are exempt; plus a
cross-reference from `load_compiled_function`'s Returns.

Q: `optimize_assert`'s copy of the `native_backend` threading is untested; the
eager-exemption test only takes the `_optimize` branch, so the two call sites can
drift.

A: The test is now parametrized over `fullgraph` (False -> `_optimize`, True ->
`optimize_assert`) so both paths are pinned.

Q: `initialize()` restores `_device_types` from the cache entry but not
`requires_native_backend_compatibility`, and neither store load path passes the
kwarg, so a loaded eager package loses its exemption and re-saves with a baked
codegen target.

A: Correct at this revision; #195913 closes it in both ways the review lists:
`initialize()` ORs the entry's flag into the package's (monotone, with the probe
deferred), AND `DynamoStore.load_package` / `load_and_install_package` pass
`requires_native_backend_compatibility=entry.dynamo.requires_native_backend_compatibility`
so a False survives the constructor default. The eval_frame path (a native
session reloading an eager entry) is why the entry is not made authoritative on
its own: that would fail open. The manual kwarg in
`test_loaded_eager_package_stays_exempt_on_resave` models that eval_frame path.

Q: The blacklist rationale ("a false rejection at load is recoverable") does not
hold on the `aot_compile` path: `CompileArtifacts` derives the gate solely from the
backend name, so a user backend that emits no native code is fingerprinted with the
capture ISA and cannot be loaded on a narrower or toolchain-less host.

A: Fixed: `CompileArtifacts.requires_native_backend_compatibility` (default True
so artifacts saved before the field keep loading) is set at capture from the
backend -- the eager family by name, or any callable declaring
`emits_native_code = False` (honoured by `_backend_emits_native_code` for the
package path too) -- and `check_compatibility` skips the ISA gate when it is
False. Pinned by `test_aot_compile_backend_declaring_no_native_code_skips_the_isa_gate`
(no target recorded; loads with a host that resolves no target). The docs now
state the true scope: every backend outside the eager family is gated unless it
declares otherwise.

Q: The install-collision retry lands on `install_global` only, but
`install_global_by_id` and the resume-function install also reach `CleanupHook.create`,
which raises on a name that already exists.

A: The resume half is closed by #195911's per-package token rename (the FAQ above
says where). `install_global_by_id` names (`___module_<name>_<id>_c<compile_id>`)
are never seeded by any load path -- `install()` seeds only `import_sources` and
`function_names`, and the AOT loader seeds import aliases and the builtins-dict
key -- so there is no baked-in name for a later compile to collide with (probe:
capture, reset, load, recompile in the same module: OK). Only `__builtins_dict___N`
carries no distinguisher, which is why the retry is scoped to it.

Q: `linux-docs` is red from this PR up.

A: The cross-reference added last round used a `#heading` anchor, which this
docs build (no `myst_heading_anchors`) does not resolve; it now uses the file's
explicit `(choosing-a-backend)=` label and a `{ref}` role.

ghstack-source-id: 6fed4ac
Pull-Request: #195354
bobrenjc93 added a commit that referenced this pull request Sep 9, 2026
Guards on globals resolve against the traced function's global scope.
`AOTCompiledFunction.deserialize` takes `f_globals` for this, but
`AOTCompiledModel.deserialize` never passed one, so a reloaded module artifact
rebuilt its guards against only what the serialized bytecode reconstructs, and
a global Dynamo specialized away failed every call with "KeyError on G['...']".

`AOTCompiledModel.deserialize` now resolves the scope from
`model.forward.__globals__` and passes it through a new keyword-only
`guard_globals`, kept apart from `_extra_globals`, which feeds the bytecode.
Guards read the live dict by reference: a rebind after load redirects dispatch,
and a missing global fails the guard with no fallback to serialized values. A
`forward` without `__globals__` warns and uses the reconstructed scope. Since
Dynamo roots guards at `__import_*` aliases it mints into the tracing
process's globals, loading inserts the recorded `__import_*` aliases and the
`__builtins_dict___N` key into the live dict without overwriting existing keys. A baked-in `__builtins_dict___N` would otherwise collide with the identical name a later compile in that module regenerates -- `unique_id` is a fresh per-process counter a load never advances -- so `install_global` now skips any name already bound in the global scope. Both public docstrings document this.

It also adds the CPU codegen target the precompile package layer needs.
`SystemInfo` records `(machine, vec_isa, vec_isa_width, vec_isa_macro, simdlen,
march)` for an artifact holding generated CPU code, and the load gate compares
the *resolved* target `(machine, vec_isa, vec_isa_width, vec_isa_macro)` against
what `pick_vec_isa()` picks on the host: the artifact's kernel source was tiled
for the capture ISA and the host recompiles it with its own. `pick_vec_isa()`
already folds the raw knobs (`cpp.simdlen` and `ATEN_CPU_CAPABILITY`; `march` never reaches it) into the
ISA it returns, so the resolved triple is the complete key; simdlen and march
stay in the recorded tuple for diagnostics but do not gate. The sample is taken
under the backend's own inductor config: `torch.compile(options={...})` builds a
`_TorchCompileInductorWrapper` that patches config such as `cpp.simdlen` only for
the duration of `backend()`, which has already returned by the time we sample, so
we re-apply that config while reading `SystemInfo.current()`; otherwise the
fingerprint would record the ambient ISA rather than the one the kernels were
tiled for. `emits_native_code(backend_name)` exempts eager-family artifacts from
the toolchain probe and the comparison.
`_graph_device_types` scans the whole graph instead of reading the first meta
value's device, which misreported a SymInt placeholder as "cpu" and let a mixed
cpu+accelerator graph skip the check.

The Triton-version and GPU-model checks now exempt off the artifact (the
receiver), not the loading host: an artifact built with Triton is rejected on a
Triton-less host, where before the host-side exemption let it load and then fail
later at kernel load.

User-visible: `AOTCompiledModel.__call__` raises `RuntimeError("No AOT compiled
graph matched ...")` listing why each input was rejected instead of running
graph 0's guards, and a result opted out via `disable_guard_check()` is
consulted only after every guarded result was rejected.
`CompilePackage.__init__`'s `requires_native_backend_compatibility` is
keyword-only.

Test Plan:

```
python test/dynamo/test_aot_compile.py
python test/dynamo/test_package.py
python test/test_precompile.py
```

The scope tests fail on the pre-change tree with the KeyError. Codegen-target
tests patch `_current_cpu_codegen_target` instead of
depending on host hardware.

Authored with an AI assistant.

FAQ

Q: Why does the gate compare only the resolved ISA (machine, vec_isa,
vec_isa_width, vec_isa_macro) and not simdlen and march too? An earlier version
compared all of them exactly.

A: Because pick_vec_isa() already folds simdlen and ATEN_CPU_CAPABILITY (march never reaches pick_vec_isa; it only changes how the same tiled source is compiled)
into the ISA it resolves -- a simdlen that caps the width picks a narrower ISA,
so the recorded width and macros already reflect it -- the resolved triple is
the complete correctness key. Comparing the raw simdlen/march knobs on top of it
is not merely redundant, it is wrong in two ways. First, it rejects an artifact
this host can reproduce: an artifact captured under cpp.simdlen=256 is loadable
on any host that resolves to the same 256-bit ISA, whether the host gets there by
default or via ATEN_CPU_CAPABILITY, yet a raw-simdlen comparison rejects the
default-knob host. Second, it makes the documented escape hatch ineffective --
setting cpp.simdlen to fix an ISA mismatch would only trade the ISA error for a
simdlen error. A related bug the exact comparison hid: the sample was read after
backend() returned, so the _TorchCompileInductorWrapper's config patch (e.g.
cpp.simdlen) had already exited and the fingerprint recorded the ambient ISA,
not the one the kernels were tiled for -- so an artifact could reject its own
build host and accept a wider one. This commit re-applies the wrapper's config
while sampling so the recorded ISA is the one the kernels were actually built
for, and gates on that resolved ISA. The gate is still fail-closed: a genuine
ISA/width/macro mismatch is refused, and the caller can fix it with
ATEN_CPU_CAPABILITY or cpp.simdlen.

Q: A wider host ISA (AVX-512 loading an AVX2 artifact) is a superset, so why
reject it instead of running the narrower kernels?

A: A wider ISA is not a superset here. The kernels were tiled for the narrower
width, so the wider host's masked loads zero-fill the lanes the narrow tiling
never wrote and its unmasked reductions then read them, changing the result.
The comparison is exact -- and it compares the recorded ISA name, its bit
width, and its build macros together -- because
VecSVE(128), VecSVE(256), and VecNEON overlap in name and/or width and only the
full fingerprint tells them apart.

Q: When the loading host has no usable CPU codegen target at all (no C++
toolchain), the check hard-refuses rather than loading best-effort. Isn't that
too aggressive?

A: Fail-closed on purpose. An artifact that recorded a CPU codegen target holds
vectorized CPU kernels that must be compiled to run, and a host with no
toolchain cannot build them, so there is nothing to run best-effort; refusing
with a clear message beats failing deep in compilation. Eager-family artifacts,
which bake no native code, are exempted up front by emits_native_code(), so this
refuses only artifacts that genuinely need a compiler.

Q: The CPU codegen fingerprint records tuple(vec_isa.build_macro()), but for
AVX-512 that macro is the constant CPU_CAPABILITY_AVX512 and does not encode the
bf16/fp16 probe. Two x86 hosts that differ only in AVX-512-BF16 / AMX-FP16
support then produce an identical fingerprint, yet build_arch_flags() appends
-mavx512bf16 / -mamx-fp16 only where supported -- so a capture host bakes bf16
intrinsics and a loading host without them recompiles wrong. Isn't that a
collision?

A: Correct, and a real gap: build_macro() captures the ISA family but not the
bf16/fp16 arch-flag suffixes, so the fingerprint is coarser than the code the
recompile actually emits. The fix is to record build_arch_flags() -- which
subsumes the macros and the -mavx512bf16 / -mamx-fp16 / SVE -msve-vector-bits
suffixes -- rather than build_macro(). That changes the recorded fingerprint
semantics and can only be validated by exercising the codegen path across ISAs,
so it is tracked as a follow-up rather than folded into this commit unverified;
until then the check is correct on ISA family and width and misses only the
same-family bf16/fp16 sub-variant. When that follow-up records build_arch_flags(), note the ordering trap: VecAVX512/VecAMX set _arch_flags as a side effect of their __bool__ probe, so the recorder must read build_arch_flags() only after bool() has run on the instance.

Q: An artifact saved under one backend and loaded under another disagrees on
whether the ISA gate applies (an inductor-saved entry loaded in an eager
session, or the reverse). How is that reconciled?

A: initialize() no longer clobbers _requires_native_backend_compatibility with
the loaded entry's value, so the constructor value -- taken from the backend the
caller is loading under -- stands. That fixes the load gate: an eager
constructor can no longer disarm the ISA check an inductor entry needs, so the
load never relaxes a host. The mirror direction is subtler: an inductor-saved
entry loaded in an eager-family (e.g. aot_eager) session and then re-saved
(literal "eager" records no bundled artifact, so only aot_eager reaches this)
would strip the fingerprint.
That is closed by the monotone OR-accumulate in #195913
(self._requires_native_backend_compatibility |= dynamo.requires...), which
neither the entry nor the constructor can relax; this commit removes only the
clobber the load gate needed.

Q: _graph_device_types walks the FX graph with its own heuristic instead of
reading V.graph.device_types, so it both over-reports (a false "cpu" for unused
placeholders arms the toolchain probe) and under-reports (string device= specs
are invisible). Why reimplement it?

A: The FX-level walk runs before inductor lowering, where V.graph.device_types
is not yet populated, so it cannot be read here; the heuristic is deliberately a
superset because arming the CPU toolchain probe for an artifact that turns out
to hold no CPU code only costs a load-time ISA check the caller can satisfy,
which is the fail-closed direction. String device= kwargs and a .to() device
argument are read, but only in those device positions -- not from any flat arg
-- because an autocast device type is a plain string positional of
_enter_autocast, and trusting every string leaf would inject a phantom "cuda"
into a CPU-only graph (unloadable on the very host that saved it) or a phantom
"cpu" from torch.utils.checkpoint's unconditional autocast("cpu") (arming the
ISA gate on an accelerator-only artifact). Device-carrying method calls beyond
.to()/.cuda()/.xpu() are still narrowing work tracked separately.

Q: A `functools.wraps` wrapper assigned to `forward` silently yields the wrong
guard scope: `get_traced_fn` never unwraps `__wrapped__` and `_get_signature`
uses `follow_wrapped=False`, so a wrapper defined in a different module resolves
guards against the decorator's module with no warning -- the very failure this PR
fixes, in a shape the fix does not cover. Why leave it?

A: The silent case is asymmetric wrapping only: `functools.wraps` copies
`__module__`/`__name__`/`__qualname__` but not `__globals__`, so when the same
wrapper is present at both save and load the scopes agree and the artifact is
correct. It breaks only if the capture and the runtime wrap `forward` in
different modules, which is not a shape any real serve path produces (the loaded
callable installs onto the recorded code object). Unwrapping `__wrapped__` and
comparing `original_code` against `traced_fn.__code__` to warn on the mismatch is
the right hardening and is tracked as follow-up; it is a detection improvement,
not a correctness fix for the paths this PR serves.

Q: Seeding `__builtins_dict___N` into the live module globals makes a later
`torch.compile` in that same module crash. `unique_id()` is a process-global monotonic
counter that a load-only process never advances, so the artifact bakes in the capture
process's `__builtins_dict___0`, deserialize writes that key into the module `__dict__`,
and the next `OutputGraph.__init__` there regenerates `__builtins_dict___0` and hits
`CleanupHook.create`, which raises because the name is already in scope. This is every
caller of the default `guard_filter_fn`, not just those who keep global guards.

A: Correct, and it was a real crash -- reproduced with the default filter. Fixed here in
`OutputGraph.install_global`: after minting a name from `unique_id`, it now skips any
name already bound in `self.global_scope` (`while name in self.global_scope: name =
unique_id(prefix)`) before installing, so a later compile that regenerates a baked-in
`__builtins_dict___N`/`__import_*` name transparently picks the next id instead of
colliding in `CleanupHook.create`. `unique_id` is monotonic, so the loop always
terminates. The seeding itself stays -- guards rooted at those names must resolve -- and
the collision it could cause on the next compile is what this fix removes.

Q: The AOT path inserts the `__import_*` aliases and the `__builtins_dict___N`
key straight into the caller's dict, without the `CleanupHook.disown` the
precompile path does first and without any `_installed_globals`/`uninstall`/
`__del__` bookkeeping -- and because the default `guard_filter_fn` drops every
`is_global` guard, the common path mutates a torch namespace for guards that were
filtered out. Isn't the missing cleanup a hazard?

A: The insertions are bounded and idempotent (`if name not in scope`), so this is
permanent-and-untracked, not unbounded growth, and it mirrors what tracing itself
already does into the same namespace at `symbolic_convert`. The precompile path
needs `disown` and `_installed_globals` because it supports `unload()`; the AOT
artifact has no uninstall surface by design (it is a load-and-run function, not an
installer), so there is nothing to take back out. Seeding a torch namespace when
the filter dropped the global guards is wasteful but harmless -- the keys are
inert if unread, and the one active hazard, a later compile colliding on a baked-in
name, is closed by `install_global` skipping already-bound names (see the collision
FAQ below). A cleanup API on `AOTCompiledFunction`/`AOTCompiledModel` and
gating the seed on whether global guards survived are both reasonable follow-ups;
neither changes a result today.

Q: `_backend_emits_native_code` classifies the same backend differently by
entrypoint and never classifies instance backends: `torch.compile(backend=eager)`
correctly yields `False` (the wrapper stamps `compiler_name`), but
`torch._dynamo.optimize(eager)` stringifies the raw callable to native, an
instance like `CompileCounter` has no `__name__`, and the aot path reads
`"unknown"` after `get_compiler_fn` erased the string. Worse, a user backend
whose function is named `eager` is silently exempted from the ISA gate. Why is
this acceptable?

A: The classifier is fail-closed by construction: an unrecognized backend is
assumed to emit native code and pays the ISA check, which only ever refuses a
load the caller can satisfy. The two "misclassified as native" cases
(`optimize(eager)`, instance backends) therefore cost a spurious toolchain probe,
never a wrong result. The one genuinely fail-open direction -- a user callable
coincidentally named `eager`/`aot_eager` tripping the name blacklist -- requires a
user to name their own inductor-lowering backend after an eager builtin, which is
not a shape that occurs in practice; a name-based blacklist is the only signal
available before `get_compiler_fn` runs, and tightening it (identity match rather
than name, and stamping `compiler_name` on `register_backend`) is tracked
separately. The `"unknown"` the aot path records is the same fail-closed default.

Q: `_NO_NATIVE_CODE_BACKENDS` omits every non-inductor backend that is not
eager-family -- `ts`/`aot_ts`, `invoke_subgraph`, `cudagraphs`, `openxla`, `tvm`,
the `*_TESTING_ONLY` gm-passthrough backends and the minifier backends -- so all
of them are now gated on host ISA even though none emit inductor CPU kernels.
Shouldn't they be exempt?

A: Same fail-closed rationale: these backends are rare enough that the exemption
list intentionally enumerates only the eager family (the common no-codegen path),
and everything else pays a host ISA check. (Correction: that check is NOT
satisfiable on every host -- ATEN_CPU_CAPABILITY / cpp.simdlen can only lower a
host's resolved ISA, never raise it, and a toolchain-less host resolves no target
at all -- so a user backend that bakes no native code now has an opt-out on the
aot_compile path too: declare `emits_native_code = False` on the backend callable
and the artifact records no codegen target and skips the gate, mirroring the
package's requires_native_backend_compatibility.)
Enumerating each additional no-native-code backend is a pure widening of the
exemption with no correctness stake and is deferred; the current list is
conservative in the safe direction.

Q: The mixed cpu+accelerator device change is a load-time behavior change on
existing artifacts that neither the description nor the FAQ mentions: pre-PR a
mixed graph whose first meta value was a CPU tensor recorded `device_type="cpu"`
and skipped the GPU check, so it loaded on a host lacking the accelerator;
post-PR the device set is unioned and every device is checked, so it now
hard-fails there. Isn't that a BC break?

A: It is an intentional correctness fix, and the new answer is the right one: an
artifact that genuinely uses an accelerator must not load on a host without it,
and the pre-PR behavior (silently skipping the GPU check because a CPU tensor
happened to be first) was the bug. The only wrinkle is message ordering -- when
both the accelerator is absent and the ISA differs, the user sees the ISA message
first because `sorted({"cpu","cuda"})` puts codegen first -- and that is
deliberate (ISA skew is fixable via `ATEN_CPU_CAPABILITY`/`cpp.simdlen`, device
absence is not, so leading with the fixable one is the better default). The
behavior change is called out here for the record.

Q: `check_codegen=False` returns early inside the GPU block, so for an
eager-family artifact carrying a cuda device the `toolkit_version`,
`triton_version` and `gpu_name` checks are all skipped -- and `gpu_name` is not a
"describes generated code" check the way the gate's comment justifies. Isn't
skipping `gpu_name` for an eager artifact wrong?

A: Intentional. An eager-family artifact bakes no device-specific code -- no
Triton kernels, no toolkit-versioned cubins, nothing pinned to a particular GPU
model -- so it is portable across accelerators of the same family, and all three
GPU checks exist to protect generated code that an eager artifact does not carry.
Gating them together under `check_codegen` is therefore correct for what the
artifact actually contains; `gpu_name` guarding an eager artifact would refuse a
load that is in fact safe. The comment's "describes generated code" framing is
about why the gate exists, not a per-check taxonomy.

Q: When the loading host reports no CPU codegen target at all,
`_cpu_codegen_target_problem` returns a message that does not name the machine
the artifact was built for. Shouldn't the message name it?

A: The enclosing `RuntimeError` already prints the full cached tuple
(`cached={self.cpu_codegen_target}`, machine included) next to `current=...`, so
the machine is named at the call site. The per-branch string only supplies the
component-level reason for the mismatch, and a `None` host has no component to
compare against -- duplicating the machine there would be redundant.

Q: pick_vec_isa() at save is expensive (seen around 18s cold). Why pay it there?

A: It is gated on needs_cpu_codegen, so only artifacts that will emit native
CPU code reach it, and pick_vec_isa() caches its result -- the probe runs once
per process, not once per save. Recording the resolved ISA at save is what lets
load fail closed against a host that would pick a different ISA; deferring the
probe to load would move the cost, not remove it.

Q: An artifact captured under options={'cpp.simdlen': N} loads only on a host
that resolves to N. Doesn't passing the same options={'cpp.simdlen': N} on the
loading side fix it?

A: No, and this is worth stating explicitly -- including the sharp corner that it
fails even on the very machine that built it, in the same process. On load there is
no backend wrapper, so check_compatibility() samples SystemInfo.current() ambiently
-- outside any torch.compile(options=...) patch, which only takes effect once
tracing begins. simdlen lived only in the per-compile options, never in the global
config, so nothing re-applies it at load and the build host re-resolves to its
native (wider) ISA and rejects its own artifact. The documented escape hatch on the
loading host is therefore the *global* torch._inductor.config.cpp.simdlen (or the
ATEN_CPU_CAPABILITY env var), set before the load, not the options= form. The
capture-time half is fixed here by widening the config.patch context to cover
CompileArtifacts / AOTCompiledFunction construction, so __post_init__'s self-check
samples under the same ISA the fingerprint recorded. Auto-re-applying the recorded
simdlen at load (so the round-trip needs no env/config) is a real improvement, but it
belongs with the load-side recompile-config plumbing that lands with the store-reload
work in #195913, not this commit's gate; the AOT load path deserializes bundled
kernels rather than recompiling from source, so the gate is a run-safety check and the
escape hatch is the supported reload path until then.

Q: The codegen fingerprint is armed from the backend and device
(emits_native_code(backend_name) and "cpu" in device_types), not from whether
inductor actually emitted a cpp kernel. An artifact whose CPU output is all
extern calls (torch.mm lowering to BLAS) still records a target, so the
load-time gate pays the full pick_vec_isa() dry-compile (~19s measured) for
nothing. Arm it from whether a cpp kernel was emitted.

A: The over-arming is deliberate and errs toward correctness. The gate rejects a
host whose resolved ISA differs from the one the kernels were tiled for; if we
under-arm -- record no target when a cpp kernel WAS emitted -- the gate accepts
an ISA-incompatible host and runs a mistiled kernel, a silent-wrong-result/crash
hazard that is strictly worse than a slow load. Arming on "the backend can emit
native CPU code" is the conservative superset that never under-arms. Precisely
detecting "inductor emitted zero cpp kernels for this graph" means introspecting
the compiled artifact's kernel sources, which is not reliably available at this
call site and, per the measurement's own method, needs a built inductor to
validate that the narrower signal never drops a real target; narrowing the arming
to it (and skipping the dry-compile when no cpp kernel exists) is the right
optimization but is tracked as follow-up rather than attempted without a build.
The one-time load cost is also amortized by TORCHINDUCTOR_CACHE_DIR.

Q: The remedy sentence points the user at ATEN_CPU_CAPABILITY /
torch._inductor.config.cpp.simdlen, but on fbcode/x86 pick_vec_isa()
short-circuits to VecAVX2() before reading either knob, so neither can move the
resolved ISA and _current_cpu_codegen_target() can never return None there. The
hint is inert in fbcode.

A: Correct that on fbcode/x86 pick_vec_isa() returns VecAVX2() unconditionally,
so the two knobs the hint names cannot change the resolved ISA and the escape
hatch is a no-op there. The hint is advisory and accurate off fbcode (OSS x86,
where valid_vec_isa_list()/cpp.simdlen/ATEN_CPU_CAPABILITY do resolve the ISA),
which is where an ISA-mismatch rejection is actually reachable; on fbcode the
fixed AVX2 target means two builds on the same machine class agree and the gate
does not fire in the first place. Conditioning the message on config.is_fbcode()
to drop the inert knob suggestion is a reasonable message-only refinement that
changes no gate behavior, deferred with the other fbcode-specific paths that
cannot be validated in this environment.

Q: The two store reload APIs -- DynamoStore.load_package and
DynamoCache.load_and_install_package -- construct CompilePackage(fn,
entry.dynamo) with the constructor default requires_native_backend_compatibility=True
and no backend to derive it from, and initialize() restores _device_types but
not the flag. So an eager package round-tripped through a store upgrades to
native on re-save: cache_entry() pays the pick_vec_isa() probe and stamps a
cpu_codegen_target onto an artifact that bakes no native code, which then
hard-refuses on an ISA-different host. Restore the flag from the entry here (it
records the value), or thread the kwarg through the store APIs.

A: Correct that at this commit the harm is real: the two store paths pass the
bare default True (the eval_frame path is the only one that derives the
constructor value from the backend, so the existing "the constructor value,
taken from the backend, stands" FAQ does not cover the store paths), and this
commit's cache_entry() probes eagerly, so a store round-trip of an eager package
re-saves as native. But the suggested entry-authoritative fix is the wrong
resolution, because at this commit the flag has no compile-path accumulation: it
is written once at construction and never OR'd by a later native compile. Making
the reloaded entry authoritative would fail OPEN in the mirror direction -- a
native session that reloads an eager entry (flag False) would then run native
compiles with the ISA gate disarmed and load a kernel built for another target
on an incompatible host, a silent-wrong-result hazard strictly worse than the
wasteful-but-safe over-arm this comment describes. The correct resolution lands
higher in this same stack (#195913): the flag is made monotone
(self._requires_native_backend_compatibility = self._requires_native_backend_compatibility
or dynamo.requires_native_backend_compatibility, which neither a reload nor a new
compile can relax), and the pick_vec_isa() probe is deferred out of cache_entry
-- the reload path stamps _system_info via SystemInfo.current(cpu_codegen=False)
carrying the entry's recorded target (None for an eager artifact) straight
through re-save, and the probe fires only in update_device_type during an actual
cpu-bearing compile. At the stack tip the store-reloaded eager package therefore
pays no probe and stamps no target on re-save -- exactly the harm this comment
asks for -- while a genuinely native new compile still arms the gate fail-closed.
The eager over-arm visible here is an intermediate-state artifact removed by that
deferred-probe change above it, not a shape the stack ships; adopting a local
entry-authoritative fix here would have to be reverted to reach the safe design.

Q: The CPU-codegen half of this commit -- SystemInfo, emits_native_code, the
check_compatibility rework, the fingerprint gate and roughly half the new tests
-- is an independent feature from the AOTCompiledModel.deserialize guard-scope
fix in the title, and it is the part that can newly hard-refuse a load. Split it
into (1) the guard-scope fix, (2) the _graph_device_types rewrite, and (3) the
CPU codegen fingerprint and gate so each lands on its own evidence.

A: Agreed on the logical separation, and in a fresh stack these would be three
commits. This commit sits deep in a 24-PR ghstack whose upper commits (the
capture session, save() entry point, and the monotone OR-accumulate /
deferred-probe changes that this very FAQ leans on) already depend on the
SystemInfo and emits_native_code surface introduced here; splitting it now
reindexes every PR above it and restarts their in-flight CI, which is a real cost
the reviewer explicitly flagged as "your call". The three parts are individually
reviewable in place: the guard-scope fix is the first three paragraphs and its
KeyError-reproducing tests, _graph_device_types is self-contained, and the
codegen gate is the part the FAQ scrutinizes. Keeping them together is the
smaller net change given the stack's current depth; the split is noted as the
right shape for any future reland.

Q: install_global's collision retry (the `while name in self.global_scope` loop)
lives only in install_global, not install_global_unsafe, which
install_resume_function_global calls directly. Doesn't the resume-name collision
class the retry closes survive for resume functions?

A: The durable separator lands higher in this stack, in #195911, not at this
commit -- `_resume_global_renames`, `package_token` and the per-package uuid are
all absent from package.py at this revision, so this answer describes where the
collision is closed, not code present here. #195911 renames a loaded package's
resume globals to `{name}_{package_token}` (uuid minted once in __init__) while a
fresh compile installs the bare `__resume_at_<offset>_<n>`, so the two can never
collide and install_global_unsafe's assert-only behavior is correct on the resume
path. `__builtins_dict___N` carries no such distinguisher, which is why the retry
loop was added to install_global for it here and now. Until #195911 the resume-name
collision class is pre-existing and open; ghstack lands each PR individually, so
main can carry this commit without #195911's separator for a window; the
resume-name collision in that window is pre-existing, not introduced here. (#195911 also makes an
intra-package duplicate resume name raise loudly, closing the last silent route.)

Q: load_compiled_function passes guard_globals=f_globals, conflating the globals
the function runs in with the globals guards evaluate against, despite the
docstring distinguishing them. Shouldn't they be separate?

A: They are intentionally the same here. A compiled function's guards check the
very globals that function will read at runtime -- that is the point of a global
guard -- so evaluating them against a different dict would guard state the
function never sees. deserialize() keeps guard_globals as a distinct parameter for
callers that genuinely have two dicts (a guard tree rooted in one module served
into another), but load_compiled_function is the common single-module entry point
and binds both to f_globals deliberately. Exposing a second kwarg on it would add
API surface for a split that this entry point, by construction, does not have. The
docstring describes the general deserialize() contract; the narrowing to one dict
at this call site is intended, not an oversight.

Q: The module path auto-resolves its guard scope, but
torch.compiler.load_compiled_function(f) with no f_globals still lands on the
function path and fails any surviving global guard with a bare KeyError on
G['...']. Why not record fn.__module__ at capture and resolve sys.modules[...] the
way AOTCompiledModel does?

A: This commit takes the cheaper of the two remedies the finding offers. When
_guard_globals is None and the guard fails on a KeyError on G[...],
AOTCompiledFunction.__call__ now appends a pointer telling the user to pass
f_globals to load_compiled_function, so the degraded mode names its own fix
instead of surfacing a bare KeyError; AOTCompiledModel's no-match footer gets the
same missing-global branch. Recording the defining module at capture and
resolving sys.modules[...] is the durable version and a reasonable follow-up, but
it is a capture-time schema change, whereas the pointer hint closes the
diagnosability gap without one. The condition is pre-existing, not a regression
introduced here.

Q: SystemInfo.current defaults cpu_codegen to True, which runs the expensive
pick_vec_isa() probe, yet every call site passes cpu_codegen=False explicitly.
Shouldn't the default be False so the probe is opt-in?

A: The default is deliberately the complete value, not the cheap one.
check_compatibility only compares cpu_codegen_target when it is not None, so a
SystemInfo built without the probe silently carries no codegen fingerprint and a
later load on a mismatched ISA is not caught -- a correctness hole. Building one
with the probe is merely slower. Every current call site already passes the flag
explicitly, so the default governs only a future caller that omits it;
defaulting to True means such a caller gets a correct-but-slower artifact rather
than a fast-but-silently-incompatible one. The False overrides sit exactly where
codegen is known to be irrelevant -- the field factory's placeholder and the no-
graph-captured case -- so the expensive probe is opt-OUT there, not opt-in
everywhere.

Q: AOTCompiledModel._no_match_message picks one footer via an exclusive
`if missing_global / else`, so when two results fail and only one lacks a global
the ModelInput hint on the other is dropped; and the two branches test "is a global
missing" with different predicates (`"G['"` over-matches, `"KeyError on G["`
under-matches). Shouldn't the hint be per-result and the predicate shared?

A: Both are real refinements and neither changes a report a user sees today. The
per-result `[i]` lines already print every failure with its own reason; only the
trailing hint is a single footer, so the mixed-cause pair loses advice, not
diagnosis -- and attaching the hint to the `[i]` line that triggered it is the
right shape (it also keeps the len(splitlines)==4 assertions intact), but that is
a message-layout change, not a correctness one. The predicate divergence is a
wording inconsistency: both predicates only gate whether the "pass f_globals / add
a ModelInput" hint is appended, so an over-match appends it spuriously and an
under-match omits it -- in both cases the load still fails with the same error and
the same per-result reasons. Consolidating on `"KeyError on G["` in both places is
the clean fix and is safe to fold; it is called out so the mismatch is not read as
two intentionally different checks.

Q: AOTCompiledFunction.__call__ appends a hint saying the guard scope "was
reconstructed from the serialized bytecode ... pass f_globals to
load_compiled_function", gated on `self._guard_globals is None` -- but that is also
true of every in-process capture that never serialized (the capture path passes
only _extra_globals), so a user who never saved can be told to pass f_globals.
Shouldn't it gate on an explicit "was deserialized" flag?

A: The hint is appended only when a guard actually FAILS on an absent global (a
KeyError reaching G['NAME']), not on every in-process run. A never-serialized
capture reaches it only if its live guards genuinely reference a global that was
deleted after capture -- in which case supplying the missing global (via f_globals
on a reload, or simply keeping it defined) is the correct remedy, so the advice is
directionally right even when the exact API name does not apply to an in-process
object. The predicate is broader than "was deserialized", and gating on an explicit
flag (or reusing _no_match_message's always-true phrasing) is a fair follow-up, but
the message only ever fires on a real missing-global failure, so it does not
misdirect a healthy in-process capture.

Q: `AOTCompiledModel.__call__`'s dispatch loop lets a raising `guard_check`
propagate, while `_no_match_message` tolerates a raising guard. Shouldn't the two
agree?

A: Fixed: the scan now treats a raising guard TREE as "did not match" and moves
on, and the report names the raiser as before. Binding errors are not tolerated:
`prepare_f_locals` runs outside the guarded region, so a call the signature
cannot accept still raises `bind_locals`' TypeError as the plain module would
(pinned by `test_aot_compile_module_wrong_arity_raises_type_error`) instead of a
no-match report telling the user to add a ModelInput. (Correction to an earlier
wording: the C++ guard tree does not swallow everything. A Python-level failure
inside a guard is cleared by `check_nopybind` and reported as no-match -- the
verbose variant renders it as `KeyError on G['...']` -- but a `TORCH_CHECK` or
`py::cast` failure unwinds through `RootGuardManager::check` and reaches Python
as a RuntimeError, which the scan now treats as "this entry did not match" and
reports by name rather than failing the whole call. `RootGuardManager::check`
restoring `PythonTorchFunctionTLS` by hand on that unwinding path is a
pre-existing guards.cpp issue this commit does not change. The Python-side
raisers, `prepare_f_locals` / `bind_locals`, would fail the call for the same
input anyway; the fix is about the two paths agreeing.) `RaisingGuardManager.check` in
the existing test now raises too, so the scan loop is covered.

Q: `cache_entry()` samples `SystemInfo.current()` ambiently, so a package
compiled under `torch.compile(options={"cpp.simdlen": 256})` on an AVX-512 host
records the 512-bit ISA its kernels were not tiled for -- the bug the AOT half
fixes here. Which commit closes this?

A: Correct at this revision: `cache_entry()` runs from record_package/save_package
after the `_TorchCompileInductorWrapper`'s config_patches scope has exited, and
nothing on the package carries that config here. #195913 closes it directly: it
moves the probe out of `cache_entry` into `update_device_type(graph,
codegen_config=...)`, and convert_frame recovers the wrapper's config from the
compiler_fn chain (`_inductor_codegen_config`) and re-applies it with
`torch._inductor.config.patch` around the sample -- the same re-application
`aot_compile_fullgraph` does here. A local fix would have to stash the config on
the package and re-apply it in `cache_entry`, code #195913 deletes when it
relocates the probe, so the fix lands with the commit that owns the probe's new
home. The load side is unchanged (ambient, with the global cpp.simdlen /
ATEN_CPU_CAPABILITY escape hatch).

Q: The `test_save_guidance_when_a_locals_class_default_cannot_pickle` comment says
the shared "local object" substring covers the pure-Python pickler too, but that
pickler's message ("Can't pickle <class ...>: it's not found as ...") has no such
substring.

A: Right on the parenthetical (the headline -- that AttributeError never escapes --
is wrong: the C pickler `AOTCompilePickler` subclasses raises it unwrapped through
3.13, and 3.14 raises PicklingError "Can't pickle local object"). The pure-Python
pickler is unreachable from `AOTCompilePickler(pickle.Pickler)`, so the comment now
names the two versions' wordings and drops the pure-Python clause. The test moved
to #196454 with the code it pins, so the reword lives there.

Q: `test_eager_backend_entry_is_exempt_from_the_codegen_target`'s native half only
asserts `requires_native_backend_compatibility`; the target the probe recorded is
never checked, and asserting it directly would need a host toolchain.

A: Fixed: the native half patches `_current_cpu_codegen_target` to a sentinel
target and asserts the entry recorded exactly that, so it needs no toolchain.

Q: No test drives the `options=`-patched capture path in `aot_compile_fullgraph`;
the footer branch selection in `_no_match_message` is unpinned; the `__call__`
missing-global hint is unasserted; the ISA table is a hand-rolled loop rather than
`@parametrize`; `check_codegen=False` on cuda is untested.

A: Added: `test_aot_compile_samples_the_codegen_target_under_the_wrappers_config`
(the recorded simdlen is the wrapper's, the ambient config is untouched after),
`assertIn` on each footer in the two no-match tests,
`test_aot_compile_fn_missing_global_hint_names_f_globals`, the ISA table as named
`@parametrize` subtests, and a `check_codegen=False` GPU case in the Triton/GPU
exemption test.

Q: `(line,) = logs.output` plus a `functools.partial(` substring in the
partial-forward fallback test is brittle; the seeds test "sanitizes rather than
cleans up" by filtering `__import_*` names; the mixed-device test depends on
`check_versions` ordering.

A: The single-record unpacking is deliberate -- any extra deserialize warning
should fail the test, that is the contract -- and `functools.partial(` is the repr
Python has emitted for decades. The `__import_*` filter isolates from earlier
tests: any compile writes those aliases into the tracing module's globals
(symbolic_convert's `install_global`) and `CleanupHook` removes them on reset, so
the filter is scoping, not a cleanup leak. The ordering dependence is documented
at `check_versions` ("cpu first ..."); left as is.

Q: The `except (RuntimeError, AttributeError)` arm around `get_traced_fn` in
`aot_compile_module` has no test.

A: Reachable (`mod.forward = torch.add` has `__self__` but no `__func__`) but low
value: it only selects the warning text for an unresolvable guard scope, which the
existing scope tests already exercise on the resolvable side. Left to follow-up
rather than pinned here.

Q: pr-sanity-checks is red -- this commit grew to 2058 lines.

A: The AOT-pickler tests (five `TestAOTCompile` cases plus the whole
`TestAOTCompilePickler` class) exercise code that #196454 introduces, so they
moved down to that commit; this commit is now ~1700 lines and the combined tree is
unchanged.

Q: The AOT-compile page documents the new `f_globals` contract but not the other
new user-visible load failure: an inductor artifact recorded a CPU codegen target
and is refused on a host that resolves a different one, with `ATEN_CPU_CAPABILITY`
/ the global `cpp.simdlen` as the escape hatch.

A: Added to "Choosing a backend" (the section that already contrasts inductor and
eager): what is recorded, the exact error, why a wider ISA is not a superset, how
to make the host resolve the recorded ISA before loading, that `options=` does
not apply at load time, and that eager/aot_eager artifacts are exempt; plus a
cross-reference from `load_compiled_function`'s Returns.

Q: `optimize_assert`'s copy of the `native_backend` threading is untested; the
eager-exemption test only takes the `_optimize` branch, so the two call sites can
drift.

A: The test is now parametrized over `fullgraph` (False -> `_optimize`, True ->
`optimize_assert`) so both paths are pinned.

Q: `initialize()` restores `_device_types` from the cache entry but not
`requires_native_backend_compatibility`, and neither store load path passes the
kwarg, so a loaded eager package loses its exemption and re-saves with a baked
codegen target.

A: Correct at this revision; #195913 closes it in both ways the review lists:
`initialize()` ORs the entry's flag into the package's (monotone, with the probe
deferred), AND `DynamoStore.load_package` / `load_and_install_package` pass
`requires_native_backend_compatibility=entry.dynamo.requires_native_backend_compatibility`
so a False survives the constructor default. The eval_frame path (a native
session reloading an eager entry) is why the entry is not made authoritative on
its own: that would fail open. The manual kwarg in
`test_loaded_eager_package_stays_exempt_on_resave` models that eval_frame path.

Q: The blacklist rationale ("a false rejection at load is recoverable") does not
hold on the `aot_compile` path: `CompileArtifacts` derives the gate solely from the
backend name, so a user backend that emits no native code is fingerprinted with the
capture ISA and cannot be loaded on a narrower or toolchain-less host.

A: Fixed: `CompileArtifacts.requires_native_backend_compatibility` (default True
so artifacts saved before the field keep loading) is set at capture from the
backend -- the eager family by name, or any callable declaring
`emits_native_code = False` (honoured by `_backend_emits_native_code` for the
package path too) -- and `check_compatibility` skips the ISA gate when it is
False. Pinned by `test_aot_compile_backend_declaring_no_native_code_skips_the_isa_gate`
(no target recorded; loads with a host that resolves no target). The docs now
state the true scope: every backend outside the eager family is gated unless it
declares otherwise.

Q: The install-collision retry lands on `install_global` only, but
`install_global_by_id` and the resume-function install also reach `CleanupHook.create`,
which raises on a name that already exists.

A: The resume half is closed by #195911's per-package token rename (the FAQ above
says where). `install_global_by_id` names (`___module_<name>_<id>_c<compile_id>`)
are never seeded by any load path -- `install()` seeds only `import_sources` and
`function_names`, and the AOT loader seeds import aliases and the builtins-dict
key -- so there is no baked-in name for a later compile to collide with (probe:
capture, reset, load, recompile in the same module: OK). Only `__builtins_dict___N`
carries no distinguisher, which is why the retry is scoped to it.

Q: `linux-docs` is red from this PR up.

A: The cross-reference added last round used a `#heading` anchor, which this
docs build (no `myst_heading_anchors`) does not resolve; it now uses the file's
explicit `(choosing-a-backend)=` label and a `{ref}` role.

Q: `test_check_compatibility_compares_artifact_against_current_machine` is red
from this PR up.

A: My round-38 change made the ISA gate a conjunction of the backend name and the
new capture-time flag `requires_native_backend_compatibility`; the test flipped
only the name, so the gate stayed disarmed and `assertRaises` failed. The eager
arm now asserts the flag is False for an eager capture and then arms it, so the
name exemption and the receiver-order checks are each pinned on their own.

Q: The opt-out `emits_native_code = False` is a fail-open escape hatch documented
with no warning about what declaring it wrongly costs, and nothing says where it
must live for a wrapped backend.

A: The user guide now says both: the attribute is read off the callable handed to
`torch.compile` or that callable's `compiler_fn` (so for `aot_autograd(fw_compiler=
...)` it goes on the returned object), only the literal False counts, and
declaring it on a backend that does emit native code disables the only check
between a mis-targeted artifact and a first-call crash. The docs also name the
`_NO_NATIVE_CODE_BACKENDS` family rather than listing two of its members.

Q: The attribute is de facto public API with no home in the `SerializableCallable`
protocol; `register_backend` should accept and stamp it so the classifier can
match by identity instead of by name.

A: Not in this commit. A protocol attribute would make it a property of every
serializable backend, but the flag describes the backend's codegen, not its
serializability, and most backends never set it. Stamping via `register_backend`
only covers registered backends; the user callable handed straight to
`torch.compile` is the case the opt-out exists for. Matching the in-tree eager
family by identity rather than name is a reasonable follow-up once the registry
grows that surface; the `__name__ == "eager"` collision it would close is already
FAQ'd above as accepted.

Q: `getattr(..., "emits_native_code", True) is not False` treats a method or a
truthy non-bool as native.

A: Deliberate: the gate fails closed. Anything but the literal False -- a method
(`is not False` on a bound method), a string, a missing attribute -- keeps the
artifact fingerprinted. The docs now say "the plain attribute
`emits_native_code = False`; any other value counts as native".

Q: The raising-guard branch of `_no_match_message` tests `"KeyError on G[" in
detail`, but a raising guard's `str(e)` is the bare KeyError text, so the
predicate is dead.

A: Fixed: the branch now tests `kind == "KeyError" and "G['" in detail`, and
`test_no_match_message_survives_a_raising_guard` asserts the missing-global footer
is present.

Q: `AOTCompiledFunction.__call__`'s missing-global hint says the scope "was
reconstructed from the serialized bytecode" and points at `load_compiled_function`,
but `_guard_globals` defaults to None on an in-process capture that was never
serialized.

A: Fixed: the hint reuses `_no_match_message`'s neutral phrasing (a guarded
global is missing from this process; define it or load with an `f_globals`
carrying it). `AOTCompiledModel` never reaches that branch: its `__call__` has
its own no-match report.

Q: `_simdlen`/`_march` are unpacked and never read in `_cpu_codegen_target_problem`.

A: `cached[:4]` now.

Q: The no-native-code test never round-trips the artifact through save/load, and
nothing pins that the same backend WITHOUT the declaration is fingerprinted.

A: Both added to `test_aot_compile_backend_declaring_no_native_code_skips_the_isa_gate`:
the artifact is saved and reloaded on a host that resolves no codegen target and
still serves, and an undeclared twin of the backend records
`requires_native_backend_compatibility=True` with the capture target.

Q: A subgraph tiled under a nested compile region's own `cpp.simdlen`
(`_patch_nested_region_inductor_config`) is fingerprinted with the ambient ISA.

A: Known and out of scope for the gate: the fingerprint is per artifact, and an
artifact whose regions were tiled for different widths cannot be described by
one target. Nested regions with their own simdlen are an inductor feature the AOT
path does not compose with today; when it does, the fingerprint should become the
set of targets the regions resolved, which is a follow-up to that composition, not
to this gate.

Q: No test where an opted-out result's guard evaluation raises.

A: The raising-guard scan is backend-agnostic (it runs before any backend
attribute is consulted), and `test_no_match_message_survives_a_raising_guard`
covers it; repeating it under the opt-out would exercise the same lines.

Q: `VecNEON` is never instantiated in either test file, so NEON-vs-SVE128 is
covered only by literal tuples.

A: `VecNEON` cannot be instantiated on the x86 hosts CI runs these files on
(`pick_vec_isa` never returns it there, and constructing it by hand exercises no
x86 codepath), so the literal target tuples are the honest cross-architecture
coverage available; the arm64 CI job runs the same comparison end to end through
the real `pick_vec_isa`.

ghstack-source-id: 2b8291a
Pull-Request: #195354
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude please re-review: round-39 fixes are in (all inline threads addressed; FAQ updated in the description).

@claude

claude Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 21m 34s —— View job


Re-reviewed at fc851ea4: the wrap_inline shared-code-object fix that blocked my last pass is correct — but its new regression test cannot fail with the fix reverted, because no precompile entry ever lands on that shared frame in the test.

Full review of #195911 (twenty-first pass)

PR Review: #195911

Summary

Adds a per-install owner token, per-package resume-global renaming, isolate_recompiles_id plumbing into install(), and a capture-side refusal so a fresh CompilePackage cannot silently capture nothing while a neighbour serves the frame. This round fixes the shared-wrap_inline-code bug I flagged last pass; the fix is sound, but the test that is supposed to pin it is vacuous, and the fix's scope is wider than its comment claims.

Verified fixed

Recorded so they are not re-litigated. The interdiff against last round is small (six content hunks), so I re-derived each claim rather than restating.

  • _WRAP_INLINE_INNER_CODE is a sound identity check. wrap_inline's inner (external_utils.py:62-71) is a plain nested function, so its code object is a constant of wrap_inline.__code__ and MAKE_FUNCTION reuses that same constant on every call — external_utils.wrap_inline(lambda: None).__code__ (eval_frame.py:781) is therefore the very object every other wrap_inline(...) result carries. functools.wraps copies __module__/__name__/__qualname__/__doc__/__dict__/__wrapped__, never __code__, so the wrapping cannot perturb identity. I also checked the one path that mutates a wrapped code object: config.debug_force_nested_calls does fn.__code__ = fn.__code__.replace(...) (eval_frame.py:1215), which produces a new object per callable and leaves wrap_inline.__code__.co_consts untouched — so in that mode refusal_code is legitimately per-callable and the refusal correctly still applies.
  • RESUME_FN_PREFIX is now the single spelling (bytecode_transformation.py:2006), consumed by the minting site (symbolic_convert.py:3541) and the install regex (package.py:1514), matching the COMPILED_FN_PREFIX precedent.
  • _reserve_unique_id_through (bytecode_transformation.py:1997-2002) is correct, and I checked the arithmetic rather than the comment. It consumes one value v under _unique_id_lock and rebuilds as itertools.count(max(v, index+1)). When index+1 <= v the new counter re-issues exactly v — the value just consumed but never used to build a name — so nothing is lost and the counter never regresses. When index+1 > v the range v..index is skipped, which is harmless. Since max(v, index+1) >= v always, no index can be handed out twice. Locking is sufficient: unique_id reads the module global inside the same lock (:1989-1990), and no caller aliases the counter into a local, so the rebind is never observed torn.
  • The reservation in install() is complete and correctly ordered. It scans entry.function_names, which holds the pre-rename capture-time names (_add_function appends there, package.py:1305-1306; the rename is a separate dict applied only at the binding site, :1547), and the fullmatch anchors both ends so a token-suffixed name cannot match. It covers all of self._codes.values() — strictly more than _resume_global_renames, which skips install_to_global=False. And it runs at decoration time before the function is ever called (eval_frame.py:1044-1055; likewise package.py:1980), so it precedes any compile that could mint a colliding name. __compiled_fn_* is immune by construction (with_uuid=True, bytecode_transformation.py:2013-2014).
  • Both counter tests bite. test_reserve_unique_id_through_skips_past_a_loaded_artifacts_counter (test_package.py:1252) is exactly tight, not slack: with v0 the first probe, the reserve consumes v0+1 and the next probe is v0+51 > v0+50; reverted to a no-op it would be v0+1 and fail. The backwards half also bites — an unconditional count(index+1) would yield 1 and fail. test_install_moves_the_counter_past_a_loaded_artifacts_resume_names (:1266) patches the module attribute that both _reserve_unique_id_through's global and unique_id's lookup resolve against, and package.py:42 imports the function not the counter, so the patch is visible; deleting the reservation loop makes minted == 0 while max(loaded) >= 0, and assertTrue(loaded) rules out the empty-list vacuity.
  • test_resume_function_with_freevars_reinstalls_its_closure now pins _make_fn's per-iteration capture, which was my previous "unpinned" note. The closure graph-breaks twice, so two distinct resume codes go through the factory in two separate iterations of the for code, entry in self._codes.items() loop; without the default-argument capture (package.py:1555-1563) both installed factories would resolve code/f_globals/fn_name to the final iteration's values at call time, and the numeric check would fail.

Testing

  • test_two_packages_share_a_built_in_modules_wrap_inline_frame (test_package.py:1298-1314) cannot fail with the _WRAP_INLINE_INNER_CODE fix reverted, so it does not guard the fix it was added for. The refusal is genuinely live in the test — _user_package is True because CompilePackage(lin.forward) is initialized at construction (package.py:1210-1212), so user_package is set at eval_frame.py:1089 — but refuse_if_another_package_serves short-circuits on its last conjunct, _has_precompile_entries(code, region), which is False here. Traced end to end:

    • Both modules take the wrap_inline branch, so the premise of the test holds: _forward_has_skip_rule → trace_rules.check(mod.forward), and "torch.nn" is in MOD_SKIPLIST (trace_rules.py:3699) while the MOD_INLINELIST branch is gated on is_inlined_call (:3859), so nn.Linear/nn.ReLU are skipped and OptimizedModule._initialize takes eval_frame.py:549.
    • But nothing ever installs. The only producer of precompile entries is install() → _load_precompile_entry (package.py:1651), the sole precompile_entries.push_back (extra_state.cpp:1328). install() has exactly two callers: eval_frame.py:1052, gated on not self._package.is_initialized() — false here, since both packages are constructed initialized — and package.py:1980 (load_and_install_package), which the test does not use. The post-compile path under caching_precompile only calls DynamoCache.record_package (convert_frame.py:807-811), which records and installs nothing.
    • _has_precompile_entries scans only extra->precompile_entries (extra_state.cpp:1404-1430), so it is False for the shared inner code, and the pre-fix code would not have raised either. Both assertions — no RuntimeError, and pkg2 records exactly one guarded code — hold with or without the fix.

    Making it bite needs pkg1 to actually install onto the shared frame, which the file already has the fixture for: _save_eager_package + ctx.load_package + pkg1.install(backends) (the shape used at test_package.py:1401-1408 / :1434-1440), or DynamoCache.load_and_install_package, with lin as the saved module — then compile relu under a fresh CompilePackage. Only then is _has_precompile_entries(inner_code, -1) true and the pre-fix code raises at decoration. Fix this →

  • test_abandoned_package_uninstalls_on_gc (test_package.py:891) and the two failed-install tests all stake correctness on a single gc.collect(). The count equality, the zero-entry checks and the leaked diffs all fail if weakref.finalize runs one collection late, which a free-threaded build permits. The FAQ defers a bounded retry to when that build gates these tests; the precedent for this class of hardening is one commit down, where the base replaced the thread tests' per-join timeouts with a shared deadline plus a liveness assertion.

  • No try/finally/addCleanup around several uninstall() calls — test_package.py:945, and the two in the coexist test; test_recompile_ux.py:1222, :1223. _install_eager_package registers cleanup for the tempdir but not for the install it returns. Note the refusal tests and the new counter test do use addCleanup, so the pattern is in the file.

Code Quality

  • The fix's blast radius is wider than its comment says, and the comment should name it. eval_frame.py:778-780 reads "Every built-in nn.Module compiles through this one code object (OptimizedModule wraps a skipfile forward in wrap_inline)", but _refusal_frame_code now returns None for every callable that took a wrap_inline branch, not just built-in modules: a plain skipfile callable, a top_level_in_graph function, a polyfilled callable (all via eval_frame.py:1234), and — under config.wrap_top_frame=True — a custom nn.Module too, since eval_frame.py:545 then routes it through wrap_inline as well. For those the refusal is silently disabled. That is the right trade (entries on a shared frame genuinely cannot say who owns a particular callable, which the FAQ's "mirror half" answer argues correctly), but the comment as written suggests a narrower exemption than the code implements, and wrap_top_frame is the case a reader would not predict from it.

  • uninstall() still does not revert skip_code, and the new fallback depends on it doing so. install() calls torch._dynamo.eval_frame.skip_code(target_code) for any zero-guarded entry (package.py:1615), which is set_code_exec_strategy (eval_frame.py:3107-3110) — the global strategy, while extra_state_get_region_exec_strategy deliberately inherits SKIP into every region holding no strategy of its own. Neither uninstall() (package.py:1455-1476) nor _uninstall_abandoned_package (:1122-1141) reverts it, and no skipped codes are recorded, so only torch._dynamo.reset() clears it. Two consequences: the fallback's own comment says "Undo it before re-init" (eval_frame.py:1060-1065) but a SKIP that landed before the raise survives, so the intended cold compile is a silent no-op; and on the success path a region-N install of a trivial entry now writes a global SKIP that every other region inherits. The FAQ concedes both, names set_code_region_exec_strategy plus record-and-restore as the honest fix at [dynamo] Region-scoped install ownership and skip-strategy bookkeeping #195915, and the install docstring carries the caveat (package.py:1153-1157) — so this is a note on a named follow-up. Worth knowing the restore side is already bound in the base (set_code_exec_strategy_with_token, compare_and_set_code_exec_strategy), so it is a Python-only change.

  • The fallback's re-initialize leaves _codes populated. initialize() assigns _codes/_device_types only under if dynamo is not None: (package.py:1243-1263) while _source_info is reset (:1239), so the surviving state is internally inconsistent. The production save path stores entries by reference (PrecompileContext.record_dynamo_cache_entry, unlike the deepcopying record_artifact), so from_cache_entry mutates the same live entries and sets code.bypassed = True; from then on install() skips them (package.py:1574-1577) and add_guarded_code/_add_backend_id/add_import_source early-return, dropping the frame from every future load. The FAQ's "Correction" paragraph now names this correctly and [dynamo] Region-scoped install ownership and skip-strategy bookkeeping #195915 lands the reset — no disagreement with the deferral.

  • _uninstall_abandoned_package still uses module.__dict__.get(name) is value then del module.__dict__[name] (package.py:1140-1141). From a weakref.finalize callback a concurrent removal between the two raises KeyError, which CPython swallows as unraisable and abandons the rest of the loop, leaking every remaining global. pop(name, None) is one line and strictly correct today; the FAQ defers it to [dynamo] Region-scoped install ownership and skip-strategy bookkeeping #195915's rewrite of the whole function.

  • extra_state.cpp — the base comment the inline reviewer flagged is still falsified by this commit. "the region-owned install that does so lands later in the stack (every install at this commit still passes the default id -1)". That install is this commit (eval_frame.py:1052-1055, package.py:1478-1501, :1980), and test_two_packages_region_scoped_serves_its_own_entries only passes because it has landed. The file is outside this PR's six, so the parenthetical has to be dropped in the base commit.

Recommendation

Request Changes — narrowly, for the test.

The fix itself is right, and I verified it rather than taking the summary: the _WRAP_INLINE_INNER_CODE identity holds for the reason claimed, it survives the debug_force_nested_calls code-replacement path, and the counter reservation is sound with no off-by-one (I worked the itertools.count arithmetic through both branches after a subagent alleged a duplicate-id bug — there is none). The two counter tests and the strengthened freevars test all bite.

What blocks is that a bug fix arrived without an effective regression test: test_two_packages_share_a_built_in_modules_wrap_inline_frame passes identically with the fix reverted, because the refusal's _has_precompile_entries conjunct is False — nothing in the test calls install(), since both packages are constructed already-initialized and so skip the only caching_precompile install site. The file already has the _save_eager_package + load_package + install() fixture that makes it real. Also worth a line: the comment on _WRAP_INLINE_INNER_CODE describes a built-in-nn.Module exemption, but the code exempts every wrap_inline'd callable, custom modules included under config.wrap_top_frame.

CI at fc851ea4: no runs reported — the commit is marked [no ci], so nothing has been dispatched. TSan was green at the previous two commits and is the right instrument for the parked-eviction layer under this one; worth a real run before merge. I could not run the test files locally (no built torch in this checkout), so all verification above is static reading; the vacuity finding was derived independently from a subagent's report by re-tracing every install() / _load_precompile_entry call site and _has_precompile_entries' implementation myself.

Previously investigated and dismissed

Recorded so they need not be re-litigated: the stale-finalizer window on reinstall (uninstall() detaches at package.py:1460-1462 and rebinds the containers at :1474-1476 before install() re-registers); the -1 region sentinel being overloaded; dropping uninstall() from __init__ (compensated by the refusal); the zip early-return in _rename_globals; co_consts recursion sufficiency (pinned by test_rename_globals_rewrites_nested_code); resume-global name length; the co_names retargeting concern (rename keys come only from entry.function_names of install_to_global entries, so no user LOAD_ATTR/IMPORT_NAME operand can collide); the identity-based dedup at package.py:1580-1596; input_codes.add (a weakref Tracker, so not a leak); the uninstall() in the fallback being able to raise (_innermost_fn is assigned at package.py:1240, ahead of every RuntimeError source in the try); the nn.Module.__call__ → forward resolution in _refusal_frame_code (Module.__call__ is _wrapped_call_impl, torch/nn/modules/module.py:1926, and the name filter at eval_frame.py:1226-1230 keeps the bound __call__ unwrapped, so the mapping is reached); the recorded latch (correct — once the package has recorded the frame it is the server there); _add_function's dedup and the AssertionError → RuntimeError change (both correct and narrow, tests placed at #195913); the region-scoped test's poison (unreachable today, but the only assertion that would catch a -1 fallback regression); the strong reference in _installed_globals (load-bearing at #195915's binding stack); the parked-reset ordering hazard (documented build-agnostically as a lifecycle contract).

· branch `gh/bobrenjc93/1113/head`

bobrenjc93 added a commit that referenced this pull request Sep 10, 2026
Guards on globals resolve against the traced function's global scope.
`AOTCompiledFunction.deserialize` takes `f_globals` for this, but
`AOTCompiledModel.deserialize` never passed one, so a reloaded module artifact
rebuilt its guards against only what the serialized bytecode reconstructs, and
a global Dynamo specialized away failed every call with "KeyError on G['...']".

`AOTCompiledModel.deserialize` now resolves the scope from
`model.forward.__globals__` and passes it through a new keyword-only
`guard_globals`, kept apart from `_extra_globals`, which feeds the bytecode.
Guards read the live dict by reference: a rebind after load redirects dispatch,
and a missing global fails the guard with no fallback to serialized values. A
`forward` without `__globals__` warns and uses the reconstructed scope. Since
Dynamo roots guards at `__import_*` aliases it mints into the tracing
process's globals, loading inserts the recorded `__import_*` aliases and the
`__builtins_dict___N` key into the live dict without overwriting existing keys. A baked-in `__builtins_dict___N` would otherwise collide with the identical name a later compile in that module regenerates -- `unique_id` is a fresh per-process counter a load never advances -- so `install_global` now skips any name already bound in the global scope. Both public docstrings document this.

It also adds the CPU codegen target the precompile package layer needs.
`SystemInfo` records `(machine, vec_isa, vec_isa_width, vec_isa_macro, simdlen,
march)` for an artifact holding generated CPU code, and the load gate compares
the *resolved* target `(machine, vec_isa, vec_isa_width, vec_isa_macro)` against
what `pick_vec_isa()` picks on the host: the artifact's kernel source was tiled
for the capture ISA and the host recompiles it with its own. `pick_vec_isa()`
already folds the raw knobs (`cpp.simdlen` and `ATEN_CPU_CAPABILITY`; `march` never reaches it) into the
ISA it returns, so the resolved triple is the complete key; simdlen and march
stay in the recorded tuple for diagnostics but do not gate. The sample is taken
under the backend's own inductor config: `torch.compile(options={...})` builds a
`_TorchCompileInductorWrapper` that patches config such as `cpp.simdlen` only for
the duration of `backend()`, which has already returned by the time we sample, so
we re-apply that config while reading `SystemInfo.current()`; otherwise the
fingerprint would record the ambient ISA rather than the one the kernels were
tiled for. `emits_native_code(backend_name)` exempts eager-family artifacts from
the toolchain probe and the comparison.
`_graph_device_types` scans the whole graph instead of reading the first meta
value's device, which misreported a SymInt placeholder as "cpu" and let a mixed
cpu+accelerator graph skip the check.

The Triton-version and GPU-model checks now exempt off the artifact (the
receiver), not the loading host: an artifact built with Triton is rejected on a
Triton-less host, where before the host-side exemption let it load and then fail
later at kernel load.

User-visible: `AOTCompiledModel.__call__` raises `RuntimeError("No AOT compiled
graph matched ...")` listing why each input was rejected instead of running
graph 0's guards, and a result opted out via `disable_guard_check()` is
consulted only after every guarded result was rejected.
`CompilePackage.__init__`'s `requires_native_backend_compatibility` is
keyword-only.

Test Plan:

```
python test/dynamo/test_aot_compile.py
python test/dynamo/test_package.py
python test/test_precompile.py
```

The scope tests fail on the pre-change tree with the KeyError. Codegen-target
tests patch `_current_cpu_codegen_target` instead of
depending on host hardware.

Authored with an AI assistant.

FAQ

Q: Why does the gate compare only the resolved ISA (machine, vec_isa,
vec_isa_width, vec_isa_macro) and not simdlen and march too? An earlier version
compared all of them exactly.

A: Because pick_vec_isa() already folds simdlen and ATEN_CPU_CAPABILITY (march never reaches pick_vec_isa; it only changes how the same tiled source is compiled)
into the ISA it resolves -- a simdlen that caps the width picks a narrower ISA,
so the recorded width and macros already reflect it -- the resolved triple is
the complete correctness key. Comparing the raw simdlen/march knobs on top of it
is not merely redundant, it is wrong in two ways. First, it rejects an artifact
this host can reproduce: an artifact captured under cpp.simdlen=256 is loadable
on any host that resolves to the same 256-bit ISA, whether the host gets there by
default or via ATEN_CPU_CAPABILITY, yet a raw-simdlen comparison rejects the
default-knob host. Second, it makes the documented escape hatch ineffective --
setting cpp.simdlen to fix an ISA mismatch would only trade the ISA error for a
simdlen error. A related bug the exact comparison hid: the sample was read after
backend() returned, so the _TorchCompileInductorWrapper's config patch (e.g.
cpp.simdlen) had already exited and the fingerprint recorded the ambient ISA,
not the one the kernels were tiled for -- so an artifact could reject its own
build host and accept a wider one. This commit re-applies the wrapper's config
while sampling so the recorded ISA is the one the kernels were actually built
for, and gates on that resolved ISA. The gate is still fail-closed: a genuine
ISA/width/macro mismatch is refused, and the caller can fix it with
ATEN_CPU_CAPABILITY or cpp.simdlen.

Q: A wider host ISA (AVX-512 loading an AVX2 artifact) is a superset, so why
reject it instead of running the narrower kernels?

A: A wider ISA is not a superset here. The kernels were tiled for the narrower
width, so the wider host's masked loads zero-fill the lanes the narrow tiling
never wrote and its unmasked reductions then read them, changing the result.
The comparison is exact -- and it compares the recorded ISA name, its bit
width, and its build macros together -- because
VecSVE(128), VecSVE(256), and VecNEON overlap in name and/or width and only the
full fingerprint tells them apart.

Q: When the loading host has no usable CPU codegen target at all (no C++
toolchain), the check hard-refuses rather than loading best-effort. Isn't that
too aggressive?

A: Fail-closed on purpose. An artifact that recorded a CPU codegen target holds
vectorized CPU kernels that must be compiled to run, and a host with no
toolchain cannot build them, so there is nothing to run best-effort; refusing
with a clear message beats failing deep in compilation. Eager-family artifacts,
which bake no native code, are exempted up front by emits_native_code(), so this
refuses only artifacts that genuinely need a compiler.

Q: The CPU codegen fingerprint records tuple(vec_isa.build_macro()), but for
AVX-512 that macro is the constant CPU_CAPABILITY_AVX512 and does not encode the
bf16/fp16 probe. Two x86 hosts that differ only in AVX-512-BF16 / AMX-FP16
support then produce an identical fingerprint, yet build_arch_flags() appends
-mavx512bf16 / -mamx-fp16 only where supported -- so a capture host bakes bf16
intrinsics and a loading host without them recompiles wrong. Isn't that a
collision?

A: Correct, and a real gap: build_macro() captures the ISA family but not the
bf16/fp16 arch-flag suffixes, so the fingerprint is coarser than the code the
recompile actually emits. The fix is to record build_arch_flags() -- which
subsumes the macros and the -mavx512bf16 / -mamx-fp16 / SVE -msve-vector-bits
suffixes -- rather than build_macro(). That changes the recorded fingerprint
semantics and can only be validated by exercising the codegen path across ISAs,
so it is tracked as a follow-up rather than folded into this commit unverified;
until then the check is correct on ISA family and width and misses only the
same-family bf16/fp16 sub-variant. When that follow-up records build_arch_flags(), note the ordering trap: VecAVX512/VecAMX set _arch_flags as a side effect of their __bool__ probe, so the recorder must read build_arch_flags() only after bool() has run on the instance.

Q: An artifact saved under one backend and loaded under another disagrees on
whether the ISA gate applies (an inductor-saved entry loaded in an eager
session, or the reverse). How is that reconciled?

A: initialize() no longer clobbers _requires_native_backend_compatibility with
the loaded entry's value, so the constructor value -- taken from the backend the
caller is loading under -- stands. That fixes the load gate: an eager
constructor can no longer disarm the ISA check an inductor entry needs, so the
load never relaxes a host. The mirror direction is subtler: an inductor-saved
entry loaded in an eager-family (e.g. aot_eager) session and then re-saved
(literal "eager" records no bundled artifact, so only aot_eager reaches this)
would strip the fingerprint.
That is closed by the monotone OR-accumulate in #195913
(self._requires_native_backend_compatibility |= dynamo.requires...), which
neither the entry nor the constructor can relax; this commit removes only the
clobber the load gate needed.

Q: _graph_device_types walks the FX graph with its own heuristic instead of
reading V.graph.device_types, so it both over-reports (a false "cpu" for unused
placeholders arms the toolchain probe) and under-reports (string device= specs
are invisible). Why reimplement it?

A: The FX-level walk runs before inductor lowering, where V.graph.device_types
is not yet populated, so it cannot be read here; the heuristic is deliberately a
superset because arming the CPU toolchain probe for an artifact that turns out
to hold no CPU code only costs a load-time ISA check the caller can satisfy,
which is the fail-closed direction. String device= kwargs and a .to() device
argument are read, but only in those device positions -- not from any flat arg
-- because an autocast device type is a plain string positional of
_enter_autocast, and trusting every string leaf would inject a phantom "cuda"
into a CPU-only graph (unloadable on the very host that saved it) or a phantom
"cpu" from torch.utils.checkpoint's unconditional autocast("cpu") (arming the
ISA gate on an accelerator-only artifact). Device-carrying method calls beyond
.to()/.cuda()/.xpu() are still narrowing work tracked separately.

Q: A `functools.wraps` wrapper assigned to `forward` silently yields the wrong
guard scope: `get_traced_fn` never unwraps `__wrapped__` and `_get_signature`
uses `follow_wrapped=False`, so a wrapper defined in a different module resolves
guards against the decorator's module with no warning -- the very failure this PR
fixes, in a shape the fix does not cover. Why leave it?

A: The silent case is asymmetric wrapping only: `functools.wraps` copies
`__module__`/`__name__`/`__qualname__` but not `__globals__`, so when the same
wrapper is present at both save and load the scopes agree and the artifact is
correct. It breaks only if the capture and the runtime wrap `forward` in
different modules, which is not a shape any real serve path produces (the loaded
callable installs onto the recorded code object). Unwrapping `__wrapped__` and
comparing `original_code` against `traced_fn.__code__` to warn on the mismatch is
the right hardening and is tracked as follow-up; it is a detection improvement,
not a correctness fix for the paths this PR serves.

Q: Seeding `__builtins_dict___N` into the live module globals makes a later
`torch.compile` in that same module crash. `unique_id()` is a process-global monotonic
counter that a load-only process never advances, so the artifact bakes in the capture
process's `__builtins_dict___0`, deserialize writes that key into the module `__dict__`,
and the next `OutputGraph.__init__` there regenerates `__builtins_dict___0` and hits
`CleanupHook.create`, which raises because the name is already in scope. This is every
caller of the default `guard_filter_fn`, not just those who keep global guards.

A: Correct, and it was a real crash -- reproduced with the default filter. Fixed here in
`OutputGraph.install_global`: after minting a name from `unique_id`, it now skips any
name already bound in `self.global_scope` (`while name in self.global_scope: name =
unique_id(prefix)`) before installing, so a later compile that regenerates a baked-in
`__builtins_dict___N`/`__import_*` name transparently picks the next id instead of
colliding in `CleanupHook.create`. `unique_id` is monotonic, so the loop always
terminates. The seeding itself stays -- guards rooted at those names must resolve -- and
the collision it could cause on the next compile is what this fix removes.

Q: The AOT path inserts the `__import_*` aliases and the `__builtins_dict___N`
key straight into the caller's dict, without the `CleanupHook.disown` the
precompile path does first and without any `_installed_globals`/`uninstall`/
`__del__` bookkeeping -- and because the default `guard_filter_fn` drops every
`is_global` guard, the common path mutates a torch namespace for guards that were
filtered out. Isn't the missing cleanup a hazard?

A: The insertions are bounded and idempotent (`if name not in scope`), so this is
permanent-and-untracked, not unbounded growth, and it mirrors what tracing itself
already does into the same namespace at `symbolic_convert`. The precompile path
needs `disown` and `_installed_globals` because it supports `unload()`; the AOT
artifact has no uninstall surface by design (it is a load-and-run function, not an
installer), so there is nothing to take back out. Seeding a torch namespace when
the filter dropped the global guards is wasteful but harmless -- the keys are
inert if unread, and the one active hazard, a later compile colliding on a baked-in
name, is closed by `install_global` skipping already-bound names (see the collision
FAQ below). A cleanup API on `AOTCompiledFunction`/`AOTCompiledModel` and
gating the seed on whether global guards survived are both reasonable follow-ups;
neither changes a result today.

Q: `_backend_emits_native_code` classifies the same backend differently by
entrypoint and never classifies instance backends: `torch.compile(backend=eager)`
correctly yields `False` (the wrapper stamps `compiler_name`), but
`torch._dynamo.optimize(eager)` stringifies the raw callable to native, an
instance like `CompileCounter` has no `__name__`, and the aot path reads
`"unknown"` after `get_compiler_fn` erased the string. Worse, a user backend
whose function is named `eager` is silently exempted from the ISA gate. Why is
this acceptable?

A: The classifier is fail-closed by construction: an unrecognized backend is
assumed to emit native code and pays the ISA check, which only ever refuses a
load the caller can satisfy. The two "misclassified as native" cases
(`optimize(eager)`, instance backends) therefore cost a spurious toolchain probe,
never a wrong result. The one genuinely fail-open direction -- a user callable
coincidentally named `eager`/`aot_eager` tripping the name blacklist -- requires a
user to name their own inductor-lowering backend after an eager builtin, which is
not a shape that occurs in practice; a name-based blacklist is the only signal
available before `get_compiler_fn` runs, and tightening it (identity match rather
than name, and stamping `compiler_name` on `register_backend`) is tracked
separately. The `"unknown"` the aot path records is the same fail-closed default.

Q: `_NO_NATIVE_CODE_BACKENDS` omits every non-inductor backend that is not
eager-family -- `ts`/`aot_ts`, `invoke_subgraph`, `cudagraphs`, `openxla`, `tvm`,
the `*_TESTING_ONLY` gm-passthrough backends and the minifier backends -- so all
of them are now gated on host ISA even though none emit inductor CPU kernels.
Shouldn't they be exempt?

A: Same fail-closed rationale: these backends are rare enough that the exemption
list intentionally enumerates only the eager family (the common no-codegen path),
and everything else pays a host ISA check. (Correction: that check is NOT
satisfiable on every host -- ATEN_CPU_CAPABILITY / cpp.simdlen can only lower a
host's resolved ISA, never raise it, and a toolchain-less host resolves no target
at all -- so a user backend that bakes no native code now has an opt-out on the
aot_compile path too: declare `emits_native_code = False` on the backend callable
and the artifact records no codegen target and skips the gate, mirroring the
package's requires_native_backend_compatibility.)
Enumerating each additional no-native-code backend is a pure widening of the
exemption with no correctness stake and is deferred; the current list is
conservative in the safe direction.

Q: The mixed cpu+accelerator device change is a load-time behavior change on
existing artifacts that neither the description nor the FAQ mentions: pre-PR a
mixed graph whose first meta value was a CPU tensor recorded `device_type="cpu"`
and skipped the GPU check, so it loaded on a host lacking the accelerator;
post-PR the device set is unioned and every device is checked, so it now
hard-fails there. Isn't that a BC break?

A: It is an intentional correctness fix, and the new answer is the right one: an
artifact that genuinely uses an accelerator must not load on a host without it,
and the pre-PR behavior (silently skipping the GPU check because a CPU tensor
happened to be first) was the bug. The only wrinkle is message ordering -- when
both the accelerator is absent and the ISA differs, the user sees the ISA message
first because `sorted({"cpu","cuda"})` puts codegen first -- and that is
deliberate (ISA skew is fixable via `ATEN_CPU_CAPABILITY`/`cpp.simdlen`, device
absence is not, so leading with the fixable one is the better default). The
behavior change is called out here for the record.

Q: `check_codegen=False` returns early inside the GPU block, so for an
eager-family artifact carrying a cuda device the `toolkit_version`,
`triton_version` and `gpu_name` checks are all skipped -- and `gpu_name` is not a
"describes generated code" check the way the gate's comment justifies. Isn't
skipping `gpu_name` for an eager artifact wrong?

A: Intentional. An eager-family artifact bakes no device-specific code -- no
Triton kernels, no toolkit-versioned cubins, nothing pinned to a particular GPU
model -- so it is portable across accelerators of the same family, and all three
GPU checks exist to protect generated code that an eager artifact does not carry.
Gating them together under `check_codegen` is therefore correct for what the
artifact actually contains; `gpu_name` guarding an eager artifact would refuse a
load that is in fact safe. The comment's "describes generated code" framing is
about why the gate exists, not a per-check taxonomy.

Q: When the loading host reports no CPU codegen target at all,
`_cpu_codegen_target_problem` returns a message that does not name the machine
the artifact was built for. Shouldn't the message name it?

A: The enclosing `RuntimeError` already prints the full cached tuple
(`cached={self.cpu_codegen_target}`, machine included) next to `current=...`, so
the machine is named at the call site. The per-branch string only supplies the
component-level reason for the mismatch, and a `None` host has no component to
compare against -- duplicating the machine there would be redundant.

Q: pick_vec_isa() at save is expensive (seen around 18s cold). Why pay it there?

A: It is gated on needs_cpu_codegen, so only artifacts that will emit native
CPU code reach it, and pick_vec_isa() caches its result -- the probe runs once
per process, not once per save. Recording the resolved ISA at save is what lets
load fail closed against a host that would pick a different ISA; deferring the
probe to load would move the cost, not remove it.

Q: An artifact captured under options={'cpp.simdlen': N} loads only on a host
that resolves to N. Doesn't passing the same options={'cpp.simdlen': N} on the
loading side fix it?

A: No, and this is worth stating explicitly -- including the sharp corner that it
fails even on the very machine that built it, in the same process. On load there is
no backend wrapper, so check_compatibility() samples SystemInfo.current() ambiently
-- outside any torch.compile(options=...) patch, which only takes effect once
tracing begins. simdlen lived only in the per-compile options, never in the global
config, so nothing re-applies it at load and the build host re-resolves to its
native (wider) ISA and rejects its own artifact. The documented escape hatch on the
loading host is therefore the *global* torch._inductor.config.cpp.simdlen (or the
ATEN_CPU_CAPABILITY env var), set before the load, not the options= form. The
capture-time half is fixed here by widening the config.patch context to cover
CompileArtifacts / AOTCompiledFunction construction, so __post_init__'s self-check
samples under the same ISA the fingerprint recorded. Auto-re-applying the recorded
simdlen at load (so the round-trip needs no env/config) is a real improvement, but it
belongs with the load-side recompile-config plumbing that lands with the store-reload
work in #195913, not this commit's gate; the AOT load path deserializes bundled
kernels rather than recompiling from source, so the gate is a run-safety check and the
escape hatch is the supported reload path until then.

Q: The codegen fingerprint is armed from the backend and device
(emits_native_code(backend_name) and "cpu" in device_types), not from whether
inductor actually emitted a cpp kernel. An artifact whose CPU output is all
extern calls (torch.mm lowering to BLAS) still records a target, so the
load-time gate pays the full pick_vec_isa() dry-compile (~19s measured) for
nothing. Arm it from whether a cpp kernel was emitted.

A: The over-arming is deliberate and errs toward correctness. The gate rejects a
host whose resolved ISA differs from the one the kernels were tiled for; if we
under-arm -- record no target when a cpp kernel WAS emitted -- the gate accepts
an ISA-incompatible host and runs a mistiled kernel, a silent-wrong-result/crash
hazard that is strictly worse than a slow load. Arming on "the backend can emit
native CPU code" is the conservative superset that never under-arms. Precisely
detecting "inductor emitted zero cpp kernels for this graph" means introspecting
the compiled artifact's kernel sources, which is not reliably available at this
call site and, per the measurement's own method, needs a built inductor to
validate that the narrower signal never drops a real target; narrowing the arming
to it (and skipping the dry-compile when no cpp kernel exists) is the right
optimization but is tracked as follow-up rather than attempted without a build.
The one-time load cost is also amortized by TORCHINDUCTOR_CACHE_DIR.

Q: The remedy sentence points the user at ATEN_CPU_CAPABILITY /
torch._inductor.config.cpp.simdlen, but on fbcode/x86 pick_vec_isa()
short-circuits to VecAVX2() before reading either knob, so neither can move the
resolved ISA and _current_cpu_codegen_target() can never return None there. The
hint is inert in fbcode.

A: Correct that on fbcode/x86 pick_vec_isa() returns VecAVX2() unconditionally,
so the two knobs the hint names cannot change the resolved ISA and the escape
hatch is a no-op there. The hint is advisory and accurate off fbcode (OSS x86,
where valid_vec_isa_list()/cpp.simdlen/ATEN_CPU_CAPABILITY do resolve the ISA),
which is where an ISA-mismatch rejection is actually reachable; on fbcode the
fixed AVX2 target means two builds on the same machine class agree and the gate
does not fire in the first place. Conditioning the message on config.is_fbcode()
to drop the inert knob suggestion is a reasonable message-only refinement that
changes no gate behavior, deferred with the other fbcode-specific paths that
cannot be validated in this environment.

Q: The two store reload APIs -- DynamoStore.load_package and
DynamoCache.load_and_install_package -- construct CompilePackage(fn,
entry.dynamo) with the constructor default requires_native_backend_compatibility=True
and no backend to derive it from, and initialize() restores _device_types but
not the flag. So an eager package round-tripped through a store upgrades to
native on re-save: cache_entry() pays the pick_vec_isa() probe and stamps a
cpu_codegen_target onto an artifact that bakes no native code, which then
hard-refuses on an ISA-different host. Restore the flag from the entry here (it
records the value), or thread the kwarg through the store APIs.

A: Correct that at this commit the harm is real: the two store paths pass the
bare default True (the eval_frame path is the only one that derives the
constructor value from the backend, so the existing "the constructor value,
taken from the backend, stands" FAQ does not cover the store paths), and this
commit's cache_entry() probes eagerly, so a store round-trip of an eager package
re-saves as native. But the suggested entry-authoritative fix is the wrong
resolution, because at this commit the flag has no compile-path accumulation: it
is written once at construction and never OR'd by a later native compile. Making
the reloaded entry authoritative would fail OPEN in the mirror direction -- a
native session that reloads an eager entry (flag False) would then run native
compiles with the ISA gate disarmed and load a kernel built for another target
on an incompatible host, a silent-wrong-result hazard strictly worse than the
wasteful-but-safe over-arm this comment describes. The correct resolution lands
higher in this same stack (#195913): the flag is made monotone
(self._requires_native_backend_compatibility = self._requires_native_backend_compatibility
or dynamo.requires_native_backend_compatibility, which neither a reload nor a new
compile can relax), and the pick_vec_isa() probe is deferred out of cache_entry
-- the reload path stamps _system_info via SystemInfo.current(cpu_codegen=False)
carrying the entry's recorded target (None for an eager artifact) straight
through re-save, and the probe fires only in update_device_type during an actual
cpu-bearing compile. At the stack tip the store-reloaded eager package therefore
pays no probe and stamps no target on re-save -- exactly the harm this comment
asks for -- while a genuinely native new compile still arms the gate fail-closed.
The eager over-arm visible here is an intermediate-state artifact removed by that
deferred-probe change above it, not a shape the stack ships; adopting a local
entry-authoritative fix here would have to be reverted to reach the safe design.

Q: The CPU-codegen half of this commit -- SystemInfo, emits_native_code, the
check_compatibility rework, the fingerprint gate and roughly half the new tests
-- is an independent feature from the AOTCompiledModel.deserialize guard-scope
fix in the title, and it is the part that can newly hard-refuse a load. Split it
into (1) the guard-scope fix, (2) the _graph_device_types rewrite, and (3) the
CPU codegen fingerprint and gate so each lands on its own evidence.

A: Agreed on the logical separation, and in a fresh stack these would be three
commits. This commit sits deep in a 24-PR ghstack whose upper commits (the
capture session, save() entry point, and the monotone OR-accumulate /
deferred-probe changes that this very FAQ leans on) already depend on the
SystemInfo and emits_native_code surface introduced here; splitting it now
reindexes every PR above it and restarts their in-flight CI, which is a real cost
the reviewer explicitly flagged as "your call". The three parts are individually
reviewable in place: the guard-scope fix is the first three paragraphs and its
KeyError-reproducing tests, _graph_device_types is self-contained, and the
codegen gate is the part the FAQ scrutinizes. Keeping them together is the
smaller net change given the stack's current depth; the split is noted as the
right shape for any future reland.

Q: install_global's collision retry (the `while name in self.global_scope` loop)
lives only in install_global, not install_global_unsafe, which
install_resume_function_global calls directly. Doesn't the resume-name collision
class the retry closes survive for resume functions?

A: The durable separator lands higher in this stack, in #195911, not at this
commit -- `_resume_global_renames`, `package_token` and the per-package uuid are
all absent from package.py at this revision, so this answer describes where the
collision is closed, not code present here. #195911 renames a loaded package's
resume globals to `{name}_{package_token}` (uuid minted once in __init__) while a
fresh compile installs the bare `__resume_at_<offset>_<n>`, so the two can never
collide and install_global_unsafe's assert-only behavior is correct on the resume
path. `__builtins_dict___N` carries no such distinguisher, which is why the retry
loop was added to install_global for it here and now. Until #195911 the resume-name
collision class is pre-existing and open; ghstack lands each PR individually, so
main can carry this commit without #195911's separator for a window; the
resume-name collision in that window is pre-existing, not introduced here. (#195911 also makes an
intra-package duplicate resume name raise loudly, closing the last silent route.)

Q: load_compiled_function passes guard_globals=f_globals, conflating the globals
the function runs in with the globals guards evaluate against, despite the
docstring distinguishing them. Shouldn't they be separate?

A: They are intentionally the same here. A compiled function's guards check the
very globals that function will read at runtime -- that is the point of a global
guard -- so evaluating them against a different dict would guard state the
function never sees. deserialize() keeps guard_globals as a distinct parameter for
callers that genuinely have two dicts (a guard tree rooted in one module served
into another), but load_compiled_function is the common single-module entry point
and binds both to f_globals deliberately. Exposing a second kwarg on it would add
API surface for a split that this entry point, by construction, does not have. The
docstring describes the general deserialize() contract; the narrowing to one dict
at this call site is intended, not an oversight.

Q: The module path auto-resolves its guard scope, but
torch.compiler.load_compiled_function(f) with no f_globals still lands on the
function path and fails any surviving global guard with a bare KeyError on
G['...']. Why not record fn.__module__ at capture and resolve sys.modules[...] the
way AOTCompiledModel does?

A: This commit takes the cheaper of the two remedies the finding offers. When
_guard_globals is None and the guard fails on a KeyError on G[...],
AOTCompiledFunction.__call__ now appends a pointer telling the user to pass
f_globals to load_compiled_function, so the degraded mode names its own fix
instead of surfacing a bare KeyError; AOTCompiledModel's no-match footer gets the
same missing-global branch. Recording the defining module at capture and
resolving sys.modules[...] is the durable version and a reasonable follow-up, but
it is a capture-time schema change, whereas the pointer hint closes the
diagnosability gap without one. The condition is pre-existing, not a regression
introduced here.

Q: SystemInfo.current defaults cpu_codegen to True, which runs the expensive
pick_vec_isa() probe, yet every call site passes cpu_codegen=False explicitly.
Shouldn't the default be False so the probe is opt-in?

A: The default is deliberately the complete value, not the cheap one.
check_compatibility only compares cpu_codegen_target when it is not None, so a
SystemInfo built without the probe silently carries no codegen fingerprint and a
later load on a mismatched ISA is not caught -- a correctness hole. Building one
with the probe is merely slower. Every current call site already passes the flag
explicitly, so the default governs only a future caller that omits it;
defaulting to True means such a caller gets a correct-but-slower artifact rather
than a fast-but-silently-incompatible one. The False overrides sit exactly where
codegen is known to be irrelevant -- the field factory's placeholder and the no-
graph-captured case -- so the expensive probe is opt-OUT there, not opt-in
everywhere.

Q: AOTCompiledModel._no_match_message picks one footer via an exclusive
`if missing_global / else`, so when two results fail and only one lacks a global
the ModelInput hint on the other is dropped; and the two branches test "is a global
missing" with different predicates (`"G['"` over-matches, `"KeyError on G["`
under-matches). Shouldn't the hint be per-result and the predicate shared?

A: Both are real refinements and neither changes a report a user sees today. The
per-result `[i]` lines already print every failure with its own reason; only the
trailing hint is a single footer, so the mixed-cause pair loses advice, not
diagnosis -- and attaching the hint to the `[i]` line that triggered it is the
right shape (it also keeps the len(splitlines)==4 assertions intact), but that is
a message-layout change, not a correctness one. The predicate divergence is a
wording inconsistency: both predicates only gate whether the "pass f_globals / add
a ModelInput" hint is appended, so an over-match appends it spuriously and an
under-match omits it -- in both cases the load still fails with the same error and
the same per-result reasons. The two branches now use predicates fitted to their
inputs: the raising branch tests `kind == "KeyError" and "G['" in detail` (a raised
KeyError stringifies to the bare `"G['NAME']"`, so the verbose-report text
`"KeyError on G["` can never appear there) and the non-raising branch keeps
`"KeyError on G["` over the verbose parts. They are intentionally different, not
drift.

Q: AOTCompiledFunction.__call__ appends a hint saying the guard scope "was
reconstructed from the serialized bytecode ... pass f_globals to
load_compiled_function", gated on `self._guard_globals is None` -- but that is also
true of every in-process capture that never serialized (the capture path passes
only _extra_globals), so a user who never saved can be told to pass f_globals.
Shouldn't it gate on an explicit "was deserialized" flag?

A: The hint is appended only when a guard actually FAILS on an absent global (a
KeyError reaching G['NAME']), not on every in-process run. A never-serialized
capture reaches it only if its live guards genuinely reference a global that was
deleted after capture -- in which case supplying the missing global (via f_globals
on a reload, or simply keeping it defined) is the correct remedy, so the advice is
directionally right even when the exact API name does not apply to an in-process
object. The predicate is broader than "was deserialized", and gating on an explicit
flag (or reusing _no_match_message's always-true phrasing) is a fair follow-up, but
the message only ever fires on a real missing-global failure, so it does not
misdirect a healthy in-process capture.

Q: `AOTCompiledModel.__call__`'s dispatch loop lets a raising `guard_check`
propagate, while `_no_match_message` tolerates a raising guard. Shouldn't the two
agree?

A: Fixed: the scan now treats a raising guard TREE as "did not match" and moves
on, and the report names the raiser as before. Binding errors are not tolerated:
`prepare_f_locals` runs outside the guarded region, so a call the signature
cannot accept still raises `bind_locals`' TypeError as the plain module would
(pinned by `test_aot_compile_module_wrong_arity_raises_type_error`) instead of a
no-match report telling the user to add a ModelInput. (Correction to an earlier
wording: the C++ guard tree does not swallow everything. A Python-level failure
inside a guard is cleared by `check_nopybind` and reported as no-match -- the
verbose variant renders it as `KeyError on G['...']` -- but a `TORCH_CHECK` or
`py::cast` failure unwinds through `RootGuardManager::check` and reaches Python
as a RuntimeError, which the scan now treats as "this entry did not match" and
reports by name rather than failing the whole call. `RootGuardManager::check`
restoring `PythonTorchFunctionTLS` by hand on that unwinding path is a
pre-existing guards.cpp issue this commit does not change. The Python-side
raisers, `prepare_f_locals` / `bind_locals`, would fail the call for the same
input anyway; the fix is about the two paths agreeing.) `RaisingGuardManager.check` in
the existing test now raises too, so the scan loop is covered.

Q: `cache_entry()` samples `SystemInfo.current()` ambiently, so a package
compiled under `torch.compile(options={"cpp.simdlen": 256})` on an AVX-512 host
records the 512-bit ISA its kernels were not tiled for -- the bug the AOT half
fixes here. Which commit closes this?

A: Correct at this revision: `cache_entry()` runs from record_package/save_package
after the `_TorchCompileInductorWrapper`'s config_patches scope has exited, and
nothing on the package carries that config here. #195913 closes it directly: it
moves the probe out of `cache_entry` into `update_device_type(graph,
codegen_config=...)`, and convert_frame recovers the wrapper's config from the
compiler_fn chain (`_inductor_codegen_config`) and re-applies it with
`torch._inductor.config.patch` around the sample -- the same re-application
`aot_compile_fullgraph` does here. A local fix would have to stash the config on
the package and re-apply it in `cache_entry`, code #195913 deletes when it
relocates the probe, so the fix lands with the commit that owns the probe's new
home. The load side is unchanged (ambient, with the global cpp.simdlen /
ATEN_CPU_CAPABILITY escape hatch).

Q: The `test_save_guidance_when_a_locals_class_default_cannot_pickle` comment says
the shared "local object" substring covers the pure-Python pickler too, but that
pickler's message ("Can't pickle <class ...>: it's not found as ...") has no such
substring.

A: Right on the parenthetical (the headline -- that AttributeError never escapes --
is wrong: the C pickler `AOTCompilePickler` subclasses raises it unwrapped through
3.13, and 3.14 raises PicklingError "Can't pickle local object"). The pure-Python
pickler is unreachable from `AOTCompilePickler(pickle.Pickler)`, so the comment now
names the two versions' wordings and drops the pure-Python clause. The test moved
to #196454 with the code it pins, so the reword lives there.

Q: `test_eager_backend_entry_is_exempt_from_the_codegen_target`'s native half only
asserts `requires_native_backend_compatibility`; the target the probe recorded is
never checked, and asserting it directly would need a host toolchain.

A: Fixed: the native half patches `_current_cpu_codegen_target` to a sentinel
target and asserts the entry recorded exactly that, so it needs no toolchain.

Q: No test drives the `options=`-patched capture path in `aot_compile_fullgraph`;
the footer branch selection in `_no_match_message` is unpinned; the `__call__`
missing-global hint is unasserted; the ISA table is a hand-rolled loop rather than
`@parametrize`; `check_codegen=False` on cuda is untested.

A: Added: `test_aot_compile_samples_the_codegen_target_under_the_wrappers_config`
(the recorded simdlen is the wrapper's, the ambient config is untouched after),
`assertIn` on each footer in the two no-match tests,
`test_aot_compile_fn_missing_global_hint_names_f_globals`, the ISA table as named
`@parametrize` subtests, and a `check_codegen=False` GPU case in the Triton/GPU
exemption test.

Q: `(line,) = logs.output` plus a `functools.partial(` substring in the
partial-forward fallback test is brittle; the seeds test "sanitizes rather than
cleans up" by filtering `__import_*` names; the mixed-device test depends on
`check_versions` ordering.

A: The single-record unpacking is deliberate -- any extra deserialize warning
should fail the test, that is the contract -- and `functools.partial(` is the repr
Python has emitted for decades. The `__import_*` filter isolates from earlier
tests: any compile writes those aliases into the tracing module's globals
(symbolic_convert's `install_global`) and `CleanupHook` removes them on reset, so
the filter is scoping, not a cleanup leak. The ordering dependence is documented
at `check_versions` ("cpu first ..."); left as is.

Q: The `except (RuntimeError, AttributeError)` arm around `get_traced_fn` in
`aot_compile_module` has no test.

A: Reachable (`mod.forward = torch.add` has `__self__` but no `__func__`) but low
value: it only selects the warning text for an unresolvable guard scope, which the
existing scope tests already exercise on the resolvable side. Left to follow-up
rather than pinned here.

Q: pr-sanity-checks is red -- this commit grew to 2058 lines.

A: The AOT-pickler tests (five `TestAOTCompile` cases plus the whole
`TestAOTCompilePickler` class) exercise code that #196454 introduces, so they
moved down to that commit; this commit is now ~1700 lines and the combined tree is
unchanged.

Q: The AOT-compile page documents the new `f_globals` contract but not the other
new user-visible load failure: an inductor artifact recorded a CPU codegen target
and is refused on a host that resolves a different one, with `ATEN_CPU_CAPABILITY`
/ the global `cpp.simdlen` as the escape hatch.

A: Added to "Choosing a backend" (the section that already contrasts inductor and
eager): what is recorded, the exact error, why a wider ISA is not a superset, how
to make the host resolve the recorded ISA before loading, that `options=` does
not apply at load time, and that eager/aot_eager artifacts are exempt; plus a
cross-reference from `load_compiled_function`'s Returns.

Q: `optimize_assert`'s copy of the `native_backend` threading is untested; the
eager-exemption test only takes the `_optimize` branch, so the two call sites can
drift.

A: The test is now parametrized over `fullgraph` (False -> `_optimize`, True ->
`optimize_assert`) so both paths are pinned.

Q: `initialize()` restores `_device_types` from the cache entry but not
`requires_native_backend_compatibility`, and neither store load path passes the
kwarg, so a loaded eager package loses its exemption and re-saves with a baked
codegen target.

A: Correct at this revision; #195913 closes it in both ways the review lists:
`initialize()` ORs the entry's flag into the package's (monotone, with the probe
deferred), AND `DynamoStore.load_package` / `load_and_install_package` pass
`requires_native_backend_compatibility=entry.dynamo.requires_native_backend_compatibility`
so a False survives the constructor default. The eval_frame path (a native
session reloading an eager entry) is why the entry is not made authoritative on
its own: that would fail open. The manual kwarg in
`test_loaded_eager_package_stays_exempt_on_resave` models that eval_frame path.

Q: The blacklist rationale ("a false rejection at load is recoverable") does not
hold on the `aot_compile` path: `CompileArtifacts` derives the gate solely from the
backend name, so a user backend that emits no native code is fingerprinted with the
capture ISA and cannot be loaded on a narrower or toolchain-less host.

A: Fixed: `CompileArtifacts.requires_native_backend_compatibility` (default True
so artifacts saved before the field keep loading) is set at capture from the
backend -- the eager family by name, or any callable declaring
`emits_native_code = False` (honoured by `_backend_emits_native_code` for the
package path too) -- and `check_compatibility` skips the ISA gate when it is
False. Pinned by `test_aot_compile_backend_declaring_no_native_code_skips_the_isa_gate`
(no target recorded; loads with a host that resolves no target). The docs now
state the true scope: every backend outside the eager family is gated unless it
declares otherwise.

Q: The install-collision retry lands on `install_global` only, but
`install_global_by_id` and the resume-function install also reach `CleanupHook.create`,
which raises on a name that already exists.

A: The resume half is closed by #195911's per-package token rename (the FAQ above
says where). `install_global_by_id` names (`___module_<name>_<id>_c<compile_id>`)
are never seeded by any load path -- `install()` seeds only `import_sources` and
`function_names`, and the AOT loader seeds import aliases and the builtins-dict
key -- so there is no baked-in name for a later compile to collide with (probe:
capture, reset, load, recompile in the same module: OK). Only `__builtins_dict___N`
carries no distinguisher, which is why the retry is scoped to it.

Q: `linux-docs` is red from this PR up.

A: The cross-reference added last round used a `#heading` anchor, which this
docs build (no `myst_heading_anchors`) does not resolve; it now uses the file's
explicit `(choosing-a-backend)=` label and a `{ref}` role.

Q: `test_check_compatibility_compares_artifact_against_current_machine` is red
from this PR up.

A: My round-38 change made the ISA gate a conjunction of the backend name and the
new capture-time flag `requires_native_backend_compatibility`; the test flipped
only the name, so the gate stayed disarmed and `assertRaises` failed. The eager
arm now asserts the flag is False for an eager capture and then arms it, so the
name exemption and the receiver-order checks are each pinned on their own.

Q: The opt-out `emits_native_code = False` is a fail-open escape hatch documented
with no warning about what declaring it wrongly costs, and nothing says where it
must live for a wrapped backend.

A: The user guide now says both: the attribute is read off the object passed as
`backend=` to `torch.compile` (a registered name resolves to its function first),
so for `aot_autograd(fw_compiler=...)` it goes on the returned `AotAutograd`
object and not on `fw_compiler`; only the literal False counts; and
declaring it on a backend that does emit native code disables the only check
between a mis-targeted artifact and a first-call crash. The docs also name the
`_NO_NATIVE_CODE_BACKENDS` family rather than listing two of its members.

Q: The attribute is de facto public API with no home in the `SerializableCallable`
protocol; `register_backend` should accept and stamp it so the classifier can
match by identity instead of by name.

A: Not in this commit. A protocol attribute would make it a property of every
serializable backend, but the flag describes the backend's codegen, not its
serializability, and most backends never set it. Stamping via `register_backend`
only covers registered backends; the user callable handed straight to
`torch.compile` is the case the opt-out exists for. Matching the in-tree eager
family by identity rather than name is a reasonable follow-up once the registry
grows that surface; the `__name__ == "eager"` collision it would close is already
FAQ'd above as accepted.

Q: `getattr(..., "emits_native_code", True) is not False` treats a method or a
truthy non-bool as native.

A: Deliberate: the gate fails closed. Anything but the literal False -- a method
(`is not False` on a bound method), a string, a missing attribute -- keeps the
artifact fingerprinted. The docs now say "the plain attribute
`emits_native_code = False`; any other value counts as native".

Q: The raising-guard branch of `_no_match_message` tests `"KeyError on G[" in
detail`, but a raising guard's `str(e)` is the bare KeyError text, so the
predicate is dead.

A: Fixed: the branch now tests `kind == "KeyError" and "G['" in detail`, and
`test_no_match_message_survives_a_raising_guard` asserts the missing-global footer
is present.

Q: `AOTCompiledFunction.__call__`'s missing-global hint says the scope "was
reconstructed from the serialized bytecode" and points at `load_compiled_function`,
but `_guard_globals` defaults to None on an in-process capture that was never
serialized.

A: Fixed: the hint reuses `_no_match_message`'s neutral phrasing (a guarded
global is missing from this process; define it or load with an `f_globals`
carrying it). `AOTCompiledModel` never reaches that branch: its `__call__` has
its own no-match report.

Q: `_simdlen`/`_march` are unpacked and never read in `_cpu_codegen_target_problem`.

A: `cached[:4]` now.

Q: The no-native-code test never round-trips the artifact through save/load, and
nothing pins that the same backend WITHOUT the declaration is fingerprinted.

A: Both added to `test_aot_compile_backend_declaring_no_native_code_skips_the_isa_gate`:
the artifact is saved and reloaded on a host that resolves no codegen target and
still serves, and an undeclared twin of the backend records
`requires_native_backend_compatibility=True` with the capture target.

Q: A subgraph tiled under a nested compile region's own `cpp.simdlen`
(`_patch_nested_region_inductor_config`) is fingerprinted with the ambient ISA.

A: Known and out of scope for the gate: the fingerprint is per artifact, and an
artifact whose regions were tiled for different widths cannot be described by
one target. Nested regions with their own simdlen are an inductor feature the AOT
path does not compose with today; when it does, the fingerprint should become the
set of targets the regions resolved, which is a follow-up to that composition, not
to this gate.

Q: No test where an opted-out result's guard evaluation raises.

A: The raising-guard scan is backend-agnostic (it runs before any backend
attribute is consulted), and `test_no_match_message_survives_a_raising_guard`
covers it; repeating it under the opt-out would exercise the same lines.

Q: `VecNEON` is never instantiated in either test file, so NEON-vs-SVE128 is
covered only by literal tuples.

A: `VecNEON` cannot be instantiated on the x86 hosts CI runs these files on
(`pick_vec_isa` never returns it there, and constructing it by hand exercises no
x86 codepath), so the literal target tuples are the honest cross-architecture
coverage available; the arm64 CI job runs the same comparison end to end through
the real `pick_vec_isa`.

Q: The docs say the attribute is read "off that callable's compiler_fn when it
is a wrapper", but `aot_autograd()` returns an `AotAutograd` whose `__name__` is
"compiler_fn" and which has no `compiler_fn` attribute. Which wrapper is meant?

A: Only torch.compile's own `_TorchCompileWrapper`, which stores the user's
backend as `.compiler_fn`; the one-hop getattr exists to see through it.
`AotAutograd` is never unwrapped (it IS the wrapper's compiler_fn), so the docs
now state the rule without naming an internal: set it on the object passed as
`backend=`. One limit for the record: `torch._dynamo.optimize("name")` with a
registered NAME string never resolves the name before classifying, so a
declaration on the registered function is honoured only through
`torch.compile`; the string path falls back to the name blacklist (fail-closed,
native).

Q: The mismatch RuntimeError prints the full six-tuple, so a 256-vs-None
simdlen/march tail can read as the cause while the remedy names cpp.simdlen.

A: The tail is diagnostic on purpose (`_cpu_codegen_target_problem`'s docstring:
simdlen and march stay in the recorded tuple for diagnostics but do not gate),
and the `problem` sentence appended to the same error names the exact gating
component (machine, or ISA/width/macros) with both values, so the cause is
stated next to the tuple. Labelling the two trailing fields is a wording
refinement left for follow-up.

Q: Neither shipped store reload path is exercised for the package flag.

A: The kwarg threading through `DynamoStore.load_package` /
`load_and_install_package` lands in #195913, which owns that seam; the test
belongs there (noted for that PR's next round), not in this commit whose reload
sites are unchanged.

ghstack-source-id: bdfdf3539edd4d29fcd1a3b27d39bde4cc837bad
Pull-Request: https://github.com/pytorch/pytorch/pull/195354
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude please re-review: round-40 fixes are in (every finding from the last review is fixed or answered in the description's FAQ).

@claude

claude Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 55m 54s —— View job


Re-reviewed at 593c1902: both findings from my last pass are genuinely fixed — I verified the wrap_inline regression test now bites end-to-end (install lands on the shared inner code, so removing the exemption raises at decoration) — so this is an approve. The carried residuals are unchanged and all named in the FAQ.

Full review of #195911 (twenty-second pass)

PR Review: #195911

Summary

Stamps every precompile install with a per-install owner token and renames resume globals per package so two packages loaded from one artifact coexist on a shared code object, plumbs isolate_recompiles_id from _TorchDynamoContext into install(), and adds a capture-side refusal so a fresh CompilePackage cannot silently capture nothing while a neighbour serves the frame. Both last-pass findings are fixed; what remains are three side effects the failed-install teardown does not undo, each with a named follow-up.

This round's delta

This PR's own contribution moved by exactly 21 content lines across three hunks (interdiff of git diff 1f559569...fc851ea4 vs git diff 24da0543...593c1902, restricted to the six files). All three are the two items I raised:

  1. test_two_packages_share_a_built_in_modules_wrap_inline_frame rewritten to save, load and install() the first package (test_package.py:1304-1309) instead of merely recording it.
  2. The _WRAP_INLINE_INNER_CODE comment (eval_frame.py:778-782) now enumerates the full blast radius — skipfile functions and built-in module forwards, top-level in-graph and polyfilled functions, and any module under config.wrap_top_frame — and says the refusal is skipped for all of them.
  3. The test's own comment reworded from "a first package's entries" to "a loaded package's entries", matching the new fixture.

Base update 24da0543 is +2465/-104 across 101 files but touches no C++ at all (git diff --stat 1f559569..24da0543 -- torch/csrc/ is empty) and only 5 lines of package.py (lower-stack FunctionPicklerBase work). I re-read the region filter directly rather than inferring: still entry.isolate_recompiles_id == isolate_recompiles_id with no -1 fallback (extra_state.cpp:761-762).

Also fixed in the base, and worth recording since it was an open inline thread: the extra_state.cpp comment that this commit falsified now reads "Installs below #195911 in this stack pass the default id -1; that commit's region-owned install registers each region under its id" (extra_state.cpp:759-760). That is accurate at every point in the stack, which closes the finding.

Verified fixed

Recorded so they are not re-litigated. I fact-checked the test rather than taking the summary, because it was vacuous once already.

  • The wrap_inline regression test now bites. With return None if code is _WRAP_INLINE_INNER_CODE else code (eval_frame.py:797) deleted, it raises RuntimeError: another CompilePackage is installed on inner at decoration. All four links hold:
    1. Capture lands on the shared inner. trace_rules.check(lin.forward) is True — the MOD_INLINELIST branch is gated on is_inlined_call (trace_rules.py:3859) so it is skipped, and torch.nn is in MOD_SKIPLIST (:3699). __name__ is "forward" (not in the _call_impl filter) and linear.py is not in DONT_WRAP_FILES, so eval_frame.py:1236 rebinds fn = external_utils.wrap_inline(lin.forward), whose __code__ is the same object as _WRAP_INLINE_INNER_CODE (:783).
    2. install() lands on that same object — this is the part that changed. _get_code_source records function_name="wrap_inline", code_source="__code__.co_consts[i]", and _lookup_code (package.py:1572-1573) re-walks sys.modules["torch._dynamo.external_utils"].wrap_inline.__code__.co_consts[i], i.e. the live shared code — not the deserialized copy in _codes. _load_precompile_entry then fires at package.py:1652. The entry cannot be silently zero-guarded (which is what made the old test vacuous): the class patches strict_precompile=True (test_package.py:103), so a bypass raises rather than clearing guarded_codes, and the method's caching_precompile=True (:1298) is what filters the ID_MATCH-derived guards so it is serializable at all.
    3. pkg2 resolves the same code. optimize(package=pkg2)(relu) takes the Module branch → OptimizedModule._initialize, _forward_has_skip_rule(relu) is True (same MOD_SKIPLIST reason), so eval_frame.py:549 re-enters with wrap_inline(relu). In that nested __call__ no second wrap happens (external_utils is in LEGACY_MOD_INLINELIST), so _refusal_frame_code returns the shared code via the plain fn.__code__ path. has_guarded_codes_for is False and owns_install_on is False, so neither short-circuit fires.
    4. _has_precompile_entries(inner, -1) scans extra->precompile_entries filtered on region (extra_state.cpp:1404-1433); pkg1 installed with -1 and pkg2's context is non-isolated.
  • The comment's blast radius is now stated. My note was that the code exempts every wrap_inline'd callable while the comment described only built-in modules; eval_frame.py:778-782 now names all four routes including config.wrap_top_frame, which is the case a reader would not predict.

Code Quality

  • uninstall() still does not revert skip_code, and the new fallback depends on it doing so. install() calls torch._dynamo.eval_frame.skip_code(target_code) for any zero-guarded entry (package.py:1613-1616), which writes the global exec strategy; extra_state_get_region_exec_strategy deliberately inherits SKIP into every region holding no strategy of its own. Neither uninstall() (package.py:1456-1477) nor _uninstall_abandoned_package (:1123-1142) reverts it, and no skipped codes are recorded, so only torch._dynamo.reset() clears it. Two consequences: the fallback's own comment says "Undo it before re-init" (eval_frame.py:1062-1067) but a SKIP that landed before the raise survives, so the intended cold compile is a silent no-op; and on the success path a region-N install of a trivial entry writes a global SKIP that every other region inherits. The FAQ concedes both, names set_code_region_exec_strategy plus record-and-restore at [dynamo] Region-scoped install ownership and skip-strategy bookkeeping #195915, and the docstring carries the caveat (package.py:1157-1158) — so this is a note on a named follow-up, not a new ask. Worth knowing the restore side is already bound in the base (set_code_exec_strategy_with_token, compare_and_set_code_exec_strategy), so it is a Python-only change.

  • The fallback's re-initialize leaves _codes populated. initialize() assigns _codes/_device_types only under if dynamo is not None: (package.py:1259-1264) while _source_info is reset (:1240), so the surviving state is internally inconsistent as well. The production save path stores entries by reference (PrecompileContext.record_dynamo_cache_entry, unlike the deepcopying record_artifact), so from_cache_entry mutates the same live entries and sets code.bypassed = True; from then on install() skips them and add_guarded_code/_add_backend_id/add_import_source early-return, dropping the frame from every future load and preventing re-capture. The FAQ's "Correction" paragraph names this correctly and [dynamo] Region-scoped install ownership and skip-strategy bookkeeping #195915 lands the reset — no disagreement with the deferral.

  • _uninstall_abandoned_package still uses module.__dict__.get(name) is value then del module.__dict__[name] (package.py:1141-1142). From a weakref.finalize callback a concurrent removal between the two raises KeyError, which CPython swallows as unraisable and abandons the rest of the loop, leaking every remaining global this package installed. pop(name, None) is one line and strictly correct today; the FAQ defers it to [dynamo] Region-scoped install ownership and skip-strategy bookkeeping #195915's rewrite of the whole function.

Testing

  • test_abandoned_package_uninstalls_on_gc (test_package.py:891) and the two failed-install tests all stake correctness on a single gc.collect(). The count equality, the zero-entry checks and the leaked diffs all fail if weakref.finalize runs one collection late, which a free-threaded build permits. The FAQ defers a bounded retry to when that build gates these tests; the precedent for this class of hardening is one commit down, where the base replaced the thread tests' per-join timeouts with a shared deadline plus a liveness assertion.

  • test_two_packages_share_a_built_in_modules_wrap_inline_frame reaches into pkg2._codes for its second assertion (test_package.py:1315), which is fine, but the first assertion is the load-bearing one and it is implicit: "no RuntimeError was raised" is expressed only by the assertEqual on the numeric result. A future edit that moves the refusal to a different site would still pass if it happened not to raise for another reason. Cheap hardening: assert _refusal_frame_code returns None for the wrapped callable, or assert _has_precompile_entries(inner_code, -1) is True so the test cannot silently regress back to the short-circuit it was written to escape.

  • No try/finally/addCleanup around several uninstall() calls — test_package.py:945 and the two in the coexist test; test_recompile_ux.py:1222, :1223. _install_eager_package registers cleanup for the tempdir but not for the install it returns. Note the new test, the refusal tests and the counter test all use addCleanup(pkg.uninstall), so the pattern is now well established in the file — the remaining sites are the older ones.

  • DynamoCache.load_and_install_package's isolate_recompiles_id kwarg is still never called with a non-default region — lower priority, since the region path is covered end-to-end through install() by test_two_packages_region_scoped_serves_its_own_entries.

Recommendation

Approve.

The blocker from my last pass is closed, and I verified it rather than accepting the claim: the rewritten test now installs onto the shared wrap_inline frame, the artifact's code_source resolves back to that same live code object through _lookup_code, and strict_precompile+caching_precompile together guarantee the entry is genuinely guarded rather than zero-guarded — so all four conjuncts of the refusal are live and deleting the exemption raises at decoration. The comment now names every route through wrap_inline, including the config.wrap_top_frame case. The base also landed the extra_state.cpp reword that keeps its invariant note true at every point in the stack, closing that inline thread.

The three carried residuals — skip_code non-reversion, _codes surviving the re-initialize, and del vs pop in the finalizer — are all real and all named in the FAQ with #195915 as the fix. None blocks: the first is narrow to reach on the fallback path, the second is deferred with the harm now correctly described as an unrecoverable bypassed write rather than per-load growth, and the third is superseded by a rewrite of the same function.

CI at 593c1902: no runs reported — the commit is marked [no ci], so nothing has been dispatched. TSan was green at the last several dispatched commits and is the right instrument for the parked-eviction layer under this one; worth a real run before merge. I could not run the test files locally (no built torch in this checkout), so all verification above is static reading; the four-step test-bites analysis was carried out by a dedicated agent reading trace_rules.py, eval_frame.py, package.py, guards.py, output_graph.py and extra_state.cpp, and I confirmed its load-bearing claims (the _lookup_code resolution path and the strict_precompile patch) against the files myself.

Previously investigated and dismissed

Recorded so they need not be re-litigated: the stale-finalizer window on reinstall (uninstall() detaches and rebinds the containers before install() re-registers); the -1 region sentinel being overloaded; dropping uninstall() from __init__ (compensated by the refusal); the zip early-return in _rename_globals; co_consts recursion sufficiency (pinned by test_rename_globals_rewrites_nested_code); resume-global name length; the co_names retargeting concern (rename keys come only from entry.function_names of install_to_global entries, so no user LOAD_ATTR/IMPORT_NAME operand can collide); the identity-based dedup at package.py:1597; input_codes.add (a weakref Tracker, so not a leak); the uninstall() in the fallback being able to raise (_innermost_fn is assigned at package.py:1241, ahead of every RuntimeError source in the try); _reserve_unique_id_through's counter arithmetic (no duplicate id — max(v, index+1) >= v always, and the consumed value is re-issued when index+1 <= v); the nn.Module.__call__ → forward resolution in _refusal_frame_code; the recorded latch; _add_function's dedup and the AssertionError → RuntimeError change (correct and narrow; tests placed at #195913); the region-scoped test's poison (unreachable today, but the only assertion that would catch a -1 fallback regression); the strong reference in _installed_globals (load-bearing at #195915's binding stack); the parked-reset ordering hazard (documented build-agnostically as a lifecycle contract, tracked as #196394); the earlier FAQ dispute over whether __compiled_fn_* globals are renamed (they are not, and the body says so); the extra_state.cpp invariant comment (now reworded in the base to name #195911).

· branch `gh/bobrenjc93/1113/head`

@bobrenjc93 bobrenjc93 closed this Sep 19, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1113/head branch November 17, 2026 01:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request module: dynamo release notes: dynamo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant