Skip to content

[aot_compile] Reconstruct fqn-mismatched functions in the AOT pickler - #196454

Closed
bobrenjc93 wants to merge 6 commits into
gh/bobrenjc93/1133/basefrom
gh/bobrenjc93/1133/head
Closed

bobrenjc93 wants to merge 6 commits into
gh/bobrenjc93/1133/basefrom
gh/bobrenjc93/1133/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Follow-up to the guard-serialization reconstruction below it in the stack, which
adds the shared FunctionPicklerBase to package.py. This commit also brings the
resolve=True branch of _read_raw_annotations (its only caller is here) and the
AOT-pickler tests that exercise this code, so the PR below stays under the
pr-sanity size gate and each test lives with the code it pins.

AOTCompilePickler now subclasses FunctionPicklerBase instead of
pickle.Pickler, so save_compiled_function rebuilds an fqn-mismatched function
from its code object through the same reconstruction the guard path uses --
dispatching on the shared _fqn_resolves test (a <locals> function, or one
whose module + qualname do not resolve back to it, such as a functools.wraps
wrapper of a module-level function), not only on the <locals> marker -- and its
own _unpickle_cell/_unpickle_bound_method/_unpickle_module/_unpickle_code/
_unpickle_nested_function duplicates are dropped. On top of the shared base it
adds the AOT-only pruning: _dumps_cleanly probes each nested-function attribute
and annotation by object id (memoized, in-flight-aware) so an unpicklable one is
dropped rather than aborting the save, __doc__ is pruned the same way, and
__kwdefaults__ is carried unpruned so a function stays callable.

BC note: torch._dynamo.aot_compile now carries a nested function's
__kwdefaults__, so a helper with an unpicklable keyword default fails
save_compiled_function where it used to serialize with the default dropped
(__doc__, annotations, type params, and __dict__ entries that will not pickle
are pruned instead). The pickle targets _unpickle_nested_function and
_unpickle_cell are removed and _unpickle_module is renamed
_unpickle_python_module; only artifacts saved by an earlier build of the same
torch version can hit the removed targets (check_compatibility requires an
exact torch_version, so released-version artifacts were never cross-loadable),
and they fail with the raw pickle AttributeError because deserialize unpickles
before check_compatibility runs.

Test Plan:

python test/dynamo/test_aot_compile.py

The pickler tests pin the two halves of the prune split directly: an unpicklable
__doc__ is dropped to None and the function still loads and runs, and an
unpicklable __kwdefaults__ raises rather than silently vanishing. A __dict__
cycle between two nested functions round-trips with its unpicklable sibling
pruned, an unmarked nn.Module reached through a nested function's __dict__ is
pruned (and kept when marked as external data), and the two test_save_guidance_*
tests drive serialize()'s guidance through save_compiled_function.

Authored with an AI assistant.

FAQ

Q: AOTCompilePickler shares reducer_override's _reduce_function, which carries
a nested function's whole __dict__ unpruned -- wider than the BC note, since
compile_wrapper is functools.wraps(fn)-decorated and so inherits a
<locals> qualname whenever fn is nested, dragging its get_compiler_config
/aot_compile closures into the pickle; and the annotations/type-params probes
do not help because __dict__ bypasses them. Separately the removed
_unpickle_cell/_unpickle_nested_function and the _unpickle_module rename
surface as a raw AttributeError, not the version-mismatch message. Why is this
acceptable?

A: The AOT path deliberately carries __dict__ unpruned: unlike the guard side,
the runtime's job is to RUN the reconstructed function, so anything it closes
over must survive. _reduce_function on the AOT side takes
attributes=obj.__dict__ by design, and a genuinely unpicklable attribute is
what the BC note describes -- it now fails the save loudly instead of silently
dropping the attribute, which is the safer direction for a callable that will be
executed. The compile_wrapper case does dump its closures, but those are the
compiler configuration the artifact needs; there is no correctness gap, only a
larger blob. The AttributeError-before-version-message ordering is real but
pre-existing (deserialize has always unpickled before check_compatibility, so
any removed pickle target on an old artifact surfaces at unpickle time); making
the version check run first is a separate deserialize-ordering change, tracked
apart from this guard-reconstruction commit.

Q: _dumps_cleanly treats a RecursionError as unpicklable and prunes the
value, and its False outcomes are unlogged, including the suppression of the
"mark these as external data" diagnostic. Is prune-on-overflow right on the
AOT side, which has no bypass to degrade into?

A: Prune is right, and it is the same fix the guard side got. _dumps_cleanly
is a prune probe -- its whole job is to answer "does this value pickle?" and
drop the nested-function attribute or annotation when it does not. A
RecursionError there means "does not pickle cleanly within the limit," so it
prunes rather than aborting. An earlier revision re-raised, on the theory that a
non-memoizing __reduce__ is a pickler bug that should fail loudly; but that
made a deep-but-finite __dict__ value -- ordinary user data reached through a
traversed function -- hard-fail a save that has nothing wrong with it, the same
regression pickle_guards_state fixes on the guard side. A genuinely
non-memoizing __reduce__ cannot be told from deep-finite data at runtime, so
both prune. The value the runtime actually needs still surfaces the "mark as
external data" guidance from the real serialize(), which is unaffected; a
log.debug on the probe is a reasonable observability addition left as
follow-up.

Q: Treating "the probe reaches an unmarked nn.Module" as unpicklable in
_dumps_cleanly silently prunes exactly the modules serialize()'s "mark these as
external data" RuntimeError exists to report. Reached through a nested
function's dict, such a module now vanishes with no diagnostic. Shouldn't it
surface instead?

A: The prune is scoped to the nested-function attributes and annotations that
reducer_override walks, not to the artifact payload. Those attributes are
best-effort: the runtime reassigns whatever survived and never forces a pruned
one, so a module dragged in incidentally -- the classic case is the wrapped
that functools.wraps stashes, which can pull an unrelated Module into a
closure's dict -- has to be dropped rather than allowed to abort the whole
save. That silent-drop-of-incidental-attributes is precisely the regression this
commit fixes; re-surfacing every module reached through any nested dict would
reintroduce it. persistent_id records a value the user DID mark as external data
cleanly and keeps it, so the only thing pruned is an unmarked module reached
through a runtime-optional attribute. A module the user genuinely intends as
payload still reaches serialize() through the top-level
CompileArtifacts.signature, which is dumped unpruned (the known limitation
reducer_override already calls out), so its "mark as external data" diagnostic is
not lost -- only the incidental attributes are.

Q: The BC note and the AOT reduce FAQ blame __dict__, but __dict__ is dropped
per-key through _dumps_cleanly (unchanged, silent) -- the values that NEWLY
hard-fail save_compiled_function are __kwdefaults__ and __doc__, which the old
reduce tuple never carried. Shouldn't the note target those?

A: Yes -- corrected. attributes is built as
{k: v for k, v in obj.__dict__.items() if self._dumps_cleanly(v)}, so an
unpicklable __dict__ entry is dropped, not fatal; the earlier answer's
"carries dict unpruned" wording is stale and superseded by this entry. The
two values this reduce path adds over the old tuple are __kwdefaults__ and
__doc__. This commit now prunes __doc__ too (the runtime assigns it in
_apply_function_state but never reads it back, so an unpicklable docstring must
not fail the whole dump), leaving __kwdefaults__ as the one newly-carried value
that still fails loudly -- correctly, since a function cannot be called without
its keyword defaults. The BC note is about __kwdefaults__.

Q: The AOT reduce path -- the doc prune, the kwdefaults fail-loud, and
the doc/kwdefaults split that is the declared BC break -- shipped without
a test that reaches it (the ~1200 new test lines drive GuardsStatePickler and the
guard/package path, not the AOT reducer).

A: Added two tests to test/dynamo/test_aot_compile.py that pin the two halves of
the split directly: test_pickler_prunes_an_unpicklable_docstring asserts an
unpicklable doc is dropped to None and the function still loads and runs, and
test_pickler_does_not_prune_an_unpicklable_kwdefault asserts an unpicklable
kwdefaults raises (TypeError/PicklingError) rather than silently vanishing, so
a future change to the prune list can no longer flip the split unnoticed.
annotations/type_params ride the same dumps_cleanly prune path the
docstring test exercises. The serialize() e.args augmentation is introduced here and is
pinned through save_compiled_function by the two test_save_guidance
* tests (now
in this commit); the _build_function name-vs-qualname detail the finding also
lists is pre-existing naming behavior, not the BC split, and is left to the
existing coverage.

Q: BQ argues the except AttributeError in serialize() rests on a mechanism
pickle does not produce: on 3.12 save_global catches the local-object
AttributeError and re-raises PicklingError (pickle.py:1085-1088), so the
AttributeError never escapes and "Can't get local object" is not a string pickle
emits. Doesn't that falsify the comment?

A: That reads the pure-Python pickle.py, but pickle.dumps uses the C _pickle
accelerator by default, and the C path does NOT wrap. Reproduced on this env's
CPython 3.12.14: pickling a tuple holding a -class instance raises
AttributeError: "Can't get local object 'outer.<locals>.Cfg'" straight from
_pickle -- unwrapped -- while pickle._Pickler (pure-Python) on the same value
raises PicklingError("Can't pickle <class ...<locals>...>: it's not found ...").
So the AttributeError does escape on the pickler that actually runs, "Can't get
local object" is exactly the C accelerator's message, and catching AttributeError
is required (the reworded comment now attributes the variance to the accelerator
rather than to a CPython version). The broad-catch-relabels-an-internal-bug point
is fair, but the guidance is appended around the original exception -- its message
is preserved, not replaced -- and message-sniffing to narrow the catch is the
brittleness BQ itself warns against. Narrowing to a save/reduce boundary is not
possible either: pickle drives the recursion inside dump(), so the only narrower
filter IS message-sniffing; an internal reducer bug still surfaces with its
original message intact as the prefix, with only guidance appended.

Q: On 3.14 _read_raw_annotations(resolve=True) evaluates PEP 649 annotations
through annotationlib.get_annotations(format=VALUE); a value that probes False
is dropped from the result and referenced only by the discarded probe, so its id
can be reused and the id-keyed _dumps_cleanly cache can go stale. Doesn't that
falsify "probed values stay alive for the whole dump"?

A: No. Format.VALUE reads func.__annotations__, and CPython 3.14 caches the
__annotate__(VALUE) result in the function's __annotations__ slot:
get_annotations returns a fresh dict but the same value objects. Verified on
3.14.7: two VALUE calls return identical objects, all identical to
f.__annotations__[k], and their ids stay live after the returned dicts are
dropped and gc.collect() runs (also with a hand-assigned __annotate__). Every
probed value -- __dict__ values, __doc__, __type_params__, annotation values
-- is therefore owned by the function being pickled, which pickle's memo/state
keeps alive until dump() returns; the cache is per-serialize() call.

Q: The removed _unpickle_nested_function imported __module__ bare, so a
missing module failed inside deserialize; the shared base swallows an import
failure into f_globals = {} and the AOT function fails with a bare NameError at
first call. Shouldn't the AOT subclass re-raise?

A: Deliberate. Nested functions reached here are closure helpers and lambdas
whose __module__ is routinely un-importable at load (exec-created,
transformers_modules.*, the __main__ of a different entry script,
functools.wraps-copied names, non-str values a decorator set), and most never
touch a module global -- the strict rule would make every such artifact
un-loadable for no reason. A helper that does read a global fails at call with a
NameError naming exactly the missing symbol, and builtins still resolve. The
trade-off is documented at the one site that owns it (package.py,
_unpickle_fn_from_module) rather than duplicated as an AOT override; logging the
swallowed module name is a cheap follow-up owned by the base.

Q: serialize() mutates e.args to append guidance; for an AttributeError that
leaves .name / .obj describing the original attribute while args says
something else. Inconsistent?

A: Verified on 3.12: after e.args = (prefix + guidance,), e.name and e.obj
still hold the original attribute and object -- which is correct, since the
original message survives as the prefix of the new one. The traceback "did you
mean" machinery reads .name/.obj, not args, so nothing is desynchronized.

Q: _dumps_cleanly fully serializes each candidate into a throwaway buffer and
the real dump serializes it again, with no size cap. Why not probe lazily or cap?

A: Pickle has no rollback: a failure mid-save leaves partial bytes in the stream
and entries in the memo, so "try the real dump and prune on failure" cannot be
implemented on a Pickler; a probe is the only way to ask "does this pickle?".
The probe scope is narrow -- only nested-function __dict__ values, annotations,
__type_params__ and __doc__; the artifact payload (compiled_fn, guards_state,
runtime_env) is never probed -- and the shared id-cache probes each distinct value
once. A byte cap cannot be made correct: a large-but-picklable value would either
be pruned (breaking the function) or optimistically admitted (defeating the
probe).

Q: The three shared probe attributes (_dumps_cleanly_cache, _inflight, and a
one-element list[bool] used as a mutable box) are implicit state; the
_dumps_cleanly comments narrate rejected revisions; the reducer_override comment
omits __doc__ from the pruned set.

A: All fixed: the three attributes are one explicit _ProbeState dataclass shared
into probe picklers by a single assignment, the two comments state the invariant
instead of the history, and the pruned-set comment lists __doc__.

Q: The cache/cycle machinery, the nn.Module prune, and the BC break had no test
reaching them through this PR's own suite.

A: Added: test_pickler_breaks_a_dict_cycle_between_nested_functions (the
in-flight short-circuit, sibling prune, self-reference intact),
test_pickler_prunes_an_unmarked_module_from_a_nested_functions_dict (pruned
unmarked, kept when marked external), the kwdefault test asserts the original
"cannot pickle" message survives, and the two test_save_guidance_* tests that
drive save_compiled_function moved down from #195354 to the commit that
introduces the try/except they pin.

Q: Adopting the shared _reduce_bound_method is an uncovered BC break that fires
on nn.Module: its hasattr(cls, "__getattr__") clause treats every Module
method as instance-served, so a <locals> Module's method is rebuilt by value
(an unpicklable default now fails the dump, and the reloaded __func__ is no
longer the class attribute).

A: Confirmed and fixed at the shared reducer in #195353: it now asks the class
MRO first (inspect.getattr_static(cls, name) is func, which never runs a user
__getattr__) and returns to pickle's default getattr(self, name) when the
class serves the name; only a name the MRO does not serve falls to the
instance-dict / slot / __getattr__-proxy heuristics. The reviewer's script
passes and the reloaded method's __func__ is the class attribute again; a
decorated forward (MRO serves the wrapper, not __wrapped__) still takes the
explicit path. With the fix there is no BC change to note.

Q: Not caching a leaned False is correct but makes the probe exponential on a
cyclic function cluster whose members are unpicklable through an unpruned slot
(n=20: 0.75s, Fibonacci-like).

A: Fixed: a leaned False is parked in _ProbeState.parked for the rest of the
probe tree and consulted after the final cache while a probe is in flight; the
park is cleared when the outermost probe finishes, so the real dump never sees it.
Sound because a stale park can only over-prune inside a probe, and over-pruning
never flips a probe verdict. n=160 now probes in milliseconds; the wrong-False
regression test still passes.

Q: The dispatch condition is still "<locals>" in __qualname__, so a
functools.wraps wrapper of a module-level function (no marker, but its qualname
resolves to the wrapped function) still fails the save -- the description's
"rebuilds an fqn-mismatched function" overclaims.

A: Fixed: FunctionPicklerBase._fqn_resolves (module + qualname walk, shared with
the guard pickler so the two cannot diverge) is now the dispatch test on the AOT
side; test_aot_compile_rebuilds_a_wraps_wrapper_of_a_module_level_function
saves and reloads exactly that shape. The trade-off for a module absent from
sys.modules is the already-documented one: a by-value rebuild with an empty
scope (NameError at first call) instead of a save-time PicklingError.

Q: The four direct AOTCompilePickler tests sit in TestAOTCompile although
TestAOTCompilePickler exists in the same file, and two re-import io/threading
inside the body.

A: Moved into TestAOTCompilePickler, in-body imports dropped (the module-level
ones exist).

Q: Widening the AOT dispatch to every function _fqn_resolves rejects makes a
cross-module functools.wraps wrapper reload against the wrappee's module dict
(__module__ is copied), so a same-named global reads the wrong value silently
where it previously failed at save.

A: Real; fixed in the shared reducer at #195353 (the no-snapshot reduce now
carries the compile scope, fn.__globals__["__name__"], separately from
__module__, and imports the scope). This commit adds the test that calls the
rebuilt wrapper: test_aot_compile_rebuilt_wrapper_keeps_its_own_module_scope
builds a decorator module with its own SCALE, wraps a test-module function,
escapes the wrapper from the compiled function and checks the reloaded wrapper
still reads the decorator module's value. The __module__ is None case from the
review is cured by the same change (the scope is read off __globals__).

Q: The _aot_wraps_* helpers sit between @torch._dynamo.config.patch( "enable_aot_compile", True) and class TestAOTCompile, so the decorator applies
to the helper, not the class.

A: Fixed: the helpers live above the decorator stack, and the wraps test moved
below path()/setUp() with the other tests.

Q: serialize() rebuilds e.args as (prefix + guidance,) + e.args[1:], which
garbles a multi-argument exception's rendering.

A: Fixed: str(e) is computed once and e.args becomes the single guidance
string.

Q: Dead local SerializedCode imports in serialize()/deserialize(); an
in-body import threading in a test.

A: Removed.

Q: _dumps_cleanly prunes silently; there is no way to see what was dropped.

A: log.debug now records each pruned value (unpicklable, or an unmarked
nn.Module reached by the probe) under torch._dynamo.aot_compile.

Q: The wrapper's broad except Exception in the dispatch loop should narrow to
the pickling errors it means.

A: Kept: the exceptions a reducer raises are user-code exceptions (a
__getstate__ that asserts, a property that raises), and the point is that any
of them makes the value unpicklable for our purposes. The type of the original
exception is preserved on the real dump path (serialize() re-raises the same
instance with guidance appended), which is what callers doing except TypeError
rely on.

Q: _dumps_cleanly fully serializes each candidate, which is wasteful for
trivial values.

A: A None/str/int/bytes/bool/float value (exact types) now
short-circuits to picklable without a probe; anything else still needs the real
dump because its reducers can run user code.

Q: The BC break (a nested function's unpicklable keyword default now fails the
save instead of being dropped) could be made opt-in through a
save_compiled_function kwarg.

A: Not done: the dropped default was a silent wrong-result at call time, so the
old behaviour is not something a flag should preserve; the guidance in the error
names the value and the external_data escape hatch.

Q: The deserialize-ordering gap (a same-version artifact referencing a removed
reducer fails with a bare pickle AttributeError because deserialize unpickles
before check_compatibility) should be a tracked issue, not an FAQ answer.

A: Filed as #196521.

Q: _ProbeState.leaned is never reset when the probe tree ends, so it stays
True for the rest of serialize().

A: Fixed: reset alongside the park clear when the outermost probe returns. It
was inert -- the cache/park decision reads the local leaned, which comes from
state.leaned being reset to False before every probe.dump, and a probe run
after a leaned tree still cached its False as final -- but the field now matches
its docstring.

Q: On 3.14, _read_raw_annotations(resolve=True) permanently evaluates and
caches a nested function's lazy annotations at save; the guard side takes
FORWARDREF to avoid that.

A: The premise is off: on 3.14 Format.FORWARDREF also evaluates __annotate__
and caches into __annotations__ whenever the names resolve; it differs only by
returning proxies instead of raising when a name does not. Verified on 3.14.7: a
FORWARDREF read of def g(x: G) with G=1 returned {'x': 1}, a later VALUE
read after G=2 still returned {'x': 1}, and an annotation side effect fired
exactly once across both reads. inspect.signature (default format VALUE) does
the same, and aot_compile already calls it on the top-level function. So
"annotations frozen at first read" is CPython's PEP 649 contract for any
annotation consumer, not something this save introduces.

Q: The probe rebuilds id_map per candidate (O(|external_data|) per probe) and
discards a _ProbeState each time.

A: Measured: the constructor costs 1.5us with no external data, 2.1us at 8
entries, 68us at 1000, against roughly 100us for one nested-function probe dump;
external_data is a user-supplied dict of a handful of named tensors/modules.
Sharing id_map would mean bypassing __init__ for a change below measurement
noise, so the two-line construction stays.

Q: RecursionError escapes serialize() without the external_data guidance.

A: Fixed: RecursionError joins the except tuple. Reproduced with a 10000-deep
list kwdefault on a closure-carried helper: the message had no guidance, while
the same value in __dict__ was pruned as designed. The guidance is right for
it too, since the deep value is one the user can hand over as external data.

Q: The declared BC break (a nested function's unpicklable keyword default now
fails the save) is only exercised at the pickler level.

A: Added test_save_fails_loudly_on_a_helpers_unpicklable_kwdefault, which drives
save_compiled_function and asserts the original "cannot pickle" text plus the
kwdefault/external_data guidance. The helper is a test-method local on purpose:
a module-global helper is loaded from f_globals at run time and never enters
the artifact, so that shape would not exercise the reduce path.

Q: Comment volume in the new probe methods; release-notes label.

A: Three redundant comments trimmed (the inflight field restating its name, the
"one memo" half that duplicated the _ProbeState docstring, and the "also
leaned" line that restated the assignment below it). The PR already carries
release notes: dynamo.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit ed252fe 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.

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 9, 2026
This was referenced Sep 9, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@bobrenjc93
bobrenjc93 marked this pull request as draft September 9, 2026 15:25
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

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


Reviewed: the shared-base refactor is the right direction, but the e.args[1:] retention in serialize() makes the new guidance render as a tuple repr for multi-arg exceptions, the four new pickler tests landed in the wrong test class, and every prune in _dumps_cleanly is silent despite the module already having a logger.

Full review

PR Review: #196454

Summary

Repoints AOTCompilePickler at the shared FunctionPicklerBase and adds AOT-only pruning so an unpicklable nested-function attribute, annotation, type param, or __doc__ is dropped rather than aborting the dump. The probe state machine holds up under adversarial reading, but the new serialize() error rewriting has a message-rendering bug, the pruning is entirely unlogged, and the new tests are split across two classes with no principle.

Code Quality

  • e.args[1:] retention corrupts the message for any multi-arg exception. torch/_dynamo/aot_compile.py:345-351 does e.args = (prefix + guidance,) + e.args[1:]. BaseException.__str__ returns str(args[0]) only when len(args) == 1; otherwise it returns str(args). So for a TypeError("a", "b") raised from a user __reduce__, prefix is already the tuple repr ('a', 'b'), and because the rewrite keeps arity at 2 the result still renders as a tuple — the user sees ("('a', 'b')\nSome value reached by the artifact is not picklable...", 'b'), with the guidance buried inside a repr and the newline escaped. Nothing reads args[1:]; drop it and write e.args = (prefix + guidance,). (str(e) is also computed twice at :344 and :346.) Fix this →

  • Every prune is silent, and the module already has a logger it does not use. log is defined at :33 and never used by any of the new code. _dumps_cleanly returning False drops a __dict__ entry, an annotation, a whole __type_params__ tuple, or __doc__ with no record anywhere — and the nn.Module branch at :170-175 deliberately suppresses the "mark these as external data" diagnostic that serialize() exists to emit. A user whose helper quietly loses .mod gets an AttributeError at call time with nothing connecting it to save. The same argument applies to the inherited _unpickle_fn_from_module behaviour: package.py:207-211 swallows the import failure into {}, and the new docstring at :196-199 explicitly acknowledges that the AOT path turns that into a first-call NameError. A log.debug naming the pruned key (and the swallowed module) is a few lines and is what makes these failures diagnosable in production; the PR defers it to follow-up, but it is the observability half of a feature whose entire premise is dropping things behind the user's back.

  • The broad except (pickle.PicklingError, TypeError, AttributeError) relabels PyTorch's own reducer bugs as user data problems. Three paths inside the try at :331 can raise these without any unpicklable user value being involved: package.py:281 returns obj.__annotations__ unguarded below 3.14; package.py:328's getattr(method.__self__, name, None) swallows AttributeError but not a TypeError from a user __getattr__/property; and SerializedCode(**kwargs) (package.py:94-99, reached from reducer_override at aot_compile.py:101) raises TypeError: unexpected keyword argument on a get_code_keys()/field mismatch. Any of those now reads 'Foo' object has no attribute 'bar' followed by advice to pass external_data={...}. The FAQ argues narrowing requires message-sniffing, but there is a third option the guard side already uses (guards.py:4804-4820): raise a distinct wrapper exception (from e) whose message carries the guidance, leaving the original message and type intact on __cause__ rather than grafting advice onto a foreign exception object.

  • Comment volume. Roughly half of the lines added to aot_compile.py are comment prose: :109-119 (11 lines on one reduce call), :141-144, :151-154, :158-161, :171-174, :178-186, :189-193, :201-203, :333-343. CLAUDE.md asks to minimize comments and reserve them for non-obvious global context. Several of these restate what the following line says (:70-71 "Ids being probed right now, for cycle-breaking" above a field named inflight), and :333-343 spends five lines on CPython version archaeology that belongs in the commit message. The invariants worth keeping are: don't cache a verdict computed against an in-flight optimistic True; __kwdefaults__ is never pruned because the function must stay callable.

  • Redundant local imports in the new tests. The diff adds io, sys, and threading to the test module's top-level imports, then test_pickler_prunes_an_unpicklable_docstring (test_aot_compile.py:583-584), test_pickler_does_not_prune_an_unpicklable_kwdefault (:604-605), and test_pickler_does_not_persist_a_wrong_false_across_an_inflight_seed re-import io/threading inside the function body, while the sibling tests added in the same PR use the module-level ones. Drop the local imports.

Testing

  • The four new pickler-level tests are in the wrong class. test_pickler_prunes_an_unpicklable_docstring, test_pickler_does_not_prune_an_unpicklable_kwdefault, test_pickler_breaks_a_dict_cycle_between_nested_functions, and test_pickler_prunes_an_unmarked_module_from_a_nested_functions_dict are inserted into TestAOTCompile (test_aot_compile.py:580-673), ahead of that class's own def path() helper — while this same PR adds TestAOTCompilePickler at :2071 holding seven tests that do exactly the same thing (construct AOTCompilePickler directly, dump, reload). Consequences beyond tidiness: the four inherit @torch._dynamo.config.patch("enable_aot_compile", True) and @instantiate_parametrized_tests, neither of which is meaningful for a bare pickler test, and a reader looking for the prune coverage will read TestAOTCompilePickler, find no __doc__/__kwdefaults__ test, and conclude the split is untested. Move all four into TestAOTCompilePickler. Fix this →

  • The declared BC break is not exercised on the API that breaks. The BC note is about save_compiled_function, but test_pickler_does_not_prune_an_unpicklable_kwdefault calls AOTCompilePickler({}, buf).dump(fn) directly, so it never reaches serialize()'s new try/except and would keep passing if that block swallowed the error or if the guidance rewrite mangled the message. The two test_save_guidance_* tests do go through save_compiled_function, but for a closure cell and a __defaults__ entry — not a kwdefault. Add a save_compiled_function case with an unpicklable __kwdefaults__ on a helper, asserting both "cannot pickle" and the appended guidance survive; that is also the test that would have caught the args[1:] rendering bug.

Performance

  • The probe fully serializes each candidate into a throwaway buffer, and rebuilds id_map per probe. _dumps_cleanly constructs type(self)(self.external_data, io.BytesIO()) at :157 on every cache miss, and AOTCompilePickler.__init__ rebuilds id_map from external_data each time — O(|external_data|) per probed value on top of the dump itself. The nn.Module case is cheap (persistent_id short-circuits), but a plain torch.Tensor or a large container in a nested function's __dict__ is serialized in full twice, doubling peak memory and time on the save path. Cheap mitigations that do not weaken the probe: skip the probe entirely for values that are trivially picklable (None, str, int, bytes — __doc__ at :134 is a str or None in the overwhelming majority of cases and currently pays a full pickler construction), and hoist id_map so probes share the parent's mapping instead of recomputing it.

Backward Compatibility

  • Make sure this carries release notes: dynamo. A nested function with an unpicklable keyword default now fails save_compiled_function where it previously saved with the default silently dropped. The direction is right, but it is a user-visible behaviour change in a public API and needs a release-notes label rather than topic: not user facing.

  • File the deserialize ordering gap rather than only answering it in the FAQ. Removing _unpickle_cell/_unpickle_nested_function and renaming _unpickle_module means a same-version artifact from an earlier build fails with a bare pickle AttributeError, because deserialize (:369-372) unpickles before CompileArtifacts.__post_init__ runs check_compatibility. Agreed that reordering belongs in a separate change — but it should exist as a tracked issue referenced from the description, not just as an FAQ answer that disappears when the PR merges.

Recommendation

Request Changes

The e.args[1:] bug is a straight defect in the new error path, the test-class split needs fixing before it calcifies, and the BC break needs a test through save_compiled_function plus a release-notes label. The probe state machine itself (the in-flight lean, the don't-cache-a-leaned-False rule, the shared id cache) I read adversarially and could not break — a True recorded while leaning is validated by the enclosing probe having actually dumped the leaned-on value, so the asymmetry is correct.

· branch `gh/bobrenjc93/1133/head`

[ghstack-poisoned]
[ghstack-poisoned]
Comment thread torch/_dynamo/aot_compile.py Resolved
Comment thread torch/_dynamo/aot_compile.py Resolved
Comment thread torch/_dynamo/aot_compile.py Resolved
Comment thread test/dynamo/test_aot_compile.py Resolved
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

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


Reviewed: the dispatch widening from "<locals>" in qualname to not _fqn_resolves(obj) turns a loud save-time PicklingError into a silently wrong __globals__ for a cross-module functools.wraps wrapper (the AOT path never sends the globals_snapshot the guard path uses), and the new module-level test helpers were inserted between @config.patch and class TestAOTCompile, detaching the decorator from the class.

Full review

PR Review: #196454

Summary

Repoints AOTCompilePickler at the shared FunctionPicklerBase, widens the by-value dispatch to not self._fqn_resolves(obj), and adds AOT-only pruning (_dumps_cleanly) so an unpicklable nested-function attribute, annotation, type param, or __doc__ is dropped instead of aborting the dump. The probe state machine holds up under adversarial reading (see the note at the end), but the dispatch widening introduces a silent-wrong-scope hazard the tests do not reach, and a test-file edit detached a class decorator.

Code Quality

  • The widened dispatch gives a cross-module functools.wraps wrapper the wrong __globals__, replacing a loud save failure with silent wrong behaviour at call time. aot_compile.py:109 routes every fqn-mismatched function to _reduce_function with no globals_snapshot, so the load path is always _unpickle_fn_from_module (package.py:200-212), which reimports fn.__module__ and uses that dict as the scope. But functools.wraps copies __module__ from the wrapped function — so for a wrapper defined in module A around a function from module B, the wrapper's __module__ is "B", and at load its globals become B.__dict__ while its code was compiled against A:

    # a.py                                  # b.py
    HELPER = ...                            def base(x): return x
    def deco(f):                            helper = a.deco(base)   # __module__ == "b"
        @functools.wraps(f)
        def wrapper(x): return HELPER(f(x))  # HELPER looked up in b at load
        return wrapper

    A reference to an A-only global raises a bare NameError on first call; worse, a same-named global in B binds silently to the wrong object. Under the old "<locals>" in __qualname__ condition this shape returned NotImplemented and pickle's save_global raised PicklingError: it's not the same object as ... at save time. Loud save failure → silent wrong-scope runtime is the wrong direction, and this is exactly the shape the PR description advertises as the motivation for the widening. The guard side avoids it by sending a snapshot (guards.py:4435-4437, 4497); the AOT side has no equivalent. The clean fix is to stop conflating "the module whose dict is the function's scope" with "the module the function advertises": pass fn.__globals__.get("__name__") as the import target in _reduce_function's args and keep fn.__module__ only for the fn.__module__ = assignment in _build_function (package.py:173-181), which already treats them as separable. Fix this →

  • e.args[1:] garbles the guidance for any multi-arg exception. aot_compile.py:354-361 does e.args = (prefix + guidance,) + e.args[1:]. BaseException.__str__ returns str(args[0]) only when len(args) == 1; otherwise it returns str(args) — the tuple repr. So retaining args[1:] keeps arity at 2 for a TypeError("a", "b") and the user sees ("('a', 'b')\nSome value reached by the artifact is not picklable...", 'b'), with the guidance escaped inside a repr and 'b' duplicated. Nothing in torch/_dynamo/ reads args[1:] off a pickling exception, so it is not load-bearing. Every raise on pickle's own dump path is single-arg (copyreg.py:70,77; all PicklingError sites in pickle.py; the C accelerator's AttributeError), so the multi-arg case arrives only from a user __reduce__ — which is precisely the scenario the comment at :345-347 invokes to justify mutating rather than reconstructing. Drop the + e.args[1:]. str(e) is also computed twice at :354.

  • A function whose __module__ is None now hard-fails at call instead of pickling by reference. _fqn_resolves returns False for a non-str __module__ (package.py:260), but pickle's whichmodule falls back to scanning sys.modules and can resolve such a function by reference. It now takes _unpickle_fn_from_module, which requires a non-empty str and so yields f_globals = {} (package.py:205-211) — a guaranteed NameError for any global the function reads. Narrow shape, flagging at moderate confidence on reachability.

  • Every prune is silent, and the module's log (:33) is still unused by any of the new code. _dumps_cleanly returning False drops a __dict__ entry, an annotation, the whole __type_params__ tuple, or __doc__ with no record; the nn.Module branch (:174-178) deliberately suppresses the "mark these as external data" diagnostic. A user whose helper quietly loses .mod gets an AttributeError at call time with nothing tying it back to save. Same for the inherited _unpickle_fn_from_module, which swallows the import failure into {} while the new docstring at :196-199 acknowledges the AOT path turns that into a first-call NameError. A log.debug naming the pruned key and the swallowed module is a handful of lines and is the observability half of a feature whose premise is dropping things behind the user's back — it should not be follow-up.

  • The broad except (pickle.PicklingError, TypeError, AttributeError) still relabels PyTorch's own reducer bugs as user data problems. SerializedCode(**kwargs) raising TypeError: unexpected keyword argument on a get_code_keys() mismatch (package.py:94-99, reached from aot_compile.py:102), or package.py:290 returning obj.__annotations__ unguarded below 3.14, both surface as advice to pass external_data={...}. The FAQ argues narrowing requires message-sniffing, but there is a third option: raise a distinct wrapper exception from e carrying the guidance, leaving the original type and message intact on __cause__.

  • Comment volume. Roughly half the lines added to aot_compile.py are prose: :110-120, :130-134, :142-145, :154-157, :161-164, :174-177, :181-189, :199-203, :211-213, :343-353. CLAUDE.md asks to minimize comments and reserve them for non-obvious global context. :70 ("Ids being probed right now, for cycle-breaking") restates the field name below it, and :348-353 spends six lines on CPython accelerator archaeology that belongs in the commit message. The invariants worth keeping: don't cache a verdict computed against an in-flight optimistic True; __kwdefaults__ is never pruned because the function must stay callable.

Testing

  • The new module-level helpers detached @config.patch from TestAOTCompile. On base, test_aot_compile.py:574-576 read @torch._dynamo.config.patch("enable_aot_compile", True) / @instantiate_parametrized_tests / class TestAOTCompile. The PR inserted _aot_wraps_deco/_aot_wraps_base/_aot_wraps_helper between them, so the decorator now sits on the plain function at :578 and the class at :596 has none. ConfigModule.patch special-cases unittest.TestCase subclasses (torch/utils/_config_module.py:1025-1051, entering in setUpClass); on a plain function it falls through to contextlib.ContextDecorator and just patches config around that one import-time call — silently useless. Nothing fails today because the default is True (config.py:927) and nothing in the repo sets it False, so this is a lost guard rather than a live break — but ~60 tests in that class would fail at eval_frame.py:573/591/608 if the default ever flips or a co-resident suite disables it. Move the decorator back above @instantiate_parametrized_tests and drop it from _aot_wraps_deco. Fix this →

  • test_aot_compile_rebuilds_a_wraps_wrapper_of_a_module_level_function cannot catch the globals bug it appears to cover. _aot_wraps_deco and _aot_wraps_base live in the same module (:578, :586), so the copied __module__ happens to be correct and the wrapper body reads only a closure cell, never a module global. Add a case where the decorator and the wrapped function are in different modules and the wrapper body reads a global from the decorator's own module — that is the shape the widening actually changed. The test is also inserted at :597, ahead of the class's own def path(self) helper; move it below.

  • The declared BC break is still not exercised on the API that breaks. The BC note is about save_compiled_function, but test_pickler_does_not_prune_an_unpicklable_kwdefault (:2035) calls AOTCompilePickler({}, buf).dump(fn) directly, so it never reaches serialize()'s new try/except and would keep passing if that block swallowed the error or mangled the message. The two test_save_guidance_* tests do go through save_compiled_function, but for a closure cell and a __defaults__ entry — not a kwdefault. A save_compiled_function case with an unpicklable __kwdefaults__, asserting both "cannot pickle" and the appended guidance survive, is also the test that would have caught the args[1:] rendering bug.

Performance

  • The probe fully serializes each candidate into a throwaway buffer and rebuilds id_map per probe. _dumps_cleanly constructs type(self)(self.external_data, io.BytesIO()) at :160 on every cache miss, and AOTCompilePickler.__init__ rebuilds id_map from external_data each time — O(|external_data|) per probed value on top of the dump itself. A tensor or large container in a nested function's __dict__ is serialized in full twice, doubling peak memory and save time. Two cheap mitigations that do not weaken the probe: short-circuit trivially picklable values (None, str, int, bytes — __doc__ at :135 is one of those in the overwhelming majority of cases and currently pays a full pickler construction per nested function), and hoist id_map so probes share the parent's mapping.

Backward Compatibility

  • This needs release notes: dynamo. A nested function with an unpicklable keyword default now fails save_compiled_function where it previously saved with the default silently dropped. The direction is right, but it is a user-visible behaviour change in a public API and should not ship under topic: not user facing.

  • File the deserialize ordering gap rather than only answering it in the FAQ. Removing _unpickle_cell/_unpickle_nested_function and renaming _unpickle_module means a same-version artifact from an earlier build fails with a bare pickle AttributeError, because deserialize (:379-382) unpickles before CompileArtifacts.__post_init__ runs check_compatibility. Agreed the reordering belongs in a separate change — but it should exist as a tracked issue referenced from the description, not as an FAQ answer that disappears at merge.

Recommendation

Request Changes

The globals-scope hazard is the blocker: the widening the PR is named for makes the AOT path silently rebuild a cross-module wraps wrapper against the wrong module dict, where it previously failed at save. The detached @config.patch and the args[1:] rendering bug are both small mechanical fixes. The probe state machine itself I read adversarially and could not break — a True recorded while leaning is validated because the enclosing probe.dump is a fresh pickler with a fresh memo and so re-serializes the leaned-on value in full; persistent_id's two short-circuits (id_map, nn.Module → probe.errors → False) are consistent between probe and real dump; and parked Falsees are unreachable from the real dump given the state.inflight gate at :149 plus the clear at :194-195. Not merging probe.errors upward is also fine — it over-prunes rather than under-prunes.

· branch `gh/bobrenjc93/1133/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 27m 42s —— View job


Reviewed round-39: every blocker from the previous rounds is fixed (e.args is now single-arg, the @config.patch is reattached to TestAOTCompile, the four pickler tests moved into TestAOTCompilePickler, _ProbeState replaced the three loose attributes, prunes are logged, and the cross-module scope fix is covered by a test that actually calls the rebuilt wrapper) — what's left is minor, plus one undocumented save-time side effect on 3.14.

Full review

PR Review: #196454

Summary

AOTCompilePickler now subclasses FunctionPicklerBase, dispatches on not self._fqn_resolves(obj), and prunes unpicklable nested-function __dict__ entries / annotations / __type_params__ / __doc__ through _dumps_cleanly, carrying __kwdefaults__ unpruned. I re-read the probe state machine adversarially against the round-39 changes and could not break it; the remaining items are nits and one behavioural note.

Verification of the previous rounds' findings

  • e.args rewrite (aot_compile.py:344-360): now str(e) once into message, and e.args = (prefix + guidance,) — single-arity, so BaseException.__str__ returns the guidance plainly instead of a tuple repr. Fixed.
  • @torch._dynamo.config.patch("enable_aot_compile", True) sits at test_aot_compile.py:595, directly above @instantiate_parametrized_tests / class TestAOTCompile:597, with the _aot_wraps_* helpers above it at :578-592. Fixed.
  • The four direct-pickler tests are in TestAOTCompilePickler (:2055+), and no test re-imports io/threading/sys in-body. Fixed.
  • _ProbeState (aot_compile.py:63-75) replaces _dumps_cleanly_cache/_inflight/the list[bool] box; one probe._probe_state = state assignment shares it. Fixed.
  • log.debug on both prune reasons (:174, :183). Fixed.
  • Trivial-value short-circuit (:146) means a str/None __doc__ no longer builds a probe pickler at all — the dominant case. Fixed.
  • Cross-module scope: _reduce_function sends fn.__globals__.get("__name__") as scope separately from fn.__module__ (package.py:356-359), and test_aot_compile_rebuilt_wrapper_keeps_its_own_module_scope (:633) builds a decorator module with its own SCALE, escapes the wrapper, and asserts the reloaded wrapper reads 100. This is the test that would have caught the silent wrong-global bind. Fixed and covered.
  • Dead SerializedCode/importlib locals removed; importlib no longer appears in aot_compile.py.
  • The probe state machine: I re-traced the test_pickler_does_not_persist_a_wrong_false_across_an_inflight_seed ordering both ways (top.f first and top.g first) and the parked/cached split is sound in both. The invariant "the real dump never consults parked" also holds: the real pickler's reducer_override is only ever entered with state.inflight empty (a probe's dump runs synchronously inside _dumps_cleanly, so the real pickler cannot be re-entered mid-probe), and parked is cleared at :199-200 before the outermost call returns.

Code Quality

  • _ProbeState.leaned is never reset when the probe tree ends, so it stays True for the rest of the serialize(). aot_compile.py:188 sets state.leaned = leaned_before or leaned; at the outermost call leaned_before is the residue from the previous outermost call, so once any probe leans, state.leaned is permanently True. It happens to be inert — the caching decision at :195 reads the local leaned, and state.leaned is set to False at :170 before every probe.dump, so no sibling or later verdict is affected — but a reader has to prove that to trust the code, and the field now contradicts its own docstring ("whether a probe short-circuited"). Reset it with the park: if not state.inflight: state.parked.clear(); state.leaned = False. Fix this →

  • On 3.14, saving now permanently materializes a nested function's lazy annotations. _pickleable_annotations (:203-213) calls _read_raw_annotations(obj, resolve=True), which on 3.14+ goes through annotationlib.get_annotations(obj, format=VALUE) — and Format.VALUE reads obj.__annotations__, which under PEP 649 evaluates __annotate__ and caches the result into the function's __annotations__ slot. The PR's own FAQ relies on exactly that caching for id-stability, so this is known — but it is an observable mutation of the user's live function performed by a save, and the guard side deliberately takes FORWARDREF to avoid it. Two consequences worth a line of comment at the call site: an annotation whose referenced global changes after the save is now frozen at the save-time value on the original object, and any side effect in an annotation expression fires at save. Neither is a correctness problem for the artifact; it is just not written down anywhere.

  • The probe rebuilds id_map per candidate. _dumps_cleanly:162 does type(self)(self.external_data, io.BytesIO()), and __init__ (:82-84) rebuilds {id(v): k for ...} from scratch — O(|external_data|) per probed value, plus a _ProbeState() that is immediately discarded at :167. Both are cheap next to the dump itself, but sharing the parent's id_map (and skipping the throwaway _ProbeState) is a two-line change on a path that already runs once per __dict__ key per nested function.

  • RecursionError escapes serialize() without the guidance. except (pickle.PicklingError, TypeError, AttributeError) at :342 covers the probe-free payload's usual failures, but a deeply nested value in the unpruned payload (a closure cell, __kwdefaults__, the top-level signature) raises RecursionError straight out of save_compiled_function with no pointer at external_data. _dumps_cleanly treats a recursion overflow as unpicklable by design; the real dump has no equivalent. Minor and arguably out of scope, but it is the one failure mode the new guidance does not reach.

  • The broad catch still relabels PyTorch's own reducer bugs. Unchanged from the last round and the FAQ answer stands on the message-preservation point — the original text survives as the prefix. Noting only that SerializedCode(**kwargs) raising TypeError: unexpected keyword argument on a get_code_keys() mismatch would come out advising external_data={...}; a wrapper exception from e would keep the original type on __cause__. Not blocking.

  • Comment volume in the new methods. :110-120 (11 lines), :130-134, :142-145, :156-159, :163-166, :177-180, :187-194, :204-208, :216-218 — roughly 45 comment lines against ~80 lines of new code, against CLAUDE.md's "minimize comments." The invariants that earn their space are the two at :189-194 (don't cache a verdict computed against an in-flight optimistic True) and :133-134 (__kwdefaults__ is never pruned because the function must stay callable); several others restate the line below them (:70 "Ids being probed right now" above a field named inflight). Cosmetic; flagging once and not again.

  • Positive: replacing the isinstance(obj, type((lambda x: lambda: x)(0).__closure__[0])) incantation with isinstance(obj, types.CellType) and routing through _reduce_cell also fixes the old save-time ValueError on an empty cell — test_pickler_rebuilds_a_nested_function_faithfully pins it.

Testing

  • Coverage is now proportionate to the machinery. test_pickler_breaks_a_dict_cycle_between_nested_functions (:2097) hits the in-flight short-circuit plus a sibling prune, test_pickler_does_not_persist_a_wrong_false_across_an_inflight_seed (:2278) pins the regression the :189-194 comment describes, test_pickler_prunes_an_unmarked_module_from_a_nested_functions_dict (:2122) covers both halves of the nn.Module prune, and the two test_save_guidance_* tests drive serialize()'s try/except through save_compiled_function — so the guidance rewrite is no longer untested, and the args[1:] bug could not recur silently.

  • The declared BC break is still only exercised at the pickler level. test_pickler_does_not_prune_an_unpicklable_kwdefault (:2078) calls AOTCompilePickler({}, buf).dump(fn), so the __kwdefaults__-fails-loudly / __doc__-is-pruned split — the thing the BC note is about — is never asserted through save_compiled_function. Lower priority than in the previous rounds now that the guidance path has its own two tests, but a save_compiled_function case with an unpicklable kwdefault on a helper is a three-line addition to the existing pattern and pins the user-visible contract rather than an internal one.

Backward Compatibility

  • Confirm the release notes: dynamo label. A nested function with an unpicklable keyword default now fails save_compiled_function where it previously saved with the default silently dropped — a user-visible change in a public API. (The rest of the widened reduce is strictly better: before this PR the nested-function reduce carried only (code, module, qualname, argdefs, closure), so __dict__, __doc__, annotations and __type_params__ were dropped unconditionally; __kwdefaults__ is the only value that goes from silently-dropped to loudly-failing.)
  • The deserialize-ordering gap is filed as [dynamo][aot_compile] deserialize() unpickles the artifact before check_compatibility runs #196521 and referenced from the description. Resolved as far as this PR is concerned.

Recommendation

Approve (nits only)

The blockers from rounds 36-38 are all addressed and, importantly, the two that were silent-wrongness (args[1:] rendering, cross-module __globals__) now have tests that would catch a regression. Remaining: reset _ProbeState.leaned with the park clear, note the 3.14 annotation-materialization side effect at the call site, and confirm the release-notes label. The __kwdefaults__-through-save_compiled_function test and the id_map/RecursionError items are optional follow-ups.

· branch `gh/bobrenjc93/1133/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 12m 7s —— View job


Reviewed round-40: the two behavioural items from the last round are fixed (_ProbeState.leaned now resets with the park; RecursionError joined the guidance catch) — what remains are three test-quality gaps: the new BC-break test's kwdefault/external_data assertions are tautologies satisfied by the fixed guidance string, the new RecursionError branch has no test, and the 3.14 annotation-materialization side effect is still undocumented at the call site.

Full review

PR Review: #196454

Summary

AOTCompilePickler now subclasses FunctionPicklerBase, dispatches on not self._fqn_resolves(obj), and prunes unpicklable nested-function __dict__ entries / annotations / __type_params__ / __doc__ through _dumps_cleanly while carrying __kwdefaults__ unpruned. I re-diffed round-39→round-40 (bf85833..ed252fe) and re-read the probe state machine adversarially; no new correctness defects. The findings below are all in the test and documentation layer.

Verification of the round-39 findings

  • _ProbeState.leaned reset: aot_compile.py:196-198 now clears parked and sets state.leaned = False when the outermost probe returns. Fixed.
  • RecursionError guidance: added to the except tuple at :342 with the comment at :351-354. Fixed (but untested — see below).
  • The two comments the last round flagged as restating the line below them (# Ids being probed right now above inflight, # A caller that consulted this value also leaned...) are gone, and the _ProbeState-docstring-duplicating half of the probe._probe_state comment is trimmed. Fixed.
  • _instance_dict's docstring (package.py:115-117) is corrected to say object.__getattribute__ rather than "the plain slot", and to note the type-level __dict__ property caveat. Fixed.
  • id_map-per-probe: not changed; the FAQ's measurement (1.5-68us construction vs ~100us per probe dump) is the right call, closing that item.
  • Probe state machine, re-traced against round-40: the state.leaned = False addition at :198 is reachable only when inflight is empty, i.e. from the outermost _dumps_cleanly frame, and the cache/park decision at :192 reads the local leaned captured at :184 — so the reset cannot change any verdict, only make the field match its docstring. The park is still unreachable from the real dump (the state.inflight gate at :150 plus the clear at :197).

Testing

  • The new BC-break test's two distinguishing assertions are tautologies. test_save_fails_loudly_on_a_helpers_unpicklable_kwdefault (test/dynamo/test_aot_compile.py:823-846) asserts assertIn("kwdefault", msg) and assertIn("external_data", msg), but the guidance literal serialize() unconditionally appends (aot_compile.py:357-363) contains both substrings verbatim — "a closure cell, a default/kwdefault, or the top-level function's own signature annotations" and "`external_data={'key': ...}`". Those two assertions therefore pass for any unpicklable value anywhere in the artifact and carry no signal about __kwdefaults__; only assertIn("cannot pickle", msg) is load-bearing, and the two sibling test_save_guidance_* tests already cover that. As written the test would keep passing if the reduce path stopped carrying __kwdefaults__ and the failure came from a closure cell instead — i.e. it does not pin the BC break it is named for. Assert the shape rather than the boilerplate: after the raise, dump the same helper directly and assert _reduce_function was called with the kwdefault present, or (simpler) build the only unpicklable value in the artifact as the kwdefault and additionally assert "_thread.lock" in msg together with a positive control that the same helper without the kwdefault saves cleanly. Fix this →

  • The RecursionError branch added this round has no test. aot_compile.py:342 newly catches RecursionError, and the FAQ says the case was reproduced by hand with a 10000-deep list kwdefault on a closure-carried helper. Nothing in the suite exercises it: test/dynamo/test_aot_compile.py has zero matches for RecursionError, setrecursionlimit, or any deep-but-finite value construction. This is one of the four exception types the guidance path handles and the only one whose "does the guidance actually reach the user" question is unanswered by a test — the same gap that let the e.args[1:] rendering bug survive two rounds. The repro from the FAQ is a three-line test in the existing pattern. Note that if it is added, the assertIn("external_data", msg) there has the same tautology problem as above, so it should assert on RecursionError being the raised type plus the guidance, not on the substring alone.

Code Quality

  • The 3.14 annotation-materialization side effect is still undocumented at the call site. _pickleable_annotations (aot_compile.py:201-211) calls _read_raw_annotations(obj, resolve=True), which on 3.14+ goes through annotationlib.get_annotations(obj, format=VALUE) (package.py:280-286). Under PEP 649 that evaluates __annotate__ and caches into the function's __annotations__ slot — the PR's own FAQ depends on exactly that caching for the id-stability argument behind _dumps_cleanly's id() memo. So a save permanently freezes a user's live nested function's annotations at their save-time values and fires any side effect in an annotation expression. The FAQ correctly argues this is CPython's contract for any annotation consumer (inspect.signature does it too, and aot_compile already calls that on the top-level function) — but the comment at :202-206 describes only the resolve-vs-FORWARDREF shape, not the mutation, and the comment in package.py:269-276 describes the guard side's motivation. One line at :202 noting that this materializes and caches the annotations on the original function is what stops the next reader from re-litigating it, and is also the load-bearing premise for the id()-keyed cache two methods down.

  • The broad except (pickle.PicklingError, TypeError, AttributeError, RecursionError) still relabels PyTorch's own reducer bugs. Unchanged, and the FAQ's message-preservation argument stands (the original text survives as the prefix). Noting once more that SerializedCode(**kwargs) raising TypeError: unexpected keyword argument on a get_code_keys() mismatch (package.py:94-99, reached from aot_compile.py:101) comes out advising external_data={...}; a wrapper exception from e would keep the original type on __cause__. Not blocking, and I will not raise it again.

Backward Compatibility

  • Confirm the release notes: dynamo label is actually applied. The description says the PR carries it; I cannot read labels from the diff. A nested function with an unpicklable keyword default now fails save_compiled_function where it previously saved with the default silently dropped — that must not ship under topic: not user facing.

Recommendation

Approve (test-quality follow-ups)

The implementation is in good shape and every behavioural finding from rounds 36-39 is now fixed with a test that would catch a regression. The remaining items are all about test signal rather than code correctness: the BC-break test's kwdefault/external_data assertions are satisfied by the boilerplate and should assert the discriminating shape, the newly-added RecursionError branch needs the FAQ's own repro as a test, and the 3.14 annotation mutation deserves one line at _pickleable_annotations. None of those blocks a merge, but the first two are the kind of gap that lets the next round's regression through.

· branch `gh/bobrenjc93/1133/head`

bobrenjc93 added a commit that referenced this pull request Sep 10, 2026
A pure move with no behavior change. Within this stack the new base class has
exactly ONE subclass, `GuardsStatePickler`; the second user is
`AOTCompilePickler`, which #196454 (in the stack above, not yet rebased onto
this one) moves onto the base. The extraction happens here so the next five
commits have one place to add the by-value function reducers that both
picklers will share.

`GuardsStatePickler` (guard state) and `AOTCompilePickler`
(torch/_dynamo/aot_compile.py, the AOT compile artifact) both have to rebuild
objects that pickle cannot do by reference -- code objects, python modules,
bound methods -- and each carries its own copy of those reducers. This commit
moves `GuardsStatePickler`'s copies into a new `FunctionPicklerBase` in
package.py and makes `GuardsStatePickler` subclass it. Bodies are unchanged
(one parameter renamed, one return annotation tightened).

Until #196454 lands, `AOTCompilePickler` keeps its own copies of these
reducers, including the same bugs the commits here fix in the guard pickler
(an unguarded `cell_contents` read and the old nested-function rebuild).
#196454 changes its base to `FunctionPicklerBase` and deletes the duplicates;
because the closure-cell, bound-method and by-value function reducers that
#196472-#196478 add already live on the base, that move is a one-line
base-class change rather than a second relocation of the code.

The reducers are pickled by reference as `getattr(GuardsStatePickler, name)`
(pickle records the bound classmethod's owner), so an artifact records the
same reference before and after this move; they have to stay classmethods for
that reason. When `AOTCompilePickler` moves onto the base it must consciously
replace its own `_unpickle_module` (an `importlib` import) with the inherited
`_unpickle_python_module`, since `GuardsStatePickler._unpickle_module`
rebuilds an `nn.Module`.

guards.py now imports `SerializedCode` at module level (package.py does not
import guards.py, so there is no cycle) instead of inside two methods, and
drops `import pickle`, whose only use was the base class.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
```

Authored with an AI assistant.

FAQ

Q: The docstring says the base exists "so that a fix cannot be missed in one
pickler", but there is exactly one subclass at this commit.

A: The same paragraph states that `GuardsStatePickler` is the one subclass
today; the clause is the reason `AOTCompilePickler` is moved onto the base
separately, not a claim that it already has been.

Q: The base shares the reducer bodies, but both `reducer_override`s still
duplicate the `iscode`/`ismodule`/`ismethod` dispatch predicates.

A: This change is a pure move that prepares the base, and aot_compile.py is
deliberately untouched in this stack so the AOT move is one reviewable step.
The bound-method predicate does move into the base later in the stack
(`FunctionPicklerBase._reduce_bound_method`); the remaining predicates are
one-liners whose divergence risk lives in the reducer bodies the base now owns.

ghstack-source-id: 14e22de
Pull-Request: #196471
bobrenjc93 added a commit that referenced this pull request Sep 10, 2026
A pure move with no behavior change. Within this stack the new base class has
exactly ONE subclass, `GuardsStatePickler`; the second user is
`AOTCompilePickler`, which #196454 (in the stack above, not yet rebased onto
this one) moves onto the base. The extraction happens here so the next five
commits have one place to add the by-value function reducers that both
picklers will share.

`GuardsStatePickler` (guard state) and `AOTCompilePickler`
(torch/_dynamo/aot_compile.py, the AOT compile artifact) both have to rebuild
objects that pickle cannot do by reference -- code objects, python modules,
bound methods -- and each carries its own copy of those reducers. This commit
moves `GuardsStatePickler`'s copies into a new `FunctionPicklerBase` in
package.py and makes `GuardsStatePickler` subclass it. Bodies are unchanged
(one parameter renamed, one return annotation tightened).

Until #196454 lands, `AOTCompilePickler` keeps its own copies of these
reducers, including the same bugs the commits here fix in the guard pickler
(an unguarded `cell_contents` read and the old nested-function rebuild).
#196454 changes its base to `FunctionPicklerBase` and deletes the duplicates;
because the closure-cell, bound-method and by-value function reducers that
#196472-#196478 add already live on the base, that move is a one-line
base-class change rather than a second relocation of the code.

The reducers are pickled by reference as `getattr(GuardsStatePickler, name)`
(pickle records the bound classmethod's owner), so an artifact records the
same reference before and after this move; they have to stay classmethods for
that reason. When `AOTCompilePickler` moves onto the base it must consciously
replace its own `_unpickle_module` (an `importlib` import) with the inherited
`_unpickle_python_module`, since `GuardsStatePickler._unpickle_module`
rebuilds an `nn.Module`.

guards.py now imports `SerializedCode` at module level (package.py does not
import guards.py, so there is no cycle) instead of inside two methods, and
drops `import pickle`, whose only use was the base class.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
```

Authored with an AI assistant.

FAQ

Q: The docstring says the base exists "so that a fix cannot be missed in one
pickler", but there is exactly one subclass at this commit.

A: The same paragraph states that `GuardsStatePickler` is the one subclass
today; the clause is the reason `AOTCompilePickler` is moved onto the base
separately, not a claim that it already has been.

Q: The base shares the reducer bodies, but both `reducer_override`s still
duplicate the `iscode`/`ismodule`/`ismethod` dispatch predicates.

A: This change is a pure move that prepares the base, and aot_compile.py is
deliberately untouched in this stack so the AOT move is one reviewable step.
The bound-method predicate does move into the base later in the stack
(`FunctionPicklerBase._reduce_bound_method`); the remaining predicates are
one-liners whose divergence risk lives in the reducer bodies the base now owns.

ghstack-source-id: 14e22de
Pull-Request: #196471
pytorchmergebot pushed a commit that referenced this pull request Sep 11, 2026
…196472)

When Dynamo serializes guard state it pickles some functions by value (every
`<locals>` function reached through a capture, and the wrapped functions the
commits above add), and pickling a function by value pickles every cell in its
`__closure__`. The old reducer read the cell's contents up front and passed
them as a constructor argument, `_unpickle_cell(cell.cell_contents)`. Two
ordinary shapes broke on that:

    def make(captured):
        def fn(x):
            if x is None:
                return unset  # never runs
            return x + captured

        if captured is None:
            unset = 1  # never runs, so the cell for `unset` stays EMPTY

        return fn

`fn` closes over `captured` (filled) and `unset` (never assigned, so its cell
is empty). Tracing a call to `fn` installs a TENSOR_MATCH on `captured`, and
serializing that guard state pickles `fn` with its closure. Reading
`cell_contents` on the empty cell raised `ValueError: Cell is empty` out of the
pickler: a `PackageError` under strict precompile (an internal error before the
previous commit), a bypass of a perfectly serializable frame otherwise.

    def outer():
        def fact(n):
            return 1 if n <= 1 else n * fact(n - 1)
        return fact

`fact`'s one cell contains `fact` itself. Pickling `fact` pickles its cell,
whose constructor argument was `fact`, which is not memoized yet because it is
still being pickled, so pickle started over: `RecursionError`, reported as
"exceeded the recursion limit while pickling guard state".

The fix rebuilds a cell in two steps, an empty `types.CellType()` that pickle
memoizes first and its contents assigned afterwards as pickle state. A cell
that refers back to its own function no longer recurses: the second time pickle
reaches the function it finds the CELL memoized, builds the inner copy of the
function and sets the cell's contents to it, and the outer `save_reduce` then
drops its duplicate through the recursive-object fallback because the object
is in the memo by then. A genuinely empty cell (reading
`cell_contents` raised `ValueError`) carries no state and is rebuilt empty,
and the contents are wrapped in a 1-tuple because pickle skips the state step
for a bare None, which would otherwise turn a cell holding None into an empty
one. The reducer lives on `FunctionPicklerBase` so the function-rebuilding
commits above share it; `AOTCompilePickler` keeps its own unguarded read until
#196454 moves it onto the base.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k test_empty_closure_cell_of_a_traced_local_function -k test_reduce_handles_an_empty_cell_reached_directly -k test_reduce_keeps_a_none_valued_cell -k test_reduce_preserves_a_self_referential_cell
```

On the previous commit the capture test and the direct-cell test error with
`ValueError: Cell is empty` and the self-referential one with `RecursionError`;
the capture test is the realistic trigger (a traced local function with an
empty sibling cell), the pickler-level one covers a raw cell, which no
serializable guard type can root at (CLOSURE_MATCH is unsupported). The new
`TestGuardsStatePickler` class drives the pickler directly.

Authored with an AI assistant.

FAQ

Q: Isn't the `keep_name_with_empty_cell` / `functools.wraps` / module-level
`EMPTY_CELL_WRAPPED` fixture more than this change needs? A local helper that
returns an empty cell would do.

A: At this commit only the empty cell is needed, but the fixture is shaped for
the by-value function commits above it: one pickles `EMPTY_CELL_WRAPPED`
itself as a rebuilt function with an empty sibling cell, and another renames
the wrapped function to prove the wrapper is rebuilt rather than resolved by
name. Defining it once here avoids reshaping it two commits later.

Q: The `FunctionPicklerBase` docstring claims a shared-fix invariant that
`AOTCompilePickler` violates.

A: The docstring states that `GuardsStatePickler` is the only subclass and
that `AOTCompilePickler` keeps its own copies until it is moved onto the base
separately; `prepare_f_locals` dereferences cells unconditionally there, so
that migration is a standalone change.

Pull Request resolved: #196472
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196505, #196470, #196471
@bobrenjc93 bobrenjc93 closed this Sep 11, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1133/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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant