Skip to content

[ref-stack][aot_compile] Fix global guards on reloaded nn.Module artifacts - #195354

Closed
bobrenjc93 wants to merge 57 commits into
gh/bobrenjc93/1094/basefrom
gh/bobrenjc93/1094/head
Closed

bobrenjc93 wants to merge 57 commits into
gh/bobrenjc93/1094/basefrom
gh/bobrenjc93/1094/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary. A reloaded nn.Module artifact rebuilt its global guards against
only the scope the serialized bytecode reconstructs, because
AOTCompiledModel.deserialize never passed an f_globals, so any global Dynamo
had specialized away failed every call with KeyError on G['...']. The load
now resolves the guard scope from model.forward.__globals__ and re-roots the
guards at that live dict through a new keyword-only guard_globals, seeding
into it the __import_* aliases and __builtins_dict___N key Dynamo minted
in the tracing process, never overwriting a key already there, and
install_global skips a name a load already bound so a later compile in that
module cannot collide with it. When no compiled input's guards match, module
dispatch now raises a report naming why each input was rejected instead of
re-running graph 0's guards, and a result opted out via
disable_guard_check() is consulted only after every guarded result was
rejected. Separately, SystemInfo gains a CPU codegen target so the precompile
load gate compares the vector ISA an artifact's CPU kernels were tiled for
against the one pick_vec_isa() picks on the host, sampled under the
torch.compile wrapper's own inductor config and skipped for backends that
emit no native code. Two smaller correctness fixes ride along: the device scan
reads the whole graph rather than the first meta leaf, and the Triton-version
and GPU-model checks exempt off the artifact rather than the loading host.

Guard scope for a reloaded module artifact

# mypkg/model.py
MODE = "sum"                                  # Dynamo specializes on it: a constant in the graph, not a lifted input
class M(torch.nn.Module):
    def forward(self, x):
        return x.sum(1) if MODE == "sum" else x.mean(1)

# fresh process
loaded = AOTCompiledModel.deserialize(M(), data)     # parent passed no scope
loaded(x)
# parent: RuntimeError: GuardManager check failed ... KeyError on G['MODE']   on EVERY call
# now:    guards read vars(mypkg.model) by reference; MODE resolves, and a rebind of MODE
#         in this process fails the guard instead of being invisible

AOTCompiledFunction.deserialize takes f_globals for this, but
AOTCompiledModel.deserialize never passed one. It now resolves the scope from
model.forward.__globals__ (via get_traced_fn(forward), since for a hooked
module get_traced_fn(model) would return Module._wrapped_call_impl and
nn.Module's namespace) and passes it through a new keyword-only
guard_globals, kept apart from _extra_globals, which feeds the bytecode:

# f_globals is MERGED over the reconstructed scope (a name it omits still resolves to the baked-in value)
# guard_globals REPLACES the guard scope (a name it lacks fails the guard; no fallback to serialized values)
return cls(artifacts, _extra_globals=f_globals, _guard_globals=guard_globals)

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__ (a functools.partial, say) 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:

for alias, module_name in runtime_env.import_sources.items():
    CleanupHook.disown(guard_scope, alias)                   # a pre-reset compile may still own the name
    if alias not in guard_scope:
        guard_scope[alias] = importlib.import_module(module_name)
if builtins_key and builtins_key not in guard_scope:
    guard_scope.setdefault("__builtins__", builtins.__dict__)
    guard_scope[builtins_key] = get_builtins_dict(guard_scope)

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:

name = unique_id(prefix)
while name in self.global_scope:      # a load seeded this name; do not trip CleanupHook.create on it
    name = unique_id(prefix)

torch.compiler.load_compiled_function forwards its f_globals as
guard_globals too, and both public docstrings document the by-reference read,
the seeding, and the no-fallback contract.

Dispatch: a report instead of graph 0's guard error

model._aot_compile([ModelInput((x_f32,), {}, []), ModelInput((x_f64,), {}, [])])
model(x_f16)
# parent: ran compiled_results[0]'s own guard check and raised ITS error, or silently served [0]
#         if [0] had opted out -- the answer depended on which result sat at index 0
# now:    RuntimeError: No AOT compiled graph matched this call. Tried 2 compiled input(s):
#           [0] <guards [0] named>
#           [1] <guards [1] named>
#         Add a ModelInput covering this call, or check whether a guard that distinguishes it was
#         dropped by guard_filter_fn.

AOTCompiledModel.__call__ scans every result for a real match first (a guard
tree that raises counts as "did not match", and the report names the raiser), then
serves the first result opted out via disable_guard_check(), and only then
raises the report. A call the signature cannot bind still raises bind_locals'
TypeError, as the plain module call would. When an entry failed on a missing
global, the footer says so instead of the generic advice.

The CPU codegen target

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.

# capture host picks AVX-512; loading host picks AVX2
loaded = torch.compiler.load_compiled_function(f)
# RuntimeError: Compile package was created for a CPU codegen target this host cannot run:
#   cached=('x86_64', 'avx512', 512, (...), None, None), current=('x86_64', 'avx2', 256, (...), None, None).
#   The artifact's CPU kernels were generated for vector ISA 'avx512' (512-bit, ...); this host would
#   compile them for 'avx2' (256-bit, ...). Set ATEN_CPU_CAPABILITY or torch._inductor.config.cpp.simdlen
#   so the host picks the same ISA.

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 name and width must both agree
(VecSVE(128)/VecSVE(256) share the name asimd), and the build macros
disambiguate further (VecNEON and VecSVE(128) share name and width but
compile with different capability macros). A wider host ISA is not a superset:
its masked loads zero-fill the lanes the narrower tiling never wrote.

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():

codegen_config_ctx = nullcontext()
if isinstance(backend, torch._TorchCompileInductorWrapper):
    codegen_config_ctx = torch._inductor.config.patch(backend.config)   # e.g. {"cpp.simdlen": 256}
with codegen_config_ctx:
    system_info = SystemInfo.current(cpu_codegen=(native_backend and "cpu" in device_types))
    artifacts = CompileArtifacts(..., system_info=system_info, ...)    # __post_init__ runs check_compatibility
                                                                        # under the same config, or the artifact
                                                                        # rejects its own build

Otherwise the fingerprint would record the ambient ISA rather than the one the
kernels were tiled for, and an artifact could reject its own build host and
accept a wider one. emits_native_code(backend_name) exempts eager-family
artifacts from the toolchain probe and the comparison (a blacklist on purpose:
anything unrecognised, a user callable included, is assumed to emit code, since
a false rejection at load is recoverable and running a kernel built for another
ISA is not), and a user backend can declare emits_native_code = False on the
callable it hands torch.compile. CompilePackage.__init__ takes the same
decision as the keyword-only requires_native_backend_compatibility, which
eval_frame computes from the backend before get_compiler_fn erases its
name. Device EXISTENCE stays outside that exemption: an artifact holding cuda
tensors cannot run without cuda whatever backend produced it.

The device scan reads the whole graph

@torch.compile(dynamic=True)
def f(x):                     # x on cuda
    return x * x.shape[0]
# parent: the first meta leaf is the SymInt for x.shape[0] -> "cpu"; the cuda placeholder was never reached
# now:    _graph_device_types(graph) == frozenset({"cuda"})

_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. It returns every device type the graph
names, from meta leaves, from .cuda()/.xpu() calls, and from the two device
positions (a device= kwarg and .to()'s device argument, where a bare string
is parsed by torch.device; autocast device strings are ordinary positional
args and never reach it), minus meta. An empty result means the graph names
no device, which is not "cpu"; callers lower that to CPU code. CompilePackage
unions what its frames named, and both CompileArtifacts and
_DynamoCacheEntry keep the collapsed accelerator-wins device_type for BC
beside the new device_types set, since a mixed graph still emits native CPU
code that has to be gated.

Triton and GPU checks exempt off the artifact

# parent
if other.triton_version != (0, 0) and self.triton_version != other.triton_version: raise
if other.gpu_name is not None and self.gpu_name != other.gpu_name: raise
# now: self is the ARTIFACT (the cached info is the receiver)
if self.triton_version != (0, 0) and self.triton_version != other.triton_version: raise
if self.gpu_name is not None and self.gpu_name != other.gpu_name: raise

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. Making the cached info the receiver also labels
mismatch messages cached=..., matching _DynamoCacheEntry.check_versions.

User-visible changes

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. An artifact saved
before cpu_codegen_target and requires_native_backend_compatibility existed
keeps loading: both default to values that skip the new gate.

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-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 28e7c03 with merge base 9d5a710 (image):
💚 Looks good so far! There are no failures yet. 💚

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

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
A standalone aot_compile fix, which the precompile PR at the top of this stack
also needs: it introduces the CPU codegen target that the package layer below
torch.compiler.precompile uses to decide whether an artifact is safe to load
on the machine reading it.

Guards on globals resolve against the traced function's global scope.
`AOTCompiledFunction.deserialize` takes an `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. A
global Dynamo specialized away never appears there, and the guard then fails on
every call with "KeyError on G['...']".

Two details of the fix carry weight. The scope is resolved from `model.forward`,
not from the model: `get_traced_fn` returns `Module._wrapped_call_impl` for a
hooked module, which would silently inject nn.Module's namespace over a
colliding graph-input global. And it is threaded through a dedicated,
keyword-only `guard_globals` rather than `_extra_globals`, which feeds
`forward_callable` and would rewire what the compiled bytecode reads. The scope
is the loading process's live module dict, by reference: a global rebound after
load redirects dispatch on the next call, which is the point. There is
deliberately no fallback to the serialized value, because the deployment model
is capture on one machine and serve on another, and a loud refusal there is
recoverable where a silently stale answer is not.

Using the live scope has a side effect worth knowing about. Dynamo mints
`__import_*` aliases into the TRACING process's globals
(symbolic_convert.import_source) and roots guards at them -- every child
nn.Module call guards its hook dicts through
G['__import_torch_dot_nn_dot_modules_dot_module']. A process that only loads
never traced, so its module dict has none of them. Loading therefore seeds the
artifact's recorded import aliases into the user's live module globals with
`setdefault`, so only the synthetic names are added and a real global the
loading process already has keeps its live value. Each alias is resolved with
`importlib.import_module` while the guard manager is being built, so a module
the serving process cannot import raises at load rather than at the first call.

The CPU codegen target guards generated code: inductor bakes a vector width in,
so an artifact captured on one target and loaded on another would run kernels
for an ISA the host may not have. Artifacts that hold no generated code -- the
eager and aot_eager family -- are exempt, and skip the toolchain probe as well
as the comparison. `emits_native_code(backend_name)` in package.py is the one
place that decides this; `CompileArtifacts.check_compatibility` calls it
directly, and eval_frame.py's `_backend_emits_native_code` helper resolves what
`torch.compile` actually hands `_optimize`/`_optimize_assert` (a
`_TorchCompileWrapper` whose `compiler_name` is the string the user wrote, or
None) before asking. Anything unrecognised is assumed to generate code, since a
false rejection at load is recoverable and running a foreign kernel is not.

Which devices a graph targets is now a scan of the whole graph
(`_graph_device_types`, returning a frozenset) rather than the device of the
first meta value. The single-value read was wrong in two ways. Under dynamic
shapes the leading placeholder is a SymInt, which has no device, so it reported
"cpu" for an all-accelerator graph and hung a toolchain probe and a hard
load-time rejection off that answer; values carrying no device now contribute
nothing rather than defaulting. And collapsing to one device let a mixed
cpu+accelerator graph -- for which inductor still emits vectorized native CPU
kernels -- skip both recording and comparing the codegen target. Both
`CompileArtifacts` (`device_types`, with a getattr fallback for artifacts
pickled before the field existed) and `CompilePackage` accumulate the full set;
`check_compatibility` and `_DynamoCacheEntry.check_versions` iterate it sorted,
so the specific codegen-target refusal is not masked by a GPU-availability
error; `cache_entry()` keys the toolchain probe on "cpu" being in the set and a
loaded package restores the set for re-save. `CompilePackage.__init__`'s
`requires_native_backend_compatibility` is keyword-only.

Dispatch reporting on `AOTCompiledModel` changes too. When nothing matched it
used to run graph 0 so its guard check would raise, which always blamed the
first input; it now reports why each compiled input was rejected, one line
apiece, and consults an opted-out result only after a real match has been
sought.

Review aot_compile.py first (the guard scope and `CompileArtifacts`), then
package.py (`emits_native_code`, the alias seeding, the device set through
`cache_entry`/`check_versions`), then graph_utils.py and eval_frame.py, then
the tests.

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 KeyError on the guarded global;
the rebound-global and absent-global tests were also reproduced across two real
processes. The recording side is pinned so a regression cannot disarm itself
through the predates-the-field skip: an inductor CPU capture records a non-None
target, a mixed-device capture (GPU-gated) records one despite an accelerator
being present, and a fabricated-graph test pins recording and refusal for
`_DynamoCacheEntry` artifacts without needing an accelerator.

Authored with an AI assistant.

ghstack-source-id: 221166b
Pull-Request: #195354
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
A standalone aot_compile fix, which the precompile PR at the top of this stack
also needs: it introduces the CPU codegen target that the package layer below
torch.compiler.precompile uses to decide whether an artifact is safe to load
on the machine reading it.

Guards on globals resolve against the traced function's global scope.
`AOTCompiledFunction.deserialize` takes an `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. A
global Dynamo specialized away never appears there, and the guard then fails on
every call with "KeyError on G['...']".

Two details of the fix carry weight. The scope is resolved from `model.forward`,
not from the model: `get_traced_fn` returns `Module._wrapped_call_impl` for a
hooked module, which would silently inject nn.Module's namespace over a
colliding graph-input global. And it is threaded through a dedicated,
keyword-only `guard_globals` rather than `_extra_globals`, which feeds
`forward_callable` and would rewire what the compiled bytecode reads. The scope
is the loading process's live module dict, by reference: a global rebound after
load redirects dispatch on the next call, which is the point. There is
deliberately no fallback to the serialized value, because the deployment model
is capture on one machine and serve on another, and a loud refusal there is
recoverable where a silently stale answer is not.

Using the live scope has a side effect worth knowing about. Dynamo mints
`__import_*` aliases into the TRACING process's globals
(symbolic_convert.import_source) and roots guards at them -- every child
nn.Module call guards its hook dicts through
G['__import_torch_dot_nn_dot_modules_dot_module']. A process that only loads
never traced, so its module dict has none of them. Loading therefore seeds the
artifact's recorded import aliases into the user's live module globals with
`setdefault`, so only the synthetic names are added and a real global the
loading process already has keeps its live value. Each alias is resolved with
`importlib.import_module` while the guard manager is being built, so a module
the serving process cannot import raises at load rather than at the first call.

The CPU codegen target guards generated code: inductor bakes a vector width in,
so an artifact captured on one target and loaded on another would run kernels
for an ISA the host may not have. Artifacts that hold no generated code -- the
eager and aot_eager family -- are exempt, and skip the toolchain probe as well
as the comparison. `emits_native_code(backend_name)` in package.py is the one
place that decides this; `CompileArtifacts.check_compatibility` calls it
directly, and eval_frame.py's `_backend_emits_native_code` helper resolves what
`torch.compile` actually hands `_optimize`/`_optimize_assert` (a
`_TorchCompileWrapper` whose `compiler_name` is the string the user wrote, or
None) before asking. Anything unrecognised is assumed to generate code, since a
false rejection at load is recoverable and running a foreign kernel is not.

Which devices a graph targets is now a scan of the whole graph
(`_graph_device_types`, returning a frozenset) rather than the device of the
first meta value. The single-value read was wrong in two ways. Under dynamic
shapes the leading placeholder is a SymInt, which has no device, so it reported
"cpu" for an all-accelerator graph and hung a toolchain probe and a hard
load-time rejection off that answer; values carrying no device now contribute
nothing rather than defaulting. And collapsing to one device let a mixed
cpu+accelerator graph -- for which inductor still emits vectorized native CPU
kernels -- skip both recording and comparing the codegen target. Both
`CompileArtifacts` (`device_types`, with a getattr fallback for artifacts
pickled before the field existed) and `CompilePackage` accumulate the full set;
`check_compatibility` and `_DynamoCacheEntry.check_versions` iterate it sorted,
so the specific codegen-target refusal is not masked by a GPU-availability
error; `cache_entry()` keys the toolchain probe on "cpu" being in the set and a
loaded package restores the set for re-save. `CompilePackage.__init__`'s
`requires_native_backend_compatibility` is keyword-only.

Dispatch reporting on `AOTCompiledModel` changes too. When nothing matched it
used to run graph 0 so its guard check would raise, which always blamed the
first input; it now reports why each compiled input was rejected, one line
apiece, and consults an opted-out result only after a real match has been
sought.

Review aot_compile.py first (the guard scope and `CompileArtifacts`), then
package.py (`emits_native_code`, the alias seeding, the device set through
`cache_entry`/`check_versions`), then graph_utils.py and eval_frame.py, then
the tests.

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 KeyError on the guarded global;
the rebound-global and absent-global tests were also reproduced across two real
processes. The recording side is pinned so a regression cannot disarm itself
through the predates-the-field skip: an inductor CPU capture records a non-None
target, a mixed-device capture (GPU-gated) records one despite an accelerator
being present, and a fabricated-graph test pins recording and refusal for
`_DynamoCacheEntry` artifacts without needing an accelerator.

Authored with an AI assistant.

ghstack-source-id: 221166b
Pull-Request: #195354
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
A standalone aot_compile fix, which the precompile PR at the top of this stack
also needs: it introduces the CPU codegen target that the package layer below
torch.compiler.precompile uses to decide whether an artifact is safe to load
on the machine reading it.

Guards on globals resolve against the traced function's global scope.
`AOTCompiledFunction.deserialize` takes an `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. A
global Dynamo specialized away never appears there, and the guard then fails on
every call with "KeyError on G['...']".

Two details of the fix carry weight. The scope is resolved from `model.forward`,
not from the model: `get_traced_fn` returns `Module._wrapped_call_impl` for a
hooked module, which would silently inject nn.Module's namespace over a
colliding graph-input global. And it is threaded through a dedicated,
keyword-only `guard_globals` rather than `_extra_globals`, which feeds
`forward_callable` and would rewire what the compiled bytecode reads. The scope
is the loading process's live module dict, by reference: a global rebound after
load redirects dispatch on the next call, which is the point. There is
deliberately no fallback to the serialized value, because the deployment model
is capture on one machine and serve on another, and a loud refusal there is
recoverable where a silently stale answer is not.

Using the live scope has a side effect worth knowing about. Dynamo mints
`__import_*` aliases into the TRACING process's globals
(symbolic_convert.import_source) and roots guards at them -- every child
nn.Module call guards its hook dicts through
G['__import_torch_dot_nn_dot_modules_dot_module']. A process that only loads
never traced, so its module dict has none of them. Loading therefore seeds the
artifact's recorded import aliases into the user's live module globals with
`setdefault`, so only the synthetic names are added and a real global the
loading process already has keeps its live value. Each alias is resolved with
`importlib.import_module` while the guard manager is being built, so a module
the serving process cannot import raises at load rather than at the first call.

The CPU codegen target guards generated code: inductor bakes a vector width in,
so an artifact captured on one target and loaded on another would run kernels
for an ISA the host may not have. Artifacts that hold no generated code -- the
eager and aot_eager family -- are exempt, and skip the toolchain probe as well
as the comparison. `emits_native_code(backend_name)` in package.py is the one
place that decides this; `CompileArtifacts.check_compatibility` calls it
directly, and eval_frame.py's `_backend_emits_native_code` helper resolves what
`torch.compile` actually hands `_optimize`/`_optimize_assert` (a
`_TorchCompileWrapper` whose `compiler_name` is the string the user wrote, or
None) before asking. Anything unrecognised is assumed to generate code, since a
false rejection at load is recoverable and running a foreign kernel is not.

Which devices a graph targets is now a scan of the whole graph
(`_graph_device_types`, returning a frozenset) rather than the device of the
first meta value. The single-value read was wrong in two ways. Under dynamic
shapes the leading placeholder is a SymInt, which has no device, so it reported
"cpu" for an all-accelerator graph and hung a toolchain probe and a hard
load-time rejection off that answer; values carrying no device now contribute
nothing rather than defaulting. And collapsing to one device let a mixed
cpu+accelerator graph -- for which inductor still emits vectorized native CPU
kernels -- skip both recording and comparing the codegen target. Both
`CompileArtifacts` (`device_types`, with a getattr fallback for artifacts
pickled before the field existed) and `CompilePackage` accumulate the full set;
`check_compatibility` and `_DynamoCacheEntry.check_versions` iterate it sorted,
so the specific codegen-target refusal is not masked by a GPU-availability
error; `cache_entry()` keys the toolchain probe on "cpu" being in the set and a
loaded package restores the set for re-save. `CompilePackage.__init__`'s
`requires_native_backend_compatibility` is keyword-only.

Dispatch reporting on `AOTCompiledModel` changes too. When nothing matched it
used to run graph 0 so its guard check would raise, which always blamed the
first input; it now reports why each compiled input was rejected, one line
apiece, and consults an opted-out result only after a real match has been
sought.

Review aot_compile.py first (the guard scope and `CompileArtifacts`), then
package.py (`emits_native_code`, the alias seeding, the device set through
`cache_entry`/`check_versions`), then graph_utils.py and eval_frame.py, then
the tests.

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 KeyError on the guarded global;
the rebound-global and absent-global tests were also reproduced across two real
processes. The recording side is pinned so a regression cannot disarm itself
through the predates-the-field skip: an inductor CPU capture records a non-None
target, a mixed-device capture (GPU-gated) records one despite an accelerator
being present, and a fabricated-graph test pins recording and refusal for
`_DynamoCacheEntry` artifacts without needing an accelerator.

Authored with an AI assistant.

ghstack-source-id: 221166b
Pull-Request: #195354
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
A standalone aot_compile fix, which the precompile PR at the top of this stack
also needs: it introduces the CPU codegen target that the package layer below
torch.compiler.precompile uses to decide whether an artifact is safe to load
on the machine reading it.

Guards on globals resolve against the traced function's global scope.
`AOTCompiledFunction.deserialize` takes an `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. A
global Dynamo specialized away never appears there, and the guard then fails on
every call with "KeyError on G['...']".

Two details of the fix carry weight. The scope is resolved from `model.forward`,
not from the model: `get_traced_fn` returns `Module._wrapped_call_impl` for a
hooked module, which would silently inject nn.Module's namespace over a
colliding graph-input global. And it is threaded through a dedicated,
keyword-only `guard_globals` rather than `_extra_globals`, which feeds
`forward_callable` and would rewire what the compiled bytecode reads. The scope
is the loading process's live module dict, by reference: a global rebound after
load redirects dispatch on the next call, which is the point. There is
deliberately no fallback to the serialized value, because the deployment model
is capture on one machine and serve on another, and a loud refusal there is
recoverable where a silently stale answer is not.

Using the live scope has a side effect worth knowing about. Dynamo mints
`__import_*` aliases into the TRACING process's globals
(symbolic_convert.import_source) and roots guards at them -- every child
nn.Module call guards its hook dicts through
G['__import_torch_dot_nn_dot_modules_dot_module']. A process that only loads
never traced, so its module dict has none of them. Loading therefore seeds the
artifact's recorded import aliases into the user's live module globals with
`setdefault`, so only the synthetic names are added and a real global the
loading process already has keeps its live value. Each alias is resolved with
`importlib.import_module` while the guard manager is being built, so a module
the serving process cannot import raises at load rather than at the first call.

The CPU codegen target guards generated code: inductor bakes a vector width in,
so an artifact captured on one target and loaded on another would run kernels
for an ISA the host may not have. Artifacts that hold no generated code -- the
eager and aot_eager family -- are exempt, and skip the toolchain probe as well
as the comparison. `emits_native_code(backend_name)` in package.py is the one
place that decides this; `CompileArtifacts.check_compatibility` calls it
directly, and eval_frame.py's `_backend_emits_native_code` helper resolves what
`torch.compile` actually hands `_optimize`/`_optimize_assert` (a
`_TorchCompileWrapper` whose `compiler_name` is the string the user wrote, or
None) before asking. Anything unrecognised is assumed to generate code, since a
false rejection at load is recoverable and running a foreign kernel is not.

Which devices a graph targets is now a scan of the whole graph
(`_graph_device_types`, returning a frozenset) rather than the device of the
first meta value. The single-value read was wrong in two ways. Under dynamic
shapes the leading placeholder is a SymInt, which has no device, so it reported
"cpu" for an all-accelerator graph and hung a toolchain probe and a hard
load-time rejection off that answer; values carrying no device now contribute
nothing rather than defaulting. And collapsing to one device let a mixed
cpu+accelerator graph -- for which inductor still emits vectorized native CPU
kernels -- skip both recording and comparing the codegen target. Both
`CompileArtifacts` (`device_types`, with a getattr fallback for artifacts
pickled before the field existed) and `CompilePackage` accumulate the full set;
`check_compatibility` and `_DynamoCacheEntry.check_versions` iterate it sorted,
so the specific codegen-target refusal is not masked by a GPU-availability
error; `cache_entry()` keys the toolchain probe on "cpu" being in the set and a
loaded package restores the set for re-save. `CompilePackage.__init__`'s
`requires_native_backend_compatibility` is keyword-only.

Dispatch reporting on `AOTCompiledModel` changes too. When nothing matched it
used to run graph 0 so its guard check would raise, which always blamed the
first input; it now reports why each compiled input was rejected, one line
apiece, and consults an opted-out result only after a real match has been
sought.

Review aot_compile.py first (the guard scope and `CompileArtifacts`), then
package.py (`emits_native_code`, the alias seeding, the device set through
`cache_entry`/`check_versions`), then graph_utils.py and eval_frame.py, then
the tests.

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 KeyError on the guarded global;
the rebound-global and absent-global tests were also reproduced across two real
processes. The recording side is pinned so a regression cannot disarm itself
through the predates-the-field skip: an inductor CPU capture records a non-None
target, a mixed-device capture (GPU-gated) records one despite an accelerator
being present, and a fabricated-graph test pins recording and refusal for
`_DynamoCacheEntry` artifacts without needing an accelerator.

Authored with an AI assistant.

ghstack-source-id: 221166b
Pull-Request: #195354
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
Comment thread torch/_dynamo/aot_compile.py Resolved
Comment thread torch/_dynamo/package.py Resolved
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

[ghstack-poisoned]
Comment thread torch/_dynamo/aot_compile.py Resolved
Comment thread torch/_dynamo/eval_frame.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 37m 42s —— View job


Round 23: three of the four claimed fixes verify cleanly and this round closes a lot of standing items — but the predicate consolidation went the wrong direction and made the raising-branch missing-global detection dead code, and the new except Exception in the dispatch scan is broader than the FAQ's justification for it.

Full review of #195354

PR Review: #195354

Summary

Fixes global guards on reloaded nn.Module artifacts by passing the live model.forward.__globals__ as a guard-only scope, and adds a CPU-codegen-target compatibility check to precompile and AOT artifacts.

Delta since round 22, separating PR-owned from base-owned. The raw ed9e71f7..636d0a5b range spans two base updates; diffing the round-22 PR-owned three-dot diff against the current one isolates it. Base-owned (absent from git diff origin/gh/bobrenjc93/1094/base...HEAD, present verbatim in git show origin/.../base:...): the whole TestAOTCompilePickler class, test_save_guidance_when_a_closure_cell_cannot_pickle, test_save_guidance_when_a_locals_class_default_cannot_pickle, test_aot_compile_reloads_a_runtime_env_helper_faithfully, test_aot_compile_prunes_a_helpers_unpicklable_attribute, test_aot_compile_prunes_functools_wraps_wrapped, and the _ProbeState/_dumps_cleanly/doc= pickler work. Those belong to #195353 — including the "Can't get local object" wording I flagged last round, which has been corrected there (test_aot_compile.py:973-977 now says AttributeError on ≤3.13 / PicklingError on 3.14+ and drops the false pure-Python-pickler clause).

This PR's own delta is four items:

  1. The dispatch scan hoists prepare_f_locals out of the guarded region and wraps only guard_manager.check in try/except Exception: continue (aot_compile.py:697-714).
  2. The _no_match_message except-branch predicate narrowed from "KeyError on G[" in detail or "G['" in detail to just "KeyError on G[" in detail (:745).
  3. The docs page gained a CPU-codegen-target paragraph under "Choosing a backend" (torch.compiler_aot_compile.md:184-195) plus a cross-reference from load_compiled_function's Returns (:162-164).
  4. Tests: test_aot_compile_module_wrong_arity_raises_type_error, test_aot_compile_samples_the_codegen_target_under_the_wrappers_config, test_aot_compile_fn_missing_global_hint_names_f_globals, assertIn on both footers, the ISA table converted to @parametrize/subtest, @parametrize("fullgraph", ...) on the eager-exemption test with a sentinel target asserted on the native half, and a check_codegen=False-on-cuda case.

What closes this round

The @parametrize("fullgraph", ...) genuinely covers both threading sites. I traced it rather than taking the comment: torch.compile ends in torch._dynamo.optimize(backend=backend, nopython=fullgraph, ...) with no package= (torch/__init__.py:3311-3313); _optimize returns early to optimize_assert at eval_frame.py:1885-1895 when nopython and not config.debug_force_graph_break_on_leaf_return, so the two CompilePackage(...) constructions at :1909 and :2853 are mutually exclusive and both see package is None. _backend_emits_native_code runs before get_compiler_fn at both sites, so it reads the wrapper's compiler_name ("eager" / "custom_backend") rather than the erased callable. Since the constructor default is True (package.py:1068), deleting the kwarg at either site breaks the assertFalse at test_package.py:280 for the corresponding fullgraph value. One latent fragility worth a word in the comment: coverage of the optimize_assert side depends on debug_force_graph_break_on_leaf_return staying False.

The options=-patched capture is now pinned, and the test is well-built. test_aot_compile_samples_the_codegen_target_under_the_wrappers_config (test_aot_compile.py:2547-2570) patches _current_cpu_codegen_target with a side_effect that reads the ambient cpp.simdlen and bakes it into the returned tuple, so if config.patch(backend.config) (aot_compile.py:636-637) were removed the recorded target[4] would be None and the assertion fails. It also pins the widening over artifact construction: __post_init__ → check_compatibility samples again inside the same with, so both sides see simdlen=256 and agree; move the construction outside and the artifact rejects its own build with the ISA error. And assertIsNone(torch._inductor.config.cpp.simdlen) after confirms the patch unwound. This is the test I have been asking for since round 12, and it needs no host toolchain.

The @parametrize conversion of the ISA table (test_package.py:158-230) is done properly — named subtests, targets in a shared _CODEGEN_TARGETS dict, error=None for the two accept cases. A failure now names the case instead of aborting the six after it. The stale march comment I flagged last round is corrected in the same hunk (:195-203 now says pick_vec_isa() folds cpp.simdlen and ATEN_CPU_CAPABILITY and that "march never reaches it"), so it matches the production docstring at package.py:695-702.

check_codegen=False on cuda is covered (test_aot_compile.py:2595-2604), including the mirror that device existence is not skipped. The native half of the eager-exemption test now asserts the recorded target against a sentinel (test_package.py:287-297), closing the half-vacuous assertion. Both footers are asserted (test_aot_compile.py:1463, :1802). The docs paragraph is accurate: the quoted RuntimeError text matches package.py:843-845 verbatim, the remedy matches :734-735, and the options=-does-not-apply-at-load claim matches the ambient sample in check_compatibility.

And the raising-guard half of my long-standing disable_guard_check finding is closed. With check wrapped, an opted-out result whose guard tree raises now continues and the second loop (:717-719) serves it, instead of the exception escaping before the fallback was reachable. RaisingGuardManager.check raising in the existing test (:1488-1489) exercises that path.

Code Quality

The predicate consolidation made the except-branch missing-global detection dead code, silently undoing round 21's fix. _no_match_message now reads:

except Exception as e:
    detail = str(e).replace("\n", " ")
    # A guard that RAISES a missing-global error still names the
    # global; feed that into the same detection the non-raising
    # branch uses ...
    if "KeyError on G[" in detail:
        missing_global = True

Nothing that raises can contain that substring. "KeyError on " is produced in exactly four places in the tree — guards.cpp:5569, :5688, :5780, :6892 — and all four are GuardDebugInfo(false, std::string("KeyError on ") + get_source(), 0) return values on the non-raising path, immediately after PyErr_Clear(). There is no raiser anywhere that formats a message that way. The round-22 disjunct or "G['" in detail was what made the branch live, because a raised KeyError("G['NAME']") stringifies to "G['NAME']".

Concretely: test_no_match_message_survives_a_raising_guard raises exactly KeyError("G['SOME_GLOBAL']") (test_aot_compile.py:1489, :1492), and that message now fails the predicate, so that test's report gets the generic "Add a ModelInput covering this call" footer for a failure whose cause is a named missing global. The test asserts KeyError, SOME_GLOBAL, dtype mismatch and len(splitlines()) == 4 — never the footer — so nothing catches the reversal. My round-21/22 note was that the two branches used different predicates; the consolidation resolved that by adopting the one that cannot match a raised message. Either restore the or "G['" in detail disjunct (over-matching an arbitrary exception text is a wrong hint, never a wrong result), or drop the dead if and its four-line comment and let a raising guard take the generic footer honestly. Fix this →

The except Exception in the scan is broader than the FAQ's justification, and it now silences a global-state leak. The FAQ says: "The C++ guard tree never propagates -- check_nopybind clears and returns false -- so today's raisers are Python-side, prepare_f_locals / bind_locals." The first clause is not true as stated. guards.cpp contains zero catch blocks (grep -c "} catch" → 0), and RootGuardManager::check_nopybind_template (:4368-4417) has no try/catch either — so any C++ throw inside the tree unwinds through RootGuardManager::check (:4357-4359, bound at :8779), and pybind converts it to a raised Python exception out of .check(). The per-guard PyErr_Clear() calls the claim leans on (LAMBDA_GUARD::check_nopybind at :1918-1928, the accessors, py_equals(..., false_on_error=true)) cover CPython-C-API failures, not TORCH_CHECK/TORCH_INTERNAL_ASSERT/py::cast. Throw sites reachable from check_nopybind (not check_verbose_nopybind) include TORCH_CHECK(register_weakref_callback(value), ...) at :3849-3851, TORCH_INTERNAL_ASSERT(result != nullptr, "issubset call failed ...") in DIMENSION_DYNAMIC_MARKING_GUARD at :3005-3007 and :3081, handle.cast<c10::DispatchKeySet>() in DISPATCH_KEY_SET_MATCH at :5197, and TORCH_CHECK(THPVariable_Check(obj)) reached from STORAGE_OVERLAPPING::check_nopybind at :2766 → :1658.

The sharp consequence is not the swallowed error message, it is the state: check_nopybind_template sets PythonTorchFunctionTLS::set_disabled_state(ALL_DISABLED) at :4396 and restores it by hand at :4400, :4408 and :4414 — no RAII guard — so an unwinding throw skips every restore and leaves torch-function dispatch globally disabled for the rest of the process. That leak is pre-existing in guards.cpp, but before this round the exception propagated and the user saw something; now it becomes continue → "no matching graph" (or, with an opted-out result present, a silently-served wrong graph) with the interpreter left in a broken torch-function state. Narrowing the catch to what prepare_f_locals can raise — or at least to the exception types the scan means to tolerate — keeps this round's fix and stops converting internal errors into misses. Whatever the disposition, the FAQ sentence should not assert that the C++ tree cannot propagate. Fix this →

Hoisting prepare_f_locals out of the try makes the report's own prepare_f_locals catch unreachable for the arity case. The scan calls it at :703 unguarded, so a bind_locals TypeError raises before _no_match_message is ever entered — yet _no_match_message still wraps prepare_f_locals inside its try at :736. That is now dead for the case the comment at :698-702 is about, so the two paths agree on the guard tree and disagree on binding in the opposite direction from before. Harmless, but the report's try should probably narrow to check_verbose so the split is legible. Note also that prepare_f_locals reads cell.cell_contents at :293, which raises ValueError on an empty cell; that now propagates out of dispatch as a bare ValueError rather than being tolerated. Capture reads every cell of the top-level function up front (convert_frame.py:1423-1432), so an empty cell there is not reachable from a healthy artifact — but it is a second, unintended thing the hoist un-tolerates alongside the arity TypeError the comment names.

test_aot_compile_module_wrong_arity_raises_type_error pins the right thing but only the two positional shapes. ScaleModule.forward(self, x) gives too many positional arguments for model(x, x) and missing a required argument: 'x' for model(), both from signature.bind at aot_compile.py:47. An unexpected keyword (model(y=x)) is the third bind failure mode and the one most likely to be mistaken for a guard miss by a caller; a third assertRaisesRegex there is nearly free.

The __call__ missing-global hint still fires on artifacts that were never serialized. :375 gates on self._guard_globals is None, but the field defaults to None (:282) and the capture path constructs AOTCompiledFunction(_artifacts=artifacts, _extra_globals=fn.__globals__) (:661-663) without it, while artifacts.guard_manager is already set from check_fn.guard_manager (:649) so __post_init__'s rebuild at :316 is skipped and guards stay rooted at the live tracing globals. Reachable with a filter that keeps global guards. The FAQ now argues the advice is directionally right because the hint only fires on a real missing-global failure, which I accept as a deferral — but the text names load_compiled_function, an API an in-process capture never called. Reusing _no_match_message's always-true phrasing at :756-757 ("define it (or load with an f_globals carrying it)") costs nothing.

The footer is still exclusive (:754-763), so a two-result failure where one result lacks a global and the other has an ordinary mismatch drops the ModelInput advice. compile_single_graph traces each ModelInput under its own contexts, so the guard trees genuinely differ per result. Diagnosis is not lost (the [i] lines are all emitted); the trailing hint is misdirected. The FAQ concedes this and prefers per-[i] attachment, which also keeps the len(splitlines()) == 4 assertions intact.

The guard-scope seeding is unconditional with respect to guard filtering (:322-361), with no check that any global guard survived. The default filter drops every g.is_global (:532-541) including builtins-rooted guards, and builtins_key is truthy regardless since name_of_builtins_dict_key_in_fglobals is assigned unconditionally at trace time. For a bound nn.Linear.forward, get_traced_fn takes the hasattr(mod, "__self__") branch so the mutated dict is torch/nn/modules/linear.py's namespace, and uninstall/__del__/_installed_globals have zero occurrences in aot_compile.py. FAQ'd as "no uninstall surface by design", which is fair for the mutation; gating the seed on whether any global guard survived would make the default path a no-op.

A functools.wraps wrapper assigned to forward silently yields the wrong guard scope — get_traced_fn has no __wrapped__ handling and _get_signature passes follow_wrapped=False; functools.wraps copies __module__/__name__/__qualname__ but not __globals__. Silent only under asymmetric wrapping, and the RuntimeError/AttributeError fallback at :799 fires only for objects that are neither a plain function nor a method with __globals__. FAQ'd; deferral is right.

_cpu_codegen_target_problem tests current is None (package.py:717) before unpacking cached (:726), so an x86 artifact on a toolchain-less aarch64 host never learns about the architecture. Presentational only — the enclosing RuntimeError at :843-845 prints the full cached tuple, machine included. _simdlen/_march at :726 are bound and never read; cached[:4] says the same thing.

The nested-compile-region config path is outside the in-scope sample. _patch_nested_region_inductor_config (compile_fx.py:667-673) is live inside backend() and is not in backend.config, so a subgraph tiled under a per-region cpp.simdlen is fingerprinted with the ambient wider ISA. Reachable only via nested_compile_region(options=get_invoke_subgraph_compile_options(...)); not a regression, but the comment at aot_compile.py:627-634 reads as though the wrapper's config is the only scope that matters.

API Design (carried forward, all FAQ'd)

_TorchCompileWrapper derives compiler_name from backend.__name__ (torch/__init__.py:3003-3005), so a user callable named eager/aot_eager lands in _NO_NATIVE_CODE_BACKENDS and is exempted from the ISA gate even if it lowers through inductor — the one fail-open direction, and the opposite of what package.py:742-745 claims. The other three are fail-closed: _backend_emits_native_code (eval_frame.py:1802-1807) misclassifies by entrypoint, since register_backend stamps no compiler_name, so torch._dynamo.optimize(debugging.eager) stringifies to "<function eager at 0x…>" → native while torch.compile(backend=debugging.eager) correctly yields False; instance backends are never classifiable (CompileCounter has no __name__); and aot_compile.py:626 records getattr(backend, "compiler_name", "unknown") after get_compiler_fn erased the string.

_NO_NATIVE_CODE_BACKENDS (package.py:746-758) enumerates exactly nine eager-family names, so ts/torchscript, aot_ts, invoke_subgraph, cudagraphs, openxla/openxla_eval, tvm, the *_TESTING_ONLY gm-passthrough backends and the minifier backends are all gated on host ISA despite emitting no inductor CPU kernels — and each also pays the save-time pick_vec_isa() probe.

Both store reload sites take the constructor default True. package.py:1620 and :1762 are bare CompilePackage(fn, entry.dynamo) / (fn, results.dynamo); initialize() restores _device_types but not the flag, and cache_entry() reads it at :1475 and :1479-1480. So an eager artifact round-tripped through a store is re-saved as True and pays the probe. The FAQ now states this plainly and calls it deliberately fail-closed, which matches the code. Still untested through either shipped API — test_loaded_eager_package_stays_exempt_on_resave (test_package.py:299-309) hand-constructs CompilePackage(fn, requires_native_backend_compatibility=False), i.e. exactly the argument the two shipped callers do not pass.

The resume-name collision class is open at this commit. install_resume_function_global (output_graph.py:3539-3563) calls install_global_unsafe directly, bypassing the while name in self.global_scope retry at :3606-3607; install_global_unsafe (:3565-3576) checks only the per-OutputGraph installed_globals, then CleanupHook.create raises. _resume_global_renames, package_token and uuid still have zero occurrences in package.py, so the separator the FAQ describes lands in #195911 above this PR. Pre-existing, so it does not block; the FAQ correctly says so now.

The build_arch_flags() follow-up has the ordering trap the FAQ records: VecAVX512.__bool__/VecAMX.__bool__ set the bf16/fp16 flags as a side effect of the probe via base_flags = self._arch_flags / += / restore, which on a dataclass whose _arch_flags is a class attribute permanently shadows it per-instance.

Backward Compatibility (carried forward, both FAQ'd)

A capture under options=/mode= imposes a matching-config requirement at load, since save samples under backend.config and load samples ambiently. The docs paragraph added this round covers it correctly, including that options= does not apply at load — that closes the docs half of this note.

A mixed cpu+accelerator artifact hard-fails on a host lacking the accelerator, where pre-PR it loaded — the device set is unioned, the collapse is accelerator-wins, and check_versions loops every device (package.py:915-919). Correct. Residual is ordering: sorted(device_types) puts codegen first, so a host that is both accelerator-less and ISA-skewed is told to set ATEN_CPU_CAPABILITY and never learns there is no GPU.

check_codegen=False returns early inside the GPU block (:856-857, after only the availability check at :853-854), so an eager-family cuda artifact skips toolkit_version (:859), triton_version (:868) and gpu_name (:877). Now covered by a test, and the comment at :848-852 explicitly carves device existence out of the gate, which is the right framing.

Testing

This round's additions are the strongest test delta of any round: the options=-patched capture is pinned without a toolchain, the ISA table is @parametrized, both threading sites of native_backend are covered, check_codegen=False-on-cuda is covered, and the native half of the eager-exemption test now asserts the sentinel target rather than just the flag.

Remaining gaps, each tied to a finding above:

  • Footer selection in the raising branch is unpinned, which is what let this round's predicate narrowing pass unnoticed — see the first finding. One assertIn in test_no_match_message_survives_a_raising_guard would fix both.
  • Nothing exercises either shipped store reload path for requires_native_backend_compatibility.
  • The AttributeError arm at aot_compile.py:799 is uncovered. The only unusual-forward test assigns a functools.partial, which has no __self__ and takes the RuntimeError arm inside get_traced_fn. mod.forward = torch.relu and types.MethodType(callable_instance, mod) are the two reaching shapes; MethodType has zero occurrences in test_aot_compile.py. The FAQ concedes this one as low-value, which I accept.
  • No test for an unexpected-keyword bind failure in the new arity test.
  • Nothing covers the nested-compile-region config path.
  • VecNEON is never instantiated in either test file; only VecSVE(128)/VecSVE(256) are real (test_package.py:249-250), so NEON-vs-SVE128 is covered solely by the literal tuples in _CODEGEN_TARGETS and a drift in VecNEON.build_macro() would not be caught.
  • test_mixed_device_capture_records_cpu_codegen_target still depends on check_versions' sorted(device_types) putting "cpu" first; the production comment at package.py:914 documents it, the test does not.

Recommendation

Approve with comments

Three of the four changes verify cleanly and this round closes a lot: the options= capture-scope fix finally has a test that pins it without a toolchain, the fullgraph parametrization really does hit both _optimize and _optimize_assert (I traced the dispatch and the package is None precondition at both sites), the ISA table is properly @parametrized with the stale march comment corrected, and the docs paragraph's error text and remedy match the code verbatim. The raising-guard half of my long-standing disable_guard_check finding is closed by the try around check.

Two things I would fix before merge, neither large. The predicate consolidation at aot_compile.py:745 adopted the substring that cannot appear in a raised exception — "KeyError on " exists only in GuardDebugInfo return values at guards.cpp:5569/5688/5780/6892, all after PyErr_Clear() — so the except-branch missing-global detection is now dead code, and the very test that motivated it (KeyError("G['SOME_GLOBAL']")) silently regressed to the generic "Add a ModelInput" footer. That was my predicate-divergence note resolved in the wrong direction; restoring the or "G['" in detail disjunct, or deleting the dead if, plus one assertIn on the footer, settles it. And the FAQ's justification for the new except Exception — that the C++ guard tree cannot propagate — does not hold: guards.cpp has zero catch blocks and RootGuardManager::check_nopybind_template none either, so TORCH_CHECK/TORCH_INTERNAL_ASSERT/py::cast throws do escape .check(), and because that function restores PythonTorchFunctionTLS by hand at three explicit sites rather than via RAII, an unwinding throw leaves torch-function dispatch globally disabled — which the bare catch now makes silent.

Carrying forward: a test through load_package; the exclusive footer; the __call__ hint's load_compiled_function wording on in-process captures; an unexpected-keyword case in the arity test; and VecNEON as a real instance.

| Branch: `gh/bobrenjc93/1094/head`

[ghstack-poisoned]
Comment thread torch/_dynamo/package.py Resolved
Comment thread torch/_dynamo/package.py Resolved
Comment thread torch/_dynamo/output_graph.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 59m 20s —— View job


Round 24: the emits_native_code = False opt-out is wired correctly through both entrypoints and closes the "gate is not satisfiable on every host" hole — but it is a fail-open escape hatch documented with no warning, its test never round-trips through save/load, and the dead except-branch predicate from round 23 is unchanged.

Full review of #195354

PR Review: #195354

Summary

Fixes global guards on reloaded nn.Module artifacts by passing the live model.forward.__globals__ as a guard-only scope, and adds a CPU-codegen-target compatibility check to precompile and AOT artifacts.

Delta since round 23, separating PR-owned from base-owned. The raw 636d0a5b..HEAD range touches eight files, but the three-dot diff against the base narrows it sharply. git diff origin/gh/bobrenjc93/1094/base...HEAD -- torch/_dynamo/guards.py test/dynamo/test_guard_serialization.py is empty, so the guard_tree_verbatim set→dict change, the _fqn_resolves extraction, and every comment rewording in those files are base-owned (#195353) — as are the _ProbeState.parked mechanism (present verbatim at base:aot_compile.py:73-75), the _reduce_bound_method static is func rewrite (base:package.py:323-332), the _aot_wraps_deco fixture and its test (base:test_aot_compile.py:578-597), the six TestAOTCompilePickler relocations, and the cached_backends assertion in test_package.py (base:140-142).

This PR's own delta is four items:

  1. CompileArtifacts.requires_native_backend_compatibility (aot_compile.py:70-73), defaulting True, ANDed into check_codegen (:83-86) and set at capture from native_backend (:682).
  2. The capture-time derivation (:655-660): getattr(getattr(backend, "compiler_fn", backend), "emits_native_code", True) is not False and emits_native_code(backend_name).
  3. _backend_emits_native_code honors the declaration for the package path (eval_frame.py:1807-1810).
  4. Docs (torch.compiler_aot_compile.md:162-198): the #choosing-a-backend anchor replaced by a (choosing-a-backend)= label plus a {ref} role, and the ISA-gate paragraph rewritten to name the opt-out. Plus one test, test_aot_compile_backend_declaring_no_native_code_skips_the_isa_gate.

What verifies

The declaration reaches both aot entrypoints, which is the part I'd have expected to break. I traced it rather than trusting the comment. Via torch.compile(fn, backend=python_backend): _TorchCompileWrapper.__init__ sets compiler_fn = lookup_backend(python_backend), and lookup_backend returns a non-str argument unchanged (backends/registry.py:124-142), so compiler_fn is the user callable; innermost_backend unwraps _torchdynamo_orig_backend past WrapBackendDebug and stops at the _TorchCompileWrapper (which defines no such attribute), so aot_compile.py:657's getattr(backend, "compiler_fn", backend) lands on the declaration. Via torch._dynamo.optimize(python_backend): innermost_backend stops at the raw callable itself, getattr(..., "compiler_fn", callable) is the identity, and the declaration is read directly. So the opt-out works on the entrypoint where backend_name is "unknown" (get_compiler_fn erased the string) as well as the one where it is the callable's __name__ — this is the first thing in the stack that makes those two paths agree, and it closes the finding from the review thread that the gate "is NOT satisfiable on every host."

_TorchCompileInductorWrapper and _TorchCompileAOTInductorWrapper have no compiler_fn (torch/__init__.py:2842-2963), so the inductor path reads the declaration off the wrapper, finds nothing, and falls through to the "inductor" name check. No accidental exemption.

No BC change for existing artifacts. CompileArtifacts(**state) at :493 supplies the dataclass default True for an artifact whose pickled __dict__ lacks the key, so an old inductor artifact stays gated and an old eager artifact is still exempted by emits_native_code(backend_name). The AND is more permissive than either operand alone, so nothing that loaded before is refused now.

The {ref} fix is correct. docs/source/conf.py enables myst_nb and myst_enable_extensions but sets no myst_heading_anchors, so the old [...](#choosing-a-backend) had no target to resolve; an explicit (choosing-a-backend)= target plus {ref} needs no extension and is order-independent. grep confirms that anchor is the only cross-reference of its kind left in the file.

API Design

The opt-out is a documented public contract with no misuse warning, and it is the one fail-open lever in a design that is otherwise fail-closed everywhere. The user guide now tells readers that a backend "declaring emits_native_code = False … bake[s] no generated code and [is] not subject to this check" (torch.compiler_aot_compile.md:196-198). A user who sets that attribute on a backend that does lower through inductor gets an artifact with cpu_codegen_target=None that loads on any host and then recompiles capture-ISA-tiled source with the host's ISA — exactly the outcome the PR's own FAQ calls a "silent-wrong-result/crash hazard" and the reason _NO_NATIVE_CODE_BACKENDS is described as "a blacklist on purpose" (package.py:746-751). Every other exemption in this design is either name-matched against an in-tree allowlist or defaults to armed; this one is user-asserted and unverifiable. The docs should say what declaring it wrongly costs, and where it must live: the attribute is read exactly one compiler_fn deep, so a backend wrapped in another callable (an aot_autograd(fw_compiler=...)-style shim) has to carry the declaration on the outer object, which nothing states.

Relatedly, this attribute is now de facto public API — named in a user guide, read via getattr in two modules — with no home in the SerializableCallable protocol (aot_compile_types.py), no __all__ entry, and no type surface. register_backend (backends/registry.py:87-115) would be the natural place to accept and stamp it, which would also let the classifier match by identity instead of by name and close the __name__ == "eager" collision that is the other fail-open direction. Fix this →

The docs' exempt list is narrower than the code's. _NO_NATIVE_CODE_BACKENDS (package.py:752-764) holds nine names, including aot_eager_decomp_partition, aot_eager_decomp_partition_crossref, aot_eager_decomp_partition_with_mode, aot_eager_default_partitioner, eager_debug, eager_noexcept and pre_dispatch_eager; the paragraph names only "eager" and "aot_eager". A user on aot_eager_decomp_partition reads that their artifact is gated when it is not.

getattr(..., "emits_native_code", True) is not False treats a callable declaration as native. A backend that spells the opt-out as a method returning False (rather than a class/instance attribute) is silently gated. Fail-closed, so not a defect, but the docs say "declares emits_native_code = False" without saying it must be the value, not a predicate.

Code Quality (carried forward, all re-verified at this head)

The except-branch missing-global predicate is still dead code, and the footer it selects is still unpinned there. aot_compile.py:769 tests "KeyError on G[" in detail where detail = str(e) from a raised exception. That substring is produced in exactly four places in the tree — guards.cpp:5569, :5688, :5780, :6892 — and all four are GuardDebugInfo(false, std::string("KeyError on ") + get_source(), 0) return values on the non-raising path, immediately after PyErr_Clear(). Nothing raises a message shaped that way. test_no_match_message_survives_a_raising_guard raises KeyError("G['SOME_GLOBAL']") (test_aot_compile.py:1434, :1437), whose str() is "G['SOME_GLOBAL']" — it fails the predicate, so that report gets the generic "Add a ModelInput" footer for a failure whose cause is a named missing global.

Sharpening this from round 23: footer selection is now pinned on the non-raising branch — test_aot_compile_module_no_match_error asserts "Add a ModelInput" (:1408) and test_aot_compile_module_absent_global_fails_guard asserts "load with an f_globals" (:1747) — so the only unpinned branch is precisely the one whose predicate cannot fire. Restoring the round-22 or "G['" in detail disjunct (an over-match yields a wrong hint, never a wrong result) plus one assertIn in the raising test settles it; deleting the dead if and its four-line comment is the honest alternative.

The FAQ's justification for the dispatch loop's except Exception is still wrong. aot_compile.py:731-734 wraps guard_manager.check in a bare catch, defended by "The C++ guard tree never propagates -- check_nopybind clears and returns false". grep -c "} catch" torch/csrc/dynamo/guards.cpp returns 0, and RootGuardManager::check_nopybind_template has no try/catch, so TORCH_CHECK/TORCH_INTERNAL_ASSERT/py::cast throws do unwind through RootGuardManager::check and pybind raises them out of .check(). That function also restores PythonTorchFunctionTLS by hand at three sites (guards.cpp:4400, :4408, :4414) with no RAII guard, so an unwinding throw leaves torch-function dispatch globally disabled — which the bare catch now converts from a loud failure into a silent miss.

The __call__ missing-global hint fires on artifacts that were never serialized. :392 gates on self._guard_globals is None, but the field defaults to None (:299) and the capture path constructs AOTCompiledFunction(_artifacts=artifacts, _extra_globals=fn.__globals__) (:685-687) without it, while artifacts.guard_manager is already populated (:672) so __post_init__'s rebuild at :333 is skipped and guards stay rooted at the live tracing globals. Reachable under a filter that keeps global guards. The text names load_compiled_function, which an in-process capture never called, and is also inapplicable on AOTCompiledModel.deserialize's except fallback (:833), since OptimizedModule._load_aot_compiled_module takes no f_globals. _no_match_message's always-true phrasing at :780-781 costs nothing to reuse.

The footer is exclusive (:778-787), so a two-result failure where one result lacks a global and the other has an ordinary mismatch drops the ModelInput advice. compile_single_graph (:858-869) traces each ModelInput under its own contexts, so guard trees genuinely differ per result. Diagnosis is not lost; the trailing hint is misdirected.

The guard-scope seeding runs regardless of whether any global guard survived filtering (:340-378), and the default guard_filter_fn drops every g.is_global — builtins-rooted guards included, while builtins_key is truthy regardless since name_of_builtins_dict_key_in_fglobals is assigned unconditionally at trace time. For a bound nn.Linear.forward the mutated dict is torch/nn/modules/linear.py's namespace, and uninstall/__del__/_installed_globals have zero occurrences in aot_compile.py. FAQ'd as "no uninstall surface by design", which is fair for the mutation; gating the seed on survival would make the default path a no-op.

A functools.wraps wrapper assigned to forward silently yields the wrong guard scope — get_traced_fn has no __wrapped__ handling, _get_signature passes follow_wrapped=False, and functools.wraps copies __module__/__name__/__qualname__ but not __globals__. Silent only under asymmetric wrapping. FAQ'd; deferral is right.

_cpu_codegen_target_problem tests current is None before unpacking cached, so an x86 artifact on a toolchain-less aarch64 host never learns about the architecture. Presentational only — the enclosing RuntimeError prints the full cached tuple. _simdlen/_march are unpacked and never read; cached[:4] says the same.

The nested-compile-region config path is outside the in-scope sample. _patch_nested_region_inductor_config (compile_fx.py:667-673) is live inside backend() and is not in backend.config, so a subgraph tiled under a per-region cpp.simdlen is fingerprinted with the ambient wider ISA. The comment at aot_compile.py:644-654 reads as though the wrapper's config is the only scope that matters.

Both store reload sites take the constructor default True. package.py:1624 and :1766 are bare CompilePackage(fn, entry.dynamo) / (fn, results.dynamo); the field's only write is the constructor and its only reads are cache_entry() (:1479, :1483-1485). FAQ'd as deliberately fail-closed, which matches the code, and still untested through either shipped API — test_loaded_eager_package_stays_exempt_on_resave (test_package.py:299-321) hand-constructs the package with the kwarg the two shipped callers do not pass.

The resume-name collision class is open at this commit. install_resume_function_global calls install_global_unsafe directly, bypassing the retry this PR added to install_global; _resume_global_renames, package_token and uuid still have zero occurrences in package.py, so the separator the FAQ describes lands in #195911 above this PR. Pre-existing, so it does not block.

Testing

The new test never round-trips the flag it exists to persist. test_aot_compile_backend_declaring_no_native_code_skips_the_isa_gate (test_aot_compile.py:2517-2548) asserts on the live compiled._artifacts and calls artifacts.check_compatibility() directly, so it covers capture-time derivation and the in-process gate skip but never save_compiled_function / load_compiled_function. The comment claims the artifact "loads on a host whose ISA differs (or that has no toolchain at all)", and loading is the scenario the field serializes for. Since serialize copies _artifacts.__dict__ and deserialize splats it into CompileArtifacts(**state), a field-name change or a state.pop added upstream would silently restore the default True and re-arm the gate with no test failing. A save/reload under patch(_current_cpu_codegen_target, return_value=None) is a few lines, and it is the assertion the second half of the test is already reaching for.

The test's negative half is also asserted only indirectly — assertFalse(requires_native_backend_compatibility) and assertIsNone(cpu_codegen_target) — with no companion case showing the same backend minus the declaration does record a target. test_eager_backend_entry_is_exempt_from_the_codegen_target (test_package.py:262-297) covers that on the package path; the aot path does not. Fix this →

Other gaps, each tied to a finding above:

  • The raising branch's footer is unpinned — the one place the dead predicate lives.
  • No test where an opted-out result's guard evaluation raises, and nothing covers the PythonTorchFunctionTLS leak the bare catch now hides.
  • Neither shipped store reload path is exercised for the package flag.
  • The AttributeError arm at aot_compile.py:820 is uncovered. The only unusual-forward test assigns a functools.partial, which has no __self__ and takes the RuntimeError arm inside get_traced_fn. mod.forward = torch.relu and types.MethodType(callable_instance, mod) are the two reaching shapes; MethodType has zero occurrences in the file. FAQ'd as low-value, which I accept.
  • Nothing covers the nested-compile-region config path.
  • VecNEON is never instantiated in either test file; only VecSVE(128)/VecSVE(256) are real, so NEON-vs-SVE128 is covered solely by the literal tuples in _CODEGEN_TARGETS.

Recommendation

Approve with comments

The opt-out is the right shape and it lands correctly on both entrypoints — I traced lookup_backend returning the raw callable through _TorchCompileWrapper.compiler_fn, and innermost_backend stopping at the wrapper (no _torchdynamo_orig_backend) rather than past it, so getattr(backend, "compiler_fn", backend) reaches the declaration whether the user went through torch.compile or torch._dynamo.optimize. That closes the review-thread finding that the ISA gate was not satisfiable on a toolchain-less host for a no-codegen user backend, and it does so without changing behavior for any artifact already on disk (the default True plus the pre-existing name check reproduce the old answer exactly). The {ref} label also fixes the docs build for the right reason — no myst_heading_anchors is configured, so the #heading form had no target.

Three things I'd tighten. The opt-out is now advertised in a user guide as a supported declaration, and it is the only user-assertable fail-open lever in a design the FAQ repeatedly justifies as fail-closed — the docs should say that declaring it on a backend that does emit CPU kernels produces the silent wrong-result the gate exists to prevent, and that the attribute is read one compiler_fn level deep so a wrapped backend must carry it on the outer callable. The new test never saves and reloads, which is the whole point of persisting the field, so a serialization regression would restore the default True silently. And the round-23 predicate narrowing is unchanged: "KeyError on " appears only in GuardDebugInfo return values at four guards.cpp sites, all after PyErr_Clear(), so the except-branch detection cannot fire — and that branch is now the only footer path without an assertIn, since both non-raising footers picked up assertions last round.

Carrying forward: the FAQ's "the C++ guard tree never propagates" claim (guards.cpp has zero catch blocks), the __call__ hint's load_compiled_function wording on in-process captures, the exclusive footer, the docs' incomplete eager-family list, and a test through load_package.

| Branch: `gh/bobrenjc93/1094/head`

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
[ghstack-poisoned]
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
@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 9, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 11m 6s —— View job


Round 25: all four round-24 items land correctly — the dead predicate is fixed and pinned, the opt-out now round-trips through disk, and the docs carry the misuse warning — but the emits_native_code placement rule the docs added is wrong for the one example it names, aot_autograd(fw_compiler=...).

Full review of #195354

PR Review: #195354

Summary

Fixes global guards on reloaded nn.Module artifacts by passing the live model.forward.__globals__ as a guard-only scope, and adds a CPU-codegen-target compatibility check to precompile and AOT artifacts.

Delta since round 24. Diffing the round-24 PR-owned three-dot diff against the current one isolates 116 changed lines, and every one is a response to a round-24 item. Base-owned this round (absent from git diff origin/.../base...HEAD, present verbatim in git show origin/.../base:...): the "Can't get local object" comment correction in serialize's except clause — that wording finding has been fixed in #195353, where it belongs.

This PR's own delta is five items:

  1. The dead except-branch predicate fixed (aot_compile.py:770): "KeyError on G[" in detail → kind == "KeyError" and "G['" in detail.
  2. The raising-guard footer pinned (test_aot_compile.py:1505): assertIn("load with an f_globals", message).
  3. The opt-out test round-trips through save/load and gained its mirror (:2588-2608).
  4. The __call__ hint reworded to _no_match_message's always-true phrasing (:398-402).
  5. Docs: the eager-family list now names _NO_NATIVE_CODE_BACKENDS, the "any other value counts as native" rule, the placement rule, and a misuse warning (torch.compiler_aot_compile.md:196-208). Plus cached[:4] replacing the two throwaway unpacks (package.py:729) and an arming fix in test_check_compatibility_compares_artifact_against_current_machine.

What verifies

The predicate fix is correct and reachable. kind == "KeyError" plus "G['" matches what a raised KeyError("G['SOME_GLOBAL']") stringifies to ("G['SOME_GLOBAL']" — KeyError.__str__ is repr(args[0])), which is exactly what the old "KeyError on G[" could not: that substring exists in the tree only at guards.cpp:5569, :5688, :5780 and :6892, all as GuardDebugInfo return values on the non-raising path after PyErr_Clear(). Requiring the type name rather than just the disjunct also narrows the over-match I was ambivalent about last round — an arbitrary RuntimeError mentioning a global repr no longer flips the footer, so the fix is tighter than the round-22 form it restores.

And it is now pinned: test_no_match_message_survives_a_raising_guard (test_aot_compile.py:1505) asserts the missing-global footer, alongside test_aot_compile_module_no_match_error's "Add a ModelInput" (:1447). Both footer branches now have an assertion, which is what let this regress twice unnoticed. len(message.splitlines()) == 4 still holds — one footer either way.

The opt-out test now covers the thing the field serializes for. test_aot_compile_backend_declaring_no_native_code_skips_the_isa_gate (:2588-2596) saves to self.path(), then under patch(_current_cpu_codegen_target, return_value=None) both calls artifacts.check_compatibility() and reloads through torch.compiler.load_compiled_function, asserting the reloaded callable serves. That closes the hole I described: serialize copies _artifacts.__dict__ (:420) and deserialize splats into CompileArtifacts(**state) (:494), so a dropped key would silently restore the default True and re-arm the gate — and the reload happens inside the return_value=None patch, which is the host shape that would raise if it did. The mirror is there too (:2598-2608): an undeclared_backend with the same body records requires_native_backend_compatibility=True and the sentinel target, so "the declaration is what did it" is asserted rather than assumed.

The __call__ hint no longer names an API the caller may not have used. :398-402 now reads "a guarded global is missing from this process; define it (or load with an f_globals carrying it)", matching _no_match_message:780-783. That is true for the in-process capture path (_guard_globals defaults None at :495, and the capture path at aot_compile_fullgraph never sets it) and for AOTCompiledModel.deserialize's except fallback, where OptimizedModule._load_aot_compiled_module takes no f_globals. The FAQ's own preferred wording, adopted.

The eager-arm arming fix is a real repair, not cosmetic. test_check_compatibility_compares_artifact_against_current_machine:2497-2499 now asserts backend_name == "eager" and requires_native_backend_compatibility is False, then sets the flag True before the exemption assertion. Without that, check_codegen is the AND of the name check and the new flag (aot_compile.py:83-86), so flipping only backend_name = "inductor" at :2507 would leave the gate disarmed by the flag and the subsequent assertRaises at :2523 would fail. The test now pins the name exemption and the receiver order independently, which is the right split.

cached[:4] (package.py:729) drops the two bound-and-never-read names. Correct — gating is 4-of-6 and the docstring says so at :717-718.

API Design

The docs' placement rule is wrong for the example it gives. torch.compiler_aot_compile.md:202-205 says the attribute is read off the callable handed to torch.compile "or off that callable's compiler_fn when it is a wrapper, so for aot_autograd(fw_compiler=...) set it on the object aot_autograd returns."

The general rule matches the code — aot_compile.py:658 and eval_frame.py:1808 both do getattr(backend, "compiler_fn", backend) — but the aot_autograd instance is the one shape where "set it on the returned object" does not work. aot_autograd(**kwargs) returns an AotAutograd instance (backends/common.py:170-171), and AotAutograd.__init__ sets self.__name__ = "compiler_fn" (:76) — a __name__, not a compiler_fn attribute. So when a user writes torch.compile(fn, backend=aot_autograd(fw_compiler=my_fn)):

  • lookup_backend returns the non-str argument unchanged, so _TorchCompileWrapper.compiler_fn is the AotAutograd instance.
  • innermost_backend stops at the _TorchCompileWrapper (it defines no _torchdynamo_orig_backend), so getattr(backend, "compiler_fn", backend) yields the AotAutograd instance — one level, and it lands there.
  • Setting emits_native_code = False on that instance therefore does work by luck, but not for the reason the docs give: it works because the instance is itself the compiler_fn of the wrapper, not because AotAutograd exposes a compiler_fn the lookup unwraps. A reader following the stated mechanism would look for instance.compiler_fn and find __name__ == "compiler_fn" instead — a confusing near-miss.
  • Worse, on the torch._dynamo.optimize(aot_autograd(...)) entrypoint the unwrap stops at the instance directly, so the same placement works via a different path. The rule as written describes neither.

The accurate statement is simpler and covers both entrypoints: set it on the callable you pass to torch.compile/optimize; the lookup also follows one compiler_fn hop, which is what makes _TorchCompileWrapper transparent. Naming aot_autograd specifically invites the wrong mental model for the one in-tree wrapper whose attribute is __name__, not compiler_fn. Fix this →

The misuse warning is now present and correctly scoped. :205-208 says declaring it on a backend that does emit native code "disables the only check standing between a mis-targeted artifact and a crash or wrong result at first call" — that is the right severity, and the "any other value, including a method, counts as native" clause (:201-202) documents the is not False semantics I flagged. The eager-family list also now names the set rather than two of its members, closing the incomplete-list note. What remains from that finding is the protocol/registry half, which the FAQ declines with a reason I accept (the flag describes codegen, not serializability, and the opt-out exists for the callable handed straight to torch.compile, which register_backend would not cover).

_TorchCompileWrapper derives compiler_name from backend.__name__, so a user callable named eager/aot_eager lands in _NO_NATIVE_CODE_BACKENDS and is exempted even if it lowers through inductor — the other fail-open direction, and the opposite of what package.py:745-748 claims ("anything unrecognised … is assumed to emit code"). The other three classifier paths are fail-closed: _backend_emits_native_code misclassifies by entrypoint since register_backend stamps no compiler_name; instance backends are never classifiable (CompileCounter has no __name__); and aot_compile.py:644 records getattr(backend, "compiler_name", "unknown") after get_compiler_fn erased the string. FAQ'd, and now partly moot for the intentional case since the declaration is a first-class opt-out.

Both store reload sites take the constructor default True. package.py:1621 and :1763 are bare CompilePackage(fn, entry.dynamo) / (fn, results.dynamo); initialize() restores _device_types but not the flag, and cache_entry() reads it at :1476 and :1480-1482. FAQ'd as deliberately fail-closed with the fix attributed to #195913, which matches the code. Still untested through either shipped API — test_loaded_eager_package_stays_exempt_on_resave hand-constructs the package with the kwarg the two shipped callers do not pass, and test_package.py calls ctx.load_package in eight other tests, so the seam is available.

The resume-name collision class is open at this commit. install_resume_function_global calls install_global_unsafe directly, bypassing the while name in self.global_scope retry install_global gained; _resume_global_renames, package_token and uuid still have zero occurrences in package.py, so the separator lands in #195911 above this PR. Pre-existing and correctly FAQ'd as such.

Code Quality (carried forward)

The FAQ's justification for the dispatch loop's except Exception is still overstated. aot_compile.py:732-735 wraps guard_manager.check in a bare catch; the review-thread reply says "the C++ tree clears and returns false". Re-verified: grep -c "} catch" torch/csrc/dynamo/guards.cpp returns 0, and RootGuardManager::check_nopybind_template has no try/catch, so TORCH_CHECK/TORCH_INTERNAL_ASSERT/py::cast throws unwind through RootGuardManager::check and pybind raises them out of .check(). That function restores PythonTorchFunctionTLS by hand at guards.cpp:4400, :4408 and :4414 (and the mirror at :4466-:4486) with no RAII guard, so an unwinding throw leaves torch-function dispatch globally disabled — which the bare catch converts from a loud failure into a silent miss. The PR body's FAQ has since been corrected on this point ("the C++ guard tree does not swallow everything … reaches Python as a RuntimeError, which the scan now treats as 'this entry did not match'"), so the description and the code agree; the leak itself is pre-existing in guards.cpp and out of scope. Narrowing the except to the types the scan means to tolerate would still be the tighter form.

The footer is exclusive (:779-788), so a two-result failure where one result lacks a global and the other has an ordinary mismatch drops the ModelInput advice. compile_single_graph traces each ModelInput under its own contexts, so guard trees genuinely differ per result. Diagnosis is not lost — the [i] lines are all emitted — and the FAQ concedes per-[i] attachment is the right shape. Note the predicate divergence I raised is now asymmetric in the other direction: the raising branch requires kind == "KeyError" while the non-raising branch matches "KeyError on G[" anywhere in the joined parts. Both are defensible for their input shapes, so I am not carrying this further.

The guard-scope seeding runs regardless of whether any global guard survived filtering (:340-378), and the default guard_filter_fn drops every g.is_global — builtins-rooted guards included, while builtins_key is truthy regardless since name_of_builtins_dict_key_in_fglobals is assigned unconditionally at trace time. For a bound nn.Linear.forward the mutated dict is torch/nn/modules/linear.py's namespace, and uninstall/__del__/_installed_globals have zero occurrences in aot_compile.py. FAQ'd as "no uninstall surface by design", fair for the mutation; gating the seed on survival would make the default path a no-op.

A functools.wraps wrapper assigned to forward silently yields the wrong guard scope — get_traced_fn has no __wrapped__ handling, _get_signature passes follow_wrapped=False, and functools.wraps copies __module__/__name__/__qualname__ but not __globals__. Silent only under asymmetric wrapping. FAQ'd; deferral is right.

_cpu_codegen_target_problem tests current is None (package.py:720) before unpacking cached (:729), so an x86 artifact on a toolchain-less aarch64 host never learns about the architecture. Presentational only — the enclosing RuntimeError at :845-849 prints the full cached tuple, machine included.

The recorded simdlen/march are diagnostics-only but printed prominently. :845-849 interpolates the whole six-tuple while the ISA remedy at :737-738 names cpp.simdlen, so a 256-vs-None tail difference can read as causal. The docstring says plainly at :717-718 that they do not gate; only the message is silent.

The nested-compile-region config path is outside the in-scope sample. _patch_nested_region_inductor_config (compile_fx.py:667-673) is live inside backend() and is not in backend.config, so a subgraph tiled under a per-region cpp.simdlen is fingerprinted with the ambient wider ISA. FAQ'd as out of scope for a per-artifact fingerprint, which is a fair framing; the comment at aot_compile.py:645-655 still reads as though the wrapper's config is the only scope that matters.

Backward Compatibility (carried forward, both FAQ'd)

A mixed cpu+accelerator artifact hard-fails on a host lacking the accelerator, where pre-PR it loaded — the device set is unioned, the collapse is accelerator-wins (package.py:1462-1466), and check_versions loops every device (:918-923). Correct. Residual is ordering: sorted(device_types) puts codegen first (:917), so a host that is both accelerator-less and ISA-skewed is told to set ATEN_CPU_CAPABILITY and never learns there is no GPU.

check_codegen=False returns early inside the GPU block (:859-860, after only the availability check at :856-857), so an eager-family cuda artifact skips toolkit_version (:862), triton_version (:871) and gpu_name (:880). The comment at :851-855 now explicitly carves device existence out of the gate, which is the right framing, and the case is covered by a test.

A capture under options=/mode= imposes a matching-config requirement at load. Save samples under backend.config (aot_compile.py:654-664), load samples ambiently. The docs paragraph covers this correctly, including that options= does not apply at load.

Testing

The strongest addition is the save/reload half of the opt-out test — it is the one assertion that would catch a serialization regression on the new field, and it needs no host toolchain. The second footer assertIn is small but structurally important: both branches are now pinned, and the dead-predicate regression that survived two rounds could not recur.

Remaining gaps:

  • Neither shipped store reload path is exercised for the package flag. ctx.load_package(fn, self.path()) appears eight times in test_package.py, so the seam is right there.
  • The AttributeError arm at aot_compile.py:824 is uncovered. The only unusual-forward test assigns a functools.partial, which has no __self__ and takes the RuntimeError arm inside get_traced_fn. mod.forward = torch.relu and types.MethodType(callable_instance, mod) are the two reaching shapes; MethodType has zero occurrences in the file. FAQ'd as low-value; I accept it.
  • Nothing covers the nested-compile-region config path.
  • VecNEON is never instantiated in either test file; only VecSVE(128)/VecSVE(256) are real, so NEON-vs-SVE128 is covered solely by the literal tuples in _CODEGEN_TARGETS. FAQ'd with the arm64-CI argument, which is reasonable.
  • test_mixed_device_capture_records_cpu_codegen_target still depends on check_versions' sorted(device_types) putting "cpu" first; the production comment at package.py:917 documents it, the test does not.

Recommendation

Approve

All four round-24 items land, and three of them are the tighter version of what I asked for. The predicate fix is better than the round-22 form it restores — requiring kind == "KeyError" alongside "G['" kills the dead branch without reintroducing the over-match — and both footers now carry an assertIn, so the branch that silently regressed twice cannot again. The opt-out test's save/reload leg exercises the exact path the new field exists for (__dict__ copy out, **state splat back in, where a lost key restores the default True), and it runs the reload inside the return_value=None patch, so a re-armed gate would raise. The undeclared_backend mirror pins that the declaration is what caused the exemption. The __call__ hint now uses _no_match_message's always-true phrasing, and the docs carry the misuse warning, the is not False semantics, and the full eager-family reference. I also want to flag the eager-arm arming fix in test_check_compatibility_compares_artifact_against_current_machine — that was a real latent failure, since check_codegen is a conjunction and flipping only the name would have left the gate disarmed.

One thing I would correct, docs-only: the placement rule names aot_autograd(fw_compiler=...) as the wrapper example, but AotAutograd sets self.__name__ = "compiler_fn" (backends/common.py:76) — a __name__, not a compiler_fn attribute. Setting the flag on that instance does work, but because the instance is _TorchCompileWrapper.compiler_fn, not because the lookup unwraps anything on AotAutograd; a reader following the stated mechanism will look for instance.compiler_fn and find the near-miss. Stating the rule without that example ("set it on the callable you pass to torch.compile/optimize; the lookup follows one compiler_fn hop, which is what makes _TorchCompileWrapper transparent") is accurate for both entrypoints.

Carrying forward, none blocking: a test through load_package; the exclusive footer; narrowing the dispatch loop's except Exception to the types it means to tolerate; and labelling simdlen/march as diagnostic in the mismatch message.

| Branch: `gh/bobrenjc93/1094/head`

[ghstack-poisoned]
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
@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 6m 8s —— View job


Re-reviewing PR #195354 (round 26)

  • Isolate the PR-owned delta since round 25 (separate from base updates)
  • Verify the claimed fix against the working tree
  • Re-check standing findings
  • Post review

Round 26: the delta is a single docs paragraph and it is exactly the round-25 fix — the reworded placement rule is now correct for aot_autograd, which is the one in-tree case the old wording got wrong. Nothing blocking; no new findings.

Full review of #195354

PR Review: #195354

Summary

Fixes global guards on reloaded nn.Module artifacts by passing the live model.forward.__globals__ as a guard-only scope, and adds a CPU-codegen-target compatibility check to precompile and AOT artifacts.

Delta since round 25. I diffed the PR-owned three-dot diff at the round-25 head (ff9469b1...bfaba059) against the current one (b95c1191...28e7c03a), ignoring hunk offsets. The result is four lines, all in one paragraph of docs/source/user_guide/torch_compiler/torch.compiler_aot_compile.md:

-the callable handed to `torch.compile`, or off that callable's `compiler_fn`
-when it is a wrapper, so for `aot_autograd(fw_compiler=...)` set it on the
-object `aot_autograd` returns. Declaring it on a backend that does emit
+the object handed to `torch.compile` as `backend` (for a registered backend
+name, off the function that name resolves to), never off anything that object
+wraps: for `aot_autograd(fw_compiler=...)` set it on the object `aot_autograd`
+returns, not on `fw_compiler`. Declaring it on a backend that does emit

No production code changed, no tests changed. Everything else in the bfaba059..28e7c03a range is base-owned (two base updates pulling in unrelated main commits).

Verification of the reword: correct, and it fixes the exact confusion

My round-25 objection was that the old wording described the mechanism as "off that callable's compiler_fn when it is a wrapper" and then named aot_autograd as the example — but AotAutograd sets self.__name__ = "compiler_fn" (backends/common.py:76) and has no compiler_fn attribute (its kwargs live in self.kwargs, :77), so a reader following the stated mechanism would look for instance.compiler_fn, find the __name__ near-miss, and conclude the placement was wrong when it in fact works.

The new wording states the rule in user-visible terms and adds the explicit negative. Checked against the code:

  • "the object handed to torch.compile as backend" — _TorchCompileWrapper.__init__ does self.compiler_fn = lookup_backend(backend) (torch/__init__.py:3009), and lookup_backend returns a non-str argument unchanged (backends/registry.py:124-142), so compiler_fn is the user's object. innermost_backend (eval_frame.py:756-767) walks _torchdynamo_orig_backend and stops at the _TorchCompileWrapper, which defines no such attribute, so the one-hop getattr(backend, "compiler_fn", backend) at aot_compile.py:658 / eval_frame.py:1808 lands exactly there. ✔
  • "for a registered backend name, off the function that name resolves to" — with backend="my_registered", compiler_name is the string (torch/__init__.py:3003) while compiler_fn is _COMPILER_FNS["my_registered"] (registry.py:137-141), so the declaration is read off the resolved function. ✔
  • "never off anything that object wraps … not on fw_compiler" — the getattr is exactly one hop and AotAutograd exposes nothing to descend through, so a declaration on fw_compiler is invisible and one on the returned instance is what is read. ✔ This is the clause that was missing, and it is the one a user would otherwise get wrong.

Scoping it to torch.compile is also right: torch._dynamo.optimize("my_registered") hands _backend_emits_native_code the raw string, so getattr(str, "emits_native_code", True) is True and a declaration on the registered function is not honored on the package path. The FAQ already records that limit; the paragraph no longer over-promises by omitting the entrypoint.

One thing worth a sentence for completeness, not a defect: _TorchCompileWrapper.compiler_name becomes backend.__name__ when the backend is not a string (torch/__init__.py:3005), so aot_autograd(...) classifies under the name "compiler_fn", which is not in _NO_NATIVE_CODE_BACKENDS — i.e. an aot_autograd-wrapped backend is name-classified as native and needs the declaration even when its fw_compiler is eager-family. That is the fail-closed direction and consistent with the paragraph's warning, but it is the concrete reason a reader would reach for the attribute on that shape in the first place.

Standing items, all re-verified at this head

Nothing regressed, and nothing new. Line numbers refreshed:

Fail-open direction in the name classifier. _TorchCompileWrapper derives compiler_name from backend.__name__ (torch/__init__.py:3005), so a user callable named eager/aot_eager lands in _NO_NATIVE_CODE_BACKENDS (package.py:747-762) and is exempted even if it lowers through inductor — the opposite of what emits_native_code's surrounding comment claims. The other three classifier paths are fail-closed: _backend_emits_native_code (eval_frame.py:1802-1811) misclassifies by entrypoint since register_backend stamps no compiler_name; instance backends are never classifiable (CompileCounter has no __name__); and aot_compile.py:644 records getattr(backend, "compiler_name", "unknown") after get_compiler_fn erased the string. FAQ'd, and now largely moot for the intentional case since the declaration is a first-class opt-out.

_NO_NATIVE_CODE_BACKENDS enumerates only the eager family, so ts/aot_ts, invoke_subgraph, cudagraphs, openxla, tvm, the *_TESTING_ONLY gm-passthrough backends and the minifier backends are gated on host ISA despite emitting no inductor CPU kernels. Pure widening; the declaration now gives each of them an escape hatch.

Both store reload sites take the constructor default True. package.py:1622 and :1764 are bare CompilePackage(fn, entry.dynamo) / (fn, results.dynamo); the field's only write is the constructor (:1083-1084) and its only reads are in cache_entry() (:1477, :1481-1482). FAQ'd as deliberately fail-closed with the fix attributed to #195913, which matches the code. Still untested through either shipped API — ctx.load_package(fn, ...) is used in eight other test_package.py tests, so the seam is available.

The resume-name collision class is open at this commit. install_resume_function_global calls install_global_unsafe directly at output_graph.py:3558 and :3560, bypassing the while name in self.global_scope retry at :3606-3608. grep -c 'package_token\|_resume_global_renames\|uuid' torch/_dynamo/package.py is 0, so the separator lands in #195911 above this PR. Pre-existing and correctly FAQ'd as such.

The dispatch loop's except Exception (aot_compile.py:732-735) is broader than the types the scan means to tolerate. grep -c '} catch' torch/csrc/dynamo/guards.cpp is still 0 and RootGuardManager::check_nopybind_template has no try/catch, so TORCH_CHECK/TORCH_INTERNAL_ASSERT/py::cast throws unwind out of .check() — and that function restores PythonTorchFunctionTLS by hand rather than via RAII, so an unwinding throw leaves torch-function dispatch globally disabled, which the bare catch makes silent. The leak is pre-existing in guards.cpp; the PR body's FAQ has been corrected on the propagation claim, so description and code agree. Narrowing the except is still the tighter form. The comment at :723-727 correctly explains why prepare_f_locals is hoisted out (:728), pinned by test_aot_compile_module_wrong_arity_raises_type_error.

The footer is exclusive (:779-788), so a two-result failure where one result lacks a global and the other has an ordinary mismatch drops the ModelInput advice. Both branches are pinned now (test_aot_compile.py:1472 and :1530), and the FAQ concedes per-[i] attachment is the right shape.

The __call__ missing-global hint (:395-400) still fires whenever _guard_globals is None, which includes every in-process capture (:687 passes only _extra_globals), but the wording adopted last round is true in all those cases. Closed as far as I am concerned.

The guard-scope seeding runs regardless of whether any global guard survived filtering (:340-381), so under the default guard_filter_fn the __import_* aliases and __builtins_dict___N land in a torch namespace (torch/nn/modules/linear.py's dict for a bound nn.Linear.forward) for guards that were all dropped. uninstall/__del__/_installed_globals have zero occurrences in aot_compile.py. FAQ'd as "no uninstall surface by design"; gating the seed on survival would make the default path a no-op.

_cpu_codegen_target_problem tests current is None (package.py:721) before unpacking cached[:4] (:730), so an x86 artifact on a toolchain-less aarch64 host never learns about the architecture. Presentational only — the enclosing RuntimeError prints the full cached tuple. The round-25 cached[:4] cleanup is in.

A functools.wraps wrapper assigned to forward silently yields the wrong guard scope under asymmetric wrapping only. FAQ'd; deferral is right.

Nested-compile-region config patches are outside the in-scope sample (compile_fx.py:667-673 is live inside backend() and not in backend.config). FAQ'd as out of scope for a per-artifact fingerprint.

Mixed cpu+accelerator BC change and check_codegen=False inside the GPU block are both FAQ'd and both covered by tests; the ordering residual (a host that is both accelerator-less and ISA-skewed hears only about the ISA) stands as a message-quality note.

Testing

No test changes this round. Remaining gaps, unchanged and all previously discussed:

  • Neither shipped store reload path is exercised for the package flag.
  • The AttributeError arm in deserialize is uncovered — MethodType has 0 occurrences in test_aot_compile.py, and the only unusual-forward test uses functools.partial, which takes the RuntimeError arm inside get_traced_fn. FAQ'd as low-value; accepted.
  • Nothing covers the nested-compile-region config path.
  • VecNEON is never instantiated — 0 occurrences of VecNEON() in either test file, so NEON-vs-SVE128 is covered solely by the literal tuples in _CODEGEN_TARGETS. FAQ'd with the arm64-CI argument, which is reasonable.
  • test_mixed_device_capture_records_cpu_codegen_target still depends on check_versions' sorted(device_types) putting "cpu" first; the production comment documents it, the test does not.

Recommendation

Approve

The one-paragraph reword is exactly the round-25 fix and it is correct. The rule is now stated in terms of the object the user passes rather than an internal attribute, the registered-name case is called out, and the explicit "not on fw_compiler" closes the aot_autograd trap — which was the whole problem, since AotAutograd has a __name__ of "compiler_fn" and no compiler_fn attribute, so the old mechanism-first phrasing pointed a reader at something that does not exist. I re-verified the one-hop getattr lands on the _TorchCompileWrapper's compiler_fn (the user's object, or the function a registered name resolves to) and descends no further.

Nothing blocking, and no new findings. Carrying forward as follow-ups, none of which need to hold this up: a test through load_package for the package flag; per-[i] attachment of the missing-global hint instead of an exclusive footer; narrowing the dispatch loop's except Exception to the types it means to tolerate; and labelling simdlen/march as diagnostic in the mismatch message. Worth one sentence in the docs if you touch that paragraph again: aot_autograd(...) classifies under compiler_name == "compiler_fn" (from AotAutograd.__name__), which is not in the eager-family set, so that shape is name-classified as native and is the concrete case the declaration exists for.

| Branch: `gh/bobrenjc93/1094/head`

pytorchmergebot pushed a commit that referenced this pull request Sep 14, 2026
…t of snapshots, guard the 3.14 annotation read (#196767)

Follow-up to the reviews of #196476, #196478 and #196479.

`_keep_container_verbatim` decided a plain tuple in two steps: is it in
`guard_tree_values`, and is it in `value_guarded_containers`. The second alone
is the rule; the first held because `EQUALS_MATCH` registers the value it
reads, a separate invariant whose failure would be the silent forever-miss the
rule exists to prevent. The tuple case now reads the recording alone:

```python
if type(container) is tuple:
    return id(container) in self.value_guarded_containers
if type(container) is dict:
    return False
return self._keep(container)
```

That is a behaviour change for the case the two invariants disagree on: a
recorded tuple with no tree entry was pruned per value and is now carried
whole. A test builds exactly that state, and it fails on the previous commit.

A globals snapshot kept `__builtins__` "as read" when some guard had registered
it and replaced it with the `builtins` module only when pruned. For an imported
module `f_globals["__builtins__"]` IS `builtins.__dict__`, and a traced
module's own dict binds that same object a second time under the
`__builtins_dict___N` Dynamo installs; that dict is the one a saved
BUILTIN_MATCH guard registers, so wherever one is saved the kept branch was
taken and the snapshot carried all of builtins (about 6 KB) next to
the filtered copy `G` already holds. The live builtins dict is now exempt from
the keep contract by value rather than by name, so every slot holding it -- the
alias included -- travels as a reference resolved in the loading process rather
than as a copy, one shared `_LiveBuiltins` standing for it so a second slot in
the same scope is a pickle memo reference rather than a second reduce. On a
scope carrying both keys that takes the dump from 6781 bytes to 729; a
cross-module snapshot, which has only `__builtins__`, goes from 6758 to 706.
The slot stays a dict, since a guard may have walked through it and rebakes
against whatever it holds at load. A dict without the key stays without
one, since `FunctionType` falls back to the loading frame's builtins and a
guard on the dict's shape must see the same keys; `FunctionType` accepts either
value. The key set is the module dict's at save time, names Dynamo installed
into it included, so such a guard is only as portable as those names.

The snapshot loop iterated the live module dict. A `CleanupHook` pops the name
it owns, and it fires from a weakref callback (`CleanupManager` holds a
`weakref.ref` per traced code object, whose callback runs the hooks attached to
it), so a code object collected during the dump pops a `__compiled_fn_N` or
`__builtins_dict___N` key mid-loop and the next iteration raises `RuntimeError:
dictionary changed size during iteration`. The loop now walks a copy,
`dict(f_globals)`, which also makes the sentence above literally true: the key
set is the one the loop entered with, not whatever survived to its end.
The rarity is not the loop's own doing -- measured with `gc.callbacks`,
snapshotting a scope of 80 `nn.Linear`s runs 82 iterations and takes zero
automatic collections at the default gen-0 threshold (zero at 300, one at 10),
since it allocates almost nothing GC-tracked. What decides whether a callback
lands inside the loop is where the process-wide gen-0 counter already stood when
the dump began. Scanning that offset with default thresholds and no forced
collection, 1 of 200 positions raises against the live dict, and 0 of 200 once
the loop walks a copy; being a flake rather than a reproducible failure is why
the test forces the hook to fire from the loop's first `_prune` call instead of
waiting for a collection. The copy is `dict(f_globals)` rather than
`list(f_globals.items())`: at a gen-0 threshold of 1, where a callback popping a
key raises out of a live `for k, v in d.items()` loop in all 50 trials, neither
spelling raises once, and the dict copy is shorter and materializes no N-entry
list of 2-tuples.

The 6 KB is a snapshot's cost, and `_reduce_function_by_value` builds a snapshot
only for a function whose own `__globals__` is registered too. A plain
`CompilePackage` compile
(`torch._dynamo.optimize("eager", package=CompilePackage(fn))`) applies no guard
filter and keeps that BUILTIN_MATCH, so building its manager registers the dict
the guard reads through -- but the traced function's module dict is not
registered there, so no snapshot is built at all. Reading a global through a
function's `__globals__` does register that dict, and it also guards the
function itself with a CLOSURE_MATCH, which `serialize_guards` refuses
outright, so with no filter at all an artifact built that way bypasses rather
than saving. The 6 KB is paid where a caller-supplied `guard_filter_fn` drops
that function guard and keeps the BUILTIN_MATCH: there the parent embedded the
whole dict and the exemption hands back a reference instead. Both high-level
entry points filter the BUILTIN_MATCH away instead -- `aot_compile`'s default
`guard_filter_fn` drops every `is_global` entry and the alias's BUILTIN_MATCH is
one, and `caching_precompile=True` drops it as ID_MATCH-derived -- so under them
nothing registers `builtins.__dict__` and the parent embedded no copy of it: it
pruned the alias slot to a sentinel and replaced `__builtins__` with the
builtins module. There the exemption instead hands those slots back the live
dict, 772 bytes to 729 on the same scope, which the same rebake argument covers.

On 3.14 the guard pickler read FORWARDREF annotations unguarded, so whatever
that read raised failed the dump. FORWARDREF reruns the annotate function, but
only NAME lookups are proxied -- the rest of the expression runs for real, so
whatever that real work raises comes out:

```python
def f(x: f"{Missing}"):    # TypeError: the proxy refuses __format__
def f(x: ()[0]):           # IndexError: no proxy is involved at all
def f(x: "%s" % Missing):  # reads fine -- it is the operation, not the name
```

That would fail the dump for a slot the prune exists to make optional, so
`_reduce_function_by_value` drops the whole set instead, with a debug log naming
the code object by `co_qualname` where the runtime has one and by `co_name` on
3.10. That log line repeats the AOT pickler's `_pickleable_annotations` one
rather than sharing it: the two handlers differ in policy (that one swallows a
RecursionError too, and afterwards drops unpicklable values key by key instead
of sentinelling them) and each logs under its own module's logger, which is what
tells the two drops apart in a `TORCH_LOGS` run, so what is left to share is a
format string. The handler sits at that caller
rather than inside the shared
`_read_raw_annotations`, which stays a pure reader raising for either format:
the other caller, the AOT pickler's `evaluate=True` one, already handles its own
read (it logs the reason it saw), so a keyword that selects a format does not
also select an error policy. A RecursionError is re-raised rather than dropped:
it is the dump's own limit, which `pickle_guards_state` reports as a bypass, not
a property of the annotation, and swallowing it would drop a set that reads fine
at any other depth. Dropping the whole set cannot silently break a guard: a
guard rooted at `fn.__annotations__` evaluated them at trace time (the VALUE
format, cached on the function), so a read that raises at dump time is one no
guard performed. The 3.14 path had no test at all, since every annotation in the
suite either was an assigned dict or resolved; a 3.14-gated test now pins that
the TYPE_CHECKING-only name is genuinely unreadable outside the FORWARDREF read
-- a direct `__annotations__` read raises `NameError`, a premise pruning to a
sentinel cannot tell from a resolved class -- and that the f-string case drops
the set (CI runs this file on 3.14; there is no local 3.14 build).

Test and comment cleanups: the guarded-defaults test names the full-compile
round trip that can tell a whole-container guard from a per-element one instead
of forward-referencing it; the two snapshot tests assert on names their
module cannot lose instead of comparing whole key sets against a live module
dict a `CleanupHook` can pop from; the
`name_beside_unpicklable_default` subtest now says why the default prunes,
which is that `bind_args` guards `__defaults__` with SEQUENCE_LENGTH and only
`EQUALS_MATCH` records a tuple in `value_guarded_containers`, so a length guard
survives per-value pruning; the pickler `__init__` comment no longer claims
omitting the recording prunes every container; the snapshot comment names both
regimes whose guard filter drops the alias's BUILTIN_MATCH; and the annotations
comment says what the keep branch there is for, which is a dict SUBCLASS assigned
onto `__annotations__` that a guard registered (an exact dict is never carried
whole on any version, and on 3.14 the read hands back a copy, so neither is a
subclass one) -- the branch stays, since deleting it would prune that mapping
per value and rebuild it as a plain dict. The snapshot comment also says what
the exemption costs, which is that a guard walking the slot rebakes against the
loading process's builtins rather than the binding the compile saw; and the two
builtins tests pin the reference identity alone, since a copy cannot be `is` the
live dict, while an absolute byte bound over a stream whose size depends on the
pickle protocol and the per-version `SerializedCode` payload adds nothing to it.

Kept as one commit rather than split three ways along the paragraphs above (the
tuple rule, the builtins exemption, the annotation guard are independent and
each carries its own test): this is the bottom PR of an already-submitted
pickler stack, so splitting it rebases and renumbers every PR above it; what
that buys is a finer bisect over three changes that already sit in disjoint
functions and cannot interact.

One #196476 comment is not a change here: the AOT pickler's own by-value
reducer carried only `__defaults__` at that commit, so an AOT-rebuilt helper
lost `__kwdefaults__` and `__dict__` and its `__name__` was the qualname.
#196685 and the commits between it and this one moved that pickler onto the
shared base, which is where those are already fixed.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k test_snapshot_survives_a_cleanup_hook_pop_during_the_loop
python test/dynamo/test_guard_serialization.py -k snapshot -k verbatim -k alias -k unresolvable_annotation -k raising_annotation_read -k without_builtins -k length_guarded -k name_beside_unpicklable_default
python test/dynamo/test_aot_compile.py -k Pickler
python test/dynamo/test_package.py
```

The preserves-module snapshot test asserts the rebuilt scope's `__builtins__`
comes back as whatever the live dict held (the module when this file runs as
`__main__`, the builtins dict when it is imported), and another pins the alias
slot: with the exemption keyed on the name that slot arrives as a copy of the
whole builtins dict, not the live dict. Six of the seven new tests fail on the
previous commit: that alias one,
`test_snapshot_of_an_unguarded_builtins_dict_stays_a_dict`,
`test_a_recorded_tuple_is_kept_verbatim_without_a_tree_entry` (the behaviour
change above), `test_a_raising_annotation_read_drops_the_set_but_not_a_recursion_error`
(the parent's read is unguarded and nothing on its save path catches it),
`test_snapshot_survives_a_cleanup_hook_pop_during_the_loop` (the parent builds
the snapshot as a comprehension over the same live dict) and, on a 3.14 shard,
`test_reduce_prunes_an_unresolvable_annotation_and_drops_a_raising_one`
via its f-string case. Only
`test_snapshot_of_a_scope_without_builtins_stays_without` passes there, and is
kept for the contract the exemption must not break: a scope that has no
`__builtins__` does not gain one. The TYPE_CHECKING test is 3.14-only and runs
in CI, while the raising-read test patches the read itself, so the drop, its log
and the RecursionError re-raise are covered on every shard, 3.10 included.

Authored with an AI assistant.

Co-Authored-By: Claude Opus 5 <[email protected]>

## FAQ

> **FAQ: why is this not three commits (tuple rule / builtins exemption / 3.14
> annotation guard)?** The three changes are independent, each already carries its
> own test, and the message's paragraphs are the seam -- but #196767 is the
> pre-existing bottom PR of the pickler stack, not part of the #195354 re-slice
> this round is doing. Splitting it renumbers and rebases every PR above it, and
> what that buys is a finer bisect over three behaviour changes that already sit in
> disjoint functions (`_keep_container_verbatim`, `_globals_snapshot`, the
> annotation read in `_reduce_function_by_value`) and cannot interact. The commit
> message keeps the three-way structure so a bisect landing here can tell which
> behaviour it is.

> **FAQ: isn't the `_keep_container_verbatim(raw_annotations)` keep branch dead code
> now?** No, only on 3.14. Below 3.14 the read hands back `fn.__annotations__`
> itself, and CPython lets that be a `dict` subclass; a subclass instance falls past
> the `type(container) is dict` rule to the identity check, so a guard-registered
> one is still carried whole (verified: it round-trips as the subclass, while
> unregistered it comes back a plain dict of sentinels). Deleting the call would
> silently change that case, so the call stays and the comment now states exactly
> when it fires instead of the misleading 3.14-specific parenthetical it replaced.

> **FAQ: the review asked for "FORWARDREF raises for an operation the proxy will
> not represent". Why does the comment say something else?** Because that is not
> the rule either, and the comment now has to be right in both directions. On
> 3.14.7 the discriminator is `_Stringifier.__format__`, which
> `annotationlib.py:520` raises from outright, not string formatting as a class:
> `f"{Missing}"` and `f"{Missing:>10}"` raise, while `f"{Missing!r}"`,
> `f"{Missing!s}"`, `f"{Missing=}"`, `"%s" % Missing` and `str(Missing)` all read
> fine and give `{'x': 'Missing'}` -- those convert to `str` before the format
> opcode, so the proxy's `__str__`/`__repr__` answers. And the proxy is not the
> only way out: `()[0]`, `1/0` and `{}["k"]` raise with no proxy involved at all,
> and `"".join([Missing])` raises from a real callee rejecting the proxy (`expected
> str instance, _Stringifier found`). One sentence covers all three: only NAME
> lookups are proxied, and the rest of the expression runs for real. That is what
> the comment now says, and it is why `[Missing][0]` -- an expression with real
> work that does not fail -- still reads back a `ForwardRef`.

> **FAQ: the review says the `expected_keys` assertions can flake in either
> direction. Isn't a `list()` at the capture the matching fix?** No, on both
> counts. `CleanupHook.__call__` only ever `pop`s and nothing on the dump path
> installs a name into a traced module dict, so the snapshot can only ever come
> back a subset of the captured key set -- one direction, not two. And a `list()`
> would not close it, because the hole is not inside an iteration: it is the gap
> between `expected_keys = set(g)` and the dump, on a dict that is this test
> module's live globals. That capture is itself a third exposure the finding did
> not name -- `set(g)` iterates the live dict, so a hook firing during that
> statement raises `RuntimeError` from the test body. Both tests therefore stop
> comparing whole key sets and assert `assertIn` on names their module cannot
> lose, which is what each was pinning (the module's own state arrived; the shared
> scope is not the half-loaded copy) without depending on a key Dynamo owns.

> **FAQ: Was `list(f_globals.items())` really exposed to a `CleanupHook` pop,
> and is that what `dict(f_globals)` fixes?**
>
> Measured on 3.12.14 with `gc.set_threshold(1, 1, 1)` and a `gc.callbacks`
> entry that pops a key out of a 5000-entry dict: a live
> `for k, v in d.items()` loop that allocates per step raises
> `RuntimeError: dictionary changed size during iteration` in all 50 trials,
> while `list(d.items())` and `dict(d)` each raise in 0 of 50 -- both see one
> or two collections during the call, but those land at a bytecode boundary
> outside the C-level copy rather than between two iterator steps. The window
> inside `list()` therefore did not reproduce on this interpreter, and the
> change is not a bug fix: the loop walks `dict(f_globals)` because it is the
> shorter spelling and materializes no N-entry list of 2-tuples, and the
> comment above it now claims only what the measurement supports, which is
> that iterating the LIVE dict while pruning is what raises.

> **FAQ: the annotation on `raw_annotations: dict[str, Any] = {}` is redundant
> and sits on the fallback rebinding -- the `try` binding two statements up
> already comes from `_read_raw_annotations`, declared `-> dict[str, Any]`, so
> drop it and leave `raw_annotations = {}`.** Declined: dropping it turns
> PYREFLY red. `pyrefly.toml:143-146` switches `implicit-any` on for
> `torch/_dynamo/**`, and pyrefly types each binding on its own rather than
> joining the branches, so a bare empty literal is an error regardless of what
> the other branch binds. Measured with pyrefly 0.58.0, the version pinned in
> `tools/linter/adapters/pyrefly_linter.py`, on a standalone reduction of
> exactly this shape (a `-> dict[str, Any]` callee in the `try`, a bare `= {}`
> in the `except`): `Cannot infer type of empty container; it will be treated
> as containing Any [implicit-any]` on the fallback line without the
> annotation, and clean with it. The callee's declared return type does not
> reach the `except` branch -- only a declaration gives `{}` a contextual type
> -- and `torch/_dynamo/guards.py` is otherwise clean today (`pyrefly check
> --config pyrefly.toml torch/_dynamo/guards.py` reports 0 errors, 28
> suppressed), so this would be a new error on a line the PR touches. The one
> variant that also measures clean is moving the annotation up onto the `try`
> binding; it was not taken because there it merely restates the callee's
> declared return type, whereas on the fallback it is the only binding pyrefly
> cannot infer.

> **FAQ: the review says the 3.14 test's fixture rots "if that name ever gets
> defined at this module's scope". Doesn't the new `NameError` assertion pin a
> premise that a stray `TYPE_CHECKING` import could already break?** No -- that
> particular vector cannot reach the fixture, and the assertion went in anyway
> because the rest of the finding is right. `inner` is built by `exec` into a fresh
> namespace, `ns = {"__name__": __name__}`
> (`test/dynamo/test_guard_serialization.py:1767`), so the annotate function's
> globals are `ns` and not this module's: measured on 3.14.7 with `class
> OnlyUnderTypeChecking` defined at the module scope of the running file,
> `inner.__annotate__.__globals__ is ns` is `True`, `"OnlyUnderTypeChecking" in ns`
> is `False`, and the direct read still raises `NameError: name
> 'OnlyUnderTypeChecking' is not defined`. The reachable rot is an edit to that
> seed dict or to the `exec` string. What does hold is the non-discrimination:
> every unguarded annotation prunes to a sentinel (`torch/_dynamo/guards.py:4535`
> over `_prune` at `:4380-4383`, which keeps only a literal or a guard-registered
> value), so measured on 3.12.14 a fully RESOLVED class annotation comes back
> `_Missing` as well, and the assertion at `:1787` could not tell a proxy from a
> resolved class. One line can: `inner.__annotations__` raising `NameError` before
> the dump, which is the exact premise `_read_raw_annotations` cites for asking for
> the FORWARDREF format at all (`torch/_dynamo/package.py:320-322`). It passes on
> the fixture as written and fails loudly on the seeded namespace.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: #196767
Approved by: https://github.com/pytorchgreenlight
@bobrenjc93 bobrenjc93 changed the title [aot_compile] Fix global guards on reloaded nn.Module artifacts [ref-stack][aot_compile] Fix global guards on reloaded nn.Module artifacts Sep 17, 2026
@bobrenjc93 bobrenjc93 closed this Sep 19, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1094/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