Repository navigation
[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
Closed
[aot_compile] Re-read a guarded global before every call instead of serving the load-time value#196897bobrenjc93 wants to merge 49 commits into
bobrenjc93 wants to merge 49 commits into
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 keptTENSOR_MATCHcertifies 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, andtest_aot_compile_module_reload_reads_the_live_globalpinned that as intended behaviour. This commit addsAOTCompiledFunction._serve, which re-takes the certified names out of_guard_globalsintofn.__globals__immediately before running the graph, and routes__call__and all four exits ofAOTCompiledModel.__call__through it, so_serveis the only caller of the rawfnand what a guard just certified is what the graph reads. Only a global a kept guard's own bareGlobalSourcenames is re-read (_live_global_names, recorded under the module load path's_bytecode_reads_guard_scope and _has_global_guardsgate and not intersected with the scope), the load-time merge stays because_check_external_refsneeds a certified global the graph never lifted bound before any call, and each read is onescope.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 thatSTORE_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 servesAOTCompiledFunction.__call__and all four exits ofAOTCompiledModel.__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 toload_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
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_globalpinned that as intended behaviour ("A rebind after the load: the call still answers with the load-time value"), andAOTCompiledModel.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.
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, anddisable_guard_check()flips one bool without disarming the re-read.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.test_aot_compile_module_store_global_does_not_accumulatepins 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, andtest_load_compiled_function_f_globals_accepted_rebind_is_not_usedstill 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'saot_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 intoextra_globals, i.e. into the dictforward_callablebuilds, so the live read happened exactly once, at load.__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_functionpasses one dict as bothf_globalsandguard_globalsand 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_callableruns_check_external_refsat load, before_servecan ever run, and a certified global the bytecode reads but the graph never lifted -- a global the forward mutates or returns -- is inexternal_refsbut in neitherimport_sourcesnorused_globals, the only dictsforward_callablebuildsfn.__globals__from, so the merge is what binds it. (The serializedoutput_graph.global_scopedoes carry it, being filtered to the kept guards' roots, butforward_callablenever reads that dict.) The comment on the merge says so, andtest_aot_compile_module_load_binds_a_global_off_the_graphpins that shape on its RETURNS half:A forward that returns
EPSrather than computing with it has the placeholder it was lifted into pruned as unused, soused_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
_serveAOTCompiledModel.__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 overresults[1:], a re-check pass that re-runs everycheck()(one exit ofcheck()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 viadisable_guard_check().All four call
_serve, which is thereby the only caller of the rawfn, and_serve's docstring says so. That also rules out a state the re-read could otherwise have introduced:_serve's write intofn.__globals__persists between calls, so a pass that ran the rawfnafter 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_servedpins exactly that:The call at
EPS = 2.0, on a LOADED artifact, the only kind the re-read is armed for, has to runcheck()exactly twice and servex * 2.0. The stub replaces this case's earlier use of the file's_install_global_probeidiom, for a measured reason the Test Plan gives.test_aot_compile_module_sweep_rebind_is_servedpins theresults[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'sfn.__globals__then holds the rebind and the first's still the load-time value, both asserted. The same test then callsresults[0]directly, throughAOTCompiledFunction.__call__, with the(3,)input its guards accept, and that call has to compute with the rebind and leave it in the first result'sfn.__globals__:__call__is the one_servesite module dispatch never reaches, and it is public throughcompiled_results.The dispatch comment records why the
_serveframe 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 contractguard_globalsexists 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_globalskeeps the bareGlobalSources -- 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_livepins that on the module path, and_serve's andAOTCompiledModel.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_servedpins the certified set from both sides withTwoGlobalsModule, whose forward readsEPS, a plain tensor whoseTENSOR_MATCHis kept, andAOT_UNGUARDED_PARAM, annn.Parameterwhose 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 aSTORE_GLOBALinto 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 isglobal P; y = x * EPS + P; P = P * 2, withEPSa plain tensor (certified) andPa Parameter (its guard dropped by the filter, so not in_live_global_names):fn.__globals__["P"]after the callPx * 6.0 + 1.021.0x * 6.0 + 2.041.0x * 6.0 + 4.081.0test_aot_compile_module_store_global_does_not_accumulatepins the certified half on the module load path: three calls of a loadedStoresEpsModuleartifact answer alike, the scope'sEPSis 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.
test_aot_compile_module_opted_out_load_rebind_is_servedasserts the no-match report'sexpected 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_namesindisable_guard_check()was tried as a mutation and refuted by that test.One read:
scope.get(name, _UNBOUND)_serve's re-read is onescope.get(name, _UNBOUND): neither a membership test followed by a read, nor a subscript undertry/except KeyError.Against the membership test, the scope is live, so a
delof the name landing between the test and the read would let a bareKeyErrorout 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_skippedpins that with a scope that answers the membership test and raises from__getitem__: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: acollections.defaultdictis 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_fabricatepins both reads against one:The
defaultdictis 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.getneither dispatches through an overridden__getitem__nor pays the raise, so it keeps the single lookup thedelwindow argues for, and the module-level_UNBOUNDsentinel is what separates a global bound toNonefrom an absent one, whichtest_aot_compile_module_global_bound_to_none_is_re_readpins (withNoneas 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 thedelwindow is pinned at the_servesite 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
AssertionErrornarrowing_servenarrows_guard_globalsthe way_live_guard_managernarrowsguard_manager, with anAssertionErrorrather than a fall-through to the rawfn. The arm is unreachable:_live_global_nameshas its one assignment in__post_init__, underif 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_globalspatched toNoneon an armed result, theis not Noneform 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: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_namesfield comment says what arms the set:_bytecode_reads_guard_scope, and not a supplied scope as such, sinceload_compiled_functionsupplies one asguard_globalsand is not armed. That only the module load path sets that flag is the adjacent_bytecode_reads_guard_scopecomment's own line, rewritten here to say the certified names are picked in again by_servebefore every call.The
AOTCompiledModel.deserializedocstring 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 throughdisable_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 exittest_aot_compile_module_opted_out_load_rebind_is_servedpins, 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 artifactdeserializereturns has no globals of its own: it builds oneAOTCompiledFunctionper serialized result andforward_callablegives each a freshf_globals, which is why two threads whose calls land on DIFFERENT results do not race, andtest_aot_compile_module_sweep_rebind_is_servedasserts exactly that shape -- the rebind inresults[1]'s globals and the load-time value still inresults[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:_serveis private.The
bytecode_reads_guard_scopeparagraph ofAOTCompiledFunction.deserializesays 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 servesx * 2.0after an accepted call re-read3.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_oncenow says the scan calls the matching result's_serve, since the rawfnfield it named is no longer what any dispatch exit calls.test_load_rederives_a_builtins_key_bound_to_its_own_snapshotsays what keeps the builtins key out of the bytecode's globals now that thename != builtins_keytest 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 bareGlobalSourcealone.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 newcertifiedline as- {builtins_key}, where it can never remove anything:load_builtin_from_argvalis the one site in the tree that mints a source under this key, alwaysDictGetItemSource(GlobalSource(key), name)and only for a callable builtin, so a chained source is the only way the key is reached and_guard_source_globalsdrops 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 intoglobal_scopewhether 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.
TwoGlobalsModuleis the one that moves: it was a class local totest_aot_compile_module_only_the_guarded_global_is_read_liveand the newtest_aot_compile_module_rebind_after_load_is_servedloads it too.AOT_UNGUARDED_PARAM's initial binding moves up beside it; the NAME was already a module-level global at the parent, declaredglobal EPS, AOT_UNGUARDED_PARAMin 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, withAOT_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, andReturnsEpsModule, 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 anaddCleanupforAOT_UNGUARDED_PARAM, which fixes a leak the parent already had rather than one the move introduces: the parent rebound that global under its ownglobalstatement and restored onlyEPS, so the rebind was file-visible and unrestored there too -- unnoticed, not invisible.Review order
Review
_servefirst, then what__post_init__records for it,__call__and the four exits ofAOTCompiledModel.__call__with the dispatch comment, then the two prose passages that described the old snapshot semantics (theAOTCompiledModel.deserializedocstring and thebytecode_reads_guard_scopeparagraph ofAOTCompiledFunction.deserialize), then the tests, starting with_load_armed_module, the loader all but one new case goes through.Test Plan:
The new cases, and the existing cases that pinned the old behaviour:
The existing case that pins the sub-path exclusion the docstrings describe:
test_aot_compile_module_rebind_after_load_is_servedrebinds two globals underkeep_tensor_guards_unsafe: a plain tensor whoseTENSOR_MATCHis kept, andan
nn.Parameterwhose guard the filter drops. The call has to follow the newtensor 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 resultbefore 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, sincewhat it needs as the guard scope is a
collections.defaultdictand the helperalways 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 andtorch.tensor(6.0 + i)between the save and the load, oneaddCleanuppername, and it loops its
assertIs(result.fn.__globals__[name], value)overthose 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 * EPSis insideassertEqual's tolerance ofzero, 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
assertIsin the file. Binding every name is what pins themerge's LOOP over the certified set, not just its first iteration: with
for name in sorted(certified)[-1:], which bindsEPSand skipsAOT_LIVE_SCALEon an artifact that has two certified names, the whole file was green while the
helper hardcoded
EPS, and now fails at the helper's ownassertIs,tensor(5.) is not tensor(6.), in the cases whose artifact has two certifiednames. The two baselines that case reads (
load_time_eps, load_time_scale) aretaken after the helper returns for the same reason, since both names now move
under it.
test_aot_compile_module_every_certified_global_is_re_readis one of the caseswhose artifact has two certified names, and it is what pins
_serve's loopover them rather than its first iteration. With
for name in self._live_global_names[:1], which re-reads the first name and leaves the restat their load-time values, and with a
breakon the first name the scope nolonger 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_loadpins thesorted()at the load, which that case leans on to know that the name itdeletes (
AOT_LIVE_SCALE) is the recorded set's first. An assertion on therecorded tuple cannot pin the sort on its own:
_guard_source_globalshandsback a set, so with
tuple(certified)in place oftuple(sorted(certified))atwo-element order follows string-hash randomization, and that mutant passes the
two-name case under some
PYTHONHASHSEEDvalues and fails it under others. Thenew case takes the seed out of it by stubbing
_guard_source_globalswith thereverse-sorted order, so the mutant lands
('EPS', 'AOT_LIVE_SCALE')whateverthe 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 whichthe helper's assertion pins nothing -- and not the recorded tuple, which is the
comparison the helper already made against the
namesthe case passes it.test_aot_compile_module_store_global_does_not_accumulateis the BC change norebind by the caller is needed to see: three calls of a loaded
StoresEpsModuleartifact each answerx * 6.0-- the helper's load-timeEPS, which is what the test asserts against, not a literal -- the scope'sEPSis still the tensor it bound before them, and the bytecode's globals hold12.0, the store the last call replayed. The same load and the same threecalls against the parent's
aot_compile.py, run as a script since the parenthas no
_live_global_namesfor the helper to assert on, answer[6.0, 12.0, 24.0]as scale factors onx(the helper'sxistorch.randn(n); measuredwith
torch.ones(3)) and leave48.0in the bytecode's globals, the scope'sEPSstill6.0.test_aot_compile_module_load_binds_a_global_off_the_graphis the only casewhose certified name never becomes a graph input, which is the shape the
load-time merge exists for:
ReturnsEpsModule.forwardreturnsEPSinstead ofcomputing 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. Thecase asserts the name is in
external_refsand in neitherused_globalsnorimport_sources, then thatfn.__globals__binds the scope's tensor with nocall 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_readloads that same shapefor the sentinel. A scope that binds a certified name to
NoneBINDS it, so thegraph owes the call
None, and withNoneas the absent-name default of eitherread 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
Nonereach the answer rather than an operator,and the check has to be off, since
Noneis a binding no keptTENSOR_MATCHaccepts -- dispatch refuses it on both checked passes and the opted-out last
resort is the exit that serves. Measured over the whole file,
_UNBOUND = Nonefails only this case,
AssertionError: tensor(2.) is not None, the rebind theprevious call re-read; so does the equivalent, a
scope.get(name)read withif value is not Noneat 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.pychecked into the tree and thistest 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_nameserror withAttributeError: '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
_servere-take a no-op fails nearly every case above, withTensor-likes are not close!where the forward computes with the global andScalars are not close!where it returns it, and the ones it leaves green are the ones thatobserve no served rebind, the sort pin and the
__missing__pin, whose scopeis empty. Intersecting the recorded set with the scope at load time fails
test_aot_compile_module_absent_global_fails_guard, the same way, andtest_aot_compile_module_missing_hook_scope_is_not_asked_to_fabricate, whosename would not be recorded at all. Clearing
_live_global_namesindisable_guard_check(), i.e. letting the opt-out hold the load-time value,fails
test_aot_compile_module_opted_out_load_rebind_is_servedand theopted-out tail of
test_aot_compile_module_every_certified_global_is_re_readthe same way, and
test_aot_compile_module_global_bound_to_none_is_re_readatits
assertIsNone. Putting the membership test back in front of_serve'sread fails only
test_aot_compile_module_global_deleted_under_the_re_read_is_skipped, withKeyError: 'EPS'; turning either read back into a subscript undertry/except KeyErrorfails onlytest_aot_compile_module_missing_hook_scope_is_not_asked_to_fabricate-- atthe 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.0against the serialized5.0). Reverting each exit ofAOTCompiledModel.__call__to the rawfnone at a time: the first pass failsmost of the cases above, including
test_aot_compile_module_second_pass_rebind_is_servedat its acceptedfirst-pass call; the
results[1:]sweep fails onlytest_aot_compile_module_sweep_rebind_is_served; the re-check pass fails onlytest_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 thatserves its
Nonebinding -- and, at its opted-out tail,test_aot_compile_module_every_certified_global_is_re_read. RevertingAOTCompiledFunction.__call__to the rawfnfails onlytest_aot_compile_module_sweep_rebind_is_served, at its direct call ofresults[0], withTensor-likes are not close!; with that call left out ofthe 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
liveloopand the
extra_globals = {**(extra_globals or {}), **live}line fails thecases above in two ways: the ones whose forward returns the global error at
the load itself,
RuntimeError: Missing required external references: ['EPS'], andthe ones that go through
_load_armed_modulefail at itsassertIswithtensor(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 failsthe 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
assertIswhose operands were numerically equal; restricting the mergeto 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'snarrowing, was measured with a scratch script (not committed) that loads an
armed
EpsOnlymodule artifact through the samekeep_tensor_guards_unsafepath: with
_guard_globalspatched toNone, the call raisesAssertionError: _live_global_names recorded without a scopehere, where theis not Noneformthis replaces, patched over the method, served
x * 9.0-- the rebind theprevious call had re-read -- with the scope binding
11.0.test_aot_compile_module_second_pass_rebind_is_servedforced its re-check with_install_global_probe("EPS", misses=1)until this round, and that made itscheck()count order-dependent. The count holds only if the scan'scheck()isthe evaluation that spends the probe's one miss, and that miss is a budget EVERY
reader of the module's
EPSdraws 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_tagfast path, which lets aDictGetItemGuardAccessorskip itslookup altogether, is not a second defeater here -- it is gated on
_is_immutable_object && !_is_tensor(torch/csrc/dynamo/guards.cpp:5758) andEPSis a tensor, so it is unreachable for this global; the shared miss budgetis 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 servedvalue: 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 justbefore 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; theyassert the same
check()count,assertEqual(check.call_count, 2), under thesame shared budget, and it holds there because the helper installs the probe on
AOT_BRANCH_SCALEitself and makes exactly one call with it, so nothing canspend that miss between the install and the call it is meant for.
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
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98