Skip to content

[dynamo] Give CompilePackage an explicit capture/serve mode - #195913

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

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

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

An explicit torch.compiler.precompile capture is a different mode from the
ambient caching_precompile cache: guards are built strictly, only a FILTERED
copy is serialized while the live guards stay intact, and the package is
never auto-persisted. That mode used to be inferred from
serialization_guard_filter_fn is not None, which made the filter double
as a flag. It is now an explicit explicit_capture property, with a
serving sibling for a package that serves a loaded artifact and is never
saved; convert_frame's record/bypass paths, the caching_precompile filter
rewrite and the strict-error selection all read the properties, and
DynamoOutput.build_guards threads them into CheckFunctionManager, whose
filter application is refactored so a serialization filter, on any package,
applies to the saved copy only (an explicit capture without one saves its
guards unfiltered), pruning values against the unfiltered guard tree so
dropping a guard never drops the value it named. An explicit package also
counts its own cache entries for the recompile limit and records the frame
that hit it (mark_current_entry_truncated) plus frames that hold no
guarded code at all (uncovered_frames, derived from the entries so a later
variant that compiles closes the gap), the facts an artifact builder needs to
tell a complete capture from a gap. eval_frame keeps a registry of explicit compile
regions so ordinary compiles subtract them from the shared recompile count.

Three package fixes ride along because the capture path exposed them.
PrecompileCacheEntry.from_cache_entry bypasses a code whose backend it
cannot find on a COPY, so saving can no longer flip the live entry that keeps
serving this process. SystemInfo is read once per package rather than on
every compile that contributes a device, and a CPU codegen-target drift
mid-capture is recorded with a warning instead of raised from inside every
compile; refuse_unserializable() raises at serialization boundaries only,
and convert_frame downgrades that to a skipped save with a warning.

Test Plan:

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

Authored with an AI assistant.

[no ci]

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

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

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 3, 2026
This was referenced Sep 3, 2026
bobrenjc93 added a commit that referenced this pull request Sep 10, 2026
Guards on globals resolve against the traced function's global scope.
`AOTCompiledFunction.deserialize` takes `f_globals` for this, but
`AOTCompiledModel.deserialize` never passed one, so a reloaded module artifact
rebuilt its guards against only what the serialized bytecode reconstructs, and
a global Dynamo specialized away failed every call with "KeyError on G['...']".

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

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

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

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

Test Plan:

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

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

Authored with an AI assistant.

FAQ

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

A: `cached[:4]` now.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

ghstack-source-id: bdfdf3539edd4d29fcd1a3b27d39bde4cc837bad
Pull-Request: https://github.com/pytorch/pytorch/pull/195354
[ghstack-poisoned]
This was referenced Sep 22, 2026
bobrenjc93 added a commit that referenced this pull request Sep 22, 2026
**Problem.** A frame that entered Dynamo and came out with no guarded code is a hole in the artifact: `install()` skips that code object, so after a load the frame runs eagerly for the life of the process, and nothing on `CompilePackage` says which frames those are. The one report that exists, the summary in torch/_dynamo/precompile_package.py, recomputes the predicate off the cache entry and keys it on the bare `co_name`, so two frames that happen to share a name are two entries a reader cannot tell apart. Recording the gap the way the commit below records a truncated frame would get the common case wrong: a frame's first call may take a graph-less branch and a later call may compile a real variant, so a recorded gap would have to be un-recorded at the second call, and with the variants in the other order it would never be recorded at all.

**Fix.** Adds a read-only `uncovered_frames` property to `CompilePackage` that walks the package's entries and reports each one that has a compile id, holds no guarded code and is not bypassed, as a frozenset of `"co_name (filename:firstlineno)"` strings. Nothing is recorded and nothing is serialized; every read recomputes the set from the same entries `install()` consumes. One test compiles a function that returns its input untouched through `torch._dynamo.optimize` with a package and watches the gap appear and then vanish once a variant with guarded code is added under `code_context`; the other registers two entries whose code objects share a name and differ only in filename and checks that both are reported.

**Summary.** The predicate is exactly the set `install()` calls `skip_code()` on minus the entries that never entered Dynamo: it skips every entry that is not bypassed and has no guarded code whether or not the frame ran, and the ones without a compile id are resume functions generated at a graph break and never executed (registered by `add_resume_function`; only leaving `code_context` sets the compile id), which are not gaps because no call reached them. A bypassed entry is excluded because it is not skipped but re-traced on the next call and is already reported through its bypass flag and reason, and a frame that hit the recompile limit keeps its working variants installed, so it has guarded code and shows up only in `truncated_frames`. The key matches the one the commit below uses for truncated frames, so the two sets compose and two frames sharing a name stay two, which the summary's bare-name key cannot tell apart; that summary can read this property instead of recomputing the predicate. Deriving rather than recording is the point: the set is a function of the entries, so whichever order a graph-less variant and a compiling variant ran in, the frame is a gap exactly while it has no guarded code, and `add_guarded_code` closes it with no bookkeeping. The property is runtime-only and changes nothing about what is saved or installed. Carved out of #195913.

## A graph-less frame is a gap until a variant compiles

```python
import torch
from torch._dynamo.package import CompilePackage

def fn(x):
    return x

pkg = CompilePackage(fn)
pkg.uncovered_frames
# parent: AttributeError, CompilePackage has no such property
# now:    frozenset()

torch._dynamo.optimize(backend="eager", package=pkg)(fn)(torch.randn(3))
entry = pkg._codes[fn.__code__]
(entry.has_compile_id, len(entry.guarded_codes), entry.bypassed)
# parent and now: (True, 0, False); the frame entered Dynamo, produced no
#                 graph, and install() would skip_code() it after a load
pkg.uncovered_frames
# now: frozenset({'fn (<this file>:4)'})

with pkg.code_context(fn.__code__):
    pkg.add_guarded_code(b"", fn.__code__)
pkg.uncovered_frames
# now: frozenset(); the set is derived from the entry, so the variant that
#      compiled closed the gap whichever order the two variants ran in
```

Pinned by `test_uncovered_frames_follows_the_entries`.

## Two frames sharing a co_name stay two

```python
from torch._dynamo.package import _DynamoCodeCacheEntry, SerializedCode

def one(x):
    return x

def two(x):
    return x + 0

code_a = one.__code__.replace(co_name="frame", co_filename="a.py")
code_b = two.__code__.replace(co_name="frame", co_filename="b.py")
pkg = CompilePackage(fn)
for code in (code_a, code_b):
    pkg._codes[code] = _DynamoCodeCacheEntry(
        python_code=SerializedCode.from_code_object(code),
        python_module="m", function_names=[], guarded_codes=[],
        import_sources={}, backend_ids=[], code_source=None,
        install_to_global=False, has_compile_id=True,
    )
sorted(pkg.uncovered_frames)
# now: ['frame (a.py:7)', 'frame (b.py:10)']
#      keyed on the bare co_name, as the precompile_package.py summary does
#      today, this reads ('frame', 'frame'): two entries nobody can tell apart

pkg._codes[code_a].has_compile_id = False  # generated, never-executed resume code
sorted(pkg.uncovered_frames)
# now: ['frame (b.py:10)']; install() still skip_code()s code_a, but no call
#      ever reached it, so it is not a gap

pkg._codes[code_b].bypassed = True
sorted(pkg.uncovered_frames)
# now: []; a bypassed entry is re-traced on the next call and is reported
#      through bypassed / bypass_reason instead
```

The first result and the bypass exclusion are pinned by `test_uncovered_frames_distinguish_frames_that_share_a_name`; the compile-id exclusion follows from the predicate and was checked by running the snippet.

Test Plan:
```
python test/dynamo/test_package.py -k uncovered_frames
python test/dynamo/test_package.py
```
The new tests fail on the parent, which has no `uncovered_frames` attribute, and pass here.

Authored with an AI assistant.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

ghstack-source-id: 065f207
Pull-Request: #198093
bobrenjc93 added a commit that referenced this pull request Sep 22, 2026
**Problem.** A frame that entered Dynamo and came out with no guarded code is a hole in the artifact: `install()` skips that code object, so after a load the frame runs eagerly for the life of the process, and nothing on `CompilePackage` says which frames those are. The one report that exists, the summary in torch/_dynamo/precompile_package.py, recomputes the predicate off the cache entry and keys it on the bare `co_name`, so two frames that happen to share a name are two entries a reader cannot tell apart. Recording the gap the way the commit below records a truncated frame would get the common case wrong: a frame's first call may take a graph-less branch and a later call may compile a real variant, so a recorded gap would have to be un-recorded at the second call, and with the variants in the other order it would never be recorded at all.

**Fix.** Adds a read-only `uncovered_frames` property to `CompilePackage` that walks the package's entries and reports each one that has a compile id, holds no guarded code and is not bypassed, as a frozenset of `"co_name (filename:firstlineno)"` strings. Nothing is recorded and nothing is serialized; every read recomputes the set from the same entries `install()` consumes. One test compiles a function that returns its input untouched through `torch._dynamo.optimize` with a package and watches the gap appear and then vanish once a variant with guarded code is added under `code_context`; the other registers two entries whose code objects share a name and differ only in filename and checks that both are reported.

**Summary.** The predicate is exactly the set `install()` calls `skip_code()` on minus the entries that never entered Dynamo: it skips every entry that is not bypassed and has no guarded code whether or not the frame ran, and the ones without a compile id are resume functions generated at a graph break and never executed (registered by `add_resume_function`; only leaving `code_context` sets the compile id), which are not gaps because no call reached them. A bypassed entry is excluded because it is not skipped but re-traced on the next call and is already reported through its bypass flag and reason, and a frame that hit the recompile limit keeps its working variants installed, so it has guarded code and shows up only in `truncated_frames`. The key matches the one the commit below uses for truncated frames, so the two sets compose and two frames sharing a name stay two, which the summary's bare-name key cannot tell apart; that summary can read this property instead of recomputing the predicate. Deriving rather than recording is the point: the set is a function of the entries, so whichever order a graph-less variant and a compiling variant ran in, the frame is a gap exactly while it has no guarded code, and `add_guarded_code` closes it with no bookkeeping. The property is runtime-only and changes nothing about what is saved or installed. Carved out of #195913.

## A graph-less frame is a gap until a variant compiles

```python
import torch
from torch._dynamo.package import CompilePackage

def fn(x):
    return x

pkg = CompilePackage(fn)
pkg.uncovered_frames
# parent: AttributeError, CompilePackage has no such property
# now:    frozenset()

torch._dynamo.optimize(backend="eager", package=pkg)(fn)(torch.randn(3))
entry = pkg._codes[fn.__code__]
(entry.has_compile_id, len(entry.guarded_codes), entry.bypassed)
# parent and now: (True, 0, False); the frame entered Dynamo, produced no
#                 graph, and install() would skip_code() it after a load
pkg.uncovered_frames
# now: frozenset({'fn (<this file>:4)'})

with pkg.code_context(fn.__code__):
    pkg.add_guarded_code(b"", fn.__code__)
pkg.uncovered_frames
# now: frozenset(); the set is derived from the entry, so the variant that
#      compiled closed the gap whichever order the two variants ran in
```

Pinned by `test_uncovered_frames_follows_the_entries`.

## Two frames sharing a co_name stay two

```python
from torch._dynamo.package import _DynamoCodeCacheEntry, SerializedCode

def one(x):
    return x

def two(x):
    return x + 0

code_a = one.__code__.replace(co_name="frame", co_filename="a.py")
code_b = two.__code__.replace(co_name="frame", co_filename="b.py")
pkg = CompilePackage(fn)
for code in (code_a, code_b):
    pkg._codes[code] = _DynamoCodeCacheEntry(
        python_code=SerializedCode.from_code_object(code),
        python_module="m", function_names=[], guarded_codes=[],
        import_sources={}, backend_ids=[], code_source=None,
        install_to_global=False, has_compile_id=True,
    )
sorted(pkg.uncovered_frames)
# now: ['frame (a.py:7)', 'frame (b.py:10)']
#      keyed on the bare co_name, as the precompile_package.py summary does
#      today, this reads ('frame', 'frame'): two entries nobody can tell apart

pkg._codes[code_a].has_compile_id = False  # generated, never-executed resume code
sorted(pkg.uncovered_frames)
# now: ['frame (b.py:10)']; install() still skip_code()s code_a, but no call
#      ever reached it, so it is not a gap

pkg._codes[code_b].bypassed = True
sorted(pkg.uncovered_frames)
# now: []; a bypassed entry is re-traced on the next call and is reported
#      through bypassed / bypass_reason instead
```

The first result and the bypass exclusion are pinned by `test_uncovered_frames_distinguish_frames_that_share_a_name`; the compile-id exclusion follows from the predicate and was checked by running the snippet.

Test Plan:
```
python test/dynamo/test_package.py -k uncovered_frames
python test/dynamo/test_package.py
```
The new tests fail on the parent, which has no `uncovered_frames` attribute, and pass here.

Authored with an AI assistant.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

ghstack-source-id: 5a96458
Pull-Request: #198093
bobrenjc93 added a commit that referenced this pull request Sep 22, 2026
**Problem.** A frame that entered Dynamo and came out with no guarded code is a hole in the artifact: `install()` skips that code object, so after a load the frame runs eagerly for the life of the process, and nothing on `CompilePackage` says which frames those are. The one report that exists, the summary in torch/_dynamo/precompile_package.py, recomputes the predicate off the cache entry and keys it on the bare `co_name`, so two frames that happen to share a name are two entries a reader cannot tell apart. Recording the gap the way the commit below records a truncated frame would get the common case wrong: a frame's first call may take a graph-less branch and a later call may compile a real variant, so a recorded gap would have to be un-recorded at the second call, and with the variants in the other order it would never be recorded at all.

**Fix.** Adds a read-only `uncovered_frames` property to `CompilePackage` that walks the package's entries and reports each one that has a compile id, holds no guarded code and is not bypassed, as a frozenset of `"co_name (filename:firstlineno)"` strings. Nothing is recorded and nothing is serialized; every read recomputes the set from the same entries `install()` consumes. One test compiles a function that returns its input untouched through `torch._dynamo.optimize` with a package and watches the gap appear and then vanish once a variant with guarded code is added under `code_context`; the other registers two entries whose code objects share a name and differ only in filename and checks that both are reported.

**Summary.** The predicate is exactly the set `install()` calls `skip_code()` on minus the entries that never entered Dynamo: it skips every entry that is not bypassed and has no guarded code whether or not the frame ran, and the ones without a compile id are resume functions generated at a graph break and never executed (registered by `add_resume_function`; only leaving `code_context` sets the compile id), which are not gaps because no call reached them. A bypassed entry is excluded because it is not skipped but re-traced on the next call and is already reported through its bypass flag and reason, and a frame that hit the recompile limit keeps its working variants installed, so it has guarded code and shows up only in `truncated_frames`. The key matches the one the commit below uses for truncated frames, so the two sets compose and two frames sharing a name stay two, which the summary's bare-name key cannot tell apart; that summary can read this property instead of recomputing the predicate. Deriving rather than recording is the point: the set is a function of the entries, so whichever order a graph-less variant and a compiling variant ran in, the frame is a gap exactly while it has no guarded code, and `add_guarded_code` closes it with no bookkeeping. The property is runtime-only and changes nothing about what is saved or installed. Carved out of #195913.

## A graph-less frame is a gap until a variant compiles

```python
import torch
from torch._dynamo.package import CompilePackage

def fn(x):
    return x

pkg = CompilePackage(fn)
pkg.uncovered_frames
# parent: AttributeError, CompilePackage has no such property
# now:    frozenset()

torch._dynamo.optimize(backend="eager", package=pkg)(fn)(torch.randn(3))
entry = pkg._codes[fn.__code__]
(entry.has_compile_id, len(entry.guarded_codes), entry.bypassed)
# parent and now: (True, 0, False); the frame entered Dynamo, produced no
#                 graph, and install() would skip_code() it after a load
pkg.uncovered_frames
# now: frozenset({'fn (<this file>:4)'})

with pkg.code_context(fn.__code__):
    pkg.add_guarded_code(b"", fn.__code__)
pkg.uncovered_frames
# now: frozenset(); the set is derived from the entry, so the variant that
#      compiled closed the gap whichever order the two variants ran in
```

Pinned by `test_uncovered_frames_follows_the_entries`.

## Two frames sharing a co_name stay two

```python
from torch._dynamo.package import _DynamoCodeCacheEntry, SerializedCode

def one(x):
    return x

def two(x):
    return x + 0

code_a = one.__code__.replace(co_name="frame", co_filename="a.py")
code_b = two.__code__.replace(co_name="frame", co_filename="b.py")
pkg = CompilePackage(fn)
for code in (code_a, code_b):
    pkg._codes[code] = _DynamoCodeCacheEntry(
        python_code=SerializedCode.from_code_object(code),
        python_module="m", function_names=[], guarded_codes=[],
        import_sources={}, backend_ids=[], code_source=None,
        install_to_global=False, has_compile_id=True,
    )
sorted(pkg.uncovered_frames)
# now: ['frame (a.py:7)', 'frame (b.py:10)']
#      keyed on the bare co_name, as the precompile_package.py summary does
#      today, this reads ('frame', 'frame'): two entries nobody can tell apart

pkg._codes[code_a].has_compile_id = False  # generated, never-executed resume code
sorted(pkg.uncovered_frames)
# now: ['frame (b.py:10)']; install() still skip_code()s code_a, but no call
#      ever reached it, so it is not a gap

pkg._codes[code_b].bypassed = True
sorted(pkg.uncovered_frames)
# now: []; a bypassed entry is re-traced on the next call and is reported
#      through bypassed / bypass_reason instead
```

The first result and the bypass exclusion are pinned by `test_uncovered_frames_distinguish_frames_that_share_a_name`; the compile-id exclusion follows from the predicate and was checked by running the snippet.

Test Plan:
```
python test/dynamo/test_package.py -k uncovered_frames
python test/dynamo/test_package.py
```
The new tests fail on the parent, which has no `uncovered_frames` attribute, and pass here.

Authored with an AI assistant.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

ghstack-source-id: ae9d0d2
Pull-Request: #198093
@bobrenjc93 bobrenjc93 closed this Oct 16, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1115/head branch November 17, 2026 01:46
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