Repository navigation
[aot_compile] Make module dispatch scan every compiled result before falling through - #196929
bobrenjc93 wants to merge 16 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/196929
Note: Links to docs will display an error until the docs builds have been completed. ⏳ 199 Pending, 2 Unrelated FailuresAs of commit 6da07d1 with merge base 4c54342 ( GREEN LIGHT - PR requires human review:
reason: 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. |
|
Claude finished @bobrenjc93's task in 58m 6s —— View job PR Review: #196929One real regression found: the new Full reviewPR Review: #196929SummaryReplaces Backward Compatibility
API Design
Testing
Performance
Code Quality
RecommendationRequest Changes The signature-comparison crash is a straightforward regression for any module with a tensor-valued parameter default and more than one Verified by reading: dispatch does not lose anything by bypassing Note on verification limits: Python execution was blocked in this environment, so the tensor-default crash was established from the CPython 3.12 |
[ghstack-poisoned]
|
Claude finished @bobrenjc93's task in 26m 38s —— View job PR Review: #196929The previous round's blocker (tensor-default Full reviewPR Review: #196929SummaryReplaces API Design
Code Quality
Performance
RecommendationNeeds Discussion No defect here produces a wrong answer under any state reachable through the in-tree APIs. What I verified rather than assumed, since the design leans on it: reusing one The two items to settle before landing are the Note on verification limits: this review is from reading source only — the test suite was not executed in this environment, so the PR's reported counts and timings are taken as stated. |
[ghstack-poisoned]
PR Review: #196929
|
[ghstack-poisoned]
|
Claude finished @bobrenjc93's task in 39m 1s —— View job PR Review: #196929No blocking defects — the one item worth taking before landing is still the missing Full reviewPR Review: #196929SummaryReplaces Testing
Code Quality
RecommendationApprove The Verified rather than assumed, since the whole design rests on it: calling Note on verification limits: source reading only — no |
[ghstack-poisoned]
|
Claude finished @bobrenjc93's task in 59m 35s —— View job PR Review: #196929No blocking defects — three items remain: the decider thread is still unjoined on the failure path of Full reviewPR Review: #196929SummaryReplaces Testing
API Design
RecommendationApprove None of these is a wrong answer reachable through the in-tree APIs. The thread cleanup is the one I would take before landing, since its consequence — a stray thread mutating the model after Verified rather than assumed, since the whole design rests on both: (a) Note on verification limits: source reading only — no |
[ghstack-poisoned]
[ghstack-poisoned]
Superseded by a newer greenlight verdict.
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
|
Superseded: the scan/re-check/binding rewrite continues as a new PR at the bottom of this stack, and the any-position opt-out serve as #197047, so each can be reviewed on its own. |
…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
… its advice stays Tests only, for the no-match report the report commit (#196823) raises, split out of it so that its review fits in one pass -- the pattern of #196824 and #196825, which pin the dispatch's last resort and a guarded global the loading process does not have from test-only commits. Each of the four passes at the report commit, whose report it pins, and fails below it, at the dispatch commit 049617d (#196929), where the no-match fall-through `results[0](self.model, *args, **kwargs)` raises the function path's `GuardManager check failed` message. That message is not empty of the report's text: it quotes the guard's `KeyError on G[...]` part and, for a whole missing global, appends the function path's hint sentence, so the `loaded against; define it there`, `the module the compiled function was traced in` and `a guarded global is missing` substrings the tests also look for are present there. What it lacks is the `[i]` entry prefix and the `Add a ModelInput` footer, and each of the four asserts on one of those two: measured with that commit's `aot_compile.py` under this tree's test file, `stays_neutral`, `advises_an_input` and `resolves_forward_only` each fail on `"[0] KeyError on G[...]" not found` alone, and `missing_key_inside_a_present_global` on `'Add a ModelInput' not found` alone. Every one of them captures in this process, so every one calls `_hide_leaked_dynamo_globals()` on entry, as the capture-only `test_aot_compile_fn_missing_global_hint_names_the_tracing_scope` does. What each catches at this tree, and which of the report commit's own tests would catch the same edit, was measured by editing the report: `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` loads through `AOTCompiledModel.deserialize(..., guard_globals=...)` with a dict that never had the guarded name, so the guards hold a dict no `forward` resolves to, asserts the scope-neutral wording, and then the advice it gives: `compiled_results[0]._guard_globals is scope`, and defining the name in that dict serves the call -- with `AOT_HERMETIC_WEIGHT` defined in this module's dict, where the class's `forward` lives, the whole time. The wording is decided by the identity compare `resolved is not missing_global._guard_globals`, and this test is not the only one that pins it: reducing the condition to `resolved is None` fails it with a report that names `this HermeticModule instance's forward`, and of the file's 194 tests fails exactly one other, #196818's `test_aot_compile_module_missing_global_hint_names_the_resolved_module`, whose second half loads with `guard_globals=dict(globals())` -- a copy of the module dict, taken while the module itself lacked the name, that is not the dict `forward` resolves to -- and asserts `loaded against; define it there`. The report commit's `test_no_match_report_survives_a_forward_resolve_that_raises` reaches the neutral wording through `resolved is None`, and `test_no_match_message_hint_covers_a_rebound_forward` through a resolve that IS the dict the guards hold, so both pass under that edit. What this test adds over `..._names_the_resolved_module` is the other way to the wording, a supplied dict that never had the name rather than a stale copy carrying the module's `__name__`, and the recovery: no other `AOTCompiledModel.deserialize(..., guard_globals=)` test defines a missing name in the supplied dict and asserts the call is served (`..._deserialize_takes_a_guard_globals_scope` supplies a copy that already carries its names, and `covers_a_rebound_forward` defines the name in the dict the load RESOLVED, not one the caller passed). `test_missing_key_inside_a_present_global_is_not_a_missing_global` pins which predicate the report reaches for. A guard on `G['GLOBAL_POOLING_CONFIG']['pooling']` with the KEY popped reports `KeyError on G['GLOBAL_POOLING_CONFIG']['pooling']`, asserted in full, as the function path's `test_aot_compile_fn_missing_nested_key_gets_no_missing_global_hint` asserts it -- an ordinary mismatch: the report keeps the advice and withholds the hint, whose "define the global" would be wrong. Replacing `_names_a_missing_global` with a `"KeyError on G["` substring test fails it on the hint's presence, and passes every report test in the report commit, each of whose missing globals is a whole part. The whole-part match itself came in with the function path's hint and is pinned there. `test_no_match_message_advises_an_input_for_a_missing_global` pins the shape the report commit's argument for unconditional advice rests on. `SelfModeBranchGlobalModule`, the fixture it adds, branches on `self.mode` rather than an argument: that guard is a `LOCAL_UNSPECIALIZED_NN_MODULE` source, which sorts after `GLOBAL`, so the root's `G` accessor is installed -- and fails -- before the `self.mode` guard (the `L['x']` `TENSOR_MATCH`, a `LOCAL`, precedes both), and the one entry names only the missing global. `check_verbose` quotes the first failing guard and nothing after it, so the absence of `L['self'].mode` from that report cannot by itself show a mismatch was hidden; the test then puts the global back and calls again, and the same call now fails on `[0] L['self'].mode == 1` alone. The two halves run in that order because a failed `check()` re-sorts the root's children by fail count (`GuardManager::check_nopybind`, guards.cpp): had `self.mode` failed first, it would sit ahead of the `G` accessor and the popped-global call would name it instead of the KeyError. An input captured for the `mode == 2` branch would not read `AOT_BRANCH_SCALE` at all, so the advice is right and is the only actionable line. Withholding it when every entry named a missing global -- counting the entries that did and returning before the footer when the count is the whole report -- fails it on `Add a ModelInput`; two other one-entry reports on a missing global fail under that edit as well, the report commit's `test_no_match_report_survives_a_forward_resolve_that_raises` and this commit's `test_no_match_report_resolves_forward_only_for_a_supplied_scope` (`failures=3` on the whole file, all on `'Add a ModelInput' not found`), and `test_no_match_message_keeps_the_advice_for_every_entry`, which pairs the missing global with a plain mismatch, passes. What this test adds is the hidden mismatch, which none of those has. `test_no_match_report_resolves_forward_only_for_a_supplied_scope` is the CAPTURED half of the pair whose SUPPLIED half, `test_no_match_report_survives_a_forward_resolve_that_raises`, stays with the report. It captures a plain `HermeticModule` in-process, pops the global, and asserts the CAPTURED report arrives with no `forward` named. It wraps `_resolve_guard_scope` in a `patch(..., wraps=...)` for the call and asserts it was never invoked, since the wording alone cannot pin the gate: the CAPTURED hint never names `forward`, so it reads the same whether or not the resolve ran. Replacing the SUPPLIED gate with `if True:` fails it on the count, `Expected '_resolve_guard_scope' to not have been called. Called 1 times`, with the `except Exception` around the resolve kept or removed, and passes every other SUPPLIED report test -- the report commit's `test_no_match_report_survives_a_forward_resolve_that_raises` and `test_no_match_message_hint_covers_a_rebound_forward`, and this commit's `test_no_match_message_hint_stays_neutral_for_a_supplied_scope`, all of which resolve either way -- so this is the one test that pins the gate. The count carries the assertion, so the test no longer rebinds `forward` to a `functools.partial` over `RaisingReprModule`: on this path a resolve that raised would be swallowed by that catch and change nothing the test could see, and the catch itself is `survives_a_forward_resolve_that_raises`'s to pin -- with the catch removed it errors with `ValueError: extra_repr`. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_no_match_message_hint_stays_neutral_for_a_supplied_scope python test/dynamo/test_aot_compile.py -k test_missing_key_inside_a_present_global_is_not_a_missing_global python test/dynamo/test_aot_compile.py -k test_no_match_message_advises_an_input_for_a_missing_global python test/dynamo/test_aot_compile.py -k test_no_match_report_resolves_forward_only_for_a_supplied_scope python test/dynamo/test_aot_compile.py ``` The whole file runs 194 tests here, 190 on the parent commit: `Ran 194 tests`, `OK (skipped=6)`. ## FAQ > **FAQ: The review asked that > `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` read > `AOT_HERMETIC_WEIGHT` through a reference captured at import instead of > asserting it is in `HermeticModule.forward.__globals__`. Why an identity > assertion instead?** > > The membership assertion was standing in for a claim about which dict the > guards read, so the test states that claim directly: > `compiled.compiled_results[0]._guard_globals is scope` -- the guards hold the > supplied dict -- and the read that follows, `scope["AOT_HERMETIC_WEIGHT"] = > AOT_HERMETIC_WEIGHT` serving the call, is the dict a forward-naming hint would > have sent the reader away from. An earlier revision also asserted > `HermeticModule.forward.__globals__ is globals()`; that holds by construction > for a class defined in this file and observes nothing about the code under > test, so it is gone. The two bare `AOT_HERMETIC_WEIGHT` reads are pre-existing > and shared with every test in the file that uses the fixture; a sibling that > failed to restore the name would break the module, not this test's ordering, > and a captured alias would only move that dependency to import time. > **FAQ: The review asked > `test_no_match_message_advises_an_input_for_a_missing_global` to first show > the report naming `L['self'].mode` with the global defined, then pop the > global and show the KeyError replacing it. Why the other order?** > > Because the guard tree remembers its failures. `GuardManager::check_nopybind` > (torch/csrc/dynamo/guards.cpp) bumps a child's fail count when it rejects and, > unless the failure was on the first child, re-sorts the root's accessors by > fail count so the next check fails fast. Run the mismatch half first and the > `self.mode` accessor moves ahead of the `G` accessor; the popped-global call > then reports `L['self'].mode == 1` rather than the KeyError (measured on a > scratch copy: both calls name `self.mode`). Popped first, the `G` accessor > is the one promoted, it resolves once the global is back, and the second call > fails on `self.mode` alone -- which is the positive witness the review asked > for, on the same compiled result. > **FAQ: The review found that > `test_aot_compile_module_missing_global_hint_names_the_resolved_module`, in > #196818 below, already fails under the `resolved is None` edit that this > commit's `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` was > described as the one test to catch. Why keep the test?** > > Because the coverage claim was wrong, and the test's other half is not pinned > anywhere else. Re-measured on the whole file with the compare reduced to > `resolved is None`: `Ran 194 tests`, `FAILED (failures=2)`, the two being > `..._names_the_resolved_module` (`'loaded against; define it there' not > found`) and this test; every other test passes. So the identity compare is > fenced at #196818, and the message now says so instead of crediting this > test. What this test alone covers is a `guard_globals=` dict that never had > the name -- `..._names_the_resolved_module` reaches the same wording through > `dict(globals())`, a copy taken while the module itself lacked the name -- > and the recovery, defining the name in that dict and asserting the call is > served, which no other `AOTCompiledModel.deserialize(..., guard_globals=)` > test does. The same pass dropped the static > `HermeticModule.forward.__globals__ is globals()` assertion, replaced the > raising-repr scaffolding in `..._resolves_forward_only_for_a_supplied_scope` > with a plain `HermeticModule()` (the mock's call count carries the > assertion; a raise on that path would be swallowed by the report's catch), > and moved the `patch(...)` construction there above `g.pop` so nothing sits > between the pop and the `try`. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: 9cea9f6 Pull-Request: #197001
…and that its advice stays Tests only, for the no-match report the report commit (#196823) raises, split out of it so that its review fits in one pass -- the pattern of #196824 and #196825, which pin the dispatch's last resort and a guarded global the loading process does not have from test-only commits. Each of the four passes at the report commit, whose report it pins, and fails below it, at the dispatch commit 049617d (#196929), where the no-match fall-through `results[0](self.model, *args, **kwargs)` raises the function path's `GuardManager check failed` message. That message is not empty of the report's text: it quotes the guard's `KeyError on G[...]` part and, for a whole missing global, appends the function path's hint sentence, so the `loaded against; define it there`, `the module the compiled function was traced in` and `a guarded global is missing` substrings the tests also look for are present there. What it lacks is the `[i]` entry prefix and the `Add a ModelInput` footer, and each of the four asserts on one of those two: measured with that commit's `aot_compile.py` under this tree's test file, `stays_neutral`, `advises_an_input` and `resolves_forward_only` each fail on `"[0] KeyError on G[...]" not found` alone, and `missing_key_inside_a_present_global` on `'Add a ModelInput' not found` alone. Every one of them captures in this process, so every one calls `_hide_leaked_dynamo_globals()` on entry, as the capture-only `test_aot_compile_fn_missing_global_hint_names_the_tracing_scope` does. What each catches at this tree, and which of the report commit's own tests would catch the same edit, was measured by editing the report: `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` loads through `AOTCompiledModel.deserialize(..., guard_globals=...)` with a dict that never had the guarded name, so the guards hold a dict no `forward` resolves to, asserts the scope-neutral wording, and then the advice it gives: `compiled_results[0]._guard_globals is scope`, and defining the name in that dict serves the call -- with `AOT_HERMETIC_WEIGHT` defined in this module's dict, where the class's `forward` lives, the whole time. The wording is decided by the identity compare `resolved is not missing_global._guard_globals`, and this test is not the only one that pins it: reducing the condition to `resolved is None` fails it with a report that names `this HermeticModule instance's forward`, and of the file's 194 tests fails exactly one other, #196818's `test_aot_compile_module_missing_global_hint_names_the_resolved_module`, whose second half loads with `guard_globals=dict(globals())` -- a copy of the module dict, taken while the module itself lacked the name, that is not the dict `forward` resolves to -- and asserts `loaded against; define it there`. The report commit's `test_no_match_report_survives_a_forward_resolve_that_raises` reaches the neutral wording through `resolved is None`, and `test_no_match_message_hint_covers_a_rebound_forward` through a resolve that IS the dict the guards hold, so both pass under that edit. What this test adds over `..._names_the_resolved_module` is the other way to the wording, a supplied dict that never had the name rather than a stale copy carrying the module's `__name__`, and the recovery: no other `AOTCompiledModel.deserialize(..., guard_globals=)` test defines a missing name in the supplied dict and asserts the call is served (`..._deserialize_takes_a_guard_globals_scope` supplies a copy that already carries its names, and `covers_a_rebound_forward` defines the name in the dict the load RESOLVED, not one the caller passed). `test_missing_key_inside_a_present_global_is_not_a_missing_global` pins which predicate the report reaches for. A guard on `G['GLOBAL_POOLING_CONFIG']['pooling']` with the KEY popped reports `KeyError on G['GLOBAL_POOLING_CONFIG']['pooling']`, asserted in full, as the function path's `test_aot_compile_fn_missing_nested_key_gets_no_missing_global_hint` asserts it -- an ordinary mismatch: the report keeps the advice and withholds the hint, whose "define the global" would be wrong. Replacing `_names_a_missing_global` with a `"KeyError on G["` substring test fails it on the hint's presence, and passes every report test in the report commit, each of whose missing globals is a whole part. The whole-part match itself came in with the function path's hint and is pinned there. `test_no_match_message_advises_an_input_for_a_missing_global` pins the shape the report commit's argument for unconditional advice rests on. `SelfModeBranchGlobalModule`, the fixture it adds, branches on `self.mode` rather than an argument: that guard is a `LOCAL_UNSPECIALIZED_NN_MODULE` source, which sorts after `GLOBAL`, so the root's `G` accessor is installed -- and fails -- before the `self.mode` guard (the `L['x']` `TENSOR_MATCH`, a `LOCAL`, precedes both), and the one entry names only the missing global. `check_verbose` quotes the first failing guard and nothing after it, so the absence of `L['self'].mode` from that report cannot by itself show a mismatch was hidden; the test then puts the global back and calls again, and the same call now fails on `[0] L['self'].mode == 1` alone. The two halves run in that order because a failed `check()` re-sorts the root's children by fail count (`GuardManager::check_nopybind`, guards.cpp): had `self.mode` failed first, it would sit ahead of the `G` accessor and the popped-global call would name it instead of the KeyError. An input captured for the `mode == 2` branch would not read `AOT_BRANCH_SCALE` at all, so the advice is right and is the only actionable line. Withholding it when every entry named a missing global -- counting the entries that did and returning before the footer when the count is the whole report -- fails it on `Add a ModelInput`; two other one-entry reports on a missing global fail under that edit as well, the report commit's `test_no_match_report_survives_a_forward_resolve_that_raises` and this commit's `test_no_match_report_resolves_forward_only_for_a_supplied_scope` (`failures=3` on the whole file, all on `'Add a ModelInput' not found`), and `test_no_match_message_keeps_the_advice_for_every_entry`, which pairs the missing global with a plain mismatch, passes. What this test adds is the hidden mismatch, which none of those has. `test_no_match_report_resolves_forward_only_for_a_supplied_scope` is the CAPTURED half of the pair whose SUPPLIED half, `test_no_match_report_survives_a_forward_resolve_that_raises`, stays with the report. It captures a plain `HermeticModule` in-process, pops the global, and asserts the CAPTURED report arrives with no `forward` named. It wraps `_resolve_guard_scope` in a `patch(..., wraps=...)` for the call and asserts it was never invoked, since the wording alone cannot pin the gate: the CAPTURED hint never names `forward`, so it reads the same whether or not the resolve ran. Replacing the SUPPLIED gate with `if True:` fails it on the count, `Expected '_resolve_guard_scope' to not have been called. Called 1 times`, with the `except Exception` around the resolve kept or removed, and passes every other SUPPLIED report test -- the report commit's `test_no_match_report_survives_a_forward_resolve_that_raises` and `test_no_match_message_hint_covers_a_rebound_forward`, and this commit's `test_no_match_message_hint_stays_neutral_for_a_supplied_scope`, all of which resolve either way -- so this is the one test that pins the gate. The count carries the assertion, so the test no longer rebinds `forward` to a `functools.partial` over `RaisingReprModule`: on this path a resolve that raised would be swallowed by that catch and change nothing the test could see, and the catch itself is `survives_a_forward_resolve_that_raises`'s to pin -- with the catch removed it errors with `ValueError: extra_repr`. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_no_match_message_hint_stays_neutral_for_a_supplied_scope python test/dynamo/test_aot_compile.py -k test_missing_key_inside_a_present_global_is_not_a_missing_global python test/dynamo/test_aot_compile.py -k test_no_match_message_advises_an_input_for_a_missing_global python test/dynamo/test_aot_compile.py -k test_no_match_report_resolves_forward_only_for_a_supplied_scope python test/dynamo/test_aot_compile.py ``` The whole file runs 194 tests here, 190 on the parent commit: `Ran 194 tests`, `OK (skipped=6)`. ## FAQ > **FAQ: The review asked that > `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` read > `AOT_HERMETIC_WEIGHT` through a reference captured at import instead of > asserting it is in `HermeticModule.forward.__globals__`. Why an identity > assertion instead?** > > The membership assertion was standing in for a claim about which dict the > guards read, so the test states that claim directly: > `compiled.compiled_results[0]._guard_globals is scope` -- the guards hold the > supplied dict -- and the read that follows, `scope["AOT_HERMETIC_WEIGHT"] = > AOT_HERMETIC_WEIGHT` serving the call, is the dict a forward-naming hint would > have sent the reader away from. An earlier revision also asserted > `HermeticModule.forward.__globals__ is globals()`; that holds by construction > for a class defined in this file and observes nothing about the code under > test, so it is gone. The two bare `AOT_HERMETIC_WEIGHT` reads are pre-existing > and shared with every test in the file that uses the fixture; a sibling that > failed to restore the name would break the module, not this test's ordering, > and a captured alias would only move that dependency to import time. > **FAQ: The review asked > `test_no_match_message_advises_an_input_for_a_missing_global` to first show > the report naming `L['self'].mode` with the global defined, then pop the > global and show the KeyError replacing it. Why the other order?** > > Because the guard tree remembers its failures. `GuardManager::check_nopybind` > (torch/csrc/dynamo/guards.cpp) bumps a child's fail count when it rejects and, > unless the failure was on the first child, re-sorts the root's accessors by > fail count so the next check fails fast. Run the mismatch half first and the > `self.mode` accessor moves ahead of the `G` accessor; the popped-global call > then reports `L['self'].mode == 1` rather than the KeyError (measured on a > scratch copy: both calls name `self.mode`). Popped first, the `G` accessor > is the one promoted, it resolves once the global is back, and the second call > fails on `self.mode` alone -- which is the positive witness the review asked > for, on the same compiled result. > **FAQ: The review found that > `test_aot_compile_module_missing_global_hint_names_the_resolved_module`, in > #196818 below, already fails under the `resolved is None` edit that this > commit's `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` was > described as the one test to catch. Why keep the test?** > > Because the coverage claim was wrong, and the test's other half is not pinned > anywhere else. Re-measured on the whole file with the compare reduced to > `resolved is None`: `Ran 194 tests`, `FAILED (failures=2)`, the two being > `..._names_the_resolved_module` (`'loaded against; define it there' not > found`) and this test; every other test passes. So the identity compare is > fenced at #196818, and the message now says so instead of crediting this > test. What this test alone covers is a `guard_globals=` dict that never had > the name -- `..._names_the_resolved_module` reaches the same wording through > `dict(globals())`, a copy taken while the module itself lacked the name -- > and the recovery, defining the name in that dict and asserting the call is > served, which no other `AOTCompiledModel.deserialize(..., guard_globals=)` > test does. The same pass dropped the static > `HermeticModule.forward.__globals__ is globals()` assertion, replaced the > raising-repr scaffolding in `..._resolves_forward_only_for_a_supplied_scope` > with a plain `HermeticModule()` (the mock's call count carries the > assertion; a raise on that path would be swallowed by the report's catch), > and moved the `patch(...)` construction there above `g.pop` so nothing sits > between the pop and the `try`. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: b077b77 Pull-Request: #197001
…and that its advice stays Tests only, for the no-match report the report commit (#196823) raises, split out of it so that its review fits in one pass -- the pattern of #196824 and #196825, which pin the dispatch's last resort and a guarded global the loading process does not have from test-only commits. Each of the four passes at the report commit, whose report it pins, and fails below it, at the dispatch commit 049617d (#196929), where the no-match fall-through `results[0](self.model, *args, **kwargs)` raises the function path's `GuardManager check failed` message. That message is not empty of the report's text: it quotes the guard's `KeyError on G[...]` part and, for a whole missing global, appends the function path's hint sentence, so the `loaded against; define it there`, `the module the compiled function was traced in` and `a guarded global is missing` substrings the tests also look for are present there. What it lacks is the `[i]` entry prefix and the `Add a ModelInput` footer, and each of the four asserts on one of those two: measured with that commit's `aot_compile.py` under this tree's test file, `stays_neutral`, `advises_an_input` and `resolves_forward_only` each fail on `"[0] KeyError on G[...]" not found` alone, and `missing_key_inside_a_present_global` on `'Add a ModelInput' not found` alone. Every one of them captures in this process, so every one calls `_hide_leaked_dynamo_globals()` on entry, as the capture-only `test_aot_compile_fn_missing_global_hint_names_the_tracing_scope` does. What each catches at this tree, and which of the report commit's own tests would catch the same edit, was measured by editing the report: `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` loads through `AOTCompiledModel.deserialize(..., guard_globals=...)` with a dict that never had the guarded name, so the guards hold a dict no `forward` resolves to, asserts the scope-neutral wording, and then the advice it gives: `compiled_results[0]._guard_globals is scope`, and defining the name in that dict serves the call -- with `AOT_HERMETIC_WEIGHT` defined in this module's dict, where the class's `forward` lives, the whole time. The wording is decided by the identity compare `resolved is not missing_global._guard_globals`, and this test is not the only one that pins it: reducing the condition to `resolved is None` fails it with a report that names `this HermeticModule instance's forward`, and of the file's 194 tests fails exactly one other, #196818's `test_aot_compile_module_missing_global_hint_names_the_resolved_module`, whose second half loads with `guard_globals=dict(globals())` -- a copy of the module dict, taken while the module itself lacked the name, that is not the dict `forward` resolves to -- and asserts `loaded against; define it there`. The report commit's `test_no_match_report_survives_a_forward_resolve_that_raises` reaches the neutral wording through `resolved is None`, and `test_no_match_message_hint_covers_a_rebound_forward` through a resolve that IS the dict the guards hold, so both pass under that edit. What this test adds over `..._names_the_resolved_module` is the other way to the wording, a supplied dict that never had the name rather than a stale copy carrying the module's `__name__`, and the recovery: no other `AOTCompiledModel.deserialize(..., guard_globals=)` test defines a missing name in the supplied dict and asserts the call is served (`..._deserialize_takes_a_guard_globals_scope` supplies a copy that already carries its names, and `covers_a_rebound_forward` defines the name in the dict the load RESOLVED, not one the caller passed). `test_missing_key_inside_a_present_global_is_not_a_missing_global` pins which predicate the report reaches for. A guard on `G['GLOBAL_POOLING_CONFIG']['pooling']` with the KEY popped reports `KeyError on G['GLOBAL_POOLING_CONFIG']['pooling']`, asserted in full, as the function path's `test_aot_compile_fn_missing_nested_key_gets_no_missing_global_hint` asserts it -- an ordinary mismatch: the report keeps the advice and withholds the hint, whose "define the global" would be wrong. Replacing `_names_a_missing_global` with a `"KeyError on G["` substring test fails it on the hint's presence, and passes every report test in the report commit, each of whose missing globals is a whole part. The whole-part match itself came in with the function path's hint and is pinned there. `test_no_match_message_advises_an_input_for_a_missing_global` pins the shape the report commit's argument for unconditional advice rests on. `SelfModeBranchGlobalModule`, the fixture it adds, branches on `self.mode` rather than an argument: that guard is a `LOCAL_UNSPECIALIZED_NN_MODULE` source, which sorts after `GLOBAL`, so the root's `G` accessor is installed -- and fails -- before the `self.mode` guard (the `L['x']` `TENSOR_MATCH`, a `LOCAL`, precedes both), and the one entry names only the missing global. `check_verbose` quotes the first failing guard and nothing after it, so the absence of `L['self'].mode` from that report cannot by itself show a mismatch was hidden; the test then puts the global back and calls again, and the same call now fails on `[0] L['self'].mode == 1` alone. The two halves run in that order because a failed `check()` re-sorts the root's children by fail count (`GuardManager::check_nopybind`, guards.cpp): had `self.mode` failed first, it would sit ahead of the `G` accessor and the popped-global call would name it instead of the KeyError. An input captured for the `mode == 2` branch would not read `AOT_BRANCH_SCALE` at all, so the advice is right and is the only actionable line. Withholding it when every entry named a missing global -- counting the entries that did and returning before the footer when the count is the whole report -- fails it on `Add a ModelInput`; two other one-entry reports on a missing global fail under that edit as well, the report commit's `test_no_match_report_survives_a_forward_resolve_that_raises` and this commit's `test_no_match_report_resolves_forward_only_for_a_supplied_scope` (`failures=3` on the whole file, all on `'Add a ModelInput' not found`), and `test_no_match_message_keeps_the_advice_for_every_entry`, which pairs the missing global with a plain mismatch, passes. What this test adds is the hidden mismatch, which none of those has. `test_no_match_report_resolves_forward_only_for_a_supplied_scope` is the CAPTURED half of the pair whose SUPPLIED half, `test_no_match_report_survives_a_forward_resolve_that_raises`, stays with the report. It captures a plain `HermeticModule` in-process, pops the global, and asserts the CAPTURED report arrives with no `forward` named. It wraps `_resolve_guard_scope` in a `patch(..., wraps=...)` for the call and asserts it was never invoked, since the wording alone cannot pin the gate: the CAPTURED hint never names `forward`, so it reads the same whether or not the resolve ran. Replacing the SUPPLIED gate with `if True:` fails it on the count, `Expected '_resolve_guard_scope' to not have been called. Called 1 times`, with the `except Exception` around the resolve kept or removed, and passes every other SUPPLIED report test -- the report commit's `test_no_match_report_survives_a_forward_resolve_that_raises` and `test_no_match_message_hint_covers_a_rebound_forward`, and this commit's `test_no_match_message_hint_stays_neutral_for_a_supplied_scope`, all of which resolve either way -- so this is the one test that pins the gate. The count carries the assertion, so the test no longer rebinds `forward` to a `functools.partial` over `RaisingReprModule`: on this path a resolve that raised would be swallowed by that catch and change nothing the test could see, and the catch itself is `survives_a_forward_resolve_that_raises`'s to pin -- with the catch removed it errors with `ValueError: extra_repr`. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_no_match_message_hint_stays_neutral_for_a_supplied_scope python test/dynamo/test_aot_compile.py -k test_missing_key_inside_a_present_global_is_not_a_missing_global python test/dynamo/test_aot_compile.py -k test_no_match_message_advises_an_input_for_a_missing_global python test/dynamo/test_aot_compile.py -k test_no_match_report_resolves_forward_only_for_a_supplied_scope python test/dynamo/test_aot_compile.py ``` The whole file runs 194 tests here, 190 on the parent commit: `Ran 194 tests`, `OK (skipped=6)`. ## FAQ > **FAQ: The review asked that > `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` read > `AOT_HERMETIC_WEIGHT` through a reference captured at import instead of > asserting it is in `HermeticModule.forward.__globals__`. Why an identity > assertion instead?** > > The membership assertion was standing in for a claim about which dict the > guards read, so the test states that claim directly: > `compiled.compiled_results[0]._guard_globals is scope` -- the guards hold the > supplied dict -- and the read that follows, `scope["AOT_HERMETIC_WEIGHT"] = > AOT_HERMETIC_WEIGHT` serving the call, is the dict a forward-naming hint would > have sent the reader away from. An earlier revision also asserted > `HermeticModule.forward.__globals__ is globals()`; that holds by construction > for a class defined in this file and observes nothing about the code under > test, so it is gone. The two bare `AOT_HERMETIC_WEIGHT` reads are pre-existing > and shared with every test in the file that uses the fixture; a sibling that > failed to restore the name would break the module, not this test's ordering, > and a captured alias would only move that dependency to import time. > **FAQ: The review asked > `test_no_match_message_advises_an_input_for_a_missing_global` to first show > the report naming `L['self'].mode` with the global defined, then pop the > global and show the KeyError replacing it. Why the other order?** > > Because the guard tree remembers its failures. `GuardManager::check_nopybind` > (torch/csrc/dynamo/guards.cpp) bumps a child's fail count when it rejects and, > unless the failure was on the first child, re-sorts the root's accessors by > fail count so the next check fails fast. Run the mismatch half first and the > `self.mode` accessor moves ahead of the `G` accessor; the popped-global call > then reports `L['self'].mode == 1` rather than the KeyError (measured on a > scratch copy: both calls name `self.mode`). Popped first, the `G` accessor > is the one promoted, it resolves once the global is back, and the second call > fails on `self.mode` alone -- which is the positive witness the review asked > for, on the same compiled result. > **FAQ: The review found that > `test_aot_compile_module_missing_global_hint_names_the_resolved_module`, in > #196818 below, already fails under the `resolved is None` edit that this > commit's `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` was > described as the one test to catch. Why keep the test?** > > Because the coverage claim was wrong, and the test's other half is not pinned > anywhere else. Re-measured on the whole file with the compare reduced to > `resolved is None`: `Ran 194 tests`, `FAILED (failures=2)`, the two being > `..._names_the_resolved_module` (`'loaded against; define it there' not > found`) and this test; every other test passes. So the identity compare is > fenced at #196818, and the message now says so instead of crediting this > test. What this test alone covers is a `guard_globals=` dict that never had > the name -- `..._names_the_resolved_module` reaches the same wording through > `dict(globals())`, a copy taken while the module itself lacked the name -- > and the recovery, defining the name in that dict and asserting the call is > served, which no other `AOTCompiledModel.deserialize(..., guard_globals=)` > test does. The same pass dropped the static > `HermeticModule.forward.__globals__ is globals()` assertion, replaced the > raising-repr scaffolding in `..._resolves_forward_only_for_a_supplied_scope` > with a plain `HermeticModule()` (the mock's call count carries the > assertion; a raise on that path would be swallowed by the report's catch), > and moved the `patch(...)` construction there above `g.pop` so nothing sits > between the pop and the `try`. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: 4c20b93 Pull-Request: #197001

Stack from ghstack (oldest at bottom):
AOTCompiledModel.__call__is the dispatcher over the several graphs a modulewas AOT-compiled for, one
AOTCompiledFunctionperModelInputincompiled_results. The parent's loop was four lines:Whether the caller saw an error at all turned on the order of the list. The
fall-through re-raised only because
compiled_results[0]still had its guardcheck enabled; had that one result opted out through
disable_guard_check()it would have run instead, so the answer was an accident of position rather
than a decision. Measured on a two-input
ScaleModule(float32 and float64)called with float16:
A match was not cheap either:
result()entersAOTCompiledFunction.__call__,which binds the call and runs
guard_checkagain before runningfn, so amatching tree was bound and evaluated twice per call.
Three explicit stages ahead of the fall-through
Only a call none of the three stages serves reaches the parent's fall-through
into
compiled_results[0], which by then is a result with its guard checkenabled, so it raises the same
GuardManager check failederror the parentraised; a report that names every compiled input replaces that fall-through in
the next commit.
The scan calls
fndirectly. One evaluation of a matching tree per call,where
result()made two, which is whattest_module_dispatch_evaluates_a_matching_tree_oncemeasures. The scan cannotskip opted-out results even though they accept anything: guard evaluation
happens regardless of the flag, so scanning them first still finds the right
graph, and skipping them would reinstate the old fall-through when every result
has opted out.
Honouring the opt-out from any position is the one answer this commit
changes. With
compiled_results = [enabled, opted_out]and a call neitherartifact guards, the parent raises and this commit serves
compiled_results[1]:So one opted-out result now replaces the error for the whole model, where
before only
compiled_results[0]could. That is whatdisable_guard_check()is for: on the function path
AOTCompiledFunction.__call__short-circuits onthe flag and runs the graph whatever it is called with, so the alternative,
raising anyway, would leave the flag with no effect at all on a model, since a
scan that serves an opted-out result whose guards pass is what an enabled result
gets too. It would also refuse the
[opted_out, enabled]call the parentserves today.
test_module_dispatch_serves_an_opted_out_result_from_any_positionpins it (deleting the last-resort loop raises
GuardManager check failed).The doc bullet for
disable_guard_check()is where a reader meets the flag, soit now says the compiled function then runs whatever it is called with. The
module dispatch's own answer lives in a new
Developer notessection at the endof the user guide, headed by the bold private/unstable warning, since a private
multi-input path does not belong beside the public quick start; the bullet is
scoped to the function path and cross-references that section. The section
names what the path needs: the list is of
torch._dynamo.aot_compile.ModelInput,which nothing re-exports,
torch._dynamo.config.enable_aot_compile, on bydefault, which only a caller who turned it off has to restore, and
model.forward.compiled_results[i].disable_guard_check(), the only route tothe flag from a module.
AOTCompiledModelis out of it:_aot_compilereturnsNoneand assignsself.forward, so a reader never holds one.The re-check is what keeps the last resort last
check()can reject from the recursive dict-tag fast path without ever runningthe tree, so a rejection in the scan is not yet an answer about this call. The
node that rejected and its ancestors have their
_disable_dict_tag_matchingset, which nothing resets (
guards.cpp:4270is the member's= falsedefaultinitializer; every other write sets it true), so a second
check()re-evaluates those in full. The flag is a per-
GuardManagermember, so that isnot a whole-tree re-evaluation: a sibling tag-safe root the first pass never
reached stays armed and can still answer from its own fast path. That is
exactly the rescue the old fall-through got from re-entering
AOTCompiledFunction.__call__oncompiled_results[0], here extended to everyresult, so nothing that used to be served is refused
(
test_module_dispatch_serves_a_call_the_guard_tree_accepts). A genuinemismatch pays almost nothing for the second pass: such a tree still
short-circuits at its first failing guard.
Ordering matters more than it looks. With the last resort ahead of the
re-check, an opted-out result answers first and silently serves a graph
compiled for a different call in exactly the case the fall-through got right,
because the fall-through re-checked before it gave up.
test_module_dispatch_rechecks_before_honouring_an_opt_outpins the position(moving the loop ahead serves
[0]'sx * 2and fails withMismatched elements: 9 / 9); #196824 pins the same loop fromGlobalConfigModule's side.The re-check covers opted-out results too, for the scan's reason: a scan
check()that refused from the fast path is no more an answer about anopted-out tree than about an enabled one (
check()never reads the flag), andthe last resort does not stand in for the re-check it would skip, since it
serves the FIRST opted-out result:
test_module_dispatch_rechecks_an_opted_out_result_whose_tree_acceptsoptsboth results out and misses
[1]'s global once; restoring the re-check'sopt-out skip serves
[0]'sx * 2and fails it withMismatched elements: 9 / 9. That costs one extracheck()per opted-out result on the no-scan-matchpath only.
Two alternatives to that second
check()were measured and rejected. Runningcheck_verboseas the second pass, so that its answer could double as thefailure's explanation, makes the shape it was meant to help worse: an opted-out
result makes the guards fail on every call by construction, so dispatch ends at
the last resort and the raise is never reached, and
check_verboseis 1.76x acheck()per tree. Gating the stage onconfig.use_recursive_dict_tags_for_guardscannot be made sound at this callsite either, because whether a tree is armed is decided once, in
GuardManagerWrapper.finalize(): a manager built under the config stillreports its tag-safe nodes after the patch exits, and one built without it
reports none however the flag reads at call time. There is no per-manager query
for "has an armed tag-safe root", only the per-node
is_tag_safe_root, so acorrect gate would need the tree walk the gate exists to avoid.
One bind per call, decided safely against a public list
Binding dominates the per-call cost. Measured on this machine,
prepare_f_locals(inspect.Signature.bindplusapply_defaults) costs2.563us against 1.000us for a whole
check()and 1.758us for acheck_verbose(), so paying the bind once per call rather than once per stageis worth more than removing a stage would be. Every result
aot_compile_moduleproduces binds alike (same parameter names, kinds and default objects, same
co_freevarsand the same closure cells, sinceorig_forwardis read beforeany
ModelInputcontext is entered), so one bind serves them all. End to end onthe same fixture, dispatch that finds a match costs 23.3us against the parent's
29.3us at one, two and four compiled inputs, since the parent pays a second
bind and a second
check()insideresult(). With one bind per call, a matchat the fourth of four inputs costs 20.1us against 33.5us with one bind per
result (17.1us at the first, unchanged);
test_module_dispatch_binds_a_call_once_for_results_sharing_a_signaturecountsprepare_f_localson that model for a call matched at[3]and expects one;binding per result again fails it with
Absolute difference: 3. Thefall-through this commit keeps is the one path that still binds again, twice,
inside
AOTCompiledFunction.__call__; the next commit's report reuses thedispatch's binding instead.
Deciding "binds alike" without
inspect.Signatureequality.AOTCompiledModel._binds_alike()decides through_binding_key, whichcompares exactly what
prepare_f_localsreads, with defaults and cells byidentity:
It deliberately does not compare
Signatures:Parameter.__eq__takesbool()ofdefault == defaultas a non-finalandoperand, so aforwardwith a tensor default made the first call raise for any model with two or more
results, however it was built (
_aot_compile,deserializeor the publicconstructor):
test_module_dispatch_shares_a_binding_past_a_tensor_defaultpins that, andthe closure half is pinned by
test_module_dispatch_shares_a_binding_across_closure_cells, whosehand-assembled model holds two cells of the same name. The shared bind is
hoisted ahead of the scan, so the two regimes read as one bind per call or one
per result rather than as an index test inside the loop, and a model whose
results do not agree (
deserializeunpickles each blob on its own and theconstructor is public) binds each result on its own, which
test_module_dispatch_binds_per_result_when_signatures_differpins. Only thatregime records a binding per result for the re-check; the shared one is reused
as is, so a matching call allocates nothing for a pass it never reaches.
A loaded model whose
forwardhas a real default or a closure cell binds perresult for the same reason: each blob unpickles through its own
AOTCompileUnpickler, so equal defaults and cells come back as distinctobjects 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.serializeanddeserialize; aforwardwith neither,whose defaults are the
Parameter.emptysingleton, still shares one bind aftera load. Both shared-binding tests round-trip and pin the loaded verdict as
False.
Re-deciding when the list changes.
compiled_resultsis a public list thedocs teach callers to index into, so
_binds_alikedecides again whenever thetuple differs by length or identity from the contents it last judged. A stale
True would bind a later result from
compiled_results[0]'s signature, and ifa
guard_filter_fndropped the guard on the parameter the two disagree about,serve a graph for a call its guards never saw:
The staleness check is by identity, not
==(the dataclass__eq__reachesthe
Signaturecompare above), and costs 0.27us for four results against0.81us for a
check(); snapshots by id were measured at 0.89us and rejected.test_module_dispatch_rebinds_after_a_result_is_appendedandtest_module_dispatch_judges_a_replaced_result_on_its_own_bindingpin there-decision, the second through the silent shape above.
The verdict and the contents it was reached over are one field.
_binding_verdict = (results, shared), so a call reads both with one attributeload and the re-decision publishes both with one store. Two fields cannot be
made consistent by store order: storing the contents first let a second thread
identity-match the freshly stored contents and return the previous list's
verdict, a stale True that binds an appended result from
compiled_results[0]'sdefault; storing the verdict first left the mirror, a caller that had
snapshotted the list before a
pop, matched the contents still published, andtook the True just decided about the shorter list, so
[1]was bound from[0]'s default and servedx * 3for a call eager answersx * 2. Bothinterleavings are forced deterministically.
test_module_dispatch_never_pairs_new_contents_with_a_stale_verdictholds thedeciding thread inside its first
_binding_keyon athreading.Event, beforeit publishes anything, and calls the model from another thread in that window.
test_module_dispatch_never_pairs_old_contents_with_a_new_verdictholds itright after its first attribute store (an
AOTCompiledModelsubclass whose__setattr__parks the decider) while a call that snapshotted both resultsbefore the pop decides; with the pair in two fields it fails with
RuntimeError not raised,[1]having been served. A window between the two halves of thepublication is the one thing no test can pin, because there is no longer one:
whatever the first store publishes is all a reader can ever see, which is what
the second test asserts. Nothing decides eagerly: the field default is the
verdict over no results, so a fresh model decides on its first call, and the
tests read
_binds_alike(tuple(model.compiled_results))rather than the field.The list is read once per call.
__call__snapshotsresults = tuple(self.compiled_results)before anything else (26ns for four results),_binds_aliketakes that snapshot rather than reading the list itself, andevery stage iterates it. Two reads would let an append or a replacement land
between them, so the shared bind could come from one list and the verdict about
another (a result replaced mid-call judged on the binding decided over its
predecessor) and the re-check's
bound[i]could index a binding the scan nevermade.
test_module_dispatch_judges_only_the_results_a_call_began_withmakes[0]'scheck()splice in a[1]compiled formode=1that defaultsmodeto 0: a scan over the live list reaches it on the same call, judges it on
[0]'s binding wheremodereads 1, and servesx * 3for a call eageranswers
x * 2; with the snapshot that call raises and the next one decidesover both.
Two smaller changes
guard_checkand the function path's__call__route their ownguard_managernarrowing through the new_live_guard_manager()rather thanrestating it, and the dispatch reads its manager the same way. That moves one
dead state:
__call__asserted on a nullguard_managerbefore it read_guard_check_enabled, so an artifact that had opted out raised there and nowruns instead.
__post_init__always populates the field (onlyserialize()nulls it, and on a copy), so reaching that state takes assigning the private
field by hand, and both paths that do read the manager still raise.
A call the signature cannot bind is left alone, so it still surfaces as a
TypeError, as the plain module call would (the type matches, though themessage is
inspect's rather thannn.Module's), instead of a guard errorabout a call the guards never saw. The bind is the first thing the scan does,
ahead of every guard, which is what preserves that. The test for it sits with
#196826, the first commit where the placement of the guard check's
trycouldbreak it.
Test Plan:
The full file runs 168 tests and passes (6 skipped). The mid-call test fails
without the snapshot with
AssertionError: RuntimeError not raised, thespliced-in result having been served. The old-contents interleaving test fails
the same way on the two-field layout in verdict-first order,
[1]having beenserved
x * 3on[0]'s binding; readingbound[i]in the re-checkregardless of the shared bind fails five dispatch tests with
IndexError: list index out of range, so the shared path does reach the re-check with noper-result binding recorded. All five new tests fail at the parent: the two
counted-lookup tests on their counts (
Absolute difference: 1;GuardManager check failedraised where[1]should have been served), the two bindingtests on the missing
_binds_alike, and the opted-out re-check test withMismatched elements: 9 / 9.The four tests added for
_binding_keyand the last resort also fail at theparent: the two binding tests on the missing
_binds_alike, theany-position test with
GuardManager check failed, the re-check-first testwith
Mismatched elements: 9 / 9. RestoringSignatureequality in_binding_keyfails the tensor-default test withBoolean value of Tensor with more than one value is ambiguous; dropping the cells from the key fails theclosure test with
True is not false. Theco_freevarsterm of the key has nomismatch test: two results holding the same cell under different names take a
hand-built code object, and the term is one tuple compare of what the bind
reads.
The two rebinding tests fail without the re-decision: the appended one with
GuardManager check failed(bound from[0],[1]'smode == 0guardmisses), the replaced one with
RuntimeError not raised([1]servedx * 3on
[0]'s binding); dropping the identity term and keeping only the lengthcheck passes the first and still fails the second.
The three counted-lookup tests were also run under
torch._dynamo.config.patch(use_recursive_dict_tags_for_guards=True)toconfirm the counts do not depend on the flag. Deleting the re-check loop as a
mutation control fails
test_module_dispatch_serves_a_call_the_guard_tree_accepts(the fall-through raises
GuardManager check failed) andtest_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts(
Mismatched elements: 9 / 9) while the other three stay green; callingresult()in the scan instead ofresult.fnfailstest_module_dispatch_evaluates_a_matching_tree_oncewithAbsolute difference: 1.Authored with the assistance of Claude Code.
Co-Authored-By: Claude Opus 5 [email protected]
Co-Authored-By: Claude Fable 5.1 [email protected]
FAQ
🤖 Generated with Claude Code