Skip to content

[aot_compile] Honour disable_guard_check() from any position in module dispatch - #197047

Closed
bobrenjc93 wants to merge 5 commits into
gh/bobrenjc93/1192/basefrom
gh/bobrenjc93/1192/head
Closed

bobrenjc93 wants to merge 5 commits into
gh/bobrenjc93/1192/basefrom
gh/bobrenjc93/1192/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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

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:

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.

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:

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

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/197047

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

⏳ 2 Pending, 2 Unrelated Failures

As of commit 3b93289 with merge base b8bd7cf (image):

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

  • Correctness
    • The new loop at torch/_dynamo/aot_compile.py:1558-1562 runs after both guard passes (:1536, :1555), so a real match still outranks an opt-out
    • Serving via result.fn(self.model, ...) matches the two stages above and is equivalent to result(...), which short-circuits on the same flag at :886
    • The fall-through at :1565 is now reached only when every result is enabled, so results[0] re-checks and raises as its comment says
  • Existing coverage holds
    • test_module_dispatch_rechecks_before_honouring_an_opt_out and ..._rechecks_an_opted_out_result_whose_tree_accepts are rescued by the re-check, which still precedes the new stage
    • test_module_dispatch_no_match_falls_through_to_the_first_result opts out only prefixes, so all three parametrized rows keep their outcomes under the index-ordered loop
    • test_aot_compile_module_opted_out_result_is_the_last_resort still serves [0] for its both-opted-out no-match case
  • Testing
    • test_module_dispatch_serves_an_opted_out_result_from_any_position pins the [enabled, opted_out] serve, that [0]'s real match outranks it, and the index-order tie-break
    • mode=2 fails both L['mode'] guards and the graphs return x * 2 vs x * 3, so the assertions cannot pass by coincidence
  • Scope
    • Confined to AOTCompiledModel.__call__; the public aot_compile() path in AOTCompiledFunction.__call__ is untouched
    • _aot_compile/compiled_results is documented private and experimental at torch/_dynamo/aot_compile.py:1471, and the widened fallback is reachable only after an explicit disable_guard_check()
    • The class docstring and the disable_guard_check() bullet in docs/source/user_guide/torch_compiler/torch.compiler_aot_compile.md are updated in the same diff

reason: clean
Reviewed commit: 3b93289

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
@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 6m 56s —— View job


Review of #197047

Mechanically the change is correct, minimal, and consistent with the surrounding dispatch stages — the ordering claim in the description holds against the existing test_module_dispatch_* tests. My one real reservation is a design one: a single opt-out anywhere in compiled_results now silently serves a wrong-numbers graph for a call that used to raise, and there is a narrower fix that addresses the stated defect (#196929's "report depends on list order") without broadening what gets served.

Full review

What I checked

  • Diff vs origin/gh/bobrenjc93/1192/base
  • AOTCompiledModel.__call__ dispatch (torch/_dynamo/aot_compile.py:1513-1551) and the _guard_check_enabled flag (:588, :886, :1042)
  • Traced the four existing test_module_dispatch_* / test_aot_compile_module_*_opt* tests against the new stage to confirm none flip
  • Docstring / public doc consistency

I could not run the tests: this checkout has no built torch extension (torch/_C*.so is absent) and no .venv is reachable from the working directory, so import torch fails. All verification below is by reading.

Correctness

The new stage at torch/_dynamo/aot_compile.py:1545-1549 is placed after both guard passes and before the fall-through, which is the ordering the description claims. Walking the existing tests confirms none of them change verdict:

test arrangement path taken unchanged?
..._opted_out_result_keeps_its_place_in_the_scan (:2394) [opted_out, enabled], [0] matches scan serves [0] yes
..._opted_out_result_is_the_last_resort (:2427) first half [opted_out, enabled], [1] matches scan serves [1] yes
..._opted_out_result_is_the_last_resort second half [opted_out, opted_out], neither matches new stage serves [0] — same result the fall-through used to serve yes
..._rechecks_an_opted_out_result_whose_tree_accepts (:2252) [opted_out, opted_out], [1] falsely rejected once re-check serves [1], compares == 2 yes
..._rechecks_before_honouring_an_opt_out (:2297) [opted_out, enabled], [1] falsely rejected once re-check serves [1] before the new stage yes

The second-half row above is the one that would have been easy to break, and it survives only because the new loop iterates in index order — same tie-break the fall-through had. Worth keeping in mind if anyone ever "simplifies" it to next(r for r in results if not r._guard_check_enabled) with a different ordering, though that expression is order-preserving too.

One pleasant side effect the code does not say out loud: the fall-through at :1550-1551 is now reachable only when every result has its guard check enabled, so results[0](...) is guaranteed to raise. The comment there still reads "just run one of them and throw the guard check error", which was hedged wording from when that line could also silently serve an opted-out [0]. Since the new stage makes the raise unconditional, consider tightening it — e.g. "Every result's guards failed and none opted out, so results[0] is enabled and its call raises." That documents the invariant the new loop establishes rather than leaving the reader to derive it.

_guard_check_enabled is read directly rather than through a predicate; that matches :886 and the # Guard evaluation ignores _guard_check_enabled comment at :1527, so no complaint. The empty-results IndexError at :1551 is pre-existing and untouched.

Design: is "serve" the right answer, and is model-wide the right scope?

The description makes a solid case that raising would leave disable_guard_check() inert on this path, and I agree with that reasoning as far as it goes. But there is a third option the FAQ does not consider, and it is the one that most directly targets the defect #196929 names:

the fall-through re-raised only because compiled_results[0] happened to have its guard check enabled

That defect is about which result reports, not about what gets served. It can be fixed by making the fall-through raise from the first enabled result instead of from results[0]:

# All guards failed; report from the first result that asked to be checked.
report = next((r for r in results if r._guard_check_enabled), results[0])
return report(self.model, *args, **kwargs)

That is position-independent in exactly the sense #196929 complains about, and it does not widen the set of calls that get served. The tradeoff, which the description is right about, is that it would refuse the [opted_out, enabled] no-match call the parent serves today — so it is not a free win. I am not asking for the change; I am asking that the description name it, because "raise" and "serve" are presented as the only two options and the FAQ's argument against raising (the flag becomes inert) does not apply to this variant.

The scope question is the part I would want a second opinion on before this lands. After this PR, compiled_results[1].disable_guard_check() — an opt-out a user might reach for because that one artifact's globals do not resolve on the serving machine, which is the motivation the sibling test at :2371-2374 gives — also silently converts every no-match call on the whole model from RuntimeError into a wrong-numbers answer from result 1. The new test itself is a demonstration: model(x, 2) returns x * 3 where eager returns x * 2. The mitigation ("a real match is always preferred") is real but only helps when a match exists; the case where it does not is precisely the case that used to be loud. Given _aot_compile is private and experimental this is a defensible call, and the docstring now says so, so I would not block on it — but the public doc at docs/source/user_guide/torch_compiler/torch.compiler_aot_compile.md:130-132 describes disable_guard_check() as scoped to "the compiled function", which is now only true on the function path. A one-clause note there that on a module artifact the flag is model-wide would save a future reader the trip into the private docstring.

Test

test_module_dispatch_serves_an_opted_out_result_from_any_position (test/dynamo/test_aot_compile.py:2281-2295) does pin the [enabled, opted_out] serve, and it is a real discriminator: [0] guards L['mode'] == 0, [1] guards L['mode'] == 1, the call passes mode=2, and the two results compute x * 2 vs x * 3 so the assertion cannot pass by coincidence.

Two gaps:

  1. The asserted value is deliberately wrong relative to eager and the test does not say so. ModeBranchGlobalModule.forward answers x * 2 for mode=2, and the test asserts x * AOT_BRANCH_SCALE (x * 3). That is the whole point of an opt-out, but a reader hitting this test cold will read the assertion as the expected answer. The sibling at :2379-2385 handles exactly this by spelling out that what is served is the wrong graph on purpose; one sentence of the same here would help.

  2. Nothing pins that a real match at a later index still outranks an opt-out at an earlier one under the new stage. ..._opted_out_result_is_the_last_resort covers [opted_out, enabled], and this new test covers [enabled, opted_out] with no match — but not [enabled, opted_out] where [0] genuinely matches. That combination is what would catch a future refactor that hoisted the opt-out check into or ahead of the scan for the [enabled, opted_out] shape specifically. Two extra lines on the existing model in the new test would close it:

    self.assertEqual(model(x, 0), x * 2)   # [0]'s real match outranks [1]'s opt-out

    Fix this →

Nits

  • The new test's comment says "the fall-through this dispatch replaced" — the fall-through is not replaced, it is still at :1550-1551; this stage sits ahead of it. "the fall-through this stage now precedes" would be accurate.
  • The docstring clause at :1482-1483 reads well, but "only when no check accepted the call" undersells that both passes run first. "only after both passes above found no match" would match the code comment at :1546 and be harder to misread as "the first scan".
  • Dr. CI is still asking for a release notes: or topic: not user facing label.

Verdict

No correctness bug found; the stage is well placed and the existing tests genuinely pin the ordering. I would like the description to name the "raise from the first enabled result" alternative rather than presenting raise-vs-serve as exhaustive, the public doc to note the model-wide scope, and the new test to add the [enabled, opted_out]-with-a-match case.

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

@bobrenjc93 bobrenjc93 changed the title [aot_compile] Honour disable_guard_check() from any position in module dispatch [no-ci] [aot_compile] Honour disable_guard_check() from any position in module dispatch Sep 15, 2026
[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 6m 21s —— View job


Review of #197047

The diff does not contain the change this PR describes. Against the stated base origin/gh/bobrenjc93/1192/base (9cf0efa), the five-line opt-out loop and the new test are already present in the base — so this PR's only net effect is (a) restoring the AOTCompiledModel docstring and (b) deleting the "Developer notes" doc section and reverting the disable_guard_check() doc bullet, which looks like an unintended loss from the base-update merge rather than anything the description asks for.

Full review

What the diff actually is

$ git diff origin/gh/bobrenjc93/1192/base...HEAD --stat
 .../torch_compiler/torch.compiler_aot_compile.md   | 25 +++-------------------
 torch/_dynamo/aot_compile.py                       | 21 +++++++++++++++---
 2 files changed, 21 insertions(+), 25 deletions(-)

No test/ changes. And the base already has both the loop and the test:

$ git show origin/gh/bobrenjc93/1192/base:torch/_dynamo/aot_compile.py | sed -n '1530,1536p'
        # A result that opted out via disable_guard_check() accepts anything, but
        # only after both passes above have failed to find a real match.
        for result in results:
            if not result._guard_check_enabled:
                return result.fn(self.model, *args, **kwargs)

$ git grep -n "serves_an_opted_out_result_from_any_position" origin/gh/bobrenjc93/1192/base -- test/
origin/.../base:test/dynamo/test_aot_compile.py:2281: def test_module_dispatch_serves_an_opted_out_result_from_any_position(self):

How this happened

Two commits, the second a merge:

6535a3b [UPDATE] Update        parents = ad26044 9cf0efa
ad26044 [INITIAL] Update       test_aot_compile.py +16 | aot_compile.py +8/-1

ad26044 is the described change — it adds the loop, the docstring clause, and the test — against the old base bdc7675. Then the base moved to 9cf0efa, and that base update already carries the same work:

$ git diff ad26044^ 9cf0efa --stat
 .../torch.compiler_aot_compile.md | 25 +++++++++++++++++---
 test/dynamo/test_aot_compile.py   | 16 ++++++++++++++
 torch/_dynamo/aot_compile.py      | 25 +++++++---------------

That base update adds a byte-identical opt-out loop and a byte-identical test_module_dispatch_serves_an_opted_out_result_from_any_position, plus a new doc "Developer notes" section — and it replaces the class docstring with the older two-line comment.

The merge 6535a3b then resolved to the head side wholesale:

$ git rev-parse ad26044^{tree} HEAD^{tree}
b18329a87a7b22e50c7b26df6b17bc62ffa24872
b18329a87a7b22e50c7b26df6b17bc62ffa24872

HEAD's tree is bit-identical to the pre-merge commit, i.e. everything the base update contributed to these files was discarded in favour of the head side. For the loop and the test that is harmless (both sides were identical). For the docs it is a straight revert of the base's work.

The consequence I'd actually fix

The base added, and this PR removes, 17 lines of docs/.../torch.compiler_aot_compile.md:

-(aot-compile-developer-notes)=
-
-## Developer notes
-
-**Private, unstable -- may change or disappear without notice.** A module can
-also be compiled for several calls at once: ...

and reverts the bullet that pointed at it back to the unqualified wording (now docs/.../torch.compiler_aot_compile.md:130-132):

- `disable_guard_check()` -- Disable runtime guard validation (advanced use): the
  compiled function then runs whatever it is called with, without evaluating its
  guards.

That reintroduces a statement this very stack establishes as wrong for the module path — dispatch does evaluate an opted-out result's guards (torch/_dynamo/aot_compile.py:1527, :1547). It also makes the removal self-consistent only by accident: the anchor aot-compile-developer-notes and its sole {ref} are removed together, so there is no dangling-reference Sphinx warning (I checked: grep -rn "aot-compile-developer-notes" → no hits, and advanced.md:13 only toctree-includes the page). So this will build green while silently regressing the docs a sibling PR added.

If the doc revert is intentional — e.g. the "Developer notes" section is meant to live in a different stack entry — the description should say so, because as written it claims the docs are untouched.

Fix this →

The docstring restoration

The other half of the diff re-adds the AOTCompiledModel docstring (torch/_dynamo/aot_compile.py:1470-1484) in place of the base's two-line comment. The docstring is accurate and better than what it replaces — the dispatch paragraph correctly describes all three stages including the opt-out clause. But the description does not mention it at all, and the base deliberately went the other way, so whichever sibling PR owns that docstring is now in a tug-of-war with this one. Worth deciding explicitly rather than letting merge order pick.

Claims in the description that no longer hold

  • "This commit adds a third stage between the re-check and the fall-through" — the base already has it.
  • "To review: the five-line loop in torch/_dynamo/aot_compile.py between the re-check and the fall-through ... the one test" — neither is in the diff.
  • "The new test fails at the parent with RuntimeError: GuardManager check failed ... and passes here" — the test exists at the parent, alongside the code that makes it pass, so it passes at the parent too.
  • The PARENT/HEAD behaviour table is measured against bdc7675, not against the current base. Against the current base, PARENT and HEAD rows are identical.

The measured table and the FAQ are still a good record of why the loop is shaped this way — they just belong on whichever PR actually introduces it.

On the code itself

Since the description asks for review of the loop, for what it is worth I read it as it stands at torch/_dynamo/aot_compile.py:1545-1551 and found no correctness problem. It sits after both guard passes, iterates in index order (same tie-break the fall-through had), and calling result.fn directly rather than result(...) is equivalent here because AOTCompiledFunction.__call__ (:886) short-circuits on the same _guard_check_enabled flag. One nice invariant it establishes: the fall-through at :1550-1551 is now reachable only when every result has its check enabled, so results[0](...) is guaranteed to raise — the comment's "just run one of them and throw the guard check error" is now unconditionally true rather than hedged. The empty-compiled_results IndexError at :1551 is pre-existing.

Verification I could not do

I could not run the test plan. This checkout has no built extension (torch/_C*.so absent) and no reachable .venv, so import torch fails. Per CLAUDE.md I did not attempt to install or work around that. Everything above is from git and reading the source; the tree-hash and git diff outputs are quoted verbatim so they are checkable.

Also outstanding

Dr. CI still wants a release notes: or topic: not user facing label. Given the diff is docs + a docstring, topic: not user facing looks right.

Verdict

I'd hold this one. The diff as it stands is not the change described, and its one substantive effect on the base is a documentation regression. Either rebase so the loop and test are genuinely new here and the docs survive the merge, or — if the sibling below now owns that change — retarget this PR to whatever is actually left (the docstring), and say so in the description.

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

@bobrenjc93 bobrenjc93 changed the title [no-ci] [aot_compile] Honour disable_guard_check() from any position in module dispatch [no-ci] [aot_compile] Document module dispatch in the AOTCompiledModel docstring, not the user guide Sep 15, 2026
[ghstack-poisoned]
@bobrenjc93 bobrenjc93 changed the title [no-ci] [aot_compile] Document module dispatch in the AOTCompiledModel docstring, not the user guide [aot_compile] Honour disable_guard_check() from any position in module dispatch 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 7m 12s —— View job


Review of #197047

The diff is now the change the description says it is — the base moved from 9cf0efa to 30d1cb8, which no longer carries the opt-out loop or the test, so my previous review's blocking concern (change already in base, plus a docs regression) is resolved. I found no correctness bug in the new stage; my remaining comments are one test-coverage gap, a stale doc sentence, and a comment that is now under-stated.

Full review

Base moved; the previous objection is gone

$ git rev-parse origin/gh/bobrenjc93/1192/base
30d1cb8df997b7d85bc3c219d7536c50c144b7f4

$ git show origin/gh/bobrenjc93/1192/base:torch/_dynamo/aot_compile.py | grep -n _guard_check_enabled
588:    _guard_check_enabled: bool = True
870:        if self._guard_check_enabled and not self.guard_check(...)
1027:        self._guard_check_enabled = False
1510:        # Guard evaluation ignores _guard_check_enabled, so scan every result.

$ git grep -c serves_an_opted_out_result_from_any_position origin/gh/bobrenjc93/1192/base -- test/
(no match)

$ git diff --name-only origin/gh/bobrenjc93/1192/base...HEAD
test/dynamo/test_aot_compile.py
torch/_dynamo/aot_compile.py

The base's dispatch ends at the re-check and falls straight through to results[0](...), so the loop and the test are new here, and docs/ is untouched — the "Developer notes" deletion I flagged last time is not in this diff (that section is not in the base either, so there is nothing to lose). The description's PARENT rows also still hold against this base: the fall-through calls results[0](...), which raises iff [0] is enabled, giving exactly [enabled, *] → raise, [opted_out, *] → serve. The description is accurate as written now.

The new stage

torch/_dynamo/aot_compile.py:1529-1535 sits after both guard passes and before the fall-through, iterates in index order (the same tie-break the fall-through had, so a [opted_out, opted_out] no-match still serves [0]), and calls result.fn directly — consistent with the two stages above it, and equivalent to result(...) anyway since AOTCompiledFunction.__call__ (:870) short-circuits on the same flag. Reading the flag directly rather than via a predicate matches :870 and the # Guard evaluation ignores _guard_check_enabled comment at :1511. The empty-compiled_results IndexError at :1535 is pre-existing and untouched.

Neither surviving opt-out test flips, and for the right reason — both are rescued by the re-check, which still runs first:

test arrangement path verdict
..._rechecks_an_opted_out_result_whose_tree_accepts (:2208) [opted_out, opted_out], [1] falsely rejected once re-check serves [1], compares == 2 unchanged
..._rechecks_before_honouring_an_opt_out (:2253) [opted_out, enabled], [1] falsely rejected once re-check serves [1] before the new stage unchanged

Both would go red if the stage were hoisted ahead of the re-check (they'd get [0]'s x * 2 and compares == 1), which is the ordering the description says they pin. That checks out.

One thing the code does not say out loud: the fall-through at :1534-1535 is now reachable only when every result has its check enabled, so results[0](...) is guaranteed to raise. The comment there still reads "just run one of them and throw the guard check error" — hedged wording from when that line could also silently serve an opted-out [0]. Worth tightening to state the invariant the new loop establishes, e.g. # Every result's guards failed and none opted out, so results[0] is enabled and raises.

Test coverage gap

test_module_dispatch_serves_an_opted_out_result_from_any_position (test/dynamo/test_aot_compile.py:2237-2251) is a real discriminator: [0] guards L['mode'] == 0, [1] guards L['mode'] == 1 (both local guards, so the default filter keeps them), the call passes mode=2, and the graphs compute x * 2 vs x * 3, so the assertion cannot pass by coincidence. It fails at this base with GuardManager check failed exactly as claimed.

Two things I'd add:

  1. Nothing pins that a real match at a later index outranks an opt-out at an earlier one for the [enabled, opted_out] shape. ..._rechecks_before_honouring_an_opt_out covers [opted_out, enabled], and this new test covers [enabled, opted_out] with no match — but not [enabled, opted_out] where [0] genuinely matches. That is the combination that would catch a future refactor hoisting the opt-out check into or ahead of the scan. It is one line on the model already built:

    self.assertEqual(model(x, 0), x * 2)   # [0]'s real match outranks [1]'s opt-out

    Note this base also dropped the ..._opted_out_result_is_the_last_resort / ..._keeps_its_place_in_the_scan tests that existed on the older base, so the [opted_out, enabled]-with-a-match and [opted_out, opted_out]-no-match cases are now unpinned too. The new stage's index-order tie-break in particular has no test.

  2. The asserted value is deliberately not what eager answers, and the comment doesn't say so. ModeBranchGlobalModule.forward (:594-600) returns x * 2 for mode=2, while the test asserts x * AOT_BRANCH_SCALE (x * 3). That is the point of an opt-out, but a reader hitting this cold will read the assertion as the expected answer. One sentence would fix it.

Fix this →

Public doc is now inaccurate for the module path

docs/source/user_guide/torch_compiler/torch.compiler_aot_compile.md:130-132 still says:

disable_guard_check() -- Disable runtime guard validation (advanced use): the compiled function then runs whatever it is called with, without evaluating its guards.

Both halves are false on the module path after this PR: dispatch does evaluate an opted-out result's guards (:1511, :1529), and the flag is now model-wide rather than scoped to the one artifact it was called on. Given _aot_compile is private and the class docstring now says the right thing, I would not block on it, but a one-clause note pointing at the module behaviour would save a future reader the trip into the private docstring.

On the scope question (repeating myself briefly, not blocking)

After this PR, compiled_results[1].disable_guard_check() — reached because that one artifact's globals do not resolve on the serving machine — also converts every no-match call on the whole model from RuntimeError into a wrong-numbers answer from result 1. The description's mitigation ("a real match is always preferred") is real but only helps when a match exists, which is not the case the flag changes. The FAQ presents raise-vs-serve as exhaustive; there is a third option it doesn't name — raise from the first enabled result rather than from results[0]:

report = next((r for r in results if r._guard_check_enabled), results[0])
return report(self.model, *args, **kwargs)

That is position-independent in exactly the sense #196929 complains about (it fixes which result reports) without widening what gets served, and the FAQ's "the flag becomes inert" argument does not apply to it. Its real cost is the one the description identifies: it would refuse the [opted_out, enabled] no-match the parent serves today. I am not asking for the change — I am asking the FAQ to name it, since as written it reads as if the option space were two.

Nits

  • The new test's comment says "the fall-through this dispatch replaced" — the fall-through is not replaced, it is still at :1534-1535; this stage precedes it. (The same phrasing at :2183 predates this PR.)
  • The docstring clause at :1466-1467, "only when no check accepted the call", undersells that both passes run first. "only after both passes above found no match" would match the code comment at :1530.
  • _guard_check_enabled is not serialized (serialize copies fn._artifacts.__dict__), so the opt-out and therefore this new stage are in-process only — pre-existing and consistent, just worth knowing when reading the doc wording above.
  • Dr. CI still wants a release notes: or topic: not user facing label.

Verification I could not do

I could not run the test plan. This checkout has no built extension (torch/_C*.so absent — confirmed by glob) and no reachable .venv, so import torch fails; per CLAUDE.md I did not try to install or work around that. Everything above is from git and reading the source, with the git output quoted verbatim so it is checkable.

Verdict

The blocking objection from my previous review no longer applies — the diff, the description, and the base now agree, and the stage is correctly placed. Remaining asks are all non-blocking: add the [enabled, opted_out]-with-a-match assertion (the index-order tie-break is currently untested), note in the test that the asserted value is intentionally not eager's, fix the stale public doc sentence, and tighten the now-unconditional fall-through comment.

· branch [`gh/bobrenjc93/1192/head`](https://github.com/pytorch/pytorch/tree/gh/bobrenjc93/1192/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 9m 1s —— View job


Review of #197047

The diff is now the change the description says it is (base 30d1cb8 has neither the loop nor the test), and I found no correctness defect in the new dispatch stage; my remaining asks are one over-strong comment, ~12 lines of test setup that duplicates an existing helper, one assertion that duplicates an existing test, and a public-doc bullet that documents a private path in the wrong place.

Full review

PR Review: #197047

Summary

Adds a third dispatch stage to AOTCompiledModel.__call__ that serves the first disable_guard_check()-opted-out result from any index, after both the scan and the re-check found no match. The stage is correctly placed and the existing test_module_dispatch_* / test_aot_compile_module_opted_out_* tests genuinely pin the ordering; the problems below are a comment that overstates its invariant, duplicated test setup and assertions, and doc placement.

Verified first that my previous blocking objection is gone — the base moved and no longer carries this work:

$ git rev-parse origin/gh/bobrenjc93/1192/base
30d1cb8df997b7d85bc3c219d7536c50c144b7f4
$ git show origin/gh/bobrenjc93/1192/base:torch/_dynamo/aot_compile.py | grep -c "_guard_check_enabled:$"
(dispatch ends at the re-check; no opt-out loop)
$ git grep -c serves_an_opted_out_result_from_any_position origin/gh/bobrenjc93/1192/base -- test/
(no match)

Also correcting an error in my previous review: I claimed this base had dropped test_aot_compile_module_opted_out_result_keeps_its_place_in_the_scan and ..._is_the_last_resort. It has not — they are at test/dynamo/test_aot_compile.py:2329 and :2362. That matters below, because one of them already covers part of what the new test asserts.

Code Quality

  • torch/_dynamo/aot_compile.py:1547-1548 states an invariant the code does not guarantee. The new comment reads "so results[0] is enabled and raises the guard check error". Only the first half is an invariant. results[0](...) goes through AOTCompiledFunction.__call__ (:885-899), which calls guard_check() — a third evaluation of that result's tree. The whole premise of the stage above it (:1535-1537) is that a check() can answer differently on a later evaluation; _install_global_probe (test/dynamo/test_aot_compile.py:2007) exercises exactly that for real. So a third check can accept, and the fall-through can serve rather than raise. The pre-existing wording was vague enough to survive this; the new wording promises something stronger. Suggest: # No result opted out, so results[0] is enabled: its __call__ re-checks and normally raises the guard error.

  • test/dynamo/test_aot_compile.py:2280-2288 re-implements _aot_compile_mode_branches (:2225) inline. The only difference is the missing options={"guard_filter_fn": keep_global_guards}, and that difference is not load-bearing for this test: with the global guards kept, [0] still guards L['mode'] == 0, [1] still guards L['mode'] == 1 plus a global guard on AOT_BRANCH_SCALE that passes, so mode=2 still fails both and every one of the three assertions holds. Twelve lines collapse to model, x = self._aot_compile_mode_branches(), and the test then sits alongside its three siblings (:2254, :2264, :2299) on the same fixture rather than a near-copy of it. If the default filter is deliberate, the comment should say why, because the divergence from the neighbours reads as accidental.

    Fix this →

  • torch/_dynamo/aot_compile.py:1485-1486 and :1542-1543 omit the tie-break the new test pins. The docstring says an opted-out result is served "on the strength of its opt-out alone only after both the scan and the re-check found no match" and the code comment says "accepts anything, but only after both passes above have failed"; neither says which opted-out result serves when several opted out. The test's third assertion (:2296-2297) makes index order a contract, and the docstring already uses the phrase "in index order" one clause earlier for the scan, so it is a two-word fix: "…the first of them in index order is served on the strength of its opt-out alone…".

Testing

  • test/dynamo/test_aot_compile.py:2294-2297 duplicates test_aot_compile_module_opted_out_result_is_the_last_resort:2412-2419. That test already asserts, with its own message, "with both opted out, the last resort must serve the first" for a call no result's guards accept. The new assertion is the same arrangement ([opted_out, opted_out], no match, must serve [0]) on a different fixture, and it passes at the base as well as at HEAD — the fall-through served [0] too. Either drop it and let the existing test own that case, or keep it and say in the comment that it is a local restatement of ..._is_the_last_resort so the new stage's iteration order is pinned next to the stage it belongs to. As written a reader cannot tell which.

    Note this assertion is also the weakest of the three in isolation: [0]'s graph returns x * 2, which is what eager answers for mode=2 as well, so it only discriminates against serving [1].

  • The first two assertions are good and are new coverage: mode=2 fails both EQUALS_MATCH guards (both local, so the default filter keeps them), the two graphs compute x * 2 vs x * 3, and [enabled, opted_out]-with-a-match at [0] (:2293) is a shape no existing test covers — ..._is_the_last_resort:2405-2411 covers only [opted_out, enabled].

API Design

  • docs/source/user_guide/torch_compiler/torch.compiler_aot_compile.md:130-135 puts module-dispatch semantics in the wrong place. That bullet list documents the methods of the AOTCompiledFunction returned by the public aot_compile(), and the added four lines describe what happens on the private, experimental _aot_compile path instead — a path this page otherwise never mentions (grep -n "_aot_compile\b\|compiled_results" on the file returns only these new lines). A reader of the public page has no compiled_results to hold. Fixing the pre-existing sentence's inaccuracy is right, but the module-specific half belongs in a developer-notes section on this page or in the AOTCompiledModel docstring, which already says it (torch/_dynamo/aot_compile.py:1483-1486); the public bullet then only needs "on a module artifact the flag does not skip dispatch's guard evaluation — see AOTCompiledModel".

  • Also in that bullet: "its opt-out only makes it, from any index, the one that serves a call no result's guards accept" is wrong when more than one result opts out — it is the first of them. Same fix as the docstring item above.

  • The scope of the flag is now model-wide on this path: one compiled_results[i].disable_guard_check(), reached because that one artifact's guards fail on the serving machine (the motivation test_aot_compile_module_disable_guard_check:2307-2309 gives), converts every no-match call on the whole model from RuntimeError into a wrong-numbers answer from result i. The description argues this through and the mitigation ("a real match always outranks the opt-out") is real and tested, so given _aot_compile is private I am not asking for a change. One gap in the FAQ's framing: it presents raise-vs-serve as the whole option space, but there is a third — keep the fall-through and raise from the first enabled result, next((r for r in results if r._guard_check_enabled), results[0]) — which fixes the position-dependence [aot_compile] Make module dispatch scan every compiled result before falling through #196929 names without widening what is served, and which the FAQ's "the flag becomes inert" argument does not reach. Its cost is the one the description identifies (it would refuse the [opted_out, enabled] no-match the parent serves). Worth naming in the description so the choice reads as a choice.

Recommendation

Approve once the four items above are addressed — the comment at :1547-1548, reusing _aot_compile_mode_branches, resolving the duplicated third assertion, and the doc bullet's placement and "the one" wording. None is a correctness bug; the stage itself is right, in the right position, and adequately tested.

Verification I could not do

I could not run the test plan: this checkout has no built extension (torch/_C*.so absent, confirmed by glob) and no reachable .venv, so import torch fails. Per CLAUDE.md I did not attempt to install or work around it. Everything above is from git and reading the source, with git output quoted verbatim so it is checkable.

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

[ghstack-poisoned]
@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:22
@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, 2, 2, mt-l-x86iamx-8-64, unstable), inductor / unit-test / inductor-cpu-test / test (inductor_aoti_fallback, 1, 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

@github-actions
github-actions Bot deleted the gh/bobrenjc93/1192/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