Skip to content

[aot_compile] Bind a module dispatch call once for results that bind alike - #197071

Closed
bobrenjc93 wants to merge 2 commits into
gh/bobrenjc93/1198/basefrom
gh/bobrenjc93/1198/head
Closed

bobrenjc93 wants to merge 2 commits into
gh/bobrenjc93/1198/basefrom
gh/bobrenjc93/1198/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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:

# 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:

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

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.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
# 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:

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:

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:

# 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

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ 1 Pending, 2 Unrelated Failures

As of commit d0dd350 with merge base b8bd7cf (image):

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

  • Correctness of the shared bind
    • _binding_key (torch/_dynamo/aot_compile.py:1455-1464) compares exactly the freevar cells and signature that prepare_f_locals (:625-638) reads, by identity
    • __call__ (:1535-1542) appends one bound entry per result either way, so the re-check zip(results, bound) at :1554 pairs as before
    • No PyDict_SetItem/PyDict_DelItem anywhere in torch/csrc/dynamo/guards.cpp, and RootGuardManager::check_nopybind (:4419-4425) resets relational state at every exit, so one dict can serve N trees
  • Staleness handling
    • _binds_alike (:1514-1523) re-decides on any length or identity change of compiled_results, publishing contents and verdict in one store at :1522
    • Weak references mean a popped result is not retained; a dead w() fails the is check at :1516 and forces a re-decision
  • Testing
    • 10 new test_module_dispatch_* tests in test/dynamo/test_aot_compile.py pin the replaced-result staleness path, weakref retention, tensor defaults, closure cells, and both publication interleavings
  • Scope
    • Confined to AOTCompiledModel, which its own docstring calls private and experimental; torch/_dynamo/eval_frame.py:595-617 only isinstance-checks and deserializes it, so no public signature changes

reason: clean
Reviewed commit: d0dd350

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 15, 2026
This was referenced Sep 15, 2026
@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 28m 34s —— View job


Reviewed — the sharing itself is sound (I verified check() neither mutates nor caches across managers, so one f_locals for N guard trees is safe), but the cache exists entirely to serve a compiled_results mutation contract that is nowhere documented, and the single-result case — the common one — now pays pure overhead.

Full review

PR Review: #197071

Summary

Caches a "do all results bind alike" verdict on AOTCompiledModel so a dispatch call can build one prepare_f_locals binding and reuse it across the guard scan and the re-check, instead of binding once per result. The core optimization is sound and I confirmed the safety premise it rests on, but the invalidation machinery around it is built for an undocumented contract, and N=1 regresses.

API Design

  • torch/_dynamo/aot_compile.py:1490-1508 — the entire cache-invalidation design serves a contract the class does not document. The weak references, the length-and-identity re-decision, the single-field publication, and the two threading tests all exist for exactly one scenario: an external caller mutating compiled_results between calls. But the class docstring (1473-1486) only ever describes reading it — "Dispatch walks compiled_results in order and serves the first result whose guard check accepts the call" — and never states that post-construction mutation is supported. I searched the repo: no production code mutates a compiled_results list post-construction; the only mutations are in tests added by this PR and its stack (test_aot_compile.py:2086, 2101, 2116, 2135, 2154), and the parent's test_module_dispatch_judges_only_the_results_a_call_began_with reaches the mid-dispatch mutation only through a mock-installed check(), not through real library machinery. There is no user-facing documentation for the field anywhere under docs/.

    That leaves two coherent positions, and the PR should pick one explicitly rather than implying the first while documenting neither:

    1. Mutation is supported — then say so in the class docstring, since every line of _binds_alike and both threading tests are load-bearing only under that promise, and a future reader deleting the cache has no way to know what they are breaking.
    2. Mutation is not supported — then decide the verdict once at construction, document post-construction mutation as unsupported, and the weakrefs, the re-decision, and the two 40-line threading tests all go away.

    For a class the docstring itself calls "Private and experimental", the second is the far cheaper design. As written, 58 source lines and 242 test lines defend a path nothing exercises.

Thread Safety

  • torch/_dynamo/aot_compile.py:1495-1497 — the atomicity invariant the design rests on is argued only in the PR description, not in the code. The reasoning for one field over two is genuinely correct (I traced both interleavings and they hold), but the comment compresses it to "one field, so no reader pairs the verdict with another list's contents", which states the conclusion and not the premise. The premise is that a single attribute store publishes the (contents, verdict) pair indivisibly, so a reader sees the old pair or the new one and never a mix. That premise is a CPython guarantee about instance-dict stores, and it is the reason the field must never be split — exactly the thing a future refactor would break. PR descriptions do not survive into the repo; per CLAUDE.md this is the kind of "non-obvious global context that can't be inferred locally" a comment is for. State the invariant in one line at the field.

    Related: the checklist calls out GIL-reliant correctness for free-threaded builds. The store-atomicity premise does still hold there (free-threaded dict stores are internally locked), so this is not a bug — but since the design is explicitly built around store atomicity, the comment should name it rather than leave a NoGIL reader to re-derive it.

Testing

  • test/dynamo/test_aot_compile.py:2144-2225 — the two threading tests fail by hanging rather than by asserting. Both park a thread on release.wait() with no timeout and gate progress on entered.wait(timeout=60). The addCleanup(release.set) ordering correctly prevents a leaked thread on assertion failure, but if the parking point ever stops being reached — precisely the regression these tests exist to catch — the test burns 60 seconds before failing. Given these are two of only a handful of concurrency tests in the file, a shorter timeout would turn a slow CI job into a fast, legible failure.

Performance

  • torch/_dynamo/aot_compile.py:1516-1520 — the single-result case, which is the dominant one, is now pure overhead. With one compiled result the parent built exactly one binding; this change builds exactly one binding plus an attribute load, a length compare, and a weakref dereference through _binds_alike on every dispatch. There is no bind to save, because there was never more than one. aot_compile_module with a single ModelInput and every deserialize-of-a-single-result path land here. The PR's own measurements corroborate the direction: "a match at [0] ... measures 23.0us against 23.0us at two inputs and 23.5us against 22.0us at four" — flat at best, a regression at worst, and that is before counting N=1. An early-out (len(results) == 1 binds directly and skips the verdict entirely) recovers the parent's cost for the common case and costs one comparison for the multi-result case this PR is actually optimizing. Fix this →

Code Quality

  • torch/_dynamo/aot_compile.py:1522-1538 — the enumerate + bound[i] rewrite trades the parent's clearer zip for a saving that is noise. The two loops were restructured so that a shared binding appends nothing, defended as "a matching call allocates nothing for a pass it never reaches." Appending an existing reference to a list is tens of nanoseconds; the bind this PR is optimizing costs 2.39us and a passing check() 0.93us by the PR's own figures. Appending the shared dict unconditionally in the first loop restores for result, f_locals in zip(results, bound): verbatim, is behavior-equivalent on every path (early return, no match, empty results, shared and unshared), and drops the index arithmetic and the second ternary. Per CLAUDE.md's "choose the simpler, more concise implementation," the zip shape is the one to keep. Fix this →

  • torch/_dynamo/aot_compile.py:1455-1456 — _ParamKey and _BindingKey are each used exactly once, in the signature of the function immediately below them. The checklist flags premature abstraction and one-use helpers; inlining the return type (or dropping the aliases) removes two names from module scope without costing readability. Relatedly, _BindingKey names a "key" whose first and third members are list, making it unhashable — harmless since it is only ever compared with ==, but the name promises something the type does not deliver. Tuples cost nothing here and make the alias honest.

Recommendation

Needs Discussion

The optimization is well-motivated and the sharing premise is correct — I independently verified in torch/csrc/dynamo/guards.cpp that RootGuardManager::check_nopybind_template (4368-4417) neither writes into the mapping it is handed nor caches a verdict keyed on it: recording state is cleared at entry (4377), _dict_tag and _dict_pointers are per-manager members (4264-4270), and relational state resets on every exit. So passing one f_locals to N guard trees, twice each, is safe, and the _binding_key design correctly avoids Signature.__eq__ and the tensor-default explosion it causes.

What blocks approval is scope rather than correctness. The mutation contract question under API Design decides how much of this change should exist at all — answering it may delete most of the diff, so it should be settled before the rest is polished. The N=1 regression is worth fixing regardless of how that lands.

· branch [`gh/bobrenjc93/1198/head`](https://github.com/pytorch/pytorch/tree/gh/bobrenjc93/1198/head)

[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 52s —— View job


Reviewed — the sharing itself is sound (I verified in guards.cpp that check() neither mutates the f_locals it is handed nor caches a verdict keyed on it, so one binding for N guard trees is safe), but the read-only contract that safety rests on is nowhere stated, and several new tests assert on private internals rather than on dispatch behavior.

Full review

PR Review: #197071

Summary

Caches a "do all results bind alike" verdict on AOTCompiledModel so a dispatch call builds one prepare_f_locals binding and reuses it across the guard scan and the re-check, instead of binding once per result. The optimization is correct and the invalidation logic holds under both interleavings I traced, but the cross-result safety invariant is undocumented, the single-result case regresses, and the test suite pins private structure.

Thread Safety

  • torch/_dynamo/aot_compile.py:1514-1523 — _binds_alike publishes its verdict without holding a lock, and two threads that decide concurrently can each publish, but only one of the two published pairs describes the list a third caller is about to iterate. The single-field design correctly rules out the mixed pair (I traced both interleavings the description names and they do hold). What it does not rule out is lost-update: thread A decides over (r0, r1), thread B decides over (r0, r1, r2), B stores, A stores, and the field now claims A's shorter contents. That is not a correctness bug — the next call finds a length mismatch and re-decides — but it means the cache can thrash indefinitely under concurrent dispatch on a mutating list, silently paying a _binding_key per result per call, which is the exact cost the cache exists to avoid. Worth a line in the field comment saying the field is a hint, not a lock, so the last writer wins and a contended model just re-decides.

  • torch/_dynamo/aot_compile.py:1538-1539 — the invariant that makes sharing safe at all is not stated anywhere in the file. Reusing bound[0] across N distinct RootGuardManager trees, and again in the re-check pass at 1554, is only correct because guard evaluation treats the mapping as read-only. I verified this holds today: RootGuardManager::check_nopybind_template (torch/csrc/dynamo/guards.cpp:4368-4417) contains no PyDict_SetItem/PyDict_DelItem on the passed mapping, the root is constructed non-dict (4329) so no _dict_tag is ever recorded against the f_locals dict, the tag-safe fast path that does cache pointers lives in GuardManager::check_nopybind which the root overrides and bypasses (4419-4425), and relational state (NO_TENSOR_ALIASING::_unique_tensors, OBJECT_ALIASING, SYMBOLIC_SHAPE_GUARD::_args_seen) is reset on entry (4377) and on all four exits (4386, 4401, 4409, 4415) including the early no-tensor-aliasing refuse. But nothing in aot_compile.py records that the sharing depends on it, and nothing in guards.cpp promises it. A future leaf guard that writes into the mapping — or a LAMBDA_GUARD body that got a handle on L — would silently make result[1] check a dict result[0] modified, and the failure would surface as a wrong graph served, not a crash. Per CLAUDE.md, this is exactly the "non-obvious global context that can't be inferred locally" a comment is for: one line at 1538 stating that guard evaluation must not mutate f_locals, which is why one dict can serve every tree.

Performance

  • torch/_dynamo/aot_compile.py:1536-1537 — the single-result case, the common one, is pure overhead. With one compiled result the parent built exactly one binding; this builds one binding and nothing else changes — but the shared is None test is evaluated on every iteration of the scan rather than once, so the multi-result scan pays a redundant is None check per result after the first. More importantly, for len(results) == 1 there is no bind to save and no verdict worth deciding, yet the code still carries the shared variable and the per-iteration branch through the only path most models ever take. aot_compile_module with a single ModelInput, and every deserialize of a single-result artifact, land here. Hoisting the decision out of the loop — decide once before iterating when len(results) > 1, and skip it entirely otherwise — removes the per-iteration branch and makes the N=1 path identical to the parent's. Fix this →

Testing

  • test/dynamo/test_aot_compile.py:2187 and :2227 — the worker-side waits in both threading tests are unbounded. release.wait() has no timeout, and the decider.join() calls at :2196/:2203/:2239/:2248 are likewise unbounded. The addCleanup ordering is correct (LIFO, release.set registered second so it fires before join), so an assertion failure inside the with block does release the worker. But if the parking point stops being reached for any reason other than a clean assertion failure, the worker blocks forever and the test hangs rather than failing. release.wait(timeout=...) costs nothing and converts a hang into a legible failure.

  • test/dynamo/test_aot_compile.py:2248 — decider.join() runs unconditionally, but decider.start() only happens inside the patched racing callback at :2237. If dispatch ever stops calling _binds_alike on this path, racing never runs, the RuntimeError is still raised by [1]'s own guards so assertRaisesRegex at :2246 passes, and the test then dies at :2248 with cannot join thread before it is started — a confusing failure for a test that has silently stopped exercising the race it exists to test. Assert decider.is_alive() or gate the join on decider.ident.

  • test/dynamo/test_aot_compile.py:2190 and :2220 — neither threading test captures exceptions raised in the worker thread. If _binds_alike raises inside decider, threading prints to stderr and the test still passes green, because entered may already have been set before the raise. Record the exception on the closure and re-raise it after join.

  • test/dynamo/test_aot_compile.py:2065 — assertEqual(len(binds), 1) is only a real assertion if all four results are actually scanned. Nothing in the test asserts len(compiled.compiled_results) == 4, nor that xs[3] is served by compiled_results[3]. If compilation ever collapses the four dtypes into fewer results, the count degenerates to 1 either way and the test passes vacuously. Assert the result count, or assert binds == [compiled.compiled_results[0]], which pins both the count and which result was bound.

  • test/dynamo/test_aot_compile.py:2081 — assertEqual(combined._binding_verdict, ((), False)) hardcodes the field's internal tuple shape while its only writer is mocked out. With _binds_alike patched, nothing can write the field, so the assertion can essentially only fail if unrelated code writes it; verdict.assert_not_called() at :2078 already carries the laziness claim this test is about. Meanwhile the literal ((), False) breaks the moment the field gains a third element or becomes a named tuple, for no behavioral reason.

  • test/dynamo/test_aot_compile.py:2458 and :2488 — both assert assertFalse(loaded._binds_alike(...)), pinning a known false negative as expected behavior. The PR description is explicit that per-result binding after deserialize is an accepted limitation (each blob unpickles through its own AOTCompileUnpickler, so equal defaults come back as distinct objects). Asserting False here means that if serialization is ever improved to share the memo, these two tests go red despite the change being strictly better. Assert the observable behavior — that the loaded model answers correctly for both inputs, which the following lines already do — and drop the verdict assertion, or comment it as intentionally pinning a limitation so a future author knows it is safe to flip.

  • test/dynamo/test_aot_compile.py:2108-2109, :2122-2123, :2176-2177, :2215-2216 — the four-line mod, x = ScaleModule(), torch.randn(3, 3) plus triples, doubles = make_mode_default_forward(1), make_mode_default_forward(0) setup is repeated verbatim four times. Per the checklist's "no duplicated test logic," this should be one helper returning the assembled model.

  • test/dynamo/test_aot_compile.py:611 — mask=torch.ones(3) is a module-global tensor evaluated at import and shared as a parameter default across every test in the file. Any test that mutates it in place leaks into the others. Harmless today since nothing writes to it, but a torch.ones(3) constructed inside the class body is a shared mutable global by construction.

Code Quality

  • torch/_dynamo/aot_compile.py:1501-1512 — an eleven-line comment on one field, arguing a design alternative rather than stating the invariant. Most of it justifies why the field is one field instead of two ("two fields have no store order that keeps them consistent"), which is a defense of a decision against an alternative that does not exist in the code. CLAUDE.md asks for comments that "remind the reader about some global context that is non-obvious and can't be inferred locally" and for minimal comments otherwise. The load-bearing facts are: the pair must be published by a single store, weak references so nothing is retained, and the default is the empty verdict. That is three lines. The rebuttal of the two-field design belongs in the commit message, where it already is.

  • torch/_dynamo/aot_compile.py:1461-1463 — _binding_key builds list comprehensions inside tuple() rather than generator expressions. tuple([...]) materializes an intermediate list on a path the PR describes as costing ~1.0us per result and calls once per result when deciding. tuple(... for ...) is the idiomatic form and avoids the intermediate.

  • torch/_dynamo/aot_compile.py:1455-1464 — _binding_key returns tuple[object, ...], which erases the structure the function's own comment describes. The three members have concrete types (a tuple of name/kind/id triples, a co_freevars tuple, a tuple of ids); typing the return as tuple[object, ...] means a caller comparing two keys gets no help from the checker, and the id()-based members — the subtle part, since they make the key identity-sensitive and unhashable-by-intent — are invisible in the signature. Either spell the tuple out or name it.

Recommendation

Needs Discussion

The optimization is well-motivated and I independently confirmed the premise it rests on. Two things should be settled before merge: the undocumented read-only contract on f_locals under Thread Safety, since that is the invariant a future guards.cpp change could silently break with a wrong-graph-served failure mode; and the unbounded worker waits plus the unconditional join at test_aot_compile.py:2248, which turn the two tests that guard the trickiest part of this change into potential hangs and misleading errors. The vacuous-assertion issues at :2065 and :2081 weaken the coverage claim for the central behavior and are cheap to strengthen.

Note: I could not run the test suite in this environment (no built PyTorch available to the review job), so all findings are from reading the code. The correctness claims about guards.cpp are from reading check_nopybind_template and its exits directly, not from execution.

· branch [`gh/bobrenjc93/1198/head`](https://github.com/pytorch/pytorch/tree/gh/bobrenjc93/1198/head)

@bobrenjc93 bobrenjc93 added ciflow/trunk Trigger trunk jobs on your pull request topic: not user facing topic category labels Sep 15, 2026
@bobrenjc93
bobrenjc93 marked this pull request as ready for review September 15, 2026 15:17
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@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
…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
…econd scanned result

A follow-up to #197071, which landed as first reviewed; this commit carries
what its review asked for and changes no behaviour: every call is served by
the same result or refused with the same error, and pays the number of binds
#197071 set. Against the landed code it restructures `AOTCompiledModel.__call__`
so the first result is bound and checked ahead of the scan and the
shared-binding verdict is asked exactly once, after that result has refused
the call and only when there is a second result; it names `_binding_key`'s
return type `_BindingKey`; it shortens the `_binding_verdict` field comment to
the invariants and says the field is a hint, not a lock; it states above the
scan the read-only `f_locals` contract the sharing rests on; and it hardens
the tests: both interleaving tests bound every wait, record what the decider
raised and assert it was started, the binds-once test asserts which result
served and which one bound, the first-result test stops reading the private
field and gains a one-result half, the tensor-default forward is built per
test rather than as a module global, and the setup four tests repeated is one
helper.

Review order: `_BindingKey` and `_binding_key`, then the `_binding_verdict`
field comment, then `__call__` down to the re-check, then the tests.

`_binding_key` returned `tuple[object, ...]`, which says nothing about what a
key holds. `_BindingKey` spells its three members out -- parameters as name,
kind and default id, `co_freevars`, cell ids -- so the identity-sensitive
parts are visible in the signature; the body is unchanged, `tuple([...])`
over list comprehensions included (FAQ below).

The field comment argued against a two-field design in eleven lines. It now
states the invariants in six -- the contents are weak references so a dropped
result is not kept alive, one store publishes contents and verdict together
so a reader never sees one list's contents beside another's verdict, the
default is the verdict over no results -- and adds the one thing the landed
comment left unsaid: the field is a hint, not a lock. Two threads deciding at
once each publish a pair and the last writer wins, so a reader can find a
pair about a list other than the one it holds, decide again and publish
again, at a `_binding_key` per result and never at a wrong binding, since a
call binds from the verdict it decided or from a pair whose contents are the
results it holds. The two-field rebuttal stays in #197071's message.

In the landed `__call__` the scan tests `bound and shared is None` on every
iteration, and a single-result model runs that test for a served call and a
refused one alike. Now `results[0]` is peeled out of the loop: bound and
checked as at a single-result model and served on a match; only when it
refuses does `__call__` ask `_binds_alike` once, gated on `len(results) > 1`,
and scan the rest, reusing the first binding or binding each result on its
own. So a call `[0]` serves pays nothing for the sharing, a single-result
model never consults the verdict whether it serves or refuses, and the scan
tests no per-result branch about the verdict.
`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`,
the next call, which `[0]` refuses, calls it once -- and, new here, on a
one-result model, where neither a served nor a refused call calls it. Every
binding, shared or not, is still appended once per result, so the re-check
zips `results` with `bound` as before, and the opt-out stage below it is
untouched. This is a restructure, not a speedup: measured on the machine
#197071's figures come from, the landed `__call__` and this one exec'd from
source into subclasses over the same results and timed in alternation, best
of 9, min of two rounds, a match at `[1]` of two costs 17.5us against 17.9us,
a match at `[3]` of four 20.5us against 20.7us, and a no-match call that
raises 23.5us against 23.3us at two results and 27.8us against 27.5us at
four, all within noise; the per-iteration test the review pointed at costs
tens of nanoseconds. A match at `[0]` of one result, which now runs the
statements the code before #197071 ran in their order, costs 15.1us against
14.6us for that code.

Handing one dict to N guard trees is sound only because `check()` reads the
mapping it is given and never writes it, and the comment above the scan now
says so: a future leaf guard that stored into `f_locals` would make `[1]`
check a dict `[0]` had changed, and that would surface as a wrong graph
served, not as a crash. Today `torch/csrc/dynamo/guards.cpp` has no
`PyDict_SetItem`, `PyDict_DelItem` or `PyObject_SetItem` call at all, so
`RootGuardManager::check_nopybind_template` cannot store into the mapping it
is passed, and the relational guard state that could carry one tree's view
into the next (`NO_TENSOR_ALIASING`, `OBJECT_ALIASING`, the symbolic shape
guard's `_args_seen`) is reset on entry and on every one of its four exits,
the early no-tensor-aliasing refusal included.

The tests change as follows.
`test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature`
asserted `len(binds) == 1`, which a model that compiled fewer results than
the four it asked for would also satisfy; it now asserts four results, that
`[3]`'s `fn` served the call (`patch.object(..., wraps=)`) and that
`binds == [results[0]]`. The first-result test asserted
`combined._binding_verdict == ((), False)`, hardcoding the private tuple; the
mock on `_binds_alike` carries the laziness claim, so the assertion is gone
and the one-result half is added. Both interleaving tests waited without
bound: the decider now parks for at most 10s and the test waits at most 10s
for it to park, so a decider that never reaches its parking point fails the
test in seconds and no `join` can hang; the decider is a `RecordedThread`,
which keeps what its target raised so the test fails on it after the join
instead of `threading` printing it to stderr; and the old-contents test
asserts the decider was started before joining it, since only the patched
`_binds_alike` starts it and a dispatch that stopped consulting the verdict
would still raise the error the test expects. `TensorDefaultModule` held its
`mask=torch.ones(3)` default as a module global shared across the file;
`make_masked_forward()` builds the forward per test on a bare
`torch.nn.Module`. The two shared-binding round-trip tests keep their
`assertFalse(loaded._binds_alike(...))`, now commented as pinning the accepted
limitation -- each blob unpickles through its own `AOTCompileUnpickler`, so
equal defaults and cells come back as distinct objects -- that a load sharing
one memo across the blobs is free to flip. `compile_mode_defaults` is the two
`mode`-default results four tests built by hand.

> **FAQ: Can two threads deciding at once leave the cache re-deciding on every
> call?** Only while the list is being edited under them: two deciders over
> the same contents publish the same pair, and a pair about other contents is
> found stale by the next call, which decides once more and publishes. Each
> such decision costs a `_binding_key` per result, about 1.0us, and none of
> them can produce a wrong binding, since a call binds from the verdict it
> decided or from a pair whose contents are the results it holds. A lock would
> put an acquire on every call `[0]` refuses to spare a re-decision that only a
> concurrent edit of `compiled_results` can cause.

> **FAQ: Why does `_binding_key` still build `tuple([...])` over list
> comprehensions rather than `tuple(...)` over generators?** Because it is
> faster: measured on the same artifact, best of 9 over 200000 calls, run
> twice, the shipped form costs 0.99us per key and the generator form 1.33us;
> for these sizes the list a comprehension builds is cheaper than a generator
> frame. The key is computed once per result on every re-decision, which is
> the cost the cache exists to bound, so the idiomatic form was not taken.

Test Plan:

```
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_a_call_once_for_results_sharing_a_signature
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 -k test_module_dispatch
python test/dynamo/test_aot_compile.py
lintrunner --take RUFF,PYFMT torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py
```

This commit adds no test; the full file runs 205 tests and passes (6 skipped),
as at the parent, and `-k test_module_dispatch` runs 19. Behaviour is
unchanged, so all 19 also pass with the landed `torch/_dynamo/aot_compile.py`
under this commit's test file; what the tests pin is the shape, by mutation,
each run against the 19 and each failing only the tests named: dropping the
`len(results) > 1` gate fails the first-result test through its one-result
half with `Expected '_binds_alike' to not have been called. Called 1 times`,
and deciding ahead of the first result fails it the same way through the
two-result half; never consulting `_binds_alike` fails the binds-once test
with `The length of the sequences mismatch: 4 != 1`, the first-result test
with `Called 0 times` and the old-contents test at its started-decider
assertion with `unexpectedly None`, where the landed test died on `cannot
join thread before it is started`. The mutation controls in #197071's message
concern code this commit does not change and were not re-run. Lint is clean.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: cd50e86
Pull-Request: #197133
bobrenjc93 added a commit that referenced this pull request Sep 15, 2026
…h matches

Once module dispatch found no match, `AOTCompiledModel.__call__` fell through
to `compiled_results[0]`, so the user saw whatever that one artifact's guard
manager said -- with several compiled inputs, a failure report about the first
one only, and no sign that the others existed or why they did not match. The
dispatch commits below made the dispatch itself scan every result, re-check
every result and serve an opted-out result before giving up, and kept that
fall-through as the raise. This commit replaces it with a report that names
every compiled input, built from the binding the dispatch already judged.

This commit and `[aot_compile] Keep a no-match report entry to one line that
says what its guards answered` (#<sibling>, the next commit) were one commit,
split for review budget: the sibling owns what an entry's line holds when its
guards' verbose parts are empty or carry a line boundary, and this commit is
the rest of the report.

The raise carries one line per compiled input, and closes with what to do about
it: add a `ModelInput`, or check whether `guard_filter_fn` KEPT a guard this
call cannot satisfy. That last phrasing matters -- a guard the filter DROPPED
cannot make a call fail to match, so the reverse advice sent the reader looking
in the wrong place. Both levers are the capturing process's, and this report is
reachable from a process that only loaded an artifact (nothing on
`_load_aot_compiled_module` takes either), so the line says so rather than
implying the reader holds them.

When a guard died on a global the process does not have, the report adds a line
prefixed `For [i]: `, with the index of the entry the hint is about, carrying
the function path's own `_missing_global_hint` for that entry -- the sentence
worded for the scope its guards were resolved against (CAPTURED, SUPPLIED or
RECONSTRUCTED), so the two paths say the same thing about the same scope. The
parent already delivered that hint on the module path, appended to the
fall-through's `GuardManager check failed` message for `[0]`, and five tests
below (`test_aot_compile_module_missing_global_hint_names_the_resolved_module`
and the four `deserialize_refuses_*` / `fallback_scope_hint` tests) assert its
text through a module call; a report without the hint fails all five, so the
hint is part of this commit rather than a follow-up. The helper now returns a
bare sentence and each caller adds its own lead-in: the function path, which
continues a line of its own, adds ` -- ` at its one call site in
`AOTCompiledFunction.__call__`, so its message is byte-identical to the
parent's (`test_aot_compile_fn_missing_global_hint_names_the_tracing_scope`
keeps asserting `) -- a guarded global is missing`), and the report's
`For [i]: ` prefix makes the line self-locating rather than an unindented
fragment between the entries and the footer. The report carries at most one
such line, read off the FIRST entry that failed on a missing global, and the
class docstring says so. For a model `deserialize` built, every entry shares
that scope, since `deserialize` hands them all one `guard_globals`; the public
constructor accepts results of differing scopes, and there the hint is worded
for whichever such entry came first, while every entry line already carries
the name it failed on. The SUPPLIED wording is the parent's, unchanged: `the
live scope this artifact was loaded against, here vars(<module>)`. Naming the
instance's `forward` there, for a load whose guards hold the dict that
attribute resolves to, is #197048's, above the sibling.

The advice and that hint are independent, so a report every entry of which named
a missing global carries both. Withholding the advice there would assume a new
`ModelInput`'s guards must fail on the same absent name, which only holds when
every path of `forward` reads that global: an entry fails on a global because
ITS tree reads it, and an input captured for the branch this call takes need not
read it at all -- such an input is captured and served with the name still
undefined. Withholding also makes the only actionable line in the report turn on
whether an unrelated global happens to be defined, and that masking is easy to
hit, since guards are installed in `sorted(guards)` order and
`GuardSource.LOCAL` sorts before `GLOBAL`, which sorts before
`LOCAL_UNSPECIALIZED_NN_MODULE`: the root's `G` accessor fails before an
`nn.Module` attribute guard runs, so the mismatch the reader needs to hear about
is hidden behind the `KeyError`. The report cannot tell the two shapes apart and
the advice is already hedged, so it is emitted next to the hint rather than in
place of it.

An entry's line quotes the guards `check_verbose` named, joined with `; `, and
one of its answers names none while meaning the opposite of a failure: a tree
that ACCEPTS the call. Both dispatch passes rejected it and `check_verbose`,
which never takes the dict-tag fast path, accepts it, so either a guard here
does not answer consistently between evaluations or a still-armed tag-safe root
neither rejection reached refused from its own fast path -- the
`check_dict_pointer_tags` branch of `GuardManager::check_nopybind` in
guards.cpp, where `check_no_tensor_aliasing_guards_fast` answering false sets
`_disable_dict_tag_matching` and returns false before the tree runs. That is
not a match to serve, and quoting the guards it just passed as a reason the
call failed would name the wrong thing, so the entry says what happened
instead. `GuardDebugInfo.user_stack` and `num_guards_executed` are dropped on
purpose: the verbose part usually embeds `# <source> # file:line in forward`
already, the stack is `None` for the `KeyError on G[...]` case this report
exists to explain, and one line per input is the point. A genuine failure can
also arrive with no parts, and a part can carry a boundary `splitlines()`
breaks on; here such an entry prints nothing after `[i]`, or spans several
lines, and the call is refused either way. What the line should say in those
two cases is the sibling's.

A describer that raises is not caught here. `check_verbose` runs paths
`check()` does not -- `DIMENSION_DYNAMIC_MARKING_GUARD` calls `py::repr` on
user objects, and a `TENSOR_MATCH` failure on a tensor of the compiled type
calls `is_parameter`, which runs `_ParameterMeta.__instancecheck__` -- so an
entry's describer can raise where the dispatch's rejection was clean, and when
it does the exception escapes the `raise RuntimeError(...)` argument and takes
the report with it, exactly as it escaped the parent's fall-through, whose
`AOTCompiledFunction.__call__` runs the same `check_verbose` unguarded. An
earlier revision ran each entry's `check_verbose` under its own `try` and
described the other entries anyway; that catch is unsound below #197049 and
the lines it saved were wrong (FAQ below), so it is gone from here, and the
place a raising tree is read as no answer and reported as one line is #196826,
above the TorchFunction restore #197049 adds.

Two calls the fall-through handled differently are refused by the report, and
that is intended:

- A tree that rejected the call in both dispatch passes and accepts it on a
  third evaluation. PARENT: for `[0]` only, the fall-through's
  `AOTCompiledFunction.__call__` evaluated its guards a third time and served
  the graph when that evaluation accepted -- with a `CountedKey(misses=2)` in
  the slot of the one global `[0]`'s tree reads: `SERVED equal_to_x*3= True
  compares= 3`. HEAD: the report's `check_verbose` is that third evaluation, an
  accept there prints `[0] <guards rejected this call twice and then accepted
  it here ...>`, and the call raises: `RAISED compares= 3`. An accept that
  arrives only on the third evaluation is not a certified match, for the two
  reasons the entry names, and the parent extended that third chance to `[0]`
  alone, by its position; a result in any other slot never had it.
  `test_no_match_message_when_a_guard_answers_inconsistently` pins the raise
  and the three evaluations.
- A model with no compiled results. PARENT: `AOTCompiledModel(mod, [])(x)`
  raised `IndexError: tuple index out of range` from `results[0]`. HEAD: the
  same `RuntimeError` report as any other no-match, with zero entries (`Tried 0
  compiled input(s):` and the footer). Measured by hand; no test pins it.

Otherwise the exception type stays `RuntimeError`, and the text `GuardManager
check failed` is replaced on the module path only: the function path's
`__call__` still raises it, and the five regexes this commit updates in
test_aot_compile.py belong to the dispatch tests below.

The report reuses the binding the dispatch judged, one per result, so it
explains the same binding rather than a fresh one, and the one bind per call
#197071 introduced holds end to end; the fall-through it replaces bound twice
more inside `AOTCompiledFunction.__call__`.
`test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature` now
also counts `prepare_f_locals` for a call nothing matches and expects one --
the fall-through fails that with `Expected 1 but got 3`. The same test counts
the report's entry lines -- one per result off that single bind -- rather than
its total line count, so a footer line added later does not break it. Measured
once when this report was first written, against the dispatch before the
one-bind-per-call commit and this commit, and not re-run since: a report costs
12.6us against the old 15.0us, and the no-match path costs 18.5us against
27.9us at one input and 29.9us against 33.0us at two, and crosses over by four,
50.9us against 41.3us, where the report's N `check_verbose` calls and the
re-check's N `check()` calls outweigh the binds saved; with one bind per call
rather than per result it costs 30.2us against 43.1us at four. That path ends
in a raise, and the match path is the one every call takes.

The report is handed the results the dispatch judged as well: `__call__` reads
`compiled_results` once, and the report indexes `bound` against that tuple
rather than re-reading a public list an append or a replacement can have
changed under it -- re-read, an appended result asks for a binding the dispatch
never made, and an `IndexError` raised inside the `raise RuntimeError(...)`
argument takes the report's place.
`test_no_match_report_names_the_results_the_dispatch_judged` makes `[0]`'s
`check()` splice a second result into the list mid-call and asserts the report
counts one input, with the second the next call's to judge.

The supplied-scope hint on an un-rebound load is pinned by #196825, a test-only
commit higher in the stack, which also pins that the advice above still reaches
a report whose only failure is a missing global. Folding that commit's test
lines down here would put a guarded global the loading process does not have in
the same commit as this report, which is the split this re-slice exists to
make; they land together in any case. Four more of the report's tests sit in
#197001, above #197048, since three of them pin that commit's forward naming:
that the hint stays scope-neutral for a caller-supplied `guard_globals=`, that
a CAPTURED result's report names no `forward` and never resolves it, that the
advice reaches a report whose every entry named a missing global, and that a
missing KEY inside a present global is not a missing global.

> **FAQ: an earlier revision ran each entry's `check_verbose` under its own
> `try`, so one raising describer did not cost the other entries their lines.
> Why is that gone?** Because below #197049 the catch continues on a thread the
> throw left broken, and the lines it saves are wrong.
> `RootGuardManager::check_verbose_nopybind` sets the TorchFunction TLS to
> `ALL_DISABLED` for its accessors and restores it on each of its return paths,
> not under RAII, so a `py::error_already_set` unwinding out of the tree skips
> the restore; `_reset_relational_guard_state()` is skipped the same way, and
> has no Python binding to call instead. Measured at that revision's tree with
> `_ParameterMeta.__instancecheck__` patched to raise -- the Python
> `is_parameter` reaches from `TENSOR_MATCH::check_verbose_nopybind`'s failure
> branch, the route a tensor subclass `__getattr__` takes -- on a two-input
> `ScaleModule` called with `x.double()`: the report arrived, `[0]` read `<guard
> check could not be described: RuntimeError(...)>`, and `[1]` read
> `GLOBAL_STATE changed: torch_function` instead of its dtype mismatch, since
> `[1]`'s tree was evaluated on the thread `[0]`'s throw had left disabled;
> after the report was caught, `torch._C._get_torch_function_state()` read
> `ALL_DISABLED` against `ENABLED` before the call, and `t + 1` on a
> `__torch_function__` subclass returned a plain `Tensor` without dispatching.
> Without the `try`, the same script raises `RuntimeError('user __getattr__
> raised')` out of `__call__` on this tree and on the parent's alike, and leaves
> the thread the same way -- an exposure `AOTCompiledFunction.__call__` has
> always had, which #197049 repairs inside `GuardManagerWrapper.check_verbose`
> for every caller. Fixing the C++ exit itself is outside this Python-only
> stack. So the catch belongs above the restore, in #196826, and the test that
> pinned it here, `test_no_match_report_describes_the_other_entries_when_one_raises`,
> goes with it.

> **FAQ: `test_no_match_message_when_a_guard_answers_inconsistently` asserts
> exactly 3 evaluations. Isn't that count a property of the guard tree's shape
> rather than of the dispatch?** The count is the pin: it says the report's
> `check_verbose` is the third evaluation of that tree and nothing evaluates it
> a fourth time to serve it, which is the behaviour the entry above describes.
> It does rest on the tree's shape -- one `DictGetItemGuardAccessor` rooted at
> the global, so one lookup per evaluation -- and on the dict-tag fast path not
> firing, which it cannot here because the probe's pop/insert bumped this
> module dict's version past the one the last accepting evaluation recorded
> (`_dict_tag` is stored only on an accept). A second accessor rooted at the
> same global would change the count and the `misses=2` premise together, and
> the test's comment now names both dependencies, so a reader who changes the
> tree knows what to re-derive; loosening the assertion to `>= 3` would stop
> pinning that the report evaluates it once.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_no_match_error
python test/dynamo/test_aot_compile.py -k test_no_match_message_keeps_the_advice_for_every_entry
python test/dynamo/test_aot_compile.py -k test_no_match_message_when_a_guard_answers_inconsistently
python test/dynamo/test_aot_compile.py -k test_no_match_report_names_the_results_the_dispatch_judged
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
```

The whole file runs 190 tests, `OK (skipped=6)`; the parent runs four fewer.
Every test above fails with the parent's `aot_compile.py` under this test file
(5/5): the three that assert on report text (`No AOT compiled graph matched this
call`, `[0] L['mode'] == 0`, `Tried 1 compiled input(s)`) find the
fall-through's `GuardManager check failed` message instead; the binding test's
no-match half counts `Expected 1 but got 3`; and the inconsistent-guard test
counts `Expected 3 but got 2` evaluations, since the fall-through's third
evaluation is of `[0]`, which fails on `L['mode']` before it reads the global.

`test_aot_compile_module_no_match_error` asserts that each of the two entries
is one line of the report -- the two lines after the header, with unindented
advice after them -- rather than that the whole report is four lines: reporting
an entry as `str(GuardDebugInfo)` instead of the joined one-line reason makes
line 2 read `result=...` and fails it, while an advice line a later commit
appends does not.

Withholding the advice when an entry named a missing global fails
`test_no_match_message_keeps_the_advice_for_every_entry` on `Add a
ModelInput`.

Reading `self.compiled_results` in the report again fails
`test_no_match_report_names_the_results_the_dispatch_judged` with `IndexError:
list index out of range` raised in place of the report.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 448d7a5
Pull-Request: #196823
pytorchmergebot pushed a commit that referenced this pull request Sep 15, 2026
…econd scanned result (#197133)

**Summary.** This is the follow-up #197071's review asked for, and it changes no
behaviour: every call is served by the same result or refused with the same
error, and pays the number of binds #197071 set. The landed dispatch loop tested
`bound and shared is None` on every iteration, so even a single-result model ran
a per-result branch about the shared-binding verdict on every call. The first
result is now bound and checked ahead of the loop, exactly as a single-result
model always was, and only when it refuses the call does `__call__` ask
`_binds_alike` once, gated on there being a second result, before scanning the
rest. Around that, `_binding_key`'s return type gets a name that spells out its
three identity-sensitive members, the `_binding_verdict` comment shrinks to the
invariants and says the field is a hint rather than a lock, and the scan states
the read-only `f_locals` contract that sharing one dict across N guard trees
rests on. The tests are hardened rather than added to: bounded waits and a
recorded exception in both interleaving tests, an assertion of which result
served and which one bound in the binds-once test, a one-result half for the
first-result test, and one helper for the setup four tests repeated.

Review order: `_BindingKey` and `_binding_key`, then the `_binding_verdict`
field comment, then `__call__` down to the re-check, then the tests.

## `__call__`: peel the first result out of the loop

```python
# landed (#197071)
bound, shared = [], None
for result in results:
    if bound and shared is None:                  # tested on EVERY iteration, single-result models included
        shared = self._binds_alike(results)
    f_locals = bound[0] if shared else result.prepare_f_locals(self.model, *args, **kwargs)
    bound.append(f_locals)
    if result._live_guard_manager().check(f_locals):
        return result.fn(self.model, *args, **kwargs)

# now
first = results[0]
f_locals = first.prepare_f_locals(self.model, *args, **kwargs)
if first._live_guard_manager().check(f_locals):
    return first.fn(self.model, *args, **kwargs)  # served by [0]: the verdict is never consulted
bound = [f_locals]
shared = len(results) > 1 and self._binds_alike(results)   # asked ONCE, only after [0] refused
for result in results[1:]:
    if not shared:
        f_locals = result.prepare_f_locals(self.model, *args, **kwargs)
    bound.append(f_locals)
    if result._live_guard_manager().check(f_locals):
        return result.fn(self.model, *args, **kwargs)
```

So a call `[0]` serves pays nothing for the sharing, a single-result model
never consults the verdict whether it serves or refuses, and the scan tests no
per-result branch about the verdict.
`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`; the
next call, which `[0]` refuses, calls it once) and, new here, on a one-result
model, where neither a served nor a refused call calls it:

```python
single = AOTCompiledModel(mod, results[:1])
with patch.object(AOTCompiledModel, "_binds_alike", ...) as verdict:
    single(xs[0])                                               # served
    with self.assertRaisesRegex(RuntimeError, "GuardManager check failed"):
        single(xs[1])                                           # refused
    verdict.assert_not_called()                                 # neither asked
```

Every binding, shared or not, is still appended once per result, so the
re-check zips `results` with `bound` as before, and the opt-out stage below it
is untouched. This is a restructure, not a speedup: measured on the machine
#197071's figures come from, the landed `__call__` and this one exec'd from
source into subclasses over the same results and timed in alternation, best of
9, min of two rounds:

| call | landed | this commit |
|---|---|---|
| match at `[1]` of two | 17.9us | 17.5us |
| match at `[3]` of four | 20.7us | 20.5us |
| no match, two results (raises) | 23.3us | 23.5us |
| no match, four results (raises) | 27.5us | 27.8us |
| match at `[0]` of one result | 14.6us (pre-#197071 code) | 15.1us |

All within noise; the per-iteration test the review pointed at costs tens of
nanoseconds. The one-result row now runs the statements the code before
#197071 ran, in their order.

## Why one dict can serve N guard trees

Handing one `f_locals` to N guard trees is sound only because `check()` reads
the mapping it is given and never writes it, and the comment above the scan now
says so: a future leaf guard that stored into `f_locals` would make `[1]` check
a dict `[0]` had changed, and that would surface as a wrong graph served, not
as a crash. Today `torch/csrc/dynamo/guards.cpp` has no `PyDict_SetItem`,
`PyDict_DelItem` or `PyObject_SetItem` call at all, so
`RootGuardManager::check_nopybind_template` cannot store into the mapping it
is passed, and the relational guard state that could carry one tree's view
into the next (`NO_TENSOR_ALIASING`, `OBJECT_ALIASING`, the symbolic shape
guard's `_args_seen`) is reset on entry and on every one of its four exits, the
early no-tensor-aliasing refusal included.

## `_BindingKey` names what a key holds

```python
# landed
def _binding_key(artifacts: CompileArtifacts) -> tuple[object, ...]: ...

# now: parameters as (name, kind, default id), co_freevars, closure cell ids
_BindingKey = tuple[tuple[tuple[str, int, int], ...], tuple[str, ...], tuple[int, ...]]
def _binding_key(artifacts: CompileArtifacts) -> _BindingKey: ...
```

`tuple[object, ...]` says nothing about what a key holds. `_BindingKey` spells
its three members out so the identity-sensitive parts are visible in the
signature; the body is unchanged, `tuple([...])` over list comprehensions
included (FAQ below).

## The field comment: invariants, and "a hint, not a lock"

The field comment argued against a two-field design in eleven lines. It now
states the invariants in six: the contents are weak references so a dropped
result is not kept alive, one store publishes contents and verdict together so
a reader never sees one list's contents beside another's verdict, and the
default is the verdict over no results. It adds the one thing the landed
comment left unsaid: the field is a hint, not a lock.

```python
# two threads decide at once over the same list: each publishes a pair, the last writer wins
# a reader finds a pair about OTHER contents: it decides again (one _binding_key per result, ~1.0us each)
#                                              and publishes again -- never binds from a wrong verdict,
#                                              since a call binds from the verdict it decided or from a
#                                              pair whose contents are the results it holds
```

The two-field rebuttal stays in #197071's message.

## The tests, hardened

- `test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature`
  asserted `len(binds) == 1`, which a model that compiled fewer results than
  the four it asked for would also satisfy. It now asserts four results, that
  `[3]`'s `fn` served the call (`patch.object(..., wraps=)`), and
  `binds == [results[0]]`.
- The first-result test asserted `combined._binding_verdict == ((), False)`,
  hardcoding the private tuple; the mock on `_binds_alike` carries the
  laziness claim, so the assertion is gone and the one-result half above is
  added.
- Both interleaving tests waited without bound. The decider now parks for at
  most 10s and the test waits at most 10s for it to park, so a decider that
  never reaches its parking point fails the test in seconds and no `join` can
  hang. The decider is a `RecordedThread`, which keeps what its target raised
  so the test fails on it after the join instead of `threading` printing it to
  stderr. The old-contents test asserts the decider was started before joining
  it, since only the patched `_binds_alike` starts it and a dispatch that
  stopped consulting the verdict would still raise the error the test expects:

  ```python
  class RecordedThread(threading.Thread):
      failure: Exception | None = None
      def run(self):
          try: super().run()
          except Exception as e: self.failure = e

  release.wait(timeout=10)            # in the parked decider
  self.assertIsNotNone(decider.ident) # it was started
  decider.join(); self.assertIsNone(decider.failure)
  ```

- `TensorDefaultModule` held its `mask=torch.ones(3)` default as a module
  global shared across the file; `make_masked_forward()` builds the forward
  per test on a bare `torch.nn.Module`.
- The two shared-binding round-trip tests keep their
  `assertFalse(loaded._binds_alike(...))`, now commented as pinning the
  accepted limitation (each blob unpickles through its own
  `AOTCompileUnpickler`, so equal defaults and cells come back as distinct
  objects) that a load sharing one memo across the blobs is free to flip.
- `compile_mode_defaults` is the two `mode`-default results four tests built
  by hand.

> **FAQ: Can two threads deciding at once leave the cache re-deciding on every
> call?** Only while the list is being edited under them: two deciders over
> the same contents publish the same pair, and a pair about other contents is
> found stale by the next call, which decides once more and publishes. Each
> such decision costs a `_binding_key` per result, about 1.0us, and none of
> them can produce a wrong binding, since a call binds from the verdict it
> decided or from a pair whose contents are the results it holds. A lock would
> put an acquire on every call `[0]` refuses to spare a re-decision that only a
> concurrent edit of `compiled_results` can cause.

> **FAQ: Why does `_binding_key` still build `tuple([...])` over list
> comprehensions rather than `tuple(...)` over generators?** Because it is
> faster: measured on the same artifact, best of 9 over 200000 calls, run
> twice, the shipped form costs 0.99us per key and the generator form 1.33us;
> for these sizes the list a comprehension builds is cheaper than a generator
> frame. The key is computed once per result on every re-decision, which is
> the cost the cache exists to bound, so the idiomatic form was not taken.

Test Plan:

```
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_a_call_once_for_results_sharing_a_signature
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 -k test_module_dispatch
python test/dynamo/test_aot_compile.py
lintrunner --take RUFF,PYFMT torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py
```

This commit adds no test; the full file runs 205 tests and passes (6 skipped),
as at the parent, and `-k test_module_dispatch` runs 19. Behaviour is
unchanged, so all 19 also pass with the landed `torch/_dynamo/aot_compile.py`
under this commit's test file; what the tests pin is the shape, by mutation,
each run against the 19 and each failing only the tests named: dropping the
`len(results) > 1` gate fails the first-result test through its one-result
half with `Expected '_binds_alike' to not have been called. Called 1 times`,
and deciding ahead of the first result fails it the same way through the
two-result half; never consulting `_binds_alike` fails the binds-once test
with `The length of the sequences mismatch: 4 != 1`, the first-result test
with `Called 0 times` and the old-contents test at its started-decider
assertion with `unexpectedly None`, where the landed test died on `cannot
join thread before it is started`. The mutation controls in #197071's message
concern code this commit does not change and were not re-run. Lint is clean.

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: #197133
Approved by: https://github.com/pytorchgreenlight
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
…h matches

Once module dispatch found no match, `AOTCompiledModel.__call__` fell through
to `compiled_results[0]`, so the user saw whatever that one artifact's guard
manager said -- with several compiled inputs, a failure report about the first
one only, and no sign that the others existed or why they did not match. The
dispatch commits below made the dispatch itself scan every result, re-check
every result and serve an opted-out result before giving up, and kept that
fall-through as the raise. This commit replaces it with a report that names
every compiled input, built from the binding the dispatch already judged.

This commit and the three above it -- `[aot_compile] Give the no-match report's
missing-global hint one For [i, j]: line per distinct sentence` (#197149), `[aot_compile]
Say when a no-match report entry's guards accepted the call the dispatch
refused` (#197150) and `[aot_compile] Keep a no-match report entry to one
line that says what its guards answered` (#197134) -- were one commit, split for
review budget. This commit is the report: the raise, the header, one line per
compiled input quoting the guards `check_verbose` named, the missing-global hint
the fall-through already gave, and the closing advice. The siblings own where
that hint sits, and what an entry's line holds when `check_verbose` names no
guard: because the tree accepted the call, because a failing accessor named
nothing, or because a part carries a line boundary.

The raise carries one line per compiled input, and closes with what to do about
it: add a `ModelInput`, or check whether `guard_filter_fn` KEPT a guard this
call cannot satisfy. That last phrasing matters -- a guard the filter DROPPED
cannot make a call fail to match, so the reverse advice sent the reader looking
in the wrong place. Both levers are the capturing process's, and this report is
reachable from a process that only loaded an artifact (nothing on
`_load_aot_compiled_module` takes either), so the line says so rather than
implying the reader holds them.

When an entry's guards died on a global the process does not have, its line
carries the function path's own `_missing_global_hint`, appended with ` -- `
exactly as the fall-through's `AOTCompiledFunction.__call__` appended it to
`[0]`'s `GuardManager check failed` message -- the sentence worded for the scope
that result's guards were resolved against (CAPTURED, SUPPLIED or
RECONSTRUCTED), so the two paths say the same thing about the same scope. The
hint is part of this commit rather than a follow-up because the parent already
delivered it on the module path and five tests below
(`test_aot_compile_module_missing_global_hint_names_the_resolved_module` and
the four `deserialize_refuses_*` / `fallback_scope_hint` tests) assert its text
through a module call; a report without it fails all five. Here it rides on
every entry that named a missing global, as the parent's message carried it for
`[0]`; giving the report one self-locating `For [i, j]:` line per distinct
sentence, naming the entries that share it, and the helper a bare sentence each
caller leads into, is #197149's, the next commit. The SUPPLIED wording is the parent's, unchanged: `the live
scope this artifact was loaded against, here vars(<module>)`. Naming the
instance's `forward` there, for a load whose guards hold the dict that attribute
resolves to, is #197048's, above the siblings.

The advice and that hint are independent, so a report every entry of which named
a missing global carries both. Withholding the advice there would assume a new
`ModelInput`'s guards must fail on the same absent name, which only holds when
every path of `forward` reads that global: an entry fails on a global because
ITS tree reads it, and an input captured for the branch this call takes need not
read it at all -- such an input is captured and served with the name still
undefined. Withholding also makes the only actionable line in the report turn on
whether an unrelated global happens to be defined, and that masking is easy to
hit, since guards are installed in `sorted(guards)` order and
`GuardSource.LOCAL` sorts before `GLOBAL`, which sorts before
`LOCAL_UNSPECIALIZED_NN_MODULE`: the root's `G` accessor fails before an
`nn.Module` attribute guard runs, so the mismatch the reader needs to hear about
is hidden behind the `KeyError`. The report cannot tell the two shapes apart and
the advice is already hedged, so it is emitted next to the hint rather than in
place of it.

An entry's line quotes the guards `check_verbose` named, joined with `; `.
`GuardDebugInfo.user_stack` and `num_guards_executed` are dropped on purpose:
the verbose part usually embeds `# <source> # file:line in forward` already,
the stack is `None` for the `KeyError on G[...]` case this report exists to
explain, and one line per input is the point. Three of `check_verbose`'s
answers leave that line saying nothing, or spread it over several lines, and
each is a sibling's. A tree that ACCEPTS the call both dispatch passes rejected
answers with no parts, so here its entry prints nothing after `[i]`; the call is
refused all the same, and what the entry should say about it is #197150's.
A genuine failure can also arrive with no parts, and a part can carry a
boundary `splitlines()` breaks on; here such an entry prints nothing after
`[i]`, or spans several lines, the call is refused either way, and those two
lines are #197134's.

A describer that raises is not caught here. `check_verbose` runs paths
`check()` does not -- `DIMENSION_DYNAMIC_MARKING_GUARD` calls `py::repr` on
user objects, and a `TENSOR_MATCH` failure on a tensor of the compiled type
calls `is_parameter`, which runs `_ParameterMeta.__instancecheck__` -- so an
entry's describer can raise where the dispatch's rejection was clean, and when
it does the exception escapes the `raise RuntimeError(...)` argument and takes
the report with it, exactly as it escaped the parent's fall-through, whose
`AOTCompiledFunction.__call__` runs the same `check_verbose` unguarded. An
earlier revision ran each entry's `check_verbose` under its own `try` and
described the other entries anyway; that catch is unsound below #197049 and
the lines it saved were wrong (FAQ below), so it is gone from here, and the
place a raising tree is read as no answer and reported as one line is #196826,
above the TorchFunction restore #197049 adds.

One call the fall-through served is refused by the report, and that is
intended: a tree that rejected the call in both dispatch passes and accepts it
on a third evaluation. PARENT: for `[0]` only, the fall-through's
`AOTCompiledFunction.__call__` evaluated its guards a third time and served the
graph when that evaluation accepted -- with a `CountedKey(misses=2)` in the
slot of the one global `[0]`'s tree reads: `SERVED equal_to_x*3= True
compares= 3`. HEAD: the report's `check_verbose` is that third evaluation, an
accept there leaves the entry with nothing after its index, and the call
raises: `RAISED compares= 3`. An accept that arrives only on the third
evaluation is not a certified match -- a guard that does not answer
consistently, or a tag-safe fast path that refused without running the tree --
and the parent extended that third chance to `[0]` alone, by its position; a
result in any other slot never had it. The entry that says so, and
`test_no_match_message_when_a_guard_answers_inconsistently`, which pins the
raise and the three evaluations, are #197150's. A model with no compiled
results is not a case this commit changes: `results[0]` at the top of
`__call__` raises `IndexError: tuple index out of range` before any stage runs,
on the parent and here alike.

Otherwise the exception type stays `RuntimeError`, and the text `GuardManager
check failed` is replaced on the module path only: the function path's
`__call__` still raises it, and the five regexes this commit updates in
test_aot_compile.py belong to the dispatch tests below.

The report reuses the binding the dispatch judged, one per result, so it
explains the same binding rather than a fresh one, and the one bind per call
#197071 introduced holds end to end; the fall-through it replaces bound twice
more inside `AOTCompiledFunction.__call__`.
`test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature` now
also counts `prepare_f_locals` for a call nothing matches and expects one bind
for it as for the matched call, `[results[0], results[0]]` -- the fall-through
fails that with `The length of the sequences mismatch: 4 != 2`, its no-match
call binding three times. The same test counts the report's entry lines -- one
per result off that single bind -- rather than its total line count, so a
footer line added later does not break it. Measured
once when this report was first written, against the dispatch before the
one-bind-per-call commit and this commit, and not re-run since: a report costs
12.6us against the old 15.0us, and the no-match path costs 18.5us against
27.9us at one input and 29.9us against 33.0us at two, and crosses over by four,
50.9us against 41.3us, where the report's N `check_verbose` calls and the
re-check's N `check()` calls outweigh the binds saved; with one bind per call
rather than per result it costs 30.2us against 43.1us at four. That path ends
in a raise, and the match path is the one every call takes.

The report is handed the results the dispatch judged as well: `__call__` reads
`compiled_results` once, and the report indexes `bound` against that tuple
rather than re-reading a public list an append or a replacement can have
changed under it -- re-read, an appended result asks for a binding the dispatch
never made, and an `IndexError` raised inside the `raise RuntimeError(...)`
argument takes the report's place.
`test_no_match_report_names_the_results_the_dispatch_judged` makes `[0]`'s
`check()` splice a second result into the list mid-call and asserts the report
counts one input, with the second the next call's to judge.

The supplied-scope hint on an un-rebound load is pinned by #196825, a test-only
commit higher in the stack, which also pins that the advice above still reaches
a report whose only failure is a missing global. Folding that commit's test
lines down here would put a guarded global the loading process does not have in
the same commit as this report, which is the split this re-slice exists to
make; they land together in any case. Four more of the report's tests sit in
#197001, above #197048, since three of them pin that commit's forward naming:
that the hint stays scope-neutral for a caller-supplied `guard_globals=`, that
a CAPTURED result's report names no `forward` and never resolves it, that the
advice reaches a report whose every entry named a missing global, and that a
missing KEY inside a present global is not a missing global.

> **FAQ: an earlier revision ran each entry's `check_verbose` under its own
> `try`, so one raising describer did not cost the other entries their lines.
> Why is that gone?** Because below #197049 the catch continues on a thread the
> throw left broken, and the lines it saves are wrong.
> `RootGuardManager::check_verbose_nopybind` sets the TorchFunction TLS to
> `ALL_DISABLED` for its accessors and restores it on each of its return paths,
> not under RAII, so a `py::error_already_set` unwinding out of the tree skips
> the restore; `_reset_relational_guard_state()` is skipped the same way, and
> has no Python binding to call instead. Measured at that revision's tree with
> `_ParameterMeta.__instancecheck__` patched to raise -- the Python
> `is_parameter` reaches from `TENSOR_MATCH::check_verbose_nopybind`'s failure
> branch, the route a tensor subclass `__getattr__` takes -- on a two-input
> `ScaleModule` called with `x.double()`: the report arrived, `[0]` read `<guard
> check could not be described: RuntimeError(...)>`, and `[1]` read
> `GLOBAL_STATE changed: torch_function` instead of its dtype mismatch, since
> `[1]`'s tree was evaluated on the thread `[0]`'s throw had left disabled;
> after the report was caught, `torch._C._get_torch_function_state()` read
> `ALL_DISABLED` against `ENABLED` before the call, and `t + 1` on a
> `__torch_function__` subclass returned a plain `Tensor` without dispatching.
> Without the `try`, the same script raises `RuntimeError('user __getattr__
> raised')` out of `__call__` on this tree and on the parent's alike, and leaves
> the thread the same way -- an exposure `AOTCompiledFunction.__call__` has
> always had, which #197049 repairs inside `GuardManagerWrapper.check_verbose`
> for every caller. Fixing the C++ exit itself is outside this Python-only
> stack. So the catch belongs above the restore, in #196826, and the test that
> pinned it here, `test_no_match_report_describes_the_other_entries_when_one_raises`,
> goes with it.

> **FAQ: an entry whose `check_verbose` ACCEPTS the call, or fails without
> naming a guard, prints nothing after `[i]` here, and a part carrying a line
> boundary spans several lines. Why not branch on `reason.result` and an empty
> `verbose_code_parts`, and collapse `splitlines()`, in this commit?** Because
> those branches are #197150's (the entry for a tree that accepted on the third
> evaluation) and #197134's (the entry for a failure that named no guard, and
> the one-line collapse), split out of this commit for review budget so that
> each lands next to the test that pins it and the report's plumbing here --
> the raise, the header, the per-entry join off the dispatch's own `bound` and
> `results`, the hint and the advice -- stays reviewable on its own; the call
> is refused all the same on every one of those answers, so nothing is served
> in the meantime that a sibling later refuses.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_no_match_error
python test/dynamo/test_aot_compile.py -k test_no_match_message_keeps_the_advice_for_every_entry
python test/dynamo/test_aot_compile.py -k test_no_match_report_names_the_results_the_dispatch_judged
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
```

The whole file runs 208 tests, `OK (skipped=6)`; the parent runs three
fewer. Every test above fails with the parent's `aot_compile.py` under this
test file (4/4): the three that assert on report text (`No AOT compiled graph
matched this call`, `[0] L['mode'] == 0`, `Tried 1 compiled input(s)`) find the
fall-through's `GuardManager check failed` message instead, and the binding
test sees four binds against the two it expects, `The length of the sequences
mismatch: 4 != 2`.

`test_aot_compile_module_no_match_error` asserts that each of the two entries
is one line of the report -- the two lines after the header, with unindented
advice after them -- rather than that the whole report is four lines, and that
each entry says something after its index: reporting an entry as
`str(GuardDebugInfo)` instead of the joined one-line reason makes line 2 read
`result=...` and fails it, printing `  [0] ` with nothing after the index fails
it with `entry says nothing: '  [0] '`, while an advice line a later commit
appends does not.

Withholding the advice when an entry named a missing global fails
`test_no_match_message_keeps_the_advice_for_every_entry` on `Add a
ModelInput`.

Reading `self.compiled_results` in the report again fails
`test_no_match_report_names_the_results_the_dispatch_judged` with `IndexError:
list index out of range` raised in place of the report.

`test_no_match_message_keeps_the_advice_for_every_entry` captures through
`_aot_compile_mode_branches`, whose `_hide_leaked_dynamo_globals` pops the
minted globals a sibling's capture leaked and strips this test's own in cleanup
(run alone in a fresh process, the inline capture it replaces left eight
minted names in this module's dict -- two `__builtins_dict___*`, two
`__compiled_fn_*` and four `__import_*` aliases; this form leaves none), and
it registers the `AOT_BRANCH_SCALE` restore with
`addCleanup` before deleting the name, so an interrupt anywhere leaves the
module dict whole.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 721d9ff
Pull-Request: #196823
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
…h matches

Once module dispatch found no match, `AOTCompiledModel.__call__` fell through
to `compiled_results[0]`, so the user saw whatever that one artifact's guard
manager said -- with several compiled inputs, a failure report about the first
one only, and no sign that the others existed or why they did not match. The
dispatch commits below made the dispatch itself scan every result, re-check
every result and serve an opted-out result before giving up, and kept that
fall-through as the raise. This commit replaces it with a report that names
every compiled input, built from the binding the dispatch already judged.

This commit and the three above it -- `[aot_compile] Give the no-match report's
missing-global hint one For [i, j]: line per distinct sentence` (#197149), `[aot_compile]
Say when a no-match report entry's guards accepted the call the dispatch
refused` (#197150) and `[aot_compile] Keep a no-match report entry to one
line that says what its guards answered` (#197134) -- were one commit, split for
review budget. This commit is the report: the raise, the header, one line per
compiled input quoting the guards `check_verbose` named, the missing-global hint
the fall-through already gave, and the closing advice. The siblings own where
that hint sits, and what an entry's line holds when `check_verbose` names no
guard: because the tree accepted the call, because a failing accessor named
nothing, or because a part carries a line boundary.

The raise carries one line per compiled input, and closes with what to do about
it: add a `ModelInput`, or check whether `guard_filter_fn` KEPT a guard this
call cannot satisfy. That last phrasing matters -- a guard the filter DROPPED
cannot make a call fail to match, so the reverse advice sent the reader looking
in the wrong place. Both levers are the capturing process's, and this report is
reachable from a process that only loaded an artifact (nothing on
`_load_aot_compiled_module` takes either), so the line says so rather than
implying the reader holds them.

When an entry's guards died on a global the process does not have, its line
carries the function path's own `_missing_global_hint`, appended with ` -- `
exactly as the fall-through's `AOTCompiledFunction.__call__` appended it to
`[0]`'s `GuardManager check failed` message -- the sentence worded for the scope
that result's guards were resolved against (CAPTURED, SUPPLIED or
RECONSTRUCTED), so the two paths say the same thing about the same scope. The
hint is part of this commit rather than a follow-up because the parent already
delivered it on the module path and five tests below
(`test_aot_compile_module_missing_global_hint_names_the_resolved_module` and
the four `deserialize_refuses_*` / `fallback_scope_hint` tests) assert its text
through a module call; a report without it fails all five. Here it rides on
every entry that named a missing global, as the parent's message carried it for
`[0]`; giving the report one self-locating `For [i, j]:` line per distinct
sentence, naming the entries that share it, and the helper a bare sentence each
caller leads into, is #197149's, the next commit. The SUPPLIED wording is the parent's, unchanged: `the live
scope this artifact was loaded against, here vars(<module>)`. Naming the
instance's `forward` there, for a load whose guards hold the dict that attribute
resolves to, is #197048's, above the siblings.

The advice and that hint are independent, so a report every entry of which named
a missing global carries both. Withholding the advice there would assume a new
`ModelInput`'s guards must fail on the same absent name, which only holds when
every path of `forward` reads that global: an entry fails on a global because
ITS tree reads it, and an input captured for the branch this call takes need not
read it at all -- such an input is captured and served with the name still
undefined. Withholding also makes the only actionable line in the report turn on
whether an unrelated global happens to be defined, and that masking is easy to
hit, since guards are installed in `sorted(guards)` order and
`GuardSource.LOCAL` sorts before `GLOBAL`, which sorts before
`LOCAL_UNSPECIALIZED_NN_MODULE`: the root's `G` accessor fails before an
`nn.Module` attribute guard runs, so the mismatch the reader needs to hear about
is hidden behind the `KeyError`. The report cannot tell the two shapes apart and
the advice is already hedged, so it is emitted next to the hint rather than in
place of it.

An entry's line quotes the guards `check_verbose` named, joined with `; `.
`GuardDebugInfo.user_stack` and `num_guards_executed` are dropped on purpose:
the verbose part usually embeds `# <source> # file:line in forward` already,
the stack is `None` for the `KeyError on G[...]` case this report exists to
explain, and one line per input is the point. Three of `check_verbose`'s
answers leave that line saying nothing, or spread it over several lines, and
each is a sibling's. A tree that ACCEPTS the call both dispatch passes rejected
answers with no parts, so here its entry prints nothing after `[i]`; the call is
refused all the same, and what the entry should say about it is #197150's.
A genuine failure can also arrive with no parts, and a part can carry a
boundary `splitlines()` breaks on; here such an entry prints nothing after
`[i]`, or spans several lines, the call is refused either way, and those two
lines are #197134's.

A describer that raises is not caught here. `check_verbose` runs paths
`check()` does not -- `DIMENSION_DYNAMIC_MARKING_GUARD` calls `py::repr` on
user objects, and a `TENSOR_MATCH` failure on a tensor of the compiled type
calls `is_parameter`, which runs `_ParameterMeta.__instancecheck__` -- so an
entry's describer can raise where the dispatch's rejection was clean, and when
it does the exception escapes the `raise RuntimeError(...)` argument and takes
the report with it, exactly as it escaped the parent's fall-through, whose
`AOTCompiledFunction.__call__` runs the same `check_verbose` unguarded. An
earlier revision ran each entry's `check_verbose` under its own `try` and
described the other entries anyway; that catch is unsound below #197049 and
the lines it saved were wrong (FAQ below), so it is gone from here, and the
place a raising tree is read as no answer and reported as one line is #196826,
above the TorchFunction restore #197049 adds.

One call the fall-through served is refused by the report, and that is
intended: a tree that rejected the call in both dispatch passes and accepts it
on a third evaluation. PARENT: for `[0]` only, the fall-through's
`AOTCompiledFunction.__call__` evaluated its guards a third time and served the
graph when that evaluation accepted -- with a `CountedKey(misses=2)` in the
slot of the one global `[0]`'s tree reads: `SERVED equal_to_x*3= True
compares= 3`. HEAD: the report's `check_verbose` is that third evaluation, an
accept there leaves the entry with nothing after its index, and the call
raises: `RAISED compares= 3`. An accept that arrives only on the third
evaluation is not a certified match -- a guard that does not answer
consistently, or a tag-safe fast path that refused without running the tree --
and the parent extended that third chance to `[0]` alone, by its position; a
result in any other slot never had it. The entry that says so, and
`test_no_match_message_when_a_guard_answers_inconsistently`, which pins the
raise and the three evaluations, are #197150's. A model with no compiled
results is not a case this commit changes: `results[0]` at the top of
`__call__` raises `IndexError: tuple index out of range` before any stage runs,
on the parent and here alike.

Otherwise the exception type stays `RuntimeError`, and the text `GuardManager
check failed` is replaced on the module path only: the function path's
`__call__` still raises it, and the five regexes this commit updates in
test_aot_compile.py belong to the dispatch tests below.

The report reuses the binding the dispatch judged, one per result, so it
explains the same binding rather than a fresh one, and the one bind per call
#197071 introduced holds end to end; the fall-through it replaces bound twice
more inside `AOTCompiledFunction.__call__`.
`test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature` now
also counts `prepare_f_locals` for a call nothing matches and expects one bind
for it as for the matched call, `[results[0], results[0]]` -- the fall-through
fails that with `The length of the sequences mismatch: 4 != 2`, its no-match
call binding three times. The same test counts the report's entry lines -- one
per result off that single bind -- rather than its total line count, so a
footer line added later does not break it. Measured
once when this report was first written, against the dispatch before the
one-bind-per-call commit and this commit, and not re-run since: a report costs
12.6us against the old 15.0us, and the no-match path costs 18.5us against
27.9us at one input and 29.9us against 33.0us at two, and crosses over by four,
50.9us against 41.3us, where the report's N `check_verbose` calls and the
re-check's N `check()` calls outweigh the binds saved; with one bind per call
rather than per result it costs 30.2us against 43.1us at four. That path ends
in a raise, and the match path is the one every call takes.

The report is handed the results the dispatch judged as well: `__call__` reads
`compiled_results` once, and the report indexes `bound` against that tuple
rather than re-reading a public list an append or a replacement can have
changed under it -- re-read, an appended result asks for a binding the dispatch
never made, and an `IndexError` raised inside the `raise RuntimeError(...)`
argument takes the report's place.
`test_no_match_report_names_the_results_the_dispatch_judged` makes `[0]`'s
`check()` splice a second result into the list mid-call and asserts the report
counts one input, with the second the next call's to judge.

The supplied-scope hint on an un-rebound load is pinned by #196825, a test-only
commit higher in the stack, which also pins that the advice above still reaches
a report whose only failure is a missing global. Folding that commit's test
lines down here would put a guarded global the loading process does not have in
the same commit as this report, which is the split this re-slice exists to
make; they land together in any case. Four more of the report's tests sit in
#197001, above #197048, since three of them pin that commit's forward naming:
that the hint stays scope-neutral for a caller-supplied `guard_globals=`, that
a CAPTURED result's report names no `forward` and never resolves it, that the
advice reaches a report whose every entry named a missing global, and that a
missing KEY inside a present global is not a missing global.

> **FAQ: an earlier revision ran each entry's `check_verbose` under its own
> `try`, so one raising describer did not cost the other entries their lines.
> Why is that gone?** Because below #197049 the catch continues on a thread the
> throw left broken, and the lines it saves are wrong.
> `RootGuardManager::check_verbose_nopybind` sets the TorchFunction TLS to
> `ALL_DISABLED` for its accessors and restores it on each of its return paths,
> not under RAII, so a `py::error_already_set` unwinding out of the tree skips
> the restore; `_reset_relational_guard_state()` is skipped the same way, and
> has no Python binding to call instead. Measured at that revision's tree with
> `_ParameterMeta.__instancecheck__` patched to raise -- the Python
> `is_parameter` reaches from `TENSOR_MATCH::check_verbose_nopybind`'s failure
> branch, the route a tensor subclass `__getattr__` takes -- on a two-input
> `ScaleModule` called with `x.double()`: the report arrived, `[0]` read `<guard
> check could not be described: RuntimeError(...)>`, and `[1]` read
> `GLOBAL_STATE changed: torch_function` instead of its dtype mismatch, since
> `[1]`'s tree was evaluated on the thread `[0]`'s throw had left disabled;
> after the report was caught, `torch._C._get_torch_function_state()` read
> `ALL_DISABLED` against `ENABLED` before the call, and `t + 1` on a
> `__torch_function__` subclass returned a plain `Tensor` without dispatching.
> Without the `try`, the same script raises `RuntimeError('user __getattr__
> raised')` out of `__call__` on this tree and on the parent's alike, and leaves
> the thread the same way -- an exposure `AOTCompiledFunction.__call__` has
> always had, which #197049 repairs inside `GuardManagerWrapper.check_verbose`
> for every caller. Fixing the C++ exit itself is outside this Python-only
> stack. So the catch belongs above the restore, in #196826, and the test that
> pinned it here, `test_no_match_report_describes_the_other_entries_when_one_raises`,
> goes with it.

> **FAQ: an entry whose `check_verbose` ACCEPTS the call, or fails without
> naming a guard, prints nothing after `[i]` here, and a part carrying a line
> boundary spans several lines. Why not branch on `reason.result` and an empty
> `verbose_code_parts`, and collapse `splitlines()`, in this commit?** Because
> those branches are #197150's (the entry for a tree that accepted on the third
> evaluation) and #197134's (the entry for a failure that named no guard, and
> the one-line collapse), split out of this commit for review budget so that
> each lands next to the test that pins it and the report's plumbing here --
> the raise, the header, the per-entry join off the dispatch's own `bound` and
> `results`, the hint and the advice -- stays reviewable on its own; the call
> is refused all the same on every one of those answers, so nothing is served
> in the meantime that a sibling later refuses.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_no_match_error
python test/dynamo/test_aot_compile.py -k test_no_match_message_keeps_the_advice_for_every_entry
python test/dynamo/test_aot_compile.py -k test_no_match_report_names_the_results_the_dispatch_judged
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
```

The whole file runs 208 tests, `OK (skipped=6)`; the parent runs three
fewer. Every test above fails with the parent's `aot_compile.py` under this
test file (4/4): the three that assert on report text (`No AOT compiled graph
matched this call`, `[0] L['mode'] == 0`, `Tried 1 compiled input(s)`) find the
fall-through's `GuardManager check failed` message instead, and the binding
test sees four binds against the two it expects, `The length of the sequences
mismatch: 4 != 2`.

`test_aot_compile_module_no_match_error` asserts that each of the two entries
is one line of the report -- the two lines after the header, with unindented
advice after them -- rather than that the whole report is four lines, and that
each entry says something after its index: reporting an entry as
`str(GuardDebugInfo)` instead of the joined one-line reason makes line 2 read
`result=...` and fails it, printing `  [0] ` with nothing after the index fails
it with `entry says nothing: '  [0] '`, while an advice line a later commit
appends does not.

Withholding the advice when an entry named a missing global fails
`test_no_match_message_keeps_the_advice_for_every_entry` on `Add a
ModelInput`.

Reading `self.compiled_results` in the report again fails
`test_no_match_report_names_the_results_the_dispatch_judged` with `IndexError:
list index out of range` raised in place of the report.

`test_no_match_message_keeps_the_advice_for_every_entry` captures through
`_aot_compile_mode_branches`, whose `_hide_leaked_dynamo_globals` pops the
minted globals a sibling's capture leaked and strips this test's own in cleanup
(run alone in a fresh process, the inline capture it replaces left eight
minted names in this module's dict -- two `__builtins_dict___*`, two
`__compiled_fn_*` and four `__import_*` aliases; this form leaves none), and
it registers the `AOT_BRANCH_SCALE` restore with
`addCleanup` before deleting the name, so an interrupt anywhere leaves the
module dict whole.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 7ccd7d3
Pull-Request: #196823
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
…h matches

Once module dispatch found no match, `AOTCompiledModel.__call__` fell through
to `compiled_results[0]`, so the user saw whatever that one artifact's guard
manager said -- with several compiled inputs, a failure report about the first
one only, and no sign that the others existed or why they did not match. The
dispatch commits below made the dispatch itself scan every result, re-check
every result and serve an opted-out result before giving up, and kept that
fall-through as the raise. This commit replaces it with a report that names
every compiled input, built from the binding the dispatch already judged.

This commit and the three above it -- `[aot_compile] Give the no-match report's
missing-global hint one For [i, j]: line per distinct sentence` (#197149), `[aot_compile]
Say when a no-match report entry's guards accepted the call the dispatch
refused` (#197150) and `[aot_compile] Keep a no-match report entry to one
line that says what its guards answered` (#197134) -- were one commit, split for
review budget. This commit is the report: the raise, the header, one line per
compiled input quoting the guards `check_verbose` named, the missing-global hint
the fall-through already gave, and the closing advice. The siblings own where
that hint sits, and what an entry's line holds when `check_verbose` names no
guard: because the tree accepted the call, because a failing accessor named
nothing, or because a part carries a line boundary.

The raise carries one line per compiled input, and closes with what to do about
it: add a `ModelInput`, or check whether `guard_filter_fn` KEPT a guard this
call cannot satisfy. That last phrasing matters -- a guard the filter DROPPED
cannot make a call fail to match, so the reverse advice sent the reader looking
in the wrong place. Both levers are the capturing process's, and this report is
reachable from a process that only loaded an artifact (nothing on
`_load_aot_compiled_module` takes either), so the line says so rather than
implying the reader holds them.

When an entry's guards died on a global the process does not have, its line
carries the function path's own `_missing_global_hint`, appended with ` -- `
exactly as the fall-through's `AOTCompiledFunction.__call__` appended it to
`[0]`'s `GuardManager check failed` message -- the sentence worded for the scope
that result's guards were resolved against (CAPTURED, SUPPLIED or
RECONSTRUCTED), so the two paths say the same thing about the same scope. The
hint is part of this commit rather than a follow-up because the parent already
delivered it on the module path and five tests below
(`test_aot_compile_module_missing_global_hint_names_the_resolved_module` and
the four `deserialize_refuses_*` / `fallback_scope_hint` tests) assert its text
through a module call; a report without it fails all five. Here it rides on
every entry that named a missing global, as the parent's message carried it for
`[0]`; giving the report one self-locating `For [i, j]:` line per distinct
sentence, naming the entries that share it, and the helper a bare sentence each
caller leads into, is #197149's, the next commit. The SUPPLIED wording is the parent's, unchanged: `the live
scope this artifact was loaded against, here vars(<module>)`. Naming the
instance's `forward` there, for a load whose guards hold the dict that attribute
resolves to, is #197048's, above the siblings.

The advice and that hint are independent, so a report every entry of which named
a missing global carries both. Withholding the advice there would assume a new
`ModelInput`'s guards must fail on the same absent name, which only holds when
every path of `forward` reads that global: an entry fails on a global because
ITS tree reads it, and an input captured for the branch this call takes need not
read it at all -- such an input is captured and served with the name still
undefined. Withholding also makes the only actionable line in the report turn on
whether an unrelated global happens to be defined, and that masking is easy to
hit, since guards are installed in `sorted(guards)` order and
`GuardSource.LOCAL` sorts before `GLOBAL`, which sorts before
`LOCAL_UNSPECIALIZED_NN_MODULE`: the root's `G` accessor fails before an
`nn.Module` attribute guard runs, so the mismatch the reader needs to hear about
is hidden behind the `KeyError`. The report cannot tell the two shapes apart and
the advice is already hedged, so it is emitted next to the hint rather than in
place of it.

An entry's line quotes the guards `check_verbose` named, joined with `; `.
`GuardDebugInfo.user_stack` and `num_guards_executed` are dropped on purpose:
the verbose part usually embeds `# <source> # file:line in forward` already,
the stack is `None` for the `KeyError on G[...]` case this report exists to
explain, and one line per input is the point. Three of `check_verbose`'s
answers leave that line saying nothing, or spread it over several lines, and
each is a sibling's. A tree that ACCEPTS the call both dispatch passes rejected
answers with no parts, so here its entry prints nothing after `[i]`; the call is
refused all the same, and what the entry should say about it is #197150's.
A genuine failure can also arrive with no parts, and a part can carry a
boundary `splitlines()` breaks on; here such an entry prints nothing after
`[i]`, or spans several lines, the call is refused either way, and those two
lines are #197134's.

A describer that raises is not caught here. `check_verbose` runs paths
`check()` does not -- `DIMENSION_DYNAMIC_MARKING_GUARD` calls `py::repr` on
user objects, and a `TENSOR_MATCH` failure on a tensor of the compiled type
calls `is_parameter`, which runs `_ParameterMeta.__instancecheck__` -- so an
entry's describer can raise where the dispatch's rejection was clean, and when
it does the exception escapes the `raise RuntimeError(...)` argument and takes
the report with it, exactly as it escaped the parent's fall-through, whose
`AOTCompiledFunction.__call__` runs the same `check_verbose` unguarded. An
earlier revision ran each entry's `check_verbose` under its own `try` and
described the other entries anyway; that catch is unsound below #197049 and
the lines it saved were wrong (FAQ below), so it is gone from here, and the
place a raising tree is read as no answer and reported as one line is #196826,
above the TorchFunction restore #197049 adds.

One call the fall-through served is refused by the report, and that is
intended: a tree that rejected the call in both dispatch passes and accepts it
on a third evaluation. PARENT: for `[0]` only, the fall-through's
`AOTCompiledFunction.__call__` evaluated its guards a third time and served the
graph when that evaluation accepted -- with a `CountedKey(misses=2)` in the
slot of the one global `[0]`'s tree reads: `SERVED equal_to_x*3= True
compares= 3`. HEAD: the report's `check_verbose` is that third evaluation, an
accept there leaves the entry with nothing after its index, and the call
raises: `RAISED compares= 3`. An accept that arrives only on the third
evaluation is not a certified match -- a guard that does not answer
consistently, or a tag-safe fast path that refused without running the tree --
and the parent extended that third chance to `[0]` alone, by its position; a
result in any other slot never had it. The entry that says so, and
`test_no_match_message_when_a_guard_answers_inconsistently`, which pins the
raise and the three evaluations, are #197150's. A model with no compiled
results is not a case this commit changes: `results[0]` at the top of
`__call__` raises `IndexError: tuple index out of range` before any stage runs,
on the parent and here alike.

Otherwise the exception type stays `RuntimeError`, and the text `GuardManager
check failed` is replaced on the module path only: the function path's
`__call__` still raises it, and the five regexes this commit updates in
test_aot_compile.py belong to the dispatch tests below. One of those tests,
`test_module_dispatch_no_match_falls_through_to_the_first_result`, was named
and commented for the fall-through its zero-opt-out row now proves gone, so
it is renamed `test_module_dispatch_no_match_raises_unless_a_result_opted_out`
and its comment says what the rows show: a call neither result guards raises
and is handed to no result, and with `[0]` opted out its graph runs.

The report reuses the binding the dispatch judged, one per result, so it
explains the same binding rather than a fresh one, and the one bind per call
#197071 introduced holds end to end; the fall-through it replaces bound twice
more inside `AOTCompiledFunction.__call__`.
`test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature` now
also counts `prepare_f_locals` for a call nothing matches, and counts it apart
from the matched call's: the list is asserted `[results[0]]` and cleared after
the matched call, and asserted `[results[0]]` again after the no-match call,
so each bind is attributed to the call that made it -- a combined
`[results[0], results[0]]` would also accept a dispatch that bound the matched
call nowhere and the no-match call twice. The fall-through fails the second
assertion with `The length of the sequences mismatch: 3 != 1`, its no-match
call binding three times. The same test counts the report's entry lines -- one
per result off that single bind -- rather than its total line count, so a
footer line added later does not break it. Measured
once when this report was first written, against the dispatch before the
one-bind-per-call commit and this commit, and not re-run since: a report costs
12.6us against the old 15.0us, and the no-match path costs 18.5us against
27.9us at one input and 29.9us against 33.0us at two, and crosses over by four,
50.9us against 41.3us, where the report's N `check_verbose` calls and the
re-check's N `check()` calls outweigh the binds saved; with one bind per call
rather than per result it costs 30.2us against 43.1us at four. That path ends
in a raise, and the match path is the one every call takes.

The report is handed the results the dispatch judged as well: `__call__` reads
`compiled_results` once, and the report indexes `bound` against that tuple
rather than re-reading a public list an append or a replacement can have
changed under it -- re-read, an appended result asks for a binding the dispatch
never made, and an `IndexError` raised inside the `raise RuntimeError(...)`
argument takes the report's place.
`test_no_match_report_names_the_results_the_dispatch_judged` makes `[0]`'s
`check()` splice a second result into the list mid-call and asserts the report
counts one input, with the second the next call's to judge.

The supplied-scope hint on an un-rebound load is pinned by #196825, a test-only
commit higher in the stack, which also pins that the advice above still reaches
a report whose only failure is a missing global. Folding that commit's test
lines down here would put a guarded global the loading process does not have in
the same commit as this report, which is the split this re-slice exists to
make; they land together in any case. Four more of the report's tests sit in
#197001, above #197048, since three of them pin that commit's forward naming:
that the hint stays scope-neutral for a caller-supplied `guard_globals=`, that
a CAPTURED result's report names no `forward` and never resolves it, that the
advice reaches a report whose every entry named a missing global, and that a
missing KEY inside a present global is not a missing global.

> **FAQ: an earlier revision ran each entry's `check_verbose` under its own
> `try`, so one raising describer did not cost the other entries their lines.
> Why is that gone?** Because below #197049 the catch continues on a thread the
> throw left broken, and the lines it saves are wrong.
> `RootGuardManager::check_verbose_nopybind` sets the TorchFunction TLS to
> `ALL_DISABLED` for its accessors and restores it on each of its return paths,
> not under RAII, so a `py::error_already_set` unwinding out of the tree skips
> the restore; `_reset_relational_guard_state()` is skipped the same way, and
> has no Python binding to call instead. Measured at that revision's tree with
> `_ParameterMeta.__instancecheck__` patched to raise -- the Python
> `is_parameter` reaches from `TENSOR_MATCH::check_verbose_nopybind`'s failure
> branch, the route a tensor subclass `__getattr__` takes -- on a two-input
> `ScaleModule` called with `x.double()`: the report arrived, `[0]` read `<guard
> check could not be described: RuntimeError(...)>`, and `[1]` read
> `GLOBAL_STATE changed: torch_function` instead of its dtype mismatch, since
> `[1]`'s tree was evaluated on the thread `[0]`'s throw had left disabled;
> after the report was caught, `torch._C._get_torch_function_state()` read
> `ALL_DISABLED` against `ENABLED` before the call, and `t + 1` on a
> `__torch_function__` subclass returned a plain `Tensor` without dispatching.
> Without the `try`, the same script raises `RuntimeError('user __getattr__
> raised')` out of `__call__` on this tree and on the parent's alike, and leaves
> the thread the same way -- an exposure `AOTCompiledFunction.__call__` has
> always had, which #197049 repairs inside `GuardManagerWrapper.check_verbose`
> for every caller. Fixing the C++ exit itself is outside this Python-only
> stack. So the catch belongs above the restore, in #196826, and the test that
> pinned it here, `test_no_match_report_describes_the_other_entries_when_one_raises`,
> goes with it.

> **FAQ: an entry whose `check_verbose` ACCEPTS the call, or fails without
> naming a guard, prints nothing after `[i]` here, and a part carrying a line
> boundary spans several lines. Why not branch on `reason.result` and an empty
> `verbose_code_parts`, and collapse `splitlines()`, in this commit?** Because
> those branches are #197150's (the entry for a tree that accepted on the third
> evaluation) and #197134's (the entry for a failure that named no guard, and
> the one-line collapse), split out of this commit for review budget so that
> each lands next to the test that pins it and the report's plumbing here --
> the raise, the header, the per-entry join off the dispatch's own `bound` and
> `results`, the hint and the advice -- stays reviewable on its own; the call
> is refused all the same on every one of those answers, so nothing is served
> in the meantime that a sibling later refuses. What the reader is told in the
> meantime, measured at this tree against the parent's: with a
> `CountedKey(misses=2)` on the global `[1]`'s tree reads and a `mode=1` call,
> this tree raises `[0] L['mode'] == 0` over a blank `[1]` (`compares= 3`),
> and the parent raised `[0]`'s `L['mode'] == 0` alone (`compares= 2`) -- it
> never evaluated `[1]` a third time and said nothing of it, and with the probe
> on a global `[0]`'s tree reads it served the graph (above); so no `result=1`
> repr was ever printed for this answer. With #197134's fixture -- a
> `SetIterModule` iterating a set, `SEQUENCE_LENGTH` dropped by the filter,
> called with a shorter set -- this tree prints `  [0] ` blank, and the parent
> printed `GuardDebugInfo(result=0, verbose_code_parts=[], num_guards_executed=6,
> user_stack=None)`: no guard named either, but a `result=0` the blank entry
> here does not carry. That one entry is what this commit says less about than
> the fall-through did, for the three commits until #197134, which lands with
> it.

> **FAQ: a report whose entries all failed on the same missing global repeats
> the hint on every one of them. Why not one hint per report here?** Because
> where the hint sits is #197149's, the next commit, which gives the report one
> `For [i, j]:` line per distinct sentence naming the entries that share it,
> and pins the count at one in
> `test_aot_compile_module_missing_global_hint_names_the_resolved_module` and
> `test_no_match_message_hints_only_the_entry_that_named_a_missing_global`.
> Here each entry carries its own hint, appended with ` -- ` as the
> fall-through appended it to `[0]`'s message, so the five tests below that
> assert the hint's text keep passing across the split. Measured at this tree,
> the report `test_aot_compile_module_missing_global_hint_names_the_resolved_module`
> produces on its first load is four lines, the two entries 203 characters each
> and identical, with `a guarded global is missing` twice; that test asserts
> the text with `assertIn`, so it sees neither count, and pinning the
> repetition here only to remove it one commit up would assert something no
> user is meant to rely on. The class docstring describes what this commit
> does -- one line per result, carrying the hint when that result's guards
> failed on a missing global -- and #197149 rewrites it for the `For` line.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_no_match_error
python test/dynamo/test_aot_compile.py -k test_no_match_message_keeps_the_advice_for_every_entry
python test/dynamo/test_aot_compile.py -k test_no_match_report_names_the_results_the_dispatch_judged
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_no_match_raises_unless_a_result_opted_out
python test/dynamo/test_aot_compile.py
```

The whole file runs 208 tests, `OK (skipped=6)`; the parent's file
defines three fewer. Every `-k` above fails with the parent's `aot_compile.py`
under this test file (5/5): the three that assert on report text (`No AOT
compiled graph matched this call`, `[0] L['mode'] == 0`, `Tried 1 compiled
input(s)`) find the fall-through's `GuardManager check failed` message instead,
the binding test sees three binds for the no-match call against the one it
expects, `The length of the sequences mismatch: 3 != 1`, and the renamed
test's zero-opt-out row finds `GuardManager check failed` where it expects
`No AOT compiled graph matched` (its two opt-out rows pass on both, as they
should: an opted-out `[0]` is served on the parent and here alike).

`test_aot_compile_module_no_match_error` asserts that each of the two entries
is one line of the report -- the two lines after the header, with unindented
advice after them -- rather than that the whole report is four lines, and that
each entry says something after its index: reporting an entry as
`str(GuardDebugInfo)` instead of the joined one-line reason makes line 2 read
`result=...` and fails it, printing `  [0] ` with nothing after the index fails
it with `entry says nothing: '  [0] '`, while an advice line a later commit
appends does not.

Withholding the advice when an entry named a missing global fails
`test_no_match_message_keeps_the_advice_for_every_entry` on `Add a
ModelInput`.

Reading `self.compiled_results` in the report again fails
`test_no_match_report_names_the_results_the_dispatch_judged` with `IndexError:
list index out of range` raised in place of the report.

`test_no_match_message_keeps_the_advice_for_every_entry` captures through
`_aot_compile_mode_branches`, whose `_hide_leaked_dynamo_globals` pops the
minted globals a sibling's capture leaked and strips this test's own in cleanup
(run alone in a fresh process, the inline capture it replaces left eight
minted names in this module's dict -- two `__builtins_dict___*`, two
`__compiled_fn_*` and four `__import_*` aliases; this form leaves none), and
it registers the `AOT_BRANCH_SCALE` restore with
`addCleanup` before deleting the name, so an interrupt anywhere leaves the
module dict whole.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 103add6
Pull-Request: #196823
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
…h matches

Once module dispatch found no match, `AOTCompiledModel.__call__` fell through
to `compiled_results[0]`, so the user saw whatever that one artifact's guard
manager said -- with several compiled inputs, a failure report about the first
one only, and no sign that the others existed or why they did not match. The
dispatch commits below made the dispatch itself scan every result, re-check
every result and serve an opted-out result before giving up, and kept that
fall-through as the raise. This commit replaces it with a report that names
every compiled input, built from the binding the dispatch already judged.

This commit and the three above it -- `[aot_compile] Give the no-match report's
missing-global hint one For [i, j]: line per distinct sentence` (#197149), `[aot_compile]
Say when a no-match report entry's guards accepted the call the dispatch
refused` (#197150) and `[aot_compile] Keep a no-match report entry to one
line that says what its guards answered` (#197134) -- were one commit, split for
review budget. This commit is the report: the raise, the header, one line per
compiled input quoting the guards `check_verbose` named, the missing-global hint
the fall-through already gave, and the closing advice. The siblings own where
that hint sits, and what an entry's line holds when `check_verbose` names no
guard: because the tree accepted the call, because a failing accessor named
nothing, or because a part carries a line boundary.

The raise carries one line per compiled input, and closes with what to do about
it: add a `ModelInput`, or check whether `guard_filter_fn` KEPT a guard this
call cannot satisfy. That last phrasing matters -- a guard the filter DROPPED
cannot make a call fail to match, so the reverse advice sent the reader looking
in the wrong place. Both levers are the capturing process's, and this report is
reachable from a process that only loaded an artifact (nothing on
`_load_aot_compiled_module` takes either), so the line says so rather than
implying the reader holds them.

When an entry's guards died on a global the process does not have, its line
carries the function path's own `_missing_global_hint`, appended with ` -- `
exactly as the fall-through's `AOTCompiledFunction.__call__` appended it to
`[0]`'s `GuardManager check failed` message -- the sentence worded for the scope
that result's guards were resolved against (CAPTURED, SUPPLIED or
RECONSTRUCTED), so the two paths say the same thing about the same scope. The
hint is part of this commit rather than a follow-up because the parent already
delivered it on the module path and five tests below
(`test_aot_compile_module_missing_global_hint_names_the_resolved_module` and
the four `deserialize_refuses_*` / `fallback_scope_hint` tests) assert its text
through a module call; a report without it fails all five. Here it rides on
every entry that named a missing global, as the parent's message carried it for
`[0]`; giving the report one self-locating `For [i, j]:` line per distinct
sentence, naming the entries that share it, and the helper a bare sentence each
caller leads into, is #197149's, the next commit. The SUPPLIED wording is the parent's, unchanged: `the live
scope this artifact was loaded against, here vars(<module>)`. Naming the
instance's `forward` there, for a load whose guards hold the dict that attribute
resolves to, is #197048's, above the siblings.

The advice and that hint are independent, so a report every entry of which named
a missing global carries both. Withholding the advice there would assume a new
`ModelInput`'s guards must fail on the same absent name, which only holds when
every path of `forward` reads that global: an entry fails on a global because
ITS tree reads it, and an input captured for the branch this call takes need not
read it at all -- such an input is captured and served with the name still
undefined. Withholding also makes the only actionable line in the report turn on
whether an unrelated global happens to be defined, and that masking is easy to
hit, since guards are installed in `sorted(guards)` order and
`GuardSource.LOCAL` sorts before `GLOBAL`, which sorts before
`LOCAL_UNSPECIALIZED_NN_MODULE`: the root's `G` accessor fails before an
`nn.Module` attribute guard runs, so the mismatch the reader needs to hear about
is hidden behind the `KeyError`. The report cannot tell the two shapes apart and
the advice is already hedged, so it is emitted next to the hint rather than in
place of it.

An entry's line quotes the guards `check_verbose` named, joined with `; `.
`GuardDebugInfo.user_stack` and `num_guards_executed` are dropped on purpose:
the verbose part usually embeds `# <source> # file:line in forward` already,
the stack is `None` for the `KeyError on G[...]` case this report exists to
explain, and one line per input is the point. Three of `check_verbose`'s
answers leave that line saying nothing, or spread it over several lines, and
each is a sibling's. A tree that ACCEPTS the call both dispatch passes rejected
answers with no parts, so here its entry prints nothing after `[i]`; the call is
refused all the same, and what the entry should say about it is #197150's.
A genuine failure can also arrive with no parts, and a part can carry a
boundary `splitlines()` breaks on; here such an entry prints nothing after
`[i]`, or spans several lines, the call is refused either way, and those two
lines are #197134's.

A describer that raises is not caught here. `check_verbose` runs paths
`check()` does not -- `DIMENSION_DYNAMIC_MARKING_GUARD` calls `py::repr` on
user objects, and a `TENSOR_MATCH` failure on a tensor of the compiled type
calls `is_parameter`, which runs `_ParameterMeta.__instancecheck__` -- so an
entry's describer can raise where the dispatch's rejection was clean, and when
it does the exception escapes the `raise RuntimeError(...)` argument and takes
the report with it, exactly as it escaped the parent's fall-through, whose
`AOTCompiledFunction.__call__` runs the same `check_verbose` unguarded. An
earlier revision ran each entry's `check_verbose` under its own `try` and
described the other entries anyway; that catch is unsound below #197049 and
the lines it saved were wrong (FAQ below), so it is gone from here, and the
place a raising tree is read as no answer and reported as one line is #196826,
above the TorchFunction restore #197049 adds.

One call the fall-through served is refused by the report, and that is
intended: a tree that rejected the call in both dispatch passes and accepts it
on a third evaluation. PARENT: for `[0]` only, the fall-through's
`AOTCompiledFunction.__call__` evaluated its guards a third time and served the
graph when that evaluation accepted -- with a `CountedKey(misses=2)` in the
slot of the one global `[0]`'s tree reads: `SERVED equal_to_x*3= True
compares= 3`. HEAD: the report's `check_verbose` is that third evaluation, an
accept there leaves the entry with nothing after its index, and the call
raises: `RAISED compares= 3`. An accept that arrives only on the third
evaluation is not a certified match -- a guard that does not answer
consistently, or a tag-safe fast path that refused without running the tree --
and the parent extended that third chance to `[0]` alone, by its position; a
result in any other slot never had it. The entry that says so, and
`test_no_match_message_when_a_guard_answers_inconsistently`, which pins the
raise and the three evaluations, are #197150's. A model with no compiled
results is not a case this commit changes: `results[0]` at the top of
`__call__` raises `IndexError: tuple index out of range` before any stage runs,
on the parent and here alike.

Otherwise the exception type stays `RuntimeError`, and the text `GuardManager
check failed` is replaced on the module path only: the function path's
`__call__` still raises it, and the five regexes this commit updates in
test_aot_compile.py belong to the dispatch tests below. One of those tests,
`test_module_dispatch_no_match_falls_through_to_the_first_result`, was named
and commented for the fall-through its zero-opt-out row now proves gone, so
it is renamed `test_module_dispatch_no_match_raises_unless_a_result_opted_out`
and its comment says what the rows show: a call neither result guards raises
and is handed to no result, and with `[0]` opted out its graph runs. Three
sibling dispatch tests named the same fall-through for the stage before or
after the one they pin --
`test_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts`,
`test_module_dispatch_serves_an_opted_out_result_from_any_position` and
`test_module_dispatch_rechecks_before_honouring_an_opt_out` -- and their
comments now name the stages the dispatch has: the opt-out last resort, then
this report. Their assertions are unchanged.

The report reuses the binding the dispatch judged, one per result, so it
explains the same binding rather than a fresh one, and the one bind per call
#197071 introduced holds end to end; the fall-through it replaces bound twice
more inside `AOTCompiledFunction.__call__`.
`test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature` now
also counts `prepare_f_locals` for a call nothing matches, and counts it apart
from the matched call's: the list is asserted `[results[0]]` and cleared after
the matched call, and asserted `[results[0]]` again after the no-match call,
so each bind is attributed to the call that made it -- a combined
`[results[0], results[0]]` would also accept a dispatch that bound the matched
call nowhere and the no-match call twice. The fall-through fails the second
assertion with `The length of the sequences mismatch: 3 != 1`, its no-match
call binding three times. The same test counts the report's entry lines -- one
per result off that single bind -- rather than its total line count, so a
footer line added later does not break it. Measured
once when this report was first written, against the dispatch before the
one-bind-per-call commit and this commit, and not re-run since: a report costs
12.6us against the old 15.0us, and the no-match path costs 18.5us against
27.9us at one input and 29.9us against 33.0us at two, and crosses over by four,
50.9us against 41.3us, where the report's N `check_verbose` calls and the
re-check's N `check()` calls outweigh the binds saved; with one bind per call
rather than per result it costs 30.2us against 43.1us at four. That path ends
in a raise, and the match path is the one every call takes.

The report is handed the results the dispatch judged as well: `__call__` reads
`compiled_results` once, and the report indexes `bound` against that tuple
rather than re-reading a public list an append or a replacement can have
changed under it -- re-read, an appended result asks for a binding the dispatch
never made, and an `IndexError` raised inside the `raise RuntimeError(...)`
argument takes the report's place.
`test_no_match_report_names_the_results_the_dispatch_judged` makes `[0]`'s
`check()` splice a second result into the list AHEAD of it mid-call, and
asserts the report counts one input and never ran the spliced result's
`check_verbose`, which is wrapped; the splice is `[:] = [later, first]`, so
the re-check pass running the patched `check()` a second time leaves the list
as it is. Counting alone would not pin which result an entry describes: a
report that re-read the list and zipped it against `bound` would describe the
spliced result against `[0]`'s binding under a `Tried 1` header, and the two
results differ only in a closure scale, so their dtype-mismatch lines read
alike. The second call, over the spliced list, reports `Tried 2` and runs the
spliced describer once, so the watch is on the object the report reads.

The supplied-scope hint on an un-rebound load is pinned by #196825, a test-only
commit higher in the stack, which also pins that the advice above still reaches
a report whose only failure is a missing global. Folding that commit's test
lines down here would put a guarded global the loading process does not have in
the same commit as this report, which is the split this re-slice exists to
make; they land together in any case. Four more of the report's tests sit in
#197001, above #197048, since three of them pin that commit's forward naming:
that the hint stays scope-neutral for a caller-supplied `guard_globals=`, that
a CAPTURED result's report names no `forward` and never resolves it, that the
advice reaches a report whose every entry named a missing global, and that a
missing KEY inside a present global is not a missing global.

> **FAQ: an earlier revision ran each entry's `check_verbose` under its own
> `try`, so one raising describer did not cost the other entries their lines.
> Why is that gone?** Because below #197049 the catch continues on a thread the
> throw left broken, and the lines it saves are wrong.
> `RootGuardManager::check_verbose_nopybind` sets the TorchFunction TLS to
> `ALL_DISABLED` for its accessors and restores it on each of its return paths,
> not under RAII, so a `py::error_already_set` unwinding out of the tree skips
> the restore; `_reset_relational_guard_state()` is skipped the same way, and
> has no Python binding to call instead. Measured at that revision's tree with
> `_ParameterMeta.__instancecheck__` patched to raise -- the Python
> `is_parameter` reaches from `TENSOR_MATCH::check_verbose_nopybind`'s failure
> branch, the route a tensor subclass `__getattr__` takes -- on a two-input
> `ScaleModule` called with `x.double()`: the report arrived, `[0]` read `<guard
> check could not be described: RuntimeError(...)>`, and `[1]` read
> `GLOBAL_STATE changed: torch_function` instead of its dtype mismatch, since
> `[1]`'s tree was evaluated on the thread `[0]`'s throw had left disabled;
> after the report was caught, `torch._C._get_torch_function_state()` read
> `ALL_DISABLED` against `ENABLED` before the call, and `t + 1` on a
> `__torch_function__` subclass returned a plain `Tensor` without dispatching.
> Without the `try`, the same script raises `RuntimeError('user __getattr__
> raised')` out of `__call__` on this tree and on the parent's alike, and leaves
> the thread the same way -- an exposure `AOTCompiledFunction.__call__` has
> always had, which #197049 repairs inside `GuardManagerWrapper.check_verbose`
> for every caller. Fixing the C++ exit itself is outside this Python-only
> stack. So the catch belongs above the restore, in #196826, and the test that
> pinned it here, `test_no_match_report_describes_the_other_entries_when_one_raises`,
> goes with it.

> **FAQ: an entry whose `check_verbose` ACCEPTS the call, or fails without
> naming a guard, prints nothing after `[i]` here, and a part carrying a line
> boundary spans several lines. Why not branch on `reason.result` and an empty
> `verbose_code_parts`, and collapse `splitlines()`, in this commit?** Because
> those branches are #197150's (the entry for a tree that accepted on the third
> evaluation) and #197134's (the entry for a failure that named no guard, and
> the one-line collapse), split out of this commit for review budget so that
> each lands next to the test that pins it and the report's plumbing here --
> the raise, the header, the per-entry join off the dispatch's own `bound` and
> `results`, the hint and the advice -- stays reviewable on its own; the call
> is refused all the same on every one of those answers, so nothing is served
> in the meantime that a sibling later refuses. What the reader is told in the
> meantime, measured at this tree against the parent's: with a
> `CountedKey(misses=2)` on the global `[1]`'s tree reads and a `mode=1` call,
> this tree raises `[0] L['mode'] == 0` over a blank `[1]` (`compares= 3`),
> and the parent raised `[0]`'s `L['mode'] == 0` alone (`compares= 2`) -- it
> never evaluated `[1]` a third time and said nothing of it, and with the probe
> on a global `[0]`'s tree reads it served the graph (above); so no `result=1`
> repr was ever printed for this answer. With #197134's fixture -- a
> `SetIterModule` iterating a set, `SEQUENCE_LENGTH` dropped by the filter,
> called with a shorter set -- this tree prints `  [0] ` blank, and the parent
> printed `GuardDebugInfo(result=0, verbose_code_parts=[], num_guards_executed=6,
> user_stack=None)`: no guard named either, but a `result=0` the blank entry
> here does not carry. That one entry is what this commit says less about than
> the fall-through did, for the three commits until #197134, which lands with
> it. Neither blank entry loses a hint: the hint rides on a part that reads
> `KeyError on G[...]`, matched whole by `_names_a_missing_global`, so an
> answer with no parts named no missing global -- an accept has no failure to
> hint, and the short-set failure is not about a global -- and the absent hint
> is the accurate answer there, not a second loss.

> **FAQ: a report whose entries all failed on the same missing global repeats
> the hint on every one of them. Why not one hint per report here?** Because
> where the hint sits is #197149's, the next commit, which gives the report one
> `For [i, j]:` line per distinct sentence naming the entries that share it,
> and pins the count at one in
> `test_aot_compile_module_missing_global_hint_names_the_resolved_module` and
> `test_no_match_message_hints_only_the_entry_that_named_a_missing_global`.
> Here each entry carries its own hint, appended with ` -- ` as the
> fall-through appended it to `[0]`'s message, so the five tests below that
> assert the hint's text keep passing across the split. Measured at this tree,
> the report `test_aot_compile_module_missing_global_hint_names_the_resolved_module`
> produces on its first load is four lines, the two entries 203 characters each
> and identical, with `a guarded global is missing` twice; that test asserts
> the text with `assertIn`, so it sees neither count, and pinning the
> repetition here only to remove it one commit up would assert something no
> user is meant to rely on. The class docstring describes what this commit
> does -- one line per result, carrying the hint when that result's guards
> failed on a missing global -- and #197149 rewrites it for the `For` line.

> **FAQ: `test_no_match_message_keeps_the_advice_for_every_entry` asserts the
> hint with `assertIn` over the whole message rather than on the `[1]` line.
> Why not anchor it here?** Because the hint's line is #197149's, the next
> commit, which replaces that very assertion with `For [1]: a guarded global is
> missing` and `message.count("a guarded global is missing") == 1` -- the
> anchoring, at the placement the report keeps. Here the hint is appended to
> `[1]`'s own line, and an assertion pinning it there would pin a placement the
> next commit removes and be rewritten one commit up. The two substrings the
> test does assert are not one check twice: `a guarded global is missing`
> opens all three scopes' sentences, while `the module the compiled function
> was traced in` is the CAPTURED wording alone -- SUPPLIED reads `the live
> scope this artifact was loaded against` and RECONSTRUCTED `the scope rebuilt
> from the artifact` -- so the second pins that an in-process capture's result
> is hinted for the scope it resolved against.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_no_match_error
python test/dynamo/test_aot_compile.py -k test_no_match_message_keeps_the_advice_for_every_entry
python test/dynamo/test_aot_compile.py -k test_no_match_report_names_the_results_the_dispatch_judged
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_no_match_raises_unless_a_result_opted_out
python test/dynamo/test_aot_compile.py
```

The whole file runs 208 tests, `OK (skipped=6)`; the parent's file
defines three fewer. Every `-k` above fails with the parent's `aot_compile.py`
under this test file (5/5): the three that assert on report text (`No AOT
compiled graph matched this call`, `[0] L['mode'] == 0`, `Tried 1 compiled
input(s)`) find the fall-through's `GuardManager check failed` message instead,
the binding test sees three binds for the no-match call against the one it
expects, `The length of the sequences mismatch: 3 != 1`, and the renamed
test's zero-opt-out row finds `GuardManager check failed` where it expects
`No AOT compiled graph matched` (its two opt-out rows pass on both, as they
should: an opted-out `[0]` is served on the parent and here alike).

`test_aot_compile_module_no_match_error` asserts that each of the two entries
is one line of the report -- the two lines after the header, with unindented
advice after them -- rather than that the whole report is four lines, and that
each entry says something after its index: reporting an entry as
`str(GuardDebugInfo)` instead of the joined one-line reason makes line 2 read
`result=...` and fails it, printing `  [0] ` with nothing after the index fails
it with `entry says nothing: '  [0] '`, while an advice line a later commit
appends does not.

Withholding the advice when an entry named a missing global fails
`test_no_match_message_keeps_the_advice_for_every_entry` on `Add a
ModelInput`.

Reading `self.compiled_results` in the report again fails
`test_no_match_report_names_the_results_the_dispatch_judged` with `IndexError:
list index out of range` raised in place of the report; re-reading it zipped
against `bound`, with the header off `results`, passes the header and entry
counts and fails it with `Expected 'check_verbose' to not have been called.
Called 1 times.` Both mutations were run at this tree.

`test_no_match_message_keeps_the_advice_for_every_entry` captures through
`_aot_compile_mode_branches`, whose `_hide_leaked_dynamo_globals` pops the
minted globals a sibling's capture leaked and strips this test's own in cleanup
(run alone in a fresh process, the inline capture it replaces left eight
minted names in this module's dict -- two `__builtins_dict___*`, two
`__compiled_fn_*` and four `__import_*` aliases; this form leaves none), and
it registers the `AOT_BRANCH_SCALE` restore with
`addCleanup` before deleting the name, so an interrupt anywhere leaves the
module dict whole.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 93bb35b
Pull-Request: #196823
bobrenjc93 added a commit that referenced this pull request Sep 16, 2026
…h matches

Once module dispatch found no match, `AOTCompiledModel.__call__` fell through
to `compiled_results[0]`, so the user saw whatever that one artifact's guard
manager said -- with several compiled inputs, a failure report about the first
one only, and no sign that the others existed or why they did not match. The
dispatch commits below made the dispatch itself scan every result, re-check
every result and serve an opted-out result before giving up, and kept that
fall-through as the raise. This commit replaces it with a report that names
every compiled input, built from the binding the dispatch already judged.

This commit and the three above it -- `[aot_compile] Give the no-match report's
missing-global hint one For [i, j]: line per distinct sentence` (#197149), `[aot_compile]
Say when a no-match report entry's guards accepted the call the dispatch
refused` (#197150) and `[aot_compile] Keep a no-match report entry to one
line that says what its guards answered` (#197134) -- were one commit, split for
review budget. This commit is the report: the raise, the header, one line per
compiled input quoting the guards `check_verbose` named, the missing-global hint
the fall-through already gave, and the closing advice. The siblings own where
that hint sits, and what an entry's line holds when `check_verbose` names no
guard: because the tree accepted the call, because a failing accessor named
nothing, or because a part carries a line boundary.

The raise carries one line per compiled input, and closes with what to do about
it: add a `ModelInput`, or check whether `guard_filter_fn` KEPT a guard this
call cannot satisfy. That last phrasing matters -- a guard the filter DROPPED
cannot make a call fail to match, so the reverse advice sent the reader looking
in the wrong place. Both levers are the capturing process's, and this report is
reachable from a process that only loaded an artifact (nothing on
`_load_aot_compiled_module` takes either), so the line says so rather than
implying the reader holds them.

When an entry's guards died on a global the process does not have, its line
carries the function path's own `_missing_global_hint`, appended with ` -- `
exactly as the fall-through's `AOTCompiledFunction.__call__` appended it to
`[0]`'s `GuardManager check failed` message -- the sentence worded for the scope
that result's guards were resolved against (CAPTURED, SUPPLIED or
RECONSTRUCTED), so the two paths say the same thing about the same scope. The
hint is part of this commit rather than a follow-up because the parent already
delivered it on the module path and five tests below
(`test_aot_compile_module_missing_global_hint_names_the_resolved_module` and
the four `deserialize_refuses_*` / `fallback_scope_hint` tests) assert its text
through a module call; a report without it fails all five. Here it rides on
every entry that named a missing global, as the parent's message carried it for
`[0]`; giving the report one self-locating `For [i, j]:` line per distinct
sentence, naming the entries that share it, and the helper a bare sentence each
caller leads into, is #197149's, the next commit. The SUPPLIED wording is the parent's, unchanged: `the live
scope this artifact was loaded against, here vars(<module>)`. Naming the
instance's `forward` there, for a load whose guards hold the dict that attribute
resolves to, is #197048's, above the siblings.

The advice and that hint are independent, so a report every entry of which named
a missing global carries both. Withholding the advice there would assume a new
`ModelInput`'s guards must fail on the same absent name, which only holds when
every path of `forward` reads that global: an entry fails on a global because
ITS tree reads it, and an input captured for the branch this call takes need not
read it at all -- such an input is captured and served with the name still
undefined. Withholding also makes the only actionable line in the report turn on
whether an unrelated global happens to be defined, and that masking is easy to
hit, since guards are installed in `sorted(guards)` order and
`GuardSource.LOCAL` sorts before `GLOBAL`, which sorts before
`LOCAL_UNSPECIALIZED_NN_MODULE`: the root's `G` accessor fails before an
`nn.Module` attribute guard runs, so the mismatch the reader needs to hear about
is hidden behind the `KeyError`. The report cannot tell the two shapes apart and
the advice is already hedged, so it is emitted next to the hint rather than in
place of it.

An entry's line quotes the guards `check_verbose` named, joined with `; `.
`GuardDebugInfo.user_stack` and `num_guards_executed` are dropped on purpose:
the verbose part usually embeds `# <source> # file:line in forward` already,
the stack is `None` for the `KeyError on G[...]` case this report exists to
explain, and one line per input is the point. Three of `check_verbose`'s
answers leave that line saying nothing, or spread it over several lines, and
each is a sibling's. A tree that ACCEPTS the call both dispatch passes rejected
answers with no parts, so here its entry prints nothing after `[i]`; the call is
refused all the same, and what the entry should say about it is #197150's.
A genuine failure can also arrive with no parts, and a part can carry a
boundary `splitlines()` breaks on; here such an entry prints nothing after
`[i]`, or spans several lines, the call is refused either way, and those two
lines are #197134's.

A describer that raises is not caught here. `check_verbose` runs paths
`check()` does not -- `DIMENSION_DYNAMIC_MARKING_GUARD` calls `py::repr` on
user objects, and a `TENSOR_MATCH` failure on a tensor of the compiled type
calls `is_parameter`, which runs `_ParameterMeta.__instancecheck__` -- so an
entry's describer can raise where the dispatch's rejection was clean, and when
it does the exception escapes the `raise RuntimeError(...)` argument and takes
the report with it, exactly as it escaped the parent's fall-through, whose
`AOTCompiledFunction.__call__` runs the same `check_verbose` unguarded. An
earlier revision ran each entry's `check_verbose` under its own `try` and
described the other entries anyway; measured without #197049's TorchFunction
restore -- now the bottom of this stack -- that catch continued on a thread the
throw had left broken and the lines it saved were wrong (FAQ below), so it is
gone from here, and the place a raising tree is read as no answer and reported
as one line is #196826, above, with the test that pins it.

One call the fall-through served is refused by the report, and that is
intended: a tree that rejected the call in both dispatch passes and accepts it
on a third evaluation. PARENT: for `[0]` only, the fall-through's
`AOTCompiledFunction.__call__` evaluated its guards a third time and served the
graph when that evaluation accepted -- with a `CountedKey(misses=2)` in the
slot of the one global `[0]`'s tree reads: `SERVED equal_to_x*3= True
compares= 3`. HEAD: the report's `check_verbose` is that third evaluation, an
accept there leaves the entry with nothing after its index, and the call
raises: `RAISED compares= 3`. An accept that arrives only on the third
evaluation is not a certified match -- a guard that does not answer
consistently, or a tag-safe fast path that refused without running the tree --
and the parent extended that third chance to `[0]` alone, by its position; a
result in any other slot never had it. The entry that says so, and
`test_no_match_message_when_a_guard_answers_inconsistently`, which pins the
raise and the three evaluations, are #197150's. A model with no compiled
results is not a case this commit changes: `results[0]` at the top of
`__call__` raises `IndexError: tuple index out of range` before any stage runs,
on the parent and here alike.

Otherwise the exception type stays `RuntimeError`, and the text `GuardManager
check failed` is replaced on the module path only: the function path's
`__call__` still raises it, and the five regexes this commit updates in
test_aot_compile.py belong to the dispatch tests below. One of those tests,
`test_module_dispatch_no_match_falls_through_to_the_first_result`, was named
and commented for the fall-through its zero-opt-out row now proves gone, so
it is renamed `test_module_dispatch_no_match_raises_unless_a_result_opted_out`
and its comment says what the rows show: a call neither result guards raises
and is handed to no result, and with `[0]` opted out its graph runs. Three
sibling dispatch tests named the same fall-through for the stage before or
after the one they pin --
`test_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts`,
`test_module_dispatch_serves_an_opted_out_result_from_any_position` and
`test_module_dispatch_rechecks_before_honouring_an_opt_out` -- and their
comments now name the stages the dispatch has: the opt-out last resort, then
this report. Their assertions are unchanged. A fourth,
`test_module_dispatch_serves_a_call_the_guard_tree_accepts`, said the
fall-through "re-checked compiled_results[0] and raised [0]'s L['mode'] == 0";
nothing is re-checked alone any more, so its comment now says what a call the
re-check did not rescue meets: this report, with `[0]`'s guard one line of it.

The report reuses the binding the dispatch judged, one per result, so it
explains the same binding rather than a fresh one, and the one bind per call
#197071 introduced holds end to end; the fall-through it replaces bound twice
more inside `AOTCompiledFunction.__call__`.
`test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature` now
also counts `prepare_f_locals` for a call nothing matches, and counts it apart
from the matched call's: the list is asserted `[results[0]]` and cleared after
the matched call, and asserted `[results[0]]` again after the no-match call,
so each bind is attributed to the call that made it -- a combined
`[results[0], results[0]]` would also accept a dispatch that bound the matched
call nowhere and the no-match call twice. The fall-through fails the second
assertion with `The length of the sequences mismatch: 3 != 1`, its no-match
call binding three times. The same test counts the report's entry lines -- one
per result off that single bind -- rather than its total line count, so a
footer line added later does not break it. Measured
once when this report was first written, against the dispatch before the
one-bind-per-call commit and this commit, and not re-run since: a report costs
12.6us against the old 15.0us, and the no-match path costs 18.5us against
27.9us at one input and 29.9us against 33.0us at two, and crosses over by four,
50.9us against 41.3us, where the report's N `check_verbose` calls and the
re-check's N `check()` calls outweigh the binds saved; with one bind per call
rather than per result it costs 30.2us against 43.1us at four. That path ends
in a raise, and the match path is the one every call takes.

The report is handed the results the dispatch judged as well: `__call__` reads
`compiled_results` once, and the report indexes `bound` against that tuple
rather than re-reading a public list an append or a replacement can have
changed under it -- re-read, an appended result asks for a binding the dispatch
never made, and an `IndexError` raised inside the `raise RuntimeError(...)`
argument takes the report's place.
`test_no_match_report_names_the_results_the_dispatch_judged` makes `[0]`'s
`check()` splice a second result into the list AHEAD of it mid-call, wraps
both results' `check_verbose` under one `Mock` so their call order is
recorded, and asserts the report counts one input and ran the first result's
describer alone; the splice is `[:] = [later, first]`, so the re-check pass
running the patched `check()` a second time leaves the list as it is.
Counting alone would not pin which result an entry describes: a report that
re-read the list and zipped it against `bound` would describe the spliced
result against `[0]`'s binding under a `Tried 1` header, and the two results
differ only in a closure scale, so their dtype-mismatch lines read alike. The
second call, over the spliced list, reports `Tried 2` with entries `[0]` and
`[1]` -- two, not one -- and the recorded order is `first, later, first`: the
spliced result's tree is described first, as the list now orders it, so a
report over `results[:1]` or `reversed(results)` fails here rather than only
in a test elsewhere.

The supplied-scope hint on an un-rebound load is pinned by #196825, a test-only
commit higher in the stack, which also pins that the advice above still reaches
a report whose only failure is a missing global. Folding that commit's test
lines down here would put a guarded global the loading process does not have in
the same commit as this report, which is the split this re-slice exists to
make; they land together in any case. Four more of the report's tests sit in
#197001, above #197048, since three of them pin that commit's forward naming:
that the hint stays scope-neutral for a caller-supplied `guard_globals=`, that
a CAPTURED result's report names no `forward` and never resolves it, that the
advice reaches a report whose every entry named a missing global, and that a
missing KEY inside a present global is not a missing global.

> **FAQ: an earlier revision ran each entry's `check_verbose` under its own
> `try`, so one raising describer did not cost the other entries their lines.
> Why is that gone?** Because without #197049's restore the catch continues on
> a thread the throw left broken, and the lines it saves are wrong; #197049 is
> now the bottom of this stack, and the catch is #196826's with its test.
> `RootGuardManager::check_verbose_nopybind` sets the TorchFunction TLS to
> `ALL_DISABLED` for its accessors and restores it on each of its return paths,
> not under RAII, so a `py::error_already_set` unwinding out of the tree skips
> the restore; `_reset_relational_guard_state()` is skipped the same way, and
> has no Python binding to call instead. Measured at that revision's tree with
> `_ParameterMeta.__instancecheck__` patched to raise -- the Python
> `is_parameter` reaches from `TENSOR_MATCH::check_verbose_nopybind`'s failure
> branch, the route a tensor subclass `__getattr__` takes -- on a two-input
> `ScaleModule` called with `x.double()`: the report arrived, `[0]` read `<guard
> check could not be described: RuntimeError(...)>`, and `[1]` read
> `GLOBAL_STATE changed: torch_function` instead of its dtype mismatch, since
> `[1]`'s tree was evaluated on the thread `[0]`'s throw had left disabled;
> after the report was caught, `torch._C._get_torch_function_state()` read
> `ALL_DISABLED` against `ENABLED` before the call, and `t + 1` on a
> `__torch_function__` subclass returned a plain `Tensor` without dispatching.
> Without the `try`, the same script raises `RuntimeError('user __getattr__
> raised')` out of `__call__` on this tree and on the parent's alike, and leaves
> the thread the same way -- an exposure `AOTCompiledFunction.__call__` has
> always had, which #197049 repairs inside `GuardManagerWrapper.check_verbose`
> for every caller. Fixing the C++ exit itself is outside this Python-only
> stack. Above that restore the catch is sound, and it is one change with the
> test that pinned it here,
> `test_no_match_report_describes_the_other_entries_when_one_raises`; both are
> #196826's, split out of this commit for review budget.

> **FAQ: an entry whose `check_verbose` ACCEPTS the call, or fails without
> naming a guard, prints nothing after `[i]` here, and a part carrying a line
> boundary spans several lines. Why not branch on `reason.result` and an empty
> `verbose_code_parts`, and collapse `splitlines()`, in this commit?** Because
> those branches are #197150's (the entry for a tree that accepted on the third
> evaluation) and #197134's (the entry for a failure that named no guard, and
> the one-line collapse), split out of this commit for review budget so that
> each lands next to the test that pins it and the report's plumbing here --
> the raise, the header, the per-entry join off the dispatch's own `bound` and
> `results`, the hint and the advice -- stays reviewable on its own; the call
> is refused all the same on every one of those answers, so nothing is served
> in the meantime that a sibling later refuses. What the reader is told in the
> meantime, measured at this tree against the parent's: with a
> `CountedKey(misses=2)` on the global `[1]`'s tree reads and a `mode=1` call,
> this tree raises `[0] L['mode'] == 0` over a blank `[1]` (`compares= 3`),
> and the parent raised `[0]`'s `L['mode'] == 0` alone (`compares= 2`) -- it
> never evaluated `[1]` a third time and said nothing of it, and with the probe
> on a global `[0]`'s tree reads it served the graph (above); so no `result=1`
> repr was ever printed for this answer. With #197134's fixture -- a
> `SetIterModule` iterating a set, `SEQUENCE_LENGTH` dropped by the filter,
> called with a shorter set -- this tree prints `  [0] ` blank, and the parent
> printed `GuardDebugInfo(result=0, verbose_code_parts=[], num_guards_executed=6,
> user_stack=None)`: no guard named either, but a `result=0` the blank entry
> here does not carry. That one entry is what this commit says less about than
> the fall-through did, for the three commits until #197134, which lands with
> it. Neither blank entry loses a hint: the hint rides on a part that reads
> `KeyError on G[...]`, matched whole by `_names_a_missing_global`, so an
> answer with no parts named no missing global -- an accept has no failure to
> hint, and the short-set failure is not about a global -- and the absent hint
> is the accurate answer there, not a second loss.

> **FAQ: a report whose entries all failed on the same missing global repeats
> the hint on every one of them. Why not one hint per report here?** Because
> where the hint sits is #197149's, the next commit, which gives the report one
> `For [i, j]:` line per distinct sentence naming the entries that share it,
> and pins the count at one in
> `test_aot_compile_module_missing_global_hint_names_the_resolved_module` and
> `test_no_match_message_hints_only_the_entry_that_named_a_missing_global`.
> Here each entry carries its own hint, appended with ` -- ` as the
> fall-through appended it to `[0]`'s message, so the five tests below that
> assert the hint's text keep passing across the split. Measured at this tree,
> the report `test_aot_compile_module_missing_global_hint_names_the_resolved_module`
> produces on its first load is four lines, the two entries 203 characters each
> and identical, with `a guarded global is missing` twice; that test asserts
> the text with `assertIn`, as do the other tests built on
> `_two_input_global_guard_artifact`, so none sees the count, and pinning the
> repetition here only to remove it one commit up would assert something no
> user is meant to rely on. The class docstring describes what this commit
> does -- one line per result, carrying the hint when that result's guards
> failed on a missing global -- and #197149 rewrites it for the `For` line.

> **FAQ: `test_no_match_message_keeps_the_advice_for_every_entry` asserts the
> hint with `assertIn` over the whole message. Why not assert it is a suffix
> of the `[1]` line?** Because the hint's line is #197149's, the next commit,
> which replaces that very assertion with `For [1]: a guarded global is
> missing` and `message.count("a guarded global is missing") == 1` -- the
> anchoring, at the placement the report keeps. Here the hint is appended to
> `[1]`'s own line, and a suffix assertion would pin a placement the next
> commit removes and be rewritten one commit up. What holds at both placements
> is asserted here: the `[0]` line (`lines[1]`) does not carry the hint, and
> neither does the advice, which is the last line. Measured at this tree, a
> hint hoisted onto the advice, a hint appended to every entry with the
> `_names_a_missing_global` gate dropped, and a hint attached to the previous
> entry's line each fail those assertions, and #197149 cherry-picks clean on
> top of them with its renamed test green. The two substrings the test also
> asserts are not one check twice: `a guarded global is missing` opens all
> three scopes' sentences, while `the module the compiled function was traced
> in` is the CAPTURED wording alone -- SUPPLIED reads `the live scope this
> artifact was loaded against` and RECONSTRUCTED `the scope rebuilt from the
> artifact` -- so the second pins that an in-process capture's result is
> hinted for the scope it resolved against.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_no_match_error
python test/dynamo/test_aot_compile.py -k test_no_match_message_keeps_the_advice_for_every_entry
python test/dynamo/test_aot_compile.py -k test_no_match_report_names_the_results_the_dispatch_judged
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_no_match_raises_unless_a_result_opted_out
python test/dynamo/test_aot_compile.py
```

The whole file runs 210 tests, `OK (skipped=6)`; the parent's file
defines three fewer. Every `-k` above fails with the parent's `aot_compile.py`
under this test file (5/5): the three that assert on report text (`No AOT
compiled graph matched this call`, `[0] L['mode'] == 0`, `Tried 1 compiled
input(s)`) find the fall-through's `GuardManager check failed` message instead,
the binding test sees three binds for the no-match call against the one it
expects, `The length of the sequences mismatch: 3 != 1`, and the renamed
test's zero-opt-out row finds `GuardManager check failed` where it expects
`No AOT compiled graph matched` (its two opt-out rows pass on both, as they
should: an opted-out `[0]` is served on the parent and here alike).

`test_aot_compile_module_no_match_error` asserts that each of the two entries
is one line of the report -- the two lines after the header, with unindented
advice after them -- rather than that the whole report is four lines, and that
each entry says something after its index: reporting an entry as
`str(GuardDebugInfo)` instead of the joined one-line reason makes line 2 read
`result=...` and fails it, printing `  [0] ` with nothing after the index fails
it with `entry says nothing: '  [0] '`, while an advice line a later commit
appends does not.

Withholding the advice when an entry named a missing global fails
`test_no_match_message_keeps_the_advice_for_every_entry` on `Add a
ModelInput`.

Reading `self.compiled_results` in the report again fails
`test_no_match_report_names_the_results_the_dispatch_judged` with `IndexError:
list index out of range` raised in place of the report; re-reading it zipped
against `bound`, with the header off `results`, passes the header and entry
counts and fails it on the describer order. Describing `results[:1]` fails it
on the second call's entries, `'Add a ' != '  [1] '`, and `reversed(results)`
on the order, `'first' != 'later'`. Hoisting the hint onto the advice,
dropping the `_names_a_missing_global` gate, and attaching the hint to the
previous entry's line each fail
`test_no_match_message_keeps_the_advice_for_every_entry` with `'a guarded
global is missing' unexpectedly found in` the advice or the `[0]` line. All
were run at this tree.

`test_no_match_message_keeps_the_advice_for_every_entry` captures through
`_aot_compile_mode_branches`, whose `_hide_leaked_dynamo_globals` pops the
minted globals a sibling's capture leaked and strips this test's own in cleanup
(run alone in a fresh process, the inline capture it replaces left eight
minted names in this module's dict -- two `__builtins_dict___*`, two
`__compiled_fn_*` and four `__import_*` aliases; this form leaves none), and
it registers the `AOT_BRANCH_SCALE` restore with
`addCleanup` before deleting the name, so an interrupt anywhere leaves the
module dict whole.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 31dd3ef
Pull-Request: #196823
pytorchmergebot pushed a commit that referenced this pull request Sep 18, 2026
…h over a raise (#197391)

**Problem.** After #196826, dispatch that serves a graph over another result's raise does so silently, so a broken artifact that never costs the caller an answer is never noticed.

**Fix.** Log one warning per (index, exception type, opt-out state) on the `torch._dynamo.aot_compile` logger whenever a graph is served with a raise on record, deduplicated per model, quoting the raise and advising a fix.

**Summary.** Two commits below, #196826 made `AOTCompiledModel` dispatch read a guard tree that raises as no answer, so a match found beside the raise is served, and so is the raiser's own accept on the second pass, and both serves were silent: nothing else records the raise on a serving path (the report is never built), so a broken artifact that never costs the caller an answer is never seen, and the one thing a refusal would have bought -- that a raise dispatch served over cannot go unrecorded -- was not bought. This commit buys it with a warning: every path that RETURNS a graph with a raise on record logs one per index that raised on the `torch._dynamo.aot_compile` logger, quoting its last raise, naming the index served and what the raise left stale, and giving one sentence of advice whose shape depends on whether the raiser opted out of guard checks. Serving and warning beats refusing because the raise says nothing about the result that did answer and a refusal would not undo the relational residue a C++ throw leaves in the tree (a `NO_TENSOR_ALIASING` set, or under `enable_cpp_symbolic_shape_guards` a `SYMBOLIC_SHAPE_GUARD` count), which can bend the tree's NEXT check with no raise on record to veto. The warning is deduplicated per `(index, exception type name, opt-out state)` in a per-model set kept beside weak references to the results it was logged about, so a hot loop over a broken artifact logs once per defect rather than once per call, the set starts over when `compiled_results` holds other results, and the one-shot is spent only after `log.warning` returns and only when the logger's level would let the record through. Every decision here but the field's shape is pinned by a test, measured by reverting it on its own against the whole file, and the existing tests of #196826 and #197390 that reached a serving path now read the log.

## What the warning looks like

```python
model = self._model_with_stub_trees(RaisingTree("guard tree is unhappy"), Accepts())
model(x)          # served by [1]; parent: silent; now one WARNING on torch._dynamo.aot_compile:
# AOT compiled input [0]'s guard check raised RuntimeError: guard tree is unhappy; dispatch served [1]
# rather than propagating it. Fix or drop input [0]: its next check can reject a call it fits or
# accept one it does not.
model(x)          # same defect, same results: silent
```

## Order to review

`_same_results`, hoisted out of `_binds_alike` because the warning's dedup asks the same question -- are these the results last judged? -- of a weak-reference tuple of its own; the `_warned` field beside `_binding_verdict`; `_warn_swallowed` beside `_binds_alike` and its three call sites in `__call__`, one per serving path -- a match in the scan, a match on the second pass, and the last resort serving the first opted-out result while an opted-out result's raise is on record; then `_model_with_stub_trees`'s `opt_out` keyword, whose first callers are here, the `Rejects` stub, now with the `check_verbose` a report path would quote, as `RaisesThenRejects` has, and `RaisesUnprintable`, and the tests, the new ones -- one of them parametrized over the three serving sites -- and the ones already here that now read the log: those the commit below added over stub trees, and those of #196826's whose raise arrives through the real pybind boundary, which is what pins the unwrap.

## The change

```python
def _same_results(prior, results):
    return len(prior) == len(results) and all(w() is r for w, r in zip(prior, results))

class AOTCompiledModel:
    _warned: tuple[tuple[weakref.ref[AOTCompiledFunction], ...], set[tuple[int, str, bool]]]

    def _warn_swallowed(self, results, raised, served):
        if not log.isEnabledFor(logging.WARNING):      # a dropped record must not spend the one-shot
            return
        over, warned = self._warned
        if not _same_results(over, results):           # other results at these indices: start over
            warned = set()
            self._warned = (tuple(weakref.ref(r) for r in results), warned)
        for i, e in raised.items():
            kind, reason = _unwrapped_raise(e)         # the same unwrap the report line reads
            enabled = results[i]._guard_check_enabled
            if (i, kind, enabled) in warned:
                continue
            advice = ... if enabled else ...           # the two sentences below
            log.warning("AOT compiled input [%d]'s guard check raised %s: %s; dispatch served [%d] "
                        "rather than propagating it. %s", i, kind, _quoted(reason), served, advice)
            warned.add((i, kind, enabled))             # spent LAST: _quoted can let an interrupt out

    def __call__(self, *args, **kwargs):
        ...
        for i, result in enumerate(results[1:], 1):    # the scan
            if accepts(i, result):
                if raised:
                    self._warn_swallowed(results, raised, i)
                ...
        for i, result in enumerate(results):           # the second pass
            if accepts(i, result):
                if raised:
                    self._warn_swallowed(results, raised, i)
                ...
        if not any(map(enabled.__getitem__, raised)):  # the last resort
            for i, result in enumerate(results):
                if not enabled[i]:
                    if raised:
                        self._warn_swallowed(results, raised, i)
                    ...
```

## Serve and warn, rather than refuse

A match found after a raise is served, and warned about, rather than refused. The raise says nothing about the artifact that did answer, and refusing would not undo the relational residue a C++ throw leaves: by the time dispatch decides anything the throw has already happened, so a refusal costs the caller a graph whose guards passed and repairs nothing. That holds where the artifact that answered IS the one that raised, even though the residue can bend an accept and not only a rejection.

**What a throw leaves stale.** A throw elsewhere in the tree unwinds past `RootGuardManager::_reset_relational_guard_state()`, which the root check calls only at its normal exits (`guards.cpp:4386-4415`, none under RAII) and which is every relational guard's only reset (`:4543-4547`). What that leaves in a default build, wherever the tree guards more than one tensor against aliasing, is the rejection: `NO_TENSOR_ALIASING` answers false for a tensor already in its `_unique_tensors` (`:2710-2718`), which is cleared in `reset_state()` alone (`:2730-2732`), so the set the throwing evaluation filled rejects a call the tree fits. That guard has one install site and one condition, `len(no_tensor_aliasing_names) > 1` (`torch/_dynamo/guards.py:5409-5416`), and that call is also what registers the resetter the throw unwinds past (`add_no_tensor_aliasing_guard`, `guards.cpp:4339-4344`), so an artifact whose tree checks a single tensor against aliasing has no such set to leave stale. The accept needs `enable_cpp_symbolic_shape_guards`, `False` by default (`torch/_dynamo/config.py:560`) -- the qualifier this file already carries on the veto's comment (`aot_compile.py:1991-1992`) and now on the class docstring too: with that config on, `SYMBOLIC_SHAPE_GUARD` keeps the `_args_seen` this evaluation reached, since `_reset_relational_guard_state` is the sole caller of its `reset_state()` (`guards.cpp:2887-2889`) and `check_nopybind` (`:2816-2843`) zeroes it only on the complete path (`:2837`), and the next evaluation reaches `_nargs` early and calls `_guard_check_fn` over an `_args_int` buffer whose remaining slots still hold the previous call's values.

| residue | guard | needs | bends the next check toward |
| --- | --- | --- | --- |
| `_unique_tensors` left filled | `NO_TENSOR_ALIASING` | more than one tensor guarded against aliasing (default build) | a rejection of a call it fits |
| `_args_seen` left counted | `SYMBOLIC_SHAPE_GUARD` | `enable_cpp_symbolic_shape_guards=True` (off by default) | an accept of a call it does not fit |

The advice names both directions in either build: neither residue can be told from a real answer or cleared from Python, and the accept half is one config flag away. Nor would a per-call veto contain it: measured on a one-raise stub with two inputs, [0] raises inline, [1]'s real guards match, dispatch serves [1], and the NEXT call gets [0]'s post-throw answer with nothing on record -- no raise, so nothing to veto.

### The enabled advice

So the warning for an enabled tree names both directions a stale tree can bend a later answer:

```
Fix or drop input [i]: its next check can reject a call it fits or accept one it does not.
```

It holds at any index and needs no qualification.

### The opted-out advice

`check()` ignores the opt-out, so an opted-out tree's rejections and accepts are acted on in both passes like any other's. A stale rejection forfeits only the calls the last resort does not then hand it: the last resort serves the FIRST opted-out result, and only when no enabled input raised, so the rejection costs it the call when another opted-out result sits ahead of it (`[opted-out A, opted-out B]`, B's stale tree rejecting a call it fits: A's unguarded graph is served where B's accept would have served B) or when an enabled input's raise withholds the last resort (`[enabled E raising, opted-out B]`: B's stale rejection turns a serve into the no-match report). A stale accept serves its graph for a call it does not fit ahead of a later result whose guards would have matched, a cost the opt-out never promised (opt-out means the last resort, after the real matches), and one no later stage undoes. So the opted-out warning names that one direction:

```
Input [i] opted out of guard checks, but its next check can accept a call it does not fit ahead of a later match; fix or drop it.
Input [i] opted out of guard checks, but its next check can accept a call it does not fit; fix or drop it.     # from the last index
```

The `ahead of a later match` clause is appended only when `i + 1 < len(results)`, because the displaced match is positional: from the LAST index there is no later result to displace, and what a stale accept displaces there instead depends on the results ahead of it. Measured, case by case:

| results | what a stale accept at the last index displaces |
| --- | --- |
| two opted-out, `Rejects` at [0], raiser at [1] | the last resort serves [0]; with [1]'s tree accepting on the second pass instead -- which is what a stale accept looks like -- [1] is served, so [0]'s unguarded graph is displaced by the very result the opt-out promised to serve last |
| a lone opted-out raiser | nothing: the raiser is itself the first opted-out result, so the last resort would have served it anyway; warns `dispatch served [i]` for its own index |
| enabled `Rejects` at [0], opted-out raiser at [1] | nothing, same reason; warns `dispatch served [1]` |
| enabled raiser at [0], opted-out raiser at [1] | the no-match report: the pair raises the report, and with [1] accepting on the second pass it serves [1] |

None of those is the harm the clause names, so from the last index the advice states the remedy alone, `accept a call it does not fit; fix or drop it.`, and the class docstring says what the accept displaces there instead. Each advice is one sentence; the reasoning above, and the cost the raise itself has for an opted-out tree -- its graph is reachable only through its own later accept or the last resort, which any enabled tree's raise withholds -- is in the class docstring, written once for the three sites that log it and beside the dispatch rules it explains, rather than repeated in every log line. The "its own later accept" is load-bearing there too: an opted-out tree that raises once and then accepts is served by that accept on the second pass with its first pass's raise on record, so "reachable only through the last resort" outright would be false on the very path the second-pass site logs from.

## The dedup key: `(index, exception type name, opt-out state)`

**Why the opt-out state is in the key.** `disable_guard_check()` flips a field on the SAME result: the weak references still dereference to the results last warned about, `_same_results` answers true, and no reset runs, so a key of `(index, type)` alone would log the enabled advice for a raiser and never the opted-out one after the caller opts it out -- the advice that names the stale accept, which for an opted-out tree is the only cost -- though `check()` ignores the flag and the tree raises on, so the warning is still reached.

```python
model = self._model_with_stub_trees(RaisingTree("unhappy"), Accepts())
model(x)                                          # Fix or drop input [0] ...
model.forward.compiled_results[0].disable_guard_check()
model(x)                                          # Input [0] opted out of guard checks, but ... dispatch served [1]
model(x)                                          # silent
```

**Why the type name is in the key, and what it buys.** The type name tells two defects at one index apart only when they raise different types, which real trees seldom do: a `TORCH_CHECK` that fires in a guard is a `c10::Error`, translated to `RuntimeError` at the pybind boundary (`CATCH_TH_ERRORS`, `torch/csrc/Exceptions.h:96`), and every plain `TORCH_CHECK` reached at check time in `guards.cpp` lands there. The one typed one that a check reaches is `FrameLocalsGuardAccessor::check_nopybind`'s `TORCH_CHECK_TYPE` (`guards.cpp:5655`), which `_CATCH_GENERIC_ERROR(TypeError, ...)` (`Exceptions.h:74`) takes before the `RuntimeError` arm, so it would key as `TypeError`; it needs an `f_locals` that is not a dict, which this path never passes -- `prepare_f_locals` returns one it built itself. Every other typed `TORCH_CHECK` in the file is in a constructor, a manager factory or `get_type_of_guarded_value`. So under real leaves "once per defect" is closer to "once per index and opt-out state"; the docstring says so.

**Why the served index is not in the key.** The served index is in every warning but deliberately not in the key: the remedy is the raiser whichever result answered, so a defect whose serve moves is reported once, for whichever serve came first. `test_aot_compile_module_does_not_warn_again_when_the_serve_moves` pins that: a `RaisingTree` at [0] and two `Accepts`, the first call served by [1] and warning `dispatch served [1]`, and with [1]'s stub patched to refuse afterwards the next call, served by [2] over the same raise, silent. A key of `(i, kind, enabled, served)` fails it alone, `Unexpected logs found` quoting a second warning that says `dispatch served [2]`. The docstring says this too, so a reader who sees one served index does not take it for the whole story.

## When the one-shot is spent

A one-shot is spent only by a warning the logger's level let through, which takes two things.

**The level gate.** `_warn_swallowed` returns before anything else when `log.isEnabledFor(logging.WARNING)` is false: a logger whose effective level is above WARNING when the first serve happens -- a `TORCH_LOGS` setting, a library that raised the level at import, a `logging.disable` -- would otherwise record the key and drop the record, and lowering the level afterwards would never surface that defect for the model, a runtime-divergence warning about a broken artifact lost silently, the outcome the commit exists to prevent. That gate is the level and `logging.disable` and nothing further, which is why this says the logger's LEVEL rather than the log: measured directly, a `logging.Filter` on the logger and a handler whose own level is above WARNING each drop the record while `isEnabledFor(WARNING)` is still true, and nothing on this path can see either, so under those two the key is spent on a warning nobody reads.

**`add` after `log.warning`.** `warned.add` is the loop body's LAST statement, after `log.warning`, because that call's argument list reaches user code once more: the text is `_quoted(reason)`, which catches `Exception` as the handlers do, so a `BaseException` out of the recorded exception's `__str__` leaves `_warn_swallowed` from there, discarding a graph whose guards passed, and a key added ahead of the call would silence that defect for the rest of the model's life.

The two are independent and neither substitutes for the other: `log.warning` returns the same whether it emitted or filtered, so the ordering says nothing about the level, and the level gate is passed long before the quote runs. Each has its own test below, and each fails only its own.

## The unwrapped raise, quoted

Both the type the warning names and the dedup key are read off the UNWRAPPED exception through `_unwrapped_raise`, the helper the report line already reads, so the two records of one raise cannot drift:

```python
# a DICT_NOT_CONTAINS leaf raising ValueError("boom from __eq__") through the real pybind boundary
# without the unwrap: "[0]'s guard check raised SystemError: <built-in method check of pybind11_builtins... returned a result with an exception set>"
#                     key (0, "SystemError", enabled) for every raise at [0], so two defects collapse into one warning
# with the unwrap:    "[0]'s guard check raised ValueError: boom from __eq__"
#                     a ValueError and a TypeError at one index log twice
```

The text is `_quoted(reason)`, the guarded `str()` the report line uses, and not the exception object: `logging` formats a record lazily, so an object whose `__str__` raises reaches the handler's `handleError` -- a traceback on stderr and no warning -- where the report line would have said `<str() raised TypeError>`. `_quoted` guards `Exception` and not `BaseException` on both paths, and its comment now says what that costs on each: the report's quote is built over a call that was already failing, the warning's over a graph about to be served, which is the ordering above. The warning's quote is otherwise raw; only `_raised_line` collapses separators, since only the report is read back with `splitlines()`.

## A per-model set beside weak references

The dedup set is a field on the model, not `torch._logging.warning_once`, whose `functools.cache` key includes every argument -- passing the exception object defeats the dedup outright -- and whose cache is process-global, so the first model to log would silence every later one with the same defect. Measured on this file: with `_warn_swallowed` calling `warning_once` with the message it builds instead of consulting the per-model set, tests fail on `no logs of level WARNING or higher triggered` where a later test's model hits a defect an earlier test's model already logged, and `..._does_not_warn_again_when_the_serve_moves` on `Unexpected logs found` quoting `dispatch served [2]`, since a moved serve builds a different message and the cache is keyed on what it is passed. Any runner that runs a test twice in one process sees the same sharing -- `--repeat` loops `unittest.main` in place (`torch/testing/_internal/common_utils.py:1642-1645`).

The key's index is a bare list position, and `compiled_results` is public: a list that changed can put another artifact at a warned-about index -- a `pop()` shifts every later result down one, and a one-result model can have its only artifact swapped in place -- whose raise the first warning never described. So the triples are kept beside weak references to the results they were logged about, one field on the terms `_binding_verdict` states, and `_warn_swallowed` starts the set over when the results it is about to log for are not those. That is judged where the warning is logged, not with the binding verdict, although the verdict is re-decided on the same change: it is re-decided only when a second result needs a binding, which a one-result model never reaches, so a reset tied to it never runs for the model that reaches the warning most simply -- one opted-out artifact whose tree raises -- and that model's first `(0, kind, False)` would silence every artifact later put at [0]. The cost is one repeat per mutation, not per call.

The field is `init=False` and built by a factory: a caller-supplied set would share one dedup across models, the process-global behaviour it exists to avoid, and a class-level `default` would share one as surely, masked at runtime only by the reset above, which a model's first warning runs. Every decision above but the field's shape is pinned by a test here, measured by reverting it on its own against the whole file at this commit. The shape has no behavioural pin to give it: a class-level `default` is masked by the reset on every path that logs, and the per-model dedup itself is `test_aot_compile_module_warns_once_per_model_not_per_process`'s.

## A method, gated at three sites

`_warn_swallowed` is a method beside `_binds_alike`, not a closure in `__call__`: its three call sites gate it on `if raised:`, so a closure there was built on every multi-result call and entered on none of the healthy ones. Measured on a replica of the scope shape (min of 7 x 2M):

| variant | cost |
| --- | --- |
| building a three-cell annotated closure and dropping it | 140 ns per call over not building one |
| a two-result dispatch itself | 22-25 us across runs of either version |

Invisible in that noise, and paid on every call all the same; the method costs the healthy path nothing.

Those gates are also what lets a results list be changed and changed back without losing the keys already in force: a serve with nothing on record never reaches `_warn_swallowed`, so it never compares the results it is serving against the ones last warned about and never installs a fresh set over them. `test_aot_compile_module_warning_survives_a_serve_that_does_not_warn` pins that -- warn about a `RaisingTree` at [0] with an `Accepts` at [1], then put a `(Rejects(), Accepts())` list in its place and serve it, which warns nothing, then put the warned-about results back and assert the serve of them is silent. The intermediate list has to reject at [0] so its serve reaches the scan site, the one the first call warned from; a lone `Accepts()` would be served by the inline first-result path, which calls none of the three. Deleting all three gates and calling `_warn_swallowed` unconditionally fails that test and only that test, `Unexpected logs found` quoting the first warning again.

## Tests

The stubs: `Rejects` (refuses every call, with the `check_verbose` a report path would quote), `RaisesThenAccepts` (raises in the scan, accepts on the second pass; hoisted from the raised-then-accepted test to module level) and `RaisesUnprintable` (every check raises an `UnprintableError`), built into models by `_model_with_stub_trees(*stubs, opt_out=False)`.

- `test_aot_compile_module_serves_a_later_match_after_an_earlier_raise` now reads the scan's warning and pins the whole line: `AOT compiled input [0]'s guard check raised RuntimeError: guard tree is unhappy; dispatch served [1] rather than propagating it. Fix or drop input [0]: its next check can reject a call it fits or accept one it does not.` Logging the raiser's index in the served slot fails that pin, the line coming out saying `dispatch served [0]`.
- `test_aot_compile_module_serves_a_tree_that_raised_and_then_accepted` now reads the second pass's warning -- `[0]'s guard check raised RuntimeError: the scan is unhappy`, `dispatch served [0]`, both directions of the advice -- and asserts the next call, with no raise on record, is served under `assertNoLogs`.
- `test_aot_compile_module_opted_out_advice_allows_the_raisers_own_accept` is the same shape opted out: the one call logs once, `checks == 2`, and the whole line is pinned -- `dispatch served [0]` and `Input [0] opted out of guard checks, but its next check can accept a call it does not fit; fix or drop it.`, so no `Fix or drop input` (the enabled advice's opening), no charge of a stale rejection, and, the one result being the last, no later match named. `served == i` at that site cannot tell this serve from the last resort's of the same one-result model, so the advice says nothing that is true on only one of the two paths. The clause's two branches are pinned against each other: this test and `..._warns_before_the_served_graph_runs`'s `last_resort` case, whose raiser is the last of two, assert it absent, and `test_aot_compile_module_warns_again_after_the_raiser_opts_out`, whose opted-out raiser at [0] has an `Accepts` behind it, asserts it present. Appending the clause unconditionally fails this one on its whole-line pin and the cases that assert it absent, `'accept a call it does not fit; fix or drop it.' not found`. Dropping the clause unconditionally fails `..._warns_again_after_the_raiser_opts_out` alone, `'does not fit ahead of a later match' not found`.
- `test_aot_compile_module_warning_advice_follows_the_raiser_not_the_served` pins which result's opt-out the advice reads: an enabled `RaisingTree` at [0] served over by an opted-out `Accepts` at [1] -- `check()` ignores the flag, so [1] matches in the scan -- logs one warning with `dispatch served [1]` and `Fix or drop input [0]`, and not the last-resort advice. Reading `results[served]._guard_check_enabled` fails this test, `'Fix or drop input [0]' not found` in a warning reading `Input [0] opted out of guard checks, but`, and one other, `test_aot_compile_module_warns_again_after_the_raiser_opts_out`, whose served [1] stays enabled: its first call then records `(0, "RuntimeError", True)` and its second, after [0] opts out, is silent, `no logs of level WARNING or higher triggered`. Every other warning test's raiser and served result share an opt-out status.
- `test_aot_compile_module_second_pass_warning_names_the_index_served` pins the second pass's site: a `RaisingTree` at [0] and a `RaisesThenAccepts` at [1], so [0] raises inline and again on the second pass, [1] raises in the scan and accepts on the second pass, and the call is served by [1] with raises on record for both: two warnings, each saying `dispatch served [1]`. The raised-then-accepted test reaches the same site with one result, where served, raiser and 0 coincide, so this is the test that fails when that site logs `0` for the served index -- `Expected 2 but got 0` on the `dispatch served [1]` count, both warnings saying `dispatch served [0]` -- and it fails under the served-as-raiser mutation too, `Expected 2 but got 1`.
- `test_aot_compile_module_scan_warning_names_the_index_served` pins the scan site's served index at a value other than the one every other test reaches it with: a `RaisingTree` at [0], a `Rejects` at [1] and an `Accepts` at [2], so the scan serves [2] over [0]'s raise -- one warning, `dispatch served [2]` and `Fix or drop input [0]` -- and a constant `1` for that site fails it alone, `'dispatch served [2]' not found`. The last resort's index is pinned by `..._warns_before_the_served_graph_runs`'s `last_resort` case, whose stubs are a `Rejects` at [0], enabled and refusing in both passes, and an opted-out `RaisingTree` at [1]: no enabled tree raised, so the last resort serves the first opted-out result, [1], and the warning reads `[1]'s guard check raised RuntimeError: unhappy`, `dispatch served [1]` and `opted out of guard checks, but`; a constant `0` for that site fails that case alone, `'dispatch served [1]' not found`. Before these, every test that reached the scan's site was served by [1] and every one that reached the last resort's by [0], so either constant passed the whole file.
- `test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning` (renamed from `..._in_the_report`) reaches the last resort with two opted-out raisers, so one call logs two warnings and the warning about [1] says `dispatch served [0]`, the served index and the raising index read each from its own source. [1]'s message holds a form feed and a record separator, and the warning is asserted with both in place: collapsing the warning's quote as the report line's is fails it alone. Its report call, before [1] opts out, runs under `assertNoLogs`: the report chains the raise and logs nothing about it.
- `test_aot_compile_module_warns_once_per_model_not_per_process` pins the per-model set: two models with the same defect each log once, and a second call on the first logs nothing; it also pins the opted-out advice, since the helper's result opted out -- handing it the enabled tree's advice (forcing the `enabled` test in `_warn_swallowed` true) fails it with `'opted out of guard checks, but' not found` in a warning reading `Fix or drop input [0]`.
- `test_aot_compile_module_warns_once_per_exception_type_at_one_index` pins the type name in the key on a stub raising `ValueError` and then `TypeError` with one text: two warnings, and a third call raising the `TypeError` again logs nothing, so a key of `(i, enabled)` fails it alone, `Expected 2 but got 1` on `len(logs.output)`; a key of `(i,)` fails it the same way and the opts-out test next on its second call.
- `test_aot_compile_module_warns_again_after_the_raiser_opts_out` pins the opt-out state: a `RaisingTree` at [0] and an `Accepts` at [1] warn `Fix or drop input [0]` once, `disable_guard_check()` on [0] makes the next call warn once more with `Input [0] opted out of guard checks, but` and `dispatch served [1]`, and the call after that is silent. A key of `(i, kind)` fails it alone, `no logs of level WARNING or higher triggered` on the second call.
- `test_aot_compile_module_warning_is_not_spent_while_the_logger_drops_it` pins the gate: the first call runs under `assertNoLogs(level="ERROR")`, which sets the logger's level to ERROR for its block, the second under `assertLogs(level="WARNING")` logs the one warning, and the third is silent. Deleting the `isEnabledFor` test fails it alone, `no logs of level WARNING or higher triggered` on the second call, with the `add` where it is.
- `test_aot_compile_module_warning_not_spent_by_an_interrupt_from_str` pins the placement, and is the only test that does: a stub raising a `Boom` whose `__str__` raises a `KeyboardInterrupt` the first time it is called, beside an `Accepts`, so the first call leaves as that interrupt with the graph unserved and the call after it warns once, `[0]'s guard check raised Boom: boom from __str__` and `dispatch served [1]`. Moving the `add` back ahead of `log.warning` fails it alone, `no logs of level WARNING or higher triggered` on that second call. Deleting the dedup -- the `(i, kind, enabled) in warned` test and the `add` beside it -- does not fail this one, whose second call is the first warning it gets; it fails the tests whose repeat call has to be silent, `Unexpected logs found` quoting the repeated warning.
- The unwrap -- both the type the warning names and the key's type name -- is pinned by the two tests of #196826's whose raise arrives through the real `DICT_NOT_CONTAINS` leaf and now read the log, `..._raise_from_an_opted_out_result_withholds_nothing`, where the last resort serves the opted-out raiser's own graph, and `..._serves_a_later_match_over_a_raising_leaf`, where the scan serves [1]: reading the type and the text off the `SystemError` pybind hands back fails both, `"[0]'s guard check raised ValueError: boom from __eq__" not found` in a warning reading `raised SystemError: <built-in method check of pybind11_builtins...`. #196826's third serving test, `..._serving_over_a_raise_frees_this_call_s_inputs`, reads the log under a bare `assertLogs`: the record it captures holds formatted ints and strings only, so the warning does not keep alive the input that test watches die with the cycle collector off.
- `test_aot_compile_module_warns_again_about_a_replaced_single_result` is the test that tells the reset's placements apart: an opted-out artifact whose tree raises warns once, the next call is silent, `compiled_results[0] = <another such artifact>` makes the call after it warn once more, quoting the replacement's text, and the call after that is silent again. The displaced result is held in a local across the swap, so a dead weak reference cannot explain the reset and only the identity comparison in `_same_results` can: the swap would otherwise drop the last strong reference to the displaced result (a one-result model never sets `_binding_verdict`), and a `_same_results` that tested each prior reference for liveness instead of identity passed the test as it stood; held, that mutation fails it on the call after the swap, `no logs of level WARNING or higher triggered` (and, `_same_results` being `_binds_alike`'s test too, #197071's `test_module_dispatch_judges_a_replaced_result_on_its_own_binding`). Never starting the dedup over (forcing the `_same_results` test true) and gating the reset on two or more results each fail it alone with the same text on the same call; its multi-result twin, where a `pop(0)` moves a raising artifact to a warned-about index, is #197195's `test_aot_compile_module_warns_again_about_a_replaced_index`, which passes under either misplacement because a two-result model does re-decide the binding verdict.
- `test_aot_compile_module_warning_survives_a_raise_whose_str_raises` pins `_quoted` on this path: an opted-out stub raising `UnprintableError` logs one warning reading `[0]'s guard check raised UnprintableError: <str() raised TypeError>`. Handing `log.warning` the exception object instead fails it alone, `TypeError: str() of the tree's exception raised` out of the capturing handler's `format`.
- `test_aot_compile_module_warns_before_the_served_graph_runs` is `@parametrize`d over the three serving sites. A call that ends before dispatch picks a result leaves as the exception that ended it and records nothing: a later result's tree raising a `BaseException`, a later result's bind raising `TypeError`, `_binding_key` raising over a malformed artifact, and the report builder itself raising. The first two, the ones a guard manager can produce, are pinned in #197219 under `assertNoLogs`; the FAQ below says why none of the four warns. The warning is logged before `_serve` runs the graph, since it describes the dispatch decision, so a served graph that raises leaves with the warning logged. That is one decision at three sites, and the three cases differ only in the stubs, the served index and the opt-out -- each patching the served result's `_serve` to raise and reading the one warning out of the call that raised:

| case | stubs | reads |
| --- | --- | --- |
| `scan` | `RaisingTree` at [0], `Accepts` at [1] | `dispatch served [1]` |
| `second_pass` | a lone `RaisesThenAccepts` | `[0]'s guard check raised RuntimeError: the scan is unhappy`, `dispatch served [0]` |
| `last_resort` | `Rejects` at [0], opted-out `RaisingTree` at [1] | `dispatch served [1]`, `opted out of guard checks, but` |

  Every other served graph here (`ScaleModule`'s, or `GlobalConfigModule`'s in the later-match test) returns, so moving one site's `_warn_swallowed` call after `_serve`, measured a site at a time against the whole file, passes the rest of it and fails that site's case alone, `no logs of level WARNING or higher triggered`.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serves_a_later_match_after_an_earlier_raise
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_before_the_served_graph_runs
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serves_a_tree_that_raised_and_then_accepted
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_opted_out_advice_allows_the_raisers_own_accept
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warning_advice_follows_the_raiser_not_the_served
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_second_pass_warning_names_the_index_served
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_scan_warning_names_the_index_served
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_once_per_model_not_per_process
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_once_per_exception_type_at_one_index
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warning_survives_a_raise_whose_str_raises
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_again_about_a_replaced_single_result
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_again_after_the_raiser_opts_out
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_does_not_warn_again_when_the_serve_moves
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warning_not_spent_by_an_interrupt_from_str
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warning_survives_a_serve_that_does_not_warn
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warning_is_not_spent_while_the_logger_drops_it
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_raise_from_an_opted_out_result_withholds_nothing
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serves_a_later_match_over_a_raising_leaf
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serving_over_a_raise_frees_this_call_s_inputs
python test/dynamo/test_aot_compile.py
lintrunner --take RUFF,PYFMT torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py
```

The tests above were also run against the commit below's
`torch/_dynamo/aot_compile.py` under this test file: they fail on `no logs of
level WARNING or higher triggered on torch._dynamo.aot_compile`, and the
interrupt one on `KeyboardInterrupt not raised`, since with no warning built
there the `Boom` is never printed.

Authored with the assistance of Claude Code.

> **FAQ: a recorded raise can be discarded with nothing logged -- when a
> later result's tree raises a `BaseException`, when a later result's bind
> raises `TypeError`, and on two more exits of the same class: `_binds_alike`,
> called after the inline check and under no handler, so a raise from
> `_binding_key` drops `raised` as the bind's `TypeError` does, and
> `_no_match_report` runs under no handler, so a `BaseException` out of its
> `check_verbose` re-check or anything out of `_missing_global_hint` drops it
> too. Record it before it is lost?**
>
> Declined, and the claim above states the rule rather than instances of it:
> every path that RETURNS a graph with a raise on record logs one per index
> that raised, every path that builds a report chains one, and a call that
> ends before dispatch picks a result leaves as the exception that ended it
> and records nothing, whatever ended it. The
> bind case was measured on two results that do not bind alike --
> `ScaleModule`'s `forward(x)` at [0] under a stub tree that raises, and a
> `forward(y, z)` at [1] -- called with one tensor: [0] is bound and checked
> once and its raise recorded, then [1]'s bind raises `TypeError: missing a
> required argument: 'z'`, and that is what leaves `__call__`, with nothing
> logged, `__cause__` `None` and `__context__` an incidental `StopIteration`
> out of `inspect`'s bind rather than the recorded raise, which the `except`
> around [0]'s check had already handled to completion. Chaining the raise there
> would assert a `__cause__` that is false -- the raise did not make the bind
> fail -- and warning would need a text for a dispatch that served nothing,
> where the one warning says `dispatch served [i]`. The two exits a guard
> manager can produce are pinned in #197219: an interrupt out of a later tree
> leaves `__call__` as itself with nothing logged, and the next call, with
> that tree back, serves and logs the earlier raise; a later result's bind
> raising `TypeError: missing a required argument: 'z'` leaves `__call__`
> with nothing logged. The other two exits have no test because nothing
> reachable produces them: `_binding_key` reads the artifact's own signature
> parameters, `co_freevars` and closure cells, `_missing_global_hint` builds
> a string from the artifact's own record, and a guard tree's raise arrives
> as an `Exception` that neither sees. All four exits are the caller's own --
> a Ctrl-C, a call the model cannot take, an artifact or a report that could
> not be built -- and none served a graph or described the call, so a warning
> about a third artifact on the way out would be advice about a dispatch that
> did not happen, logged while the caller holds an exception to read. Nor is
> the raise gone from the process: a tree that raises raises again on the
> next call that reaches it, and is recorded then. One more exit of the same
> class is this commit's own: an interrupt out of the recorded exception's
> `__str__`, raised while the warning quotes it, leaves `_warn_swallowed`
> and discards the graph whose guards had passed. That one IS reported, on the
> next call, because the one-shot is spent after `log.warning` and not before
> -- `..._warning_not_spent_by_an_interrupt_from_str`.

> **FAQ: the `Rejects` stub grows a `check_verbose` that nothing in this
> commit calls -- every path here reads `check_nopybind`. Dead code; drop it
> until something needs it?**
>
> Kept deliberately, and it is dead here: instrumented to raise on entry, the
> whole file still passes. It is on the stub because a round-2 review of this
> commit asked for it, so the fixture has the shape a report path quotes rather
> than half of one, and its first caller is two commits up: #197179's
> `test_aot_compile_module_no_match_does_not_suppress_a_handled_exception`
> drives the no-match report over a `Rejects()`, and the report re-checks each
> result with `check_verbose` -- with the method instrumented, the report reads
> `[0] <guard check raised AssertionError: Rejects.check_verbose was reached>`,
> so the stub is answering the call that path makes. Moving it up would have
> two commits editing the same three-line stub for one method, and the stub is
> this commit's own fixture.

> **FAQ: the swallowed raise is logged with `log.warning`. Why not
> `trace_structured`, so a production job can pull it out with `tlparse`?**
>
> Because this fires at dispatch time, on a per-call path with no compile
> context, which is the wrong shape for a tlparse artifact twice over. Read
> directly in `torch/_logging/_internal.py`: with `expect_trace_id` at its
> default (`:1521`), a `trace_structured` call that finds no current trace id
> captures a full `CapturedTraceback` into the record (`:1572`) to diagnose the
> missing frame id, so the artifact would arrive attached to no frame and
> carrying a stack of the dispatch call rather than of anything compiled. And a
> raising guard tree raises on EVERY call that reaches it, so the payload would
> repeat per call instead of once per compile, which is the granularity tlparse
> presents. `log.warning` on `torch._dynamo.aot_compile` is where this file's
> other runtime-divergence warnings already go (the registered-hooks and
> overridden-`__call__` warnings), it reaches the same job log, and it is what
> the warning tests here and in #197195 assert on.

> **FAQ: the dedup key was `(index, exception type name)`, and the advice
> text branched on `_guard_check_enabled` read afterwards, so an opt-out flip
> after a warning silenced the opted-out advice. Why put the flag in the key
> rather than reset the set when it flips?**
>
> Because the set is reset on one condition, that the results are not the
> ones last warned about, and the flag is not a change of results: it lives
> on the same object, so no comparison of weak references sees it, and a
> reset would need a second record of every result's flag beside the first.
> The key already names what the message is computed from -- the index and
> the type -- and the flag is the third thing it is computed from, so the key
> covers it and nothing else changes. The cost is one more warning per index
> at most, when the caller flips the flag, which is the warning the flip
> changed.

> **FAQ: the two advice strings were ~250 and ~450 characters of prose in one
> log line. Why cut them to a sentence each instead of keeping the reasoning
> where the reader sees it?**
>
> Because the reader of a job log needs the decision and the remedy -- which
> input raised, what it raised, which input was served, fix or drop the
> raiser, and which way its next check can be wrong -- and each sentence now
> says exactly that, in the shape of this file's other warnings (one
> divergence, one remedy). The reasoning -- why a raise is served over rather
> than refused, what a C++ throw leaves stale, why an opted-out tree is
> charged only with a stale accept -- is the same for every warning, so it is
> written once in the class docstring, which is where `help(AOTCompiledModel)`
> takes the reader, not hard-wrapped into every line of a hot loop's log.

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

Pull Request resolved: #197391
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1198/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