Skip to content

[aot_compile] Resolve a loaded module's guard scope from model.forward - #196818

Closed
bobrenjc93 wants to merge 25 commits into
gh/bobrenjc93/1167/basefrom
gh/bobrenjc93/1167/head
Closed

bobrenjc93 wants to merge 25 commits into
gh/bobrenjc93/1167/basefrom
gh/bobrenjc93/1167/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

AOTCompiledModel.deserialize supplied no guard scope, so a module artifact's
global guards were evaluated against the scope rebuilt from the serialized
bytecode: the graph's import_* module aliases, GraphRuntimeEnv.used_globals
(the globals the graph lifted, plus the builtins dict its bytecode references)
and the backend id, and nothing else. That was worse than a stale read, in two
opposite ways:

# mypkg/model.py
SCALE = torch.randn(4)     # lifted into the graph as an input
MODE = "sum"               # specialized: folded into the graph as a constant, NOT lifted

class M(torch.nn.Module):
    def forward(self, x):
        y = x * SCALE
        return y.sum(1) if MODE == "sum" else y.mean(1)

# captured with a guard_filter_fn that keeps global guards; then, in a fresh process:
loaded = AOTCompiledModel.deserialize(M(), data)
loaded(x)
# guard on SCALE: compared against the serialized SCALE itself -> a guard that cannot fail
# guard on MODE:  MODE is absent from the rebuilt dict -> RuntimeError ... KeyError on G['MODE']
#                 on EVERY call: the artifact loads and then never runs

A module artifact captured with global guards kept was effectively unusable.
Resolve the live scope instead, so a module artifact dispatches on the loading
process's globals.

Where the scope comes from: model.forward

scope = convert_frame.get_traced_fn(model.forward)[0].__globals__   # vars(mypkg.model)

The scope comes from model.forward, not from model: get_traced_fn(model)
returns Module._wrapped_call_impl as soon as a hook is registered, which
would root the guards in torch/nn/modules/module.py's namespace instead of
the module definition's. model.forward is also what aot_compile_module
actually traced.

An OptimizedModule is unwrapped to the module it wraps before that
resolution, because its forward is a wrapper defined in
torch/_dynamo/eval_frame.py and would root every guard in that file's
namespace, and seed it:

def _unwrap_optimized_module(model):
    while isinstance(model, OptimizedModule):
        model = model._orig_mod
    return model

The unwrap is an isinstance(model, OptimizedModule) test rather than
getattr(model, "_orig_mod", model): _orig_mod is a legal submodule name, so
the duck-typed read hands deserialize a CHILD module whenever a plain
nn.Module happens to register one, and the parent's graph then runs against
the child's parameters and returns a wrong answer with nothing raising. It
loops rather than testing once, because wrappers nest:
OptimizedModule.__reduce__ returns (cls, (orig_mod, ctx)), so a
copy.deepcopy or pickle round-trip rebuilds the wrapper without the
_torchdynamo_orig_callable/_torchdynamo_wrapper_id that innermost_fn
follows, and torch.compile of that copy wraps it again instead of collapsing
onto the module (torch.compile(torch.compile(mod)) itself does collapse). One
unwrap then stops at the inner wrapper, whose forward is again eval_frame's
compile_wrapper, and the guards would be rooted in, and seeded into,
torch._dynamo.eval_frame's namespace after all; _load_aot_compiled_module's
self._orig_mod is that inner wrapper. Only a caller of this private
classmethod reaches either case (_load_aot_compiled_module already hands over
_orig_mod), so this is a robustness fix rather than a shipping bug. The next
commit calls the same helper at the top of aot_compile_module.

Three shapes of forward are refused, and the load falls back

m.forward = functools.partial(m.forward, flag=True)    # no __globals__ to use
object.__setattr__(m, "forward", OtherModule())         # get_traced_fn would rewrite to THAT module's forward
torch.nn.Linear(4, 4)                                   # forward is a function torch itself defines

An nn.Module as forward. get_traced_fn rewrites an nn.Module
argument to THAT module's forward, rooting the guards in its namespace, and
seeding it, with nothing raising. Plain assignment cannot produce one
(nn.Module.__setattr__ files an nn.Module value under _modules, and
forward is a class attribute so normal lookup keeps winning), but
object.__setattr__ can. Refusing takes the fallback below and warns, and it
also keeps get_traced_fn's Module branch, whose hook reads can raise
AttributeError on an uninitialized module, off this path entirely.

A forward that is neither a plain function nor a bound method (a
functools.partial, say) has no __globals__. The report names it by type
and, when it carries one, by __qualname__; a bare functools.partial has
none while a functools.wraps'd one does, and a test pins each shape.

A forward that resolves to a function torch itself defines.
nn.Module.forward on a module that never overrode it is the bound
_forward_unimplemented, a _LazyGraphModule before real_recompile binds
_lazy_forward, and mod.forward = torch.compile(mod.forward) is eval_frame's
wrapper: each resolves with nothing raising to a torch module's namespace,
which the seeding would then write __import_* aliases into permanently, with
no CleanupHook. The test is the namespace, scope is vars(sys.modules[scope['__name__']]) with a torch root, not the function's
__module__, which functools.wraps copies and which a GraphModule's exec'd
forward lacks; a GraphModule's private per-instance codegen globals is no
module's namespace and resolves, and refusing it would change nothing
observable, since fx emits only module aliases into it. The rule also covers
torch's own modules, torch.compile(torch.nn.Linear(...)) included: such a
forward reads only torch globals, so the fallback there is silent and the call
answers.

A functools.wraps'd wrapper the caller applied over forward is NOT seen
through: it resolves to the wrapper's own function and the decorator's module,
which is the scope a capture of the decorated forward records too (Dynamo
traces the decorator as the root frame), so a load agrees with that capture and
reads the decorator's guarded globals live, while an artifact captured from the
undecorated forward fails its global guards there loudly, KeyError on G['NAME'] with the SUPPLIED hint naming that module. Refusing on __wrapped__
was rejected: the shape a capture can save (a class-body decorator; the
instance-rebound one cannot, its closure holding the instance) would fall back
to the rebuilt scope, where the decorator's guarded global is compared against
the serialized value and a rebind is served silently. The docstring says so.

The fallback. A refused load still loads, against the artifact-rebuilt
scope, and warns rather than refusing, because an artifact with no global guard
runs there perfectly well. The warning and the docstring say what it costs, in
both directions: a guard on a global the graph lifted is compared against the
value serialized with it and cannot fail, and one on a global that scope does
not carry can never be satisfied, so the call reports no match. Falling back is
a property of the model, not of a ModelInput, so a compiled result only
records whether it holds a global guard and deserialize emits the paragraph
once for the whole artifact. Each refusal's reason is a full sentence ending in
; <imperative advice>, which the RECONSTRUCTED hint splices after rebuilt because and the fallback warning appends whole:

... KeyError on G['MODE'] -- a guarded global is missing from the scope rebuilt from the
artifact. That scope was rebuilt because get_traced_fn cannot resolve M.forward (partial) to a
Python function; make model.forward a plain function or bound method so its own globals are used
instead, or pass AOTCompiledModel.deserialize a guard_globals= scope that carries the name.

That rebuilt scope now has two producers, this fallback and a function artifact
loaded without an f_globals, and f_globals= is only the function path's
parameter, so a module load gets a scope argument of its own: the new
keyword-only guard_globals= on AOTCompiledModel.deserialize, which is the
guard scope instead of anything resolved from model.forward, on the same
terms: seeded into, and substituted from. _missing_global_hint's
rebuilt-scope branch is worded per producer: the module producer's report
splices the refusal's own reason and advice, then names a guard_globals=
scope, never f_globals=, which names nothing on a module load; the function
producer keeps the f_globals= advice. Both are asserted on the artifact
test_aot_compile_module_fallback_scope_hint_names_the_forward loads. The
SUPPLIED hint names the dict when it is a module's live namespace (, here vars(<name>)), since on a module load the caller passed none; a copy of that
namespace is not named, and _seed_guard_scope's TypeError names the same
way instead of blaming a guard_globals= the caller never passed. The next
commit pins the shape forward takes on a hooked module, where
get_traced_fn(model) returns Module._wrapped_call_impl; both halves of the
scope contract, the live read of a guarded global and the seeding writing
through to the dict that was resolved, are pinned by tests here.

Loading MUTATES the resolved namespace, and a third minted family is seeded

Because that dict is the defining module's live namespace, loading an artifact
that has a global-rooted guard writes into it: #196817's seeding inserts the
recorded __import_* aliases and __builtins_dict___N key there, never
overwriting an existing name. This commit adds the third minted family: the
___unnamed_scope_<id>_c<n> key an inlined frame whose globals belong to no
module is guarded through. It embeds id() of a dict in the tracing process,
so no live namespace can carry it; where the graph lifted a value read through
that dict, used_globals recorded the dict under the key, and a supplied scope
is handed that recording, the same object forward_callable spreads into the
bytecode's globals and the RECONSTRUCTED path hands the guard:

for name in guarded_globals:
    if name.startswith("___unnamed_scope") and name in used_globals:
        CleanupHook.disown(guard_scope, name)      # whether or not this load binds it
        if name not in guard_scope:
            guard_scope[name] = used_globals[name]

Gated, like the aliases, on the key being a name the kept guards read (the
widened set below), never replacing a binding the scope has, after a
CleanupHook.disown as for the builtins key (install_global_by_id binds
through install_global_unsafe). The disown runs whether or not this load
binds the key, because the guards it installs read that binding by reference
for as long as the artifact lives, and a compile's hook firing on its code's
collection would otherwise delete it and fail every later call with KeyError on G['___unnamed_scope_...']. Without the seeding, making the live scope the
module load's default turned a working artifact into one that fails every call
with that KeyError, a name _names_a_missing_global rightly offers no advice
for. A key used_globals lacks is a namespace the graph only specialized on,
which no scope can supply, and stays a no-match.

Serializing that recording surfaced a bug on main. get_runtime_env records
the namespace whole, and exec had inserted the LIVE builtins dict under its
__builtins__, so the artifact carried every builtin by value, plus whatever
an extension module stashes there:

ns = {}
exec(code, ns)                       # CPython binds ns["__builtins__"] = builtins.__dict__
pickle.dumps(ns)                     # every builtin by value, and on CPython < 3.12 with
                                     # pybind11 < 2.13: TypeError: cannot pickle 'PyCapsule' object

pybind11 < 2.13 on CPython < 3.12 keeps its internals in a PyCapsule under a
__pybind11_internals_v4_* key, and CI's scipy==1.10.1 (3.10/3.11 only) is
one, imported by every test process through common_utils, so serialize()
failed with that TypeError on exactly those shards and passed on 3.12. Only
the __builtins_dict___N key was filtered (_safe_builtins_dict).
serialize() now swaps that entry, in the pickled copy alone, for the guards
pickler's _live_builtins stand-in when it IS builtins.__dict__, so it loads
as the loading process's own dict:

def _picklable_unnamed_scope(scope):
    from .guards import _live_builtins
    return {**scope, "__builtins__": _live_builtins}

used_globals={name: _picklable_unnamed_scope(value)
              if name.startswith(_UNNAMED_SCOPE_PREFIX) and isinstance(value, dict) else value
              for name, value in runtime_env.used_globals.items()}

Nothing at load reads it, since the bytecode and the guards only subscript the
namespace, and the artifact loses ~6 KB.
test_aot_compile_module_unnamed_scope_builtins_dict_travels_by_reference
plants a real capsule (datetime.datetime_CAPI) in builtins.__dict__ so 3.12
reproduces what 3.10 saw.

Two questions read two different sets of names

This is the subtle part. The module path supplies a guard scope but no
f_globals, so unlike the function path (#196815), where the caller's dict is
merged into the bytecode's globals wholesale, this path has to decide which
live values the compiled BYTECODE may read. A module caller cannot inspect the
guards itself, so it gets the substitution only where a guard certifies it, and
never for a global whose guard a filter dropped. That takes two sets:

def _recorded_guard_globals(guards_state):      # WIDE: every global a kept guard READS at check time
    names = set(guards_state.output_graph.global_scope)
    if shape_code_parts is not None and shape_code_parts.python_fallback:
        for expr in shape_code_parts.python_code_parts.exprs:
            names.update(re.findall(r"\bG\['([^']*)'\]", expr))   # a Python-lambda shape guard's operands
    return names

def _guard_source_globals(output_graph):        # NARROW: the names a kept guard's own source IS
    return {g.originating_source.global_name for g in output_graph.guards
            if isinstance(g.originating_source, GlobalSource)}

Question one: does anything check a global at all? This arms the fallback
warning and the seeding, and reads the WIDE set minus the recorded builtins-dict
key and the recorded __import_* aliases. The serialized global_scope is the
serializer's own record of what the kept guards read, so it also carries a
global reached only through a shape source or a DUPLICATE_INPUT's source_b,
which no guard's originating_source names. The builtins key is written into
that scope whether or not a guard reads it, so it is not evidence of anything
and is subtracted out. The aliases are subtracted for a different reason: they
are not user globals, and a rebuilt scope carries every recorded one freshly
imported, so a guard rooted at one resolves there. That subtraction is
load-bearing rather than cosmetic: an artifact whose only global name is an
alias falls outside both halves of the warning's dichotomy (the rebuilt scope
carries it freshly imported, so the guard is satisfied and the call answers),
and warning for it would predict a no-match report for an artifact that works.
The ParentWithChildModule fixture #196817 added records exactly that one name
under keep_global_guards, and test_aot_compile_module_alias_only_globals_load_silently
asserts the load stays silent.

Answering this question from guard sources was wrong: with
enable_cpp_symbolic_shape_guards=True a mark_dynamic'd global tensor lands
in global_scope with no source naming it, so the artifact was treated as
holding no global guard and the fallback stayed silent about a guard that
cannot fail (the rebuilt scope carries that lifted global, so the load answers
with the serialized value and a rebind afterwards does not change that). On the
default config the same guard is a Python lambda, and even global_scope is
not wide enough for it: the serializer still prunes that name out before
writing it (shape_env_sources is filled from the cpp code parts alone, so
prune_variable never sees it), while since #196817 the lambda closes over the
SAME dict the C++ globals tree is rooted at and reads the name live. So the
arming unions in the lambda's own operands, the G['NAME'] subscripts in
shape_code_parts.python_code_parts.exprs, minus the recorded aliases; without
them _has_global_guards read False for exactly the artifact whose guard
cannot fail on the rebuilt scope. That union is _recorded_guard_globals, and
the seeding reads it too, whole, before the alias subtraction, which a seeding
must not apply.

A filter that drops the SHAPE_ENV guard drops its operands with it and needs
no gate of its own: GuardBuilder.SHAPE_ENV records shape_code_parts under
save_guards only, and check_guards runs its saving pass over the filtered
guards (the pre-filter pass, the one that gives the filter its entries, is
save_guards=False), so under skip_all_guards_unsafe or
keep_tensor_guards_unsafe the serialized shape_code_parts is None, the
union is global_scope alone, and a load neither warns about nor seeds for a
guard that does not exist.
test_aot_compile_module_dropped_shape_guard_seeds_no_alias pins that on the
alias fixture: no surviving ShapeEnvSource, no shape_code_parts,
_has_global_guards False, the alias unbound after the load and after the
call.

Gated on global_scope alone, _seed_guard_scope never bound an alias or
unnamed-scope key only the lambda reads, and that is reachable on the DEFAULT
filter with no opt-in:

# helper_mod.py
HELPER_ROWS = torch.randn(7, 4); torch._dynamo.mark_dynamic(HELPER_ROWS, 0)
def helper(x): return x + HELPER_ROWS.size(0)

# model.py: forward calls helper(x), so the read roots at AttrSource(import_source(helper_mod), 'HELPER_ROWS')
# lambda:  2 <= G['__import_helper_mod'].HELPER_ROWS.size()[0]
# every guard rooted through the alias is is_global and dropped -> alias absent from global_scope
loaded(x)   # parent: GuardManager check failed, verbose part "'__import_helper_mod'" -- the lambda's bare KeyError

The module load succeeded and every call then failed, the report's verbose part
being the lambda's bare KeyError text (not a KeyError on G[...] part, so
_names_a_missing_global never saw it), where the rebuilt scope, which imports
every recorded alias, answered. A ___unnamed_scope_* key reached the same way
(the tensor's own TENSOR_MATCH dropped for being global while used_globals
carries the dict) failed the same way. Both loops still leave a binding the
scope has alone, so the wider gate writes nothing a scope already carries; the
gate comment names the channels per form, since "a SHAPE_ENV guard reads the
shape-env sources" was true of the cpp form only. The regex is anchored on a
word boundary: shape exprs are source names, so L['self'].myG['k'] carried a
G['k'] substring that armed _has_global_guards on an artifact holding no
global guard, and a module load with an unresolvable forward then warned about
a guard that did not exist. A genuine subscript always follows a non-word
character, and its key is always single-quoted (GlobalSource's name is
G[{_esc_str(global_name, apply_repr=True)}] on a LOAD_GLOBAL identifier),
so \bG\['([^']*)'\] matches exactly those. The pick below is untouched by
this: the guard's originating_source is a ShapeEnvSource, not a
GlobalSource, so _guard_source_globals never admits the name and the graph
keeps the tensor serialized with it, while the guard itself does read the live
one: a rebind to a shape outside the range fails the call naming the range
guard, and a rebind to a same-shape tensor of another dtype passes the guard
and reaches the serialized value.

Question two: which live values may the bytecode read? This is the NARROW
set, _guard_source_globals: the names a kept guard's own originating_source
IS, an exact GlobalSource, not a chained source walked up to the global it
hangs off. Answering it from the wide set was wrong in the other direction, and
every wider channel was shown to hand the graph a value no surviving guard
certifies:

# keep_tensor_guards_unsafe keeps TENSOR_MATCH on a plain tensor and, with its default
# keep_parameters=False, drops it on an nn.Parameter
AOT_NESTED_GLOBAL = {"a": torch.randn(4), "b": torch.nn.Parameter(torch.randn(4))}

class M(torch.nn.Module):
    def forward(self, x):
        return x * AOT_NESTED_GLOBAL["a"] + AOT_NESTED_GLOBAL["b"]

# captured in float32; then, before the load:
AOT_NESTED_GLOBAL["b"] = torch.nn.Parameter(torch.randn(4, dtype=torch.float64))
loaded(x)
# root-of-chained-source pick: the surviving guard on ["a"] contributed the whole dict, the
#   call answers in float64 -- no error, no guard failure
# exact-GlobalSource pick: the container is reached only through a sub-path and keeps the
#   value serialized with it
  • A shape source. Under enable_cpp_symbolic_shape_guards=True the
    mark_dynamic'd global is reached only by SHAPE_ENV, whose
    TensorPropertyGuardAccessor checks tensor-ness and size(index) and nothing
    else, so reading it live let a rebind to a float64 tensor of a compatible
    shape into a float32 graph and the call answered in float64.
  • DUPLICATE_INPUT's source_b. Worse in one corner: it records
    source_b before its optimizer-source early return, so an optimizer-rooted
    pair records a name with no guard installed at all.
  • guard_on_key_order, the one a DEFAULT-filter capture reaches. That set
    carries no value certification and guard_filter_fn never prunes it (it is
    copied verbatim into the serialized state and only ever cleared wholesale, by
    the serializer once every kept guard is portable), so on the default filter,
    which drops every g.is_global guard, iterating a module-level dict roots its
    TYPE_MATCH and its key-order entry at the same GlobalSource, the guard is
    dropped, the key-order source survives, the artifact still reads as holding a
    global guard, and the live dict was spliced into fn.__globals__ with nothing
    checking its values: a rebind between save and load silently changed the
    answer, with every guard still passing. It is deliberately not unioned into
    the pick: a name only it contributes is precisely a name whose value no
    surviving guard checks. Whether the recorded builtins key is a checked name is
    a different question and keeps the wide union, guard_on_key_order included,
    because a dict-order check can name that key as well as a guard source can,
    and seeding a name no guard reads is at worst redundant while reading one live
    would be a wrong answer.
  • The root of a chained source, the same defect inside the pick itself,
    which the isinstance(guard.originating_source, GlobalSource) test closes.
    get_global_source_name walks a source up to the global it hangs off, so a
    TENSOR_MATCH on G['D']['a'] contributed D, and substituting D handed
    the graph the live container, every OTHER key of which that guard certifies
    nothing about. A guard certifies its own source, not the object that source
    was reached through. The example above is that defect reached through a
    shipped public filter, one level of nesting down.

Dropping each is strictly conservative: a name it stops substituting keeps the
value serialized with the artifact, still present in runtime_env.used_globals,
so the worst case is a stale but audited value rather than an unchecked live
one, and no name a surviving guard certifies is lost, because such a guard names
it through its own source.

The substitution: one certified name at a time

Where a guard's own source IS a global, the live dict supplies the compiled
bytecode's value for THAT NAME:

live = {name: guard_scope[name]
        for name in _guard_source_globals(output_graph)
        if name != builtins_key and name in guard_scope}
extra_globals = {**(extra_globals or {}), **live}

So the traced scope and the live scope agree only where a passing guard
certifies that they may, and every other global stays the one the graph was
traced with. The builtins-dict key is left out, so under a filter that keeps
BUILTIN_MATCH the guard rooted at it certifies the live dict, which the
substitution never copies into the graph's snapshot. This is enabled by the new
bytecode_reads_guard_scope=True flag on AOTCompiledFunction.deserialize,
which only the module path sets: a caller that supplies a guard scope but no
f_globals is the only one that needs it.

Substituting the whole namespace instead would change what a reloaded graph
computes with under a filter that kept one global guard and dropped another's:
with backend="inductor" and a rebound global of a different shape that
surfaces as a raw expected size ... stride ... assertion out of the compiled
kernel rather than as a guard failure, and with matching metadata it does not
surface at all. That is reachable from a shipped public filter, not a corner:
torch.compiler.keep_tensor_guards_unsafe keeps TENSOR_MATCH on a plain
tensor and drops it on an nn.Parameter, so a module reading one of each had
the Parameter substituted with nothing checking it; rebind that Parameter to a
float64 tensor before the load and the call returns a float64 result, no error
and no guard failure. Keeping the artifact-level "does anything check a global"
test as a cheap short-circuit is still right (an artifact with every global
guard dropped, what the default guard_filter_fn produces, runs entirely on
the globals serialized with it), but it may only arm the pick, not stand in for
it. The alternative, substituting nothing and documenting that guards and
bytecode read different dicts, was rejected because the substitution is exactly
where a kept guard's certification can be spent; a caller who wants neither it
nor the seeding passes guard_globals= instead. The deserialize docstring
states the limit of that certification rather than the pick working around it:
a kept guard is only as strong as its type, so a root TYPE_MATCH on a
container certifies the container's type and not the members the graph reads
through it. Narrowing the pick to value-pinning guard types instead was
rejected: a global container of nn.Modules, the only shape a shipped filter
can leave structure-only, cannot be saved at all (the pickler refuses an
unmarked nn.Module and this path threads no external_data), while the
narrowing would stop reading a container live even where the member the graph
reads keeps its own TENSOR_MATCH.

The guards state is loaded before the callable is built rather than after, so
GraphRuntimeEnv.forward_callable runs once. Deciding extra_globals needs
the guards, and the only path that loads them is the one that may substitute,
so the straightforward order built the callable and then rebuilt it with a
different extra_globals whenever the substitution applied.

Test-file plumbing

"__import_" joins _MINTED_PREFIXES in the test file, which is what lets
test_aot_compile_module_deserialize_unwraps_optimized_module do both halves
of its check: _hide_leaked_dynamo_globals has to pop the capture's own leaked
aliases, or they stand in for the one the load seeds, and the assertion then
names that one alias exactly. The comment on the constant now separates the
reasons a family is listed: five of them mint through unique_id_unbound_in,
whose skip loop burns an extra index only on a leftover the next mint at the
same prefix runs its counter onto, which is what a test pre-binding that name
is counting on (a leftover under another prefix, or at an index that counter
never reaches, burns nothing), while a __compiled_fn name carries a uuid no
other counter reproduces and an __import_* alias is derived from the module
name and written straight into f_globals, so neither goes through that skip
loop at all and is listed because a leftover of it is indistinguishable from
the name a later compile or a load has to bind. "___unnamed_scope" joins it
too: a capture in this process binds the key to the live dict, and the new test
has to hide that leftover to be the loading-process shape at all.

The helper module that supplies the alias, _HELPER_MOD, is registered in
sys.modules at import time rather than per test, because the class whose
forward inlines its function is module-level (the read has to root at
import_source(<registered module>) at capture and the alias has to import by
name at load), so a tearDownModule pops it: the module-level analogue of the
addCleanup the per-test decorator module uses, and one both unittest and
pytest run, where an addModuleCleanup cleanup pytest never calls.

Restoring the single-level unwrap makes
test_aot_compile_module_deserialize_unwraps_optimized_module fail on its
eval_frame assertion, __import_torch_dot_nn_dot_modules_dot_module having
been seeded there by the load through the deepcopied wrapper; restoring the
parent's hint text makes ..._hint_names_the_forward fail on 'make model.forward a plain function or bound method' not found.

Test Plan:

python test/dynamo/test_aot_compile.py -k test_aot_compile_module_dispatches_on_global_guard
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_fallback_scope_warns_once
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_fallback_scope_names_a_qualnamed_forward
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_alias_only_globals_load_silently
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_fallback_scope_hint_names_the_forward
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_deserialize_unwraps_optimized_module
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_default_filter_keeps_the_serialized_global
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_only_the_guarded_global_is_read_live
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_sub_path_global_is_not_read_live
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_shape_only_global_arms_the_guard_scope
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_shape_only_global_is_not_read_live
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_key_order_only_global_is_not_read_live
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_deserialize_refuses_an_nn_module_forward
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_deserialize_refuses_a_forwardless_module
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_deserialize_refuses_a_lazy_graph_module_forward
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_deserialize_resolves_a_graph_module_forward
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_deserialize_missing_global_hint_names_the_resolved_module
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_unnamed_scope_key_is_seeded_from_the_artifact
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_python_shape_guard_global_arms_the_guard_scope
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_unnamed_scope_key_is_disowned_when_left_alone
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_shape_guard_alias_is_seeded_from_the_artifact
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_dropped_shape_guard_seeds_no_alias
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_unnamed_scope_builtins_dict_travels_by_reference
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_shape_guard_unnamed_scope_key_is_seeded
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_attribute_dict_shape_guard_holds_no_global
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_deserialize_takes_a_guard_globals_scope
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_deserialize_keeps_an_orig_mod_submodule
python test/dynamo/test_aot_compile.py

Mutation-verified twice. Restoring the guard_on_key_order union makes
test_aot_compile_module_key_order_only_global_is_not_read_live fail on its
value assertion, the live 10 + 20 answering in place of the serialized
1 + 2. Restoring the root walk, get_global_source_name(...) in place of the
GlobalSource test, makes
test_aot_compile_module_sub_path_global_is_not_read_live fail with
torch.float64 != torch.float32: the rebound Parameter under ["b"] reaches a
float32 graph through the substituted container.

With the unnamed-scope seeding removed,
test_aot_compile_module_unnamed_scope_key_is_seeded_from_the_artifact fails
on its first call after the leaked key is hidden, KeyError on G['___unnamed_scope_<id>_c0']. With the shape-operand union removed from the
arming set,
test_aot_compile_module_python_shape_guard_global_arms_the_guard_scope fails
on no logs of level WARNING or higher triggered on torch._dynamo.aot_compile.
With the seeding gated on global_scope alone again,
test_aot_compile_module_shape_guard_alias_is_seeded_from_the_artifact and
test_aot_compile_module_shape_guard_unnamed_scope_key_is_seeded error on
their first call, GuardManager check failed with
verbose_code_parts=["'__import_aot_compile_helper_mod'"] and
["'___unnamed_scope_<id>_c<n>'"]; with the regex's \b dropped,
test_aot_compile_module_attribute_dict_shape_guard_holds_no_global fails on
True is not false. With GuardBuilder.SHAPE_ENV's if self.save_guards:
gate removed, so shape_code_parts is recorded on the pre-filter pass too,
test_aot_compile_module_dropped_shape_guard_seeds_no_alias fails on
assertIsNone(guards_state.shape_code_parts) with the lambda text 2 <= G['__import_aot_compile_helper_mod'].HELPER_ROWS.size()[0] in the report, and
with that assertion dropped on its closing assertNotIn(alias, globals()): the
load seeded the alias for a guard the artifact does not hold. With
_picklable_unnamed_scope bypassed,
test_aot_compile_module_unnamed_scope_builtins_dict_travels_by_reference
errors in serialize with TypeError: cannot pickle 'PyCapsule' object, the
CI failure verbatim; it plants a real capsule (datetime.datetime_CAPI) in
builtins.__dict__ so 3.12 sees what 3.10 did. Moving the unnamed-scope
CleanupHook.disown inside the bind branch makes
test_aot_compile_module_unnamed_scope_key_is_disowned_when_left_alone error
with KeyError: '___unnamed_scope_<id>_c0': the stand-in hook deleted the
binding the loaded guards read.

Replacing the torch-namespace test with if False makes
test_aot_compile_module_deserialize_refuses_a_forwardless_module and
test_aot_compile_module_deserialize_refuses_a_lazy_graph_module_forward fail
on no logs of level WARNING or higher, and on the namespace assertion with
the warning half removed; dropping the vars(module) is scope identity check
makes
test_aot_compile_module_deserialize_missing_global_hint_names_the_resolved_module
fail on its copied-namespace half.

Authored with the assistance of Claude Code.

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

FAQ

FAQ: The module-artifact hint tells the user to pass f_globals=, which the module path does not take. Fixed here rather than in #196819, where the rewrite first sat: this is the commit that makes the rebuilt-scope branch reachable from a module load and already asserts that producer's report, so the advice is worded per producer here. The module branch splices the refusal's own reason and advice and then names the remedy the path has -- pass AOTCompiledModel.deserialize a guard_globals= scope carrying the name -- and the function branch keeps f_globals=. test_aot_compile_module_fallback_scope_hint_names_the_forward asserts both, and is load-bearing: with the parent's text restored it fails on the module producer's wording.

FAQ: guarded_globals = set(output_graph.global_scope) - {builtins_key} is wider than the set of guard-certified names, so a global reached only through a ShapeEnvSource guard's shape_env_sources or DUPLICATE_INPUT's source_b gets its live value substituted into the graph with only its shape checked. Narrow the pick to a kept guard's originating_source unioned with guard_on_key_order. Agreed, and that is what this commit does -- the review was written against an earlier revision of it. The narrowing is already here as _guard_source_globals, used by the pick alone -- the builtins-key gate in _seed_guard_scope deliberately keeps the wide root set, as the message says it must -- while _has_global_guards keeps the wide set(global_scope), unioned with the G['NAME'] operands of a Python-form shape guard (see the FAQ on the base update below), so the fallback warning still fires. The measurement, on the exact case named: with enable_cpp_symbolic_shape_guards=True and a mark_dynamic'd global tensor, global_scope is ['AOT_SHAPE_ONLY_GLOBAL', '__builtins_dict___0'] while the guard-source roots are [] -- no kept guard names that global at all, the surviving checks being SHAPE_ENV, TENSOR_MATCH (dropped by aot_compile's filter), DEFAULT_DEVICE and AUTOGRAD_SAVED_TENSORS_HOOKS. Rebinding it to torch.randn(8, 4, dtype=torch.float64) before the load and calling: with the pick widened back to the wide set, OUTPUT dtype: torch.float64 and equals serialized answer: False; with the narrow pick as shipped, OUTPUT dtype: torch.float32 and equals serialized answer: True. test_aot_compile_module_shape_only_global_is_not_read_live pins it and is load-bearing: widening the pick to recorded_globals turns it RED with AssertionError: Object comparison failed: torch.float64 != torch.float32. Your note that the older ..._shape_only_global_arms_the_guard_scope test cannot catch this is also correct and confirmed -- it stays GREEN under that same mutation, because its functools.partial forward takes the no-scope fallback and never reaches the substitution, which is why the new test uses a resolvable forward.

FAQ: mod.forward = SomeOtherModule() makes get_traced_fn return that other module's forward, so the guard scope silently becomes the wrong module's namespace with no exception and no warning; and an AttributeError from an uninitialized module deeper in that branch is downgraded to "unresolvable forward". Both are real and both are already refused here, again from a revision later than the one reviewed. _resolve_guard_scope tests isinstance(forward, torch.nn.Module) before calling get_traced_fn, so an nn.Module forward never enters that branch. Measured on object.__setattr__(mod, "forward", torch.nn.ReLU()) (the test itself now binds a user-defined module, since a ReLU() forward is also caught by the torch-namespace refusal below and could not show the isinstance test load-bearing): with the refusal removed, reason: None and scope __name__: torch.nn.modules.activation, is activation ns: True -- exactly the silent mis-rooting described, seeding included; with the refusal in place, reason: M.forward (ReLU) and scope: None, so the load takes the documented fallback and warns. test_aot_compile_module_deserialize_refuses_an_nn_module_forward pins both halves and is load-bearing: replacing the isinstance test with if False turns the warning half RED on no logs of level WARNING or higher and the seeding half RED on the bound module's dict gaining __import_torch_dot_nn_dot_modules_dot_module. On the uninitialized-module half, refusing removes the reclassification rather than improving it: because the Module branch is the only place get_traced_fn reads _forward_pre_hooks, an nn.Module forward is now rejected by type at the isinstance test instead of by an AttributeError caught further down, so no hook read on this path can be mistaken for an unresolvable forward.

FAQ: deserialize should offer at least an optional guard_globals= parameter so a caller that does not want its namespace written to can pass its own dict. It has one. AOTCompiledModel.deserialize takes a keyword-only guard_globals: dict[str, Any] | None = None, uses it as scope in place of anything resolved from model.forward, and forwards it to each AOTCompiledFunction.deserialize; it is seeded into and substituted from on the same terms as a resolved scope, and the docstring documents that. test_aot_compile_module_deserialize_takes_a_guard_globals_scope pins it with ParentWithChildModule under keep_global_guards, which roots a kept guard at an __import_* alias and so makes the seeding observable: the assertion is that the alias lands in the supplied dict and that the real module namespace gains nothing.

FAQ: CompilePackage.uninstall() pops names unconditionally with no ownership token, so a precompile package that installed the same alias can delete a seeded binding out from under a loaded artifact; and a later in-process import_source asserts f_globals[alias] is value, which fails across an importlib.reload/sys.modules swap. Real, reproduced, and not fixed in this commit -- both halves are closed higher in this stack, by #196895 (an ownership token, record_only_if_new, scoped to the aliases uninstall() may not remove) and #196896 (the identity assertion replaced by a same-__name__ rebind). Measured directly at this commit: bind __import_torch_dot_nn_dot_modules_dot_module into a module dict the way a load's seeding does, then have a CompilePackage install the same alias and call uninstall() -- _installed_globals records only {'victim_mod': ['__import_torch_dot_nn_dot_modules_dot_module']}, with nothing recording who bound it first, and after uninstall() the binding is gone (False), so the artifact's guards, which hold that dict by reference, fail permanently. The import_source assertion at symbolic_convert.py is likewise a hard failure once the alias' value is no longer identical to the freshly imported module. Fixing either needs an ownership token on installed globals and a module-name rather than identity comparison in the alias check, which is out of scope for a commit whose subject is where a module artifact's guard scope comes from; #196895 and #196896 carry those two changes as their own commits, and until they land the conservative mitigation exists today: pass AOTCompiledModel.deserialize(mod, data, guard_globals=...) and own the dict yourself -- the same private surface _load_aot_compiled_module wraps.

FAQ: the four new field comments run 8-13 lines each and the ~30-line deserialize docstring restates the substitution contract three times; trim to one-or-two-line field comments with the full argument stated once. Done, as you suggested -- though the count is three fields, not four: this commit adds _forward_not_resolved_reason, _has_global_guards and _bytecode_reads_guard_scope, while _guard_scope and _guard_globals are already present at its parent, and the longest of the three ran 8 lines rather than 13. Each field comment is now one or two lines (_bytecode_reads_guard_scope in particular now says "the module load path passes one dict for both roles" on its second line rather than making the reader hold a paragraph), the wide-versus-narrow argument is stated once at _guard_source_globals and referenced from __post_init__ instead of restated at both the arming site and the pick site, and the docstring states the substitution contract once. Net 14 lines of comment and docstring removed with no behaviour change; nothing was lost, since the full reasoning is recorded in the commit message.

FAQ: The two shipped skip_guard_on_*_nn_modules_unsafe filters prune by guard SOURCE CLASS while the pick keys off the source being an exact GlobalSource, so a global container of modules -- D = {"m": nn.Linear(4, 4)} read as D["m"](x) -- keeps only its root TYPE_MATCH and is substituted live with nothing checking its members; narrow the pick to value-pinning guard types.

The guard set is exactly as you describe and the reachability is not: on the module path that artifact cannot be produced at all, in any filter configuration. Measured. If the module is CALLED, capture refuses -- PackageError: MODULE_MATCH guard cannot be serialized -- because the MODULE_MATCH guards on the __import_* aliases are rooted at GlobalSource(alias) whose guard_source is plain GLOBAL, so is_unspecialized_nn_module() does not drop them and guards.py:5126 rejects them; that holds for a hand-written single-Parameter module too, since tracing any unspecialized module reads _global_forward_hooks and pulls in MODULE_MATCH on __import_torch_dot_nn_dot_modules_dot_module. If the module is only READ THROUGH (x * D["m"].w), capture succeeds and the SAVE refuses -- RuntimeError: Failed to serialize the following objects: [Tiny()] -- because AOTCompilePickler.persistent_id records every unmarked nn.Module it reaches (aot_compile.py:181-183) and serialize raises on that (aot_compile.py:938-942), with no escape hatch on this path: AOTCompiledModel.serialize threads no external_data at all (aot_compile.py:1262-1269). Nor are the two evadable together: a bespoke filter that keeps the container's TYPE_MATCH, drops every guard the serializer refuses AND drops nn-module-sourced guards still gets CAPTURE OK then the same Failed to serialize the following objects: [Tiny()]. That closes the general case rather than a sample: for a live container substitution to change an answer the graph must READ the container, which puts it in runtime_env.used_globals, which is pickled -- and a container holding an unmarked nn.Module never pickles. Your SEQUENCE_LENGTH-on-a-global-list and DICT_KEYS_MATCH variants are the same value shape and die at the same two places. Across the shipped filters this is the whole story: keep_portable_guards_unsafe keeps no global-rooted guard, keep_tensor_guards_unsafe keeps only the value-pinning TENSOR_MATCH and no structure-only root, skip_guard_on_globals_unsafe and skip_all_guards_unsafe leave the pick empty, and the default aot_compile filter drops every is_global -- so the nn-skip pair is the only filter that can leave a structure-only root guard standing over dropped members, and only when those members are nn.Modules.

FAQ: Then restrict the pick to value-pinning guard types (EQUALS_MATCH, CONSTANT_MATCH, TENSOR_MATCH, BUILTIN_MATCH) and exclude the container-structure ones (TYPE_MATCH, SEQUENCE_LENGTH, DICT_KEYS_MATCH, DICT_CONTAINS, HASATTR, NOT_NONE_MATCH).

Declined, because it pays a reachable cost for an unreachable hole. I applied your version verbatim to _guard_source_globals (aot_compile.py:525-548) and measured it. Your worry about test_aot_compile_module_dispatches_on_global_guard is unfounded -- it stays green, as do ..._only_the_guarded_global_is_read_live, ..._default_filter_keeps_the_serialized_global and ..._key_order_only_global_is_not_read_live, because each graph's own snapshot already carries the pooling mode that graph was traced for. What it does break is the ordinary case of a container whose read member IS certified: CFG = {"scale": torch.tensor(2.0)} read as x * CFG["scale"] keeps both TYPE_MATCH @ GlobalSource('CFG') and TENSOR_MATCH @ DictGetItemSource(base=GlobalSource('CFG'), index='scale'), so the member the graph reads is guarded. Rebinding CFG["scale"] to 5.0 before the load, as shipped: pick: {'CFG'}, loaded: [5.0, 5.0, 5.0], the live value served. With your narrowing: pick: set(), loaded: [2.0, 2.0, 2.0] -- the stale traced value served past a passing guard on the very member being read. That withdraws live dispatch, which is the behaviour this commit exists to add, in a case where the certification you are asking for is present.

FAQ: Then at least qualify the certification claim in the deserialize docstring, since :1284-1281 states the contract without saying it is only as strong as the root guard's type.

Taken, as the one thing here that is both true and cheap. The claim is weaker than the phrasing, and it IS reachable -- not through a shipped filter, but through a user-written guard_filter_fn, which is public API. Measured with a filter that keeps the container's TYPE_MATCH and drops the item's TENSOR_MATCH, rebinding CFG["scale"] to a float64 5.0 before the load: pick: {'CFG'} and out: [5.0, 5.0, 5.0] dtype: torch.float32 against serialized: [2.0, 2.0, 2.0] -- the live, uncertified member reached a float32 graph. The docstring now says the certification is only as strong as the guard's type, spelling out both weakenings: a kept TENSOR_MATCH checks metadata and not values, and a root TYPE_MATCH on a container checks its type and not the members the graph reads through it. Behaviour is unchanged, so nothing new is pinned by a test and nothing claims to be.

FAQ: HASATTR with val=True installs no leaf guard on the base -- only a getattr_manager accessor -- so if it is the sole survivor for a name, that name is substituted with zero value certification.

Same class as the container case, and covered by the docstring qualification rather than by code, with two corrections. The pick reads output_graph.guards, not the leaf-manager tree (aot_compile.py:544-548), so whether a C++ leaf exists is irrelevant to admission; what matters is what the guard certifies, and HASATTR(val=True) certifies that the attribute exists. And HASATTR is not alone in practice: for a module-level OBJ = Cfg(2.0) probed with hasattr(OBJ, "scale"), the kept set is HASATTR @ GlobalSource('OBJ') AND TYPE_MATCH @ GlobalSource('OBJ'). Making HASATTR the sole survivor for that name therefore takes a user-written filter that keeps HASATTR and drops TYPE_MATCH -- the same user-filter regime the docstring now covers -- and no shipped filter does it, by the case analysis above.

FAQ: the named {qualname} half of the unresolvable-forward report has no test while the empty half is pinned on exact text twice; add one using object.__setattr__(mod, "forward", torch.relu), which has __qualname__ == "relu", no __self__/__func__ pair and fails inspect.isfunction, so get_traced_fn raises RuntimeError at convert_frame.py:1395. Taken, with a different fixture, because the one you name is wrong twice and the assertion you propose would have been red on arrival. Measured: torch.relu.__qualname__ is _VariableFunctionsClass.relu, not relu, so "forward (builtin_function_or_method named relu)" never appears; and hasattr(torch.relu, "__self__") is True -- its value is None -- so get_traced_fn takes the __self__ branch and dies on the unchecked __func__ read with AttributeError: 'builtin_function_or_method' object has no attribute '__func__', never reaching the RuntimeError at :1395. The branch is reachable only because _resolve_guard_scope catches (RuntimeError, AttributeError), which is what the comment above the __globals__ read already says; a test resting on :1395 would be documenting a path this input does not take, and pinning _VariableFunctionsClass.relu would pin a torch-internal qualname that is not this commit's to keep stable. Your two premises for why the existing tests miss the suffix are both confirmed, though -- functools.partial has no __qualname__ and neither does a ReLU() instance (__qualname__ is a getset on type, absent from torch.nn.ReLU.__dict__) -- so the gap is real and test_aot_compile_module_fallback_scope_names_a_qualnamed_forward now closes it with a self-contained fixture: functools.wraps(GlobalConfigModule.forward) over the partial, which is the realistic channel by which an unresolvable forward acquires a __qualname__ and is a one-attribute delta from the existing (partial) fixture. It reports GlobalConfigModule.forward (partial named GlobalConfigModule.forward) and is load-bearing: dropping the suffix from the f-string turns it RED with AssertionError: 'GlobalConfigModule.forward (partial named GlobalConfigModule.forward)' not found in ..., while ..._fallback_scope_warns_once, ..._refuses_an_nn_module_forward and ..._hint_names_the_forward all stay GREEN under that same mutation -- which is your finding, measured.

FAQ: _resolve_guard_scope accepts any plain function get_traced_fn returns, so mod.forward = torch.compile(mod.forward) -- the documented compile-a-method pattern -- roots the guards in torch._dynamo.eval_frame's namespace and every kept global guard fails with a hint to define the global there. Reproduced. At this commit that shape is REFUSED -- eval_frame's namespace is a torch module's, which the torch-namespace rule turns into the documented fallback with a warning -- and #196908 above then resolves through the wrapper to the forward it wraps, with a test that loads such a module and pins the scope. The hop is not folded here so this commit stays the scope-resolution move it is; the capture side cannot produce that shape, so it is a load-side mismatch that failed loudly (with a misleading hint) rather than serving a wrong answer.

FAQ: _resolve_guard_scope accepts a forward whose function is defined inside torch -- a forwardless module (nn.Module.forward is the bound _forward_unimplemented), a _LazyGraphModule before real_recompile (_lazy_forward), a plain GraphModule (a private copy of the codegen globals) -- and seeds __import_* aliases into those namespaces with no CleanupHook. Refused now, by one rule: a resolved function whose __globals__ IS a torch module's live namespace -- scope is vars(sys.modules[scope['__name__']]) with a torch root -- takes the documented fallback with a reason naming that namespace. The test is the namespace's identity, not the function's __module__, which functools.wraps copies and which a GraphModule's exec'd forward lacks. Measured: the forwardless and _LazyGraphModule shapes resolved torch.nn.modules.module and torch.fx._lazy_graph_module silently before and are refused now (test_aot_compile_module_deserialize_refuses_a_forwardless_module, ..._refuses_a_lazy_graph_module_forward, the latter also pinning that real_recompile makes the module resolve). A GraphModule's dict is no module's namespace and still resolves (..._resolves_a_graph_module_forward): it carries only __builtins__, fx emits only module aliases into it, so _has_global_guards is False under both filters and refusing it would flip SUPPLIED to RECONSTRUCTED with nothing observable. The rule also refuses torch's own modules, torch.compile(torch.nn.Linear(...)) included; such a forward reads only torch globals, so that fallback is silent and the call answers -- the capture side already writes __import_*/__builtins_dict__ into torch.nn.modules.linear when it traces Linear, so the load side is now the stricter of the two.
FAQ: _check_external_refs fails a load with advice naming f_globals= when a hand-built guard_globals= omits a global the graph specialized on; say in the docstring that the scope must be a superset. Declined, because the premise does not hold on the module path. Measured: external_refs is the LOAD_GLOBAL set of the GENERATED bytecode -- the __compiled_fn_* and __import_* names -- all of which forward_callable binds itself, and a global the graph specialized on is baked into the graph rather than read at call time. AOTCompiledModel.deserialize(mod, data, guard_globals={}) LOADS, and a too-narrow scope fails only at the call, with the SUPPLIED hint that names the scope; there is no load-time f_globals= advice on this path to qualify.
FAQ: _unwrap_optimized_module unwraps one level, so a nested OptimizedModule still roots and seeds the guards in eval_frame's namespace. Confirmed and fixed; it is a loop now. Reachability is exactly as described and not via torch.compile(torch.compile(mod)), which collapses to a plain function: OptimizedModule.__reduce__ rebuilds a copy.deepcopy'd or unpickled wrapper without the metadata innermost_fn follows, so torch.compile of the copy wraps again. Measured at this commit: torch.compile(copy.deepcopy(torch.compile(Mod())))._orig_mod is an OptimizedModule, the single unwrap returned it, and _resolve_guard_scope returned vars(torch._dynamo.eval_frame). test_aot_compile_module_deserialize_unwraps_optimized_module now also loads through that nested wrapper; with the single-level unwrap restored it fails with __import_torch_dot_nn_dot_modules_dot_module seeded into eval_frame's namespace.

FAQ: guard_globals= is unreachable from the shipped module-load API, _load_aot_compiled_module(self, data). Deliberately. Both routes are private and gated on config.enable_aot_compile; AOTCompiledModel.deserialize is the module artifact's load and the place its scope contract is documented, and the hint a failed guard emits now sends the caller there by name. _load_aot_compiled_module exists to install the artifact as the wrapper's own forward, and for that wrapper _orig_mod.forward's globals is the only scope its guards mean anything against -- a caller who wants another dict is not loading the wrapper's module and has the classmethod. The mitigation that made this look necessary is also moot: #196895 (ownership token in uninstall()) and #196896 (same-__name__ alias rebind) close the interaction higher in this stack.
FAQ: _seed_guard_scope seeds only the __import_* aliases and the builtins-dict key, so a module whose forward inlines a function from an unnamed scope and lifts a value read through it fails every call with KeyError on G['___unnamed_scope_...'] where the parent's RECONSTRUCTED load answered. Confirmed and fixed here. Reproduced with _UNNAMED_SCOPE_NS carrying a tensor under keep_global_guards: the pruned global_scope and used_globals both carry the key, the function load (RECONSTRUCTED) answers and the module load (SUPPLIED) failed on exactly that KeyError. _seed_guard_scope now binds used_globals[key] -- the same object forward_callable spreads into the bytecode's globals and the rebuilt scope hands the guard -- into a supplied scope for every ___unnamed_scope key among the names the kept guards read -- _recorded_guard_globals, the pruned global_scope plus a Python-form shape guard's G[...] operands, see the FAQ on the seeding gate below -- never replacing a binding the scope has, after CleanupHook.disown as for the builtins key (install_global_by_id goes through install_global_unsafe). A key used_globals lacks is a namespace the graph only specialized on, which no scope can supply, and stays a no-match with the hint correctly suppressed. test_aot_compile_module_unnamed_scope_key_is_seeded_from_the_artifact pins the seeding, the non-overwrite, and that EPS in the same artifact is still read live; with the seeding removed it fails on the KeyError. _has_global_guards and the fallback warning are unchanged: the key sits inside one half of the warning or the other, as the review's correction says.
FAQ: A user functools.wraps'd wrapper over forward resolves to the wrapper's function, so the guards root in the decorator's module and the call fails KeyError on G['NAME'] with a hint naming that module; refuse a resolution whose __wrapped__ owns different globals. Declined in favour of documenting it in the deserialize docstring. Measured: a capture of the decorated forward records the decorator's module as its scope -- Dynamo traces the decorator as the root frame, the model's globals root at __import_<model module> and the decorator's own at a GlobalSource -- so a load onto the same shape resolves the same dict, answers, and reads the decorator's guarded global live (a rebind of it fails its EQUALS_MATCH rather than being served stale). That shape is producible: a class-body decorator saves; the instance-rebound mod.forward = deco(mod.forward) does not (Failed to serialize the following objects: [M()], the closure holds the instance). A refusal keyed on __wrapped__ would send the class-body shape to the rebuilt scope, where the decorator's guarded global is compared against the serialized value and cannot fail, so a rebind between save and load would be served silently -- a wrong answer traded for the loud failure the review describes, which is a plain artifact loaded onto a decorated forward. Composes with #196908: innermost_fn stops at a wrapper Dynamo did not mint (the copied _torchdynamo_wrapper_id does not match id(inner)), so a user wrapper over torch.compile(mod.forward) resolves the decorator's module at the tip as here, and the paragraph reads "seen through Dynamo's own wrappers, never through a wrapper the caller applied" there.
FAQ: The base update makes a Python-fallback shape guard read the resolved scope, which the arming set does not account for -- on the default config a mark_dynamic'd global's guard reads a global live while _has_global_guards reads False and the fallback warning cannot fire -- and it inverts the message's paragraph saying the Python-form shape guard reads the serialized G. Confirmed, fixed here, and the paragraph is rewritten. Measured on a module whose forward reads a mark_dynamic'd module-level tensor, default filter and default config: python_fallback: True, the name absent from global_scope, and python_code_parts.exprs carrying 2 <= G['SHAPE_G'].size()[0]; before the fix a load onto an unresolvable forward logged nothing and _has_global_guards was False. __post_init__ now unions the G['NAME'] subscripts of shape_code_parts.python_code_parts.exprs into the arming set when python_fallback is set (_SHAPE_GUARD_GLOBAL_RE), minus the recorded aliases as before -- the union lives in _recorded_guard_globals, which _seed_guard_scope reads whole to gate its seeding, see the FAQ below; _guard_source_globals is untouched, so the pick still leaves the name alone -- a size check certifies no value. test_aot_compile_module_python_shape_guard_global_arms_the_guard_scope is the default-config mirror of ..._shape_only_global_arms_the_guard_scope and is load-bearing: with the union removed it fails on no logs of level WARNING or higher triggered on torch._dynamo.aot_compile. The default-config mirror of ..._shape_only_global_is_not_read_live needs no new test because the pick did not change; measured anyway: a same-shape float64 rebind before the load gives out dtype: torch.float32 | equals serialized answer: True, and a 1-row rebind fails the call naming 2 <= G['SHAPE_G'].size()[0] -- the guard reads the live scope, the graph keeps the serialized tensor. AOTCompiledModel.deserialize's docstring now says so, matching load_compiled_function's.
FAQ: The unnamed-scope CleanupHook.disown(guard_scope, name) runs before the if name not in guard_scope test, so on the branch where the load binds nothing it strips the ownership token of a binding a same-process capture created, whose hook then returns early and the binding leaks for the process lifetime; move the disown inside the bind branch. Declined, and pinned the other way, because the order is the builtins branch's for the same reason: the guards this load installs read that binding by reference for as long as the artifact lives, so the load has to take the ownership even when it leaves the value alone. Measured with a live binder -- a hook owning the key, as a same-process torch.compile leaves one through install_global_unsafe: as shipped, firing that hook after the load leaves the key bound and the loaded call answers; with the disown moved inside the bind branch, firing it deletes the binding and the loaded artifact fails its next call with KeyError on G['___unnamed_scope_<id>_c0'] -- the failure test_load_disowns_only_a_builtins_key_a_guard_reads pins as unacceptable for the builtins key. What leaks as shipped is a reference to a dict the artifact needs anyway for as long as it lives. The premise is also narrower than stated: on the aot capture path no hook object survives at all -- fullgraph_capture never transfers output.cleanups to CleanupManager, so after an in-process capture the token alone is left in _cleanup_owners (measured: hook objects for the key alive: 0 | token still owned: True) and the disown is a no-op in either order; only a regular compile's hook is live, and that is the case above. test_aot_compile_module_unnamed_scope_key_is_disowned_when_left_alone stands one in with CleanupHook.create and fires it after the load; with the disown moved it errors with KeyError: '___unnamed_scope_<id>_c0'.
FAQ: The seeding gate was not widened with the arming set: _seed_guard_scope still keys the __import_* aliases and the ___unnamed_scope key on the pruned global_scope, which under python_fallback records nothing the shape lambda alone reads, so a shape guard whose operand is an alias fails every call on the default filter; and the gate comment's "a SHAPE_ENV guard reads the shape-env sources" holds only for the cpp form. Confirmed, both halves, and fixed here. Reproduced on the default filter and default config with a forward calling a helper in a registered module that reads a mark_dynamic'd tensor of its own: python_code_parts.exprs is ["2 <= G['__import_aot_dyn_helper_mod'].HELPER_T.size()[0]"], global_scope is ['__builtins_dict___0'], the alias is in import_sources; the module load succeeds and its first call fails with GuardManager check failed ... verbose_code_parts=["'__import_aot_dyn_helper_mod'"] -- the Python lambda reports the bare KeyError text, not a KeyError on G[...] part, so no hint was suppressed, there was none -- while a load onto a functools.partial forward (RECONSTRUCTED) answers. Same through an unnamed-scope dict holding the dynamic tensor: expr 2 <= G['___unnamed_scope_<id>_c1']['NS_T'].size()[0], key in used_globals and not in global_scope, first call fails on "'___unnamed_scope_<id>_c1'". The union is hoisted into _recorded_guard_globals(guards_state) -- set(global_scope) plus the lambda's G['NAME'] operands when python_fallback is set, which is only ever the case when the filter kept the SHAPE_ENV guard, see the FAQ on the dropped guard below -- which __post_init__ subtracts the builtins key and the aliases from to arm, and which _seed_guard_scope reads whole, before any subtraction, to gate both loops; the comment now names the channels per form. Both loops still leave a binding the scope has alone, so the wider gate writes nothing a scope already carries. test_aot_compile_module_shape_guard_alias_is_seeded_from_the_artifact and test_aot_compile_module_shape_guard_unnamed_scope_key_is_seeded pin the two shapes on the default filter -- alias/key absent from global_scope, present in a G[...] operand, the load answers, the seeded object is the imported module / used_globals[key] -- and are load-bearing: with the gate back on global_scope alone both error on the first call with exactly those reports.
FAQ: _SHAPE_GUARD_GLOBAL_RE has no left boundary, so L['self'].myG['k'] contributes k and _has_global_guards reads True for an artifact holding no global guard. Confirmed and fixed. Measured on a module reading self.myG["k"] with a dynamic dim: exprs is ["2 <= L['self'].myG['k'].size()[0]"], global_scope is ['__builtins_dict___0'], findall gave ['k'] and a module load read _has_global_guards: True. The pattern is \bG\['([^']*)'\] now; a genuine subscript always follows a non-word character and its key is always single-quoted (GlobalSource._name_template is G[{_esc_str(global_name, apply_repr=True)}] on a LOAD_GLOBAL identifier). test_aot_compile_module_attribute_dict_shape_guard_holds_no_global pins _has_global_guards False on that artifact and fails with True is not false without the anchor. Warning-accuracy only, as noted: the pick reads _guard_source_globals.
FAQ: _recorded_guard_globals reads shape_code_parts without checking that a SHAPE_ENV guard survived the filter, and that field is populated on the pre-filter build_guards pass and never reset, so skip_all_guards_unsafe and keep_tensor_guards_unsafe still arm the fallback warning and seed an alias or unnamed-scope key for a guard that will never read it; gate the union on a surviving ShapeEnvSource guard in output_graph.guards. Declined as a code change, because the premise is not what the builder does -- measured. GuardBuilder.SHAPE_ENV writes check_fn_manager.shape_code_parts under if self.save_guards: (guards.py:3561-3582), and the pre-filter pass you cite is self.build_guards(sorted_guards, ..., False) (:4962-4968, save_guards=False); only the post-filter pass saves (:4985-4992). Instrumented on the _HELPER_MOD fixture under skip_all_guards_unsafe: pre-filter pass n=11 save=False, SHAPE_ENV in the sorted guards, shape_code_parts still None afterwards; saving pass n=0; the serialized guards_state.shape_code_parts is None, global_scope and _recorded_guard_globals empty (no guard survives, so not even the builtins key is recorded), _has_global_guards False, the alias not seeded and the call answers. Under keep_tensor_guards_unsafe shape_code_parts is None as well; the alias IS seeded there, but through global_scope, from the kept TENSOR_MATCH rooted at G['__import_...'].HELPER_ROWS -- a guard that reads it, which is the seeding doing its job. The default filter gives python_fallback True, exprs ["2 <= G['__import_aot_compile_helper_mod'].HELPER_ROWS.size()[0]"] and the seeded alias. So the operand union is already gated on the guard surviving, one call up: a filter that drops SHAPE_ENV leaves nothing for the regex to read. The explicit any(isinstance(g.originating_source, ShapeEnvSource) ...) would be a branch nothing reaches; instead the helper's comment names where the gate lives and test_aot_compile_module_dropped_shape_guard_seeds_no_alias pins it under skip_all_guards_unsafe -- no surviving ShapeEnvSource, shape_code_parts is None, _has_global_guards False, alias unbound after the load and after the call -- and is load-bearing against the regression you describe: with the if self.save_guards: gate removed from SHAPE_ENV it fails on assertIsNone(guards_state.shape_code_parts) and, that line dropped, on its closing assertNotIn(alias, globals()).
FAQ: python_fallback can be True even under enable_cpp_symbolic_shape_guards -- an OverflowError, a ConstantSource, a SymInt/SymFloat operand, or a missing C++ compiler each fall back -- so the helper's python_fallback test is the right condition, and the shape_env_sources-vs-operands split holds in every one of those cases. Right outcome, one mechanism correction: only the OverflowError case reaches the helper through python_fallback. SHAPE_ENV records shape_code_parts (guards.py:3576) BEFORE the ConstantSource, SymInt and InvalidCxxCompiler decisions (:3610-3694) flip the local, so the serialized flag stays False for those three and the helper never scans the lambda text -- and does not need to, because cpp_code_parts exists in each, shape_env_sources is filled from its source_to_symbol, and serialize_guards prunes those roots into global_scope, the set the helper starts from. Measured with CppCodeCache.load raising InvalidCxxCompiler under the cpp config on the alias fixture: recorded python_fallback False, shape_env_sources ["G['__import_...'].HELPER_ROWS.size()[0]"], global_scope carrying the alias, _recorded_guard_globals the same two names the default-config run gives, alias seeded, call answers, a 1-row rebind fails the guard. The recording order is base behaviour and not this commit's to move.
FAQ: The _HELPER_MOD fixture leaks a sys.modules entry for the process, unlike the decorator module at test_aot_compile_rebuilt_wrapper_keeps_its_own_module_scope, which has an addCleanup. Taken, with a tearDownModule that pops it. Per-test registration was declined because the fixture is module-level for a reason: ImportedRowsModule.forward inlines a function whose __globals__ has to be a REGISTERED module's dict at capture (that is what roots the read at import_source(<module>) and puts the alias in the shape operand) and importable by name at load, and the module-level class is what the tests hand to deserialize; a per-test copy would rebuild the module, the function and the class in each test for no change in what is pinned. unittest.addModuleCleanup was rejected because pytest's unittest plugin runs doClassCleanups but never doModuleCleanups, while tearDownModule is looked up by name by both runners (_pytest/python.py _inject_setup_module_fixture).
FAQ: CI is red on every 3.10/3.11 shard from this PR up with TypeError: cannot pickle 'PyCapsule' object in serialize(); the sibling test passes. It does not: run_test.py runs with -x, so the alphabetically-first unnamed-scope test fails and the rest never run; in the first red run the sibling itself failed the same way. The capsule is pybind11's internals, which pybind11 < 2.13 stores in builtins.__dict__ on CPython < 3.12 -- CI's scipy==1.10.1 (3.10/3.11 only, requirements-ci.txt:265) does, and common_utils imports scipy in every test process. get_runtime_env records an exec'd namespace whole, __builtins__ -> the live builtins dict included, and serialize() pickled it by value; only the __builtins_dict___N key was filtered. A pre-existing bug on main (the standalone repro fails at the stack base), reached in CI first by this PR's fixture. serialize() now swaps that entry, in the pickled copy only, for the guards pickler's _live_builtins stand-in; test_aot_compile_module_unnamed_scope_builtins_dict_travels_by_reference plants a real capsule (datetime.datetime_CAPI) so 3.12 reproduces it, red before / green after.

🤖 Generated with Claude Code

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (6 Unrelated Failures)

As of commit 77040a6 with merge base 4c54342 (image):

GREEN LIGHT - PR approved to be merged without human review:

  • Correctness
    • _resolve_guard_scope refuses an nn.Module forward and a torch-owned namespace, matching get_traced_fn's Module rewrite at convert_frame.py:1356-1395
    • The live-value pick uses the narrow _guard_source_globals (only GlobalSource roots, builtins_key excluded), so a sub-path guard cannot substitute its container
    • _SHAPE_GUARD_GLOBAL_RE's \bG\[' skips the myG['k'] shape-expr substring, and a spurious plain name only widens the seed gate, which binds alias and ___unnamed_scope prefixes alone
  • Preservation
    • _seed_guard_scope keeps the never-overwrite rule and adds CleanupHook.disown for the unnamed-scope key, mirroring the existing builtins-key branch at aot_compile.py:790-795
    • Under the default guard_filter_fn every global guard is dropped, so _has_global_guards stays False and the load keeps reading the serialized globals
  • Testing
    • test/dynamo/test_aot_compile.py adds coverage per branch: alias seeding, unnamed-scope seeding/disown, key-order-only, sub-path, shape-only, and each refusal reason
    • test_aot_compile_module_deserialize_keeps_an_orig_mod_submodule pins the isinstance-based unwrap against a _orig_mod submodule name
  • Scope
    • Confined to torch/_dynamo/aot_compile.py and its test file; guard_globals= is an additive keyword-only parameter
    • No CI, build, release, or documentation-policy files are touched

reason: clean
Reviewed commit: 77040a6

Inference job

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

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 11, 2026
This was referenced Sep 11, 2026
pytorchmergebot pushed a commit that referenced this pull request Sep 14, 2026
…ake (#196819)

Mostly tests for the guard-scope resolution the previous commit added, plus the
behaviour changes writing them turned up. `aot_compile_module` traces
`model.forward` directly, so `nn.Module`'s dispatch in `_call_impl` never runs
and every forward or backward hook registered on `model` itself is dropped from
the compiled callable. That is a silently different answer rather than an
error:

```python
class M(torch.nn.Module):
    def forward(self, x):
        return x * 2

m = M()
m.register_forward_hook(lambda mod, args, out: out + 1)
m(x)                                                   # eager: x * 2 + 1
aot_compile_module(m, [ModelInput((x,), {}, [])])(x)   # x * 2 -- the hook never ran, nothing raised
```

## Warn about dropped hooks, worded per group

`_warn_dropped_module_dispatch(model)` runs at the top of both
`aot_compile_module` and `AOTCompiledModel.deserialize`, since a hook present
only in the loading process is dropped just as thoroughly, and the tests pin one
record per path. It warns whenever any of the four per-instance hook dicts
`_call_impl` dispatches on is non-empty, naming the kind of hook ("forward
pre-hooks", "backward hooks") rather than the private dict a caller who used
`register_forward_pre_hook` never sees:

```
M has forward hooks registered; the AOT compiled forward calls M.forward directly, so those
hooks do NOT run and its result may differ from eager -- to keep them, AOT compile
torch.compile(model).forward instead, which traces __call__ and runs them; call the artifact
it returns with the module as its first argument if you define forward yourself; ...
```

Those four are the per-instance subset of the eight dicts `_call_impl` tests;
the four `_global_*` ones are deliberately left out, because an artifact served
through `OptimizedModule` still runs them on the wrapper's own `_call_impl`, so
warning about them would be a false positive on that path.
`test_aot_compile_module_global_hooks_are_not_warned_about` pins that by
registering a global forward hook and asserting the load stays silent while the
hook still fires through the wrapper. A direct `AOTCompiledModel` really does
drop them, and without a warning, which `deserialize`'s docstring now says
rather than a fifth warning that would claim the loss for both paths. Only the
dicts of `model` itself are polled: a hook or a `__call__` override that a
SUBMODULE carries only in the loading process is dropped with no warning at
all, because the graph baked in whatever the capture traced through that
submodule's `nn.Module.__call__`, so a `model.modules()` walk would be a false
positive for the ordinary capture-and-load-with-the-same-hooks case. The
docstring states that boundary next to the `_global_*` one. One record per
GROUP, not per dict: the forward and backward wordings each name every hook kind
in their group, and `test_aot_compile_module_warns_one_record_per_group`
registers all four kinds on a module that also overrides `__call__` and pins
the three records that come out.

The forward dicts and the backward dicts are worded separately, because the
redirect is unconditional only for the forward ones. AOT compiling
`torch.compile(model).forward` traces `_wrapped_call_impl`, which runs the
forward hooks; the same capture refuses a module-level backward hook unless
compiled autograd is enabled around it, and the flag the graph break's own hint
names does nothing here:

```python
m.register_full_backward_hook(hook)
torch.compile(m).forward.aot_compile(((x,), {}))
# Unsupported: Module-level backwards hooks require compiled autograd

torch._dynamo.config.compiled_autograd = True                  # still refuses: aot_compile never
torch.compile(m).forward.aot_compile(((x,), {}))               # enters the dynamo context that reads it

with torch._dynamo.compiled_autograd._enable(torch.compile):   # private; the capture succeeds
    art = torch.compile(m).forward.aot_compile(((x,), {}))
art(m, x).sum().backward()      # reproduces eager's hooked gradient exactly
art.save_compiled_function(p)   # saves
load_compiled_function(p)       # raises: the artifact cannot round-trip
```

What differs from eager differs too: a dropped backward hook leaves the forward
result bit-identical and changes the gradients, so a reader who checked outputs
against a "result may differ" warning would conclude it was spurious. The
backward message therefore says the hooks do not run, that the gradients may
differ while the forward result does not, and that the redirect keeps them only
under compiled autograd and only for an artifact that is never reloaded; it
calls `_enable` private, because without the word a warning naming an
underscored function reads as a supported API.
`test_aot_compile_module_dropped_hook_advice` follows the advice rather than
only reading it: for the forward dicts it registers a hook with an effect and
asserts the redirect's artifact reproduces eager, and for the backward dicts it
asserts all three legs above, so the text cannot drift back to denying a
redirect that works or promising one that round-trips.

The forward-hook warning gets a tail for a `LazyModuleMixin` module: its
initializer is registered as a forward pre-hook, so every uninitialized lazy
module lands in the warning, and while it does `OptimizedModule._initialize`
pins the wrapper's forward to `_call_lazy_check`, which has no `aot_compile`, so
the redirect says to call the module once and wrap it again.
`test_aot_compile_module_lazy_hook_advice_says_to_wrap_again` pins that pin and
its release.

## Warn about an overridden `__call__`, probed the way eager dispatches

Hooks are not the only thing tracing `model.forward` skips: a `__call__` the
module overrides is dropped the same way, because eager dispatches through
`type(model).__call__` while the artifact calls what `forward` compiled to, and
since no hook dict records it, that case was silent. It gets a warning of its
own, with the redirect, which does work for an override. The probe is the same
type lookup eager does:

```python
class Logged(torch.nn.Module):
    def __call__(self, *a, **k):
        print("called"); return super().__call__(*a, **k)
    def forward(self, x): return x

aot_compile_module(Logged(), ...)   # warns: Logged overrides __call__ ...

m2 = M(); m2.__call__ = lambda *a: ...   # an instance attribute: CPython resolves a special
aot_compile_module(m2, ...)              # method on the type, eager ignores it, the artifact matches -- silent
```

That lookup is not the whole probe. `fx.GraphModule` installs a wrapper as its
per-instance class's `__call__` on every `GraphModule.recompile`, and
`recompile` always runs from `__init__`, so the lookup alone calls every
GraphModule an override, a plain `symbolic_trace` GraphModule included (an
`ExportedProgram.module()` never gets this far: its local-scope
`GraphModuleImpl` fails the save with `PackageError`). That wrapper is not an
override: with no class `__call__` to wrap it only prettifies `eval_with_key`
tracebacks and delegates to `super(cls, obj).__call__`, so eager runs the hooks
and the artifact matches. So the probe walks `type(model).__mro__` and skips
every class whose own `__call__` is FX's wrapper, taking the next `__call__` the
MRO offers, which is the one that delegation reaches:

```python
def is_fx_wrapper(c):
    fn, wrapped = vars(c)["__call__"], vars(c).get("_wrapped_call")
    return ((fn.__module__, fn.__qualname__) == ("torch.fx.graph_module", "GraphModule.recompile.<locals>.call_wrapped")
            and isinstance(wrapped, _WrappedCall) and wrapped.cls_call is None)

call = next(vars(c)["__call__"] for c in type(model).__mro__
            if "__call__" in vars(c) and not is_fx_wrapper(c))
```

The wrapper is told apart by its def site, since `call_wrapped` is a closure
`recompile` mints anew on every run and leaves no one function to compare by
identity, with the `_WrappedCall` that `recompile` installs beside it on the
same class still carrying a `None` `cls_call`. Identifying it by its function
rather than by one class identity matters twice. `recompile` installs it on
whatever `type(self)` is at the time, and `parametrize`, `fully_shard` and
`replicate` all rebind `module.__class__` to a fresh subclass after the trace,
so a recompile after that swap leaves TWO wrapper classes on the MRO
(`recompile` reads `vars(cls)`, which does not see the inherited
`_wrapped_call`, so the fresh subclass gets one of its own), and the capture
itself performs that recompile: serializing the guards pickles the GraphModule,
whose `__reduce__` recompiles it onto the swapped class, so every probe after
the first capture, a load included, sees both, and a probe keyed on one class
identity calls the inner one an override (measured: `ParametrizedLinear
overrides __call__`; eager on that module is FX's own version of the same
mistake, a `RecursionError` between the two wrappers, so there is no override
to report). And a real `__call__` assigned onto the per-instance class
afterwards sits on the very class FX wrapped, so skipping that class by identity
dropped a genuine override that eager runs. Skipping the class rather than
starting the walk past it is what keeps an override sitting AHEAD of it
visible; a test traces an `nn.Linear`, parametrizes its weight and pins that
the capture stays silent while the artifact still matches eager. A wrapper
whose `cls_call` was set is the one shape that does not delegate to `super`;
`functional_export` sets it for a hooked root, and a test pins that this stays
an override, both on the class that owns it and behind a `__class__` swap that
leaves the fresh subclass owning neither attribute. Walking rather than
trusting `cls_call` is what makes this safe rather than merely quiet:
`cls_call` is `None` for a `GraphModule` subclass that declares `__call__` too,
because FX reads the declaration off the per-instance class, where a subclass's
does not live, so calling `cls_call is None` not-an-override would have dropped
a real one. `test_aot_compile_module_fx_call_wrapper_is_not_warned_about` pins
both halves, that a traced GraphModule stays silent on the capture and the load
and that such a subclass still warns. `_LazyGraphModule` defers that recompile
to the first call or code access, so until then no class on its MRO owns a
`__call__` and the probe is silent for want of a wrapper rather than by
skipping one; the test pins both states.

## Which arguments the redirect's artifact takes

All three redirects say which arguments the artifact they produce takes,
because getting it wrong ends on the first call in a guard failure:

```python
art = torch.compile(m).forward.aot_compile(((x,), {}))
art(m, x)   # forward you define yourself: the module first (AOTCompiledModel.__call__ hides this
            # convention by passing self.model for the user)
art(x)      # forward defined in a file Dynamo skips, as torch.nn's stock modules are, or under
            # config.wrap_top_frame: only the forward arguments
```

The branch is the one `OptimizedModule._initialize` took, and the discriminator
is `trace_rules.check(mod.forward)`, which resolves on the FILE `forward` is
defined in rather than on the class, so a subclass that inherits `forward`
unoverridden counts as skipped too. The clause names that predicate,
`OptimizedModule._forward_has_skip_rule(model)`, rather than a list, because no
list spells the rule: `check_file` consults `LEGACY_MOD_INLINELIST` before
`MOD_SKIPLIST`, so a file inside a skipped directory can still be inlined
(measured, `QuantStub`'s forward under `torch/ao/` is, so its artifact takes
the module first), and a wording that enumerated `MOD_SKIPLIST` would answer
wrongly there and rot with the list. Without the clause, following the advice
ends in `GuardManager check failed` for the hook wordings, whose trace of
`_wrapped_call_impl(self, *args, **kwargs)` absorbs the shifted argument and
then fails the recorded `len(L['args']) == 1` guard, and, for the third, in a
`TypeError` naming the override's own parameter when the override declares one,
or that same guard failure when it takes `*args`. The tests assert the clause on
all three wordings: the two hook ones through the parametrization rather than
on the forward pair alone, since a module carrying only a backward hook gets
the backward warning and no other, and the override wording in the test for
that warning. `test_aot_compile_module_redirect_arg_clause_is_conditional` pins
the branch rule itself, on a Linear, on a subclass that inherits `forward`, on
one that overrides it and on a `QuantStub`, which the inline list rescues from
the skipped directory it lives in; it pins that the inheriting subclass's
artifact takes only the forward arguments and refuses the module-first call, so
the predicate cannot drift from the branch `_initialize` takes, and that the
clause names the predicate and no list.

## The capture path unwraps too, and has to REBIND

Handed the wrapper `torch.compile` returned, `aot_compile_module` traced
`OptimizedModule.forward`, which is eval_frame's `compile_wrapper`:

```python
aot_compile_module(torch.compile(m), [ModelInput((x,), {}, [])])
# parent: Unsupported: Attempted to call function marked as skipped ... set_eval_frame
```

So the wrapper-caller path this commit documents and warns for could not reach
an artifact at all. Had it traced, `AOTCompiledModel` would have kept the
wrapper as `self.model`, which `prepare_f_locals` hands the guards as
`L['self']`, so any forward that reads `self` would report no match on every
call: measured, `___check_type_id(L['self'], ...) type=<class 'M'>` answers
false for the wrapper and true for the module. One rebind, through the
`_unwrap_optimized_module` the previous commit added, fixes both halves, and
`test_aot_compile_module_capture_warns_about_the_traced_module` now hands in a
real `ModelInput` and asserts the artifact answers and holds the module rather
than the wrapper. It counts every record rather than filtering for the hook
one, since warning about the wrapper emits exactly one record too, and joins
them into the assertion's message, which `assertEqual` otherwise drops for not
being a string. With `inputs=[]` that test stopped at "Expected at least one
compiled result", raised after the warning and before the capture, which is why
neither half showed up.

## Both shapes `forward` can take, for scope resolution

The hook case is also what discriminates `model` from `model.forward` for the
scope resolution #196818 added: a registered forward hook makes
`get_traced_fn(model)` return the `Module._wrapped_call_impl` function, whose
globals are `torch/nn/modules/module.py`, and the scope must still come out as
the module definition's namespace.
`test_aot_compile_module_scope_resolves_through_forward_hook` pins that; its
hook is deliberately the identity, precisely because hooks are dropped, so it
pins scope resolution on a hooked module rather than hook support, and it
leaves the warning count to the parametrized test that owns it.

A `functools.partial` forward is not such a case (`get_traced_fn` raises the
same "Unsupported model code type" for both spellings), so
`test_aot_compile_module_fallback_scope_hint_names_the_forward` pins the
fallback instead: the artifact loads, the warning names the object and the
consequence, and a call reports the missing global and points at the rebuilt
scope rather than at a module to define the name in. Asserting that report was
chosen over promising the fallback works: nothing on this path puts a user
global into the rebuilt scope, whose extra names are the recorded imports and
the backend id, so the honest contract is the one that runs, which keeps
#196818's choice to warn rather than refuse an unresolvable forward pinned, the
one case here with no capture to redirect to.
`test_aot_compile_module_fallback_scope_runs_without_global_guards` sits beside
it and pins the two things that half silently relied on: that the guards really
did fall back to the reconstructed scope, and that with no global guard to
satisfy nothing warns. The module dispatch body #196818's test spelled inline
becomes a helper parameterized by module factory and mode setter; both the test
it came from and the hooked-module test above call it, and the containment
#196818 added for the globals a capture leaks into this module's dict moves
with the body, to the top of the helper, where one call covers every caller.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_dispatches_on_global_guard
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_scope_resolves_through_forward_hook
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_on_dropped_hooks
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_dropped_hook_advice
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_global_hooks_are_not_warned_about
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_capture_warns_about_the_traced_module
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_on_custom_call
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_one_record_per_group
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_instance_call_is_not_warned_about
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_fx_call_wrapper_is_not_warned_about
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_fallback_scope_hint_names_the_forward
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_fallback_scope_runs_without_global_guards
python test/dynamo/test_aot_compile.py -k test_aot_compile_fn_missing_global_hint_names_f_globals
python test/dynamo/test_aot_compile.py -k test_aot_compile_fn_missing_global_hint_names_the_tracing_scope
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_lazy_hook_advice_says_to_wrap_again
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_redirect_arg_clause_is_conditional
```

Authored with the assistance of Claude Code.

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

## FAQ

> **FAQ: the three warnings fire unconditionally on every capture and every load
> with nothing deduping them -- for a module with both a forward and a backward
> hook plus a GraphModule-style `__call__` that is three multi-line warnings per
> load, so is repeat emission in a serving loop worth a `warn_once`?** Measured: a
> load of a module carrying a forward pre-hook, a forward hook and a backward hook
> emits 2 records totalling 1600 bytes, and 1000 subsequent calls of the loaded
> artifact emit 0 more bytes. The count is 2 rather than 3 because the forward and
> backward wordings each name every hook kind in their group in one record, and the
> GraphModule `__call__` is no longer one of them after this round's narrowing --
> three records now needs a module that both overrides `__call__` for real and
> carries both hook kinds. The emission is per `deserialize`, not per call, so a
> serving loop that loads once and serves many times pays it once; `warn_once`
> would buy nothing there and would cost the thing the tests pin, that a hook
> present only in the loading process is reported in that process too.

> **FAQ: the three-leg backward assertion calls `redirected.aot_compile(...)`
> three times on the same object relying on the first two raising and the third
> succeeding -- wouldn't a `torch._dynamo.reset()` between legs make the third
> leg's success attributable to the context manager rather than to accumulated
> Dynamo state?** Measured in both directions, and no state is doing any work.
> Leg 3 alone in a fresh process, with no preceding legs at all, succeeds and
> its artifact reproduces eager's hooked gradient (`LEG3 STANDALONE SUCCEEDS:
> True`, `grad matches eager: True`), so the context manager is sufficient on
> its own. Reversing the order -- the context-manager leg first, then the two
> refusal legs on the same `redirected` -- both refusal legs still raise
> `Module-level backwards hooks require compiled autograd`, so a successful
> capture leaves nothing behind that lifts the refusal either. A `reset()`
> between legs would change no observed outcome.

> **FAQ: `test_aot_compile_module_capture_warns_about_the_traced_module`
> asserts `len(logs.output) == 1` on the whole logger unlike its siblings which
> filter by substring first -- shouldn't it filter the same way so an unrelated
> `torch._dynamo.aot_compile` warning added later doesn't fail it with a
> confusing diff?** The diff was confusing, and that half is fixed; the filter
> is declined. Measured by adding a stray `log.warning` to
> `aot_compile_module`: the failure read only `Expected 1 but got 2`, because
> PyTorch's `assertEqual` appends the `msg` argument only `if isinstance(msg,
> str)` (`common_utils.py:4959`) and `logs.output` is a list, so the records
> were dropped. Joining them restores it -- the same mutation now prints
> `SOME UNRELATED FUTURE WARNING` and the `ScaleModule has forward hooks`
> record verbatim. Filtering instead would give up what the total count is
> for: this is the only assertion in the file that the capture path is
> otherwise quiet, and it is not redundant with the substring check, since
> warning about the wrapper rather than the module it wraps also emits exactly
> one record (measured: `OptimizedModule overrides __call__`, with no hook
> record, because the wrapper carries 0 forward hooks and 0 pre-hooks).

> **FAQ: `ParameterList`/`ParameterDict` override `__call__` to raise
> unconditionally, so warning that the result "may differ from eager" for a
> module that cannot be called at all is noise -- should the probe skip them
> too?** Declined, and unlike the GraphModule case the warning is not wrong
> here: eager dispatch really does reach `ParameterList.__call__`
> (`container.py:796`), so the type lookup reports a genuine override. What
> makes it moot is measurable -- the module cannot be AOT compiled either:
> `torch.compile(ParameterList([...]))._aot_compile([...])` raises
> `Unsupported: Observed exception` off `Module.forward`, so no artifact ever
> exists for the warning's claim to be wrong about. Excluding the two
> classes by name would add a special case that only ever fires on a path that
> is already an error, whereas the GraphModule narrowing removes a claim that
> is false about a module that captures, loads and answers correctly.

> **FAQ: `assertIn("takes only the forward arguments", naming[0])` cannot
> fail -- that substring is a fixed literal inside the module-level
> `_REDIRECT_CALL` which all three warnings emit unconditionally, so it pins
> nothing about conditionality, and the two `"with the module as its first
> argument"` assertions have the same shape; shouldn't they be replaced with
> something branch-dependent?** Measured, all three do fail, under exactly
> the drift they exist for. Deleting the clause's qualification tail fails
> the first one (`AssertionError: 'takes only the forward arguments' not
> found in '...call the artifact it returns with the module as its first
> argument'`), and rewording the leading clause to "with the module first"
> fails the other two -- all four parametrized hook legs plus the override
> test (`FAILED (failures=4)` and `FAILED (failures=1)`). What they pin is
> the wording of advice a caller follows verbatim, which is the part that
> rots. Conditionality is pinned separately in the same test, by the
> `wrap_top_frame` capture whose artifact raises `GuardManager check failed`
> when called with the module first, and this round adds the half that
> really was missing: that the branch is chosen by the FILE `forward` is
> DEFINED in (`OptimizedModule._forward_has_skip_rule`,
> `eval_frame.py:492-495`). Measured, that is `True` for `nn.Linear`, `True`
> for a user subclass that inherits `forward` and `False` for one that
> overrides it, and the artifacts agree: the inheriting subclass's takes
> only the forward arguments and refuses the module-first call, the
> overriding one's is the other way round.

> **FAQ: `issubclass(type(model), getattr(fx_wrapper, "cls", type(None)))` closes
> the post-hoc `__class__`-swap hole in the `__call__` probe -- why wasn't that
> one-liner taken?** Because measured, it does not close it. With exactly that
> substitution, a traced `nn.Linear` whose `weight` is then parametrized -- which
> is where `parametrize.py:384-386` rebinds `__class__` to a direct subclass --
> still emits `ParametrizedLinear overrides __call__`, so the new test leg fails
> the same way it does unfixed. The entry test was never the whole problem: the
> body walked `type(model).__mro__[1:]`, and after the swap the class FX wrapped is
> no longer element 0 of that MRO but element 1, so the walk finds `call_wrapped`
> on it anyway. The probe now walks the whole MRO and skips every class whose own
> `__call__` is the wrapper FX's `graph_module.py` installs (`call_wrapped`,
> `:1007-1010`) while its `_WrappedCall.cls_call` (`:453-456`) is `None`, which
> survives the swap, survives a `recompile()` after it (which puts a second wrapper
> class on the MRO), keeps a `__call__` assigned onto the per-instance class
> visible, and also keeps a real override sitting AHEAD of those classes visible --
> the wrapper base that `_fsdp_init.py:426-427` and `replicate.py:247` put there
> (`parametrize.py:384-386` subclasses the traced class directly, so its leg is
> silent because the FX class survives as MRO element 1, not because a wrapper sits
> ahead). Your `issubclass` relation is kept as an assertion in the test, pinning
> the shape the swap produces.

> **FAQ: `test_aot_compile_module_redirect_arg_clause_is_conditional` captures
> without the `_hide_leaked_dynamo_globals()` its siblings call, so it leaks
> Dynamo's generated globals into the test module dict -- masked today, but
> shouldn't the call be added for consistency?** Declined, and measured rather than
> assumed. The test does leak, 6 minted names, but so does nearly every capture in
> this file: 68 of the 89 test methods that capture do not hide first (58 of 80 in
> the parent), so hiding is not a convention this test departs from. It is what a
> test that asserts an exact minted-global set does FOR ITSELF -- the helper pops
> the live minted names for the duration of the test and restores them in cleanup
> (`test_aot_compile.py:1719`) -- so those tests are correct no matter who ran
> before them. Run in one process, the redirect test leaks its 6 names and both
> exact-set tests then pass, leaking 4 and 2 of their own. Even the sibling's call
> is not load-bearing: deleting it and running the whole file gives `Ran 163 tests
> ... OK (skipped=6)`. A line that changes no outcome anywhere, and that cannot
> protect a future exact-set test which fails to hide for itself, is not worth
> adding.

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

Pull Request resolved: #196819
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196767, #196817, #196815, #196816, #196818
pytorchmergebot pushed a commit that referenced this pull request Sep 14, 2026
…oks (#196820)

Tests only. The first pair covers a module artifact loaded with a live guard
scope, which splits the artifact's behaviour in two: the snapshot the bytecode
reads is taken at load, while the dict the guards resolve against is the loading
process's own. Each half is a silent-wrong-answer risk if it regresses, so each
is pinned, in the order the tests appear, along with the residual gap the first
half leaves -- a global rebound after the load, which the snapshot goes on
serving unless a guard on its value refuses the call. The second pair pins two
properties of #196819's dropped-hook warning that nothing checks: a hook
registered after the load, whose silence its docstring documents, and the
once-per-model rather than once-per-ModelInput shape of the warning, which a
single-input test cannot tell apart. What they share is the shape of what they
cover, a residual gap each of the two commits below chose to document rather than
close, which is too little to carry a commit of its own, so the subject names
both rather than pretending to one.

One half is that the compiled bytecode reads the live scope rather than the
globals serialized at capture: the load resolves the scope from `model.forward`
and passes it as the guard scope, then merges the guarded names that scope binds
-- the recorded builtins-dict key aside, which is excluded by name whether or not
a guard reads it -- over the scope rebuilt from the artifact, so an artifact
loaded after a global was rebound serves the rebound value. The merge is a
snapshot taken when the artifact is rebuilt at load, not at capture, which is why
a rebind BEFORE the load is followed while one AFTER it is caught only by a guard
on the value -- and a kept `TENSOR_MATCH` checks metadata, not values, so the
rebind this test makes after the load, to the same tensor scaled by three, is
served from the snapshot; changing the dtype is refused rather than answered
wrongly, by the guard on that global, which the assertion names so that an
unrelated dtype check cannot stand in for it. That residual gap is the same one
an `f_globals` load has; it is a known limitation rather than a goal, and the
test documents it as such. It only exists to be documented because the capture
passes `keep_global_guards`: under the default filter there is no global guard
on the weight at all, so the mechanism the test describes would not be there.
The capture-time weight is deliberately not the identity, since with `eye(3)`
the assertion cannot tell "read the serialized weight" from "the matmul was
dropped", and the test asserts the capture-time and live products differ before
it demands that the reload return the live one.

The other half is that guards read the loading process's scope dict by reference,
so a global rebound after the load redirects dispatch on the next call: a copy
taken at load time would go on serving whichever graph matched then, with no
error. The global there is a NAME this module rebinds, not a mutated container: a
mutation is visible through a copy of the scope just as well, so only a rebind can
tell a shared dict from a copied one. Every test here captures and loads in this
process, whose module dict is the scope the guards resolve to, so each hides the
globals a capture seeds there, as the function-path twin already does.

The dropped-hook pair is the same treatment applied to #196819's residual gap:
`deserialize` warns about the hooks a module carries when it is loaded, and its
docstring says one registered afterwards is dropped without a warning. The
docstring documents that silence, but nothing pins it. A test now does, from both
sides -- no warning is emitted, and the artifact keeps serving the unhooked
answer while the module it holds does not in eager -- so the cost of the silence
is on the record rather than resting on the docstring.

The warning's other property is that it is once per model, not once per
`ModelInput`: `_warn_dropped_module_dispatch` runs ahead of the per-`ModelInput`
loop on the capture path and once per `deserialize` on the load path, so a capture
of two inputs still emits one paragraph. #196819's parametrized test pins one
record per path with a single input, which cannot tell the two apart, so a test
with two inputs asserts the compiled-result count next to the warning count, the
same way the sibling fallback-scope warning is pinned.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_reload_reads_the_live_global
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_guards_track_rebound_global
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_after_load_hook_is_silently_dropped
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_hook_warning_fires_once
```

Authored with the assistance of Claude Code.

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

## FAQ

> FAQ: why keep `AOT_HERMETIC_WEIGHT` / `HermeticModule` when nothing about these
> tests is hermetic? The criticism of the name is fair -- what the fixture pins is
> that a loaded artifact reads the LIVE global as of the load rather than the
> sealed capture-time copy, so something like `AOT_LIVE_WEIGHT` would say it
> better. The fixture is not local to this commit, though: commits above this one
> reuse both names, including assertions on the literal report text
> `[0] KeyError on G['AOT_HERMETIC_WEIGHT']`. Renaming in the commit that
> introduces them therefore spans more than one commit's test hunks and rewrites
> later commits' expected strings, for a naming preference that changes nothing
> about what is covered. Nothing in the contract rests on the name: the comment
> above the fixture says what it is for (a weight deliberately not the identity, so
> "read the serialized weight" and "the matmul was dropped" cannot produce the same
> tensor), and the tests that use it spell out which global they rebind and when.
> Once the stack lands, the rename is a mechanical follow-up that can touch every
> site in one commit.

> FAQ: the first leg of `test_aot_compile_module_reload_reads_the_live_global` --
> rebind before the load, then assert the live value -- is already covered by
> `test_aot_compile_module_only_the_guarded_global_is_read_live` below; why re-argue
> it instead of referring to it? Because what the leg contributes here is not the
> detector, it is the baseline the two post-load legs are read against. Measured:
> with the live substitution disabled (`extra_globals` rebuilt without `**live`) the
> sibling fails, this leg fails, and with the leg's own `assertEqual` deleted the
> test still fails one line lower, at the second leg -- so as a detector the leg is
> redundant. What is not redundant is its setup: the second leg's expected value IS
> `live`, the product of a rebind made before the load, and the third leg's dtype
> refusal rebinds that same name; a reference cannot supply a local expectation. The
> sibling also establishes the fact under a different filter --
> `keep_tensor_guards_unsafe`, one guarded global and one unguarded Parameter --
> than the `keep_global_guards` this test uses, so pointing at it would ask the
> reader to re-derive that the mechanism is the same one. The cost of keeping it is
> one assertion line.

> FAQ: `_guard_source_globals` no longer asks what a source is ROOTED at -- it
> requires the guard's own source to BE a `GlobalSource` -- so isn't "the only kept
> global guard is rooted at `AOT_HERMETIC_WEIGHT`" stale vocabulary? No: that
> sentence is the justification for the clause before its colon, "the load seeds
> nothing into it", and the seeding gate is root-keyed on purpose.
> `_seed_guard_scope` computes `roots = {get_global_source_name(source) for source
> in sources + guard_on_key_order}` and returns early unless the builtins-dict key
> is in it, and the comment above that gate says it "stays wide where
> `_guard_source_globals` cannot be"; the alias half gates on a name in the pruned
> `global_scope`. Root is in fact the only vocabulary under which the sentence
> excludes anything: on a capture that does arm the seeding (`keep_builtin_guards`)
> the guard that arms it is
> `DictGetItemSource(base=GlobalSource('__builtins_dict___0'), index='len')`, and
> no guard's source IS `GlobalSource('__builtins_dict___0')` -- so an "is" reading
> would be vacuous there. For this test both readings hold anyway: the kept guard's
> source is the bare `GlobalSource('AOT_HERMETIC_WEIGHT')`, the only global name in
> `roots` is `AOT_HERMETIC_WEIGHT` (its other members are `None`, from the
> `LocalSource`/`GlobalStateSource`/`ShapeEnvSource` guards), and an instrumented
> `_seed_guard_scope` adds nothing and rebinds nothing on a scope that is this
> module's own `globals()`.

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

Pull Request resolved: #196820
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196767, #196817, #196815, #196816, #196818, #196819
pytorchmergebot pushed a commit that referenced this pull request Sep 14, 2026
…on, across processes (#196821)

Tests only. One covers the alias seeding in #196817, reached through the
guard-scope resolution in #196818 and exercised through an `nn.Module` artifact
where that scope is resolved rather than passed. The other covers #196822's
`install_global` retry across processes; the last paragraph explains why it rides
here rather than with the fix.

The first is the real deployment shape: the artifact is captured in a subprocess
that never runs in this interpreter, so the load itself has to seed the aliases
its kept guards are rooted at. It asserts against the namespace delta -- which
`__import_*` names this module's globals gained across the load -- rather than
against the artifact re-filtered by the gate under test, which passes with the
gate deleted: the artifact records several aliases and only the one a kept guard
reads may be written into a live user namespace. Which alias that is comes off
the serialized `global_scope`, pruned to exactly the guarded names, rather than
off a literal. The recorded `__builtins_dict___N` key is the other half of the
same rule under its own gate: the serializer writes that key into the pruned
scope whether or not a guard reads it, so the load scans the kept guards'
sources for that key instead, and this capture's filter drops BUILTIN_MATCH, so
no kept guard names it and the load leaves it unbound. No state dict is copied
from the capturing process, so the closing `assertEqual(model(x), mod(x))` is a
real numeric assertion that dispatch reads this process's live parameters
rather than tensors baked into the artifact.

It restores the globals it disturbed through the helper added lower in the
stack, which by #196818 pops the `__import_*` aliases along with the other name
families in the test file's `_MINTED_PREFIXES`. A test that loads needs that
alias half popped, since its guards are rooted at those aliases: a sibling's
in-process capture leaves them bound, and a load that finds them already there
seeds nothing, so a pin on what the load wrote would be vacuous. The test
asserts the namespace starts with none of them; cleanup still strips whatever
the load added before putting the originals back, so the names the load seeded
do not outlive it.

The second test is the cross-process half of #196822's `install_global` retry:
a fresh process loads a module artifact captured with its BUILTIN_MATCH guard
kept -- a load seeds that key only for an artifact whose kept guards read it --
so the load seeds a `__builtins_dict___N` key, and then a compile in that same
process mints that name and has to be handed another. The mint is put there by
rewinding the counter to the index read off the name the load seeded, rather
than by betting that the capturing and the loading process both stopped their
counters at the same index: either side burning an id leaves the two names in
no conflict at all, the retry never runs, and the test goes red for a reason
unrelated to it. What the in-process sibling cannot do is make the taken name a
real one -- it pre-binds a sentinel string -- and that, not the counter
arithmetic, is what this test adds. It rides here rather than with the fix
because the shape it needs -- a module load whose guard scope is the loading
module's live namespace, so the captured builtins-dict key is seeded there
rather than into a scope rebuilt from the artifact -- arrives with #196818,
above the fix. It could have been written against the function path at #196817
instead, since a caller-supplied `f_globals` is normally the defining module's
live namespace and reaches the same collision; the module shape was kept
because there the load resolves the scope itself, so nothing in the test can be
read as the caller choosing a namespace to collide in. The reloading wrapper
takes no `guard_filter_fn`: `_load_aot_compiled_module` reads only the
artifact, so the loading process's filter has no say in what a loaded artifact
checks, and naming one that drops BUILTIN_MATCH would have contradicted the
capture this test loads. #196822 keeps the in-process tests, and cites the
precompile package path that reaches the same collision at the base of this
stack.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_import_alias_guard_loads_across_processes
python test/dynamo/test_aot_compile.py -k test_load_then_compile_survives_baked_in_global_collision
```

Authored with the assistance of Claude Code.

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

## FAQ

> **FAQ: If `install_global` were changed to overwrite the taken name instead of
> retrying past it, would the load's seeded `__builtins_dict___0` be clobbered
> with this test still green, so a `model(x)` vs `mod(x)` comparison is needed
> after the colliding compile?** No. Built with that exact mutation -- the
> `while name in scope` loop deleted from `unique_id_unbound_in` AND the
> `if name in scope: raise AssertionError` deleted from `CleanupHook.create`, so
> the install really does overwrite -- the test as written FAILS:
> `AssertionError: no collision on __builtins_dict___0: [...] -> {...}`, because
> the post-compile key set is unchanged. The suggested replacement is the one
> that does not work: with the same mutation in place and the numeric comparison
> substituted for the key-set assertion, the run prints
> `EXPERIMENT: post-collision numerics OK` and passes. It cannot detect a
> clobber, because both bindings hold the SAME object -- `get_builtins_dict`
> returns `global_scope["__builtins__"]` and `_seed_guard_scope` falls back to
> `builtins.__dict__`, so within one process the seeded value and the value a
> later compile installs are identical and overwriting one with the other is
> numerically invisible. Load-path numerics are separately pinned by
> `test_aot_compile_module_import_alias_guard_loads_across_processes` in this
> same commit, whose closing `assertEqual(model(x), mod(x))` covers exactly the
> "dispatch reads live parameters" property; duplicating it here is the
> one-fact-two-places the same review asks to remove.

> **FAQ: Isn't `assertEqual({k for k in g if k.startswith("__import_")}, set())`
> tautological one line after `_hide_leaked_dynamo_globals()`, whose whole job is
> popping every `_MINTED_PREFIXES` name?** It is the only assertion in the test
> that is not vacuous if that helper stops popping the `__import_` family.
> Measured: with `__import_torch_dot_nn_dot_modules_dot_module` bound in the
> module dict after the helper runs -- exactly what a helper that no longer pops
> that prefix leaves behind -- the load seeds nothing
> (`EXPERIMENT seeded by load: set()`) and the main assertion below still passes,
> `Ran 1 test ... OK`, covering nothing. Put the line back in and the same run
> goes red: `AssertionError: Set comparison failed: Items in the first set but
> not the second`. That is the vacuity the commit message calls out ("a load that
> finds them already there seeds nothing, so a pin on what the load wrote would
> be vacuous"), and this line is what rules it out.

> **FAQ: `torch.compile(later, ...)` discards its wrapper, so shouldn't a comment
> record the hidden invariant that a `CleanupHook` cannot fire and empty `after`?**
> There is nothing hidden left to document once it is measured: two forced full
> collections inserted immediately before the read leave the name in place
> (`EXPERIMENT after gc: installed = {'__builtins_dict___1'}`, test OK), for the
> reason the review itself gives -- the hook is keyed on the output code object
> held by `later.__code__`'s `ExtraState`, and `later` is a live local through the
> assertion. Adding an explanation of why an unreachable failure is unreachable, in
> the same review that asks for roughly 40 comment lines to come down, would trade
> a real cut for a speculative one; the block instead lost nine comment lines. If
> the hook ever could fire the assertion is loud, not silent: it names the key set
> it read.

> **FAQ: Isn't the 101-column f-string at `:864` over B950's ~96-column ceiling
> at `line-length = 88`?** B950 is enforced by nothing in this repo:
> `.flake8:25` lists `B950` under "Codes where ruff is the source of truth", and
> ruff does not implement B950 (its `select` takes `B` and `E`, with `E501`
> explicitly ignored at `pyproject.toml:484`). `lintrunner --take RUFF,PYFMT` and
> `lintrunner --take FLAKE8` both report `ok No lint issues` on the file at HEAD,
> and 18 lines in this same file already exceed 96 columns before this commit
> touches it. The rewrite of the assertion shortened the message anyway, to 81
> columns.

> **FAQ: Should the colliding compile be wrapped in
> `patch.object(bytecode_transformation, "_unique_id_counter", itertools.count())`
> so the mint lands at index 0 regardless of how many ids the load burned?**
> The determinism problem is real and is fixed, but not with a counter that
> starts at 0 -- that fixes only the loading side. Measured: with the suggested
> `itertools.count()` in place and one `unique_id` burned in the LOAD path, the
> test passes; with the same fix and two ids burned in the CAPTURE path, it fails
> again, `expected a name collision: seeded={'__builtins_dict___1'},
> minted=['__builtins_dict___0', ...]`, because the artifact's baked-in index
> moved and the fresh counter still starts at 0. The counter is therefore rewound
> to the index read off the name the load actually seeded
> (`itertools.count(int(taken.rpartition("_")[2]))`), which is green under a burn
> on either side and still red under the mutation it targets.

> **FAQ: The three-line alias derivation (`guarded = set(import_sources) &
> set(...global_scope)`, `assertLess`, `(alias,) = guarded`) is duplicated
> verbatim across the two tests, with its rationale comment restated too --
> shouldn't it be one helper on the test class returning `(import_sources,
> guards_state, alias)`?** The idiom appears exactly twice in the file, and
> only one of the two is this commit's:
> `test_aot_compile_module_import_alias_guard_loads_across_processes`
> (`:3531-3536`, added here) and
> `test_load_seeds_exactly_the_recorded_globals` (`:4189-4194`), which is
> already present at this commit -- `git log -S` puts it in #196817, six
> commits down. The shared helper therefore cannot live here at all: it would
> be a new `TestAOTCompile` method added in #196817 and called once from each
> of two PRs, to save three lines. Those three are not character-for-character
> identical either -- the first two are, the third binds a different name
> (`(alias,)` vs `(kept_alias,)`), because #196817's test keeps that name live
> for another thirty lines, where "kept" is what distinguishes the guarded
> alias from the sentinel the test deliberately writes over it (`:4221`,
> `:4223-4229`). The requested return tuple also absorbs two lines that are
> not shared behaviour: #196817's test reads `builtins_key` off `guards_state`
> BEFORE the derivation (`:4186`) and checks a caller-supplied `scope`, while
> this one reads it after and checks live `globals()`. And the middle line is
> an assertion; moving `assertLess` into a shared helper reports the failure
> from the helper instead of from the test whose premise -- the artifact
> records more aliases than any kept guard reads -- it exists to pin. The
> rationale is not duplicated one-for-one either: only the "pruned to exactly
> the guarded names, rather than off `import_sources`' order" clause is
> common. This test's comment is four lines because it carries a reason the
> other has no room for (assert on what the load wrote into this live
> namespace, "not against the artifact re-filtered by the gate under test",
> and not off a literal, an alternative that only exists when the target is
> `globals()`); #196817's is two. Weighed against the repo's style rule -- do
> not add trivial one-or-two-line helpers used once unless they significantly
> improve readability, and when uncertain choose the simpler, more concise
> implementation -- a cross-PR helper wrapping five lines with two call sites
> and two different downstream shapes is the more expensive of the two options
> to read, so the derivation stays inline and identical, which was the
> substance of the earlier request.

> **FAQ: `model(torch.randn(4, 4))` in `_subprocess_load_then_compile` discards its
> result, and the seeding it looks like it triggers already ran in `__post_init__`,
> so `seeded` is populated with or without it -- either drop the line or give it
> the one-line reason?** The reason is now on it, at `:812-813`: `# The only serve
> of the loaded artifact: a guard rooted at a name the load failed to seed raises
> HERE, not at any assertion below.` Dropping it is the half the measurement rules
> out. It is the test's only call on the loaded artifact, and
> `AOTCompiledModel.__call__` raising on a guard miss (`aot_compile.py:1421-1426`)
> is the assertion. One mutation at a time in a scratch copy, each run with the
> line deleted and then restored: pop the two `__import_*` aliases the kept guards
> are rooted at back out at the end of `_seed_guard_scope`, and without the line
> the test is green, `Ran 1 test ... OK`, while with it it is red -- `RuntimeError:
> GuardManager check failed, reason: GuardDebugInfo(verbose_code_parts=["KeyError
> on G['__import_torch_dot_nn_dot_modules_dot_linear']"], ...)` (the per-input
> report that spells this `[0] KeyError on G[...]` arrives with #196823). Seed the
> builtins key to the wrong dict and the split repeats: green without the line,
> `KeyError on G['__builtins_dict___0']['isinstance']` with it. Nothing else here
> reaches either class -- `:896-902` checks only that the key is BOUND, not that
> anything resolves through it, and `:936-942` reads the mint `later`'s own compile
> made, whose guards are rooted at nothing the artifact seeded -- and no sibling
> does either: `:3509` captures under `keep_global_guards`, which drops
> BUILTIN_MATCH.

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

Pull Request resolved: #196821
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196767, #196817, #196815, #196816, #196818, #196819, #196820
pytorchmergebot pushed a commit that referenced this pull request Sep 14, 2026
`CompilePackage._install_global` appended every name it wrote to
`_installed_globals`, and `uninstall()` pops every recorded name. So the
bookkeeping recorded which names the package TOUCHED but never which of them it
CREATED, and uninstall deleted bindings the package had merely overwritten:

```python
def _install_global(self, module, name, value):
    CleanupHook.disown(module.__dict__, name)
    module.__dict__[name] = value
    self._installed_globals.setdefault(module, []).append(name)   # recorded whether or not it was already bound
```

That is reachable, and the loss is permanent. `AOTCompiledFunction._seed_guard_scope`
seeds the recorded `__import_*` aliases a kept guard is rooted at into the live
module scope those guards then resolve against BY REFERENCE, and deliberately
leaves an already-bound name alone. A `CompilePackage` that installs the same
alias into the same module afterwards is not the binding's owner, but
`uninstall()` deleted it anyway, and nothing re-seeds:

```python
# mypkg/model.py defines M, whose forward calls a child module, so a kept guard is rooted at
# G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks

loaded = torch.compiler.load_compiled_function(f, f_globals=vars(mypkg.model))
"__import_torch_dot_nn_dot_modules_dot_module" in vars(mypkg.model)   # True: the load seeded it
loaded(x)                                                             # serves

pkg.install(backends)     # a package for another function traced in mypkg.model installs the same
                          # alias: the identical module object, but the name was RECORDED
pkg.uninstall()           # popped it

loaded(x)
# RuntimeError: GuardManager check failed, reason: ...
#   KeyError on G['__import_torch_dot_nn_dot_modules_dot_module']
# on every call from now on: the guards read the dict live and nothing puts the alias back
```

## The fix: an ownership token, scoped to the aliases

The fix is in the bookkeeping rather than in `uninstall()`: `_install_global`
grows a `record_only_if_new` flag, and the alias loop in `install()` is its one
caller. For those names it reads the module dict before it writes and records
the name only when it was absent, so uninstall pops exactly the aliases this
package created:

```python
def _install_global(self, module, name, value, *, record_only_if_new=False):
    CleanupHook.disown(module.__dict__, name)
    record = not (record_only_if_new and name in module.__dict__)   # read BEFORE the write
    module.__dict__[name] = value
    if record:
        self._installed_globals.setdefault(module, []).append(name)

# install(): the one caller
for alias, module_name in entry.import_sources.items():
    self._install_global(module, alias, importlib.import_module(module_name), record_only_if_new=True)
```

The write itself and the `CleanupHook.disown` call above it are unchanged:
taking over the binding is still right, and for an alias the value being
installed is the identical module object anyway. `disown` only drops a stale
hook's claim on the name, never the binding, so reading the dict after it is
correct.

Gating EVERY install is the obvious reading and it is wrong. A package installs
into the very module its trace ran in, so wherever that trace's own bindings
are still live, the code and backend globals `install()` is about to mint are
already bound:

```python
compiled = torch.compile(fn)(x)      # the trace binds __compiled_fn_0, __resume_at_*, ... in vars(mypkg.model)
pkg.save(...); pkg = load(...)       # same process, no reset() in between to collect them
pkg.install(backends)                # gated everywhere: every name is already bound, NONE is recorded
pkg.uninstall()                      # removes nothing at all
```

Aliases are the only names anyone else can bind first, and the only names both
`install()` records and `_seed_guard_scope` writes (the builtins-dict key both
also write bypasses `_install_global` and is never recorded), so they are the
only names that need the check. `install()`'s builtins-dict branch writes
`runtime_global_scope[builtin_dict_name]` directly rather than through
`_install_global`, so that key was already never removed by `uninstall()` and
is unaffected.

## What changes in-process, and what is deliberately left alone

First binder owns the alias, which also changes an in-process case: a trace
leaves its own `__import_*` aliases bound in the module, so a package installed
in that same process no longer records them and no longer removes them on
uninstall. The next install overwrites the values, so nothing goes stale.

The reverse direction is deliberately not addressed here. If the PACKAGE binds
an alias first and a later artifact load piggybacks on that binding,
`uninstall()` still removes it and every call into the loaded artifact then
fails with the same `KeyError`:

```python
pkg.install(backends)                                             # the package binds the alias first, and records it
loaded = load_compiled_function(f, f_globals=vars(mypkg.model))   # seeding finds it bound, leaves it, guards hold it
pkg.uninstall()                                                   # pops it
loaded(x)                                                         # KeyError on G['__import_...'] again
```

Distinguishing that from ordinary package cleanup needs refcounting across
owners, which is a larger change than the bug in front of us.

Never recording an alias at all would cover both orders with no refcounting,
and that is the trade deliberately not taken. `install()` writes into a USER
module's live `__dict__` and `uninstall()` is the only thing that ever takes
those names back out, so a package that records none of its aliases can only
ever add to that namespace (measured, the helper module the new test traces
keeps five permanent `__import_*` names, not one). The leftover is not inert
either, because it is the binding every later owner defers to: a load seeds an
alias only into a scope that does not already bind it, so an alias one package
leaks is the object every later load into that module inherits in place of the
one it would have seeded. Recording a name the package did not create is the
bug being fixed; refusing to record one it did create is the same inaccuracy
pointed the other way.

Test Plan:

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

The new case, which drives the real path end to end -- a helper module in a
temp file, an artifact saved with a `guard_filter_fn` that keeps global guards,
a fresh import of the helper so the alias starts unbound, a load that seeds it,
then a package install/uninstall cycle -- and then calls the artifact. It pins
both arms of the record: the seeded alias survives uninstall, and a second
cycle in another freshly imported module, where the alias is still unbound
when install() runs, has the package create the alias and uninstall() take it
back out. The backend ids go through the default `record_only_if_new=False`,
so they are recorded and removed either way, which pins the gate's scope
rather than a second arm of it.

```
python test/dynamo/test_package.py -k test_uninstall_keeps_a_global_it_did_not_bind
```

Both arms are proven load-bearing by mutation. Recording unconditionally
(`record = True`) fails at the post-uninstall assertion with
`AssertionError: '__import_torch_dot_nn_dot_modules_dot_module' not found in
{...}`, and calling the loaded artifact under that mutation reproduces the
`KeyError on G['__import_torch_dot_nn_dot_modules_dot_module']` guard failure
above. Never recording (`record = False`), which is what gating every install
degenerates to once the names are already bound, fails at the post-uninstall
`AssertionError: Set comparison failed: Items in the first set but not the
second: '__compiled_fn_3_741f6201_...'` -- the leak the alias-only gate avoids.
Never recording an ALIAS in particular (`record = not record_only_if_new`), an
alias the package itself minted leaking into a user module's namespace forever,
fails the second cycle's post-uninstall `AssertionError:
'__import_torch_dot_nn_dot_modules_dot_module' unexpectedly found in {...}`.
Without that second cycle the mutation passed all 75 tests in the file, which
is why it is there.

A `guard_filter_fn` that keeps global guards is load-bearing in the test rather
than decoration: under the default filter the serialized `global_scope` is
pruned to `__builtins_dict___N` alone, nothing is seeded, and the collision
cannot be constructed at all.

```
lintrunner --take RUFF,PYFMT torch/_dynamo/package.py test/dynamo/test_package.py
lintrunner --take PYREFLY torch/_dynamo/package.py
```

Authored with the assistance of Claude Code.

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

## FAQ

> **FAQ: The `guard_filter_fn` closure in the new test duplicates
> `keep_global_guards` in `test/dynamo/test_aot_compile.py:633-644` line for line
> -- keep one copy, not two.** The predicate is identical and the shared form does
> work: a scratch copy of this file with the closure at `:618-626` deleted and
> `keep_global_guards` imported instead passes, `Ran 1 test in 0.384s ... OK`, and
> it stays mutation-sensitive -- with `record_only_if_new` forced back to `False`
> it fails at the same line, `AssertionError:
> '__import_torch_dot_nn_dot_modules_dot_module' not found in {...}`. So this is
> not a vacuity argument; the cost is the import itself. `test/dynamo/__init__.py`
> exists, so pytest imports this file as `dynamo.test_package` with `test/dynamo`
> off `sys.path`, and the bare `from test_aot_compile import keep_global_guards`
> takes the whole file down at collection: `python -m pytest -q --collect-only` on
> that copy reports `ModuleNotFoundError: No module named 'test_aot_compile'` and
> `no tests collected, 1 error`, against `75 tests collected` for the file as
> written. Surviving both import modes needs the try/except relative guard the
> cross-file importers under `test/dynamo` carry --
> `test_inline_and_install.py:7-10` and `test_dynamic_shapes.py:10-34` re-derive
> test classes that way, and `test_global.py:15-18`,
> `test_nested_graph_breaks.py:11-14`, `test_ctx_manager.py:34-37` and
> `test_modules.py:37-40` import helpers -- so the precedent exists; this file's
> own convention is per-test closures, and the import would also converge nothing:
> `test_package.py` has five local `guard_filter_fn` closures (`:416`, `:654`,
> `:769`, `:1054`, `:1272`), and `:416`/`:1054`/`:1272` are already byte-identical
> to each other and predate this commit -- a per-test closure is this file's
> convention, and the triplicate in it is not what the dedup touches. The one
> module both files already import, `torch/_dynamo/testing.py`, ships in the wheel
> and holds no guard filter today; putting one there also means editing
> `test_aot_compile.py`, which this commit does not touch.

> **FAQ: The deferred reverse order should just be fixed by never recording an
> alias at all -- `record = not record_only_if_new` covers both orders with no
> refcounting and no leak beyond one extra dunder name in a user module's
> `__dict__` -- so what is the argument for keeping the removal?**
>
> Both halves of that measured out, and the argument is the leak, which is
> neither one name nor inert. The reverse order is real: driving it end to end
> (a package installs into a freshly imported helper module,
> `load_compiled_function` piggybacks on the alias it bound, then
> `uninstall()`) the call reports `RuntimeError: GuardManager check failed,
> reason: ... KeyError on G['__import_torch_dot_nn_dot_modules_dot_module']`,
> the same failure this commit fixes in the other order, and the mutation does
> fix it -- the alias survives uninstall and the loaded artifact returns the
> eager result. What it costs is that `install()` writes into a USER module's
> live `__dict__` (`torch/_dynamo/package.py:1303`,
> `sys.modules[entry.python_module]`) and `uninstall()` (`:1275-1277`) is the
> only thing that ever takes those names back out, so a package that records
> none of its aliases can only ever add to that namespace. Measured on the
> helper the new test traces, whose traced function is one `nn.Module` call:
> `aliases install() writes: 5`, and after an install/uninstall cycle under the
> mutation `names left in the user module after uninstall: 6` --
> `__import_torch`, `__import_torch_dot__dynamo_dot_graph_bytecode_inputs`,
> `__import_torch_dot__dynamo_dot_utils`,
> `__import_torch_dot_autograd_dot_profiler`,
> `__import_torch_dot_nn_dot_modules_dot_module`, plus the pre-existing
> `__builtins_dict___0` this commit already accounts for. Unmutated, the same
> script reports `names left in the user module after uninstall: 1`, that
> builtins key alone. The leftover is not inert either, because it is the
> binding every later owner defers to: `_seed_guard_scope` seeds an alias only
> into a scope that does not already bind it
> (`torch/_dynamo/aot_compile.py:758`), deliberately -- "A binding this process
> already had is left alone" (`:702`) -- and measured, a load into a scope
> where the alias is already bound leaves that value in place and reads the
> artifact's guards through it: with a stand-in module of the right `__name__`
> in the slot the load leaves it there and the call fails `getattr failed on
> source
> G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks`. So
> an alias a package leaks is the object every later load into that module
> inherits in place of the one it would have seeded, and it is the right object
> only for as long as nothing rebinds `sys.modules` under it. Keeping the
> removal is what stops "first binder owns the alias" from degenerating into
> "the first package ever installed here owns it forever", and keeps the
> bookkeeping honest in both directions: recording a name the package did not
> create is the bug being fixed, and refusing to record one it did create is
> the same inaccuracy pointed the other way. The reverse order stays open for a
> change that can tell two owners apart, i.e. refcounting; the deferral in the
> body now carries this argument next to it.

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

Pull Request resolved: #196895
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196767, #196817, #196815, #196816, #196818, #196819, #196820, #196821
pytorchmergebot pushed a commit that referenced this pull request Sep 15, 2026
…ls too (#196904)

A load re-derives the serialized `__builtins_dict___N` key over the live
builtins whenever the value bound there is the artifact's own recording,
because the guard rooted at that key is an ID_MATCH on a builtin and a
pickle-filtered snapshot goes on passing after the builtin it read is rebound.
But two dicts can be holding that recording, and only on the default path are
they one: the guard scope, which the deserialized guard tree reads, and
`fn.__globals__`, which is what the generated bytecode subscripts.

```python
def fn(x):
    if isinstance(x, torch.Tensor):    # BUILTIN_MATCH guard rooted at G['__builtins_dict___0']
        return len                     # `len` survives into the bytecode: G['__builtins_dict___0']['len']

loaded = AOTCompiledFunction.deserialize(data)          # default path
loaded.fn.__globals__ is <guard scope>                  # True: one dict, one re-derive covers both
```

`_seed_guard_scope` visited only the guard scope. So every load whose scope is
not `fn.__globals__` left the guards checking the live builtins while the
bytecode went on reading the load-time recording:

```python
load_compiled_function(f, f_globals=d)                     # guards read d, bytecode reads fn.__globals__
AOTCompiledFunction.deserialize(data, guard_globals=d)     # same split
AOTCompiledModel.deserialize(model, data)                  # the COMMON case: the guard scope is
                                                           # model.forward.__globals__, and with no f_globals
                                                           # forward_callable builds fn.__globals__ as a dict of its own

scope[builtins_key] is builtins.__dict__                   # True:  the guards see live builtins
loaded.fn.__globals__[builtins_key] is builtins.__dict__   # False: the bytecode still reads the recording
```

An artifact naming a builtin the loading process no longer has could then pass
its guard check and serve a value out of the stale recording: the guard
certified one dict and the code ran off another.

```python
# the tracing process had builtins.aot_probe = os.getcwd; the loading process does not
loaded(x)
# parent: the bytecode reads G['__builtins_dict___0']['aot_probe'] from the RECORDING and returns os.getcwd
# now:    KeyError: 'aot_probe' out of the generated bytecode, exactly as on the default-path load
```

## Iterate the scopes, derive each from its own `__builtins__`

```python
scopes = [(guard_scope, where)]
if self.fn.__globals__ is not guard_scope and snapshot is not None:
    scopes.append((self.fn.__globals__, "f_globals"))

for scope, where in scopes:                              # every scope validated BEFORE anything is written
    bound = scope.get("__builtins__", builtins.__dict__)
    if not isinstance(bound, (dict, types.ModuleType)):
        raise TypeError(f"{where}['__builtins__'] must be a dict or a module, got {type(bound).__name__}")
...
for scope, _ in scopes:
    if builtins_key in scope and (snapshot is None or scope[builtins_key] is not snapshot):
        continue                                         # a binding this process chose stays
    if "__builtins__" not in scope:
        scope["__builtins__"] = builtins.__dict__
    scope[builtins_key] = get_builtins_dict(scope)       # from THIS scope's own __builtins__
```

The re-derive now iterates the scopes rather than the one, adding
`fn.__globals__` when it is a different object and there is a recording there
to replace (it needs no `__builtins__` seeding of its own), and derives each
scope's key from that scope's OWN `__builtins__`, so a guard-only scope still
cannot rewire what the bytecode resolves. The identity test against the
snapshot is unchanged: a caller who pre-bound the key in either dict keeps
their choice.

The `TypeError` naming which parameter a bad `__builtins__` arrived by is
computed per scope, keeping the existing answer for the guard scope (where
`load_compiled_function` forwards one dict as both and the public name wins, and
a module's namespace is named `vars(<module>)`) and naming `f_globals` for the
bytecode's, since that is the only parameter that reaches it. That second
`TypeError` is a new refusal:

```python
AOTCompiledFunction.deserialize(data, f_globals={"__builtins__": None}, guard_globals={})
# parent: loaded, serving off the recording with None still bound
# now:    TypeError: f_globals['__builtins__'] must be a dict or a module, got NoneType
```

## Why a separate commit

#196815 made this split reachable on its parent through
`deserialize(..., guard_globals=)` and, once it forwards the caller's dict as
both scopes, through `load_compiled_function` too, and the arm it added to
`test_load_rederives_over_a_builtin_the_loading_process_lacks` pinned it as
behaviour: live builtins in the caller's dict, the recording still in
`fn.__globals__`. (The known limitation its docstring and guide name is a
different divergence, a rebind the guards accept, which #196897 closes.) This
is a separate commit because closing the split flips that arm, so the re-slice
below stays reviewable as the re-slice it is.

Test Plan:

`test_load_rederives_a_builtins_key_bound_to_its_own_snapshot` gains the
bytecode's side of both branches of the "key already bound" check: its
caller-supplied-guard-scope arm now asserts `loaded.fn.__globals__[builtins_key]
is builtins.__dict__` as well as that the caller's own binding survives in the
guard scope, and a new arm loads the same bytes twice into one dict passed as
both `f_globals` and `guard_globals` -- `forward_callable` lets `f_globals`
override the recording, so the first load takes the derive branch and the second
finds the key bound -- requiring the two to agree on what the bytecode reads.
The last arm of `test_load_rederives_over_a_builtin_the_loading_process_lacks`
asserted the divergence; it now pins the unified behaviour, raising
`KeyError('aot_probe')` out of the generated bytecode exactly like the no-scope
arm above it, since the builtin is genuinely gone on both sides.

`test_aot_compile_module_load_rederives_the_key_the_bytecode_reads` pins the
module path: a module whose forward returns `len` is captured under
`keep_builtin_guards`, saved and loaded through `_load_aot_compiled_module`, and
both the module namespace and `fn.__globals__` must bind the live builtins under
the key. `test_load_refuses_a_non_dict_builtins_binding` gains a fourth arm,
`deserialize(data, f_globals={"__builtins__": None}, guard_globals={})`,
expecting the `f_globals`-named `TypeError`; its `fn` now returns `len` so the
bytecode reads the key. The caller-chosen-guard-scope arm of
`test_load_rederives_a_builtins_key_bound_to_its_own_snapshot` re-asserts the
`fn.__globals__` identity after the call, pinning that `_serve`'s per-call
re-read (#196897) leaves the key alone. With the parent's `aot_compile.py` the
module test fails with `AssertionError: False is not true : the bytecode kept
the recording on the module load path` (its module-dict assertion passes) and
the fourth arm with `AssertionError: TypeError not raised`.

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_load_rederives_the_key_the_bytecode_reads
python test/dynamo/test_aot_compile.py -k test_load_refuses_a_non_dict_builtins_binding
python test/dynamo/test_aot_compile.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py
```

`Ran 226 tests ... OK (skipped=6)`, `OK (skipped=40, expected failures=1)` and
`Ran 143 tests ... OK (skipped=3)`, unchanged from the parent.

The tests discriminate the change. Reverting only `aot_compile.py` and re-running
the two:

```
git checkout HEAD~1 -- torch/_dynamo/aot_compile.py
python test/dynamo/test_aot_compile.py -k test_load_rederives_a_builtins_key_bound_to_its_own_snapshot
python test/dynamo/test_aot_compile.py -k test_load_rederives_over_a_builtin_the_loading_process_lacks
git checkout HEAD -- torch/_dynamo/aot_compile.py
```

fails with `AssertionError: False is not true : the bytecode kept the snapshot
under a caller-chosen guard scope` and `AssertionError: False is not true : the
bytecode kept the recording under a caller-supplied f_globals`. Dropping the
first of those assertions as well so the arms below it run, the two-loads arm
fails on its first pass with `AssertionError: False is not true : the bytecode is
reading a dict this load chose the order of`, and dropping the second leaves the
rewritten divergence arm failing with `AssertionError: KeyError not raised` --
the parent serves `os.getcwd` there out of the recording.

```
lintrunner --take RUFF,PYFMT -- torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py
```

reports `ok No lint issues.`, and no added line exceeds 88 columns.

This change was authored with the assistance of an AI coding assistant.

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

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

Pull Request resolved: #196904
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196767, #196817, #196815, #196816, #196818, #196819, #196820, #196821, #196895
pytorchmergebot pushed a commit that referenced this pull request Sep 15, 2026
…falling through (#197055)

`AOTCompiledModel.__call__` fell through to `compiled_results[0]` once every
guard failed, so whether the caller saw an error at all turned on the order of
the list: `compiled_results[0]` re-raised only because its guard check was
still enabled, and had that one result opted out of guard checking it would
have run instead. A match was not cheap either: `result()` re-entered
`AOTCompiledFunction.__call__`, which bound the call and ran the guards
`guard_check` had just passed, so a matching tree was bound and evaluated twice
per call.

Dispatch now has two explicit stages ahead of the fall-through: scan every
result for a guard match, then re-check every result. Only a call neither stage
serves reaches the parent's fall-through into `compiled_results[0]`, which is
kept as it was: it raises the same `GuardManager check failed` error the parent
raised unless `compiled_results[0]` opted out, in which case it runs, as it did
at the parent. There is no behaviour change vs the parent on a no-match call.
Measured on a two-input `ScaleModule` (float32 and float64) called with
float16, each result's `fn` wrapped to record which one served, the parent and
this commit give the same four rows:

```
[enabled, enabled]     : RuntimeError: GuardManager check failed ...
[enabled, opted_out]   : RuntimeError: GuardManager check failed ...
[opted_out, enabled]   : SERVED by [0]
[opted_out, opted_out] : SERVED by [0]
```

`test_module_dispatch_no_match_falls_through_to_the_first_result` pins three
of those rows without a mock, on a two-input `ModeBranchGlobalModule` whose
graphs differ (`x * 2` for `mode == 0`, `x * 3` for `mode == 1`) called with
`mode=2`, so the number says which result answered: with nothing opted out the
call raises `GuardManager check failed`, with `[0]` opted out it is served
`[0]`'s `x * 2`, and with both opted out still `[0]`'s. The fourth row,
`[enabled, opted_out]`, is the one the commit that honours an opt-out from any
position changes from raise to serve; pinning it here as a raise would make
that commit red on a test it has to rewrite, so it is measured above and
pinned there, from the other side, as a serve. Honouring an opt-out from any
position rather than from `compiled_results[0]` alone is a behaviour change
and is that later commit's, with its own test and its own `## Behaviour
change` statement; a report that names every compiled input replaces the
fall-through later still.

The scan cannot skip opted-out results even though they accept anything: guard
evaluation happens regardless of the flag, so scanning them first still finds
the right graph, and skipping them would reinstate the old fall-through when
every result has opted out. On a match, the declared `fn` field is called
directly rather than `result()`, which saves re-binding and re-evaluating the
guards that just passed: one bind and one evaluation of a matching tree per
call, where `result()` made two of each.
`test_module_dispatch_evaluates_a_matching_tree_once` counts the `check()`
calls dispatch makes on the matching tree and expects one; the parent makes
two. Measured on this machine with the parent's dispatch replicated in the
same process and the two timed interleaved (best of 15 x 2000 calls), a call
matched at `compiled_results[0]` costs 23.3us against the parent's 29.4us, a
match at `[1]` of two 28.2us against 34.1us, and a match at the fourth of four
inputs 32.9us against 38.9us.

Each result is bound on its own, ahead of its guards, and the binding is kept
for the re-check. The bind is the first thing the scan does, so a call the
signature cannot bind is left alone: it still surfaces as a `TypeError`, as the
plain module call would -- the type matches, though the message is `inspect`'s
rather than `nn.Module`'s -- instead of a guard error about a call the guards
never saw. The test for it sits with the commit that first moves the guard
check inside a `try`, where its placement could break it.

Because `compiled_results` is a public list the docs teach callers to index
into, a call reads it once: `__call__` snapshots `results =
tuple(self.compiled_results)` before anything else and both stages iterate the
snapshot, so the re-check pairs every result with the binding the scan made for
it and never reaches a result the scan did not bind.
`test_module_dispatch_judges_only_the_results_a_call_began_with` makes `[0]`'s
`check()` splice in a `[1]` that matches the call: with the snapshot that call
falls through and raises and the next call serves `[1]`; a scan over the live
list serves `[1]` on the same call.

The re-check is what keeps the fall-through last, and it exists for exactly one
exit of `check()`. In `GuardManager::check_nopybind` (guards.cpp) a tag-safe
root whose recorded dict tags and tensor metadata still match runs
`check_no_tensor_aliasing_guards_fast`, and when that answers false the node
sets `_disable_dict_tag_matching` and returns false before
`check_nopybind_template` runs; that is the only path on which a false is not
the tree's answer about the call. The fast path's other exits -- a tag or
tensor-metadata mismatch, the cap on recorded pointers -- set the same flag
and fall out of the `if` into the tree, so their false is genuine. The flag is
a per-`GuardManager` member that nothing resets (`= false` at its declaration
is the default initializer; every other write sets it true), so a second
`check()` runs the tree the fast path skipped, and a sibling tag-safe root the
first pass never reached stays armed and can still answer from its own fast
path. Tag-safe roots exist only under `use_recursive_dict_tags_for_guards`,
which `finalize()` gates `find_tag_safe_roots` on and which defaults to False.
That rescue is exactly what the old fall-through got from re-entering
`AOTCompiledFunction.__call__` on `compiled_results[0]`, here extended to every
result, so nothing that used to be served is refused
(`test_module_dispatch_serves_a_call_the_guard_tree_accepts`). Ordering matters
more than it looks: an opted-out `compiled_results[0]` runs whatever the
fall-through hands it, so without the re-check a call whose `[1]` was falsely
rejected once is silently served `[0]`'s graph, compiled for a different call,
in exactly the case the parent's fall-through got right because it re-checked
`[0]` before it gave up; `test_module_dispatch_rechecks_before_honouring_an_opt_out`
pins that. The re-check covers opted-out results too, and for the scan's
reason: a scan `check()` that refused from the fast path is no more an answer
about an opted-out tree than about an enabled one -- `check()` never reads the
flag -- so with `[opted_out, opted_out]` and a false rejection of the second,
skipping it falls through to the first one's graph over a tree whose guards
genuinely fail; `test_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts`
opts both results out and misses `[1]`'s global once. The three re-check tests
force the false rejection with a `CountedKey` spliced into this module's
globals that misses the guarded global once, and count the `check()` calls
dispatch makes on `[1]`'s tree, expecting two: the scan's rejection and the
re-check's acceptance.

Under the default config no root is tag safe, so a first `check()` can only
refuse after running the tree and the re-check re-runs trees that have
genuinely failed. Two things follow that the code comment names. Whatever
Python those trees run runs again: `LAMBDA_GUARD` closures and the root's
`_epilogue_lambda_guards`. And a node that fails an evaluation adds one to its
own `_fail_count` (in `check_leaf_guards_nopybind` and
`check_accessors_nopybind`), which its parent's fail-fast sort orders
accessors by, so a result that fails a no-match call through module dispatch
counts that failure twice where a direct `AOTCompiledFunction.__call__` counts
it once; both evaluations fail at the same node, so the double count changes
how far that node rises, not which node fails. Such a tree still
short-circuits at its first failing guard, so the
second pass costs 3.2us for two results and 4.6us for four (the no-match call,
which then raises, measures 32.6us and 43.7us here against 29.4us and 39.1us
with the second pass deleted, and against the parent's 30.2us and 38.5us).

Running `check_verbose` as the second pass, so that its answer could double as
the failure's explanation, was rejected: an opted-out `compiled_results[0]`
makes the guards fail on every call by construction, so dispatch ends at the
fall-through serving it and no explanation is ever printed, and `check_verbose`
costs about 2.7x a `check()` per tree (2.55us against 0.94us here).

`guard_check` and the function path's `__call__` route their own
`guard_manager` narrowing through the new `_live_guard_manager()` rather than
restating it, and the dispatch reads its manager the same way. That moves one
dead state: `__call__` asserted on a null `guard_manager` before it read
`_guard_check_enabled`, so an artifact that had opted out raised there and now
runs instead. `__post_init__` always populates the field -- only `serialize()`
nulls it, and on a copy -- so reaching that state takes assigning the private
field by hand, and both paths that do read the manager still raise.

The module dispatch's semantics are documented in a docstring on
`AOTCompiledModel` itself, where a reader who holds one finds them, as one
paragraph later commits extend a sentence at a time. It says what each stage
does and what the fall-through does when neither accepts: the call is handed to
`compiled_results[0]` as a plain call of that function, which raises unless
that one result opted out, in which case its graph runs for a call its guards
refused; that is the only thing `disable_guard_check()` changes on this path,
since `check()` never reads the flag and an opted-out result is scanned,
re-checked and served in index order like any other. It names the one
`check()` exit the re-check exists for, and it states that `compiled_results`
must hold at least one result: `aot_compile_module` refuses an empty list, but
neither the public constructor nor `deserialize` checks, and an empty list
reaches the fall-through's `results[0]` as it did at the parent. The user
guide is not touched.

The three probe tests now start with `_hide_leaked_dynamo_globals()`, as the
other compile tests in the class do, so they no longer leave Dynamo's synthetic
globals in this module's dict. `_install_global_probe` registers both cleanups
before it touches the dict, so an interrupt anywhere leaves the name restored,
and its comment says why the probe must be installed after
`_hide_leaked_dynamo_globals`, whose sweep calls str methods on every key.
`CountedKey.__eq__` answers True for itself before it counts, so the probe's
own cleanup pop does not rest on the dict's identity-first lookup.

> **FAQ: Why does this commit leave the `disable_guard_check()` bullet of the
> user guide alone?** An earlier version extended it to say the compiled
> function "runs whatever it is called with, without evaluating its guards".
> That is what the function path does, but `disable_guard_check()` is a method
> on `AOTCompiledFunction`, which is what `compiled_results` holds, and on the
> module path this commit defines an opted-out result's guards are evaluated
> for dispatch, so the sentence was false for one of the two paths that share
> the method. Scoping it to the function path would have to name module
> dispatch, which the page does not document (`_aot_compile` is private and its
> docstring says Experimental). The parent's bullet, "Disable runtime guard
> validation (advanced use)", holds for both paths and stays; the module
> semantics live in the class docstring.

> **FAQ: Why is the re-check not gated on whether the tree has an armed
> tag-safe root?** Recording the gate is cheap, granted: `find_tag_safe_roots`
> materialises `tag_safe_roots` inside `finalize()`, so `bool(tag_safe_roots)`
> is one attribute on `GuardManagerWrapper`, decided once. It is declined for
> what it would buy and cost. It buys back 3.2us for two results and 4.6us for
> four on a call that then raises (or, once a later commit honours an opt-out
> from any position, runs a whole graph), and nothing on a match, which is the
> call every model is built for. It would make dispatch's correctness rest on a
> guards.cpp property read from Python -- "no tag-safe root means `check()`
> never refuses without running the tree" -- where the ungated re-check is
> correct whatever `check()` does; the gate would have to be re-derived every
> time the fast path grows an exit, and the reader of this file cannot see
> that. And the three re-check tests force a false rejection with a global
> lookup that misses once, which needs no tag-safe root; a gate would skip the
> re-check in exactly the configuration those tests run in, and pinning it
> would then take a real dict-tag false rejection, which is not deterministic
> to force. The code comment states instead that under the default config the
> pass re-runs trees that genuinely failed, what that re-runs and double
> counts, and that the cost is accepted.

> **FAQ: Why does dispatch call `prepare_f_locals`, `_live_guard_manager()` and
> `fn` itself rather than a method on `AOTCompiledFunction` for "run, guards
> already verified"?** `fn` is that method: it is the declared field the
> function path's `__call__` ends in (`return self.fn(*args, **kwargs)`), so a
> second name for it would be a one-line wrapper. The bind and the check are
> split because dispatch needs the binding after the check -- the re-check
> judges the same binding, and the binding-cache commit two above shares one
> binding across results -- so a method that hid the split would have to hand
> the binding back anyway; `prepare_f_locals` is the class's public method for
> it, and `_live_guard_manager()` is the narrowing this commit adds so all
> three readers of the field share one. The failure path, where
> `_missing_global_hint()` lives, is still `AOTCompiledFunction.__call__`'s
> alone and dispatch still reaches it, through the fall-through's
> `results[0](...)`; only the success path is open-coded here, and it is one
> line in both places.

> **FAQ: Where did the shared binding go?** The version reviewed last bound a
> call once and reused the binding across every result that binds alike,
> behind a cached verdict about `compiled_results`' contents. That is a
> performance change with a cross-thread publication protocol of its own, and
> the review asked for it to be reviewed against a single question; it is the
> binding-cache commit two above this one. Here every result binds on its own:
> a bind (`inspect.Signature.bind` plus `apply_defaults`) costs 2.5us against
> 0.9us for a `check()` on this machine, so a match at the fourth of four
> inputs pays three binds more than it will once the binding-cache commit
> lands.

> **FAQ: Does `CountedKey` rest on CPython dict internals?** On two documented
> behaviours, and on nothing about operand order. `str.__eq__` returns
> `NotImplemented` for a non-str, so `CountedKey.__eq__` runs whichever side
> the dict puts the stored key on (measured: `"k" == CountedKey("k", 1)` counts
> one comparison and answers False, the same as the reverse). The cleanup's
> `g.pop(probe, None)` finds the probe by identity, which `__eq__` now also
> answers True for, so it no longer rests on the lookup's identity-first
> order. And `check.call_count == 2` does not encode how many guards read the
> global: a lookup that misses fails the tree wherever it sits, so each
> `check()` consumes exactly one miss -- with `misses=2` the same model makes
> two `check()` calls on `[1]`, both refused, and the call raises from the
> fall-through (measured: `calls=2 compares=2 RAISED`, against `calls=2
> compares=2 SERVED` at `misses=1`). A one-shot in place of the counter is
> declined because the commit that replaces the fall-through with a report
> uses `misses=2` to pin that the report's `check_verbose` is the third and
> last evaluation.

> **FAQ: Why does `aot_compile_forward` take a `forward` and rebind it when the
> two calls here pass `ScaleModule.forward`?** The parameter compiles one
> module for a forward other than its class's, which is how the commits above
> assemble models whose results bind differently (a closure cell, a `mode`
> default); at this commit both calls pass the class forward, so the rebind is
> to itself, and the helper's comment says so. The helper is shared with those
> commits, so it is kept in the shape they call it in rather than inlined here
> and re-added above. `keep_global_guards` is another module-level helper
> without an underscore in this file, so the naming follows that.

> **FAQ: Why do the tests count `check()` calls rather than reads of the
> guarded global?** An earlier version counted the comparisons a `CountedKey`
> spliced into `globals()` saw, and asserted exact counts. Those counts were
> right only because CPython's dict lookup compares keys by identity before
> `__eq__`, and they encoded how many times the current guard tree happens to
> read one global, so a change of tree shape would have broken them without
> saying what regressed. The counts now wrap `check` on the result's
> `GuardManagerWrapper` (`patch.object(manager, "check", wraps=...)`) and
> measure dispatch's calls directly; `CountedKey` remains only where a false
> rejection has to be forced, answering False to the first `misses`
> comparisons.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_module_dispatch_evaluates_a_matching_tree_once
python test/dynamo/test_aot_compile.py -k test_module_dispatch_judges_only_the_results_a_call_began_with
python test/dynamo/test_aot_compile.py -k test_module_dispatch_serves_a_call_the_guard_tree_accepts
python test/dynamo/test_aot_compile.py -k test_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts
python test/dynamo/test_aot_compile.py -k test_module_dispatch_rechecks_before_honouring_an_opt_out
python test/dynamo/test_aot_compile.py -k test_module_dispatch_no_match_falls_through_to_the_first_result
python test/dynamo/test_aot_compile.py
lintrunner --take RUFF,PYFMT test/dynamo/test_aot_compile.py torch/_dynamo/aot_compile.py
```

This commit adds 6 `test_module_dispatch_*` tests, the last parametrized over
three opt-out rows; the full file runs 172 tests and passes (6 skipped) where
the parent runs 164. The first 5 fail at the parent, i.e. with the parent's
`torch/_dynamo/aot_compile.py` under this commit's test file: the counted
`check()` test with `Absolute difference: 1` (two calls where one is expected),
the mid-call splice test with `RuntimeError not raised` (the live list served
the spliced-in result on the same call), the fast-path rescue test with
`GuardManager check failed` raised where `[1]` should have been served, and the
two re-check ordering tests with `Mismatched elements: 9 / 9` (`[0]`'s `x * 2`
served). The three no-match rows pass at the parent, which is what they pin.
All 8 also pass with `torch._dynamo.config.use_recursive_dict_tags_for_guards
= True` set for the run, so no asserted count depends on the flag being off.
Lint is clean.

Mutation controls, each run against the 8 tests at this commit and each
failing only the tests named: calling `result()` in the scan instead of
`result.fn` fails the counted `check()` test with `Absolute difference: 1`;
deleting the re-check loop fails the fast-path rescue test (the fall-through
raises `GuardManager check failed`) and both re-check ordering tests
(`Mismatched elements: 9 / 9`); skipping opted-out results in the re-check
fails `test_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts`
alone; reading the live list instead of the tuple snapshot fails the mid-call
splice test with `RuntimeError not raised`; falling through into
`results[-1]` instead of `results[0]` fails the no-match rows with `[0]` opted
out (`GuardManager check failed` from the enabled `[1]`) and with both opted
out (`Mismatched elements: 9 / 9`, `[1]`'s `x * 3`) while the all-enabled row
still raises. The microsecond figures above were measured in one sitting on a
shared machine, the parent's dispatch replicated in the same process and timed
interleaved with this commit's.

Authored with the assistance of Claude Code.

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

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

Pull Request resolved: #197055
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196767, #196817, #196815, #196816, #196818, #196819, #196820, #196821, #196895, #196904
pytorchmergebot pushed a commit that referenced this pull request Sep 15, 2026
…196824)

Tests only, for the last-resort stage of the dispatch the previous commit
rewrote. `disable_guard_check()` is the escape hatch for an artifact whose
guards fail on the serving machine, and where an opted-out result sits in the
three-stage ordering decides answers that are wrong-answer bugs with no error
raised if the stages slip. Every case below is built so that the wrong stage
order returns a different NUMBER and nothing else.

## The fixture: same shapes, same dtypes, different numbers

```python
GLOBAL_POOLING_CONFIG = {"pooling": "sum"}

class GlobalConfigModule(torch.nn.Module):
    def forward(self, x):
        if GLOBAL_POOLING_CONFIG["pooling"] == "sum":
            return x.sum(1)
        return x.mean(1) * 10.0

model._aot_compile([
    ModelInput(args=(x,), kwargs={}, contexts=[_set_pooling("sum")]),    # compiled_results[0]
    ModelInput(args=(x,), kwargs={}, contexts=[_set_pooling("mean")]),   # compiled_results[1]
])
```

Both graphs accept a `(4, 8)` float tensor and differ only in what they return,
so a dispatch that picks the wrong one raises nothing and only `assertEqual`
against eager notices. Whether the global is GUARDED depends on the filter:
`keep_global_guards` keeps it, so each result matches only under its own mode;
the default filter drops it, so both results accept every call.

## Opting out changes what a result accepts, not where it sits

`test_aot_compile_module_opted_out_result_keeps_its_place_in_the_scan` uses the
default filter, so both trees pass, opts out `[0]`, and calls under the mode
`[1]` was traced for:

```python
with _set_pooling("mean"):
    assert results[0].guard_check(mod, x) and results[1].guard_check(mod, x)
    results[0].disable_guard_check()
    model(x) == expected["sum"]      # [0] served: the first accepting result in INDEX order
```

A dispatch that consults the checked results first, or holds the opted-out ones
back for the passes below, serves `[1]` instead, the graph the process global
would pick, so nothing but the number says which result answered. Only a mix of
one opted-out and one checked result can see that: with none or all opted out,
putting the checked results first reorders nothing, and holding the opted-out
ones back is what the dispatch commit's
`test_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts` already
fails on. Every other flag vector's case coincides with one of those two tests,
so this is the one case in the file that a mixed vector pins.

## The scan outranks the opt-out, and the last resort serves the first opt-out

`test_aot_compile_module_opted_out_result_is_the_last_resort` uses
`keep_global_guards`, so each result matches only its own mode:

```python
results[0].disable_guard_check()             # [0] = sum, opted out
with _set_pooling("mean"):
    model(x) == expected["mean"]             # [1]'s guards genuinely pass, so the scan serves [1]

results[1].disable_guard_check()             # both opted out
with _set_pooling("other"):                  # neither tree passes
    model(x) == expected["sum"]              # the last resort serves the FIRST opted-out result
```

The first arm is the wrong-answer bug if the opt-out is consulted before the
real guard checks: `[0]` would serve the first artifact for a call the second
was compiled for, same shapes, same dtypes, different numbers. The second arm
pins that the last resort is itself ordered: a call no artifact guards gets the
graph the earliest opted-out `ModelInput` was traced for. Both cases coincide
with the `compiled_results[0]` fall-through the parent replaced, since the
result they opt out first IS `compiled_results[0]`, so the test pins the
ordering against future reordering rather than regressing the rewrite.

A scan that skipped opted-out results is not one of them, for two different
reasons: in the first arm the result that must serve is the CHECKED one, which
the skip never applies to, so it is served by the scan itself and the second
pass is never reached; in the second both trees fail the call anyway and the
answer this ordering demands is the first opted-out result, which the last
resort serves either way. What tells a skipping scan apart is an opted-out
result whose tree the scan would accept: the keeps-its-place test above pins
that with honest guards, and the dispatch commit's re-check test covers the
false-rejection variant.

## What the escape hatch costs

`test_aot_compile_module_disable_guard_check` drives the opt-out through
`requires_grad`, which is part of `TENSOR_MATCH`, so the artifact recorded for
`requires_grad=False` genuinely cannot match the call:

```python
model = torch.compile(ScaleModule(), fullgraph=True, backend="aot_eager")
model._aot_compile([ModelInput(args=(torch.randn(3, 3),), kwargs={}, contexts=[])])

x = torch.randn(3, 3, requires_grad=True)
model(x)                                            # RuntimeError: ... requires_grad mismatch
model.forward.compiled_results[0].disable_guard_check()
out = model(x)                                      # served anyway: that is the escape hatch
out == x.detach() * 2 and not out.requires_grad     # and it is an INFERENCE graph: no grad history
```

It asserts what the opt-out COSTS rather than what it buys: with the guard that
would have rejected a `requires_grad=True` call disabled, dispatch serves an
inference graph that aot_autograd's runtime wrapper runs with grad disabled, so
the caller silently gets a result with no grad history. The expected value is
detached for that reason, since `assertEqual` does not compare `requires_grad`
and the tensor the call was made with does carry it. That is why this one test
compiles with `aot_eager` instead of the `eager` the ordering tests use: an
eager backend installs no such wrapper and would still record the grad history.
It does not discriminate against the pre-rewrite fall-through, since the result
it opts out is again `compiled_results[0]` and `AOTCompiledFunction.__call__`
short-circuits on the very same flag and serves the very same graph, so what it
is separated for is that its failure mode is loud: lose the opt-out stage and
the call reports "No AOT compiled graph matched" instead of answering wrongly,
which also keeps either direction of drift visible, a change that starts
handing back a differentiable result and a change that starts refusing the call
the opt-out was asked to allow.

## What is deliberately not duplicated here

Every case above opts out `compiled_results[0]` first, so a last resort that
read that one result instead of walking to the first that opted out satisfies
all of them. That walk, `[1]` opted out with `[0]` still checked and a call
neither artifact guards, served by `[1]` where reading `compiled_results[0]`
would refuse it with a no-match report, is pinned by the parent's
`test_module_dispatch_serves_an_opted_out_result_from_any_position`, in the
commit that introduces the loop. A copy of it here under `keep_global_guards`
was the same experiment on the dispatch axis (no edit to the three stages
separates the two), and the axis it did add, a rejection from a global guard,
is already what `test_aot_compile_module_dispatches_on_global_guard` and
`test_module_dispatch_evaluates_a_matching_tree_once` fail on when the pooling
guard is dropped, so it was removed rather than kept with a uniqueness claim it
could not make.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_disable_guard_check
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_opted_out_result_keeps_its_place_in_the_scan
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_opted_out_result_is_the_last_resort
```

Authored with the assistance of Claude Code.

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

## FAQ

> **FAQ: The review asked for the missing last-resort case to be folded into
> `test_aot_compile_module_opted_out_result_is_the_last_resort` by reordering its
> assertions so the first opt-out is `[1]`. Why is it a separate test?**
>
> Because the existing test's value is that all of its ordering assertions run
> against one capture in one order, and the case that was missing does not belong
> to that sequence: it is the only one that discriminates against reading
> `compiled_results[0]` instead of walking to the first result that opted out, and
> it needs `[0]` to still be checked while `[1]` is not -- the opposite of the
> state the ordering cases share. Reordering to make room for it costs the first
> ordering assertion its discrimination: with `[1]` opted out first, the call that
> assertion makes is one the opted-out result itself guards, so an opt-out
> consulted during the scan answers it correctly and the assertion passes anyway;
> rewriting it around a call `[0]` guards restores the check. The separate test
> states its own premise, keeps the ordering test's sequence intact, and fails
> loudly (a no-match report where a graph should have been served) rather than
> answering wrongly.

> **FAQ: nothing pins the `continue` that made the second `check()` pass skip
> opted-out results -- shouldn't there be a test?** There is now, and it is a fix
> rather than a pin. This round's audit built the case the earlier answer here said
> could not exist: both results opted out, the scan false-rejecting the one whose
> guards match (a `CountedKey` with one scripted miss), and dispatch served the
> FIRST opted-out result's graph for a call only the second matched -- wrong
> numerics, nothing raised -- because the re-check skipped every opted-out result
> and the last resort is ordered by index, not by guard. The skip is gone from
> #196823, whose re-check now evaluates every result the scan rejected, and that
> commit carries the test (asserting the served value and `compares == 2`, red with
> the skip restored). The four ordering tests here are unchanged by the fix,
> measured over the whole file.

> **FAQ: The globals-probe swap in
> `test_aot_compile_module_opted_out_result_waits_for_the_full_recheck` uses
> `try`/`finally` where the file's three other `CountedKey` swaps use `addCleanup`;
> the cleanup order is already correct, so match the sibling and drop the
> `try`/`finally` -- a mechanical translation. Why keep it?** Moot: that test is
> gone. A later pass showed every edit that reddened it also reddened one of its
> two siblings (`test_module_dispatch_serves_a_call_the_guard_tree_accepts`,
> neither result opted out, and
> `test_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts`, both),
> because all three walked the same dispatch path with a flag vector the correct
> code ignores; its replacement,
> `test_aot_compile_module_opted_out_result_keeps_its_place_in_the_scan`, pins the
> one case a mixed vector can see -- an opted-out result whose guards genuinely
> pass is served in index order, not after the checked results -- under the default
> guard filter, and swaps no probe at all. The `try`/`finally`-versus-`addCleanup`
> question therefore has no site left in this commit; the siblings that keep a
> `CountedKey` are #196823's, and they use the form their own comments justify.

> **FAQ: `test_aot_compile_module_last_resort_iterates_past_a_checked_result`
> was the same experiment as the parent's
> `test_module_dispatch_serves_an_opted_out_result_from_any_position` -- two
> results, `[0]` checked, `[1]` opted out, a call neither guards, `[1]` served.
> Fold or drop one?**
>
> Dropped, after one round of trying to keep it. On the dispatch axis the two
> were the same test: no edit to the three stages reddens one and not the other.
> The first attempt kept this copy with a comment claiming a guard-filter axis
> of its own, and that comment was wrong twice over -- `_guard_source_globals`
> cannot drop a guard at all (it only picks live global values for a rebuilt
> bytecode's globals, behind a gate this in-process test never reaches), and a
> filter regression that dropped the pooling guard already reddens
> `test_aot_compile_module_dispatches_on_global_guard` and
> `test_module_dispatch_evaluates_a_matching_tree_once`. The walk past a
> still-checked result stays pinned where the loop is introduced, in the parent
> commit.

> **FAQ: The comment on
> `test_aot_compile_module_opted_out_result_is_the_last_resort` said a scan that
> skipped opted-out results is not pinned because "the second pass re-checks
> them and recovers the graph"; neither assertion of that test ever reaches the
> second pass.**
>
> Right, and the comment now names the two actual reasons. With only `[0]` opted
> out, the result that must serve is the CHECKED `[1]`, which a skipping scan
> never skips, so `[1]` passes on its first evaluation and is served by the scan
> itself -- stage two is never entered. With both opted out under mode
> `"other"`, both trees genuinely fail the second pass too, and the answer the
> ordering rule demands is the first opted-out result, which the last resort
> serves either way. So the mutation is invisible to this test not because
> anything is recovered but because the skip never touches the result that
> decides. What does tell a skipping scan apart is an opted-out result whose
> tree the scan would accept:
> `test_aot_compile_module_opted_out_result_keeps_its_place_in_the_scan`, in
> this same commit, pins that with honest guards (both results accept under the
> default filter, `[0]` opts out, a skipping scan serves `[1]`'s graph instead),
> and `test_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts` in
> the dispatch commit covers the false-rejection variant; the comment now says
> so instead of claiming only a false rejection can see it.

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

Pull Request resolved: #196824
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196767, #196817, #196815, #196816, #196818, #196819, #196820, #196821, #196895, #196904, #197055
pytorchmergebot pushed a commit that referenced this pull request Sep 15, 2026
…alike (#197071)

Binding dominates the per-call cost of `AOTCompiledModel.__call__`.
`prepare_f_locals` (`inspect.Signature.bind` plus `apply_defaults`) costs
2.4us on this machine against 1.3us for a `check()` that passes, and the parent
binds every result it scans:

```python
# parent: one bind per result scanned
for result in results:
    f_locals = result.prepare_f_locals(self.model, *args, **kwargs)   # 2.4us, every time
    bound.append(f_locals)
    if result._live_guard_manager().check(f_locals):                   # 1.3us
        return result.fn(self.model, *args, **kwargs)
# a match at the fourth of four inputs pays four binds for one graph
```

Every result `aot_compile_module` produces binds alike: same parameter names,
kinds and default objects, same `co_freevars` and the same closure cells, since
`orig_forward` is read before any `ModelInput` context is entered. So one bind
serves them all. This commit lets a call that reaches a second result reuse the
first result's binding for it and every later one, across the scan and the
re-check, when the results bind alike:

```python
shared: bool | None = None
for result in results:
    if bound and shared is None:                    # decided only once a SECOND result is reached
        shared = self._binds_alike(results)
    f_locals = bound[0] if shared else result.prepare_f_locals(self.model, *args, **kwargs)
    bound.append(f_locals)                          # one entry per result either way, so the re-check zips as before
    if result._live_guard_manager().check(f_locals):
        return result.fn(self.model, *args, **kwargs)
```

Measured in one process on a `ScaleModule` compiled for two and for four
dtypes, the parent's `__call__` and this one exec'd from source into two
subclasses over the same results and timed in alternation, best of 9, min of
two rounds:

| call | parent | this commit |
|---|---|---|
| match at `[1]` of two | 21.0us | 20.5us |
| match at `[3]` of four | 30.3us | 22.7us |
| no match, two results (raises) | 25.3us | 23.2us |
| no match, four results (raises) | 36.2us | 27.5us |
| match at `[0]`, one / two / four results | 15.9 / 16.9 / 16.0us | 15.8 / 16.2 / 16.9us |

A match at `[0]`, which is every call to a single-result model, never reaches
the verdict and costs what it did (machine at load average 6). Behaviour is the
parent's for every call: the same result is served or the same error raised,
and a call still judges the results it began with. What changes is the number
of binds, and that editing `compiled_results` between calls, which the parent's
snapshot already tolerated, is now stated in the class docstring rather than
implied.

Review order: `_binding_key`, then the `_binding_verdict` field and
`_binds_alike`, then the `shared` lines of `__call__`, then the docstring,
then the tests.

## Deciding "binds alike" without `inspect.Signature` equality

```python
def _binding_key(artifacts):
    env, params = artifacts.runtime_env, artifacts.signature.parameters.values()
    return (tuple([(p.name, p.kind, id(p.default)) for p in params]),
            env.bytecode.co_freevars,
            tuple([id(cell) for cell in env.closure or ()]))
```

`_binding_key` compares exactly what `prepare_f_locals` reads, with defaults
and cells by identity, as a tuple of tuples so that a key is what its name
says. It deliberately does not compare `inspect.Signature`s: `Parameter.__eq__`
takes `bool()` of `default == default` as a non-final `and` operand, so a
`forward` with a tensor default made the first call raise for any model with
two or more results, however it was built (`_aot_compile`, `deserialize` or the
public constructor):

```python
class M(torch.nn.Module):
    def forward(self, x, mask=torch.ones(3)):
        return x * mask
# comparing Signatures -> RuntimeError: Boolean value of Tensor with more than one value is ambiguous
```

`test_module_dispatch_shares_a_binding_past_a_tensor_default` pins that, and
the closure half is pinned by
`test_module_dispatch_shares_a_binding_across_closure_cells`, whose
hand-assembled model holds two cells of the same name. A model whose results do
not agree (`deserialize` unpickles each blob on its own and the constructor is
public) binds each result on its own, which
`test_module_dispatch_binds_per_result_when_signatures_differ` pins.
`test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature` counts
`prepare_f_locals` on a four-input model for a call matched at `[3]` and
expects one.

A loaded model whose `forward` has a real default or a closure cell binds per
result for the same reason: each blob unpickles through its own
`AOTCompileUnpickler`, so equal defaults and cells come back as distinct
objects and the identity key reads them as different. That is a false negative
and never a false share, and it is accepted rather than closed with a memo
shared across the per-result pickles, which would turn the artifact from a list
of independent blobs into one stream and thread a shared pickler through
`AOTCompiledFunction.serialize` and `deserialize`; a `forward` with neither,
whose defaults are the `Parameter.empty` singleton, still shares one bind after
a load. Both shared-binding tests round-trip and pin the loaded verdict as
False.

## Decided at the second result, not ahead of the scan

The first result is bound and checked exactly as the parent does, so a call it
serves pays nothing for the sharing and a single-result model never consults
the verdict at all.
`test_module_dispatch_decides_a_shared_binding_past_the_first_result` pins that
on a two-result model: a call `[0]` serves never calls `_binds_alike` and
leaves the verdict at its default, the verdict over no results, and the next
call, which `[0]` refuses, calls it once. Every binding, shared or not, is
appended once per result in the scan, so the re-check zips `results` with
`bound` as the parent does.

## Re-decided whenever the public list changes

`compiled_results` is a public list; the docs teach callers to index into it
and tests assemble models from it by hand. So the verdict is decided again
whenever the list differs by length or identity from the contents it was
reached over:

```python
def _binds_alike(self, results):
    prior, shared = self._binding_verdict
    if len(results) == len(prior) and all(w() is r for w, r in zip(prior, results)):
        return shared                                    # cached: 0.37us at two results, 0.47us at four
    key = _binding_key(results[0]._artifacts) if results else None
    shared = key is not None and all(_binding_key(r._artifacts) == key for r in results[1:])
    self._binding_verdict = (tuple(weakref.ref(r) for r in results), shared)   # ONE store
    return shared
```

A stale True would bind a later result from `compiled_results[0]`'s signature,
and if a `guard_filter_fn` dropped the guard on the parameter the two disagree
about, serve a graph for a call its guards never saw:

```python
model.forward.compiled_results[1] = replaced    # forward(x, mode=0), but compiled for mode=1
model(x)   # stale True: [1] bound from [0]'s default -> serves x * 3, where eager answers x * 2
           # re-decided: [1] bound on its own signature -> raises
```

`test_module_dispatch_rebinds_after_a_result_is_appended` and
`test_module_dispatch_judges_a_replaced_result_on_its_own_binding` pin the
re-decision, the second through that silent shape. The contents are remembered
as weak references, so a result the caller drops from the list is not kept
alive by the model until a later call decides again;
`test_module_dispatch_does_not_keep_a_dropped_result_alive` pops one, collects,
and finds its weakref dead. Deciding costs a `_binding_key` per result, about
1.0us each, and the cached identity check 0.37us for two results and 0.47us
for four, 0.02us and 0.04us of which is dereferencing the weak references.

## One field, published with one store

The verdict and the contents it was reached over are one field,
`_binding_verdict`, so a call reads both with one attribute load and the
re-decision publishes both with one attribute store, and the field's comment
states the premise rather than the conclusion: a single attribute store
publishes the pair indivisibly (an instance-dict store is atomic under the GIL
and locked on free-threaded builds), so a reader sees the old pair or the new
one and never one list's contents beside another's verdict. Two fields cannot
be made consistent by store order:

```python
# contents first, verdict second:
#   T1 stores new contents ... T2 identity-matches them, returns the PREVIOUS verdict (stale True),
#   binds the appended result from [0]'s default
# verdict first, contents second:
#   T1 pops [1], decides True over the shorter list, stores it ... T2, which snapshotted both results
#   before the pop, matches the contents still published, takes that True, binds [1] from [0]'s
#   default and serves x * 3 for a call eager answers x * 2
```

Both interleavings are forced deterministically.
`test_module_dispatch_never_pairs_new_contents_with_a_stale_verdict` holds the
deciding thread inside its first `_binding_key` on a `threading.Event` and
calls the model from another thread in that window.
`test_module_dispatch_never_pairs_old_contents_with_a_new_verdict` holds it
right after its first attribute store (an `AOTCompiledModel` subclass whose
`__setattr__` parks the decider) while a call that snapshotted both results
before the pop decides. A window between the two halves of the publication is
the one thing no test can pin, which is why there is none: whatever the single
store publishes is all a reader can ever see, and that is what the second test
asserts. Both tests register their cleanups once the decider has started,
release before join, so a failed assertion neither joins an unstarted thread
nor leaves a parked one behind, and wait at most 10s for the decider to park,
so a decider that never reaches its parking point fails the test in seconds.
The tests read `_binds_alike(tuple(model.compiled_results))` rather than the
field.

`_binds_alike` takes the tuple `__call__` snapshotted rather than reading the
list itself, so the shared bind and the verdict are about the same contents the
two passes iterate; the snapshot's own test is in the dispatch commit two below
(#197055), where the per-result binds already need it.

> **FAQ: Why not decide the verdict once at construction and call editing
> `compiled_results` afterwards unsupported, dropping the re-decision, the weak
> references and both threading tests?** Because nothing stops the edit and a
> stale True fails silently. Measured by making `_binds_alike` return the stored
> verdict whenever one exists (deciding once), against the 15 tests:
> `test_module_dispatch_judges_a_replaced_result_on_its_own_binding` fails with
> `RuntimeError not raised` -- `[1]`, compiled for `mode=1` and defaulting
> `mode` to 0, is bound from `[0]`'s `mode=1` default and serves `x * 3` for a
> call eager answers `x * 2` -- `test_module_dispatch_rebinds_after_a_result_is_appended`
> errors with `GuardManager check failed`, and both interleaving tests time out
> waiting for a decider that never re-decides. The dispatch commit below
> (#197055) already snapshots the list because it is editable, so stating the
> edit as supported is the position the code was taking; the class docstring
> now says so. What deciding once would save is the cached identity check,
> 0.37us at two results and 0.47us at four, and only on calls that reach a
> second result; `_aot_compile` and `deserialize` construct once either way.

> **FAQ: Why weak references rather than `id()`s for the remembered
> contents?** Ids are reused once an object dies, so a list of ids could match
> a new result that happens to occupy a dead one's address and hand it the old
> verdict. A weak reference dereferences to the object or to None, so the
> identity check is exact, and it costs 0.02us more than comparing the objects
> directly for two results and 0.04us for four while keeping nothing alive.

> **FAQ: Why cache the verdict at all instead of deciding on every call?**
> Deciding costs a `_binding_key` per result, about 1.0us each: 4us at four
> results, most of the 7us the three binds it saves there cost. The cached
> identity check costs 0.37us at two results and 0.47us at four whatever it
> decides, and a call `[0]` serves never pays it.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature
python test/dynamo/test_aot_compile.py -k test_module_dispatch_decides_a_shared_binding_past_the_first_result
python test/dynamo/test_aot_compile.py -k test_module_dispatch_binds_per_result_when_signatures_differ
python test/dynamo/test_aot_compile.py -k test_module_dispatch_rebinds_after_a_result_is_appended
python test/dynamo/test_aot_compile.py -k test_module_dispatch_judges_a_replaced_result_on_its_own_binding
python test/dynamo/test_aot_compile.py -k test_module_dispatch_does_not_keep_a_dropped_result_alive
python test/dynamo/test_aot_compile.py -k test_module_dispatch_never_pairs_new_contents_with_a_stale_verdict
python test/dynamo/test_aot_compile.py -k test_module_dispatch_never_pairs_old_contents_with_a_new_verdict
python test/dynamo/test_aot_compile.py -k test_module_dispatch_shares_a_binding_past_a_tensor_default
python test/dynamo/test_aot_compile.py -k test_module_dispatch_shares_a_binding_across_closure_cells
python test/dynamo/test_aot_compile.py
```

This commit adds 10 `test_module_dispatch_*` tests; the full file runs 182
tests and passes (6 skipped). All 10 fail at the parent, i.e. with the parent's
`torch/_dynamo/aot_compile.py` under this commit's test file, on the missing
`_binds_alike` (`AttributeError`); the retention test reaches it through the
precondition that the verdict was decided over both results, since a parent
without the cache has nothing to retain. The parent's five
`test_module_dispatch_*` tests still pass here, and all 15 also pass with
`torch._dynamo.config.use_recursive_dict_tags_for_guards = True` set for the
run.

Mutation controls, each run against the 15 tests at this commit and each
failing only the tests named: making `_binds_alike` return the stored verdict
whenever one exists (deciding once) fails the replaced-result test with
`RuntimeError not raised`, errors the appended-result test with `GuardManager
check failed` and times out both interleaving tests; deciding ahead of the scan
fails the first-result test with `Expected '_binds_alike' to not have been
called. Called 1 times`; never reusing the first binding fails the binds-once
test (four binds counted, not one); keeping only the length check in the
staleness test fails the replaced-result test with `RuntimeError not raised`
(`[1]` served `x * 3` on `[0]`'s binding) and still passes the appended one;
restoring `Signature` equality in `_binding_key` errors the tensor-default test
with `Boolean value of Tensor with more than one value is ambiguous`; dropping
the cells from the key fails the closure test with `True is not false`;
remembering the results by strong reference fails the retention test (`... is
not None`); splitting the field in two and publishing the contents before the
key is computed errors the new-contents interleaving test with `GuardManager
check failed` (the appended result bound from `[0]`'s default), and publishing
the verdict before the contents fails the old-contents test with `RuntimeError
not raised` (both two-field variants also error the first-result test, which
reads the field they split). The `co_freevars` term of the key has no mismatch
test: two results holding the same cell under different names take a
hand-built code object, and the term is one tuple compare of what the bind
reads.

Authored with the assistance of Claude Code.

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

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

Pull Request resolved: #197071
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196767, #196817, #196815, #196816, #196818, #196819, #196820, #196821, #196895, #196904, #197055, #196824
pytorchmergebot pushed a commit that referenced this pull request Sep 15, 2026
…e dispatch (#197047)

The parent's `AOTCompiledModel.__call__` scans every compiled result for a
guard match, re-checks every result, and then falls through into
`compiled_results[0]`:

```python
for result, f_locals in zip(results, bound):           # scan
    if result._live_guard_manager().check(f_locals): return result.fn(...)
for result, f_locals in zip(results, bound):           # re-check
    if result._live_guard_manager().check(f_locals): return result.fn(...)
return results[0](self.model, *args, **kwargs)         # fall through: raises, OR runs if [0] opted out
```

The last line does not raise by itself. `AOTCompiledFunction.__call__` skips its
guards when that one result has `disable_guard_check()` set, so what an
unmatched call gets still turns on the POSITION of an opt-out:
`compiled_results[0].disable_guard_check()` makes `[0]` run any call no result
guards, while the same flag on `compiled_results[1]` is inert and the call
raises `GuardManager check failed`. Measured on a two-input `ScaleModule`
(float32 and float64) called with float16, each result's `fn` wrapped to record
which one served:

```
PARENT [enabled, enabled]     : RuntimeError: GuardManager check failed ...
PARENT [enabled, opted_out]   : RuntimeError: GuardManager check failed ...   <- the flag on [1] is inert
PARENT [opted_out, enabled]   : SERVED by [0]
PARENT [opted_out, opted_out] : SERVED by [0]
```

This commit adds a third stage between the re-check and the fall-through that
serves the first opted-out result, from any index, and only after both passes
found no match:

```python
for result in results:                                 # NEW: honour an opt-out from any position
    if not result._guard_check_enabled:
        return result.fn(self.model, *args, **kwargs)
return results[0](self.model, *args, **kwargs)         # only enabled results reach here, so it raises
```

```
HEAD   [enabled, enabled]     : RuntimeError: GuardManager check failed ...
HEAD   [enabled, opted_out]   : SERVED by [1]                                 <- the one change
HEAD   [opted_out, enabled]   : SERVED by [0]
HEAD   [opted_out, opted_out] : SERVED by [0]
```

The fall-through is then reached only when every result has its check enabled,
so its comment now says that `results[0]` raises, not "run one of them".

## What the flag now means on a module

`compiled_results[i].disable_guard_check()` on a module artifact now makes
result `i` the fallback for any call no compiled input guards, from any index.
At the parent only `i == 0` had that effect and an opt-out elsewhere was inert;
the flag was therefore position-dependent, not a contract. The module path
(`_aot_compile`, `ModelInput`) is private and its docstring says Experimental,
so no BC guarantee is owed. Nothing the parent served is refused
(`[opted_out, enabled]` still serves `[0]`); the only change is raise->serve
for `[enabled, opted_out]`, and only after every result's guards were checked
twice and none accepted.

```python
model._aot_compile([ModelInput((x, 0), {}, []), ModelInput((x, 1), {}, [])])   # ModeBranchGlobalModule
model.forward.compiled_results[1].disable_guard_check()
model(x, 2)     # neither input guards mode=2
# parent: RuntimeError: GuardManager check failed ... L['mode'] == 0   ([0] re-entered alone)
# now:    x * AOT_BRANCH_SCALE, [1]'s graph -- deliberately NOT eager's answer for mode=2:
#         serving a graph compiled for a different call is what the opt-out exists to do
```

Why serve rather than raise: on the function path
`AOTCompiledFunction.__call__` short-circuits on the flag and runs the graph
whatever it is called with, and the scan already serves an opted-out result
whose guards pass, which is what an enabled result gets too, so raising on a
no-match would leave `disable_guard_check()` with no effect at all on a model.
It would also have to keep serving `[opted_out, enabled]`, which the parent
serves, so "raise" was never available without a position rule of its own. A
real match is always preferred to the opt-out: the scan and the re-check run
over every result, opted out or not, before this stage is consulted, so the
opted-out graph is served only for a call no compiled input guards.

## Where the stage sits, and the three orderings the tests pin

Ordering matters more than it looks. With this stage ahead of the re-check, an
opted-out result answers first and silently serves a graph compiled for a
different call in exactly the case the re-check exists for: a first `check()`
that refused from the recursive dict-tag fast path without running the tree.
The parent pins that order from the fall-through's side with
`test_module_dispatch_rechecks_before_honouring_an_opt_out` and
`test_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts`; moving
this stage ahead of the re-check serves `[0]`'s `x * 2` and fails both with
`Mismatched elements: 9 / 9`, and the other twelve stay green.

`test_module_dispatch_serves_an_opted_out_result_from_any_position` pins the
other two orderings in three assertions:

```python
model.forward.compiled_results[1].disable_guard_check()
model(x, 2) == x * AOT_BRANCH_SCALE   # [1] serves from index 1; the parent raised here
model(x, 0) == x * 2                  # [0]'s REAL match still outranks [1]'s opt-out:
                                      #   the stage cannot be hoisted into the scan
model.forward.compiled_results[0].disable_guard_check()
model(x, 2) == x * 2                  # both opted out, nothing matches: index order decides,
                                      #   as it did at the fall-through
```

Moving the stage ahead of the scan as well fails the second assertion, and
reversing the stage's iteration order fails only the third.
`[opted_out, enabled]` with a match at `[1]` is
`test_module_dispatch_rechecks_before_honouring_an_opt_out`.

## To review

The five-line loop in `torch/_dynamo/aot_compile.py` between the re-check and
the fall-through, and the fall-through's reworded comment; the one clause
appended to the dispatch paragraph of the `AOTCompiledModel` docstring; the one
test, three assertions; and the clause added to the `disable_guard_check()`
entry of `docs/source/user_guide/torch_compiler/torch.compiler_aot_compile.md`,
which described the flag only as the function path honours it ("runs whatever
it is called with, without evaluating its guards") and now says that a
module's dispatch still guard-checks an opted-out result and serves it on the
opt-out alone only for a call no result's guards accept.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_module_dispatch_serves_an_opted_out_result_from_any_position
python test/dynamo/test_aot_compile.py -k test_module_dispatch_
python test/dynamo/test_aot_compile.py
lintrunner --take RUFF,PYFMT test/dynamo/test_aot_compile.py torch/_dynamo/aot_compile.py
```

The new test fails at the parent with `RuntimeError: GuardManager check
failed` (the fall-through re-enters `compiled_results[0]`, whose guard check is
enabled) and passes here; the other 13 `test_module_dispatch_*` tests pass at
both. The full file runs 182 tests and passes (6 skipped). The table above was
measured by building the model and opting results out per row at the parent
and at this commit. Lint is clean.

> **FAQ: Why does dispatch serve an opted-out result when nothing matched, when
> #196929's description calls the parent's position-dependent serve an
> accident?** Measured against the parent on a two-input `ScaleModule` (float32
> and float64) called with float16: `[opted_out, enabled]` is SERVED at the
> parent and SERVED here, `[enabled, opted_out]` raises at the parent and is
> SERVED here, and `[enabled, enabled]` raises in both. So serving an opted-out
> result on a no-match is pre-existing behaviour, not new -- what is new is that
> it no longer depends on the opt-out sitting at index 0. The defect #196929
> names is that whether you got a report at all turned on list order, since the
> fall-through re-raised only because `compiled_results[0]` happened to have its
> guard check enabled. Raising instead would make `disable_guard_check()` inert
> on the model path, because the scan already serves an opted-out result whose
> guards do pass, so the flag would buy nothing an enabled result does not
> already get; it would also refuse the `[opted_out, enabled]` call the parent
> serves today, and it would red
> `test_module_dispatch_serves_an_opted_out_result_from_any_position`, which
> pins exactly the `[enabled, opted_out]` serve.
>
> There is a third option: keep the fall-through but raise from the first
> *enabled* result rather than `results[0]`,
> `next((r for r in results if r._guard_check_enabled), results[0])`. That fixes
> which result reports without widening what is served. Measured on the same
> model it raises for `[enabled, enabled]`, `[enabled, opted_out]` and
> `[opted_out, enabled]`, and serves only `[opted_out, opted_out]` (by `[0]`):
> it refuses the `[opted_out, enabled]` no-match the parent serves today, and a
> single opt-out next to any enabled result is inert on the no-match path,
> which is the inert reading above unless every result opts out. That is a
> coherent contract too, but a narrower one than the flag has on the function
> path, so it was not taken.
>
> On the blast radius of one opt-out anywhere in the list: a real match is
> always preferred to it. The scan and the re-check run over every result, opted
> out or not, before the last resort is consulted, so the opted-out graph is
> served only for a call no compiled input guards, which is exactly the call the
> flag exists to serve;
> `test_module_dispatch_rechecks_before_honouring_an_opt_out` pins that order,
> and the new test's `model(x, 0)` assertion pins that a match at `[0]`
> outranks an opt-out at `[1]`. Narrowing the flag to "suppress my own report
> but still require a match" is the inert reading above, and is why the flag is
> documented as model-wide on this path.

> **FAQ: `_guard_check_enabled` is not serialized, so is this stage
> in-process only?** Yes, and that is pre-existing on both paths:
> `AOTCompiledFunction.serialize` copies `fn._artifacts.__dict__`, and the flag
> is a field of the function, not of its artifacts, so a loaded result starts
> enabled whether it is called directly or through a module's dispatch. The
> opt-out has always been something the caller sets on the results it holds
> after building or loading them; this commit changes where the module path
> honours it, not whether it is saved.

Authored with the assistance of Claude Code.

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

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

Pull Request resolved: #197047
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196767, #196817, #196815, #196816, #196818, #196819, #196820, #196821, #196895, #196904, #197055, #196824, #197071
bobrenjc93 added a commit that referenced this pull request Sep 15, 2026
Tests only, and end to end: a module artifact guards a global, the loading
process does not define it, and the call has to fail loudly with a report that
says which compiled input failed and how -- `[0] KeyError on
G['AOT_HERMETIC_WEIGHT']` -- and that names the scope its guards were rooted
at: the globals of the module where `HermeticModule.forward` is defined, which
on this path is the only place the caller could put it. That advice is then
taken, and the test pins how far taking it goes at this commit: defining the
name in the named scope resolves the guard and the same call is served, but the
tensor served is the one serialized with the artifact rather than the one just
defined, because the bytecode's globals are built once, at load, and substitute
a live value only for a name the scope has then. Binding `saved * 2` and
asserting `x @ saved` is what pins that, and it is what makes the recovery
assertion say which dict the dispatch read rather than only that it stopped
raising: asserting `x @ (saved * 2)` instead fails (`Tensor-likes are not
close! Mismatched elements: 9 / 9`), and rooting the guards at a copy of the
live scope rather than the dict itself is caught first by the hint assertion --
the report drops the forward clause when the resolved dict is not the one the
guards hold -- with the recovery arm as the second line of defence, pinning
which dict the dispatch READ.

That `x @ saved` value is the parent's load-time snapshot, recorded here as
the limitation it is and not as the intended end state: #196897, two commits
up this stack, makes a loaded module artifact re-read the live value on every
call and flips this very assertion to `x @ (saved * 2)`, using this test as
the witness that its recorded name set is not intersected with the scope at
load. The pin stays in this commit so that flip lands as a measured behaviour
change rather than a silent one; the test comment says the same in one
sentence, without the PR number, so it reads correctly both before and after
that commit. Binding `saved` instead, which would make the arm invariant under
#196897, was considered and declined: it would leave this test unable to tell
the live dict from the serialized copy, and #196897 would have to re-add
`saved * 2` to use it as a witness.

The report is also asserted to carry the generic mismatch advice next to that
hint: a missing global counts as the mismatch it is, because the report cannot
tell whether a new `ModelInput` would read the absent global -- one captured
for a branch that does not read it is served with the name still undefined --
so both lines are emitted, and for `HermeticModule`, which reads the global on
its only path, the hint is the actionable half. The forward clause the test
asserts is emitted when the scope `model.forward` resolves to is the dict the
guards hold (`resolved is not None and resolved is
missing_global._guard_globals`), which is the case for a load that passed no
`guard_globals=`, resolved forward, and is not rebound after the load;
`test_no_match_message_hint_covers_a_rebound_forward` rebinds BEFORE loading
and so gets the clause too, while `..._survives_a_forward_resolve_that_raises`
rebinds after and asserts it absent. What tells this test from the rebound
sibling is the recovery arm: defining the name in `globals()` serves the call
here, where the same binding in that sibling still raises.

Worth its own test because the alternative -- falling back to the serialized
scope -- makes the guard a no-op checked against capture-time state, which is
the silent failure mode; loud is recoverable on the serving machine. Most of the
load-bearing assertions are on #196823's no-match report and its forward-naming
hint -- the recovery assertion is on #196818's live-scope rooting -- so this
could equally have been folded into #196823; it stays separate because a
guarded global the loading process does not have is a failure mode of its own,
independent of where an opted-out result sits in dispatch and of what the
report says when a tree raised, and each of those gets the commit that pins it.
The fixture is the same `HermeticModule` and module-level weight
`test_aot_compile_module_reload_reads_the_live_global` uses -- the test for the
opposite direction, that a reloaded artifact reads the live global -- rather
than a second copy of it that differed only in an unchecked scale factor. Like
that sibling it hides the module dict's leaked generated globals through the
shared helper before capturing, since the scope resolved from `model.forward` is
this module's dict and the capture leaks Dynamo's generated names into it. The
load seeds nothing here, for the reason that sibling's comment gives: the only
kept global guard is rooted at `AOT_HERMETIC_WEIGHT`, not at an import alias or
the builtins-dict key. Unlike that test, the reloading wrapper here takes no
`guard_filter_fn`: the load installs the artifact's own guards and captures
nothing, so the loading process's filter has no say in what a loaded artifact
checks -- that sibling does pass a filter on its reload, where it is equally
inert.

No behaviour change vs the parent: the diff is one 66-line test, nothing under
torch/ moves.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_absent_global_fails_guard
```

Run in one process with the tests that share the fixture and the report, which
unittest orders after this one, to show they still pass with it running first
(5 tests, OK):

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_absent_global_fails_guard -k test_aot_compile_module_reload_reads_the_live_global -k test_missing_key_inside_a_present_global_is_not_a_missing_global -k test_no_match_message_keeps_the_advice_for_every_entry -k test_no_match_message_hint_covers_a_rebound_forward
```

The whole file was run at this commit:

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

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: f669e9c
Pull-Request: #196825
bobrenjc93 added a commit that referenced this pull request Sep 15, 2026
… its advice stays

Tests only, for the no-match report the report commit (#196823) raises, split
out of it so that its review fits in one pass -- the pattern of #196824 and
#196825, which pin the dispatch's last resort and a guarded global the loading
process does not have from test-only commits. Each of the four passes at the
report commit, whose report it pins, and fails below it, at the dispatch commit
049617d (#196929), where the no-match fall-through `results[0](self.model,
*args, **kwargs)` raises the function path's `GuardManager check failed`
message. That message is not empty of the report's text: it quotes the guard's
`KeyError on G[...]` part and, for a whole missing global, appends the function
path's hint sentence, so the `loaded against; define it there`, `the module the
compiled function was traced in` and `a guarded global is missing` substrings
the tests also look for are present there. What it lacks is the `[i]` entry
prefix and the `Add a ModelInput` footer, and each of the four asserts on one
of those two: measured with that commit's `aot_compile.py` under this tree's
test file, `stays_neutral`, `advises_an_input` and `resolves_forward_only` each
fail on `"[0] KeyError on G[...]" not found` alone, and
`missing_key_inside_a_present_global` on `'Add a ModelInput' not found` alone.
Every one of them captures in this process, so every one calls
`_hide_leaked_dynamo_globals()` on entry, as the capture-only
`test_aot_compile_fn_missing_global_hint_names_the_tracing_scope` does. What
each catches at this tree, and which of the report commit's own tests would
catch the same edit, was measured by editing the report:

`test_no_match_message_hint_stays_neutral_for_a_supplied_scope` loads through
`AOTCompiledModel.deserialize(..., guard_globals=...)` with a dict that never
had the guarded name, so the guards hold a dict no `forward` resolves to,
asserts the scope-neutral wording, and then the advice it gives:
`compiled_results[0]._guard_globals is scope`, and defining the name in that
dict serves the call -- with `AOT_HERMETIC_WEIGHT` defined in this module's
dict, where the class's `forward` lives, the whole time. The wording is decided
by the identity compare `resolved is not missing_global._guard_globals`, and
this test is not the only one that pins it: reducing the condition to `resolved
is None` fails it with a report that names `this HermeticModule instance's
forward`, and of the file's 194 tests fails exactly one other, #196818's
`test_aot_compile_module_missing_global_hint_names_the_resolved_module`, whose
second half loads with `guard_globals=dict(globals())` -- a copy of the module
dict, taken while the module itself lacked the name, that is not the dict
`forward` resolves to -- and asserts `loaded against; define it there`. The
report commit's `test_no_match_report_survives_a_forward_resolve_that_raises`
reaches the neutral wording through `resolved is None`, and
`test_no_match_message_hint_covers_a_rebound_forward` through a resolve that IS
the dict the guards hold, so both pass under that edit. What this test adds
over `..._names_the_resolved_module` is the other way to the wording, a
supplied dict that never had the name rather than a stale copy carrying the
module's `__name__`, and the recovery: no other
`AOTCompiledModel.deserialize(..., guard_globals=)` test defines a missing name
in the supplied dict and asserts the call is served
(`..._deserialize_takes_a_guard_globals_scope` supplies a copy that already
carries its names, and `covers_a_rebound_forward` defines the name in the dict
the load RESOLVED, not one the caller passed).

`test_missing_key_inside_a_present_global_is_not_a_missing_global` pins which
predicate the report reaches for. A guard on
`G['GLOBAL_POOLING_CONFIG']['pooling']` with the KEY popped reports `KeyError
on G['GLOBAL_POOLING_CONFIG']['pooling']`, asserted in full, as the function
path's `test_aot_compile_fn_missing_nested_key_gets_no_missing_global_hint`
asserts it -- an ordinary mismatch: the report keeps the advice and withholds
the hint, whose "define the global" would be wrong. Replacing
`_names_a_missing_global` with a `"KeyError on G["` substring test fails it on
the hint's presence, and passes every report test in the report commit, each
of whose missing globals is a whole part. The whole-part match itself came in
with the function path's hint and is pinned there.

`test_no_match_message_advises_an_input_for_a_missing_global` pins the shape
the report commit's argument for unconditional advice rests on.
`SelfModeBranchGlobalModule`, the fixture it adds, branches on `self.mode`
rather than an argument: that guard is a `LOCAL_UNSPECIALIZED_NN_MODULE`
source, which sorts after `GLOBAL`, so the root's `G` accessor is installed --
and fails -- before the `self.mode` guard (the `L['x']` `TENSOR_MATCH`, a
`LOCAL`, precedes both), and the one entry names only the missing global.
`check_verbose` quotes the first failing guard and nothing after it, so the
absence of `L['self'].mode` from that report cannot by itself show a mismatch
was hidden; the test then puts the global back and calls again, and the same
call now fails on `[0] L['self'].mode == 1` alone. The two halves run in that
order because a failed `check()` re-sorts the root's children by fail count
(`GuardManager::check_nopybind`, guards.cpp): had `self.mode` failed first, it
would sit ahead of the `G` accessor and the popped-global call would name it
instead of the KeyError. An input captured for the `mode == 2` branch would not
read `AOT_BRANCH_SCALE` at all, so the advice is right and is the only
actionable line. Withholding it when every entry named a missing global --
counting the entries that did and returning before the footer when the count is
the whole report -- fails it on `Add a ModelInput`; two other one-entry reports
on a missing global fail under that edit as well, the report commit's
`test_no_match_report_survives_a_forward_resolve_that_raises` and this commit's
`test_no_match_report_resolves_forward_only_for_a_supplied_scope` (`failures=3`
on the whole file, all on `'Add a ModelInput' not found`), and
`test_no_match_message_keeps_the_advice_for_every_entry`, which pairs the
missing global with a plain mismatch, passes. What this test adds is the hidden
mismatch, which none of those has.

`test_no_match_report_resolves_forward_only_for_a_supplied_scope` is the
CAPTURED half of the pair whose SUPPLIED half,
`test_no_match_report_survives_a_forward_resolve_that_raises`, stays with the
report. It captures a plain `HermeticModule` in-process, pops the global, and
asserts the CAPTURED report arrives with no `forward` named. It wraps
`_resolve_guard_scope` in a `patch(..., wraps=...)` for the call and asserts it
was never invoked, since the wording alone cannot pin the gate: the CAPTURED
hint never names `forward`, so it reads the same whether or not the resolve
ran. Replacing the SUPPLIED gate with `if True:` fails it on the count,
`Expected '_resolve_guard_scope' to not have been called. Called 1 times`, with
the `except Exception` around the resolve kept or removed, and passes every
other SUPPLIED report test -- the report commit's
`test_no_match_report_survives_a_forward_resolve_that_raises` and
`test_no_match_message_hint_covers_a_rebound_forward`, and this commit's
`test_no_match_message_hint_stays_neutral_for_a_supplied_scope`, all of which
resolve either way -- so this is the one test that pins the gate. The count
carries the assertion, so the test no longer rebinds `forward` to a
`functools.partial` over `RaisingReprModule`: on this path a resolve that
raised would be swallowed by that catch and change nothing the test could see,
and the catch itself is `survives_a_forward_resolve_that_raises`'s to pin --
with the catch removed it errors with `ValueError: extra_repr`.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_hint_stays_neutral_for_a_supplied_scope
python test/dynamo/test_aot_compile.py -k test_missing_key_inside_a_present_global_is_not_a_missing_global
python test/dynamo/test_aot_compile.py -k test_no_match_message_advises_an_input_for_a_missing_global
python test/dynamo/test_aot_compile.py -k test_no_match_report_resolves_forward_only_for_a_supplied_scope
python test/dynamo/test_aot_compile.py
```

The whole file runs 194 tests here, 190 on the parent commit: `Ran 194
tests`, `OK (skipped=6)`.

## FAQ

> **FAQ: The review asked that
> `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` read
> `AOT_HERMETIC_WEIGHT` through a reference captured at import instead of
> asserting it is in `HermeticModule.forward.__globals__`. Why an identity
> assertion instead?**
>
> The membership assertion was standing in for a claim about which dict the
> guards read, so the test states that claim directly:
> `compiled.compiled_results[0]._guard_globals is scope` -- the guards hold the
> supplied dict -- and the read that follows, `scope["AOT_HERMETIC_WEIGHT"] =
> AOT_HERMETIC_WEIGHT` serving the call, is the dict a forward-naming hint would
> have sent the reader away from. An earlier revision also asserted
> `HermeticModule.forward.__globals__ is globals()`; that holds by construction
> for a class defined in this file and observes nothing about the code under
> test, so it is gone. The two bare `AOT_HERMETIC_WEIGHT` reads are pre-existing
> and shared with every test in the file that uses the fixture; a sibling that
> failed to restore the name would break the module, not this test's ordering,
> and a captured alias would only move that dependency to import time.

> **FAQ: The review asked
> `test_no_match_message_advises_an_input_for_a_missing_global` to first show
> the report naming `L['self'].mode` with the global defined, then pop the
> global and show the KeyError replacing it. Why the other order?**
>
> Because the guard tree remembers its failures. `GuardManager::check_nopybind`
> (torch/csrc/dynamo/guards.cpp) bumps a child's fail count when it rejects and,
> unless the failure was on the first child, re-sorts the root's accessors by
> fail count so the next check fails fast. Run the mismatch half first and the
> `self.mode` accessor moves ahead of the `G` accessor; the popped-global call
> then reports `L['self'].mode == 1` rather than the KeyError (measured on a
> scratch copy: both calls name `self.mode`). Popped first, the `G` accessor
> is the one promoted, it resolves once the global is back, and the second call
> fails on `self.mode` alone -- which is the positive witness the review asked
> for, on the same compiled result.

> **FAQ: The review found that
> `test_aot_compile_module_missing_global_hint_names_the_resolved_module`, in
> #196818 below, already fails under the `resolved is None` edit that this
> commit's `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` was
> described as the one test to catch. Why keep the test?**
>
> Because the coverage claim was wrong, and the test's other half is not pinned
> anywhere else. Re-measured on the whole file with the compare reduced to
> `resolved is None`: `Ran 194 tests`, `FAILED (failures=2)`, the two being
> `..._names_the_resolved_module` (`'loaded against; define it there' not
> found`) and this test; every other test passes. So the identity compare is
> fenced at #196818, and the message now says so instead of crediting this
> test. What this test alone covers is a `guard_globals=` dict that never had
> the name -- `..._names_the_resolved_module` reaches the same wording through
> `dict(globals())`, a copy taken while the module itself lacked the name --
> and the recovery, defining the name in that dict and asserting the call is
> served, which no other `AOTCompiledModel.deserialize(..., guard_globals=)`
> test does. The same pass dropped the static
> `HermeticModule.forward.__globals__ is globals()` assertion, replaced the
> raising-repr scaffolding in `..._resolves_forward_only_for_a_supplied_scope`
> with a plain `HermeticModule()` (the mock's call count carries the
> assertion; a raise on that path would be swallowed by the report's catch),
> and moved the `patch(...)` construction there above `g.pop` so nothing sits
> between the pop and the `try`.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 9cea9f6
Pull-Request: #197001
bobrenjc93 added a commit that referenced this pull request Sep 15, 2026
…path, drop bytecode_reads_guard_scope

`AOTCompiledFunction` carried a `_bytecode_reads_guard_scope` flag, a matching
`deserialize(bytecode_reads_guard_scope=...)` parameter with its own docstring
paragraph, and a block in `__post_init__` that, when the flag was set, copied the
certified globals out of the supplied scope into the dict `forward_callable`
builds for the bytecode. Only `AOTCompiledModel.deserialize` passed `True`. All
of it came from #196818 of this stack, landed on main as 82c1f1e and in no
release tag, and nothing outside `AOTCompiledModel.deserialize` ever passed the
parameter, so deleting it breaks no released or in-tree caller.

That merge is not redundant with `_serve`'s per-call re-take, even though both
write the same names from the same dict: `forward_callable` runs
`_check_external_refs` over `{**import_sources, **used_globals, **extra_globals}`
at load, and `get_runtime_env` fills `used_globals` only from the graph inputs'
global roots plus the builtins the bytecode reads. A global the generated
bytecode LOAD_GLOBALs but the graph never lifted -- the side-effect replay of a
mutated global container or object, or the reconstruct of a returned global -- is
in `external_refs` and in no serialized scope, while a `guard_filter_fn` that
keeps global guards leaves a serializable TYPE_MATCH or SEQUENCE_LENGTH rooted at
its bare GlobalSource, so it is certified. On the module load path, which passes
no `f_globals`, the merge was the only thing binding that name before the check;
without it the load raises `Missing required external references`. So
`_guard_source_globals(output_graph) <= used_globals | import_sources` does not
hold, and the merge stays. What goes is the flag: the merge now runs whenever a
live scope arms `_live_global_names`. The field, the parameter, its docstring
paragraph and the kwarg at the module load site are deleted.

What that changes, per load path, against the parent:

- `AOTCompiledModel.deserialize` (`guard_globals` only): the merge already ran
  there, so nothing changes. The module-shape test below passes on the parent
  as well; what it pins is that the merge cannot be deleted.
- `AOTCompiledFunction.deserialize(data, guard_globals=G)` with no `f_globals`:
  an artifact whose bytecode reads an unlifted certified global failed to load
  with `Missing required external references`; it now loads with `G`'s value
  bound. For a certified global the serialized scope does carry, the parent
  bound the serialized value at load and took `G`'s only from the first call's
  `_serve` re-take; `G`'s is now bound from the load, so `fn.__globals__`
  agrees with the scope before the first call too. The function-shape test
  pins the first half and fails on the parent.
- `deserialize(data, f_globals=X, guard_globals=G)` with two distinct dicts: a
  certified name both bind is taken from `G` from the load onwards, where the
  parent bound `X`'s at load and `G`'s from the first call. Only
  `fn.__globals__` between load and first call can observe the difference; the
  call results are identical. The `deserialize` docstring now states this
  precedence.
- `torch.compiler.load_compiled_function(f, f_globals=X)` passes `X` as both
  `f_globals` and `guard_globals`, so the set of names bound at load and their
  values are the same as before; the public loader is unchanged.
- No live scope (`guard_globals=None`, any `f_globals`): unchanged; the bind
  sits inside the `guard_scope is not None` branch.

The loop body in `_serve` changes alongside: `if name in scope: f_globals[name]
= scope[name]` becomes a single `scope.get(name, _UNBOUND)`, so a `del
scope[name]` racing the two-step form from another thread can no longer raise
`KeyError` out of a call whose guards already passed; the name is still skipped
rather than deleted, exactly as the docstring says. The load-time bind takes
the same `.get(name, _UNBOUND)` form for the same reason: it now runs on every
live-scope load, including one against a live module dict, and the
`in`-then-subscript two-step it replaces could raise `KeyError` out of
`deserialize`. Both narrow an escape, not the guard-check-to-re-read window,
which stays non-atomic as `_serve`'s docstring says.

Test Plan:

Two tests, each parametrized over a shape that mutates a global list and one
that returns it, both under keep_global_guards -- four cases. Each asserts the
name is in external_refs and in neither used_globals nor import_sources, that
the load arms `_live_global_names` and binds the live list into
fn.__globals__, and that the call mutates or returns that same list. The
module-shape test loads through `_load_aot_compiled_module`; the function-shape
test saves with `save_compiled_function` and loads with
`AOTCompiledFunction.deserialize(data, guard_globals=globals())`, no
`f_globals`. With the parent's `torch/_dynamo/aot_compile.py` checked into the
tree and this test file kept, the four cases give `FAILED (errors=2)`: both
function-shape cases error with `RuntimeError: Missing required external
references: ['AOT_GLOBAL_LOG']` and both module-shape cases pass. With the
`extra_globals = {**(extra_globals or {}), **live}` line deleted from this
commit's file, all four fail at load with that same RuntimeError.

```
python test/dynamo/test_aot_compile.py -k binds_a_certified_global_the_graph_never_lifted
python test/dynamo/test_aot_compile.py
lintrunner --take RUFF,PYFMT -- torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py
```

The four cases report `Ran 4 tests ... OK`; the full file `Ran 242 tests ...
OK (skipped=6)` against the parent's `Ran 238 tests ... OK (skipped=6)`; lint
`ok No lint issues.`

Authored with an AI assistant (Claude).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: b037342
Pull-Request: #196909
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
… not have

Tests only, and end to end: a module artifact guards a global, the loading
process does not define it, and the call has to fail loudly with a report that
says which compiled input failed and how -- `[0] KeyError on
G['AOT_HERMETIC_WEIGHT']` -- and that names the scope its guards were rooted
at: the globals of the module where `HermeticModule.forward` is defined, which
on this path is the only place the caller could put it. That advice is then
taken, and the test pins how far taking it goes at this commit: defining the
name in the named scope resolves the guard and the same call is served, but the
tensor served is the one serialized with the artifact rather than the one just
defined, because the bytecode's globals are built once, at load, and substitute
a live value only for a name the scope has then. Binding `saved * 2` and
asserting `x @ saved` is what pins that, and it is what makes the recovery
assertion say which dict the dispatch read rather than only that it stopped
raising: asserting `x @ (saved * 2)` instead fails (`Tensor-likes are not
close! Mismatched elements: 9 / 9`), and rooting the guards at a copy of the
live scope rather than the dict itself is caught first by the hint assertion --
the report drops the forward clause when the resolved dict is not the one the
guards hold -- with the recovery arm as the second line of defence, pinning
which dict the dispatch READ.

That `x @ saved` value is the parent's load-time snapshot, recorded here as
the limitation it is and not as the intended end state: #196897, two commits
up this stack, makes a loaded module artifact re-read the live value on every
call and flips this very assertion to `x @ (saved * 2)`, using this test as
the witness that its recorded name set is not intersected with the scope at
load. The pin stays in this commit so that flip lands as a measured behaviour
change rather than a silent one; the test comment says the same in one
sentence, without the PR number, so it reads correctly both before and after
that commit. Binding `saved` instead, which would make the arm invariant under
#196897, was considered and declined: it would leave this test unable to tell
the live dict from the serialized copy, and #196897 would have to re-add
`saved * 2` to use it as a witness.

The report is also asserted to carry the generic mismatch advice next to that
hint: a missing global counts as the mismatch it is, because the report cannot
tell whether a new `ModelInput` would read the absent global -- one captured
for a branch that does not read it is served with the name still undefined --
so both lines are emitted, and for `HermeticModule`, which reads the global on
its only path, the hint is the actionable half. The forward clause the test
asserts is emitted when the scope `model.forward` resolves to is the dict the
guards hold (`resolved is not None and resolved is
missing_global._guard_globals`), which is the case for a load that passed no
`guard_globals=`, resolved forward, and is not rebound after the load;
`test_no_match_message_hint_covers_a_rebound_forward` rebinds BEFORE loading
and so gets the clause too, while `..._survives_a_forward_resolve_that_raises`
rebinds after and asserts it absent. What tells this test from the rebound
sibling is the recovery arm: defining the name in `globals()` serves the call
here, where the same binding in that sibling still raises.

Worth its own test because the alternative -- falling back to the serialized
scope -- makes the guard a no-op checked against capture-time state, which is
the silent failure mode; loud is recoverable on the serving machine. Most of the
load-bearing assertions are on #196823's no-match report and its forward-naming
hint -- the recovery assertion is on #196818's live-scope rooting -- so this
could equally have been folded into #196823; it stays separate because a
guarded global the loading process does not have is a failure mode of its own,
independent of where an opted-out result sits in dispatch and of what the
report says when a tree raised, and each of those gets the commit that pins it.
The fixture is the same `HermeticModule` and module-level weight
`test_aot_compile_module_reload_reads_the_live_global` uses -- the test for the
opposite direction, that a reloaded artifact reads the live global -- rather
than a second copy of it that differed only in an unchecked scale factor. Like
that sibling it hides the module dict's leaked generated globals through the
shared helper before capturing, since the scope resolved from `model.forward` is
this module's dict and the capture leaks Dynamo's generated names into it. The
load seeds nothing here, for the reason that sibling's comment gives: the only
kept global guard is rooted at `AOT_HERMETIC_WEIGHT`, not at an import alias or
the builtins-dict key. Unlike that test, the reloading wrapper here takes no
`guard_filter_fn`: the load installs the artifact's own guards and captures
nothing, so the loading process's filter has no say in what a loaded artifact
checks -- that sibling does pass a filter on its reload, where it is equally
inert.

No behaviour change vs the parent: the diff is one 66-line test, nothing under
torch/ moves.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_absent_global_fails_guard
```

Run in one process with the tests that share the fixture and the report, which
unittest orders after this one, to show they still pass with it running first
(5 tests, OK):

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_absent_global_fails_guard -k test_aot_compile_module_reload_reads_the_live_global -k test_missing_key_inside_a_present_global_is_not_a_missing_global -k test_no_match_message_keeps_the_advice_for_every_entry -k test_no_match_message_hint_covers_a_rebound_forward
```

The whole file was run at this commit:

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

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 15adc8c
Pull-Request: #196825
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
…and that its advice stays

Tests only, for the no-match report the report commit (#196823) raises, split
out of it so that its review fits in one pass -- the pattern of #196824 and
#196825, which pin the dispatch's last resort and a guarded global the loading
process does not have from test-only commits. Each of the four passes at the
report commit, whose report it pins, and fails below it, at the dispatch commit
049617d (#196929), where the no-match fall-through `results[0](self.model,
*args, **kwargs)` raises the function path's `GuardManager check failed`
message. That message is not empty of the report's text: it quotes the guard's
`KeyError on G[...]` part and, for a whole missing global, appends the function
path's hint sentence, so the `loaded against; define it there`, `the module the
compiled function was traced in` and `a guarded global is missing` substrings
the tests also look for are present there. What it lacks is the `[i]` entry
prefix and the `Add a ModelInput` footer, and each of the four asserts on one
of those two: measured with that commit's `aot_compile.py` under this tree's
test file, `stays_neutral`, `advises_an_input` and `resolves_forward_only` each
fail on `"[0] KeyError on G[...]" not found` alone, and
`missing_key_inside_a_present_global` on `'Add a ModelInput' not found` alone.
Every one of them captures in this process, so every one calls
`_hide_leaked_dynamo_globals()` on entry, as the capture-only
`test_aot_compile_fn_missing_global_hint_names_the_tracing_scope` does. What
each catches at this tree, and which of the report commit's own tests would
catch the same edit, was measured by editing the report:

`test_no_match_message_hint_stays_neutral_for_a_supplied_scope` loads through
`AOTCompiledModel.deserialize(..., guard_globals=...)` with a dict that never
had the guarded name, so the guards hold a dict no `forward` resolves to,
asserts the scope-neutral wording, and then the advice it gives:
`compiled_results[0]._guard_globals is scope`, and defining the name in that
dict serves the call -- with `AOT_HERMETIC_WEIGHT` defined in this module's
dict, where the class's `forward` lives, the whole time. The wording is decided
by the identity compare `resolved is not missing_global._guard_globals`, and
this test is not the only one that pins it: reducing the condition to `resolved
is None` fails it with a report that names `this HermeticModule instance's
forward`, and of the file's 194 tests fails exactly one other, #196818's
`test_aot_compile_module_missing_global_hint_names_the_resolved_module`, whose
second half loads with `guard_globals=dict(globals())` -- a copy of the module
dict, taken while the module itself lacked the name, that is not the dict
`forward` resolves to -- and asserts `loaded against; define it there`. The
report commit's `test_no_match_report_survives_a_forward_resolve_that_raises`
reaches the neutral wording through `resolved is None`, and
`test_no_match_message_hint_covers_a_rebound_forward` through a resolve that IS
the dict the guards hold, so both pass under that edit. What this test adds
over `..._names_the_resolved_module` is the other way to the wording, a
supplied dict that never had the name rather than a stale copy carrying the
module's `__name__`, and the recovery: no other
`AOTCompiledModel.deserialize(..., guard_globals=)` test defines a missing name
in the supplied dict and asserts the call is served
(`..._deserialize_takes_a_guard_globals_scope` supplies a copy that already
carries its names, and `covers_a_rebound_forward` defines the name in the dict
the load RESOLVED, not one the caller passed).

`test_missing_key_inside_a_present_global_is_not_a_missing_global` pins which
predicate the report reaches for. A guard on
`G['GLOBAL_POOLING_CONFIG']['pooling']` with the KEY popped reports `KeyError
on G['GLOBAL_POOLING_CONFIG']['pooling']`, asserted in full, as the function
path's `test_aot_compile_fn_missing_nested_key_gets_no_missing_global_hint`
asserts it -- an ordinary mismatch: the report keeps the advice and withholds
the hint, whose "define the global" would be wrong. Replacing
`_names_a_missing_global` with a `"KeyError on G["` substring test fails it on
the hint's presence, and passes every report test in the report commit, each
of whose missing globals is a whole part. The whole-part match itself came in
with the function path's hint and is pinned there.

`test_no_match_message_advises_an_input_for_a_missing_global` pins the shape
the report commit's argument for unconditional advice rests on.
`SelfModeBranchGlobalModule`, the fixture it adds, branches on `self.mode`
rather than an argument: that guard is a `LOCAL_UNSPECIALIZED_NN_MODULE`
source, which sorts after `GLOBAL`, so the root's `G` accessor is installed --
and fails -- before the `self.mode` guard (the `L['x']` `TENSOR_MATCH`, a
`LOCAL`, precedes both), and the one entry names only the missing global.
`check_verbose` quotes the first failing guard and nothing after it, so the
absence of `L['self'].mode` from that report cannot by itself show a mismatch
was hidden; the test then puts the global back and calls again, and the same
call now fails on `[0] L['self'].mode == 1` alone. The two halves run in that
order because a failed `check()` re-sorts the root's children by fail count
(`GuardManager::check_nopybind`, guards.cpp): had `self.mode` failed first, it
would sit ahead of the `G` accessor and the popped-global call would name it
instead of the KeyError. An input captured for the `mode == 2` branch would not
read `AOT_BRANCH_SCALE` at all, so the advice is right and is the only
actionable line. Withholding it when every entry named a missing global --
counting the entries that did and returning before the footer when the count is
the whole report -- fails it on `Add a ModelInput`; two other one-entry reports
on a missing global fail under that edit as well, the report commit's
`test_no_match_report_survives_a_forward_resolve_that_raises` and this commit's
`test_no_match_report_resolves_forward_only_for_a_supplied_scope` (`failures=3`
on the whole file, all on `'Add a ModelInput' not found`), and
`test_no_match_message_keeps_the_advice_for_every_entry`, which pairs the
missing global with a plain mismatch, passes. What this test adds is the hidden
mismatch, which none of those has.

`test_no_match_report_resolves_forward_only_for_a_supplied_scope` is the
CAPTURED half of the pair whose SUPPLIED half,
`test_no_match_report_survives_a_forward_resolve_that_raises`, stays with the
report. It captures a plain `HermeticModule` in-process, pops the global, and
asserts the CAPTURED report arrives with no `forward` named. It wraps
`_resolve_guard_scope` in a `patch(..., wraps=...)` for the call and asserts it
was never invoked, since the wording alone cannot pin the gate: the CAPTURED
hint never names `forward`, so it reads the same whether or not the resolve
ran. Replacing the SUPPLIED gate with `if True:` fails it on the count,
`Expected '_resolve_guard_scope' to not have been called. Called 1 times`, with
the `except Exception` around the resolve kept or removed, and passes every
other SUPPLIED report test -- the report commit's
`test_no_match_report_survives_a_forward_resolve_that_raises` and
`test_no_match_message_hint_covers_a_rebound_forward`, and this commit's
`test_no_match_message_hint_stays_neutral_for_a_supplied_scope`, all of which
resolve either way -- so this is the one test that pins the gate. The count
carries the assertion, so the test no longer rebinds `forward` to a
`functools.partial` over `RaisingReprModule`: on this path a resolve that
raised would be swallowed by that catch and change nothing the test could see,
and the catch itself is `survives_a_forward_resolve_that_raises`'s to pin --
with the catch removed it errors with `ValueError: extra_repr`.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_hint_stays_neutral_for_a_supplied_scope
python test/dynamo/test_aot_compile.py -k test_missing_key_inside_a_present_global_is_not_a_missing_global
python test/dynamo/test_aot_compile.py -k test_no_match_message_advises_an_input_for_a_missing_global
python test/dynamo/test_aot_compile.py -k test_no_match_report_resolves_forward_only_for_a_supplied_scope
python test/dynamo/test_aot_compile.py
```

The whole file runs 194 tests here, 190 on the parent commit: `Ran 194
tests`, `OK (skipped=6)`.

## FAQ

> **FAQ: The review asked that
> `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` read
> `AOT_HERMETIC_WEIGHT` through a reference captured at import instead of
> asserting it is in `HermeticModule.forward.__globals__`. Why an identity
> assertion instead?**
>
> The membership assertion was standing in for a claim about which dict the
> guards read, so the test states that claim directly:
> `compiled.compiled_results[0]._guard_globals is scope` -- the guards hold the
> supplied dict -- and the read that follows, `scope["AOT_HERMETIC_WEIGHT"] =
> AOT_HERMETIC_WEIGHT` serving the call, is the dict a forward-naming hint would
> have sent the reader away from. An earlier revision also asserted
> `HermeticModule.forward.__globals__ is globals()`; that holds by construction
> for a class defined in this file and observes nothing about the code under
> test, so it is gone. The two bare `AOT_HERMETIC_WEIGHT` reads are pre-existing
> and shared with every test in the file that uses the fixture; a sibling that
> failed to restore the name would break the module, not this test's ordering,
> and a captured alias would only move that dependency to import time.

> **FAQ: The review asked
> `test_no_match_message_advises_an_input_for_a_missing_global` to first show
> the report naming `L['self'].mode` with the global defined, then pop the
> global and show the KeyError replacing it. Why the other order?**
>
> Because the guard tree remembers its failures. `GuardManager::check_nopybind`
> (torch/csrc/dynamo/guards.cpp) bumps a child's fail count when it rejects and,
> unless the failure was on the first child, re-sorts the root's accessors by
> fail count so the next check fails fast. Run the mismatch half first and the
> `self.mode` accessor moves ahead of the `G` accessor; the popped-global call
> then reports `L['self'].mode == 1` rather than the KeyError (measured on a
> scratch copy: both calls name `self.mode`). Popped first, the `G` accessor
> is the one promoted, it resolves once the global is back, and the second call
> fails on `self.mode` alone -- which is the positive witness the review asked
> for, on the same compiled result.

> **FAQ: The review found that
> `test_aot_compile_module_missing_global_hint_names_the_resolved_module`, in
> #196818 below, already fails under the `resolved is None` edit that this
> commit's `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` was
> described as the one test to catch. Why keep the test?**
>
> Because the coverage claim was wrong, and the test's other half is not pinned
> anywhere else. Re-measured on the whole file with the compare reduced to
> `resolved is None`: `Ran 194 tests`, `FAILED (failures=2)`, the two being
> `..._names_the_resolved_module` (`'loaded against; define it there' not
> found`) and this test; every other test passes. So the identity compare is
> fenced at #196818, and the message now says so instead of crediting this
> test. What this test alone covers is a `guard_globals=` dict that never had
> the name -- `..._names_the_resolved_module` reaches the same wording through
> `dict(globals())`, a copy taken while the module itself lacked the name --
> and the recovery, defining the name in that dict and asserting the call is
> served, which no other `AOTCompiledModel.deserialize(..., guard_globals=)`
> test does. The same pass dropped the static
> `HermeticModule.forward.__globals__ is globals()` assertion, replaced the
> raising-repr scaffolding in `..._resolves_forward_only_for_a_supplied_scope`
> with a plain `HermeticModule()` (the mock's call count carries the
> assertion; a raise on that path would be swallowed by the report's catch),
> and moved the `patch(...)` construction there above `g.pop` so nothing sits
> between the pop and the `try`.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: b077b77
Pull-Request: #197001
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
…e-scope path, drop bytecode_reads_guard_scope

`AOTCompiledFunction` carried a `_bytecode_reads_guard_scope` flag, a matching
`deserialize(bytecode_reads_guard_scope=...)` parameter with its own docstring
paragraph, and a block in `__post_init__` that, when the flag was set, copied the
certified globals out of the supplied scope into the dict `forward_callable`
builds for the bytecode. Only `AOTCompiledModel.deserialize` passed `True`. All
of it came from #196818 of this stack, landed on main as 82c1f1e and in no
release tag, and nothing outside `AOTCompiledModel.deserialize` ever passed the
parameter, so deleting it breaks no released or in-tree caller.

That merge is not redundant with `_serve`'s per-call re-take, even though both
write the same names from the same dict: `forward_callable` runs
`_check_external_refs` over `{**import_sources, **used_globals, **extra_globals}`
at load, and `get_runtime_env` fills `used_globals` only from the graph inputs'
global roots plus the builtins the bytecode reads. A global the generated
bytecode LOAD_GLOBALs but the graph never lifted -- the side-effect replay of a
mutated global container or object, or the reconstruct of a returned global -- is
in `external_refs` and in no serialized scope, while a `guard_filter_fn` that
keeps global guards leaves a serializable TYPE_MATCH or SEQUENCE_LENGTH rooted at
its bare GlobalSource, so it is certified. On the module load path, which passes
no `f_globals`, the merge was the only thing binding that name before the check;
without it the load raises `Missing required external references`. So
`_guard_source_globals(output_graph) <= used_globals | import_sources` does not
hold, and the merge stays. What goes is the flag: the merge now runs whenever a
live scope arms `_live_global_names`. The field, the parameter, its docstring
paragraph and the kwarg at the module load site are deleted.

What that changes, per load path, against the parent:

- `AOTCompiledModel.deserialize` (`guard_globals` only): the merge already ran
  there, so nothing changes. The module-shape test below passes on the parent
  as well; what it pins is that the merge cannot be deleted.
- `AOTCompiledFunction.deserialize(data, guard_globals=G)` with no `f_globals`:
  an artifact whose bytecode reads an unlifted certified global failed to load
  with `Missing required external references`; it now loads with `G`'s value
  bound. For a certified global the serialized scope does carry, the parent
  bound the serialized value at load and took `G`'s only from the first call's
  `_serve` re-take; `G`'s is now bound from the load, so `fn.__globals__`
  agrees with the scope before the first call too. The function-shape test
  pins the first half and fails on the parent.
- `deserialize(data, f_globals=X, guard_globals=G)` with two distinct dicts: a
  certified name both bind is taken from `G` from the load onwards, where the
  parent bound `X`'s at load and `G`'s from the first call. Only
  `fn.__globals__` between load and first call can observe the difference; the
  call results are identical. The `deserialize` docstring now states this
  precedence.
- `torch.compiler.load_compiled_function(f, f_globals=X)` passes `X` as both
  `f_globals` and `guard_globals`, so the set of names bound at load and their
  values are the same as before; the public loader is unchanged.
- No live scope (`guard_globals=None`, any `f_globals`): unchanged; the bind
  sits inside the `guard_scope is not None` branch.

The loop body in `_serve` changes alongside: `if name in scope: f_globals[name]
= scope[name]` becomes a single `scope.get(name, _UNBOUND)`, so a `del
scope[name]` racing the two-step form from another thread can no longer raise
`KeyError` out of a call whose guards already passed; the name is still skipped
rather than deleted, exactly as the docstring says. The load-time bind takes
the same `.get(name, _UNBOUND)` form for the same reason: it now runs on every
live-scope load, including one against a live module dict, and the
`in`-then-subscript two-step it replaces could raise `KeyError` out of
`deserialize`. Both narrow an escape, not the guard-check-to-re-read window,
which stays non-atomic as `_serve`'s docstring says.

Test Plan:

Two tests, each parametrized over a shape that mutates a global list and one
that returns it, both under keep_global_guards -- four cases. Each asserts the
name is in external_refs and in neither used_globals nor import_sources, that
the load arms `_live_global_names` and binds the live list into
fn.__globals__, and that the call mutates or returns that same list. The
module-shape test loads through `_load_aot_compiled_module`; the function-shape
test saves with `save_compiled_function` and loads with
`AOTCompiledFunction.deserialize(data, guard_globals=globals())`, no
`f_globals`. With the parent's `torch/_dynamo/aot_compile.py` checked into the
tree and this test file kept, the four cases give `FAILED (errors=2)`: both
function-shape cases error with `RuntimeError: Missing required external
references: ['AOT_GLOBAL_LOG']` and both module-shape cases pass. With the
`extra_globals = {**(extra_globals or {}), **live}` line deleted from this
commit's file, all four fail at load with that same RuntimeError.

```
python test/dynamo/test_aot_compile.py -k binds_a_certified_global_the_graph_never_lifted
python test/dynamo/test_aot_compile.py
lintrunner --take RUFF,PYFMT -- torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py
```

The four cases report `Ran 4 tests ... OK`; the full file `Ran 242 tests ...
OK (skipped=6)` against the parent's `Ran 238 tests ... OK (skipped=6)`; lint
`ok No lint issues.`

Authored with an AI assistant (Claude).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: f530baa
Pull-Request: #196909
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
… not have

Tests only, and end to end: a module artifact guards a global, the loading
process does not define it, and the call has to fail loudly with a report that
says which compiled input failed and how -- `[0] KeyError on
G['AOT_HERMETIC_WEIGHT']` -- and that names the scope its guards were rooted
at: the globals of the module where `HermeticModule.forward` is defined, which
on this path is the only place the caller could put it. That advice is then
taken, and the test pins how far taking it goes at this commit: defining the
name in the named scope resolves the guard and the same call is served, but the
tensor served is the one serialized with the artifact rather than the one just
defined, because the bytecode's globals are built once, at load, and substitute
a live value only for a name the scope has then. Binding `saved * 2` and
asserting `x @ saved` is what pins that, and it is what makes the recovery
assertion say which dict the dispatch read rather than only that it stopped
raising: asserting `x @ (saved * 2)` instead fails (`Tensor-likes are not
close! Mismatched elements: 9 / 9`), and rooting the guards at a copy of the
live scope rather than the dict itself is caught first by the hint assertion --
the report drops the forward clause when the resolved dict is not the one the
guards hold -- with the recovery arm as the second line of defence, pinning
which dict the dispatch READ.

That `x @ saved` value is the parent's load-time snapshot, recorded here as
the limitation it is and not as the intended end state: #196897, two commits
up this stack, makes a loaded module artifact re-read the live value on every
call and flips this very assertion to `x @ (saved * 2)`, using this test as
the witness that its recorded name set is not intersected with the scope at
load. The pin stays in this commit so that flip lands as a measured behaviour
change rather than a silent one; the test comment says the same in one
sentence, without the PR number, so it reads correctly both before and after
that commit. Binding `saved` instead, which would make the arm invariant under
#196897, was considered and declined: it would leave this test unable to tell
the live dict from the serialized copy, and #196897 would have to re-add
`saved * 2` to use it as a witness.

The report is also asserted to carry the generic mismatch advice next to that
hint: a missing global counts as the mismatch it is, because the report cannot
tell whether a new `ModelInput` would read the absent global -- one captured
for a branch that does not read it is served with the name still undefined --
so both lines are emitted, and for `HermeticModule`, which reads the global on
its only path, the hint is the actionable half. The forward clause the test
asserts is emitted when the scope `model.forward` resolves to is the dict the
guards hold (`resolved is not None and resolved is
missing_global._guard_globals`), which is the case for a load that passed no
`guard_globals=`, resolved forward, and is not rebound after the load;
`test_no_match_message_hint_covers_a_rebound_forward` rebinds BEFORE loading
and so gets the clause too, while `..._survives_a_forward_resolve_that_raises`
rebinds after and asserts it absent. What tells this test from the rebound
sibling is the recovery arm: defining the name in `globals()` serves the call
here, where the same binding in that sibling still raises.

Worth its own test because the alternative -- falling back to the serialized
scope -- makes the guard a no-op checked against capture-time state, which is
the silent failure mode; loud is recoverable on the serving machine. Most of the
load-bearing assertions are on #196823's no-match report and its forward-naming
hint -- the recovery assertion is on #196818's live-scope rooting -- so this
could equally have been folded into #196823; it stays separate because a
guarded global the loading process does not have is a failure mode of its own,
independent of where an opted-out result sits in dispatch and of what the
report says when a tree raised, and each of those gets the commit that pins it.
The fixture is the same `HermeticModule` and module-level weight
`test_aot_compile_module_reload_reads_the_live_global` uses -- the test for the
opposite direction, that a reloaded artifact reads the live global -- rather
than a second copy of it that differed only in an unchecked scale factor. Like
that sibling it hides the module dict's leaked generated globals through the
shared helper before capturing, since the scope resolved from `model.forward` is
this module's dict and the capture leaks Dynamo's generated names into it. The
load seeds nothing here, for the reason that sibling's comment gives: the only
kept global guard is rooted at `AOT_HERMETIC_WEIGHT`, not at an import alias or
the builtins-dict key. Unlike that test, the reloading wrapper here takes no
`guard_filter_fn`: the load installs the artifact's own guards and captures
nothing, so the loading process's filter has no say in what a loaded artifact
checks -- that sibling does pass a filter on its reload, where it is equally
inert.

No behaviour change vs the parent: the diff is one 66-line test, nothing under
torch/ moves.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_absent_global_fails_guard
```

Run in one process with the tests that share the fixture and the report, which
unittest orders after this one, to show they still pass with it running first
(5 tests, OK):

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_absent_global_fails_guard -k test_aot_compile_module_reload_reads_the_live_global -k test_missing_key_inside_a_present_global_is_not_a_missing_global -k test_no_match_message_keeps_the_advice_for_every_entry -k test_no_match_message_hint_covers_a_rebound_forward
```

The whole file was run at this commit:

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

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 32e8500
Pull-Request: #196825
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
…and that its advice stays

Tests only, for the no-match report the report commit (#196823) raises, split
out of it so that its review fits in one pass -- the pattern of #196824 and
#196825, which pin the dispatch's last resort and a guarded global the loading
process does not have from test-only commits. Each of the four passes at the
report commit, whose report it pins, and fails below it, at the dispatch commit
049617d (#196929), where the no-match fall-through `results[0](self.model,
*args, **kwargs)` raises the function path's `GuardManager check failed`
message. That message is not empty of the report's text: it quotes the guard's
`KeyError on G[...]` part and, for a whole missing global, appends the function
path's hint sentence, so the `loaded against; define it there`, `the module the
compiled function was traced in` and `a guarded global is missing` substrings
the tests also look for are present there. What it lacks is the `[i]` entry
prefix and the `Add a ModelInput` footer, and each of the four asserts on one
of those two: measured with that commit's `aot_compile.py` under this tree's
test file, `stays_neutral`, `advises_an_input` and `resolves_forward_only` each
fail on `"[0] KeyError on G[...]" not found` alone, and
`missing_key_inside_a_present_global` on `'Add a ModelInput' not found` alone.
Every one of them captures in this process, so every one calls
`_hide_leaked_dynamo_globals()` on entry, as the capture-only
`test_aot_compile_fn_missing_global_hint_names_the_tracing_scope` does. What
each catches at this tree, and which of the report commit's own tests would
catch the same edit, was measured by editing the report:

`test_no_match_message_hint_stays_neutral_for_a_supplied_scope` loads through
`AOTCompiledModel.deserialize(..., guard_globals=...)` with a dict that never
had the guarded name, so the guards hold a dict no `forward` resolves to,
asserts the scope-neutral wording, and then the advice it gives:
`compiled_results[0]._guard_globals is scope`, and defining the name in that
dict serves the call -- with `AOT_HERMETIC_WEIGHT` defined in this module's
dict, where the class's `forward` lives, the whole time. The wording is decided
by the identity compare `resolved is not missing_global._guard_globals`, and
this test is not the only one that pins it: reducing the condition to `resolved
is None` fails it with a report that names `this HermeticModule instance's
forward`, and of the file's 194 tests fails exactly one other, #196818's
`test_aot_compile_module_missing_global_hint_names_the_resolved_module`, whose
second half loads with `guard_globals=dict(globals())` -- a copy of the module
dict, taken while the module itself lacked the name, that is not the dict
`forward` resolves to -- and asserts `loaded against; define it there`. The
report commit's `test_no_match_report_survives_a_forward_resolve_that_raises`
reaches the neutral wording through `resolved is None`, and
`test_no_match_message_hint_covers_a_rebound_forward` through a resolve that IS
the dict the guards hold, so both pass under that edit. What this test adds
over `..._names_the_resolved_module` is the other way to the wording, a
supplied dict that never had the name rather than a stale copy carrying the
module's `__name__`, and the recovery: no other
`AOTCompiledModel.deserialize(..., guard_globals=)` test defines a missing name
in the supplied dict and asserts the call is served
(`..._deserialize_takes_a_guard_globals_scope` supplies a copy that already
carries its names, and `covers_a_rebound_forward` defines the name in the dict
the load RESOLVED, not one the caller passed).

`test_missing_key_inside_a_present_global_is_not_a_missing_global` pins which
predicate the report reaches for. A guard on
`G['GLOBAL_POOLING_CONFIG']['pooling']` with the KEY popped reports `KeyError
on G['GLOBAL_POOLING_CONFIG']['pooling']`, asserted in full, as the function
path's `test_aot_compile_fn_missing_nested_key_gets_no_missing_global_hint`
asserts it -- an ordinary mismatch: the report keeps the advice and withholds
the hint, whose "define the global" would be wrong. Replacing
`_names_a_missing_global` with a `"KeyError on G["` substring test fails it on
the hint's presence, and passes every report test in the report commit, each
of whose missing globals is a whole part. The whole-part match itself came in
with the function path's hint and is pinned there.

`test_no_match_message_advises_an_input_for_a_missing_global` pins the shape
the report commit's argument for unconditional advice rests on.
`SelfModeBranchGlobalModule`, the fixture it adds, branches on `self.mode`
rather than an argument: that guard is a `LOCAL_UNSPECIALIZED_NN_MODULE`
source, which sorts after `GLOBAL`, so the root's `G` accessor is installed --
and fails -- before the `self.mode` guard (the `L['x']` `TENSOR_MATCH`, a
`LOCAL`, precedes both), and the one entry names only the missing global.
`check_verbose` quotes the first failing guard and nothing after it, so the
absence of `L['self'].mode` from that report cannot by itself show a mismatch
was hidden; the test then puts the global back and calls again, and the same
call now fails on `[0] L['self'].mode == 1` alone. The two halves run in that
order because a failed `check()` re-sorts the root's children by fail count
(`GuardManager::check_nopybind`, guards.cpp): had `self.mode` failed first, it
would sit ahead of the `G` accessor and the popped-global call would name it
instead of the KeyError. An input captured for the `mode == 2` branch would not
read `AOT_BRANCH_SCALE` at all, so the advice is right and is the only
actionable line. Withholding it when every entry named a missing global --
counting the entries that did and returning before the footer when the count is
the whole report -- fails it on `Add a ModelInput`; two other one-entry reports
on a missing global fail under that edit as well, the report commit's
`test_no_match_report_survives_a_forward_resolve_that_raises` and this commit's
`test_no_match_report_resolves_forward_only_for_a_supplied_scope` (`failures=3`
on the whole file, all on `'Add a ModelInput' not found`), and
`test_no_match_message_keeps_the_advice_for_every_entry`, which pairs the
missing global with a plain mismatch, passes. What this test adds is the hidden
mismatch, which none of those has.

`test_no_match_report_resolves_forward_only_for_a_supplied_scope` is the
CAPTURED half of the pair whose SUPPLIED half,
`test_no_match_report_survives_a_forward_resolve_that_raises`, stays with the
report. It captures a plain `HermeticModule` in-process, pops the global, and
asserts the CAPTURED report arrives with no `forward` named. It wraps
`_resolve_guard_scope` in a `patch(..., wraps=...)` for the call and asserts it
was never invoked, since the wording alone cannot pin the gate: the CAPTURED
hint never names `forward`, so it reads the same whether or not the resolve
ran. Replacing the SUPPLIED gate with `if True:` fails it on the count,
`Expected '_resolve_guard_scope' to not have been called. Called 1 times`, with
the `except Exception` around the resolve kept or removed, and passes every
other SUPPLIED report test -- the report commit's
`test_no_match_report_survives_a_forward_resolve_that_raises` and
`test_no_match_message_hint_covers_a_rebound_forward`, and this commit's
`test_no_match_message_hint_stays_neutral_for_a_supplied_scope`, all of which
resolve either way -- so this is the one test that pins the gate. The count
carries the assertion, so the test no longer rebinds `forward` to a
`functools.partial` over `RaisingReprModule`: on this path a resolve that
raised would be swallowed by that catch and change nothing the test could see,
and the catch itself is `survives_a_forward_resolve_that_raises`'s to pin --
with the catch removed it errors with `ValueError: extra_repr`.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_hint_stays_neutral_for_a_supplied_scope
python test/dynamo/test_aot_compile.py -k test_missing_key_inside_a_present_global_is_not_a_missing_global
python test/dynamo/test_aot_compile.py -k test_no_match_message_advises_an_input_for_a_missing_global
python test/dynamo/test_aot_compile.py -k test_no_match_report_resolves_forward_only_for_a_supplied_scope
python test/dynamo/test_aot_compile.py
```

The whole file runs 194 tests here, 190 on the parent commit: `Ran 194
tests`, `OK (skipped=6)`.

## FAQ

> **FAQ: The review asked that
> `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` read
> `AOT_HERMETIC_WEIGHT` through a reference captured at import instead of
> asserting it is in `HermeticModule.forward.__globals__`. Why an identity
> assertion instead?**
>
> The membership assertion was standing in for a claim about which dict the
> guards read, so the test states that claim directly:
> `compiled.compiled_results[0]._guard_globals is scope` -- the guards hold the
> supplied dict -- and the read that follows, `scope["AOT_HERMETIC_WEIGHT"] =
> AOT_HERMETIC_WEIGHT` serving the call, is the dict a forward-naming hint would
> have sent the reader away from. An earlier revision also asserted
> `HermeticModule.forward.__globals__ is globals()`; that holds by construction
> for a class defined in this file and observes nothing about the code under
> test, so it is gone. The two bare `AOT_HERMETIC_WEIGHT` reads are pre-existing
> and shared with every test in the file that uses the fixture; a sibling that
> failed to restore the name would break the module, not this test's ordering,
> and a captured alias would only move that dependency to import time.

> **FAQ: The review asked
> `test_no_match_message_advises_an_input_for_a_missing_global` to first show
> the report naming `L['self'].mode` with the global defined, then pop the
> global and show the KeyError replacing it. Why the other order?**
>
> Because the guard tree remembers its failures. `GuardManager::check_nopybind`
> (torch/csrc/dynamo/guards.cpp) bumps a child's fail count when it rejects and,
> unless the failure was on the first child, re-sorts the root's accessors by
> fail count so the next check fails fast. Run the mismatch half first and the
> `self.mode` accessor moves ahead of the `G` accessor; the popped-global call
> then reports `L['self'].mode == 1` rather than the KeyError (measured on a
> scratch copy: both calls name `self.mode`). Popped first, the `G` accessor
> is the one promoted, it resolves once the global is back, and the second call
> fails on `self.mode` alone -- which is the positive witness the review asked
> for, on the same compiled result.

> **FAQ: The review found that
> `test_aot_compile_module_missing_global_hint_names_the_resolved_module`, in
> #196818 below, already fails under the `resolved is None` edit that this
> commit's `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` was
> described as the one test to catch. Why keep the test?**
>
> Because the coverage claim was wrong, and the test's other half is not pinned
> anywhere else. Re-measured on the whole file with the compare reduced to
> `resolved is None`: `Ran 194 tests`, `FAILED (failures=2)`, the two being
> `..._names_the_resolved_module` (`'loaded against; define it there' not
> found`) and this test; every other test passes. So the identity compare is
> fenced at #196818, and the message now says so instead of crediting this
> test. What this test alone covers is a `guard_globals=` dict that never had
> the name -- `..._names_the_resolved_module` reaches the same wording through
> `dict(globals())`, a copy taken while the module itself lacked the name --
> and the recovery, defining the name in that dict and asserting the call is
> served, which no other `AOTCompiledModel.deserialize(..., guard_globals=)`
> test does. The same pass dropped the static
> `HermeticModule.forward.__globals__ is globals()` assertion, replaced the
> raising-repr scaffolding in `..._resolves_forward_only_for_a_supplied_scope`
> with a plain `HermeticModule()` (the mock's call count carries the
> assertion; a raise on that path would be swallowed by the report's catch),
> and moved the `patch(...)` construction there above `g.pop` so nothing sits
> between the pop and the `try`.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 4c20b93
Pull-Request: #197001
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
…e-scope path, drop bytecode_reads_guard_scope

`AOTCompiledFunction` carried a `_bytecode_reads_guard_scope` flag, a matching
`deserialize(bytecode_reads_guard_scope=...)` parameter with its own docstring
paragraph, and a block in `__post_init__` that, when the flag was set, copied the
certified globals out of the supplied scope into the dict `forward_callable`
builds for the bytecode. Only `AOTCompiledModel.deserialize` passed `True`. All
of it came from #196818 of this stack, landed on main as 82c1f1e and in no
release tag, and nothing outside `AOTCompiledModel.deserialize` ever passed the
parameter, so deleting it breaks no released or in-tree caller.

That merge is not redundant with `_serve`'s per-call re-take, even though both
write the same names from the same dict: `forward_callable` runs
`_check_external_refs` over `{**import_sources, **used_globals, **extra_globals}`
at load, and `get_runtime_env` fills `used_globals` only from the graph inputs'
global roots plus the builtins the bytecode reads. A global the generated
bytecode LOAD_GLOBALs but the graph never lifted -- the side-effect replay of a
mutated global container or object, or the reconstruct of a returned global -- is
in `external_refs` and in no serialized scope, while a `guard_filter_fn` that
keeps global guards leaves a serializable TYPE_MATCH or SEQUENCE_LENGTH rooted at
its bare GlobalSource, so it is certified. On the module load path, which passes
no `f_globals`, the merge was the only thing binding that name before the check;
without it the load raises `Missing required external references`. So
`_guard_source_globals(output_graph) <= used_globals | import_sources` does not
hold, and the merge stays. What goes is the flag: the merge now runs whenever a
live scope arms `_live_global_names`. The field, the parameter, its docstring
paragraph and the kwarg at the module load site are deleted.

What that changes, per load path, against the parent:

- `AOTCompiledModel.deserialize` (`guard_globals` only): the merge already ran
  there, so nothing changes. The module-shape test below passes on the parent
  as well; what it pins is that the merge cannot be deleted.
- `AOTCompiledFunction.deserialize(data, guard_globals=G)` with no `f_globals`:
  an artifact whose bytecode reads an unlifted certified global failed to load
  with `Missing required external references`; it now loads with `G`'s value
  bound. For a certified global the serialized scope does carry, the parent
  bound the serialized value at load and took `G`'s only from the first call's
  `_serve` re-take; `G`'s is now bound from the load, so `fn.__globals__`
  agrees with the scope before the first call too. The function-shape test
  pins the first half and fails on the parent.
- `deserialize(data, f_globals=X, guard_globals=G)` with two distinct dicts: a
  certified name both bind is taken from `G` from the load onwards, where the
  parent bound `X`'s at load and `G`'s from the first call. Only
  `fn.__globals__` between load and first call can observe the difference; the
  call results are identical. The `deserialize` docstring now states this
  precedence.
- `torch.compiler.load_compiled_function(f, f_globals=X)` passes `X` as both
  `f_globals` and `guard_globals`, so the set of names bound at load and their
  values are the same as before; the public loader is unchanged.
- No live scope (`guard_globals=None`, any `f_globals`): unchanged; the bind
  sits inside the `guard_scope is not None` branch.

The loop body in `_serve` changes alongside: `if name in scope: f_globals[name]
= scope[name]` becomes a single `scope.get(name, _UNBOUND)`, so a `del
scope[name]` racing the two-step form from another thread can no longer raise
`KeyError` out of a call whose guards already passed; the name is still skipped
rather than deleted, exactly as the docstring says. The load-time bind takes
the same `.get(name, _UNBOUND)` form for the same reason: it now runs on every
live-scope load, including one against a live module dict, and the
`in`-then-subscript two-step it replaces could raise `KeyError` out of
`deserialize`. Both narrow an escape, not the guard-check-to-re-read window,
which stays non-atomic as `_serve`'s docstring says.

Test Plan:

Two tests, each parametrized over a shape that mutates a global list and one
that returns it, both under keep_global_guards -- four cases. Each asserts the
name is in external_refs and in neither used_globals nor import_sources, that
the load arms `_live_global_names` and binds the live list into
fn.__globals__, and that the call mutates or returns that same list. The
module-shape test loads through `_load_aot_compiled_module`; the function-shape
test saves with `save_compiled_function` and loads with
`AOTCompiledFunction.deserialize(data, guard_globals=globals())`, no
`f_globals`. With the parent's `torch/_dynamo/aot_compile.py` checked into the
tree and this test file kept, the four cases give `FAILED (errors=2)`: both
function-shape cases error with `RuntimeError: Missing required external
references: ['AOT_GLOBAL_LOG']` and both module-shape cases pass. With the
`extra_globals = {**(extra_globals or {}), **live}` line deleted from this
commit's file, all four fail at load with that same RuntimeError.

```
python test/dynamo/test_aot_compile.py -k binds_a_certified_global_the_graph_never_lifted
python test/dynamo/test_aot_compile.py
lintrunner --take RUFF,PYFMT -- torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py
```

The four cases report `Ran 4 tests ... OK`; the full file `Ran 242 tests ...
OK (skipped=6)` against the parent's `Ran 238 tests ... OK (skipped=6)`; lint
`ok No lint issues.`

Authored with an AI assistant (Claude).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: a2ec7bb
Pull-Request: #196909
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
Tests only, and end to end: a module artifact guards a global, the loading
process does not define it, and the call has to fail loudly with a report that
says which compiled input failed and how -- `[0] KeyError on
G['AOT_HERMETIC_WEIGHT']` -- and that names the scope its guards were rooted
at: the globals of the module where `HermeticModule.forward` is defined, which
on this path is the only place the caller could put it. That advice is then
taken, and the test pins how far taking it goes at this commit: defining the
name in the named scope resolves the guard and the same call is served, but the
tensor served is the one serialized with the artifact rather than the one just
defined, because the bytecode's globals are built once, at load, and substitute
a live value only for a name the scope has then. Binding `saved * 2` and
asserting `x @ saved` is what pins that, and it is what makes the recovery
assertion say which dict the dispatch read rather than only that it stopped
raising: asserting `x @ (saved * 2)` instead fails (`Tensor-likes are not
close! Mismatched elements: 9 / 9`), and rooting the guards at a copy of the
live scope rather than the dict itself is caught first by the hint assertion --
the report drops the forward clause when the resolved dict is not the one the
guards hold -- with the recovery arm as the second line of defence, pinning
which dict the dispatch READ.

That `x @ saved` value is the parent's load-time snapshot, recorded here as
the limitation it is and not as the intended end state: #196897, two commits
up this stack, makes a loaded module artifact re-read the live value on every
call and flips this very assertion to `x @ (saved * 2)`, using this test as
the witness that its recorded name set is not intersected with the scope at
load. The pin stays in this commit so that flip lands as a measured behaviour
change rather than a silent one; the test comment says the same in one
sentence, without the PR number, so it reads correctly both before and after
that commit. Binding `saved` instead, which would make the arm invariant under
#196897, was considered and declined: it would leave this test unable to tell
the live dict from the serialized copy, and #196897 would have to re-add
`saved * 2` to use it as a witness.

The report is also asserted to carry the generic mismatch advice next to that
hint: a missing global counts as the mismatch it is, because the report cannot
tell whether a new `ModelInput` would read the absent global -- one captured
for a branch that does not read it is served with the name still undefined --
so both lines are emitted, and for `HermeticModule`, which reads the global on
its only path, the hint is the actionable half. The forward clause the test
asserts is emitted when the scope `model.forward` resolves to is the dict the
guards hold (`resolved is not None and resolved is
missing_global._guard_globals`), which is the case for a load that passed no
`guard_globals=`, resolved forward, and is not rebound after the load;
`test_no_match_message_hint_covers_a_rebound_forward` rebinds BEFORE loading
and so gets the clause too, while `..._survives_a_forward_resolve_that_raises`
rebinds after and asserts it absent. What tells this test from the rebound
sibling is the recovery arm: defining the name in `globals()` serves the call
here, where the same binding in that sibling still raises.

Worth its own test because the alternative -- falling back to the serialized
scope -- makes the guard a no-op checked against capture-time state, which is
the silent failure mode; loud is recoverable on the serving machine. Most of the
load-bearing assertions are on #196823's no-match report and its forward-naming
hint -- the recovery assertion is on #196818's live-scope rooting -- so this
could equally have been folded into #196823; it stays separate because a
guarded global the loading process does not have is a failure mode of its own,
independent of where an opted-out result sits in dispatch and of what the
report says when a tree raised, and each of those gets the commit that pins it.
The fixture is the same `HermeticModule` and module-level weight
`test_aot_compile_module_reload_reads_the_live_global` uses -- the test for the
opposite direction, that a reloaded artifact reads the live global -- rather
than a second copy of it that differed only in an unchecked scale factor. Like
that sibling it hides the module dict's leaked generated globals through the
shared helper before capturing, since the scope resolved from `model.forward` is
this module's dict and the capture leaks Dynamo's generated names into it. The
load seeds nothing here, for the reason that sibling's comment gives: the only
kept global guard is rooted at `AOT_HERMETIC_WEIGHT`, not at an import alias or
the builtins-dict key. Unlike that test, the reloading wrapper here takes no
`guard_filter_fn`: the load installs the artifact's own guards and captures
nothing, so the loading process's filter has no say in what a loaded artifact
checks -- that sibling does pass a filter on its reload, where it is equally
inert.

No behaviour change vs the parent: the diff is one 66-line test, nothing under
torch/ moves.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_absent_global_fails_guard
```

Run in one process with the tests that share the fixture and the report, which
unittest orders after this one, to show they still pass with it running first
(5 tests, OK):

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_absent_global_fails_guard -k test_aot_compile_module_reload_reads_the_live_global -k test_missing_key_inside_a_present_global_is_not_a_missing_global -k test_no_match_message_keeps_the_advice_for_every_entry -k test_no_match_message_hint_covers_a_rebound_forward
```

The whole file was run at this commit:

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

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: b3cec7e
Pull-Request: #196825
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
… its advice stays

Tests only, for the no-match report the report commit (#196823) raises, split
out of it so that its review fits in one pass -- the pattern of #196824 and
#196825, which pin the dispatch's last resort and a guarded global the loading
process does not have from test-only commits. Each of the five passes at the
parent, whose report it pins, and fails below the report commit (at #196896,
the commit under it), where the no-match fall-through `results[0](self.model,
*args, **kwargs)` raises the function path's `GuardManager check failed`
message. That message is not empty of the report's text: it quotes the guard's
`KeyError on G[...]` part and, for a whole missing global, appends the function
path's hint sentence, so the `loaded against; define it there`, `the module the
compiled function was traced in` and `a guarded global is missing` substrings
the tests also look for are present there. What it lacks is the `[i]` entry
prefix, the `For [i]:` hint line and the `Add a ModelInput` footer, and every
test asserts on one of those: measured with that tree's `aot_compile.py` under
this tree's test file, `stays_neutral`, `advises_an_input`,
`resolves_forward_only` and `missing_key_inside_a_present_global` each fail on
`"[0] KeyError on G[...]" not found`, and
`names_forward_only_for_the_dict_it_resolves_to` on `Expected
'_resolve_guard_scope' to have been called once. Called 0 times`, the
fall-through resolving nothing. The four that compile in their own body call
`_hide_leaked_dynamo_globals()` on entry, as the capture-only
`test_aot_compile_fn_missing_global_hint_names_the_tracing_scope` does; the
fifth shares `_two_input_global_guard_artifact` with
`test_no_match_message_hints_each_scope_a_mixed_model_failed_in` and the
landed `test_aot_compile_module_missing_global_hint_names_the_resolved_module`
and, like them, does not, its kept guards being rooted at
`GLOBAL_POOLING_CONFIG` alone.

The report at this tree decides its hint per entry. An entry whose verbose
parts name a whole missing global gets `_missing_global_hint(forward=...)`,
with `forward` set when `resolved is not None and resolved is
result._guard_globals`; `resolved` is what one `_resolve_guard_scope(self.model)`
returned, run at most once, at the first hinted entry whose scope is SUPPLIED,
and reused for every entry after it. The hints are keyed by text into
`hinted`, one `For [i, j]:` line per distinct sentence, and the footer follows
unconditionally. What each test catches, and which other tests in the file
would catch the same edit, was measured by editing the report and running the
whole file (220 tests):

`test_no_match_message_hint_stays_neutral_for_a_supplied_scope` loads through
`AOTCompiledModel.deserialize(..., guard_globals=...)` with a dict that never
had the guarded name, so the guards hold a dict no `forward` resolves to,
asserts the scope-neutral wording under its `For [0]:` prefix, and then the
advice it gives: `compiled_results[0]._guard_globals is scope`, and defining
the name in that dict serves the call -- with `AOT_HERMETIC_WEIGHT` defined in
this module's dict, where the class's `forward` lives, the whole time.
Reducing the compare to `resolved is not None` fails it with a report that
names `this HermeticModule instance's forward`, and fails exactly two others
(`failures=3`): the landed #196818's `..._names_the_resolved_module`, whose
second half loads with `guard_globals=dict(globals())` -- a copy of the module
dict, taken while the module itself lacked the name, that is not the dict
`forward` resolves to -- and asserts `loaded against; define it there`, and
this commit's `names_forward_only_for_the_dict_it_resolves_to`, whose
caller-supplied entry is then told which forward as well. #197048's
`test_no_match_report_survives_a_forward_resolve_that_raises` reaches the
neutral wording through `resolved is None`, and its
`test_no_match_message_hint_covers_a_rebound_forward` through a resolve that IS
the dict the guards hold, so both pass under that edit. What this test adds
over `..._names_the_resolved_module` is the other way to the wording, a
supplied dict that never had the name rather than a stale copy carrying the
module's `__name__`, and the recovery: no other
`AOTCompiledModel.deserialize(..., guard_globals=)` test defines a missing name
in the supplied dict and asserts the call is served
(`..._deserialize_takes_a_guard_globals_scope` supplies a copy that already
carries its names, and `covers_a_rebound_forward` defines the name in the dict
the load RESOLVED, not one the caller passed).

`test_missing_key_inside_a_present_global_is_not_a_missing_global` pins which
predicate the report reaches for. A guard on
`G['GLOBAL_POOLING_CONFIG']['pooling']` with the KEY popped reports `[0]
KeyError on G['GLOBAL_POOLING_CONFIG']['pooling']`, asserted in full with its
entry prefix, as the function path's
`test_aot_compile_fn_missing_nested_key_gets_no_missing_global_hint` asserts
the part -- an ordinary mismatch: the report keeps the advice and withholds
the hint, whose "define the global" would be wrong. Replacing the report's
`_names_a_missing_global` test with a `"KeyError on G[" in part` substring
test fails it on the hint's presence (`'a guarded global is missing'
unexpectedly found`) and nothing else in the file (`failures=1`): every other
report test's missing global is a whole part. The whole-part match itself came
in with the function path's hint and is pinned there. It sits with this
commit's other report tests rather than with the load tests, as the contrast
to the whole-global `KeyError on G['GLOBAL_POOLING_CONFIG']` entries
`hints_each_scope_a_mixed_model_failed_in` and the test before this one assert.

`test_no_match_message_advises_an_input_for_a_missing_global` pins the shape
the case for an unconditional footer rests on. `SelfModeBranchGlobalModule`,
the fixture it adds, branches on `self.mode` rather than an argument: that
guard is a `LOCAL_UNSPECIALIZED_NN_MODULE` source, which sorts after `GLOBAL`,
so the root's `G` accessor is installed -- and fails -- before the `self.mode`
guard (the `L['x']` `TENSOR_MATCH`, a `LOCAL`, precedes both), and the one
entry names only the missing global. Install order is only half of why:
`check_verbose` returns the first failing accessor's parts and nothing after
them (`check_accessors_verbose_nopybind`, torch/csrc/dynamo/guards.cpp), which
is what keeps `L['self'].mode` out of the report, so its absence cannot by
itself show a mismatch was hidden; the fixture's comment names both halves, and
the test then puts the global back and calls again, and the same call now fails
on `[0] L['self'].mode == 1` alone. The two halves run in that order because a failed `check()` re-sorts the
root's children by fail count (`GuardManager::check_nopybind`, guards.cpp): had
`self.mode` failed first, it would sit ahead of the `G` accessor and the
popped-global call would name it instead of the KeyError. An input captured for
the `mode == 2` branch would not read `AOT_BRANCH_SCALE` at all, so the advice
is right and is the only actionable line. Returning before the footer when
every entry was hinted -- `sum(map(len, hinted.values())) == len(results)` --
fails it on `Add a ModelInput`, and fails the file's three other one-entry
reports on a missing global the same way: #196825's
`test_aot_compile_module_absent_global_fails_guard`, #197048's
`test_no_match_report_survives_a_forward_resolve_that_raises` and this commit's
`test_no_match_report_resolves_forward_only_for_a_supplied_scope`
(`failures=4`, all on `'Add a ModelInput' not found`); #197149's
`test_no_match_message_hints_only_the_entry_that_named_a_missing_global`, which
pairs the missing global with a plain mismatch, passes. What this test adds is
the hidden mismatch, which none of those has.

`test_no_match_report_resolves_forward_only_for_a_supplied_scope` is the
CAPTURED half of the pair whose SUPPLIED half, #197048's
`test_no_match_report_survives_a_forward_resolve_that_raises`, stays with the
report. It captures a plain `HermeticModule` in-process, pops the global, and
asserts the CAPTURED report arrives with no `forward` named. It wraps
`_resolve_guard_scope` in a `patch(..., wraps=...)` for the call and asserts it
was never invoked, since the wording alone cannot pin the gate: the CAPTURED
hint never names `forward`, so it reads the same whether or not the resolve
ran. Dropping the SUPPLIED half of the gate, `if not tried_forward:`, fails it
on the count, `Expected '_resolve_guard_scope' to not have been called. Called
1 times`, and nothing else in the file (`failures=1`): the CAPTURED hint
ignores `forward`, and every SUPPLIED report test resolves either way. The
count carries the assertion, so the test does not rebind `forward` to a
`functools.partial` over `RaisingReprModule`: on this path a resolve that
raised would be swallowed by the report's `except Exception` and change nothing
the test could see, and the catch itself is
`survives_a_forward_resolve_that_raises`'s to pin.

`test_no_match_message_names_forward_only_for_the_dict_it_resolves_to` is the
shape that tells a per-entry `forward` from one shared across the report. Two
SUPPLIED results whose guards hold different dicts -- one from
`deserialize(GlobalConfigModule(), data)`, which resolves the scope from
`model.forward` and so holds this module's dict, the one `_resolve_guard_scope`
returns; one from `deserialize(..., guard_globals=scope)` with a dict that
never had the name -- go into one `AOTCompiledModel` by hand, as
`hints_each_scope_a_mixed_model_failed_in` builds its CAPTURED + SUPPLIED pair,
and are dispatched with `GLOBAL_POOLING_CONFIG` deleted, in both orders. Each
order enters a fresh `patch(..., wraps=_resolve_guard_scope)`, so its count is
that order's alone, and asserts `assert_called_once_with(mixed.model)` -- one
resolve, asked about the model the report is for -- two `For [i]:` lines, and
that the entry holding the resolved dict is the one told `this
GlobalConfigModule instance's forward` while the other gets the live-scope
wording. The `_with(mixed.model)` is what pins which module is resolved:
asking `_resolve_guard_scope(type(self.model)())` instead resolves a fresh
instance to the same dict here, so the wording cannot tell, and fails this test
on `expected call not found` (`failures=3`, the other two #197048's
`covers_a_rebound_forward` and `survives_a_forward_resolve_that_raises`, on
wording: a fresh instance does not carry the `forward` those rebind); under a
bare `assert_called_once()` the same edit passes this test (`failures=2`). Deciding `forward` once, at the first hinted entry, and
applying it to every entry fails it in either order on the second entry's
wording: with the resolved-dict entry first, `[1]` names the forward (`'the
live scope this artifact was loaded against; define it there' not found in
"For [1]: ... this GlobalConfigModule instance's forward resolves to ..."`),
and with it second, `[1]` gets the neutral wording (`"this GlobalConfigModule
instance's forward resolves to" not found in 'For [1]: ... loaded against,
here vars(__main__) ...'`) -- and fails nothing else in the file
(`failures=1`): `..._names_the_resolved_module`'s two entries share one dict
in each half, and `hints_each_scope`'s SUPPLIED entry is its only one. The
line count does not catch that edit, because the resolved dict carries a
`__name__` and the supplied one does not, so the two hints stay two sentences
either way; the wording does.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_hint_stays_neutral_for_a_supplied_scope
python test/dynamo/test_aot_compile.py -k test_missing_key_inside_a_present_global_is_not_a_missing_global
python test/dynamo/test_aot_compile.py -k test_no_match_message_advises_an_input_for_a_missing_global
python test/dynamo/test_aot_compile.py -k test_no_match_report_resolves_forward_only_for_a_supplied_scope
python test/dynamo/test_aot_compile.py -k test_no_match_message_names_forward_only_for_the_dict_it_resolves_to
python test/dynamo/test_aot_compile.py
```

The whole file runs 220 tests here, 215 on the parent commit: `Ran 220
tests`, `OK (skipped=6)`.

## FAQ

> **FAQ: The review asked that
> `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` read
> `AOT_HERMETIC_WEIGHT` through a reference captured at import instead of
> asserting it is in `HermeticModule.forward.__globals__`. Why an identity
> assertion instead?**
>
> The membership assertion was standing in for a claim about which dict the
> guards read, so the test states that claim directly:
> `compiled.compiled_results[0]._guard_globals is scope` -- the guards hold the
> supplied dict -- and the read that follows, `scope["AOT_HERMETIC_WEIGHT"] =
> AOT_HERMETIC_WEIGHT` serving the call, is the dict a forward-naming hint would
> have sent the reader away from. An earlier revision also asserted
> `HermeticModule.forward.__globals__ is globals()`; that holds by construction
> for a class defined in this file and observes nothing about the code under
> test, so it is gone. The two bare `AOT_HERMETIC_WEIGHT` reads are pre-existing
> and shared with every test in the file that uses the fixture; a sibling that
> failed to restore the name would break the module, not this test's ordering,
> and a captured alias would only move that dependency to import time.

> **FAQ: The review asked
> `test_no_match_message_advises_an_input_for_a_missing_global` to first show
> the report naming `L['self'].mode` with the global defined, then pop the
> global and show the KeyError replacing it. Why the other order?**
>
> Because the guard tree remembers its failures. `GuardManager::check_nopybind`
> (torch/csrc/dynamo/guards.cpp) bumps a child's fail count when it rejects and,
> unless the failure was on the first child, re-sorts the root's accessors by
> fail count so the next check fails fast. Run the mismatch half first and the
> `self.mode` accessor moves ahead of the `G` accessor; the popped-global call
> then reports `L['self'].mode == 1` rather than the KeyError (measured on a
> scratch copy: both calls name `self.mode`). Popped first, the `G` accessor
> is the one promoted, it resolves once the global is back, and the second call
> fails on `self.mode` alone -- which is the positive witness the review asked
> for, on the same compiled result.

> **FAQ: The review found that
> `test_aot_compile_module_missing_global_hint_names_the_resolved_module`, in
> the landed #196818, already fails under the edit that this commit's
> `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` was once
> described as the one test to catch. Why keep the test?**
>
> Because the coverage claim was wrong, and the test's other half is not pinned
> anywhere else. Re-measured on the whole file with the compare reduced to
> `resolved is not None`: `Ran 220 tests`, `FAILED (failures=3)`, the three
> being `..._names_the_resolved_module` (`'loaded against; define it there' not
> found`), this test, and this commit's
> `names_forward_only_for_the_dict_it_resolves_to`; every other test passes. So
> the identity compare is fenced at #196818 as well, and the message says so
> instead of crediting this test alone. What this test alone covers is a
> `guard_globals=` dict that never had the name --
> `..._names_the_resolved_module` reaches the same wording through
> `dict(globals())`, a copy taken while the module itself lacked the name --
> and the recovery, defining the name in that dict and asserting the call is
> served, which no other `AOTCompiledModel.deserialize(..., guard_globals=)`
> test does. The same pass dropped the static
> `HermeticModule.forward.__globals__ is globals()` assertion, replaced the
> raising-repr scaffolding in `..._resolves_forward_only_for_a_supplied_scope`
> with a plain `HermeticModule()` (the mock's call count carries the
> assertion; a raise on that path would be swallowed by the report's catch),
> and moved the `patch(...)` construction there above `g.pop` so nothing sits
> between the pop and the `try`.

> **FAQ: `test_missing_key_inside_a_present_global_is_not_a_missing_global`
> asserts the same `KeyError on G['GLOBAL_POOLING_CONFIG']['pooling']` string
> as the function path's
> `test_aot_compile_fn_missing_nested_key_gets_no_missing_global_hint`, some
> 2200 lines below it. Why not put them side by side?**
>
> Because the file clusters tests by the path under test, not by the string
> they assert: the module dispatch's report tests sit together (this one
> follows `names_forward_only_for_the_dict_it_resolves_to` and precedes
> `resolves_forward_only_for_a_supplied_scope`, all on `_no_match_report`), and
> the `aot_compile_fn_*` tests sit together on the function path's
> `GuardManager check failed` message, which has no report. Moving either one
> next to the other would take it out of the cluster whose contrast it is read
> against -- the whole-global `KeyError on G['GLOBAL_POOLING_CONFIG']` entries
> its neighbours assert -- to sit with a test of a different code path, and the
> review that raised it judged the move not worth another diff.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 6574151
Pull-Request: #197001
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
…path, drop bytecode_reads_guard_scope

`AOTCompiledFunction` carried a `_bytecode_reads_guard_scope` flag, a matching
`deserialize(bytecode_reads_guard_scope=...)` parameter with its own docstring
paragraph, and a block in `__post_init__` that, when the flag was set, copied the
certified globals out of the supplied scope into the dict `forward_callable`
builds for the bytecode. Only `AOTCompiledModel.deserialize` passed `True`. All
of it came from #196818 of this stack, landed on main as 82c1f1e and in no
release tag, and nothing outside `AOTCompiledModel.deserialize` ever passed the
parameter, so deleting it breaks no released or in-tree caller.

That merge is not redundant with `_serve`'s per-call re-take, even though both
write the same names from the same dict: `forward_callable` runs
`_check_external_refs` over `{**import_sources, **used_globals, **extra_globals}`
at load, and `get_runtime_env` fills `used_globals` only from the graph inputs'
global roots plus the builtins the bytecode reads. A global the generated
bytecode LOAD_GLOBALs but the graph never lifted -- the side-effect replay of a
mutated global container or object, or the reconstruct of a returned global -- is
in `external_refs` and in no serialized scope, while a `guard_filter_fn` that
keeps global guards leaves a serializable TYPE_MATCH or SEQUENCE_LENGTH rooted at
its bare GlobalSource, so it is certified. On the module load path, which passes
no `f_globals`, the merge was the only thing binding that name before the check;
without it the load raises `Missing required external references`. So
`_guard_source_globals(output_graph) <= used_globals | import_sources` does not
hold, and the merge stays. What goes is the flag: the merge now runs whenever a
live scope arms `_live_global_names`. The field, the parameter, its docstring
paragraph and the kwarg at the module load site are deleted.

What that changes, per load path, against the parent:

- `AOTCompiledModel.deserialize` (`guard_globals` only): the merge already ran
  there, so nothing changes. The module-shape test below passes on the parent
  as well; what it pins is that the merge cannot be deleted.
- `AOTCompiledFunction.deserialize(data, guard_globals=G)` with no `f_globals`:
  an artifact whose bytecode reads an unlifted certified global failed to load
  with `Missing required external references`; it now loads with `G`'s value
  bound. For a certified global the serialized scope does carry, the parent
  bound the serialized value at load and took `G`'s only from the first call's
  `_serve` re-take; `G`'s is now bound from the load, so `fn.__globals__`
  agrees with the scope before the first call too. The function-shape test
  pins the first half and fails on the parent.
- `deserialize(data, f_globals=X, guard_globals=G)` with two distinct dicts: a
  certified name both bind is taken from `G` from the load onwards, where the
  parent bound `X`'s at load and `G`'s from the first call. Only
  `fn.__globals__` between load and first call can observe the difference; the
  call results are identical. The `deserialize` docstring now states this
  precedence.
- `torch.compiler.load_compiled_function(f, f_globals=X)` passes `X` as both
  `f_globals` and `guard_globals`, so the set of names bound at load and their
  values are the same as before; the public loader is unchanged.
- No live scope (`guard_globals=None`, any `f_globals`): unchanged; the bind
  sits inside the `guard_scope is not None` branch.

The loop body in `_serve` changes alongside: `if name in scope: f_globals[name]
= scope[name]` becomes a single `scope.get(name, _UNBOUND)`, so a `del
scope[name]` racing the two-step form from another thread can no longer raise
`KeyError` out of a call whose guards already passed; the name is still skipped
rather than deleted, exactly as the docstring says. The load-time bind takes
the same `.get(name, _UNBOUND)` form for the same reason: it now runs on every
live-scope load, including one against a live module dict, and the
`in`-then-subscript two-step it replaces could raise `KeyError` out of
`deserialize`. Both narrow an escape, not the guard-check-to-re-read window,
which stays non-atomic as `_serve`'s docstring says.

Test Plan:

Two tests, each parametrized over a shape that mutates a global list and one
that returns it, both under keep_global_guards -- four cases. Each asserts the
name is in external_refs and in neither used_globals nor import_sources, that
the load arms `_live_global_names` and binds the live list into
fn.__globals__, and that the call mutates or returns that same list. The
module-shape test loads through `_load_aot_compiled_module`; the function-shape
test saves with `save_compiled_function` and loads with
`AOTCompiledFunction.deserialize(data, guard_globals=globals())`, no
`f_globals`. With the parent's `torch/_dynamo/aot_compile.py` checked into the
tree and this test file kept, the four cases give `FAILED (errors=2)`: both
function-shape cases error with `RuntimeError: Missing required external
references: ['AOT_GLOBAL_LOG']` and both module-shape cases pass. With the
`extra_globals = {**(extra_globals or {}), **live}` line deleted from this
commit's file, all four fail at load with that same RuntimeError.

```
python test/dynamo/test_aot_compile.py -k binds_a_certified_global_the_graph_never_lifted
python test/dynamo/test_aot_compile.py
lintrunner --take RUFF,PYFMT -- torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py
```

The four cases report `Ran 4 tests ... OK`; the full file `Ran 242 tests ...
OK (skipped=6)` against the parent's `Ran 238 tests ... OK (skipped=6)`; lint
`ok No lint issues.`

Authored with an AI assistant (Claude).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 3486905
Pull-Request: #196909
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
Tests only, and end to end: a module artifact guards a global, the loading
process does not define it, and the call has to fail loudly with a report that
says which compiled input failed and how -- `[0] KeyError on
G['AOT_HERMETIC_WEIGHT']` -- and that names the scope its guards were rooted
at: the globals of the module where `HermeticModule.forward` is defined, which
on this path is the only place the caller could put it. That advice is then
taken, and the test pins how far taking it goes at this commit: defining the
name in the named scope resolves the guard and the same call is served, but the
tensor served is the one serialized with the artifact rather than the one just
defined, because the bytecode's globals are built once, at load, and substitute
a live value only for a name the scope has then. Binding `saved * 2` and
asserting `x @ saved` is what pins that, and it is what makes the recovery
assertion say which dict the dispatch read rather than only that it stopped
raising: asserting `x @ (saved * 2)` instead fails (`Tensor-likes are not
close! Mismatched elements: 9 / 9`), and rooting the guards at a copy of the
live scope rather than the dict itself is caught first by the hint assertion --
the report drops the forward clause when the resolved dict is not the one the
guards hold -- with the recovery arm as the second line of defence, pinning
which dict the dispatch READ.

That `x @ saved` value is the parent's load-time snapshot, recorded here as
the limitation it is and not as the intended end state: #196897, two commits
up this stack, makes a loaded module artifact re-read the live value on every
call and flips this very assertion to `x @ (saved * 2)`, using this test as
the witness that its recorded name set is not intersected with the scope at
load. The pin stays in this commit so that flip lands as a measured behaviour
change rather than a silent one; the test comment says the same in one
sentence, without the PR number, so it reads correctly both before and after
that commit. Binding `saved` instead, which would make the arm invariant under
#196897, was considered and declined: it would leave this test unable to tell
the live dict from the serialized copy, and #196897 would have to re-add
`saved * 2` to use it as a witness.

The report is also asserted to carry the generic mismatch advice next to that
hint. That advice is not a branch the report takes for a missing global: at
this commit it closes every report unconditionally, after the hint loop, so the
assertion cannot fail while the header assertion passes. What it pins is that
the hint stays an addition to the advice rather than a replacement for it -- a
missing global counts as the mismatch the advice is for, because the report
cannot tell whether a new `ModelInput` would read the absent global (one
captured for a branch that does not read it is served with the name still
undefined), and for `HermeticModule`, which reads the global on its only path,
the hint is the actionable half. The header assertion, in turn, is what makes
`assertRaises(RuntimeError)` name which `RuntimeError` arrived. The forward
clause the test asserts is emitted when the scope `model.forward` resolves to
is the dict the guards hold (`resolved is not None and resolved is
missing_global._guard_globals`), which is the case for a load that passed no
`guard_globals=`, resolved forward, and is not rebound after the load;
`test_no_match_message_hint_covers_a_rebound_forward` rebinds BEFORE loading
and so gets the clause too, while `..._survives_a_forward_resolve_that_raises`
rebinds after and asserts it absent. What tells this test from the rebound
sibling is the recovery arm: defining the name in `globals()` serves the call
here, where the same binding in that sibling still raises.

Worth its own test because the alternative -- falling back to the serialized
scope -- makes the guard a no-op checked against capture-time state, which is
the silent failure mode; loud is recoverable on the serving machine. Most of the
load-bearing assertions are on #196823's no-match report and its forward-naming
hint -- the recovery assertion is on #196818's live-scope rooting -- so this
could equally have been folded into #196823; it stays separate because a
guarded global the loading process does not have is a failure mode of its own,
independent of where an opted-out result sits in dispatch and of what the
report says when a tree raised, and each of those gets the commit that pins it.
The fixture is the same `HermeticModule` and module-level weight
`test_aot_compile_module_reload_reads_the_live_global` uses -- the test for the
opposite direction, that a reloaded artifact reads the live global -- rather
than a second copy of it that differed only in an unchecked scale factor. Like
that sibling it hides the module dict's leaked generated globals through the
shared helper before capturing, since the scope resolved from `model.forward` is
this module's dict and the capture leaks Dynamo's generated names into it. The
load seeds nothing here, for the reason that sibling's comment gives: the only
kept global guard is rooted at `AOT_HERMETIC_WEIGHT`, not at an import alias or
the builtins-dict key. Unlike that test, the reloading wrapper here takes no
`guard_filter_fn`: the load installs the artifact's own guards and captures
nothing, so the loading process's filter has no say in what a loaded artifact
checks -- that sibling does pass a filter on its reload, where it is equally
inert.

No behaviour change vs the parent: the diff is one 69-line test, nothing under
torch/ moves.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_absent_global_fails_guard
```

Run in one process with the tests that share the fixture and the report, which
unittest orders after this one, to show they still pass with it running first
(5 tests, OK):

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_absent_global_fails_guard -k test_aot_compile_module_reload_reads_the_live_global -k test_no_match_message_hint_covers_a_rebound_forward -k test_no_match_report_survives_a_forward_resolve_that_raises -k test_no_match_message_hints_only_the_entry_that_named_a_missing_global
```

The whole file was run at this commit (215 tests, OK, 6 skipped):

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

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: eb02432
Pull-Request: #196825
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
…ard for and which share a line

Tests only, for the no-match report the report commit (#196823) raises, split
out of it so that its review fits in one pass -- the pattern of #196824 and
#196825, which pin the dispatch's last resort and a guarded global the loading
process does not have from test-only commits. Split again for review budget:
the five-test revision of this commit died at the review bot's 60-minute
ceiling, so the two tests that pin WHEN the report resolves `forward` -- only
for a SUPPLIED scope, and once -- moved up into `[aot_compile] Pin when the
no-match report resolves forward` (#<sibling>), and the three that pin WHICH
entries the hint names it for, and which entries share a hint line, stay here.
Each of the three passes at the parent, whose report it pins, and fails below
the report commit (at #196896, the commit under it), where the no-match
fall-through `results[0](self.model, *args, **kwargs)` raises the function
path's `GuardManager check failed` message. That message quotes the guard's
`KeyError on G[...]` part and, for a whole missing global, appends the function
path's hint sentence, so the `loaded against; define it there` substring the
tests also look for is present there; what it lacks is the `[i]` entry prefix,
the `For [i]:` hint line and the `Tried N` header, and with no report there is
no resolve. Measured with that tree's `aot_compile.py` under this tree's test
file: `stays_neutral` fails on `"[0] KeyError on G['AOT_HERMETIC_WEIGHT']" not
found`, `names_forward_only_for_the_dict_it_resolves_to` and
`shares_a_hint_line_across_entries_worded_alike` on `Expected
'_resolve_guard_scope' to be called once. Called 0 times`. The one that
compiles in its own body calls `_hide_leaked_dynamo_globals()` on entry, as the
capture-only `test_aot_compile_fn_missing_global_hint_names_the_tracing_scope`
does; the other two share `_two_input_global_guard_artifact` with
`test_no_match_message_hints_each_scope_a_mixed_model_failed_in` and the
landed `test_aot_compile_module_missing_global_hint_names_the_resolved_module`
and, like them, do not, its kept guards being rooted at
`GLOBAL_POOLING_CONFIG` alone.

The report at this tree decides its hint per entry. An entry whose verbose
parts name a whole missing global gets `_missing_global_hint(forward=...)`,
with `forward` set when `resolved is not None and resolved is
result._guard_globals`; `resolved` is what one `_resolve_guard_scope(self.model)`
returned, run at most once, at the first hinted entry whose scope is SUPPLIED,
and reused for every entry after it (when it runs, and that it runs once, is
#<sibling>'s). The hints are keyed by text into `hinted`, one `For [i, j]:`
line per distinct sentence, and the footer follows unconditionally. What each
test catches, and which other tests in the file would catch the same edit, was
measured by editing the report and running the whole file (222 tests):

`test_no_match_message_hint_stays_neutral_for_a_supplied_scope` loads through
`AOTCompiledModel.deserialize(..., guard_globals=...)` with a dict that never
had the guarded name, so the guards hold a dict no `forward` resolves to,
asserts the scope-neutral wording under its `For [0]:` prefix, and then the
advice it gives: `compiled_results[0]._guard_globals is scope`, and defining
the name in that dict serves the call -- with `AOT_HERMETIC_WEIGHT` defined in
this module's dict, where the class's `forward` lives, the whole time.
Reducing the compare to `resolved is not None` fails it with a report that
names `this HermeticModule instance's forward`, and fails exactly two others
(`failures=3`): the landed #196818's `..._names_the_resolved_module`, whose
second half loads with `guard_globals=dict(globals())` -- a copy of the module
dict, taken while the module itself lacked the name, that is not the dict
`forward` resolves to -- and asserts `loaded against; define it there`, and
this commit's `names_forward_only_for_the_dict_it_resolves_to`, whose
caller-supplied entry is then told which forward as well. #197048's
`test_no_match_report_survives_a_forward_resolve_that_raises` reaches the
neutral wording through `resolved is None`, its
`test_no_match_message_hint_covers_a_rebound_forward` through a resolve that IS
the dict the guards hold, and this commit's `shares_a_hint_line` through a
resolve that returns no dict, so all three pass under that edit. What this
test adds over `..._names_the_resolved_module` is the other way to the
wording, a supplied dict that never had the name rather than a stale copy
carrying the module's `__name__`, and the recovery: no other
`AOTCompiledModel.deserialize(..., guard_globals=)` test defines a missing name
in the supplied dict and asserts the call is served
(`..._deserialize_takes_a_guard_globals_scope` supplies a copy that already
carries its names, and `covers_a_rebound_forward` defines the name in the dict
the load RESOLVED, not one the caller passed).

`test_no_match_message_names_forward_only_for_the_dict_it_resolves_to` is the
shape that tells a per-entry `forward` from one shared across the report. Two
SUPPLIED results whose guards hold different dicts -- one from
`deserialize(GlobalConfigModule(), data)`, which resolves the scope from
`model.forward` and so holds this module's dict, the one `_resolve_guard_scope`
returns; one from `deserialize(..., guard_globals=scope)` with a dict that
never had the name -- go into one `AOTCompiledModel` by hand, as
`hints_each_scope_a_mixed_model_failed_in` builds its CAPTURED + SUPPLIED pair,
and are dispatched with `GLOBAL_POOLING_CONFIG` deleted, in both orders. Each
order enters a fresh `patch(..., wraps=_resolve_guard_scope)`, so its count is
that order's alone, and asserts `assert_called_once_with(mixed.model)` -- one
resolve, asked about the model the report is for -- two `For [i]:` lines, and
that the entry holding the resolved dict is the one told `this
GlobalConfigModule instance's forward` while the other gets the live-scope
wording. Deciding `forward` once, at the first hinted entry, and applying it
to every entry fails it on the second entry's wording (`'the live scope this
artifact was loaded against; define it there' not found in "For [1]: ... this
GlobalConfigModule instance's forward resolves to ..."`) and nothing else in
the file (`failures=1`): `..._names_the_resolved_module`'s two entries share
one dict in each half, `hints_each_scope`'s SUPPLIED entry is its only one,
and `shares_a_hint_line`'s three entries all hold dicts no forward resolves
to. The line count does not catch that edit, because the resolved dict carries
a `__name__` and the supplied one does not, so the two hints stay two
sentences either way; the wording does. The `_with(mixed.model)` is what pins
which module is resolved: asking `_resolve_guard_scope(type(self.model)())`
instead resolves a fresh instance to the same dict here, so the wording cannot
tell, and fails this test on `expected call not found` (`failures=4`: the
other three are #197048's `covers_a_rebound_forward` and
`survives_a_forward_resolve_that_raises` on wording, since a fresh instance
does not carry the `forward` those rebind, and this commit's
`shares_a_hint_line`, which also checks which model was asked).

`test_no_match_message_shares_a_hint_line_across_entries_worded_alike` is the
report's first three-entry test (`Tried 3` appears nowhere else in the file)
and pins four things at once. Three SUPPLIED results from three
`deserialize(GlobalConfigModule(), data, guard_globals=...)` loads, each
holding a caller dict of its own (`len({id(r._guard_globals) for r in
results}) == 3`): `[0]` and `[2]` lack `GLOBAL_POOLING_CONFIG`, `[1]` has it
bound to `{}`, so its guard fails on the KEY, `KeyError on
G['GLOBAL_POOLING_CONFIG']['pooling']`; the three entry lines are asserted
exactly. First, the hint lines are keyed by sentence, not by dict: `[0]` and
`[2]` carry no `__name__`, so their neutral sentences are identical and they
share one non-contiguous `For [0, 2]:` line. Keying `hinted` by
`(id(result._guard_globals), hint)` instead fails it on the line count
(`Expected 1 but got 2`) and nothing else (`failures=1`):
`..._names_the_resolved_module`'s `For [0, 1]` entries share one dict object.
The merge is the intended reading: a per-dict line would print the same
sentence twice, and the sentence names no dict, so the reader could not tell
the two lines apart; two entries that give one instruction get one line.
Second, `[1]` is the nested-key mismatch the whole-part match keeps off the
hint: replacing the report's `_names_a_missing_global` with a `"KeyError on
G[" in part` substring test fails it on `For [0, 1, 2]:` and nothing else
(`failures=1`), the fence the dropped
`test_missing_key_inside_a_present_global_is_not_a_missing_global` carried
(see the FAQ); the predicate itself is pinned on the function path by
`test_aot_compile_fn_missing_nested_key_gets_no_missing_global_hint`. Third,
the model is `_unresolvable_forward_module()`, whose forward is a partial
`get_traced_fn` refuses, so the report's one resolve --
`assert_called_once_with(mixed.model)` -- returns `(None, reason)` without
raising and no entry is told which forward; the fixture's three other uses
pass no `guard_globals=`, so their results are RECONSTRUCTED and never reach
the resolve. Fourth, the footer follows a report whose hinted list is
non-contiguous.

Two tests of the previous revision are gone.
`test_no_match_message_advises_an_input_for_a_missing_global` and its
`SelfModeBranchGlobalModule` fixture pinned the footer under a report whose
every entry was hinted; the footer is unconditional, and returning before it
when `sum(map(len, hinted.values())) == len(results)` fails two tests at this
tree without it (`failures=2`, both on `'Add a ModelInput' not found`):
#196825's `test_aot_compile_module_absent_global_fails_guard` and #197048's
`survives_a_forward_resolve_that_raises` (and, one commit up, #<sibling>'s
`resolves_forward_only_for_a_supplied_scope`). Its other assertions -- that
the `L['self'].mode` mismatch is absent from the first report and named by the
second -- pinned the guard tree's install order and fail-count re-sort in
guards.cpp, not the report.
`test_missing_key_inside_a_present_global_is_not_a_missing_global` is folded
into `shares_a_hint_line`'s entry `[1]`, which fences the same substring edit.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_hint_stays_neutral_for_a_supplied_scope
python test/dynamo/test_aot_compile.py -k test_no_match_message_names_forward_only_for_the_dict_it_resolves_to
python test/dynamo/test_aot_compile.py -k test_no_match_message_shares_a_hint_line_across_entries_worded_alike
python test/dynamo/test_aot_compile.py
```

The whole file runs 222 tests here, 219 on the parent commit: `Ran 222
tests`, `OK (skipped=6)`.

## FAQ

> **FAQ: The review found that
> `test_aot_compile_module_missing_global_hint_names_the_resolved_module`, in
> the landed #196818, already fails under the edit that this commit's
> `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` was once
> described as the one test to catch. Why keep the test?**
>
> Because the coverage claim was wrong, and the test's other half is not pinned
> anywhere else. Re-measured on the whole file with the compare reduced to
> `resolved is not None`: `Ran 222 tests`, `FAILED (failures=3)`, the three
> being `..._names_the_resolved_module` (`'loaded against; define it there' not
> found`), this test, and this commit's
> `names_forward_only_for_the_dict_it_resolves_to`; every other test passes. So
> the identity compare is fenced at #196818 as well, and the message says so
> instead of crediting this test alone. What this test alone covers is a
> `guard_globals=` dict that never had the name --
> `..._names_the_resolved_module` reaches the same wording through
> `dict(globals())`, a copy taken while the module itself lacked the name --
> and the recovery, defining the name in that dict and asserting the call is
> served, which no other `AOTCompiledModel.deserialize(..., guard_globals=)`
> test does.

> **FAQ: The review found two of an earlier revision's five tests largely
> redundant with the base, and two report branches -- where `tried_forward` is
> set, and hint dedup keyed by text -- unpinned. What changed?**
>
> Both redundancies were measured and both tests are gone; both branches are
> now pinned, one here and one in #<sibling>. Gating the footer on every entry
> being hinted, the edit
> `test_no_match_message_advises_an_input_for_a_missing_global` fenced, fails
> two tests at this tree without it -- #196825's `absent_global_fails_guard`
> and #197048's `survives_a_forward_resolve_that_raises` -- so that test and
> its fixture add no fence on the report, and its `L['self'].mode` assertions
> pin guards.cpp's accessor order, not this function. Replacing the report's
> whole-part predicate with a substring test, the edit
> `test_missing_key_inside_a_present_global_is_not_a_missing_global` fenced
> alone, is now fenced alone by
> `shares_a_hint_line_across_entries_worded_alike`, whose entry `[1]` is the
> same nested-key mismatch next to two whole-global ones, so the fold loses no
> coverage and the module path still has its own pin of the predicate. Keying
> `hinted` by dict identity fails only `shares_a_hint_line` (`Expected 1 but
> got 2` hint lines); the `tried_forward` mark is pinned by #<sibling>'s
> `resolves_forward_once_past_a_resolve_that_raises`.

> **FAQ: The report's comment on `hinted` says entries that share a scope
> share a sentence, but the dict is keyed by hint text, so two entries holding
> different dicts with identical wording collapse into one `For [0, 2]:` line.
> Is that intended, and why pin it rather than change it?**
>
> It is intended, and this commit changes no code. The hint sentence is the
> whole of what the reader gets: it names a scope only when the dict carries a
> `__name__` (`here vars(mod)`), and two caller-supplied dicts without one
> yield the identical sentence, so a per-dict line would print that sentence
> twice with nothing to tell the two lines apart. Two entries whose advice
> reads the same get one line; two entries whose advice differs -- a resolved
> module dict next to a supplied one, a CAPTURED entry next to a SUPPLIED one
> -- keep their own, which `names_forward_only_for_the_dict_it_resolves_to`
> and `hints_each_scope_a_mixed_model_failed_in` pin. The comment's "share a
> scope" is the common case of sharing a sentence, and belongs to #197149.

> **FAQ: Every new test passes at the parent commit. Where is the red-on-parent
> evidence?**
>
> There is none by construction: this is a tests-only commit pinning the
> report the parent already ships, so every test passes on the parent's tree.
> The two measurements that stand in for it are above: each test fails under
> the tree below the report commit (#196896), where no report exists, and each
> fails under a targeted edit of `_no_match_report` that no other test in the
> file catches -- the mutation table is what shows the pins are not vacuous.

> **FAQ: The review listed `"; ".join(parts)` with more than one verbose code
> part per entry as uncovered. Why is there no test for it here?**
>
> Because that join is #197134's (`Keep a no-match report entry to one line
> that says what its guards answered`), whose
> `test_no_match_report_keeps_an_entry_on_one_line_past_odd_separators` owns
> the entry format; how many parts an entry quotes has no bearing on the hint,
> which is what this commit pins. A multi-part entry test belongs next to that
> one, in that PR.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: a9fe180
Pull-Request: #197001
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
…path, drop bytecode_reads_guard_scope

`AOTCompiledFunction` carried a `_bytecode_reads_guard_scope` flag, a matching
`deserialize(bytecode_reads_guard_scope=...)` parameter with its own docstring
paragraph, and a block in `__post_init__` that, when the flag was set, copied the
certified globals out of the supplied scope into the dict `forward_callable`
builds for the bytecode. Only `AOTCompiledModel.deserialize` passed `True`. All
of it came from #196818 of this stack, landed on main as 82c1f1e and in no
release tag, and nothing outside `AOTCompiledModel.deserialize` ever passed the
parameter, so deleting it breaks no released or in-tree caller.

That merge is not redundant with `_serve`'s per-call re-take, even though both
write the same names from the same dict: `forward_callable` runs
`_check_external_refs` over `{**import_sources, **used_globals, **extra_globals}`
at load, and `get_runtime_env` fills `used_globals` only from the graph inputs'
global roots plus the builtins the bytecode reads. A global the generated
bytecode LOAD_GLOBALs but the graph never lifted -- the side-effect replay of a
mutated global container or object, or the reconstruct of a returned global -- is
in `external_refs` and in no serialized scope, while a `guard_filter_fn` that
keeps global guards leaves a serializable TYPE_MATCH or SEQUENCE_LENGTH rooted at
its bare GlobalSource, so it is certified. On the module load path, which passes
no `f_globals`, the merge was the only thing binding that name before the check;
without it the load raises `Missing required external references`. So
`_guard_source_globals(output_graph) <= used_globals | import_sources` does not
hold, and the merge stays. What goes is the flag: the merge now runs whenever a
live scope arms `_live_global_names`. The field, the parameter, its docstring
paragraph and the kwarg at the module load site are deleted.

What that changes, per load path, against the parent:

- `AOTCompiledModel.deserialize` (`guard_globals` only): the merge already ran
  there, so nothing changes. The module-shape test below passes on the parent
  as well; what it pins is that the merge cannot be deleted.
- `AOTCompiledFunction.deserialize(data, guard_globals=G)` with no `f_globals`:
  an artifact whose bytecode reads an unlifted certified global failed to load
  with `Missing required external references`; it now loads with `G`'s value
  bound. For a certified global the serialized scope does carry, the parent
  bound the serialized value at load and took `G`'s only from the first call's
  `_serve` re-take; `G`'s is now bound from the load, so `fn.__globals__`
  agrees with the scope before the first call too. The function-shape test
  pins the first half and fails on the parent.
- `deserialize(data, f_globals=X, guard_globals=G)` with two distinct dicts: a
  certified name both bind is taken from `G` from the load onwards, where the
  parent bound `X`'s at load and `G`'s from the first call. Only
  `fn.__globals__` between load and first call can observe the difference; the
  call results are identical. The `deserialize` docstring now states this
  precedence.
- `torch.compiler.load_compiled_function(f, f_globals=X)` passes `X` as both
  `f_globals` and `guard_globals`, so the set of names bound at load and their
  values are the same as before; the public loader is unchanged.
- No live scope (`guard_globals=None`, any `f_globals`): unchanged; the bind
  sits inside the `guard_scope is not None` branch.

The loop body in `_serve` changes alongside: `if name in scope: f_globals[name]
= scope[name]` becomes a single `scope.get(name, _UNBOUND)`, so a `del
scope[name]` racing the two-step form from another thread can no longer raise
`KeyError` out of a call whose guards already passed; the name is still skipped
rather than deleted, exactly as the docstring says. The load-time bind takes
the same `.get(name, _UNBOUND)` form for the same reason: it now runs on every
live-scope load, including one against a live module dict, and the
`in`-then-subscript two-step it replaces could raise `KeyError` out of
`deserialize`. Both narrow an escape, not the guard-check-to-re-read window,
which stays non-atomic as `_serve`'s docstring says.

Test Plan:

Two tests, each parametrized over a shape that mutates a global list and one
that returns it, both under keep_global_guards -- four cases. Each asserts the
name is in external_refs and in neither used_globals nor import_sources, that
the load arms `_live_global_names` and binds the live list into
fn.__globals__, and that the call mutates or returns that same list. The
module-shape test loads through `_load_aot_compiled_module`; the function-shape
test saves with `save_compiled_function` and loads with
`AOTCompiledFunction.deserialize(data, guard_globals=globals())`, no
`f_globals`. With the parent's `torch/_dynamo/aot_compile.py` checked into the
tree and this test file kept, the four cases give `FAILED (errors=2)`: both
function-shape cases error with `RuntimeError: Missing required external
references: ['AOT_GLOBAL_LOG']` and both module-shape cases pass. With the
`extra_globals = {**(extra_globals or {}), **live}` line deleted from this
commit's file, all four fail at load with that same RuntimeError.

```
python test/dynamo/test_aot_compile.py -k binds_a_certified_global_the_graph_never_lifted
python test/dynamo/test_aot_compile.py
lintrunner --take RUFF,PYFMT -- torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py
```

The four cases report `Ran 4 tests ... OK`; the full file `Ran 242 tests ...
OK (skipped=6)` against the parent's `Ran 238 tests ... OK (skipped=6)`; lint
`ok No lint issues.`

Authored with an AI assistant (Claude).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 417605e
Pull-Request: #196909
pytorchmergebot pushed a commit that referenced this pull request Sep 17, 2026
#196825)

**Summary.** Tests only, end to end: a module artifact guards a module-level
global, the loading process does not define it, and the call has to fail loudly
with a report that names the failing input (`[0] KeyError on
G['AOT_HERMETIC_WEIGHT']`) and the scope its guards were rooted at, the globals
of the module where `HermeticModule.forward` is defined. The alternative,
falling back to the serialized scope, would make the guard a no-op checked
against capture-time state, which is the silent failure mode; loud is
recoverable on the serving machine. The test then takes the report's advice and
pins how far that goes at this commit: defining the name resolves the guard and
the call is served, but with the tensor serialized in the artifact rather than
the one just defined, because the bytecode's globals are built once at load and
a live value is substituted only for a name the scope had then. That
`x @ saved` assertion is recorded as the limitation it is, not the intended end
state: #196897, two commits up, makes a loaded module artifact re-read the live
value on every call and flips it to `x @ (saved * 2)`, using this test as its
witness. It is a separate commit because a guarded global the loading process
lacks is a failure mode of its own, independent of where an opted-out result
sits in dispatch and of what the report says when a tree raised.

## The scenario

```python
# capture process: HermeticModule.forward reads the module-level AOT_HERMETIC_WEIGHT
model = torch.compile(HermeticModule(), fullgraph=True, backend="eager",
                      options={"guard_filter_fn": keep_global_guards})
model._aot_compile([ModelInput(args=(x,), kwargs={}, contexts=[])])
data = model._save_aot_compiled_module()

# loading process: the global is absent
torch._dynamo.reset()
saved = globals().pop("AOT_HERMETIC_WEIGHT")
reloaded = torch.compile(HermeticModule(), fullgraph=True, backend="eager")   # no guard_filter_fn: inert on a load
reloaded._load_aot_compiled_module(data)                                       # a module load takes no f_globals=
reloaded(x)
# RuntimeError: No AOT compiled graph matched this call. Tried 1 compiled input(s):
#   [0] KeyError on G['AOT_HERMETIC_WEIGHT']
# For [0]: a guarded global is missing from the globals of the function this HermeticModule instance's
#          forward resolves to, since that is the one the load resolved, here vars(test_aot_compile); ...
# Add a ModelInput covering this call, or check whether guard_filter_fn kept a guard ...
```

The reloading wrapper takes no `guard_filter_fn`: the load installs the
artifact's own guards and captures nothing, so the loading process's filter has
no say in what a loaded artifact checks. The sibling
`test_aot_compile_module_reload_reads_the_live_global` does pass a filter on
its reload, where it is equally inert.

## Taking the advice, and what the recovery arm pins

```python
globals()["AOT_HERMETIC_WEIGHT"] = saved * 2      # define it in the named scope, with a DIFFERENT value
reloaded(x) == x @ saved                          # served -- but with the tensor serialized in the artifact
```

The guards read the live scope by reference, so the new binding passes the kept
`TENSOR_MATCH`, which checks metadata and not values. The bytecode's globals
were built once, at load, and substitute a live value only for a name the scope
has then, so the value serialized with the artifact was never overwritten.
Binding `saved * 2` and asserting `x @ saved` is what pins that, and it is what
makes the recovery assertion say which dict the dispatch READ rather than only
that it stopped raising: asserting `x @ (saved * 2)` instead fails
(`Tensor-likes are not close! Mismatched elements: 9 / 9`), and rooting the
guards at a copy of the live scope rather than the dict itself is caught first
by the hint assertion (the report drops the forward clause when the resolved
dict is not the one the guards hold), with the recovery arm as the second line
of defence.

That `x @ saved` value is the parent's load-time snapshot, recorded here as the
limitation it is and not as the intended end state: #196897, two commits up
this stack, makes a loaded module artifact re-read the live value on every call
and flips this very assertion to `x @ (saved * 2)`, using this test as the
witness that its recorded name set is not intersected with the scope at load.
The pin stays in this commit so that flip lands as a measured behaviour change
rather than a silent one; the test comment says the same in one sentence,
without the PR number, so it reads correctly both before and after that commit.
Binding `saved` instead, which would make the arm invariant under #196897, was
considered and declined: it would leave this test unable to tell the live dict
from the serialized copy, and #196897 would have to re-add `saved * 2` to use
it as a witness.

## Both lines of the report, and which sibling pins what

The report is also asserted to carry the generic mismatch advice next to the
hint: a missing global counts as the mismatch it is, because the report cannot
tell whether a new `ModelInput` would read the absent global (one captured for
a branch that does not read it is served with the name still undefined), so
both lines are emitted, and for `HermeticModule`, which reads the global on its
only path, the hint is the actionable half.

The forward clause the test asserts is emitted when the scope `model.forward`
resolves to is the dict the guards hold (`resolved is not None and resolved is
missing_global._guard_globals`), which is the case for a load that passed no
`guard_globals=`, resolved forward, and is not rebound after the load:

```
this test (un-rebound load)                       -> clause present, "here vars(test_aot_compile)" suffix
..._hint_covers_a_rebound_forward (rebinds BEFORE loading) -> clause present, no suffix (foreign dict)
..._survives_a_forward_resolve_that_raises (rebinds AFTER)  -> clause absent
```

What tells this test from the rebound sibling is the recovery arm: defining the
name in `globals()` serves the call here, where the same binding in that
sibling still raises.

## Why its own test, and the fixture

Most of the load-bearing assertions are on #196823's no-match report and its
forward-naming hint, and the recovery assertion is on #196818's live-scope
rooting, so this could equally have been folded into #196823; it stays separate
because a guarded global the loading process does not have is a failure mode of
its own, and each of those gets the commit that pins it. The fixture is the
same `HermeticModule` and module-level weight
`test_aot_compile_module_reload_reads_the_live_global` uses, the test for the
opposite direction, rather than a second copy that differed only in an
unchecked scale factor. Like that sibling it hides the module dict's leaked
generated globals through the shared helper before capturing, since the scope
resolved from `model.forward` is this module's dict and the capture leaks
Dynamo's generated names into it. The load seeds nothing here, for the reason
that sibling's comment gives: the only kept global guard is rooted at
`AOT_HERMETIC_WEIGHT`, not at an import alias or the builtins-dict key.

No behaviour change vs the parent: the diff is one 66-line test, nothing under
torch/ moves.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_absent_global_fails_guard
```

Run in one process with the tests that share the fixture and the report, which
unittest orders after this one, to show they still pass with it running first
(5 tests, OK):

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_absent_global_fails_guard -k test_aot_compile_module_reload_reads_the_live_global -k test_missing_key_inside_a_present_global_is_not_a_missing_global -k test_no_match_message_keeps_the_advice_for_every_entry -k test_no_match_message_hint_covers_a_rebound_forward
```

The whole file was run at this commit:

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

Authored with the assistance of Claude Code.

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

## FAQ

> FAQ: why not rename `AOT_HERMETIC_WEIGHT`/`HermeticModule` to something that
> says what the fixture is for? The fixture is not this commit's: `git log -S`
> puts `class HermeticModule` and the module-level `AOT_HERMETIC_WEIGHT` in
> #196820, which introduces them along with its test that a reloaded module
> artifact reads the live global. #196825 reuses them rather than adding a
> near-duplicate module and weight. A rename therefore has to rewrite the fixture
> definition in #196820 together with every test body that uses it, which by this
> commit is spread across several of the stack's commits, in a stack whose whole
> point is one reviewable behaviour per commit -- for a naming preference, with no
> change in what is covered. The name is a poor one and #196820 says so: what
> these tests pin is that a load reads the LIVE global rather than a sealed
> capture-time copy, which is the opposite of hermetic. The rename is a mechanical
> follow-up once the stack lands, touching the definition and every commit's uses
> together.

> **FAQ: the test pops `AOT_HERMETIC_WEIGHT` after `_hide_leaked_dynamo_globals()`,
> and that order is what keeps cleanup from deleting the module-level fixture --
> why is the dependency not spelled out here?** It is real: the helper snapshots
> `preexisting = frozenset(g)` over `g = globals()` and its cleanup deletes every
> name not in that snapshot, so a pop moved above the helper drops the name from
> the snapshot and the cleanup deletes the module-level global for the rest of the
> process. Measured by mutation -- with the helper call moved below the pop (after
> the capture) this test still passes and the next test that reads the fixture dies
> with `NameError: name 'AOT_HERMETIC_WEIGHT' is not defined` at its `x @
> AOT_HERMETIC_WEIGHT`. The note is not added at this call site because the
> dependency is a property of the shared helper, not of this test: six tests pop a
> global around it, five of them in earlier commits of this stack (#196816,
> #196823, #196824), and a note on one call site documents the helper's contract in
> the one place that does not own it while leaving the other five bare. It belongs
> in `_hide_leaked_dynamo_globals`'s own comment, which already explains the
> snapshot-and-restore and reaches all six call sites at once; that is a one-commit
> change to the commit that introduces the helper, not to this test-only commit.

> **FAQ: why does this test not also assert `Tried 1 compiled input(s)` alongside
> `No AOT compiled graph matched`?** Because the tried-count line is the report's
> shape, which is pinned where the report is introduced: that commit asserts `Tried
> 2 compiled input(s)` together with the `[0]`/`[1]` entries and their line
> positions, and pins the exact line count for a one-input report in its
> odd-separators test. This test pins a different thing -- that a guarded global
> the loading process lacks fails the guard and is reported as `[0] KeyError on
> G['AOT_HERMETIC_WEIGHT']` -- and its `[0] ...` assertion already fails if the
> entry for the single compiled input stops being emitted. Re-asserting the count
> here would add a second place to update when the report's wording changes, for
> coverage the report's own test already has.

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

Pull Request resolved: #196825
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048
pytorchmergebot pushed a commit that referenced this pull request Sep 18, 2026
…path, drop bytecode_reads_guard_scope (#196909)

**Summary.** `AOTCompiledFunction` carried a `_bytecode_reads_guard_scope` flag, a matching `deserialize(bytecode_reads_guard_scope=...)` parameter with its own docstring paragraph, and a block in `__post_init__` that, when the flag was set, copied the certified globals out of the supplied scope into the dict `forward_callable` builds for the bytecode, and only `AOTCompiledModel.deserialize` passed `True`. That merge is not redundant with `_serve`'s per-call re-take: `forward_callable` runs `_check_external_refs` at load, and a certified global the generated bytecode `LOAD_GLOBAL`s but the graph never lifted (the side-effect replay of a mutated global container, or the reconstruct of a returned global) is in `external_refs` and in no serialized scope, so without the merge a `guard_globals`-only load raises `Missing required external references`. What goes is the flag: the merge now runs whenever a live scope arms `_live_global_names`, and the field, the parameter, its docstring paragraph and the kwarg at the module load site are deleted. Against the parent this changes one path -- `AOTCompiledFunction.deserialize(data, guard_globals=G)` with no `f_globals` now loads such an artifact with `G`'s value bound where it failed before -- and one detail, a certified name both `f_globals` and `guard_globals` bind is taken from `guard_globals` from the load onwards rather than from the first call, observable only in `fn.__globals__` between load and first call; the module path, the public loader and the no-scope path are unchanged. All of the deleted surface came from #196818 of this stack, landed on main as 82c1f1e and in no release tag, and nothing outside `AOTCompiledModel.deserialize` ever passed the parameter, so deleting it breaks no released or in-tree caller.

## What is deleted

```python
# parent
class AOTCompiledFunction:
    _bytecode_reads_guard_scope: bool = False        # deleted

    def __post_init__(self):
        ...
        certified = _guard_source_globals(output_graph)
        self._live_global_names = tuple(sorted(certified))
        if self._bytecode_reads_guard_scope:         # gate deleted; the merge below stays
            live = {}
            for name in certified:
                value = guard_scope.get(name, _UNBOUND)
                if value is not _UNBOUND:
                    live[name] = value
            extra_globals = {**(extra_globals or {}), **live}

    @classmethod
    def deserialize(cls, data, f_globals=None, ..., *, guard_globals=None,
                    bytecode_reads_guard_scope=False,    # parameter deleted
                    forward_not_resolved_reason=None): ...

# now
        certified = _guard_source_globals(output_graph)
        self._live_global_names = tuple(sorted(certified))
        live = {n: v for n in certified if (v := guard_scope.get(n, _UNBOUND)) is not _UNBOUND}
        extra_globals = {**(extra_globals or {}), **live}
```

`AOTCompiledModel.deserialize` drops the `bytecode_reads_guard_scope=True` kwarg at its `AOTCompiledFunction.deserialize` call, and the `deserialize` docstring paragraph that described the flag is folded into the `guard_globals` paragraph.

## Why the merge stays

The merge is not redundant with `_serve`'s per-call re-take, even though both write the same names from the same dict: `forward_callable` runs `_check_external_refs` over `{**import_sources, **used_globals, **extra_globals}` at load, and `get_runtime_env` fills `used_globals` only from the graph inputs' global roots plus the builtins the bytecode reads.

```python
AOT_GLOBAL_LOG: list[int] = []

def mutates_global_list(x):            # side-effect replay: bytecode LOAD_GLOBALs AOT_GLOBAL_LOG
    AOT_GLOBAL_LOG.append(x.shape[0])
    return x + 1

def returns_global_list(x):            # reconstruct of a returned global: same
    return x + 1, AOT_GLOBAL_LOG

# under keep_global_guards, after aot_compile:
"AOT_GLOBAL_LOG" in runtime_env.external_refs      # True
"AOT_GLOBAL_LOG" in runtime_env.used_globals       # False: the graph never lifted it
"AOT_GLOBAL_LOG" in runtime_env.import_sources     # False
```

A global the generated bytecode `LOAD_GLOBAL`s but the graph never lifted -- the side-effect replay of a mutated global container or object, or the reconstruct of a returned global -- is in `external_refs` and in no serialized scope, while a `guard_filter_fn` that keeps global guards leaves a serializable `TYPE_MATCH` or `SEQUENCE_LENGTH` rooted at its bare `GlobalSource`, so it is certified. On the module load path, which passes no `f_globals`, the merge was the only thing binding that name before the check; without it the load raises `Missing required external references`. So `_guard_source_globals(output_graph) <= used_globals | import_sources` does not hold, and the merge stays.

## What changes, per load path

Against the parent:

- **`AOTCompiledModel.deserialize` (`guard_globals` only).** The merge already ran there, so nothing changes. The module-shape test below passes on the parent as well; what it pins is that the merge cannot be deleted.
- **`AOTCompiledFunction.deserialize(data, guard_globals=G)` with no `f_globals`.** An artifact whose bytecode reads an unlifted certified global failed to load with `Missing required external references`; it now loads with `G`'s value bound. For a certified global the serialized scope does carry, the parent bound the serialized value at load and took `G`'s only from the first call's `_serve` re-take; `G`'s is now bound from the load, so `fn.__globals__` agrees with the scope before the first call too. The function-shape test pins the first half and fails on the parent.

```python
loaded = AOTCompiledFunction.deserialize(data, guard_globals=globals())
# parent: RuntimeError: Missing required external references: ['AOT_GLOBAL_LOG']
# now:    loads; loaded.fn.__globals__["AOT_GLOBAL_LOG"] is AOT_GLOBAL_LOG
```

- **`deserialize(data, f_globals=X, guard_globals=G)` with two distinct dicts.** A certified name both bind is taken from `G` from the load onwards, where the parent bound `X`'s at load and `G`'s from the first call. Only `fn.__globals__` between load and first call can observe the difference; the call results are identical. The `deserialize` docstring now states this precedence.
- **`torch.compiler.load_compiled_function(f, f_globals=X)`.** It passes `X` as both `f_globals` and `guard_globals`, so the set of names bound at load and their values are the same as before; the public loader is unchanged.
- **No live scope (`guard_globals=None`, any `f_globals`).** Unchanged; the bind sits inside the `guard_scope is not None` branch.

## The `.get` form

The loop body in `_serve` already takes the single `scope.get(name, _UNBOUND)` form: the commit below adopted it so a caller's `__missing__` hook is never asked to fabricate a value, and so a `del scope[name]` racing the read from another thread cannot raise `KeyError` out of a call whose guards already passed; the name is skipped rather than deleted, exactly as the docstring says. The load-time bind keeps that form for the same reason: it now runs on every live-scope load, including one against a live module dict, and an `in`-then-subscript two-step could raise `KeyError` out of `deserialize`. Neither touches the guard-check-to-re-read window, which stays non-atomic as `_serve`'s docstring says.

## Tests

`test_aot_compile_module_load_binds_a_certified_global_the_graph_never_lifted` and `test_aot_compile_function_load_binds_a_certified_global_the_graph_never_lifted`, each parametrized over `mutates` and `returns` (a shape that mutates a global list and one that returns it), both under `keep_global_guards` -- four cases. Each asserts the name is in `external_refs` and in neither `used_globals` nor `import_sources`, that the load arms `_live_global_names` and binds the live list into `fn.__globals__`, and that the call mutates or returns that same list. The module-shape test loads through `_load_aot_compiled_module`; the function-shape test saves with `save_compiled_function` and loads with `AOTCompiledFunction.deserialize(data, guard_globals=globals())`, no `f_globals`.

Test Plan:

Two tests, each parametrized over a shape that mutates a global list and one
that returns it, both under keep_global_guards -- four cases. Each asserts the
name is in external_refs and in neither used_globals nor import_sources, that
the load arms `_live_global_names` and binds the live list into
fn.__globals__, and that the call mutates or returns that same list. The
module-shape test loads through `_load_aot_compiled_module`; the function-shape
test saves with `save_compiled_function` and loads with
`AOTCompiledFunction.deserialize(data, guard_globals=globals())`, no
`f_globals`. With the parent's `torch/_dynamo/aot_compile.py` checked into the
tree and this test file kept, the four cases give `FAILED (errors=2)`: both
function-shape cases error with `RuntimeError: Missing required external
references: ['AOT_GLOBAL_LOG']` and both module-shape cases pass. With the
`extra_globals = {**(extra_globals or {}), **live}` line deleted from this
commit's file, all four fail at load with that same RuntimeError.

```
python test/dynamo/test_aot_compile.py -k binds_a_certified_global_the_graph_never_lifted
python test/dynamo/test_aot_compile.py
lintrunner --take RUFF,PYFMT -- torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py
```

The four cases report `Ran 4 tests ... OK`; the full file `Ran 242 tests ...
OK (skipped=6)` against the parent's `Ran 238 tests ... OK (skipped=6)`; lint
`ok No lint issues.`

Authored with an AI assistant (Claude).

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

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

Pull Request resolved: #196909
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218
pytorchmergebot pushed a commit that referenced this pull request Sep 19, 2026
…ard for and which share a line (#197001)

**Problem.** The no-match report decides, entry by entry, whether its missing-global hint names "this `Module` instance's forward" or stays neutral ("the live scope this artifact was loaded against"), by comparing the dict `forward` resolves to against the dict each entry's guards hold. Nothing pinned that a caller-supplied `guard_globals=` dict stays neutral, or that in a report with two entries holding different dicts only the entry holding the resolved one is told which forward.

**Fix.** Two tests pin exactly that: one where no entry holds the resolved dict (and defining the name in the supplied dict then serves the call), and one where exactly one of two does, checked in both orders with a single resolve asserted. No source change.

**Summary.** Tests only, for the no-match report the report commit (#196823) raises, split out of it so that its review fits in one pass -- the pattern of #196824 and #196825, which pin the dispatch's last resort and a guarded global the loading process does not have from test-only commits. Split twice more for review budget: the five-test revision of this commit died at the review bot's 60-minute ceiling, so the two tests that pin WHEN the report resolves `forward` -- only for a SUPPLIED scope, and once -- moved up into `[aot_compile] Pin when the no-match report resolves forward` (#197301), and the three-entry test that pins which entries share a hint line moved up into `[aot_compile] Pin that the no-match report shares one hint line across entries worded alike`. What stays here is the pair that pins WHICH entry the hint names a `forward` for: one where no entry is, and one where exactly one of two is. Both pass at the parent, whose report they pin, fail below the report commit (#196896) where no report exists, and each fails under a targeted edit of `_no_match_report` that no other test in the file catches, measured by editing the report and running the whole file. Two tests of the previous revision are gone, one because the footer gate it fenced is already fenced by two other tests and one because it is folded into the three-entry test's entry `[1]` in the commit above.

## What the report does at this tree

The report decides its hint per entry. An entry whose verbose parts name a whole missing global gets `_missing_global_hint(forward=...)`, with `forward` set when `resolved is not None and resolved is result._guard_globals`; `resolved` is what one `_resolve_guard_scope(self.model)` returned, run at most once, at the first hinted entry whose scope is SUPPLIED, and reused for every entry after it (when it runs, and that it runs once, is #197301's).

```
# the two wordings the tests tell apart
For [i]: a guarded global is missing from the live scope this artifact was loaded against; define it there ...   # neutral
For [i]: ... this GlobalConfigModule instance's forward resolves to ...                                          # named
```

## Both fail below the report commit

Both tests pass at the parent, whose report they pin, and fail below the report commit (at #196896, the commit under it), where the no-match fall-through `results[0](self.model, *args, **kwargs)` raises the function path's `GuardManager check failed` message. That message quotes the guard's `KeyError on G[...]` part and, for a whole missing global, appends the function path's hint sentence, so the `loaded against; define it there` substring the tests also look for is present there; what it lacks is the `[i]` entry prefix, the `For [i]:` hint line and the `Tried N` header, and with no report there is no resolve. Measured with that tree's `aot_compile.py` under this tree's test file:

| test | failure below the report commit |
| --- | --- |
| `..._hint_stays_neutral_for_a_supplied_scope` | `"[0] KeyError on G['AOT_HERMETIC_WEIGHT']" not found` |
| `..._names_forward_only_for_the_dict_it_resolves_to` | `Expected '_resolve_guard_scope' to be called once. Called 0 times` |

The one that compiles in its own body calls `_hide_leaked_dynamo_globals()` on entry, as the capture-only `test_aot_compile_fn_missing_global_hint_names_the_tracing_scope` does; the other shares `_two_input_global_guard_artifact` with `test_no_match_message_hints_each_scope_a_mixed_model_failed_in` and the landed `test_aot_compile_module_missing_global_hint_names_the_resolved_module` and, like them, does not, its kept guards being rooted at `GLOBAL_POOLING_CONFIG` alone.

## `test_no_match_message_hint_stays_neutral_for_a_supplied_scope`

```python
scope: dict[str, object] = {"__builtins__": builtins}          # never had AOT_HERMETIC_WEIGHT
compiled = AOTCompiledModel.deserialize(HermeticModule(), data, guard_globals=scope)
with self.assertRaises(RuntimeError) as ctx:
    compiled(x)
message = str(ctx.exception)
self.assertIn("[0] KeyError on G['AOT_HERMETIC_WEIGHT']", message)
self.assertIn("For [0]: a guarded global is missing from the live scope this artifact was loaded against; define it there", message)
self.assertNotIn("instance's forward", message)
# the advice, followed: the guards hold the supplied dict, and defining the name there serves the call
self.assertIs(compiled.compiled_results[0]._guard_globals, scope)
scope["AOT_HERMETIC_WEIGHT"] = AOT_HERMETIC_WEIGHT
self.assertEqual(compiled(x), x @ AOT_HERMETIC_WEIGHT)
```

It loads through `AOTCompiledModel.deserialize(..., guard_globals=...)` with a dict that never had the guarded name, so the guards hold a dict no `forward` resolves to, asserts the scope-neutral wording under its `For [0]:` prefix, and then the advice it gives: `compiled_results[0]._guard_globals is scope`, and defining the name in that dict serves the call -- with `AOT_HERMETIC_WEIGHT` defined in this module's dict, where the class's `forward` lives, the whole time.

Reducing the compare to `resolved is not None` fails it with a report that names `this HermeticModule instance's forward`, and fails exactly two others: the landed #196818's `..._names_the_resolved_module`, whose second half loads with `guard_globals=dict(globals())` -- a copy of the module dict, taken while the module itself lacked the name, that is not the dict `forward` resolves to -- and asserts `loaded against; define it there`, and this commit's `names_forward_only_for_the_dict_it_resolves_to`, whose caller-supplied entry is then told which forward as well. #197048's `test_no_match_report_survives_a_forward_resolve_that_raises` reaches the neutral wording through `resolved is None`, and its `test_no_match_message_hint_covers_a_rebound_forward` through a resolve that IS the dict the guards hold, so both pass under that edit.

What this test adds over `..._names_the_resolved_module` is the other way to the wording, a supplied dict that never had the name rather than a stale copy carrying the module's `__name__`, and the recovery: no other `AOTCompiledModel.deserialize(..., guard_globals=)` test defines a missing name in the supplied dict and asserts the call is served (`..._deserialize_takes_a_guard_globals_scope` supplies a copy that already carries its names, and `covers_a_rebound_forward` defines the name in the dict the load RESOLVED, not one the caller passed).

## `test_no_match_message_names_forward_only_for_the_dict_it_resolves_to`

```python
by_forward = AOTCompiledModel.deserialize(GlobalConfigModule(), data)                    # resolves scope from model.forward: this module's dict
by_caller = AOTCompiledModel.deserialize(GlobalConfigModule(), data, guard_globals=scope)  # a dict that never had the name
self.assertIs(by_forward.compiled_results[0]._guard_globals, globals())
self.assertIs(by_caller.compiled_results[0]._guard_globals, scope)
del GLOBAL_POOLING_CONFIG
pair = by_forward.compiled_results[:1] + by_caller.compiled_results[:1]
cases = ((pair, [named, neutral]), (pair[::-1], [neutral, named]))                        # both orders
for results, wording in cases:
    mixed = AOTCompiledModel(GlobalConfigModule(), results)
    with patch(target, wraps=_resolve_guard_scope) as resolves, self.assertRaises(RuntimeError) as ctx:
        mixed(x)
    resolves.assert_called_once_with(mixed.model)          # one resolve, asked about the model the report is for
    hints = [line for line in message.splitlines() if line.startswith("For [")]
    self.assertEqual([line[:9] for line in hints], ["For [0]: ", "For [1]: "], message)
    for hint, want in zip(hints, wording):
        self.assertIn(want, hint)
```

This is the shape that tells a per-entry `forward` from one shared across the report. Two SUPPLIED results whose guards hold different dicts -- one from `deserialize(GlobalConfigModule(), data)`, which resolves the scope from `model.forward` and so holds this module's dict, the one `_resolve_guard_scope` returns; one from `deserialize(..., guard_globals=scope)` with a dict that never had the name -- go into one `AOTCompiledModel` by hand, as `hints_each_scope_a_mixed_model_failed_in` builds its CAPTURED + SUPPLIED pair, and are dispatched with `GLOBAL_POOLING_CONFIG` deleted, in both orders. Each order enters a fresh `patch(..., wraps=_resolve_guard_scope)`, so its count is that order's alone, and asserts `assert_called_once_with(mixed.model)` -- one resolve, asked about the model the report is for -- two `For [i]:` lines, and that the entry holding the resolved dict is the one told `this GlobalConfigModule instance's forward` while the other gets the live-scope wording.

| edit to `_no_match_report` | fails |
| --- | --- |
| decide `forward` once, at the first hinted entry, and apply it to every entry | this test alone, on the second entry's wording (`'the live scope this artifact was loaded against; define it there' not found in "For [1]: ... this GlobalConfigModule instance's forward resolves to ..."`) |
| resolve `_resolve_guard_scope(type(self.model)())` instead of `self.model` | this test on `expected call not found`, plus #197048's `covers_a_rebound_forward` and `survives_a_forward_resolve_that_raises` on wording |

Nothing else in the file catches the first edit: `..._names_the_resolved_module`'s two entries share one dict in each half, and `hints_each_scope`'s SUPPLIED entry is its only one. The line count does not catch that edit, because the resolved dict carries a `__name__` and the supplied one does not, so the two hints stay two sentences either way; the wording does. The `_with(mixed.model)` is what pins which module is resolved: asking about a fresh instance resolves to the same dict here, so the wording cannot tell, and a fresh instance does not carry the `forward` the two #197048 tests rebind.

## Two tests of the previous revision are gone

`test_no_match_message_advises_an_input_for_a_missing_global` and its `SelfModeBranchGlobalModule` fixture pinned the footer under a report whose every entry was hinted; the footer is unconditional, and returning before it when `sum(map(len, hinted.values())) == len(results)` fails two tests at this tree without it (both on `'Add a ModelInput' not found`): #196825's `test_aot_compile_module_absent_global_fails_guard` and #197048's `survives_a_forward_resolve_that_raises` (and, one commit up, #197301's `resolves_forward_only_for_a_supplied_scope`). Its other assertions -- that the `L['self'].mode` mismatch is absent from the first report and named by the second -- pinned the guard tree's install order and fail-count re-sort in guards.cpp, not the report.

`test_missing_key_inside_a_present_global_is_not_a_missing_global` is folded into the three-entry test's entry `[1]`, which fences the same substring edit, and rides with it in the commit above.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_hint_stays_neutral_for_a_supplied_scope
python test/dynamo/test_aot_compile.py -k test_no_match_message_names_forward_only_for_the_dict_it_resolves_to
python test/dynamo/test_aot_compile.py
```

The whole file is green here and on the parent commit.

## FAQ

> **FAQ: The review found that
> `test_aot_compile_module_missing_global_hint_names_the_resolved_module`, in
> the landed #196818, already fails under the edit that this commit's
> `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` was once
> described as the one test to catch. Why keep the test?**
>
> Because the coverage claim was wrong, and the test's other half is not pinned
> anywhere else. Re-measured on the whole file with the compare reduced to
> `resolved is not None`: the failures are `..._names_the_resolved_module`
> (`'loaded against; define it there' not found`), this test, and this commit's
> `names_forward_only_for_the_dict_it_resolves_to`; every other test passes. So
> the identity compare is fenced at #196818 as well, and the message says so
> instead of crediting this test alone. What this test alone covers is a
> `guard_globals=` dict that never had the name --
> `..._names_the_resolved_module` reaches the same wording through
> `dict(globals())`, a copy taken while the module itself lacked the name --
> and the recovery, defining the name in that dict and asserting the call is
> served, which no other `AOTCompiledModel.deserialize(..., guard_globals=)`
> test does.

> **FAQ: The review found two of an earlier revision's five tests largely
> redundant with the base, and two report branches -- where `tried_forward` is
> set, and hint dedup keyed by text -- unpinned. What changed?**
>
> Both redundancies were measured and both tests are gone; both branches are
> now pinned, one in the commit above and one in #197301. Gating the footer on
> every entry being hinted, the edit
> `test_no_match_message_advises_an_input_for_a_missing_global` fenced, fails
> two tests at this tree without it -- #196825's `absent_global_fails_guard`
> and #197048's `survives_a_forward_resolve_that_raises` -- so that test and
> its fixture add no fence on the report, and its `L['self'].mode` assertions
> pin guards.cpp's accessor order, not this function. Replacing the report's
> whole-part predicate with a substring test, the edit
> `test_missing_key_inside_a_present_global_is_not_a_missing_global` fenced
> alone, and keying `hinted` by dict identity are both fenced by the
> three-entry `shares_a_hint_line_across_entries_worded_alike` in the commit
> above, so the fold loses no coverage and the module path still has its own
> pin of the predicate. The `tried_forward` mark is pinned by #197301's
> `resolves_forward_once_past_a_resolve_that_raises`.

> **FAQ: Every new test passes at the parent commit. Where is the red-on-parent
> evidence?**
>
> There is none by construction: this is a tests-only commit pinning the
> report the parent already ships, so every test passes on the parent's tree.
> The two measurements that stand in for it are above: each test fails under
> the tree below the report commit (#196896), where no report exists, and each
> fails under a targeted edit of `_no_match_report` that no other test in the
> file catches -- the mutation table is what shows the pins are not vacuous.

> **FAQ: The review listed `"; ".join(parts)` with more than one verbose code
> part per entry as uncovered. Why is there no test for it here?**
>
> Because that join is #197134's (`Keep a no-match report entry to one line
> that says what its guards answered`), whose
> `test_no_match_report_keeps_an_entry_on_one_line_past_odd_separators` owns
> the entry format; how many parts an entry quotes has no bearing on the hint,
> which is what this commit pins. A multi-part entry test belongs next to that
> one, in that PR.

Authored with the assistance of Claude Code.

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

Pull Request resolved: #197001
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1167/head branch November 19, 2026 01:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: dynamo topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants