Skip to content

[aot_compile] Re-read a guarded global before every call instead of serving the load-time value - #196897

Closed
bobrenjc93 wants to merge 49 commits into
gh/bobrenjc93/1185/basefrom
gh/bobrenjc93/1185/head
Closed

bobrenjc93 wants to merge 49 commits into
gh/bobrenjc93/1185/basefrom
gh/bobrenjc93/1185/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary. A module artifact loaded with a live guard scope has two dicts that must agree about one global: the kept guards read the scope by reference, while the compiled bytecode reads fn.__globals__, into which __post_init__ merged the guarded names exactly once, at load. A kept TENSOR_MATCH certifies the exact Python type, dtype, shape, device and requires_grad, not values, so rebinding a guarded global to a DIFFERENT tensor of identical metadata passed the check while the graph went on computing with the tensor the load happened to see -- wrong numerics, nothing raised, and test_aot_compile_module_reload_reads_the_live_global pinned that as intended behaviour. This commit adds AOTCompiledFunction._serve, which re-takes the certified names out of _guard_globals into fn.__globals__ immediately before running the graph, and routes __call__ and all four exits of AOTCompiledModel.__call__ through it, so _serve is the only caller of the raw fn and what a guard just certified is what the graph reads. Only a global a kept guard's own bare GlobalSource names is re-read (_live_global_names, recorded under the module load path's _bytecode_reads_guard_scope and _has_global_guards gate and not intersected with the scope), the load-time merge stays because _check_external_refs needs a certified global the graph never lifted bound before any call, and each read is one scope.get(name, _UNBOUND). Three things change against the parent, all on a module artifact loaded with a live scope: an accepted post-load rebind is now computed with on every dispatch exit, an opted-out result is served whatever the scope binds, and a graph that STORE_GLOBALs a certified global no longer accumulates the store across calls; load_compiled_function(f_globals=...) is unchanged until #197218.

Where this sits in the stack

Split from [aot_compile] Arm the per-call re-read of a guarded global for a function artifact loaded with f_globals (#197218, directly above) so each piece fits the review budget: this commit introduces the per-call re-read and serves AOTCompiledFunction.__call__ and all four exits of AOTCompiledModel.__call__ through it, armed for the module load path, which is the only path the load-time pick ever ran on. The re-read supersedes that pick as the source of a served value without removing it: the merge stays here and #196909 drops the flag that gates it, while #197218 widens what arms the re-read to load_compiled_function(f_globals=...). The three fallback exits of module dispatch were briefly split out as a commit of their own (#197302) and are folded back here: with them out, this commit's own dispatch path served a stale global on three of its four exits, the bug it exists to fix one pass over.

The bug: two dicts about one global

# module load path, parent and now: the kept guards resolve against the scope
# the load resolved from model.forward (or the guard_globals the caller
# supplied) and read it BY REFERENCE ...
scope = model.forward.__globals__            # guards check scope["EPS"]
# ... while the compiled bytecode reads fn.__globals__, which the load builds once.
result.fn.__globals__["EPS"]                 # graph computes with this

EPS = torch.tensor(2.0)                      # same dtype/shape/device/requires_grad
reloaded(x)
# parent: TENSOR_MATCH passes (metadata, not values); graph computes x * <load-time EPS>
# now:    TENSOR_MATCH passes; _serve writes scope["EPS"] into fn.__globals__ first; x * 2.0

Rebinding a global after the load therefore changed what the guards check but not what the graph computes with, and the two only disagreed silently. test_aot_compile_module_reload_reads_the_live_global pinned that as intended behaviour ("A rebind after the load: the call still answers with the load-time value"), and AOTCompiledModel.deserialize's docstring described the snapshot; this commit fixes it instead, and that assertion is flipped.

BC: three changes against the parent

All three are on a module artifact loaded with a live scope.

  1. A call whose guards accept a post-load rebind now computes with the rebound value, whichever of the four dispatch exits serves it; the parent served the load-time value on every one.
  2. A result that opted out via disable_guard_check() is served by the last-resort exit with whatever the scope binds, a value its kept guards REFUSED included; the parent served the load-time value there too, and disable_guard_check() flips one bool without disarming the re-read.
  3. A graph that itself STORE_GLOBALs a certified global no longer accumulates the store across calls. No scope rebind is needed to observe this one, which makes it the change a caller hits without doing anything.
class StoresEpsModule(torch.nn.Module):
    def forward(self, x):
        global EPS
        y = x * EPS
        EPS = EPS * 2
        return y

# three calls of a loaded artifact, E = the value the scope binds
reloaded(x); reloaded(x); reloaded(x)
# parent: x * E, x * 2E, x * 4E   (the store accumulates in fn.__globals__)
# now:    x * E, x * E,  x * E    (each call starts from the scope's value again)

test_aot_compile_module_store_global_does_not_accumulate pins it on the module load path, the path this commit arms. Nothing that raised before stops raising, and a global that is not itself a kept guard's source keeps its load-time value exactly as before.

One path is NOT changed by this commit: load_compiled_function(f_globals=...) still serves the load-time value, exactly as its docstring and the user guide describe, and test_load_compiled_function_f_globals_accepted_rebind_is_not_used still pins that; #197218 arms the re-read there and flips it. The tests listed under the Test Plan pin this commit's change: each is red on the parent's aot_compile.py.

The fix: move the pick from load to call

The root cause is that the substitution was a one-time merge. __post_init__ picked the guarded names out of the supplied scope and folded them into extra_globals, i.e. into the dict forward_callable builds, so the live read happened exactly once, at load.

# parent, __post_init__
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}

# now, __post_init__: record the set, and still merge at load
certified = _guard_source_globals(output_graph)
self._live_global_names = tuple(sorted(certified))
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}

# now, _serve: re-take the same names immediately before invoking the graph
def _serve(self, *args, **kwargs):
    if self._live_global_names:
        scope = self._guard_globals
        if scope is None:
            raise AssertionError("_live_global_names recorded without a scope")
        f_globals = self.fn.__globals__
        for name in self._live_global_names:
            value = scope.get(name, _UNBOUND)
            if value is not _UNBOUND:
                f_globals[name] = value
    return self.fn(*args, **kwargs)

__post_init__ records the name set under the same gate the merge already had, _bytecode_reads_guard_scope and _has_global_guards, so only the module load path arms the re-read here -- load_compiled_function passes one dict as both f_globals and guard_globals and has the same divergence, which #197218 fixes by widening the gate -- and still merges the bound names into the bytecode's globals at load.

That merge is not made redundant by the re-read. forward_callable runs _check_external_refs at load, before _serve can ever run, and a certified global the bytecode reads but the graph never lifted -- a global the forward mutates or returns -- is in external_refs but in neither import_sources nor used_globals, the only dicts forward_callable builds fn.__globals__ from, so the merge is what binds it. (The serialized output_graph.global_scope does carry it, being filtered to the kept guards' roots, but forward_callable never reads that dict.) The comment on the merge says so, and test_aot_compile_module_load_binds_a_global_off_the_graph pins that shape on its RETURNS half:

class ReturnsEpsModule(torch.nn.Module):
    def forward(self, x):
        return x + 1, EPS       # EPS returned, not computed with

env = result._artifacts.runtime_env
assert "EPS" in env.external_refs
assert "EPS" not in env.used_globals and "EPS" not in env.import_sources
# with the merge deleted the load itself refuses:
#   Missing required external references: ['EPS']

A forward that returns EPS rather than computing with it has the placeholder it was lifted into pruned as unused, so used_globals -- filled from the graph inputs' sources -- never records a name the generated bytecode still reads. The MUTATES half needs a container to show, a rebound tensor global being lifted like any other read; #196909, two commits up, parametrizes both halves over a list global and drops the flag that gates the merge.

Every dispatch exit goes through _serve

AOTCompiledModel.__call__ has four exits that run a graph. The first pass checks the first compiled result's guards and, on a pass, serves it; below it sit the rest of that sweep over results[1:], a re-check pass that re-runs every check() (one exit of check() refuses from the recursive dict-tag fast check without running the tree, and disarms it, so the second call runs the tree the first skipped), and a last resort that serves a result whose caller opted out via disable_guard_check().

# parent -> now, at each of the four exits
return first.fn(self.model, *args, **kwargs)      ->  return first._serve(self.model, *args, **kwargs)
return result.fn(self.model, *args, **kwargs)     ->  return result._serve(self.model, *args, **kwargs)   # sweep
return result.fn(self.model, *args, **kwargs)     ->  return result._serve(self.model, *args, **kwargs)   # re-check
return result.fn(self.model, *args, **kwargs)     ->  return result._serve(self.model, *args, **kwargs)   # opted-out last resort

All four call _serve, which is thereby the only caller of the raw fn, and _serve's docstring says so. That also rules out a state the re-read could otherwise have introduced: _serve's write into fn.__globals__ persists between calls, so a pass that ran the raw fn after an earlier accepted call had re-read rebind R1 would compute with R1 while the scope binds R2 -- neither the serialized value nor the live one; with every exit re-reading immediately before it runs the graph, no pass can serve a value an earlier call re-read for a name the scope binds.

test_aot_compile_module_second_pass_rebind_is_served pins exactly that:

EPS = torch.tensor(3.0)
reloaded(x)                                            # first pass accepts, re-reads 3.0
assert result.fn.__globals__["EPS"] is first_rebind    # asserted: left in fn.__globals__

EPS = torch.tensor(2.0)
# stub: the scan's check() answers False without running the tree (what the
# fast path that makes the re-check pass necessary answers); every check()
# after it runs the real tree
with patch.object(manager, "check", side_effect=rejects_the_scan) as check:
    served = reloaded(x)
assert check.call_count == 2
assert served == x * 2.0          # not the load-time value, not x * 3.0

The call at EPS = 2.0, on a LOADED artifact, the only kind the re-read is armed for, has to run check() exactly twice and serve x * 2.0. The stub replaces this case's earlier use of the file's _install_global_probe idiom, for a measured reason the Test Plan gives.

test_aot_compile_module_sweep_rebind_is_served pins the results[1:] sweep: two results compiled for inputs of shape (3,) and (4,), so the first pass refuses the (4,) call on the first and the sweep serves it from the second, which has to compute with the rebind its own guards just accepted; the second result's fn.__globals__ then holds the rebind and the first's still the load-time value, both asserted. The same test then calls results[0] directly, through AOTCompiledFunction.__call__, with the (3,) input its guards accept, and that call has to compute with the rebind and leave it in the first result's fn.__globals__: __call__ is the one _serve site module dispatch never reaches, and it is public through compiled_results.

The dispatch comment records why the _serve frame is not gated per site all the same: a site that got a per-site gate wrong would serve a stale global with every guard passing. That such a site would also be invisible to every test whose artifact is not armed is the FAQ's argument below, not the comment's.

Serve the rebind rather than refuse it

Serving is the right direction: the guard the swap satisfies certifies exactly the properties the graph was compiled for, so the new value is one the graph can legitimately run on, and refusing would mean raising on a call whose guards all pass. The alternative of re-rooting the guards at fn.__globals__ was rejected for the opposite reason -- it makes the caller's dict write-only from the guards' point of view, which is the contract guard_globals exists to provide.

What is re-read, and what is not

Two details are deliberate and each is pinned by a test.

First, the recorded name set is NOT intersected with the scope at load: a name the scope does not bind yet fails the guard rooted at it, and a caller told to bind it by the KeyError on G['X'] message then gets its value read, not the value serialized with the artifact (test_aot_compile_module_absent_global_fails_guard).

Second, only a global that is itself a kept guard's source is re-read -- _guard_source_globals keeps the bare GlobalSources -- so a global whose guard a filter dropped keeps its load-time value, because nothing certifies a live value for it, and so does a container a kept guard reaches only through a sub-path:

# test_aot_compile_module_sub_path_global_is_not_read_live: the kept TENSOR_MATCH is on
# G['AOT_NESTED_GLOBAL']['a'] and certifies that one item, not the dict's other members
AOT_NESTED_GLOBAL = {"a": torch.randn(3), "b": torch.nn.Parameter(torch.ones(3))}
# ... capture, save, load, then rebind the CONTAINER to a dict whose "a" still passes:
AOT_NESTED_GLOBAL = {"a": torch.randn(3), "b": torch.nn.Parameter(torch.ones(3, dtype=torch.float64))}
reloaded(x)   # AOT_NESTED_GLOBAL is not re-read: the load-time dict is served even though the guard passes

test_aot_compile_module_sub_path_global_is_not_read_live pins that on the module path, and _serve's and AOTCompiledModel.deserialize's docstrings say it in as many words rather than promising a re-read of every global a kept guard is "rooted at", which in this file's own vocabulary (get_global_source_name) is the wider set.

test_aot_compile_module_rebind_after_load_is_served pins the certified set from both sides with TwoGlobalsModule, whose forward reads EPS, a plain tensor whose TENSOR_MATCH is kept, and AOT_UNGUARDED_PARAM, an nn.Parameter whose guard the filter drops: after rebinding both, the call has to follow the new tensor and the OLD Parameter.

A graph that stores to its own global

A graph that itself rebinds a guarded global (global W; y = x * W; W = W * 2) is served the same way. Dynamo replays the store as a STORE_GLOBAL into the bytecode's globals, never into the scope the guards read, so the stored value is one no guard certified; previously it accumulated there across calls (call n computed with the load value doubled n times while the guards went on passing on the scope's), and now the re-read takes the scope's value back before each call. Neither writes the scope, which eager would, and that is pre-existing.

_serve's docstring says so, and says what a store to a global NO kept guard certifies gets, the one case the re-read does not take back: that value stays in the bytecode's globals and goes on accumulating there, so the docstring's "every other global" clause is about what those globals HOLD and not about the load-time value they were built with. Measured on an armed artifact whose forward is global P; y = x * EPS + P; P = P * 2, with EPS a plain tensor (certified) and P a Parameter (its guard dropped by the filter, so not in _live_global_names):

call answer fn.__globals__["P"] after the call module P
1 x * 6.0 + 1.0 2 1.0
2 x * 6.0 + 2.0 4 1.0
3 x * 6.0 + 4.0 8 1.0

test_aot_compile_module_store_global_does_not_accumulate pins the certified half on the module load path: three calls of a loaded StoresEpsModule artifact answer alike, the scope's EPS is the value it held before them and the doubled value is left in the bytecode's globals. #197218 adds the function-path case.

The opted-out last resort

The last resort changes with the other three exits: the parent served the load-time value there as well, and it now serves whatever the scope binds. What is documented and pinned rather than changed is that the opt-out does not disarm the re-read: the name set is recorded by the load, before the opt-out flips anything, so an opted-out artifact goes on serving whatever the scope binds, a value a kept guard would have rejected included.

EPS = torch.nn.Parameter(torch.tensor(2.0), requires_grad=False)   # the kept TENSOR_MATCH refuses a Parameter
reloaded(x)
# RuntimeError: No AOT compiled graph matched this call ...
#   expected type of 'G['EPS']' to be <class 'torch.Tensor'>, but found <class 'torch.nn.parameter.Parameter'>
result.disable_guard_check()
reloaded(x)                 # == x * 2.0: the last resort serves the value the check refused
del EPS
reloaded(x)                 # still x * 2.0: an unbound name is skipped, not deleted

test_aot_compile_module_opted_out_load_rebind_is_served asserts the no-match report's expected type of 'G['EPS']' line, so it is that guard and not a missing name that pushes dispatch off both guard-checked passes onto the last-resort exit, and watches the opted-out call follow the rebind. That is the opt-out being unsafe by construction, not an accident, since holding those names at their load-time values would be no more checked, only stale, and _serve's docstring says so, along with what a name the scope no longer binds gets under the opt-out: the last value read, since the re-read skips a name the scope lacks rather than deleting it. The alternative of clearing _live_global_names in disable_guard_check() was tried as a mutation and refuted by that test.

One read: scope.get(name, _UNBOUND)

_serve's re-read is one scope.get(name, _UNBOUND): neither a membership test followed by a read, nor a subscript under try/except KeyError.

Against the membership test, the scope is live, so a del of the name landing between the test and the read would let a bare KeyError out of a call whose guards had just passed, where the docstring promises a skip. test_aot_compile_module_global_deleted_under_the_re_read_is_skipped pins that with a scope that answers the membership test and raises from __getitem__:

class DeletedBetweenTestAndRead(dict):
    def __contains__(self, name):
        return True
    def __getitem__(self, name):
        raise KeyError(name)

with patch.object(result, "_guard_globals", DeletedBetweenTestAndRead()):
    reloaded(x)     # check-then-read form: KeyError: 'EPS'; dict.get consults neither, so x * rebound

Against the subscript, the scope can be a mapping the CALLER passed as guard_globals, and a subscript runs whatever __missing__ hook that mapping defines: a collections.defaultdict is then MUTATED by the read and the graph computes with the value it fabricates, every guard passing on it -- the exact failure this commit exists to remove, reached through the read that fixes it. test_aot_compile_module_missing_hook_scope_is_not_asked_to_fabricate pins both reads against one:

scope = collections.defaultdict(lambda: torch.tensor(99.0))
compiled = AOTCompiledModel.deserialize(EpsOnlyModule(), data, guard_globals=scope)
assert dict(scope) == {}                       # the load did not subscript it
compiled(x)                                    # RuntimeError: ... KeyError on G['EPS']
result.disable_guard_check()
compiled(x)                                    # == x * 5.0, the serialized value
assert dict(scope) == {}                       # nor did either call

The defaultdict is still empty after the load and after a call -- the only path that can bind the fabricated tensor in the bytecode's globals is a subscript of that dict, which would leave its entry behind, so the empty dict is the pin and an assertion on those globals adds nothing -- and the guard rooted at the name refuses the call until that result opts out, after which the serialized value is what is served. dict.get neither dispatches through an overridden __getitem__ nor pays the raise, so it keeps the single lookup the del window argues for, and the module-level _UNBOUND sentinel is what separates a global bound to None from an absent one, which test_aot_compile_module_global_bound_to_none_is_re_read pins (with None as the default the read would skip the binding and leave the last value written).

The load-time merge in __post_init__ reads the same way, and the del window is pinned at the _serve site alone: no call is in progress and no guard has run at the merge, so a name the scope lacks there, never bound or deleted under the read alike, is left unbound and the guard rooted at it then fails, which is what the merge comment says.

The AssertionError narrowing

_serve narrows _guard_globals the way _live_guard_manager narrows guard_manager, with an AssertionError rather than a fall-through to the raw fn. The arm is unreachable: _live_global_names has its one assignment in __post_init__, under if guard_scope is not None, and the constructor is the only writer of _guard_globals. It is loud all the same because a silent arm there would be the exact defect this commit fixes, a stale global served with every guard passing: with _guard_globals patched to None on an armed result, the is not None form this replaces served the value the previous call had re-read, and this form raises.

Documented rather than changed

_serve's docstring says what a name the scope does not bind gets: the re-read skips it rather than deleting it, so it keeps whatever it last held -- the serialized value if the scope never bound it -- and, unless the check is disabled, the guard rooted at it refuses the call. Two caveats that docstring carries, since the per-call re-read is what it now promises:

  • The re-read is not atomic with the guard check before it, so a rebind landing between the two is served unchecked -- the same window an eager compiled frame has between guard evaluation and its bytecode's global reads.
  • The write lands in the loaded artifact's own fn.__globals__, which every call of it shares, so two threads serving one loaded artifact race on it and a caller who needs isolation loads the artifact once per thread, each load building one such dict per compiled result.

That docstring also records what does NOT arm the re-read here: a function artifact loaded with f_globals (until #197218), and an artifact compiled in this process, which is handed no scope, so its globals keep the values the capture copied while its guards read the module dict they were rooted in. That divergence is pre-existing and deliberately not widened here.

The _live_global_names field comment says what arms the set: _bytecode_reads_guard_scope, and not a supplied scope as such, since load_compiled_function supplies one as guard_globals and is not armed. That only the module load path sets that flag is the adjacent _bytecode_reads_guard_scope comment's own line, rewritten here to say the certified names are picked in again by _serve before every call.

The AOTCompiledModel.deserialize docstring says the certified names are re-taken from the live dict on every call, and that the certification stops at a result that opted out through disable_guard_check(): dispatch serves it once every checked result refused the call, and the re-read serves it whatever the live dict binds, a value a kept guard refused included. Without that sentence the docstring's "a value the graph reads live is one a passing guard certifies" was contradicted by the last-resort exit test_aot_compile_module_opted_out_load_rebind_is_served pins, and that docstring is the one a module-load caller reads. For the same reason it also carries what the per-call write costs a caller, beside the paragraph that already discloses the load-time mutation of the same dict: every call writes the certified names into the globals of the compiled RESULT that serves it, which every call that result serves shares, so two threads whose calls land on one result while either rebinds a guarded global race on that dict, and a caller who needs isolation loads once per thread, each load building one such dict per serialized result. The artifact deserialize returns has no globals of its own: it builds one AOTCompiledFunction per serialized result and forward_callable gives each a fresh f_globals, which is why two threads whose calls land on DIFFERENT results do not race, and test_aot_compile_module_sweep_rebind_is_served asserts exactly that shape -- the rebind in results[1]'s globals and the load-time value still in results[0]'s. The parent had no per-call write at all, so this is a new hazard, and _serve's own statement of it is not enough: _serve is private.

The bytecode_reads_guard_scope paragraph of AOTCompiledFunction.deserialize says the certified names are re-taken before every call as well; both are true of every dispatch exit, measured by the tests above (the re-check pass serves x * 2.0 after an accepted call re-read 3.0; the last resort serves the Parameter the check refused).

Three test comments follow the code:

  • test_aot_compile_module_guards_track_rebound_global, whose dispatch a rebound global redirects between two results, now says every call refreshes the name the guards specialised on.
  • test_module_dispatch_evaluates_a_matching_tree_once now says the scan calls the matching result's _serve, since the raw fn field it named is no longer what any dispatch exit calls.
  • test_load_rederives_a_builtins_key_bound_to_its_own_snapshot says what keeps the builtins key out of the bytecode's globals now that the name != builtins_key test it quoted is gone: that case is a function-path load, so the gate keeps it out there and the pick never runs at all, and the pick the module path arms takes a guard's own bare GlobalSource alone.

One dead token goes with that pass. The parent filtered the key out of the load-time pick (name != builtins_key) and this commit first carried that filter into the new certified line as - {builtins_key}, where it can never remove anything: load_builtin_from_argval is the one site in the tree that mints a source under this key, always DictGetItemSource(GlobalSource(key), name) and only for a callable builtin, so a chained source is the only way the key is reached and _guard_source_globals drops it by construction. Measured: instrumenting that function to record every call where the key is truthy and present in its result reports no hit over the whole file, and the file is green with the subtraction dropped. The subtraction one branch up, on the WIDE set (recorded_globals), is load-bearing and stays: the serializer writes the key into global_scope whether a guard reads it or not, and dropping that one turns the file red, which is why only the narrow one is dropped.

Nothing in that pass changes behaviour: the docstrings, that field comment, the measured cost in the dispatch comment, the dropped subtraction and the tests only describe and pin what the code above already does.

Test fixtures

One test fixture moves to module level, others are new there, and one pre-existing leak is fixed.

class EpsOnlyModule(torch.nn.Module):          # new: x * EPS
class TwoGlobalsModule(torch.nn.Module):       # moved: x * EPS + AOT_UNGUARDED_PARAM (Parameter's guard dropped)
class TwoCertifiedModule(torch.nn.Module):     # new: x * EPS + AOT_LIVE_SCALE, two certified names
class StoresEpsModule(torch.nn.Module):        # new: rebinds EPS in forward
class ReturnsEpsModule(torch.nn.Module):       # new: returns EPS instead of computing with it

TwoGlobalsModule is the one that moves: it was a class local to test_aot_compile_module_only_the_guarded_global_is_read_live and the new test_aot_compile_module_rebind_after_load_is_served loads it too. AOT_UNGUARDED_PARAM's initial binding moves up beside it; the NAME was already a module-level global at the parent, declared global EPS, AOT_UNGUARDED_PARAM in that test and first bound there, so what changes is where the Parameter is first bound and not who can see the name. EpsOnlyModule, TwoCertifiedModule -- whose forward reads two plain tensor globals, with AOT_LIVE_SCALE, so the certified set has two names in it where every other fixture leaves it at one -- StoresEpsModule, whose forward rebinds the global it reads, and ReturnsEpsModule, whose forward returns it instead of computing with it, are new at that level, and the parent has none of them anywhere in the file. That test also gains an addCleanup for AOT_UNGUARDED_PARAM, which fixes a leak the parent already had rather than one the move introduces: the parent rebound that global under its own global statement and restored only EPS, so the rebind was file-visible and unrestored there too -- unnoticed, not invisible.

Review order

Review _serve first, then what __post_init__ records for it, __call__ and the four exits of AOTCompiledModel.__call__ with the dispatch comment, then the two prose passages that described the old snapshot semantics (the AOTCompiledModel.deserialize docstring and the bytecode_reads_guard_scope paragraph of AOTCompiledFunction.deserialize), then the tests, starting with _load_armed_module, the loader all but one new case goes through.

Test Plan:

python test/dynamo/test_aot_compile.py

The new cases, and the existing cases that pinned the old behaviour:

python test/dynamo/test_aot_compile.py -k test_aot_compile_module_rebind_after_load_is_served
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_every_certified_global_is_re_read
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_store_global_does_not_accumulate
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_load_binds_a_global_off_the_graph
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_global_bound_to_none_is_re_read
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_sweep_rebind_is_served
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_second_pass_rebind_is_served
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_opted_out_load_rebind_is_served
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_global_deleted_under_the_re_read_is_skipped
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_missing_hook_scope_is_not_asked_to_fabricate
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_certified_names_are_sorted_at_load
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_absent_global_fails_guard

The existing case that pins the sub-path exclusion the docstrings describe:

python test/dynamo/test_aot_compile.py -k test_aot_compile_module_sub_path_global_is_not_read_live

test_aot_compile_module_rebind_after_load_is_served rebinds two globals under
keep_tensor_guards_unsafe: a plain tensor whose TENSOR_MATCH is kept, and
an nn.Parameter whose guard the filter drops. The call has to follow the new
tensor and the OLD Parameter, which pins the re-read and that the set did not
widen past what a guard certifies. All but one of the new cases load through
_load_armed_module, which asserts the certified set on each loaded result
before the test rebinds anything -- ("EPS",), or ("AOT_LIVE_SCALE", "EPS")
for the two-name cases -- so a served load-time value would be the test's own
doing and not an unarmed artifact; the __missing__ pin loads directly, since
what it needs as the guard scope is a collections.defaultdict and the helper
always passes the module's own globals. That helper binds EVERY name it arms
twice rather than only EPS: torch.tensor(5.0 + i) before the capture and
torch.tensor(6.0 + i) between the save and the load, one addCleanup per
name, and it loops its assertIs(result.fn.__globals__[name], value) over
those load-time bindings on every loaded result before the caller rebinds
anything. The first binding is what makes a baseline discriminate: at the
module-level EPS = 1e-7, x * EPS is inside assertEqual's tolerance of
zero, so every assertion that the load-time value is what is served BEFORE a
rebind would hold against a served zero as well, which is the one thing those
assertions exist to rule out. The second is what makes the load-time value
differ from the pickled one in value and not only in identity; without it the
two are numerically equal and every mutant of the load-time merge is invisible
to all but one assertIs in the file. Binding every name is what pins the
merge's LOOP over the certified set, not just its first iteration: with for name in sorted(certified)[-1:], which binds EPS and skips AOT_LIVE_SCALE
on an artifact that has two certified names, the whole file was green while the
helper hardcoded EPS, and now fails at the helper's own assertIs,
tensor(5.) is not tensor(6.), in the cases whose artifact has two certified
names. The two baselines that case reads (load_time_eps, load_time_scale) are
taken after the helper returns for the same reason, since both names now move
under it.

test_aot_compile_module_every_certified_global_is_re_read is one of the cases
whose artifact has two certified names, and it is what pins _serve's loop
over them rather than its first iteration. With for name in self._live_global_names[:1], which re-reads the first name and leaves the rest
at their load-time values, and with a break on the first name the scope no
longer binds in place of the skip, the whole file is green except for that
case; both were run over the whole file.
test_aot_compile_module_certified_names_are_sorted_at_load pins the
sorted() at the load, which that case leans on to know that the name it
deletes (AOT_LIVE_SCALE) is the recorded set's first. An assertion on the
recorded tuple cannot pin the sort on its own: _guard_source_globals hands
back a set, so with tuple(certified) in place of tuple(sorted(certified)) a
two-element order follows string-hash randomization, and that mutant passes the
two-name case under some PYTHONHASHSEED values and fails it under others. The
new case takes the seed out of it by stubbing _guard_source_globals with the
reverse-sorted order, so the mutant lands ('EPS', 'AOT_LIVE_SCALE') whatever
the seed: it fails with String comparison failed: 'EPS' != 'AOT_LIVE_SCALE',
where this commit's tree passes. What the case asserts is the stub's own
record, that the load was handed ['EPS', 'AOT_LIVE_SCALE'] -- without which
the helper's assertion pins nothing -- and not the recorded tuple, which is the
comparison the helper already made against the names the case passes it.
test_aot_compile_module_store_global_does_not_accumulate is the BC change no
rebind by the caller is needed to see: three calls of a loaded
StoresEpsModule artifact each answer x * 6.0 -- the helper's load-time
EPS, which is what the test asserts against, not a literal -- the scope's
EPS is still the tensor it bound before them, and the bytecode's globals hold
12.0, the store the last call replayed. The same load and the same three
calls against the parent's aot_compile.py, run as a script since the parent
has no _live_global_names for the helper to assert on, answer [6.0, 12.0, 24.0] as scale factors on x (the helper's x is torch.randn(n); measured
with torch.ones(3)) and leave 48.0 in the bytecode's globals, the scope's
EPS still 6.0.

test_aot_compile_module_load_binds_a_global_off_the_graph is the only case
whose certified name never becomes a graph input, which is the shape the
load-time merge exists for: ReturnsEpsModule.forward returns EPS instead of
computing with it, so the placeholder it was lifted into is pruned as unused and
used_globals -- filled from the graph inputs' sources -- never records it. The
case asserts the name is in external_refs and in neither used_globals nor
import_sources, then that fn.__globals__ binds the scope's tensor with no
call yet made, so the merge is the only thing that can have bound it, then
calls, rebinds and calls again, which only the per-call re-read can follow. Both
binders are pinned there, on the one shape only one of them can serve.

test_aot_compile_module_global_bound_to_none_is_re_read loads that same shape
for the sentinel. A scope that binds a certified name to None BINDS it, so the
graph owes the call None, and with None as the absent-name default of either
read the two cases are indistinguishable: the binding is skipped and the graph
answers with the value the last read wrote, every guard passing on it. The
returning shape is what lets None reach the answer rather than an operator,
and the check has to be off, since None is a binding no kept TENSOR_MATCH
accepts -- dispatch refuses it on both checked passes and the opted-out last
resort is the exit that serves. Measured over the whole file, _UNBOUND = None
fails only this case, AssertionError: tensor(2.) is not None, the rebind the
previous call re-read; so does the equivalent, a scope.get(name) read with if value is not None at both sites. The rest of the file is green under both,
every certified global in it a tensor that no case binds to None.

With the parent's torch/_dynamo/aot_compile.py checked into the tree and this
test file kept, every red case is one listed above: the pre-existing ones fail
with Tensor-likes are not close!, and the ones that assert on
_live_global_names error with AttributeError: 'AOTCompiledFunction' object has no attribute '_live_global_names', the field being new here.

The deliberate details and every dispatch exit were checked by mutation over
the whole file, each mutant run as a whole-file run at this commit. Making the
_serve re-take a no-op fails nearly every case above, with Tensor-likes are not close! where the forward computes with the global and Scalars are not close! where it returns it, and the ones it leaves green are the ones that
observe no served rebind, the sort pin and the __missing__ pin, whose scope
is empty. Intersecting the recorded set with the scope at load time fails
test_aot_compile_module_absent_global_fails_guard, the same way, and
test_aot_compile_module_missing_hook_scope_is_not_asked_to_fabricate, whose
name would not be recorded at all. Clearing _live_global_names in
disable_guard_check(), i.e. letting the opt-out hold the load-time value,
fails test_aot_compile_module_opted_out_load_rebind_is_served and the
opted-out tail of test_aot_compile_module_every_certified_global_is_re_read
the same way, and test_aot_compile_module_global_bound_to_none_is_re_read at
its assertIsNone. Putting the membership test back in front of _serve's
read fails only
test_aot_compile_module_global_deleted_under_the_re_read_is_skipped, with
KeyError: 'EPS'; turning either read back into a subscript under
try/except KeyError fails only
test_aot_compile_module_missing_hook_scope_is_not_asked_to_fabricate -- at
the merge, on the caller's dict (Additional keys in the actual mapping: ['EPS']), and at _serve, on the served value (Tensor-likes are not close!,
99.0 against the serialized 5.0). Reverting each exit of
AOTCompiledModel.__call__ to the raw fn one at a time: the first pass fails
most of the cases above, including
test_aot_compile_module_second_pass_rebind_is_served at its accepted
first-pass call; the results[1:] sweep fails only
test_aot_compile_module_sweep_rebind_is_served; the re-check pass fails only
test_aot_compile_module_second_pass_rebind_is_served, at the served value;
the last resort fails
test_aot_compile_module_opted_out_load_rebind_is_served,
test_aot_compile_module_global_bound_to_none_is_re_read -- the exit that
serves its None binding -- and, at its opted-out tail,
test_aot_compile_module_every_certified_global_is_re_read. Reverting
AOTCompiledFunction.__call__ to the raw fn fails only
test_aot_compile_module_sweep_rebind_is_served, at its direct call of
results[0], with Tensor-likes are not close!; with that call left out of
the test, the same revert runs the whole file green, which is why the test
makes it.

The load-time merge is measured by the same battery. Deleting its live loop
and the extra_globals = {**(extra_globals or {}), **live} line fails the
cases above in two ways: the ones whose forward returns the global error at
the load itself, RuntimeError: Missing required external references: ['EPS'], and
the ones that go through _load_armed_module fail at its assertIs with
tensor(5.) is not tensor(6.), the pickled value where the scope's belongs.
Making the merge read the artifact's own dict
(self._artifacts.runtime_env.used_globals) instead of the guard scope fails
the same cases the same way, the absent-name default swallowing the one name
that dict does not have. Both of those were nearly invisible until the helper
bound its names a second time before the load: the one failure they produced
was an assertIs whose operands were numerically equal; restricting the merge
to the last sorted name fails the two-name cases, as above.

Every case named loads a module artifact rather than compiling one in this
process, which is what arms the re-read.

The one thing above no test reaches, the unreachable arm of _serve's
narrowing, was measured with a scratch script (not committed) that loads an
armed EpsOnly module artifact through the same keep_tensor_guards_unsafe
path: with _guard_globals patched to None, the call raises AssertionError: _live_global_names recorded without a scope here, where the is not None form
this replaces, patched over the method, served x * 9.0 -- the rebind the
previous call had re-read -- with the scope binding 11.0.

test_aot_compile_module_second_pass_rebind_is_served forced its re-check with
_install_global_probe("EPS", misses=1) until this round, and that made its
check() count order-dependent. The count holds only if the scan's check() is
the evaluation that spends the probe's one miss, and that miss is a budget EVERY
reader of the module's EPS draws on: a reader that gets there first spends it,
the scan then accepts, and the pass the case exists for never runs. The
matches_dict_tag fast path, which lets a DictGetItemGuardAccessor skip its
lookup altogether, is not a second defeater here -- it is gated on
_is_immutable_object && !_is_tensor (torch/csrc/dynamo/guards.cpp:5758) and
EPS is a tensor, so it is unreachable for this global; the shared miss budget
is the whole reason this case stubs the scan's answer instead. Measured with the
re-check exit reverted to the raw fn, which should fail the case on the served
value: five whole-file runs of that mutant tree failed it four times there and
once at check.call_count, Expected 2 but got 1. Re-arming the probe just
before the call does not fix it -- that one failure was measured with the re-arm
in place. Stubbing the scan's answer takes the count out of the dict's hands
altogether: it is now a property of the stub, the same mutant fails the case at
the served value, and the whole file is green at this commit in the loader's
order, reversed, and in a seeded shuffle. The pre-existing cases that force a
re-check through _rescued_by_the_recheck's probe are untouched here; they
assert the same check() count, assertEqual(check.call_count, 2), under the
same shared budget, and it holds there because the helper installs the probe on
AOT_BRANCH_SCALE itself and makes exactly one call with it, so nothing can
spend that miss between the install and the call it is meant for.

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

Authored with the assistance of Claude Code.

FAQ: the extra _serve frame is paid by every artifact, the ones that can
never use it included, and its measured 0.4us is a ~40% add on top of the
~1us guard eval the module dispatch sites exist to avoid -- so hoist the
if result._live_global_names test to the call sites and keep the fast path
frame-free.

The premise about the test is right: it is call-invariant, so this is a cost
question and not a correctness one. _live_global_names has exactly one
assignment in the tree, in __post_init__, and the field is init=False, so
whether it is empty is fixed for an instance's lifetime; what changes per call
is what the loop in _serve READS out of the scope, which is the point of the
commit, and the hoist moves the gate, not the read.

The arithmetic does not hold, because 0.4us is the ARMED cost, not the
frame. The dispatch comment prices what the sites pay on an armed artifact
with one certified name -- the frame plus a scope read and a dict write for
that name -- and that re-read is the fix itself, which no gate can remove on
an armed artifact. What a per-site gate could save is the frame alone, on the
artifacts that are not armed, and that frame was timed paired: raw, _serve
and hoisted inside ONE loop iteration so host drift cancels, 25 rounds of
20000 calls of a loaded one-op module under the default filter (not armed).
Medians of the per-round figures: raw 6.677us, _serve 6.892us, hoisted
6.664us, and the paired _serve-minus-raw difference 0.240us as a median,
0.235us as a mean (min 0.124, max 0.519); a second run of the same
script read 0.252us and 0.282us. That is ~27% of the 0.879us the
check() it follows costs and 3.6% of the raw call of a ONE-op eager graph --
the floor, since any real graph shrinks the share further. Armed with one
name, the same paired method read 0.325us and 0.373us as medians on those
two runs, which is the figure the comment rounds to 0.4us and sets against
that check() cost, which the comment states as ~0.85us -- an earlier
figure for the same eval, not a rounding of the 0.879us measured here.

What the frame buys is that _serve is the only caller of the raw fn. The
hoist spreads the gate over five sites (__call__ and the four exits of
AOTCompiledModel.__call__), and a site that gets it wrong serves the
load-time value on an armed artifact only -- silent wrong numerics, the exact
bug this commit fixes, and invisible to every test whose artifact is not armed,
which is most of the file. The commit's own history shows the shape of that
failure: with three exits on the raw fn, the whole file stayed green except
for the tests written to pin them. The frame-free variant that keeps one call
site, binding self._serve to self.fn in __post_init__ when the set is
empty, is worse: it setattrs over a method on the instance, which the fn
field comment says this class deliberately does not do.

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

🤖 Generated with Claude Code

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

[ghstack-poisoned]