Skip to content

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

Closed
bobrenjc93 wants to merge 3 commits into
gh/bobrenjc93/1197/basefrom
gh/bobrenjc93/1197/head
Closed

bobrenjc93 wants to merge 3 commits into
gh/bobrenjc93/1197/basefrom
gh/bobrenjc93/1197/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Test Plan:

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

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

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

Authored with the assistance of Claude Code.

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

🤖 Generated with Claude Code

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

[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 15, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ 1 Pending, 2 Unrelated Failures

As of commit 204e247 with merge base b8bd7cf (image):

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

  • Correctness
    • AOTCompiledModel.__call__ (torch/_dynamo/aot_compile.py:1483-1508) keeps the parent's fall-through into results[0], so a no-match call still raises or serves an opted-out [0].
    • Calling result.fn on a match is exactly AOTCompiledFunction.__call__'s success path, whose only other work is the guard check the scan just did (aot_compile.py:884-898).
    • Reusing one f_locals across both passes is safe: RootGuardManager::check_nopybind_template resets recording and relational state on every exit (guards.cpp:4377-4416).
  • Preservation
    • The dropped guard_manager is None assert moves into _live_guard_manager() (aot_compile.py:639-644), and both readers of the field still raise through it.
    • The state it stopped covering is unreachable: __post_init__ always populates the field (aot_compile.py:705) and serialize() nulls only a __dict__ copy (aot_compile.py:914-915).
  • Testing
    • Six new test_module_dispatch_* tests in test/dynamo/test_aot_compile.py cover the single check on a match, the compiled_results snapshot, the re-check rescue, and the no-match fall-through.
    • _install_global_probe registers both cleanups before touching globals() and pops the probe LIFO, so a failing test cannot leave the rekeyed global behind.
  • Scope
    • Two files, and the only source change is AOTCompiledModel.__call__, its new docstring, and the _live_guard_manager() narrowing; no public API, docs, or CI change.
    • AOTCompiledModel is reached only through the private _aot_compile (torch/_dynamo/eval_frame.py:565) and aot_compile_module (aot_compile.py:1694).

reason: clean
Reviewed commit: 204e247

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.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 23m 12s —— View job


The two-stage dispatch is correct and the guards.cpp argument behind the re-check holds, but the re-check is unreachable in the default OSS config, the doc edit now contradicts the new docstring, and the binding-sharing cache is a micro-optimization carrying most of the PR's complexity.

Full review

PR Review: #197055

Summary

Replaces AOTCompiledModel.__call__'s fall-through-to-compiled_results[0] with an explicit scan-then-recheck dispatch, plus a cached "do all results bind alike" verdict so a call binds once instead of once per result. I verified the load-bearing guards.cpp claims and they hold (details below); the problems are a documentation contradiction the PR introduces, a re-check stage that cannot fire under the default config despite an available gate, object retention in the new cache field, and scope/brittleness concerns.

Verified as correct (so I am not flagging these): _disable_dict_tag_matching is per-GuardManager (guards.cpp:4270), every write outside the initializer sets true (3554, 3694, 3723, 3810, 3816, 3823, 3860), and it does reach ancestors — not by propagation but because each ancestor's own check_nopybind hits if (!result) { _disable_dict_tag_matching = true; } at 3859-3861 as the failure unwinds. check() cannot flip false→true via the tag cache, since stop_recording_dict_pointers only stashes on a true result (3847). RootGuardManager::check_nopybind_template resets relational state and re-inits LocalState on every entry (4377-4382, 4415), so reusing one f_locals dict across managers and two passes is deterministic.

API Design

  • docs/source/user_guide/torch_compiler/torch.compiler_aot_compile.md:130-132 — the bullet now asserts disable_guard_check() means the compiled function "runs whatever it is called with, without evaluating its guards", in the same commit that makes AOTCompiledModel.__call__ evaluate exactly those guards for dispatch. disable_guard_check is a method on AOTCompiledFunction (aot_compile.py:1026), which is precisely what compiled_results holds — so the object the bullet describes is the object whose guards now are evaluated. The new class docstring says the opposite ("does not skip its guard evaluation", aot_compile.py:1465). The PR's rationale ("the page documents the public function path only") does not hold when the bullet documents a method that both paths share. Either scope the sentence to the function path explicitly or add the module-dispatch caveat. Fix this →

Performance

  • torch/_dynamo/aot_compile.py:1521-1527 — the re-check loop cannot fire in the default configuration, so on the default path it is N extra full check() calls per no-match call buying nothing. find_tag_safe_roots() only runs when config.use_recursive_dict_tags_for_guards and a justknob pass (guards.py:396-400), and the flag defaults to False (config.py:497). Without it no node is ever mark_tag_safe_root()'d (guards.py:668-670), so _is_tag_safe_root is false everywhere and the branch at guards.cpp:3797 is never taken — check() always falls through to check_nopybind_template and can only return false after running the tree.

    The PR rejects a gate on the grounds that "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." That is true of the C++ API but not of the Python side: find_tag_safe_roots already materialises the tag_safe_roots list at guards.py:667 and it is called from finalize() (guards.py:5498), i.e. at exactly the moment the PR correctly identifies as the one that decides arming. Recording bool(tag_safe_roots) on the GuardManagerWrapper there is free, is decided once, and turns the gate into a single bool read — no tree walk, and immune to the config being patched after finalize. Worth doing before shipping a second pass over every result.

  • torch/_dynamo/aot_compile.py:1478-1480, 1493 — _binding_verdict stores the judged results tuple, holding a strong reference to every AOTCompiledFunction it last saw. A caller who drops results (compiled_results.clear(), pop(), or replacing an entry) keeps the old artifacts — each carrying a compiled graph module and its baked-in tensors — alive until the next call re-decides. Since the field only ever needs to answer "are these the same objects", storing [id(r) for r in results] alongside a weakref sentinel, or clearing the field when the length shrinks, avoids pinning artifacts the caller has released. (The PR notes id-based snapshots were measured at 0.89us vs 0.27us and rejected on cost; the retention consequence is not addressed in that comparison.)

Testing

  • test/dynamo/test_aot_compile.py:2148-2175 (test_module_dispatch_never_pairs_old_contents_with_a_new_verdict) — registers self.addCleanup(release.set) but no decider.join cleanup, unlike its sibling. If the assertRaisesRegex at 2171 fails, release.set() (2173) and decider.join() (2174) are both skipped, the patch.object unwinds while the decider thread is still parked inside Held.__setattr__, and the thread outlives the test. Register the join the way line 2122 does.

  • test/dynamo/test_aot_compile.py:2122-2125 — self.addCleanup(decider.join) is registered before decider.start(). Any failure in between (the patch() entry at 2124) makes cleanup call join() on an unstarted thread, which raises RuntimeError: cannot join thread before it is started and masks the real failure. Register the cleanup immediately after start(), or use decider.join guarded on decider.is_alive().

  • test/dynamo/test_aot_compile.py:571-587, 1965-1975 — CountedKey counts guard evaluations by mutating state inside __eq__ on a key spliced into globals(), and the tests then assert exact counts (assertEqual(compares, 1) at 1993, assertEqual(compares, 2) at 2205/2233/2255). The test comment at 1988-1989 concedes the count is only correct because of CPython's identity-first key comparison in dict lookup — the same class of implementation-detail dependence the review checklist rules out for sys.getrefcount. The counts also encode how many times the current guard tree happens to read one global, so any change in guard-tree shape (an extra diff-guard manager, a check_verbose) silently breaks them with no signal about what actually regressed. For test_module_dispatch_evaluates_a_matching_tree_once, which needs misses=0 and only counts, a wrapper counting calls to manager.check — the pattern already used at 2043-2050 and 2119 — measures the property directly and does not depend on dict-lookup internals. Keep CountedKey only where a false rejection has to be forced (misses=1).

Code Quality

  • torch/_dynamo/aot_compile.py:1439-1494 — the binding-sharing cache is purely a performance optimization (the PR measures 23.3us vs 29.3us, and 20.1us vs 33.5us at four results) but it carries the majority of this PR's complexity: a new module function, a new field, a cross-thread single-store publication protocol, and 8 of the 13 new tests including two that force thread interleavings via a __setattr__ hook and a patched _binding_key. Binding per result is unconditionally correct, so the correctness fix this PR is titled for — scan every result, then re-check — stands on its own without any of it. Please split: land the two-stage dispatch (with per-result binds) and the docstring first, then the binding cache as its own commit where the publication protocol and its two race tests can be reviewed against a single question. As it is, a reviewer cannot approve the dispatch change without also approving a concurrency protocol for a private experimental API.

  • torch/_dynamo/aot_compile.py:1471-1494, 1497-1528 — a 94-line source change carries roughly 45 lines of comment, including microbenchmark constants that cannot be verified at review time or maintained afterwards ("Measured at 0.27us for four results, call included, against 0.81us for one check()", "snapshots by id were measured at 0.89us and rejected") and references to test method names. CLAUDE.md asks for no comments by default and for comments that state a non-obvious why; benchmark figures for a machine nobody else has, and pointers to tests, belong in the commit message, which already contains them. Keep the two genuinely non-obvious whys — that check() can reject without running the tree, and that Parameter.__eq__ raises on a tensor default — and drop the rest.

  • torch/_dynamo/aot_compile.py:1487 and the new import operator at line 8 — all(map(operator.is_, results, prior)) reads worse than all(a is b for a, b in zip(results, prior)) and is the only reason operator is imported. It also relies on map truncating to the shorter iterable, which is only safe because of the length test on the same line; the zip form makes that explicit and drops the import.

  • torch/_dynamo/aot_compile.py:1440 — _binding_key is annotated -> tuple[object, ...] but returns a fixed 3-tuple of (list, tuple, list). The concrete type documents the contract (and that the value is ==-compared, never hashed) better than object.

Recommendation

Needs Discussion

The dispatch change itself is sound and the guards.cpp reasoning checks out. What blocks approval: the user-guide edit now states something false about the path this PR introduces, and the re-check stage is dead weight under the default config when a cheap gate is available at finalize(). Both are small. The larger ask is splitting the binding-sharing cache out — it is a ~6us optimization that brings a cross-thread publication protocol, an artifact-retaining cache field, and two interleaving tests into a commit whose stated purpose is a correctness fix.

· branch `gh/bobrenjc93/1197/head`

@bobrenjc93
bobrenjc93 marked this pull request as ready for review September 15, 2026 03:36
@bobrenjc93
bobrenjc93 marked this pull request as draft September 15, 2026 03:38
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

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


The two-stage dispatch is sound, but the guards.cpp rationale it rests on is broader than the code supports, the re-check is unreachable under the default OSS config, and the new class docstring documents the accept path while omitting the fall-through — the one place the opt-out flag actually changes behavior.

Full review

PR Review: #197055

Summary

Replaces AOTCompiledModel.__call__'s single-pass loop + fall-through-to-compiled_results[0] with an explicit scan-then-recheck over a snapshot of compiled_results, calling result.fn directly on a match. The scan, the snapshot, and calling fn instead of result() are all correct. What needs work: the stated justification for the re-check overstates what check() does, the re-check cannot fire in the default configuration, the docstring omits the fall-through, and dispatch now open-codes three private members of AOTCompiledFunction.

I verified the claims the design rests on before writing this. Holding up: _disable_dict_tag_matching is a per-GuardManager member with = false only as its declaration default (guards.cpp:4270); every other write sets true (3554, 3694, 3723, 3810, 3816, 3823, 3860), including the weakref and dict-watcher callbacks (3874, 5027). Ancestors are reached — not by propagation, but because each ancestor's own check_nopybind hits if (!result) { _disable_dict_tag_matching = true; } at 3859-3861 as the false unwinds. check() cannot be pushed false→true by the tag cache: pointers are stashed only on a passing result (3845-3847). And reusing one f_locals across two passes and across managers is safe — RootGuardManager::check_nopybind_template calls reset_dict_tag_recording_variables() (4377), re-inits LocalState (4380-4383), and _reset_relational_guard_state() on all four exits (4386, 4401, 4409, 4415).

API Design

  • torch/_dynamo/aot_compile.py:1456-1469 — the docstring documents the accept path and omits the fall-through, which is where the interesting behavior lives. A call no check accepted is handed to results[0] (line 1494), which raises GuardManager check failed if compiled_results[0] has guard checking enabled, but runs its graph — compiled for a different call — if that one result happens to have opted out. That is the most surprising property of the class and the only place disable_guard_check() changes anything on this path, and a reader who holds an AOTCompiledModel cannot learn it from the docstring. Relatedly, "Opting a result out through disable_guard_check() does not skip its guard evaluation: it is served in index order when its check accepts" understates the situation: for dispatch the flag is entirely inert (check() never reads it), so an opted-out result is treated exactly like any other — the sentence reads as though the opt-out has some diminished effect rather than none. Say plainly that the flag does not participate in dispatch, and then document what compiled_results[0] does when nothing matched. Fix this →

Performance

  • torch/_dynamo/aot_compile.py:1490-1492 — the re-check cannot fire under the default OSS configuration, so on the default path it is N extra full tree evaluations per no-match call, buying nothing. _is_tag_safe_root is set only by mark_tag_safe_root (guards.cpp:3511), whose sole Python caller is find_tag_safe_roots (torch/_dynamo/guards.py:670), which finalize() calls only under config.use_recursive_dict_tags_for_guards and a justknobs pass (guards.py:397-400) — and the config defaults to False (config.py:497). With no tag-safe root, the entire if (_is_tag_safe_root) block at guards.cpp:3797 is unreachable and check_nopybind_template at 3843 always runs.

    The PR's stated reason for declining a gate is that it would need a new attribute on GuardManagerWrapper and would rest dispatch's correctness on a guards.cpp property read from Python. The first half is a one-line change at exactly the moment that decides arming — find_tag_safe_roots already materialises the tag_safe_roots list at guards.py:667 inside finalize(), so recording bool(tag_safe_roots) there is free and decided once. The second half is a fair objection, but it cuts the other way too: the ungated re-check is unconditionally safe, not unconditionally free, and the PR's own measurements put it at 2.0us for two results and 3.9us for four on every no-match call, growing linearly with len(compiled_results).

  • torch/_dynamo/aot_compile.py:1490-1492 — the second pass re-runs each non-matching tree in full, which re-executes arbitrary Python: LAMBDA_GUARD closures and the root's _epilogue_lambda_guards (guards.cpp:4406-4412) all fire a second time per no-match call. It also double-counts _fail_count (guards.cpp:4047) on every failing accessor, which feeds the fail-fast reordering std::sort at 4068-4075. That heuristic exists to move high-failure accessors earlier; doubling the increments only for results reached through module dispatch skews it relative to the same artifact called directly through AOTCompiledFunction.__call__. Neither effect is mentioned in the code or the docstring.

Code Quality

  • torch/_dynamo/aot_compile.py:1487-1489 and 1462-1464 — both the inline comment and the docstring attribute the early-false to "the recursive dict-tag fast path" generally, and that is broader than the code. Of the fast path's exits, only the no-tensor-aliasing sub-path returns false without running the tree (guards.cpp:3806-3811, reachable only via check_no_tensor_aliasing_guards_fast returning false at 3724 or 3729). A dict-tag or tensor-metadata mismatch (3816) and the cache-size cap (3823) both fall out of the if and still execute check_nopybind_template(value) at 3843 — they set the flag but their false is a real answer about the call. So the rescue window is: a tag-safe root, with recorded tensor pointers, under a NO_TENSOR_ALIASING guard, with use_recursive_dict_tags_for_guards enabled. The re-check is still correct, but a future reader will use these comments to reason about it and will conclude the window is far wider than it is. Name the actual path.

  • torch/_dynamo/aot_compile.py:1481-1486 — dispatch now open-codes three private members of AOTCompiledFunction (prepare_f_locals, _live_guard_manager(), fn) to assemble the equivalent of __call__ minus the guard check. The consequence is two divergent entry points into one artifact that must be kept in sync by hand: anything added to AOTCompiledFunction.__call__ — the _missing_global_hint() path at 896 is already an example — silently does not apply on the module path. Give AOTCompiledFunction a declared method for "run, guards already verified" and have dispatch call that, so the contract is stated in one place instead of reassembled at the call site.

Testing

  • test/dynamo/test_aot_compile.py — the PR's central claim is "no behaviour change vs the parent on a no-match call," backed by a hand-measured four-row table ([enabled, enabled] raises … [opted_out, opted_out] served). Nothing in the diff pins any row. The only no-match assertion is inside test_module_dispatch_judges_only_the_results_a_call_began_with:2028, where [0]'s check is monkeypatched, so it exercises the mocked path rather than the property. A plain two-result AOTCompiledModel called with a non-matching input, parametrized over the four opt-out combinations, would pin the table directly and would fail loudly if a later commit in the stack changes a row it did not mean to.

  • test/dynamo/test_aot_compile.py:571-585, 2060 — CountedKey depends on CPython dict internals in two places, which is the class of dependence the review checklist rules out (it names sys.getrefcount, but the reasoning is the same). It requires that lookdict passes the stored key as the left == operand, so CountedKey.__eq__ runs rather than str.__eq__; and it requires that g.pop(probe, None) in the cleanup succeeds via the identity fast path, since probe == probe is not reflexive under this __eq__ and would otherwise return False and leave the probe in the module dict permanently. Separately, assertEqual(check.call_count, 2) additionally encodes that the tree performs exactly one lookup of AOT_BRANCH_SCALE per check(): add a second accessor rooted at that global, or a shape-guard code part naming it, and pass 1 starts succeeding and the count becomes 1 — a failure with no signal about what actually changed. Since the counted assertion is on check.call_count, CountedKey is only needed to force the false rejection; consider narrowing misses handling to a single explicit one-shot rather than a comparison counter.

  • test/dynamo/test_aot_compile.py:1983-1995 — the probe inserts a non-str key into this module's __dict__. _hide_leaked_dynamo_globals (line 1857) iterates globals() doing k.startswith(_MINTED_PREFIXES) at 1870, which raises AttributeError on a CountedKey. It is unreachable today only because the three probe tests are the only compile tests in TestAOTCompile that don't call _hide_leaked_dynamo_globals — so the landmine and the hygiene gap are the same fact: these tests leak __compiled_fn_* into the module dict where ~50 siblings deliberately do not, and they cannot adopt the sibling pattern while the probe is live. Also, the ordering comment at 1984-1989 asserts "nothing between the pop and the insert may leave this dict without the name," but lines 1991-1994 are that window and it precedes the first addCleanup, so an interrupt there drops the global for the rest of the process. The LIFO argument itself is correct; the justifying sentence is not.

  • test/dynamo/test_aot_compile.py:600-604 — aot_compile_forward is a single-use helper (called twice from one test, line 2017-2018) whose first line is a no-op: mod.forward = types.MethodType(forward, mod) rebinds mod.forward to what it already is, since the forward argument is ScaleModule.forward at both call sites and OptimizedModule._initialize takes the same branch either way (eval_frame.py:538, _forward_has_skip_rule is False for a forward defined in the test file). CLAUDE.md asks for no trivial single-use helpers; this one is also the file's only module-level non-underscored test helper (compare _set_pooling, _two_input_global_guard_artifact). Inline it, or drop the forward parameter and the MethodType line.

  • torch/_dynamo/aot_compile.py:1494 — an empty compiled_results makes the fall-through raise a bare IndexError: tuple index out of range. This is pre-existing (the parent indexed compiled_results[0] the same way) and aot_compile_module rejects the empty list at 1677 — but AOTCompiledModel.deserialize (1602-1631) does not, and this PR's test_module_dispatch_judges_only_the_results_a_call_began_with:2019 establishes direct AOTCompiledModel(mod, [...]) construction as a used entry point. Since the commit is adding a docstring that specifies dispatch, it is the natural place to either reject the empty list or state that it is the caller's responsibility.

Recommendation

Needs Discussion

The dispatch restructuring is right and I could not break the two-pass reasoning. Three things stand between this and approval, all small: correct the guards.cpp attribution in the comment and docstring (only the no-tensor-aliasing exit returns false without running the tree), document the fall-through in the docstring since that is where the opt-out actually matters, and either gate the re-check on bool(tag_safe_roots) recorded in finalize() or state in the code that it is a no-op under the default config and accepted as such. The test asks — a plain unmocked test for the four-row no-match table, and reducing the CountedKey dict-internals surface — matter because the next several commits in the stack change exactly these rows.

· branch `gh/bobrenjc93/1197/head`

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@bobrenjc93
bobrenjc93 marked this pull request as ready for review September 15, 2026 14:20
@bobrenjc93 bobrenjc93 added the topic: not user facing topic category label Sep 15, 2026
@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

PR Review in progress

  • Load /pr-review guidelines
  • Read the diff against origin/gh/bobrenjc93/1197/base
  • Verify the guards.cpp claims the design rests on
  • Review dispatch changes in torch/_dynamo/aot_compile.py
  • Review new tests in test/dynamo/test_aot_compile.py
  • Post review

View job run · branch gh/bobrenjc93/1197/head

@pytorch pytorch deleted a comment from claude Bot Sep 15, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Sep 15, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 2 checks: inductor / unit-test / inductor-cpu-test / test (inductor_aoti_fallback, 1, 2, mt-l-x86iamx-8-64, unstable), inductor / unit-test / inductor-cpu-test / test (inductor_aoti_fallback, 2, 2, mt-l-x86iamx-8-64, unstable)

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

pytorchmergebot pushed a commit that referenced this pull request Sep 15, 2026
…196824)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

## What the escape hatch costs

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

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

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

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

## What is deliberately not duplicated here

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

Test Plan:

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

Authored with the assistance of Claude Code.

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

## FAQ

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

## Re-decided whenever the public list changes

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

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

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

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

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

## One field, published with one store

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

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

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

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

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

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

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

Test Plan:

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

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

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

Authored with the assistance of Claude Code.

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

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

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

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

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

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

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

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

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

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

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

## What the flag now means on a module

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

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

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

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

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

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

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

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

## To review

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

Test Plan:

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

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

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

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

Authored with the assistance of Claude Code.

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

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

Pull Request resolved: #197047
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196767, #196817, #196815, #196816, #196818, #196819, #196820, #196821, #196895, #196904, #197055, #196824, #197071
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1197/head branch November 20, 2026 01:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants