Skip to content

[aot_compile] Make module dispatch scan every compiled result before falling through - #196929

Closed
bobrenjc93 wants to merge 16 commits into
gh/bobrenjc93/1189/basefrom
gh/bobrenjc93/1189/head
Closed

bobrenjc93 wants to merge 16 commits into
gh/bobrenjc93/1189/basefrom
gh/bobrenjc93/1189/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

AOTCompiledModel.__call__ is the dispatcher over the several graphs a module
was AOT-compiled for, one AOTCompiledFunction per ModelInput in
compiled_results. The parent's loop was four lines:

def __call__(self, *args, **kwargs):
    for result in self.compiled_results:
        if result.guard_check(self.model, *args, **kwargs):
            return result(self.model, *args, **kwargs)        # result() re-runs the guards it just passed
    return self.compiled_results[0](self.model, *args, **kwargs)  # fall through and let [0] raise

Whether the caller saw an error at all turned on the order of the list. The
fall-through re-raised only because compiled_results[0] still had its guard
check enabled; had that one result opted out through disable_guard_check()
it would have run instead, so the answer was an accident of position rather
than a decision. Measured on a two-input ScaleModule (float32 and float64)
called with float16:

PARENT [enabled, enabled]  : RuntimeError: GuardManager check failed ...
PARENT [enabled, opted_out]: RuntimeError: GuardManager check failed ...
PARENT [opted_out, enabled]: SERVED                          <- position decided this

A match was not cheap either: result() enters AOTCompiledFunction.__call__,
which binds the call and runs guard_check again before running fn, so a
matching tree was bound and evaluated twice per call.

Three explicit stages ahead of the fall-through

def __call__(self, *args, **kwargs):
    results = tuple(self.compiled_results)                          # read the public list ONCE
    shared = results[0].prepare_f_locals(self.model, *args, **kwargs) if self._binds_alike(results) else None
    bound = []
    for result in results:                                          # 1. scan for a match
        f_locals = shared if shared is not None else result.prepare_f_locals(self.model, *args, **kwargs)
        if shared is None: bound.append(f_locals)
        if result._live_guard_manager().check(f_locals):
            return result.fn(self.model, *args, **kwargs)           # guards already passed: call fn directly
    for i, result in enumerate(results):                            # 2. re-check every result
        if result._live_guard_manager().check(shared if shared is not None else bound[i]):
            return result.fn(self.model, *args, **kwargs)
    for result in results:                                          # 3. 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: raises

Only a call none of the three stages serves reaches the parent's fall-through
into compiled_results[0], which by then is a result with its guard check
enabled, so it raises the same GuardManager check failed error the parent
raised; a report that names every compiled input replaces that fall-through in
the next commit.

The scan calls fn directly. One evaluation of a matching tree per call,
where result() made two, which is what
test_module_dispatch_evaluates_a_matching_tree_once measures. 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.

Honouring the opt-out from any position is the one answer this commit
changes.
With compiled_results = [enabled, opted_out] and a call neither
artifact guards, the parent raises and this commit serves compiled_results[1]:

HEAD   [enabled, enabled]  : RuntimeError: GuardManager check failed ...
HEAD   [enabled, opted_out]: SERVED
HEAD   [opted_out, enabled]: SERVED

So one opted-out result now replaces the error for the whole model, where
before only compiled_results[0] could. That is what disable_guard_check()
is for: on the function path AOTCompiledFunction.__call__ short-circuits on
the flag and runs the graph whatever it is called with, so the alternative,
raising anyway, would leave the flag with no effect at all on a model, since a
scan that serves an opted-out result whose guards pass is what an enabled result
gets too. It would also refuse the [opted_out, enabled] call the parent
serves today. test_module_dispatch_serves_an_opted_out_result_from_any_position
pins it (deleting the last-resort loop raises GuardManager check failed).

The doc bullet for disable_guard_check() is where a reader meets the flag, so
it now says the compiled function then runs whatever it is called with. The
module dispatch's own answer lives in a new Developer notes section at the end
of the user guide, headed by the bold private/unstable warning, since a private
multi-input path does not belong beside the public quick start; the bullet is
scoped to the function path and cross-references that section. The section
names what the path needs: the list is of torch._dynamo.aot_compile.ModelInput,
which nothing re-exports, torch._dynamo.config.enable_aot_compile, on by
default, which only a caller who turned it off has to restore, and
model.forward.compiled_results[i].disable_guard_check(), the only route to
the flag from a module. AOTCompiledModel is out of it: _aot_compile returns
None and assigns self.forward, so a reader never holds one.

The re-check is what keeps the last resort last

check() can reject from the recursive dict-tag fast path without ever running
the tree, so a rejection in the scan is not yet an answer about this call. The
node that rejected and its ancestors have their _disable_dict_tag_matching
set, which nothing resets (guards.cpp:4270 is the member's = false default
initializer; every other write sets it true), so a second check()
re-evaluates those in full. The flag is a per-GuardManager member, so that is
not a whole-tree re-evaluation: a sibling tag-safe root the first pass never
reached stays armed and can still answer from its own fast path. That is
exactly the rescue 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). A genuine
mismatch pays almost nothing for the second pass: such a tree still
short-circuits at its first failing guard.

Ordering matters more than it looks. With the last resort 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 fall-through got right,
because the fall-through re-checked before it gave up.
test_module_dispatch_rechecks_before_honouring_an_opt_out pins the position
(moving the loop ahead serves [0]'s x * 2 and fails with Mismatched elements: 9 / 9); #196824 pins the same loop from GlobalConfigModule's side.
The re-check covers opted-out results too, 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), and
the last resort does not stand in for the re-check it would skip, since it
serves the FIRST opted-out result:

# both results opted out; [1]'s tree genuinely accepts this call, [0]'s genuinely does not
# scan:      [0] rejects; [1] falsely rejects from the dict-tag fast path
# no re-check of opted-out results -> last resort serves [0]: a graph whose guards fail

test_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts opts
both results out and misses [1]'s global once; restoring the re-check's
opt-out skip serves [0]'s x * 2 and fails it with Mismatched elements: 9 / 9. That costs one extra check() per opted-out result on the no-scan-match
path only.

Two alternatives to that second check() were measured and rejected. Running
check_verbose as the second pass, so that its answer could double as the
failure's explanation, makes the shape it was meant to help worse: an opted-out
result makes the guards fail on every call by construction, so dispatch ends at
the last resort and the raise is never reached, and check_verbose is 1.76x a
check() per tree. Gating the stage on
config.use_recursive_dict_tags_for_guards cannot be made sound at this call
site either, because whether a tree is armed is decided once, in
GuardManagerWrapper.finalize(): a manager built under the config still
reports its tag-safe nodes after the patch exits, and one built without it
reports none however the flag reads at call time. There is no per-manager query
for "has an armed tag-safe root", only the per-node is_tag_safe_root, so a
correct gate would need the tree walk the gate exists to avoid.

One bind per call, decided safely against a public list

Binding dominates the per-call cost. Measured on this machine,
prepare_f_locals (inspect.Signature.bind plus apply_defaults) costs
2.563us against 1.000us for a whole check() and 1.758us for a
check_verbose(), so paying the bind once per call rather than once per stage
is worth more than removing a stage would be. 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. End to end on
the same fixture, dispatch that finds a match costs 23.3us against the parent's
29.3us at one, two and four compiled inputs, since the parent pays a second
bind and a second check() inside result(). With one bind per call, a match
at the fourth of four inputs costs 20.1us against 33.5us with one bind per
result (17.1us at the first, unchanged);
test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature counts
prepare_f_locals on that model for a call matched at [3] and expects one;
binding per result again fails it with Absolute difference: 3. The
fall-through this commit keeps is the one path that still binds again, twice,
inside AOTCompiledFunction.__call__; the next commit's report reuses the
dispatch's binding instead.

Deciding "binds alike" without inspect.Signature equality.
AOTCompiledModel._binds_alike() decides through _binding_key, which
compares exactly what prepare_f_locals reads, with defaults and cells by
identity:

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

It deliberately does not compare Signatures: 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):

class M(torch.nn.Module):
    def forward(self, x, mask=torch.ones(3)):
        return x * mask
# Signature compare -> 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. The shared bind is
hoisted ahead of the scan, so the two regimes read as one bind per call or one
per result rather than as an index test inside the loop, and 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. Only that
regime records a binding per result for the re-check; the shared one is reused
as is, so a matching call allocates nothing for a pass it never reaches.

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.

Re-deciding when the list changes. compiled_results is a public list the
docs teach callers to index into, so _binds_alike decides again whenever the
tuple differs by length or identity from the contents it last judged. 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:

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

The staleness check is by identity, not == (the dataclass __eq__ reaches
the Signature compare above), and costs 0.27us for four results against
0.81us for a check(); snapshots by id were measured at 0.89us and rejected.
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 the silent shape above.

The verdict and the contents it was reached over are one field.
_binding_verdict = (results, shared), so a call reads both with one attribute
load and the re-decision publishes both with one store. Two fields cannot be
made consistent by store order: storing the contents first let a second thread
identity-match the freshly stored contents and return the previous list's
verdict, a stale True that binds an appended result from compiled_results[0]'s
default; storing the verdict first left the mirror, a caller that had
snapshotted the list before a pop, matched the contents still published, and
took the True just decided about the shorter list, so [1] was bound from
[0]'s default and served 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, before
it publishes anything, 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; with the pair in two fields it fails with RuntimeError not raised, [1] having been served. A window between the two halves of the
publication is the one thing no test can pin, because there is no longer one:
whatever the first store publishes is all a reader can ever see, which is what
the second test asserts. Nothing decides eagerly: the field default is the
verdict over no results, so a fresh model decides on its first call, and the
tests read _binds_alike(tuple(model.compiled_results)) rather than the field.

The list is read once per call. __call__ snapshots results = tuple(self.compiled_results) before anything else (26ns for four results),
_binds_alike takes that snapshot rather than reading the list itself, and
every stage iterates it. Two reads would let an append or a replacement land
between them, so the shared bind could come from one list and the verdict about
another (a result replaced mid-call judged on the binding decided over its
predecessor) and the re-check's bound[i] could index a binding the scan never
made. test_module_dispatch_judges_only_the_results_a_call_began_with makes
[0]'s check() splice in a [1] compiled for mode=1 that defaults mode
to 0: a scan over the live list reaches it on the same call, judges it on
[0]'s binding where mode reads 1, and serves x * 3 for a call eager
answers x * 2; with the snapshot that call raises and the next one decides
over both.

Two smaller changes

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.

A call the signature cannot bind is left alone, so 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 bind is the first thing the scan does,
ahead of every guard, which is what preserves that. The test for it sits with
#196826, the first commit where the placement of the guard check's try could
break it.

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_rechecks_before_honouring_an_opt_out
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 -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_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_judges_only_the_results_a_call_began_with
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_binds_a_call_once_for_results_sharing_a_signature
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_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

The full file runs 168 tests and passes (6 skipped). The mid-call test fails
without the snapshot with AssertionError: RuntimeError not raised, the
spliced-in result having been served. The old-contents interleaving test fails
the same way on the two-field layout in verdict-first order, [1] having been
served x * 3 on [0]'s binding; reading bound[i] in the re-check
regardless of the shared bind fails five dispatch tests with IndexError: list index out of range, so the shared path does reach the re-check with no
per-result binding recorded. All five new tests fail at the parent: the two
counted-lookup tests on their counts (Absolute difference: 1; GuardManager check failed raised where [1] should have been served), the two binding
tests on the missing _binds_alike, and the opted-out re-check test with
Mismatched elements: 9 / 9.

The four tests added for _binding_key and the last resort also fail at the
parent: the two binding tests on the missing _binds_alike, the
any-position test with GuardManager check failed, the re-check-first test
with Mismatched elements: 9 / 9. Restoring Signature equality in
_binding_key fails 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. 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.

The two rebinding tests fail without the re-decision: the appended one with
GuardManager check failed (bound from [0], [1]'s mode == 0 guard
misses), the replaced one with RuntimeError not raised ([1] served x * 3
on [0]'s binding); dropping the identity term and keeping only the length
check passes the first and still fails the second.

The three counted-lookup tests were also run under
torch._dynamo.config.patch(use_recursive_dict_tags_for_guards=True) to
confirm the counts do not depend on the flag. Deleting the re-check loop as a
mutation control fails test_module_dispatch_serves_a_call_the_guard_tree_accepts
(the fall-through raises GuardManager check failed) and
test_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts
(Mismatched elements: 9 / 9) while the other three stay green; calling
result() in the scan instead of result.fn fails
test_module_dispatch_evaluates_a_matching_tree_once with Absolute difference: 1.

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: check()'s second pass is not a full evaluation of the tree, so a call
the graph would answer correctly can reach the "rejected this call twice and then
accepted it here" report. Why not serve when check_verbose accepts, or make the
second pass check_verbose?

Both are real improvements and both change a decision this stack pins, so they
belong in their own commit with their own tests rather than inside the commit
that introduces the dispatch. _disable_dict_tag_matching is a
per-GuardManager member (guards.cpp:4270), set on the node that rejected and
on its ancestors (:3860), so a second check() re-evaluates those in full
while a sibling tag-safe root the first pass never reached stays armed and can
still answer from its fast path -- measured, including the shape where that armed
sibling feeds a stale recorded tensor into the shared NO_TENSOR_ALIASING guard
and a live node then fails. check_verbose never takes the fast path, so its
accept can be a genuine full-evaluation accept, which is why the divergence
exists at all. But serving on it reverses
test_no_match_message_when_a_guard_answers_inconsistently, which exists for
this branch: a probe whose __eq__ misses twice makes the tree reject twice and
accept on the third evaluation, and the test asserts the call RAISES and that the
probe was compared exactly three times. The code cannot tell that case (a
side-effecting __eq__, where the third answer is no more trustworthy than the
first two) from the tag-safe one (where it is), so serving would trade a reported
non-match for a silent serve in the case the test was written for. Making pass 2
check_verbose is the better of the two -- genuinely full, fixes the whole
class, and costs two guard evaluations instead of three -- but it moves the
evaluation counts three tests assert and changes what the report is allowed to
reuse. The report line itself is accurate as written ("rejected this call twice
and then accepted it here" is exactly what happened), and the whole scenario
needs torch._dynamo.config.use_recursive_dict_tags_for_guards=True (False by
default here) plus a mutation the dict tags cannot see, so nothing is live under
default config.

FAQ: The recursive dict-tag fast path the second check() pass is justified
by is off by default in OSS. Why not gate that pass on
use_recursive_dict_tags_for_guards, or drop it?

Both were measured. The gate cannot be written correctly at this call site:
whether a tree is armed is decided once, in GuardManagerWrapper.finalize(),
which reads the config (AND-ed with a justknob) at BUILD time. A manager built
under config.patch(use_recursive_dict_tags_for_guards=True) still reports 6
tag-safe nodes after the patch exits, and one built with the flag False
reports 0 however the flag reads later -- so a call-time read of the config
does not describe the manager it would be gating. There is no per-manager
query for "has an armed tag-safe root", only the per-node is_tag_safe_root,
so a sound gate would have to walk the tree the gate exists to avoid.

Dropping the pass is not free either: it is what keeps the opted-out last
resort last, which #196824's
test_aot_compile_module_opted_out_result_waits_for_the_full_recheck pins
under DEFAULT config. Deleting the loop as a mutation control fails that suite
(1 failure, 1 error), so the pass is load-bearing today, flag or no flag.

The review's cost arithmetic for its own named shape does not reproduce. For
[enabled_that_never_matches, opted_out] the OLD code was measured at 3
check()s, 1 check_verbose() and 4 binds, and it RAISED rather than serving
compiled_results[0] -- the fall-through re-entered a raising
AOTCompiledFunction.__call__. The new dispatch serves that shape with 3
check()s, no check_verbose and 1 bind, i.e. strictly cheaper. The only shape
with a real regression is [opted_out, enabled]: 2 checks / 2 binds before, 3
checks / 1 bind now, so the residual is one check() less one bind, measured at
1.000us against 2.563us for a single prepare_f_locals. That is why the fix
taken here is hoisting the bind (now paid once per call for the whole dispatch
and the report, since every result of a module artifact binds identically; a
hand-assembled model whose results disagree binds per result, pinned by
test_module_dispatch_binds_per_result_when_signatures_differ) rather than
removing a guard evaluation.

FAQ: Why is the second pass still check() rather than check_verbose(),
now that the costs have been measured?

Because the measurement points the other way for the shape the review was
worried about. check_verbose() costs 1.758us against 1.000us for check()
on the same tree. In the steady state of a model carrying an opted-out result
the guards fail on every call by construction, so dispatch ends at the last
resort and the report never runs -- there is no later check_verbose for a
second-pass check_verbose to replace, and the pass simply gets 1.76x more
expensive. (The earlier FAQ entry's "costs two guard evaluations instead of
three" is about the report path, where the report's own check_verbose would
indeed be the one saved; it does not hold for the opted-out path, which is the
one the second pass exists for.)

FAQ: No test enables use_recursive_dict_tags_for_guards, so the mechanism
the dispatch is designed around is never exercised with it on. Why not?

Because merely flipping the flag would be a vacuous test, and was measured to
be. For the actual fixture these tests use, building the guard manager under
config.patch(use_recursive_dict_tags_for_guards=True) yields 6 tag-safe
NODES but 0 tag-safe ROOTS, and guards.cpp:3797 requires a root before the
fast path is entered at all -- so the flag alone changes nothing observable.
Reaching the reject-without-running-the-tree branch at guards.cpp:3810 needs
four things at once: the config, the justknob, a surviving
NO_TENSOR_ALIASING guard, and a tensor pointer recorded by one evaluation
and stale by the next. Constructing that is a guard-tree test, not an AOT
dispatch test, and it belongs with the C++ mechanism rather than in
test_aot_compile.py. What is testable here was tested: all three
counted-evaluation tests were re-run under
@torch._dynamo.config.patch(use_recursive_dict_tags_for_guards=True) and are
green with the same counts, so the numbers they assert do not silently depend
on the flag being off.
The four tests added since (the any-position serve, the re-check-before-opt-out
ordering and the two shared-binding tests) were run under the same patch and
are green.

FAQ: CLAUDE.md says minimize comments, and the comments here still run close
to 1:1 with code. Why not cut further?

The two blocks the review named, twice, are now one and two lines: the scan
comment says only that guard evaluation ignores _guard_check_enabled, and
the re-check comment that a fast-path rejection is re-evaluated in full,
opted-out results included; the commit message carries the rest. What remains
is the part a reader cannot infer locally and that this stack has already
regressed on twice: why the first scan must not skip opted-out results (a real
match among them would otherwise be served only after every other tree was
checked twice, and behind a later enabled match the scan's index order would
have put second), why the bind is hoisted (a measured 2.563us against 1.000us,
so the count of binds matters more than the count of checks), and why a
rejection from check() is not yet an answer. The test comments were left as
they are: each one records a measurement that the assertion beneath it would
otherwise look arbitrary without -- an exact evaluation count, or the CPython
dict-lookup detail that keeps the cleanup off that count.

FAQ: Module dispatch now reads AOTCompiledFunction's private members
instead of going through its __call__. Why not add a "guards already passed,
invoke" method?

Because the two callers want different things and a shared wrapper would have
to be told which. Dispatch needs the guard answer and the invocation as
separate steps: it evaluates guards for every result before invoking any of
them, it must evaluate them even for a result that opted out, and the report
then needs the same binding a third time. A single _serve() that re-checked
would reintroduce exactly the double evaluation the counted-lookup test pins,
and one that did not check would be a method whose contract is "trust the
caller", which is no more explicit than the field read it replaces. The one
repeated fragment -- narrowing _artifacts.guard_manager away from None --
did become a method, _live_guard_manager(), so the three call sites share
the assertion and its reason instead of restating it.

FAQ: Why does dispatch serve an opted-out result when nothing matched, when
this PR's own description opens by calling that a bug?
Measured against the
parent (#196821) on a two-input ScaleModule (float32 and float64) called
with float16, with the parent's __call__ body patched in: [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 description now says that in those terms rather than calling the
serve a bug: the defect it named 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. The widening and its cost to
the report are stated in the commit message and in the disable_guard_check()
doc bullet.

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.
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: Why re-evaluate every enabled result's full guard tree when, under
the default config, a stage-1 rejection is already a complete answer?

Confirmed on the premise and declined on the conclusion.
use_recursive_dict_tags_for_guards is False at config.py:497, and
GuardManagerWrapper.finalize() (guards.py:396-401) calls
find_tag_safe_roots() only under it, which is the only thing that sets
_is_tag_safe_root (guards.cpp:3514, read at :3797), so with the
default config check() never takes the fast path and the re-check finds
nothing new. What it costs is confined to the path that raises. Measured end
to end on that fixture, dispatch that finds a match -- which never reaches
the re-check -- costs 23.3us against the parent's 29.3us at one, two and
four compiled inputs, and the no-match path costs 18.5us against 27.9us at
one input, 29.9us against 33.0us at two, and 50.9us against 41.3us at four,
where the report's N check_verbose calls and the re-check's N check()
calls overtake the binds saved. Reading _guard_check_enabled instead does
not replace the stage: it is not there for the ordering, which the loop
order already gives, but so a tree whose first check() rejected without
running is still found -- the same rescue the parent got by re-entering
AOTCompiledFunction.__call__ on compiled_results[0], at a measured 3
check() calls plus a check_verbose there. Deleting it reds #196824's
test_aot_compile_module_opted_out_result_waits_for_the_full_recheck, which
reaches it through a globals key whose first comparison misses, not through
the dict-tag path, so the pin does not rest on the config either.

FAQ: The three counted tests assert guard evaluation counts but actually
measure dict lookups of the guarded global, which equals the evaluation
count only while the tree has one guard rooted at that global and nothing
else in the process reads it. Why not count evaluations directly with a spy
over GuardManagerWrapper.check/check_verbose?
Because a check() call
is not an evaluation, and this dispatch exists because of that gap, so a spy
would measure the one quantity these tests are not about. Measured on
ModeBranchGlobalModule's [1] tree: four check() calls on one manager
with one bound f_locals, all returning True, and the guarded global is
read exactly ONCE. DictGetItemGuardAccessor::check_nopybind returns true
without ever reaching its PyDict_GetItem (guards.cpp:5765) when the
enclosing dict's version tag matches and the node holds an immutable value
with no accessors under it (:5757-5763), and _dict_tag is committed only
on a passing check (:4079-4082). A spy reads 4 calls there; the tree
consulted the guard once. CountedKey.compares reads the tree, the spy
reads the caller.

That also makes the counts exact rather than coincidental. The passes tests
2 and 3 count are rejections, and a rejecting check never commits the tag,
so every pass really does re-read the name.
test_module_dispatch_evaluates_a_matching_tree_once guards a dict global
instead, so that fast path is doubly unavailable -- GLOBAL_POOLING_CONFIG
is not immutable and its node carries a child ['pooling'] accessor -- and
it was measured at 3 checks for 3 compares, with the regression the test
exists to catch (dispatch calling result() rather than result.fn)
costing exactly one more read.

The named inflation does not reproduce either: every guard on one name hangs
off the single DictGetItemGuardAccessor for it, whose one lookup is the
only lookup. That test's tree already carries a TYPE_MATCH, a nested
['pooling'] accessor and an EQUALS_MATCH under that one node and still
reads the name once per evaluation, so a DICT_VERSION beside the
DICT_GETITEM would land under the same node and not move the count.

In tests 2 and 3 the counter is not an observer at all: CountedKey.__eq__
returns self.compares > self.misses, so the counter IS the miss schedule.
compares == 2 asserts the accept arrived on the second READ of the global,
which is the claim -- the second pass re-evaluated the node the first pass
rejected. A spy can say check was called twice; it cannot say either call
reached the global. Keeping the probe only for its misses would leave its
script and the dispatch passes free to drift apart with nothing left reading
the lockstep, and an unrelated read of the name does not merely inflate a
count -- it takes a scripted miss and gets the wrong answer, which is
exactly what the count assertion notices. The window is the pop, the one
dispatch call and the cleanup, with no compilation inside it.

Finally, the spy pins two methods this commit does not own and whose own
comment says they are not the evaluation path ("Only needed for debugging
purposes", guards.py:770-776); routing dispatch straight at
self.root.check is a change that comment invites, and it would red all
three tests without changing anything they are about.

FAQ: The user guide documented a private path -- _aot_compile,
torch._dynamo.aot_compile.ModelInput,
compiled_results[i].disable_guard_check(). Why is it in a user guide?

It no longer sits in the quick start: the paragraph moved to a Developer notes section at the end of the same page, still headed by the bold "Private,
unstable -- may change or disappear without notice", and the
disable_guard_check() bullet cross-references it rather than saying "as
described above". It stays on the page at all because the bullet describes a
flag whose model-path meaning is documented nowhere else. The paragraph also
no longer calls enable_aot_compile a gate: the flag is True by default
(config.py:927), so it now says only a caller who turned it off has to
restore it. Promoting the path is a separate decision this stack does not
make.

FAQ: _binding_key compares co_freevars, but no test exercises a mismatch
on it. Why keep the term?

Two results holding the same cell under different freevar names cannot come
from a def: convert_frame asserts the output code's co_freevars equal
the input's, and distinct closed-over names get distinct cells. Reaching a
mismatch takes a hand-built code object, and the term is one tuple compare. It
is there because prepare_f_locals keys the closure entries by co_freevars,
so the key compares what the bind will read rather than a proxy for it.

FAQ: Why re-check compiled_results on every call instead of freezing it
after construction, or making it a property?

Because the list is public, the docs teach indexing into it, and nothing
enforces a freeze: deserialize and the public constructor both hand a live
list to a caller who may append to it. Detecting a change costs 0.27us for
four results (an identity compare of the list against the contents last
judged, method call included) against 0.81us for one check(), and
re-deciding costs a _binding_key per result only when the list actually
changed. Comparing the list with == would have been 0.02us, but
AOTCompiledFunction is a plain dataclass whose __eq__ reaches the
Signature compare _binding_key exists to avoid; snapshots of id()s were
measured at 0.89us, a whole check(). The verdict and the tuple it was
decided over are one field, _binding_verdict, stored and loaded as a single
attribute, so a caller on another thread that identity-matches the tuple reads
the verdict reached over it, and one that does not decides for itself. Since
the round-40 review, a call reads the list once -- results = tuple(self.compiled_results) at the top of __call__, 26ns for four results
-- and _binds_alike decides over that snapshot, so the re-check compares the
contents a call judges, never a list that changed under it.

FAQ: _binds_alike() stored _decided_over before it recomputed
_shared_binding; a thread switch between the two let a concurrent caller
identity-match the new tuple and return the old verdict. Fixed?

Yes, and not by ordering the two stores: with the pair in two fields no order
is atomic. Verdict-first ruled out new contents beside an old verdict but left
the mirror -- a reader that had snapshotted the list before a pop, matched the
contents still published, and took the True just decided about the shorter
list, which binds the popped list's [1] from [0]'s default and serves x * 3 for a call eager answers x * 2. The two fields are now one,
_binding_verdict, holding (contents, verdict) and stored and loaded as a
single attribute, so a reader either matches the contents and gets the verdict
reached over them or decides for itself. Both interleavings are forced
deterministically.
test_module_dispatch_never_pairs_new_contents_with_a_stale_verdict parks the
deciding thread on a threading.Event inside its first _binding_key, before
anything is published, and calls the model from the test thread in that
window. test_module_dispatch_never_pairs_old_contents_with_a_new_verdict
parks it right after its first attribute store (an AOTCompiledModel subclass
whose __setattr__ waits on the event) while a call that had already
snapshotted both results decides; on the two-field layout it fails with
RuntimeError not raised. The one thing no test can pin is a window between
the two halves of the publication, because there is none left: whatever the
first store publishes is all a reader can ever see, which is exactly what the
second test asserts.

FAQ: After serialize()/deserialize(), _binds_alike() answers False for
any forward with a real default or a closure cell. Why not share a memo
across the per-result pickles?

Measured and accepted as a conservative false negative. Each result is its own
blob, unpickled through its own AOTCompileUnpickler, so equal defaults and
cells return as distinct objects and the identity key reads them as different;
a forward with neither (defaults are the Parameter.empty singleton) still
shares one bind after a load. It is never a false share, so no wrong answer,
and both shared-binding tests now round-trip and pin the loaded verdict as
False. A shared memo means one Pickler/Unpickler over every result -- one
stream instead of a list of independent blobs, a pickler parameter on both
AOTCompiledFunction.serialize/deserialize, and per-function errors/probe
state mixed across results -- which is a serialization-format change, not a
dispatch one.

FAQ: Why did __post_init__ call _binds_alike()?

It no longer does. The field default, ((), False), is exactly the verdict
_binds_alike() reaches over an empty tuple, so a fresh instance's state is
already truthful and the first call decides; the eager call only let tests
read the field before a call, and they now read
_binds_alike(tuple(model.compiled_results)) instead, which is the query the
class exposes over the contents a call snapshots.

🤖 Generated with Claude Code

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ 199 Pending, 2 Unrelated Failures

As of commit 6da07d1 with merge base 4c54342 (image):

GREEN LIGHT - PR requires human review:

  • Guard-failure suppression widened
    • aot_compile.py:1516-1518's new last-resort loop serves any result whose _guard_check_enabled is False, from any list position.
    • The old fall-through (diff return self.compiled_results[0](...)) re-entered AOTCompiledFunction.__call__ and raised GuardManager check failed.
    • So one disable_guard_check() anywhere in compiled_results now silently runs a graph compiled for a different call, model-wide.
  • Documented behavior change
    • torch.compiler_aot_compile.md:414-425 adds a public-guide Developer notes section for the private _aot_compile path and the flag's new model-wide meaning.
    • Its claim that the dispatcher "serves the first input whose guards match" (:420) does not describe aot_compile.py:1504-1507, which returns on the first check() that accepts.
  • Repeated guard evaluation on the raising path
    • aot_compile.py:1510-1513 re-checks every result, so a LAMBDA_GUARD or a custom __eq__ reached by a guard tree runs twice per non-matching result.
  • Tests are present and targeted
    • test_aot_compile.py:2099-2175 forces both publication interleavings of _binding_verdict; :2244-2250 pins the any-position opt-out serve.
    • The behavior widening above is deliberate and covered, but it is a change to when guard validation is enforced, so a human should sign it off.

reason: removed_safety_logic
Reviewed commit: 6da07d1

Inference job

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 14, 2026
This was referenced Sep 14, 2026
@bobrenjc93 bobrenjc93 added ciflow/trunk Trigger trunk jobs on your pull request topic: not user facing topic category labels Sep 14, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 58m 6s —— View job


PR Review: #196929

One real regression found: the new _shared_binding signature comparison in AOTCompiledModel.__post_init__ raises RuntimeError for any module whose forward has a tensor (or ndarray) default and 2+ compiled inputs — plus a design question about the widened opt-out fall-through and three testing gaps.

Full review

PR Review: #196929

Summary

Replaces AOTCompiledModel.__call__'s single guard-check loop with a three-stage dispatch (scan / re-check / opted-out last resort), hoists the argument bind to once per call, and calls result.fn directly on a match. One new crash, one behavior widening worth discussing, and several test gaps.

Backward Compatibility

  • torch/_dynamo/aot_compile.py:1346 — artifacts.signature != first.signature raises for tensor-valued parameter defaults. inspect.Signature.__eq__ → _hash_basis() tuple compare → Parameter.__eq__ (inspect.py:2827), where self._default == other._default sits as a non-final operand of an and chain, so Python takes bool() of the result. Two Signature objects here are always distinct (inspect.signature does not cache; _signature_from_function builds fresh Parameters per call, and aot_compile.py:1079 runs once per ModelInput), so the identity fast path in PyObject_RichCompareBool does not fire. For

    class M(torch.nn.Module):
        def forward(self, x, mask=torch.ones(3)):
            return x * 2

    _aot_compile([inp_a, inp_b]) now dies in the constructor with RuntimeError: Boolean value of Tensor with more than one value is ambiguous; a numpy-array default gives ValueError: The truth value of an array ... is ambiguous. The default does not have to be used by the body — presence in the signature is enough. Nothing compared Signatures at the base commit (git grep over torch/_dynamo/ at origin/gh/bobrenjc93/1189/base finds none), so this is new, and it hits AOTCompiledModel.deserialize (line 1507) and the public constructor (test_aot_compile.py:1929) as well as aot_compile_module. Single-input models are unaffected, since the loop is over compiled_results[1:].

    A comparison that cannot run user __eq__ would avoid it — e.g. compare [(p.name, p.kind) for p in sig.parameters.values()] and the defaults by identity, which is also what bind + apply_defaults actually read. Fix this →

API Design

  • aot_compile.py:1389-1391 — the last-resort loop gives a per-result flag a model-wide blast radius. With compiled_results = [enabled, opted_out] and a call neither artifact guards, dispatch now runs opted_out's graph. The description defends this as a widening of the parent's index-0-only behavior, and that is accurate, but the consequence is that one disable_guard_check() anywhere in the list converts every unmatched call for the whole model from a report into a silent run of an arbitrarily-unrelated graph — including calls that resemble neither compiled input. The parent at least tied that to the artifact the user put first. Since the argument for it is "otherwise the flag is inert on the model path", the alternative worth weighing is making the opt-out only suppress its own report while still requiring a guard match on the model path, and documenting the flag as function-path-only. Flagging for discussion rather than as a defect.

  • docs/source/user_guide/torch_compiler/torch.compiler_aot_compile.md:114-123 — the public user guide now documents private internals. The new paragraph spells out _aot_compile, the dotted path torch._dynamo.aot_compile.ModelInput, and model.forward.compiled_results[i].disable_guard_check(). Saying "private and unstable" inline does not stop a user guide from being read as a contract; a private multi-input path either belongs in a developer note or should be promoted before it is documented here.

  • torch.compiler_aot_compile.md:141-143 contradicts the paragraph above it. The bullet says disable_guard_check() means the function "runs whatever it is called with, without evaluating its guards"; line 121 says "opting out here suppresses the failure, not the evaluation". Both are scoped correctly (function path vs model path) but a reader meets them nine lines apart with no signal that they describe different paths. Scope the bullet explicitly to the aot_compile function path.

Testing

  • The behavior this commit headlines has no test in this commit. The [enabled, opted_out] serve — the one answer the description says changes versus the parent — is pinned only by test_aot_compile_module_last_resort_iterates_past_a_checked_result in [aot_compile] Pin where an opted-out result sits in module dispatch #196824. A reviewer of this diff, and git bisect landing on this commit, sees the widening unguarded. The last-resort loop's position after the re-check is in the same situation.

  • _shared_binding is never tested with a closure-carrying forward. test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature (test_aot_compile.py:1892) uses ScaleModule, whose forward has no freevars, so the cells half of the predicate at aot_compile.py:1341-1348 is exercised only in its empty form. Note also that AOTCompiledModel.deserialize unpickles each blob separately (aot_compile.py:1477-1491), so every closure-carrying forward gets _shared_binding = False after a save/load round trip — correct, but it means the fast path silently does not apply on the load path and nothing asserts either way.

  • aot_compile.py:1341-1348 compares closure cells but not co_freevars. prepare_f_locals keys the closure entries with zip(env.bytecode.co_freevars, env.closure) (aot_compile.py:582), so the predicate proves cell identity but not that the shared dict will carry the right keys for results 1..N. In practice convert_frame.py:1923-1927 asserts code.co_freevars == out_code.co_freevars and distinct closed-over variables get distinct cells, so a real def cannot reach the mismatch — but the hand-assembled AOTCompiledModel(...) construction the sibling test exercises can. Adding co_freevars to the comparison is one term and closes the gap the predicate is asserting. (Lower confidence than the items above.)

Performance

  • The re-check pass is a no-op under default config and makes the no-match path slower. use_recursive_dict_tags_for_guards is False at torch/_dynamo/config.py:497, and GuardManagerWrapper.finalize() (guards.py:396-401) calls find_tag_safe_roots() only under it, which is the only writer of _is_tag_safe_root (guards.cpp:3514, read at :3797). So in OSS default configuration stage 2 re-evaluates every tree and can never find anything stage 1 missed — the PR's own numbers put the four-input no-match path at 50.9us against the parent's 41.3us. The FAQ's answer is that [aot_compile] Pin where an opted-out result sits in module dispatch #196824's test_aot_compile_module_opted_out_result_waits_for_the_full_recheck reaches the branch through a globals key whose first comparison misses rather than through the dict-tag path, which is true, but that is a probe with a side-effecting __eq__ rather than a shape a user hits. Since the cost falls only on the path that is about to raise, this is acceptable; recording it because the justifying mechanism is unreachable by default and the stage is therefore easy to mistake for load-bearing.

Code Quality

  • aot_compile.py:1376-1383 restates the commit message. The eight-line block re-derives the _disable_dict_tag_matching argument that the PR description already makes at length; CLAUDE.md asks for comments that carry non-local context, and "a check() rejection is not final because the fast path can reject without running the tree; the second pass re-evaluates" is that context in two lines. The same applies to the four-line bind rationale at 1354-1356 plus 1363-1366, which say the same thing twice from different angles.

  • aot_compile.py:1357-1371 — the bound list carries N references to one dict on the common path. if i and self._shared_binding: f_locals = bound[0] inside the loop reads as if the list is per-result state when in the shared case it is one dict appended N times. Hoisting the shared bind above the loop (shared = results[0].prepare_f_locals(...) if self._shared_binding else None) makes the two regimes visible without the index test in the hot loop.

Recommendation

Request Changes

The signature-comparison crash is a straightforward regression for any module with a tensor-valued parameter default and more than one ModelInput, and it needs a regression test. The missing in-commit test for the [enabled, opted_out] serve is the second blocker: the diff's own headline behavior change is only pinned from a different commit in the stack. The opt-out widening and the private-API documentation are worth settling before this lands, but neither is a defect.

Verified by reading: dispatch does not lose anything by bypassing AOTCompiledFunction.__call__ (that method is exactly guard-check + raise + self.fn(...), has no subclasses and no other in-tree wrappers, and fn's first parameter really is self), and reusing one f_locals dict across several check() calls is safe — nothing in guards.cpp writes into the mapping, relational state is reset on every exit path (guards.cpp:4386/4401/4409/4415), and RootGuardManager overrides check_nopybind (:4419-4425) so no dict-version cache is keyed on the f_locals dict identity and the second pass is a genuinely fuller evaluation.

Note on verification limits: Python execution was blocked in this environment, so the tensor-default crash was established from the CPython 3.12 inspect.py source chain and is_nonzero's error path rather than by running it. Worth confirming with the one-liner before acting.

| Branch: `gh/bobrenjc93/1189/head`

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 26m 38s —— View job


PR Review: #196929

The previous round's blocker (tensor-default Signature comparison) is fixed and pinned; what remains is a stale-cache hazard on the public compiled_results list, an inaccurate config gate in the user guide, and the still-unresolved question of documenting a private path in a user guide.

Full review

PR Review: #196929

Summary

Replaces AOTCompiledModel.__call__'s single guard-check loop with a three-stage dispatch (scan every result / re-check every result / honour an opt-out as last resort), hoists the argument bind to once per call behind a new _shared_binding predicate, and calls result.fn directly on a match. The prior review's blocker — inspect.Signature equality raising on a tensor-valued parameter default — is resolved by _binding_key (aot_compile.py:1324) and pinned by test_module_dispatch_shares_a_binding_past_a_tensor_default. Three findings remain, none of them a live wrong-answer today.

API Design

  • aot_compile.py:1346-1353 — _shared_binding is a once-computed invariant over a public, mutable, now-documented list. compiled_results is a plain list field with no encapsulation, and this PR's own doc addition (torch.compiler_aot_compile.md:121) teaches users to reach into it by index (model.forward.compiled_results[i].disable_guard_check()). __post_init__ decides _shared_binding once; appending to or replacing an element of that list afterwards leaves the flag stale, and a stale True makes __call__ feed result i's guard tree an f_locals dict bound from compiled_results[0]'s signature.

    Most mismatches fail safe — a differing parameter name means the guard's L['y'] lookup misses and the tree simply never matches — but the failure is not safe in general: if a guard_filter_fn dropped the guard on the parameter the two signatures disagree about, the appended result is served with a value bound from the other signature's defaults, i.e. a silent wrong answer rather than a no-match. I confirmed nothing in torch/ or test/ mutates a live compiled_results today (both producers build a fresh list and pass it to the constructor, aot_compile.py:1506 and :1555; the two hand-assembled tests concatenate into a new AOTCompiledModel, test_aot_compile.py:1943 and :2097), so this is latent, not live. But the invariant "compiled_results is effectively frozen after construction" is now load-bearing for correctness and nothing states or enforces it. Either compute the predicate lazily on first call, or state the invariant in the field's comment. Fix this →

  • torch.compiler_aot_compile.md:114-124 — the new paragraph describes the config gate inaccurately. It says the multi-input path is "gated on torch._dynamo.config.enable_aot_compile", which reads as something the user must turn on. That flag defaults to True (torch/_dynamo/config.py:927, whose own comment says "Should be always True"), so naming it as a gate sends a reader looking for a switch that is already closed. Either drop the clause or say the flag is on by default and only a caller who disabled it needs to restore it.

  • torch.compiler_aot_compile.md:114-124 — the public user guide documents a private path. The paragraph spells out _aot_compile, the dotted torch._dynamo.aot_compile.ModelInput, and compiled_results[i].disable_guard_check(). The bold "Private, unstable" lead-in was added since the last round and the contradiction with the disable_guard_check() bullet at :141-145 is now scoped away, so this is narrower than before — but an inline warning does not stop a user guide from being read as a contract, and the finding is that a private multi-input path belongs in a developer note rather than here. The stated reason for keeping it (no developer-notes section exists) argues for adding one, not for the current placement. Raising for a maintainer decision rather than as a defect.

Code Quality

  • aot_compile.py:1355-1392 — the comment block still runs about 1:1 with code, against CLAUDE.md's "minimize comments". Two specific ones carry little that is not local. :1366-1369 explains the scan by describing a counterfactual ordering ("not only after every other tree was checked twice below"), which requires the reader to simulate a version of the function that does not exist; "guard evaluation ignores _guard_check_enabled, so scan every result" is the whole point in one line. :1379-1382 re-derives the C++ dict-tag argument that the commit message already makes at length. The _binding_key comment at :1325-1328 is the one worth keeping as-is — the Parameter.__eq__ hazard is exactly the non-local fact a future editor would otherwise reintroduce.

  • aot_compile.py:1359 vs :1383/:1388 — the three loops disagree on how they name the same list. The scan binds results = self.compiled_results and iterates that; the re-check and last-resort loops iterate self.compiled_results directly. Same object, so no behavioral difference, but the reader has to confirm that. Use one form.

Performance

  • aot_compile.py:1383-1385 — the re-check pass cannot find anything under OSS default config, and it costs a full pass on the path that is about to raise. use_recursive_dict_tags_for_guards is False (config.py:497), and GuardManagerWrapper.finalize() (guards.py:396-401) calls find_tag_safe_roots() only under it, which is the only writer of _is_tag_safe_root (guards.cpp:3514, read at :3797), so check() never takes the fast path the stage exists to rescue from. The PR measures the four-input no-match path at 50.9us against the parent's 41.3us. This is confined to the raising path and [aot_compile] Pin where an opted-out result sits in module dispatch #196824 pins the stage through a different mechanism (a globals key whose first comparison misses), so it is not a blocker — recorded because the justifying mechanism is unreachable by default and the stage is easy to mistake for load-bearing in a way it currently is not.

Recommendation

Needs Discussion

No defect here produces a wrong answer under any state reachable through the in-tree APIs. What I verified rather than assumed, since the design leans on it: reusing one f_locals dict across N GuardManager.check() calls and then passing it to each manager a second time is safe. Guard evaluation never writes into the supplied mapping (no PyDict_SetItem/PyObject_SetItem against it anywhere in guards.cpp; framelocals_mapping.cpp:102,172 write only FrameLocalsMapping's own dict), RootGuardManager is built with the 2-arg ctor (guards.cpp:4329) so _is_dict is never set and no dict-tag cache is keyed on the f_locals identity, the tag is committed only on a passing check (:4078-4083), relational state is reset on every return path (:4386/4401/4409/4415), and _disable_dict_tag_matching is set on a rejecting node and its ancestors (:3860, propagating via :4046→:3843) with the only = false in the file being the member initializer at :4270 — so the second pass is a genuinely fuller evaluation, as claimed. _binding_key also covers exactly what bind + apply_defaults read (CPython inspect._bind reads only name/kind/default is _empty; apply_defaults reads default, kind and parameter order, which the key's list preserves), and Parameter.empty is a singleton so no-default parameters compare equal across artifacts.

The two items to settle before landing are the _shared_binding/compiled_results invariant and whether the private-path paragraph belongs in the user guide; the enable_aot_compile wording is a one-line doc fix.

Note on verification limits: this review is from reading source only — the test suite was not executed in this environment, so the PR's reported counts and timings are taken as stated.

| Branch: `gh/bobrenjc93/1189/head`

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

PR Review: #196929

  • Read the PR diff and changed files
  • Verify prior-round findings are addressed
  • Investigate dispatch correctness, thread safety, docs, tests
  • Fact-check findings against source
  • Post review

View job run | Branch: gh/bobrenjc93/1189/head

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 39m 1s —— View job


PR Review: #196929

No blocking defects — the one item worth taking before landing is still the missing addCleanup(decider.join) in test_module_dispatch_never_pairs_old_contents_with_a_new_verdict, which only bites on the failure path the test was written to produce.

Full review

PR Review: #196929

Summary

Replaces AOTCompiledModel.__call__'s single guard loop with a three-stage dispatch (scan every result / re-check every result / honour an opt-out as last resort), hoists the argument bind to once per call behind _binds_alike(), and calls result.fn directly on a match (torch/_dynamo/aot_compile.py:1418-1499). Prior rounds' findings are addressed in the current tree; two testing gaps and one code-quality item remain.

Testing

  • test/dynamo/test_aot_compile.py:2133-2174 — the decider thread is still not joined on the failure path. This was raised last round and is unchanged: test_module_dispatch_never_pairs_old_contents_with_a_new_verdict registers only self.addCleanup(release.set) (:2148) and does its decider.join() inline at :2173, inside the with self.assertRaisesRegex(...) block. When the assertRaisesRegex at :2170 does not raise — which is exactly the outcome on the two-field layout this test exists to reject, per the PR description — :2172-2173 never execute, cleanup unparks the thread, and it then completes _binds_alike((first,)) and stores into combined._binding_verdict after the test method has returned. The final assertion at :2174 is also racing that store on the failure path, so a red run can report a second, confusing failure. Its sibling at :2121-2122 already has the right shape.

    The naive fix does not work here, which is presumably why it was not taken: decider.start() happens conditionally inside the racing patch (:2165), so an earlier assertion failure (e.g. :2158) leaves the thread unstarted and join() raises RuntimeError: cannot join thread before it is started; and registering the join after addCleanup(release.set) makes LIFO run the join first and deadlock. A start-guarded join registered before the release closes both:

    self.addCleanup(lambda: decider.is_alive() and decider.join())
    self.addCleanup(release.set)

    (is_alive() is False for a never-started thread, so it is exactly the "was started" predicate, and a finished thread joins trivially.) Then drop the inline :2172-2173. Fix this →

  • aot_compile.py:1489-1492 — the re-check's bound[i] indexing is only ever exercised on paths where its answer cannot matter. bound is appended to only in the per-result regime (:1482), so bound[i] is live only when shared is None; the three tests that reach a re-check match (:2176, :2207, :2252) all build their model through _aot_compile, where _binds_alike() is True and the loop reads shared. The per-result tests that do reach the re-check (:2057, :2022) reach it only on the all-fail path, where every entry rejects and a misindex changes nothing. So the one index-alignment invariant this commit introduces — that bound[i] is result i's binding — has no test: mutating bound[i] to bound[0] leaves the suite green while making the re-check judge a result on another result's f_locals, which is the same silent-wrong-answer shape test_module_dispatch_judges_a_replaced_result_on_its_own_binding exists to rule out. A per-result-binding model whose match is found by the re-check rather than the scan (the differing-signature fixture at :2022 plus the misses=1 global probe) closes it.

Code Quality

  • aot_compile.py:1474-1492 — bound is declared and allocated on the shared path where nothing ever writes to it, and both loops re-test shared is not None per result. The list exists solely so the re-check can reuse each result's f_locals, which is meaningful only in the per-result regime; on the common path it stays empty while both loops branch on shared for every iteration. Hoisting it into that regime (bound = [] if shared is None else None, or building the per-result bindings in the branch that needs them) would make the two regimes read as differently as they behave. Minor — the previous revision appended N references to one dict, which this no longer does.

Recommendation

Approve

The bound[i] gap and the bound allocation are both small; the thread cleanup is the one I would take before landing, since its consequence is a stray thread mutating the model after tearDown precisely when the test is doing its job.

Verified rather than assumed, since the whole design rests on it: calling GuardManagerWrapper.check() twice per result, with one f_locals dict shared across N different managers, is safe for reasons beyond the _disable_dict_tag_matching argument the PR makes. GuardManagerWrapper.check/check_verbose are pure delegates to self.root.check (guards.py:770-776) and touch no per-call state — diff_guard_root is written only from populate_diff_guard_manager on the recompile path, which AOT dispatch never enters. RootGuardManager::check_nopybind_template resets dict-tag recording on entry (guards.cpp:4377) and relational state on all four exits (:4386/4401/4409/4415), and every relational leaf implements reset_state (NO_TENSOR_ALIASING :2730, OBJECT_ALIASING :2683, SYMBOLIC_SHAPE_GUARD :2887, STORAGE_OVERLAPPING :1663), all registered on the root at install time, so nothing accumulates across passes. _dict_tag, _dict_pointers and _disable_dict_tag_matching are per-GuardManager members (:4262-4270), the two process globals (dict_to_guard_managers, dict_version_state) are already many-managers-per-dict by construction (:3953, :5020), and the root is built with the two-arg ctor (:4329) so _is_dict is never set on it and the shared f_locals identity is never cached. And AOTCompiledFunction.__call__ (:855-869) is exactly guard-check plus self.fn(...), so bypassing it for result.fn drops no bookkeeping. One benign side effect the PR does not mention: the scan increments _fail_count and re-sorts _accessors (:4016/4047/4068) on results that will never be selected, which is a fail-fast heuristic only and is read outside AOT dispatch (guards.py:356).

Note on verification limits: source reading only — no .venv and no built torch in this environment, so nothing was executed; the PR's reported evaluation counts and timings are taken as stated, and lintrunner/spin were unavailable.

| Branch: `gh/bobrenjc93/1189/head`

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 59m 35s —— View job


PR Review: #196929

No blocking defects — three items remain: the decider thread is still unjoined on the failure path of ..._never_pairs_old_contents_with_a_new_verdict, the re-check's bound[i] indexing has no positive test (two mutations leave the suite green), and the new Developer notes paragraph claims dispatch "serves the first input whose guards match", which is the one thing the three-stage design exists because check() cannot promise.

Full review

PR Review: #196929

Summary

Replaces AOTCompiledModel.__call__'s single guard loop with a three-stage dispatch (scan every result / re-check every result / honour an opt-out as last resort), hoists the argument bind to once per call behind _binds_alike(), and calls result.fn directly on a match (torch/_dynamo/aot_compile.py:1483-1520). Findings below are a test-hygiene item, a coverage gap, and a doc inaccuracy.

Testing

  • test/dynamo/test_aot_compile.py:2134-2175 — the decider thread is still not joined on the failure path. Raised in the two prior rounds and unchanged. test_module_dispatch_never_pairs_old_contents_with_a_new_verdict registers only self.addCleanup(release.set) (:2149) and does its decider.join() inline at :2174, inside the with self.assertRaisesRegex(...) block. When the assertRaisesRegex at :2171 does not raise — the outcome on the two-field layout this test exists to reject — :2173-2174 never execute, cleanup unparks the thread, and it then completes _binds_alike((first,)) and stores into combined._binding_verdict after the test method has returned. The assertion at :2175 is also racing that store on the failure path, so a red run can report a second, confusing failure. Its sibling at :2122-2123 already has the right shape.

    The naive fix does not work here, which is presumably why it was not taken: decider.start() happens conditionally inside the racing patch (:2166), so an earlier assertion failure (:2165) leaves the thread unstarted and join() raises RuntimeError: cannot join thread before it is started; and registering the join after addCleanup(release.set) makes LIFO run the join first and deadlock. A start-guarded join registered before the release closes both:

    self.addCleanup(lambda: decider.is_alive() and decider.join())
    self.addCleanup(release.set)

    (is_alive() is False for a never-started thread, so it is exactly the "was started" predicate, and a finished thread joins trivially.) Then drop the inline :2173-2174. Fix this →

  • aot_compile.py:1496,1503,1511 — nothing pins that bound[i] is result i's binding, and two mutations of the re-check leave the suite green. bound is populated only when shared is None (:1503), and every test that reaches a re-check match (:2177, :2208, :2253) builds its results through one _aot_compile, where _binds_alike() is True and the loop reads shared. The only two tests that reach the re-check with shared is None (:2058, :2134) expect a raise, where every entry rejects. Consequences:

    • if shared is None: break inserted before the re-check loop (:1510) is green — both per-result tests still raise via the fall-through at :1520.
    • replacing bound[i] with a fresh result.prepare_f_locals(...) and deleting bound entirely is green — the only bind-count assertion (:2021) is in the shared regime.

    So the re-check exists for the per-result regime and is verified only in the shared one, where bound is dead code. The bound[i] → bound[0] mutation is caught (by :2069 and :2171), so the index alignment is pinned negatively; what is missing is a positive one. The fixture is already in the file: the differing-default pair from make_mode_default_forward (so _binds_alike is False) plus _install_global_probe("AOT_BRANCH_SCALE", misses=1), asserting the call is served by [1] and probe.compares == 2 — the per-result-regime twin of test_module_dispatch_serves_a_call_the_guard_tree_accepts.

  • aot_compile.py:1474 — the pop half of the re-decision is pinned only at the verdict level. test_module_dispatch_never_pairs_old_contents_with_a_new_verdict pops and asserts _binds_alike recomputes (:2165, :2175), which does kill a zip-only comparison, but no test has a shortened list change which result serves a call. Thinner than the append and replacement cases, which both have dispatch-level tests (:2044, :2058).

API Design

  • docs/.../torch.compiler_aot_compile.md:418-425 — "The dispatcher serves the first input whose guards match" is the one thing this dispatch cannot promise. The scan returns on the first result whose check() accepts (aot_compile.py:1504-1507), and the commit's own premise — stated in the comment two lines below at :1508-1509 — is that check() can reject from the dict-tag fast path without running the tree. So if [0]'s guards genuinely match but its first check() rejects, and [1]'s accepts, [1] is served and [0]'s second chance never arrives, because the re-check loop is never reached. The two tests at :2208 and :2253 construct exactly that false rejection. The served result is the first one check() accepts on the first pass, not the first whose guards match; wording it as the latter tells a reader they can order compiled_results to express a preference that dispatch does not honour.

  • torch.compiler_aot_compile.md:404-406 now reads inconsistently with the new section. The Limitations bullet says "Inputs with different shapes will trigger a guard failure at runtime unless guards are explicitly disabled", which is true of the single-artifact function path but is the opposite of what the multi-input dispatcher exists to do — a differently-shaped input is served by whichever result guards it. This is the only other place in the page touching multi-artifact behaviour, so a one-clause scope ("on the single-artifact function path") is enough.

Recommendation

Approve

None of these is a wrong answer reachable through the in-tree APIs. The thread cleanup is the one I would take before landing, since its consequence — a stray thread mutating the model after tearDown — lands precisely when the test is doing its job.

Verified rather than assumed, since the whole design rests on both: (a) _binding_key (:1439-1449) cannot false-share. prepare_f_locals (:625-638) reads only env.closure's truthiness, env.bytecode.co_freevars, each cell.cell_contents, and bind_locals (:113-118); inside CPython's Signature._bind (/usr/lib/python3.12/inspect.py:3102-3235) the only Parameter state consulted is name, kind, default is _empty and the iteration order of parameters.values(), and apply_defaults (:2918-2944) adds the default value and kind — never annotations — all of which the key carries in order. id(default)/id(cell) are strictly finer than ==, and both sides are computed inside one _binds_alike() call while every result is reachable from the snapshot, so no address reuse; env.closure being None vs () is indistinguishable to the key and to prepare_f_locals' falsy test alike. runtime_env and runtime_env.bytecode are non-Optional (:129, convert_frame.py:1113) and serialize nulls only a copy (:899-911), so the load path cannot deref None. (b) Bypassing AOTCompiledFunction.__call__ for result.fn drops nothing: that method (:869-883) is exactly the guard check, the error message and self.fn(*args, **kwargs), with no counters, context managers, _artifacts bookkeeping or return post-processing; nothing subclasses it or wraps its __call__; fn is a plain instance attribute assigned in __post_init__ (:691) from runtime_env.forward_callable (convert_frame.py:1149-1154) over the unbound forward, so fn(self.model, ...) is the right convention. The extra guard evaluations are also state-safe: relational leaves reset on every root exit (guards.cpp:4386/4401/4409/4415), the dict-tag caches are keyed on the guarded value and tag-safe roots are only marked for nn.Module-typed values (guards.py:669-670), never the fresh f_locals dict, and _fail_count/accessor reordering (guards.cpp:4016/4047) is a fail-fast heuristic read only at build time. One consequence the docs do not mention: a guard tree containing user code (LAMBDA_GUARD, an EQUALS_MATCH on a custom __eq__, a GetAttrGuardAccessor over a property) now runs that code up to twice per non-matching result on the raising path, which the counted tests assert as compares == 2.

Note on verification limits: source reading only — no .venv and no built torch in this environment, so nothing was executed and the PR's reported evaluation counts and timings are taken as stated; lintrunner/spin were also unavailable, so the new code was not lint-checked (added lines are ASCII-clean by inspection).

| Branch: `gh/bobrenjc93/1189/head`

[ghstack-poisoned]
pytorchgreenlight[bot]
pytorchgreenlight Bot previously approved these changes Sep 14, 2026
[ghstack-poisoned]
@pytorchgreenlight
pytorchgreenlight Bot dismissed their stale review September 14, 2026 19:43

Superseded by a newer greenlight verdict.

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Superseded: the scan/re-check/binding rewrite continues as a new PR at the bottom of this stack, and the any-position opt-out serve as #197047, so each can be reviewed on its own.

@bobrenjc93 bobrenjc93 closed this Sep 15, 2026
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
… 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 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
…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
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1189/head branch November 20, 2026 01:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant