Repository navigation
[aot_compile] Name the instance's forward in the no-match report's supplied-scope hint - #197048
bobrenjc93 wants to merge 15 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/197048
Note: Links to docs will display an error until the docs builds have been completed. ❌ 3 New Failures, 1 Pending, 2 Unrelated FailuresAs of commit fc82a5c with merge base 51d4378 ( GREEN LIGHT - PR approved to be merged without human review:
reason: NEW FAILURES - The following jobs have failed:
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 11m 2s —— View job Reviewed — the change is behaviorally sound and message-only, but the newly added re-resolve silently drops the improved wording whenever a forward hook is registered on the model after load; details below. Full reviewPR Review: #197048SummaryMakes the no-match report's missing-global hint name Code Quality
Testing
RecommendationApprove Nothing here blocks: the behavior change is confined to one sentence of an error message, the new tests pin the two behaviors the commit claims, and the failure mode of the finding above is a less specific hint rather than a wrong one. The hook-registration gap is worth fixing in this commit or a follow-up, since the whole point of the change is to make that sentence more specific and this silently un-does it for any hooked module. |
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
Merge startedYour change will be merged while ignoring the following 5 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), trunk / macos-py3-arm64 / test (default, 2, 3, macos-m1-stable), trunk / linux-noble-rocm-py3.11-mi350 / test (distributed, 1, 3, amd-dpx-linux.rocm.gpu.gfx950.2), trunk / linux-noble-rocm-py3.11-mi350 / test (default, 7, 8, amd-dpx-linux.rocm.gpu.gfx950.1) Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
#196825) **Summary.** Tests only, end to end: a module artifact guards a module-level global, the loading process does not define it, and the call has to fail loudly with a report that names the failing input (`[0] KeyError on G['AOT_HERMETIC_WEIGHT']`) and the scope its guards were rooted at, the globals of the module where `HermeticModule.forward` is defined. The alternative, falling back to the serialized scope, would make the guard a no-op checked against capture-time state, which is the silent failure mode; loud is recoverable on the serving machine. The test then takes the report's advice and pins how far that goes at this commit: defining the name resolves the guard and the call is served, but with the tensor serialized in the artifact rather than the one just defined, because the bytecode's globals are built once at load and a live value is substituted only for a name the scope had then. That `x @ saved` assertion is recorded as the limitation it is, not the intended end state: #196897, two commits up, makes a loaded module artifact re-read the live value on every call and flips it to `x @ (saved * 2)`, using this test as its witness. It is a separate commit because a guarded global the loading process lacks is a failure mode of its own, independent of where an opted-out result sits in dispatch and of what the report says when a tree raised. ## The scenario ```python # capture process: HermeticModule.forward reads the module-level AOT_HERMETIC_WEIGHT model = torch.compile(HermeticModule(), fullgraph=True, backend="eager", options={"guard_filter_fn": keep_global_guards}) model._aot_compile([ModelInput(args=(x,), kwargs={}, contexts=[])]) data = model._save_aot_compiled_module() # loading process: the global is absent torch._dynamo.reset() saved = globals().pop("AOT_HERMETIC_WEIGHT") reloaded = torch.compile(HermeticModule(), fullgraph=True, backend="eager") # no guard_filter_fn: inert on a load reloaded._load_aot_compiled_module(data) # a module load takes no f_globals= reloaded(x) # RuntimeError: No AOT compiled graph matched this call. Tried 1 compiled input(s): # [0] KeyError on G['AOT_HERMETIC_WEIGHT'] # For [0]: a guarded global is missing from the globals of the function this HermeticModule instance's # forward resolves to, since that is the one the load resolved, here vars(test_aot_compile); ... # Add a ModelInput covering this call, or check whether guard_filter_fn kept a guard ... ``` The reloading wrapper takes no `guard_filter_fn`: the load installs the artifact's own guards and captures nothing, so the loading process's filter has no say in what a loaded artifact checks. The sibling `test_aot_compile_module_reload_reads_the_live_global` does pass a filter on its reload, where it is equally inert. ## Taking the advice, and what the recovery arm pins ```python globals()["AOT_HERMETIC_WEIGHT"] = saved * 2 # define it in the named scope, with a DIFFERENT value reloaded(x) == x @ saved # served -- but with the tensor serialized in the artifact ``` The guards read the live scope by reference, so the new binding passes the kept `TENSOR_MATCH`, which checks metadata and not values. The bytecode's globals were built once, at load, and substitute a live value only for a name the scope has then, so the value serialized with the artifact was never overwritten. Binding `saved * 2` and asserting `x @ saved` is what pins that, and it is what makes the recovery assertion say which dict the dispatch READ rather than only that it stopped raising: asserting `x @ (saved * 2)` instead fails (`Tensor-likes are not close! Mismatched elements: 9 / 9`), and rooting the guards at a copy of the live scope rather than the dict itself is caught first by the hint assertion (the report drops the forward clause when the resolved dict is not the one the guards hold), with the recovery arm as the second line of defence. That `x @ saved` value is the parent's load-time snapshot, recorded here as the limitation it is and not as the intended end state: #196897, two commits up this stack, makes a loaded module artifact re-read the live value on every call and flips this very assertion to `x @ (saved * 2)`, using this test as the witness that its recorded name set is not intersected with the scope at load. The pin stays in this commit so that flip lands as a measured behaviour change rather than a silent one; the test comment says the same in one sentence, without the PR number, so it reads correctly both before and after that commit. Binding `saved` instead, which would make the arm invariant under #196897, was considered and declined: it would leave this test unable to tell the live dict from the serialized copy, and #196897 would have to re-add `saved * 2` to use it as a witness. ## Both lines of the report, and which sibling pins what The report is also asserted to carry the generic mismatch advice next to the hint: a missing global counts as the mismatch it is, because the report cannot tell whether a new `ModelInput` would read the absent global (one captured for a branch that does not read it is served with the name still undefined), so both lines are emitted, and for `HermeticModule`, which reads the global on its only path, the hint is the actionable half. The forward clause the test asserts is emitted when the scope `model.forward` resolves to is the dict the guards hold (`resolved is not None and resolved is missing_global._guard_globals`), which is the case for a load that passed no `guard_globals=`, resolved forward, and is not rebound after the load: ``` this test (un-rebound load) -> clause present, "here vars(test_aot_compile)" suffix ..._hint_covers_a_rebound_forward (rebinds BEFORE loading) -> clause present, no suffix (foreign dict) ..._survives_a_forward_resolve_that_raises (rebinds AFTER) -> clause absent ``` What tells this test from the rebound sibling is the recovery arm: defining the name in `globals()` serves the call here, where the same binding in that sibling still raises. ## Why its own test, and the fixture Most of the load-bearing assertions are on #196823's no-match report and its forward-naming hint, and the recovery assertion is on #196818's live-scope rooting, so this could equally have been folded into #196823; it stays separate because a guarded global the loading process does not have is a failure mode of its own, and each of those gets the commit that pins it. The fixture is the same `HermeticModule` and module-level weight `test_aot_compile_module_reload_reads_the_live_global` uses, the test for the opposite direction, rather than a second copy that differed only in an unchecked scale factor. Like that sibling it hides the module dict's leaked generated globals through the shared helper before capturing, since the scope resolved from `model.forward` is this module's dict and the capture leaks Dynamo's generated names into it. The load seeds nothing here, for the reason that sibling's comment gives: the only kept global guard is rooted at `AOT_HERMETIC_WEIGHT`, not at an import alias or the builtins-dict key. No behaviour change vs the parent: the diff is one 66-line test, nothing under torch/ moves. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_aot_compile_module_absent_global_fails_guard ``` Run in one process with the tests that share the fixture and the report, which unittest orders after this one, to show they still pass with it running first (5 tests, OK): ``` python test/dynamo/test_aot_compile.py -k test_aot_compile_module_absent_global_fails_guard -k test_aot_compile_module_reload_reads_the_live_global -k test_missing_key_inside_a_present_global_is_not_a_missing_global -k test_no_match_message_keeps_the_advice_for_every_entry -k test_no_match_message_hint_covers_a_rebound_forward ``` The whole file was run at this commit: ``` python test/dynamo/test_aot_compile.py ``` Authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> ## FAQ > FAQ: why not rename `AOT_HERMETIC_WEIGHT`/`HermeticModule` to something that > says what the fixture is for? The fixture is not this commit's: `git log -S` > puts `class HermeticModule` and the module-level `AOT_HERMETIC_WEIGHT` in > #196820, which introduces them along with its test that a reloaded module > artifact reads the live global. #196825 reuses them rather than adding a > near-duplicate module and weight. A rename therefore has to rewrite the fixture > definition in #196820 together with every test body that uses it, which by this > commit is spread across several of the stack's commits, in a stack whose whole > point is one reviewable behaviour per commit -- for a naming preference, with no > change in what is covered. The name is a poor one and #196820 says so: what > these tests pin is that a load reads the LIVE global rather than a sealed > capture-time copy, which is the opposite of hermetic. The rename is a mechanical > follow-up once the stack lands, touching the definition and every commit's uses > together. > **FAQ: the test pops `AOT_HERMETIC_WEIGHT` after `_hide_leaked_dynamo_globals()`, > and that order is what keeps cleanup from deleting the module-level fixture -- > why is the dependency not spelled out here?** It is real: the helper snapshots > `preexisting = frozenset(g)` over `g = globals()` and its cleanup deletes every > name not in that snapshot, so a pop moved above the helper drops the name from > the snapshot and the cleanup deletes the module-level global for the rest of the > process. Measured by mutation -- with the helper call moved below the pop (after > the capture) this test still passes and the next test that reads the fixture dies > with `NameError: name 'AOT_HERMETIC_WEIGHT' is not defined` at its `x @ > AOT_HERMETIC_WEIGHT`. The note is not added at this call site because the > dependency is a property of the shared helper, not of this test: six tests pop a > global around it, five of them in earlier commits of this stack (#196816, > #196823, #196824), and a note on one call site documents the helper's contract in > the one place that does not own it while leaving the other five bare. It belongs > in `_hide_leaked_dynamo_globals`'s own comment, which already explains the > snapshot-and-restore and reaches all six call sites at once; that is a one-commit > change to the commit that introduces the helper, not to this test-only commit. > **FAQ: why does this test not also assert `Tried 1 compiled input(s)` alongside > `No AOT compiled graph matched`?** Because the tried-count line is the report's > shape, which is pinned where the report is introduced: that commit asserts `Tried > 2 compiled input(s)` together with the `[0]`/`[1]` entries and their line > positions, and pins the exact line count for a one-input report in its > odd-separators test. This test pins a different thing -- that a guarded global > the loading process lacks fails the guard and is reported as `[0] KeyError on > G['AOT_HERMETIC_WEIGHT']` -- and its `[0] ...` assertion already fails if the > entry for the single compiled input stops being emitted. Re-asserting the count > here would add a second place to update when the report's wording changes, for > coverage the report's own test already has. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #196825 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048
…erving the load-time value (#196897) **Summary.** A module artifact loaded with a live guard scope has two dicts that must agree about one global: the kept guards read the scope by reference, while the compiled bytecode reads `fn.__globals__`, into which `__post_init__` merged the guarded names exactly once, at load. A kept `TENSOR_MATCH` certifies the exact Python type, dtype, shape, device and requires_grad, not values, so rebinding a guarded global to a DIFFERENT tensor of identical metadata passed the check while the graph went on computing with the tensor the load happened to see -- wrong numerics, nothing raised, and `test_aot_compile_module_reload_reads_the_live_global` pinned that as intended behaviour. This commit adds `AOTCompiledFunction._serve`, which re-takes the certified names out of `_guard_globals` into `fn.__globals__` immediately before running the graph, and routes `__call__` and all four exits of `AOTCompiledModel.__call__` through it, so `_serve` is the only caller of the raw `fn` and what a guard just certified is what the graph reads. Only a global a kept guard's own bare `GlobalSource` names is re-read (`_live_global_names`, recorded under the module load path's `_bytecode_reads_guard_scope and _has_global_guards` gate and not intersected with the scope), the load-time merge stays because `_check_external_refs` needs a certified global the graph never lifted bound before any call, and each read is one `scope.get(name, _UNBOUND)`. Three things change against the parent, all on a module artifact loaded with a live scope: an accepted post-load rebind is now computed with on every dispatch exit, an opted-out result is served whatever the scope binds, and a graph that `STORE_GLOBAL`s a certified global no longer accumulates the store across calls; `load_compiled_function(f_globals=...)` is unchanged until #197218. ## Where this sits in the stack Split from `[aot_compile] Arm the per-call re-read of a guarded global for a function artifact loaded with f_globals` (#197218, directly above) so each piece fits the review budget: this commit introduces the per-call re-read and serves `AOTCompiledFunction.__call__` and all four exits of `AOTCompiledModel.__call__` through it, armed for the module load path, which is the only path the load-time pick ever ran on. The re-read supersedes that pick as the source of a served value without removing it: the merge stays here and #196909 drops the flag that gates it, while #197218 widens what arms the re-read to `load_compiled_function(f_globals=...)`. The three fallback exits of module dispatch were briefly split out as a commit of their own (#197302) and are folded back here: with them out, this commit's own dispatch path served a stale global on three of its four exits, the bug it exists to fix one pass over. ## The bug: two dicts about one global ```python # module load path, parent and now: the kept guards resolve against the scope # the load resolved from model.forward (or the guard_globals the caller # supplied) and read it BY REFERENCE ... scope = model.forward.__globals__ # guards check scope["EPS"] # ... while the compiled bytecode reads fn.__globals__, which the load builds once. result.fn.__globals__["EPS"] # graph computes with this EPS = torch.tensor(2.0) # same dtype/shape/device/requires_grad reloaded(x) # parent: TENSOR_MATCH passes (metadata, not values); graph computes x * <load-time EPS> # now: TENSOR_MATCH passes; _serve writes scope["EPS"] into fn.__globals__ first; x * 2.0 ``` Rebinding a global after the load therefore changed what the guards check but not what the graph computes with, and the two only disagreed silently. `test_aot_compile_module_reload_reads_the_live_global` pinned that as intended behaviour ("A rebind after the load: the call still answers with the load-time value"), and `AOTCompiledModel.deserialize`'s docstring described the snapshot; this commit fixes it instead, and that assertion is flipped. ## BC: three changes against the parent All three are on a module artifact loaded with a live scope. 1. A call whose guards accept a post-load rebind now computes with the rebound value, whichever of the four dispatch exits serves it; the parent served the load-time value on every one. 2. A result that opted out via `disable_guard_check()` is served by the last-resort exit with whatever the scope binds, a value its kept guards REFUSED included; the parent served the load-time value there too, and `disable_guard_check()` flips one bool without disarming the re-read. 3. A graph that itself `STORE_GLOBAL`s a certified global no longer accumulates the store across calls. No scope rebind is needed to observe this one, which makes it the change a caller hits without doing anything. ```python class StoresEpsModule(torch.nn.Module): def forward(self, x): global EPS y = x * EPS EPS = EPS * 2 return y # three calls of a loaded artifact, E = the value the scope binds reloaded(x); reloaded(x); reloaded(x) # parent: x * E, x * 2E, x * 4E (the store accumulates in fn.__globals__) # now: x * E, x * E, x * E (each call starts from the scope's value again) ``` `test_aot_compile_module_store_global_does_not_accumulate` pins it on the module load path, the path this commit arms. Nothing that raised before stops raising, and a global that is not itself a kept guard's source keeps its load-time value exactly as before. One path is NOT changed by this commit: `load_compiled_function(f_globals=...)` still serves the load-time value, exactly as its docstring and the user guide describe, and `test_load_compiled_function_f_globals_accepted_rebind_is_not_used` still pins that; #197218 arms the re-read there and flips it. The tests listed under the Test Plan pin this commit's change: each is red on the parent's `aot_compile.py`. ## The fix: move the pick from load to call The root cause is that the substitution was a one-time merge. `__post_init__` picked the guarded names out of the supplied scope and folded them into `extra_globals`, i.e. into the dict `forward_callable` builds, so the live read happened exactly once, at load. ```python # parent, __post_init__ live = { name: guard_scope[name] for name in _guard_source_globals(output_graph) if name != builtins_key and name in guard_scope } extra_globals = {**(extra_globals or {}), **live} # now, __post_init__: record the set, and still merge at load certified = _guard_source_globals(output_graph) self._live_global_names = tuple(sorted(certified)) live = {} for name in certified: value = guard_scope.get(name, _UNBOUND) if value is not _UNBOUND: live[name] = value extra_globals = {**(extra_globals or {}), **live} # now, _serve: re-take the same names immediately before invoking the graph def _serve(self, *args, **kwargs): if self._live_global_names: scope = self._guard_globals if scope is None: raise AssertionError("_live_global_names recorded without a scope") f_globals = self.fn.__globals__ for name in self._live_global_names: value = scope.get(name, _UNBOUND) if value is not _UNBOUND: f_globals[name] = value return self.fn(*args, **kwargs) ``` `__post_init__` records the name set under the same gate the merge already had, `_bytecode_reads_guard_scope and _has_global_guards`, so only the module load path arms the re-read here -- `load_compiled_function` passes one dict as both `f_globals` and `guard_globals` and has the same divergence, which #197218 fixes by widening the gate -- and still merges the bound names into the bytecode's globals at load. That merge is not made redundant by the re-read. `forward_callable` runs `_check_external_refs` at load, before `_serve` can ever run, and a certified global the bytecode reads but the graph never lifted -- a global the forward mutates or returns -- is in `external_refs` but in neither `import_sources` nor `used_globals`, the only dicts `forward_callable` builds `fn.__globals__` from, so the merge is what binds it. (The serialized `output_graph.global_scope` does carry it, being filtered to the kept guards' roots, but `forward_callable` never reads that dict.) The comment on the merge says so, and `test_aot_compile_module_load_binds_a_global_off_the_graph` pins that shape on its RETURNS half: ```python class ReturnsEpsModule(torch.nn.Module): def forward(self, x): return x + 1, EPS # EPS returned, not computed with env = result._artifacts.runtime_env assert "EPS" in env.external_refs assert "EPS" not in env.used_globals and "EPS" not in env.import_sources # with the merge deleted the load itself refuses: # Missing required external references: ['EPS'] ``` A forward that returns `EPS` rather than computing with it has the placeholder it was lifted into pruned as unused, so `used_globals` -- filled from the graph inputs' sources -- never records a name the generated bytecode still reads. The MUTATES half needs a container to show, a rebound tensor global being lifted like any other read; #196909, two commits up, parametrizes both halves over a list global and drops the flag that gates the merge. ## Every dispatch exit goes through `_serve` `AOTCompiledModel.__call__` has four exits that run a graph. The first pass checks the first compiled result's guards and, on a pass, serves it; below it sit the rest of that sweep over `results[1:]`, a re-check pass that re-runs every `check()` (one exit of `check()` refuses from the recursive dict-tag fast check without running the tree, and disarms it, so the second call runs the tree the first skipped), and a last resort that serves a result whose caller opted out via `disable_guard_check()`. ```python # parent -> now, at each of the four exits return first.fn(self.model, *args, **kwargs) -> return first._serve(self.model, *args, **kwargs) return result.fn(self.model, *args, **kwargs) -> return result._serve(self.model, *args, **kwargs) # sweep return result.fn(self.model, *args, **kwargs) -> return result._serve(self.model, *args, **kwargs) # re-check return result.fn(self.model, *args, **kwargs) -> return result._serve(self.model, *args, **kwargs) # opted-out last resort ``` All four call `_serve`, which is thereby the only caller of the raw `fn`, and `_serve`'s docstring says so. That also rules out a state the re-read could otherwise have introduced: `_serve`'s write into `fn.__globals__` persists between calls, so a pass that ran the raw `fn` after an earlier accepted call had re-read rebind R1 would compute with R1 while the scope binds R2 -- neither the serialized value nor the live one; with every exit re-reading immediately before it runs the graph, no pass can serve a value an earlier call re-read for a name the scope binds. `test_aot_compile_module_second_pass_rebind_is_served` pins exactly that: ```python EPS = torch.tensor(3.0) reloaded(x) # first pass accepts, re-reads 3.0 assert result.fn.__globals__["EPS"] is first_rebind # asserted: left in fn.__globals__ EPS = torch.tensor(2.0) # stub: the scan's check() answers False without running the tree (what the # fast path that makes the re-check pass necessary answers); every check() # after it runs the real tree with patch.object(manager, "check", side_effect=rejects_the_scan) as check: served = reloaded(x) assert check.call_count == 2 assert served == x * 2.0 # not the load-time value, not x * 3.0 ``` The call at `EPS = 2.0`, on a LOADED artifact, the only kind the re-read is armed for, has to run `check()` exactly twice and serve `x * 2.0`. The stub replaces this case's earlier use of the file's `_install_global_probe` idiom, for a measured reason the Test Plan gives. `test_aot_compile_module_sweep_rebind_is_served` pins the `results[1:]` sweep: two results compiled for inputs of shape `(3,)` and `(4,)`, so the first pass refuses the `(4,)` call on the first and the sweep serves it from the second, which has to compute with the rebind its own guards just accepted; the second result's `fn.__globals__` then holds the rebind and the first's still the load-time value, both asserted. The same test then calls `results[0]` directly, through `AOTCompiledFunction.__call__`, with the `(3,)` input its guards accept, and that call has to compute with the rebind and leave it in the first result's `fn.__globals__`: `__call__` is the one `_serve` site module dispatch never reaches, and it is public through `compiled_results`. The dispatch comment records why the `_serve` frame is not gated per site all the same: a site that got a per-site gate wrong would serve a stale global with every guard passing. That such a site would also be invisible to every test whose artifact is not armed is the FAQ's argument below, not the comment's. ## Serve the rebind rather than refuse it Serving is the right direction: the guard the swap satisfies certifies exactly the properties the graph was compiled for, so the new value is one the graph can legitimately run on, and refusing would mean raising on a call whose guards all pass. The alternative of re-rooting the guards at `fn.__globals__` was rejected for the opposite reason -- it makes the caller's dict write-only from the guards' point of view, which is the contract `guard_globals` exists to provide. ## What is re-read, and what is not Two details are deliberate and each is pinned by a test. First, the recorded name set is NOT intersected with the scope at load: a name the scope does not bind yet fails the guard rooted at it, and a caller told to bind it by the `KeyError on G['X']` message then gets its value read, not the value serialized with the artifact (`test_aot_compile_module_absent_global_fails_guard`). Second, only a global that is itself a kept guard's source is re-read -- `_guard_source_globals` keeps the bare `GlobalSource`s -- so a global whose guard a filter dropped keeps its load-time value, because nothing certifies a live value for it, and so does a container a kept guard reaches only through a sub-path: ```python # test_aot_compile_module_sub_path_global_is_not_read_live: the kept TENSOR_MATCH is on # G['AOT_NESTED_GLOBAL']['a'] and certifies that one item, not the dict's other members AOT_NESTED_GLOBAL = {"a": torch.randn(3), "b": torch.nn.Parameter(torch.ones(3))} # ... capture, save, load, then rebind the CONTAINER to a dict whose "a" still passes: AOT_NESTED_GLOBAL = {"a": torch.randn(3), "b": torch.nn.Parameter(torch.ones(3, dtype=torch.float64))} reloaded(x) # AOT_NESTED_GLOBAL is not re-read: the load-time dict is served even though the guard passes ``` `test_aot_compile_module_sub_path_global_is_not_read_live` pins that on the module path, and `_serve`'s and `AOTCompiledModel.deserialize`'s docstrings say it in as many words rather than promising a re-read of every global a kept guard is "rooted at", which in this file's own vocabulary (`get_global_source_name`) is the wider set. `test_aot_compile_module_rebind_after_load_is_served` pins the certified set from both sides with `TwoGlobalsModule`, whose forward reads `EPS`, a plain tensor whose `TENSOR_MATCH` is kept, and `AOT_UNGUARDED_PARAM`, an `nn.Parameter` whose guard the filter drops: after rebinding both, the call has to follow the new tensor and the OLD Parameter. ## A graph that stores to its own global A graph that itself rebinds a guarded global (`global W; y = x * W; W = W * 2`) is served the same way. Dynamo replays the store as a `STORE_GLOBAL` into the bytecode's globals, never into the scope the guards read, so the stored value is one no guard certified; previously it accumulated there across calls (call n computed with the load value doubled n times while the guards went on passing on the scope's), and now the re-read takes the scope's value back before each call. Neither writes the scope, which eager would, and that is pre-existing. `_serve`'s docstring says so, and says what a store to a global NO kept guard certifies gets, the one case the re-read does not take back: that value stays in the bytecode's globals and goes on accumulating there, so the docstring's "every other global" clause is about what those globals HOLD and not about the load-time value they were built with. Measured on an armed artifact whose forward is `global P; y = x * EPS + P; P = P * 2`, with `EPS` a plain tensor (certified) and `P` a Parameter (its guard dropped by the filter, so not in `_live_global_names`): | call | answer | `fn.__globals__["P"]` after the call | module `P` | | --- | --- | --- | --- | | 1 | `x * 6.0 + 1.0` | `2` | `1.0` | | 2 | `x * 6.0 + 2.0` | `4` | `1.0` | | 3 | `x * 6.0 + 4.0` | `8` | `1.0` | `test_aot_compile_module_store_global_does_not_accumulate` pins the certified half on the module load path: three calls of a loaded `StoresEpsModule` artifact answer alike, the scope's `EPS` is the value it held before them and the doubled value is left in the bytecode's globals. #197218 adds the function-path case. ## The opted-out last resort The last resort changes with the other three exits: the parent served the load-time value there as well, and it now serves whatever the scope binds. What is documented and pinned rather than changed is that the opt-out does not disarm the re-read: the name set is recorded by the load, before the opt-out flips anything, so an opted-out artifact goes on serving whatever the scope binds, a value a kept guard would have rejected included. ```python EPS = torch.nn.Parameter(torch.tensor(2.0), requires_grad=False) # the kept TENSOR_MATCH refuses a Parameter reloaded(x) # RuntimeError: No AOT compiled graph matched this call ... # expected type of 'G['EPS']' to be <class 'torch.Tensor'>, but found <class 'torch.nn.parameter.Parameter'> result.disable_guard_check() reloaded(x) # == x * 2.0: the last resort serves the value the check refused del EPS reloaded(x) # still x * 2.0: an unbound name is skipped, not deleted ``` `test_aot_compile_module_opted_out_load_rebind_is_served` asserts the no-match report's `expected type of 'G['EPS']'` line, so it is that guard and not a missing name that pushes dispatch off both guard-checked passes onto the last-resort exit, and watches the opted-out call follow the rebind. That is the opt-out being unsafe by construction, not an accident, since holding those names at their load-time values would be no more checked, only stale, and `_serve`'s docstring says so, along with what a name the scope no longer binds gets under the opt-out: the last value read, since the re-read skips a name the scope lacks rather than deleting it. The alternative of clearing `_live_global_names` in `disable_guard_check()` was tried as a mutation and refuted by that test. ## One read: `scope.get(name, _UNBOUND)` `_serve`'s re-read is one `scope.get(name, _UNBOUND)`: neither a membership test followed by a read, nor a subscript under `try`/`except KeyError`. Against the membership test, the scope is live, so a `del` of the name landing between the test and the read would let a bare `KeyError` out of a call whose guards had just passed, where the docstring promises a skip. `test_aot_compile_module_global_deleted_under_the_re_read_is_skipped` pins that with a scope that answers the membership test and raises from `__getitem__`: ```python class DeletedBetweenTestAndRead(dict): def __contains__(self, name): return True def __getitem__(self, name): raise KeyError(name) with patch.object(result, "_guard_globals", DeletedBetweenTestAndRead()): reloaded(x) # check-then-read form: KeyError: 'EPS'; dict.get consults neither, so x * rebound ``` Against the subscript, the scope can be a mapping the CALLER passed as `guard_globals`, and a subscript runs whatever `__missing__` hook that mapping defines: a `collections.defaultdict` is then MUTATED by the read and the graph computes with the value it fabricates, every guard passing on it -- the exact failure this commit exists to remove, reached through the read that fixes it. `test_aot_compile_module_missing_hook_scope_is_not_asked_to_fabricate` pins both reads against one: ```python scope = collections.defaultdict(lambda: torch.tensor(99.0)) compiled = AOTCompiledModel.deserialize(EpsOnlyModule(), data, guard_globals=scope) assert dict(scope) == {} # the load did not subscript it compiled(x) # RuntimeError: ... KeyError on G['EPS'] result.disable_guard_check() compiled(x) # == x * 5.0, the serialized value assert dict(scope) == {} # nor did either call ``` The `defaultdict` is still empty after the load and after a call -- the only path that can bind the fabricated tensor in the bytecode's globals is a subscript of that dict, which would leave its entry behind, so the empty dict is the pin and an assertion on those globals adds nothing -- and the guard rooted at the name refuses the call until that result opts out, after which the serialized value is what is served. `dict.get` neither dispatches through an overridden `__getitem__` nor pays the raise, so it keeps the single lookup the `del` window argues for, and the module-level `_UNBOUND` sentinel is what separates a global bound to `None` from an absent one, which `test_aot_compile_module_global_bound_to_none_is_re_read` pins (with `None` as the default the read would skip the binding and leave the last value written). The load-time merge in `__post_init__` reads the same way, and the `del` window is pinned at the `_serve` site alone: no call is in progress and no guard has run at the merge, so a name the scope lacks there, never bound or deleted under the read alike, is left unbound and the guard rooted at it then fails, which is what the merge comment says. ## The `AssertionError` narrowing `_serve` narrows `_guard_globals` the way `_live_guard_manager` narrows `guard_manager`, with an `AssertionError` rather than a fall-through to the raw `fn`. The arm is unreachable: `_live_global_names` has its one assignment in `__post_init__`, under `if guard_scope is not None`, and the constructor is the only writer of `_guard_globals`. It is loud all the same because a silent arm there would be the exact defect this commit fixes, a stale global served with every guard passing: with `_guard_globals` patched to `None` on an armed result, the `is not None` form this replaces served the value the previous call had re-read, and this form raises. ## Documented rather than changed `_serve`'s docstring says what a name the scope does not bind gets: the re-read skips it rather than deleting it, so it keeps whatever it last held -- the serialized value if the scope never bound it -- and, unless the check is disabled, the guard rooted at it refuses the call. Two caveats that docstring carries, since the per-call re-read is what it now promises: - The re-read is not atomic with the guard check before it, so a rebind landing between the two is served unchecked -- the same window an eager compiled frame has between guard evaluation and its bytecode's global reads. - The write lands in the loaded artifact's own `fn.__globals__`, which every call of it shares, so two threads serving one loaded artifact race on it and a caller who needs isolation loads the artifact once per thread, each load building one such dict per compiled result. That docstring also records what does NOT arm the re-read here: a function artifact loaded with `f_globals` (until #197218), and an artifact compiled in this process, which is handed no scope, so its globals keep the values the capture copied while its guards read the module dict they were rooted in. That divergence is pre-existing and deliberately not widened here. The `_live_global_names` field comment says what arms the set: `_bytecode_reads_guard_scope`, and not a supplied scope as such, since `load_compiled_function` supplies one as `guard_globals` and is not armed. That only the module load path sets that flag is the adjacent `_bytecode_reads_guard_scope` comment's own line, rewritten here to say the certified names are picked in again by `_serve` before every call. The `AOTCompiledModel.deserialize` docstring says the certified names are re-taken from the live dict on every call, and that the certification stops at a result that opted out through `disable_guard_check()`: dispatch serves it once every checked result refused the call, and the re-read serves it whatever the live dict binds, a value a kept guard refused included. Without that sentence the docstring's "a value the graph reads live is one a passing guard certifies" was contradicted by the last-resort exit `test_aot_compile_module_opted_out_load_rebind_is_served` pins, and that docstring is the one a module-load caller reads. For the same reason it also carries what the per-call write costs a caller, beside the paragraph that already discloses the load-time mutation of the same dict: every call writes the certified names into the globals of the compiled RESULT that serves it, which every call that result serves shares, so two threads whose calls land on one result while either rebinds a guarded global race on that dict, and a caller who needs isolation loads once per thread, each load building one such dict per serialized result. The artifact `deserialize` returns has no globals of its own: it builds one `AOTCompiledFunction` per serialized result and `forward_callable` gives each a fresh `f_globals`, which is why two threads whose calls land on DIFFERENT results do not race, and `test_aot_compile_module_sweep_rebind_is_served` asserts exactly that shape -- the rebind in `results[1]`'s globals and the load-time value still in `results[0]`'s. The parent had no per-call write at all, so this is a new hazard, and `_serve`'s own statement of it is not enough: `_serve` is private. The `bytecode_reads_guard_scope` paragraph of `AOTCompiledFunction.deserialize` says the certified names are re-taken before every call as well; both are true of every dispatch exit, measured by the tests above (the re-check pass serves `x * 2.0` after an accepted call re-read `3.0`; the last resort serves the Parameter the check refused). Three test comments follow the code: - `test_aot_compile_module_guards_track_rebound_global`, whose dispatch a rebound global redirects between two results, now says every call refreshes the name the guards specialised on. - `test_module_dispatch_evaluates_a_matching_tree_once` now says the scan calls the matching result's `_serve`, since the raw `fn` field it named is no longer what any dispatch exit calls. - `test_load_rederives_a_builtins_key_bound_to_its_own_snapshot` says what keeps the builtins key out of the bytecode's globals now that the `name != builtins_key` test it quoted is gone: that case is a function-path load, so the gate keeps it out there and the pick never runs at all, and the pick the module path arms takes a guard's own bare `GlobalSource` alone. One dead token goes with that pass. The parent filtered the key out of the load-time pick (`name != builtins_key`) and this commit first carried that filter into the new `certified` line as `- {builtins_key}`, where it can never remove anything: `load_builtin_from_argval` is the one site in the tree that mints a source under this key, always `DictGetItemSource(GlobalSource(key), name)` and only for a callable builtin, so a chained source is the only way the key is reached and `_guard_source_globals` drops it by construction. Measured: instrumenting that function to record every call where the key is truthy and present in its result reports no hit over the whole file, and the file is green with the subtraction dropped. The subtraction one branch up, on the WIDE set (`recorded_globals`), is load-bearing and stays: the serializer writes the key into `global_scope` whether a guard reads it or not, and dropping that one turns the file red, which is why only the narrow one is dropped. Nothing in that pass changes behaviour: the docstrings, that field comment, the measured cost in the dispatch comment, the dropped subtraction and the tests only describe and pin what the code above already does. ## Test fixtures One test fixture moves to module level, others are new there, and one pre-existing leak is fixed. ```python class EpsOnlyModule(torch.nn.Module): # new: x * EPS class TwoGlobalsModule(torch.nn.Module): # moved: x * EPS + AOT_UNGUARDED_PARAM (Parameter's guard dropped) class TwoCertifiedModule(torch.nn.Module): # new: x * EPS + AOT_LIVE_SCALE, two certified names class StoresEpsModule(torch.nn.Module): # new: rebinds EPS in forward class ReturnsEpsModule(torch.nn.Module): # new: returns EPS instead of computing with it ``` `TwoGlobalsModule` is the one that moves: it was a class local to `test_aot_compile_module_only_the_guarded_global_is_read_live` and the new `test_aot_compile_module_rebind_after_load_is_served` loads it too. `AOT_UNGUARDED_PARAM`'s initial binding moves up beside it; the NAME was already a module-level global at the parent, declared `global EPS, AOT_UNGUARDED_PARAM` in that test and first bound there, so what changes is where the Parameter is first bound and not who can see the name. `EpsOnlyModule`, `TwoCertifiedModule` -- whose forward reads two plain tensor globals, with `AOT_LIVE_SCALE`, so the certified set has two names in it where every other fixture leaves it at one -- `StoresEpsModule`, whose forward rebinds the global it reads, and `ReturnsEpsModule`, whose forward returns it instead of computing with it, are new at that level, and the parent has none of them anywhere in the file. That test also gains an `addCleanup` for `AOT_UNGUARDED_PARAM`, which fixes a leak the parent already had rather than one the move introduces: the parent rebound that global under its own `global` statement and restored only `EPS`, so the rebind was file-visible and unrestored there too -- unnoticed, not invisible. ## Review order Review `_serve` first, then what `__post_init__` records for it, `__call__` and the four exits of `AOTCompiledModel.__call__` with the dispatch comment, then the two prose passages that described the old snapshot semantics (the `AOTCompiledModel.deserialize` docstring and the `bytecode_reads_guard_scope` paragraph of `AOTCompiledFunction.deserialize`), then the tests, starting with `_load_armed_module`, the loader all but one new case goes through. Test Plan: ``` python test/dynamo/test_aot_compile.py ``` The new cases, and the existing cases that pinned the old behaviour: ``` python test/dynamo/test_aot_compile.py -k test_aot_compile_module_rebind_after_load_is_served python test/dynamo/test_aot_compile.py -k test_aot_compile_module_every_certified_global_is_re_read python test/dynamo/test_aot_compile.py -k test_aot_compile_module_store_global_does_not_accumulate python test/dynamo/test_aot_compile.py -k test_aot_compile_module_load_binds_a_global_off_the_graph python test/dynamo/test_aot_compile.py -k test_aot_compile_module_global_bound_to_none_is_re_read python test/dynamo/test_aot_compile.py -k test_aot_compile_module_sweep_rebind_is_served python test/dynamo/test_aot_compile.py -k test_aot_compile_module_second_pass_rebind_is_served python test/dynamo/test_aot_compile.py -k test_aot_compile_module_opted_out_load_rebind_is_served python test/dynamo/test_aot_compile.py -k test_aot_compile_module_global_deleted_under_the_re_read_is_skipped python test/dynamo/test_aot_compile.py -k test_aot_compile_module_missing_hook_scope_is_not_asked_to_fabricate python test/dynamo/test_aot_compile.py -k test_aot_compile_module_certified_names_are_sorted_at_load python test/dynamo/test_aot_compile.py -k test_aot_compile_module_reload_reads_the_live_global python test/dynamo/test_aot_compile.py -k test_aot_compile_module_absent_global_fails_guard ``` The existing case that pins the sub-path exclusion the docstrings describe: ``` python test/dynamo/test_aot_compile.py -k test_aot_compile_module_sub_path_global_is_not_read_live ``` `test_aot_compile_module_rebind_after_load_is_served` rebinds two globals under `keep_tensor_guards_unsafe`: a plain tensor whose `TENSOR_MATCH` is kept, and an `nn.Parameter` whose guard the filter drops. The call has to follow the new tensor and the OLD Parameter, which pins the re-read and that the set did not widen past what a guard certifies. All but one of the new cases load through `_load_armed_module`, which asserts the certified set on each loaded result before the test rebinds anything -- `("EPS",)`, or `("AOT_LIVE_SCALE", "EPS")` for the two-name cases -- so a served load-time value would be the test's own doing and not an unarmed artifact; the `__missing__` pin loads directly, since what it needs as the guard scope is a `collections.defaultdict` and the helper always passes the module's own globals. That helper binds EVERY name it arms twice rather than only `EPS`: `torch.tensor(5.0 + i)` before the capture and `torch.tensor(6.0 + i)` between the save and the load, one `addCleanup` per name, and it loops its `assertIs(result.fn.__globals__[name], value)` over those load-time bindings on every loaded result before the caller rebinds anything. The first binding is what makes a baseline discriminate: at the module-level `EPS = 1e-7`, `x * EPS` is inside `assertEqual`'s tolerance of zero, so every assertion that the load-time value is what is served BEFORE a rebind would hold against a served zero as well, which is the one thing those assertions exist to rule out. The second is what makes the load-time value differ from the pickled one in value and not only in identity; without it the two are numerically equal and every mutant of the load-time merge is invisible to all but one `assertIs` in the file. Binding every name is what pins the merge's LOOP over the certified set, not just its first iteration: with `for name in sorted(certified)[-1:]`, which binds `EPS` and skips `AOT_LIVE_SCALE` on an artifact that has two certified names, the whole file was green while the helper hardcoded `EPS`, and now fails at the helper's own `assertIs`, `tensor(5.) is not tensor(6.)`, in the cases whose artifact has two certified names. The two baselines that case reads (`load_time_eps, load_time_scale`) are taken after the helper returns for the same reason, since both names now move under it. `test_aot_compile_module_every_certified_global_is_re_read` is one of the cases whose artifact has two certified names, and it is what pins `_serve`'s loop over them rather than its first iteration. With `for name in self._live_global_names[:1]`, which re-reads the first name and leaves the rest at their load-time values, and with a `break` on the first name the scope no longer binds in place of the skip, the whole file is green except for that case; both were run over the whole file. `test_aot_compile_module_certified_names_are_sorted_at_load` pins the `sorted()` at the load, which that case leans on to know that the name it deletes (`AOT_LIVE_SCALE`) is the recorded set's first. An assertion on the recorded tuple cannot pin the sort on its own: `_guard_source_globals` hands back a set, so with `tuple(certified)` in place of `tuple(sorted(certified))` a two-element order follows string-hash randomization, and that mutant passes the two-name case under some `PYTHONHASHSEED` values and fails it under others. The new case takes the seed out of it by stubbing `_guard_source_globals` with the reverse-sorted order, so the mutant lands `('EPS', 'AOT_LIVE_SCALE')` whatever the seed: it fails with `String comparison failed: 'EPS' != 'AOT_LIVE_SCALE'`, where this commit's tree passes. What the case asserts is the stub's own record, that the load was handed `['EPS', 'AOT_LIVE_SCALE']` -- without which the helper's assertion pins nothing -- and not the recorded tuple, which is the comparison the helper already made against the `names` the case passes it. `test_aot_compile_module_store_global_does_not_accumulate` is the BC change no rebind by the caller is needed to see: three calls of a loaded `StoresEpsModule` artifact each answer `x * 6.0` -- the helper's load-time `EPS`, which is what the test asserts against, not a literal -- the scope's `EPS` is still the tensor it bound before them, and the bytecode's globals hold `12.0`, the store the last call replayed. The same load and the same three calls against the parent's `aot_compile.py`, run as a script since the parent has no `_live_global_names` for the helper to assert on, answer `[6.0, 12.0, 24.0]` as scale factors on `x` (the helper's `x` is `torch.randn(n)`; measured with `torch.ones(3)`) and leave `48.0` in the bytecode's globals, the scope's `EPS` still `6.0`. `test_aot_compile_module_load_binds_a_global_off_the_graph` is the only case whose certified name never becomes a graph input, which is the shape the load-time merge exists for: `ReturnsEpsModule.forward` returns `EPS` instead of computing with it, so the placeholder it was lifted into is pruned as unused and `used_globals` -- filled from the graph inputs' sources -- never records it. The case asserts the name is in `external_refs` and in neither `used_globals` nor `import_sources`, then that `fn.__globals__` binds the scope's tensor with no call yet made, so the merge is the only thing that can have bound it, then calls, rebinds and calls again, which only the per-call re-read can follow. Both binders are pinned there, on the one shape only one of them can serve. `test_aot_compile_module_global_bound_to_none_is_re_read` loads that same shape for the sentinel. A scope that binds a certified name to `None` BINDS it, so the graph owes the call `None`, and with `None` as the absent-name default of either read the two cases are indistinguishable: the binding is skipped and the graph answers with the value the last read wrote, every guard passing on it. The returning shape is what lets `None` reach the answer rather than an operator, and the check has to be off, since `None` is a binding no kept `TENSOR_MATCH` accepts -- dispatch refuses it on both checked passes and the opted-out last resort is the exit that serves. Measured over the whole file, `_UNBOUND = None` fails only this case, `AssertionError: tensor(2.) is not None`, the rebind the previous call re-read; so does the equivalent, a `scope.get(name)` read with `if value is not None` at both sites. The rest of the file is green under both, every certified global in it a tensor that no case binds to `None`. With the parent's `torch/_dynamo/aot_compile.py` checked into the tree and this test file kept, every red case is one listed above: the pre-existing ones fail with `Tensor-likes are not close!`, and the ones that assert on `_live_global_names` error with `AttributeError: 'AOTCompiledFunction' object has no attribute '_live_global_names'`, the field being new here. The deliberate details and every dispatch exit were checked by mutation over the whole file, each mutant run as a whole-file run at this commit. Making the `_serve` re-take a no-op fails nearly every case above, with `Tensor-likes are not close!` where the forward computes with the global and `Scalars are not close!` where it returns it, and the ones it leaves green are the ones that observe no served rebind, the sort pin and the `__missing__` pin, whose scope is empty. Intersecting the recorded set with the scope at load time fails `test_aot_compile_module_absent_global_fails_guard`, the same way, and `test_aot_compile_module_missing_hook_scope_is_not_asked_to_fabricate`, whose name would not be recorded at all. Clearing `_live_global_names` in `disable_guard_check()`, i.e. letting the opt-out hold the load-time value, fails `test_aot_compile_module_opted_out_load_rebind_is_served` and the opted-out tail of `test_aot_compile_module_every_certified_global_is_re_read` the same way, and `test_aot_compile_module_global_bound_to_none_is_re_read` at its `assertIsNone`. Putting the membership test back in front of `_serve`'s read fails only `test_aot_compile_module_global_deleted_under_the_re_read_is_skipped`, with `KeyError: 'EPS'`; turning either read back into a subscript under `try`/`except KeyError` fails only `test_aot_compile_module_missing_hook_scope_is_not_asked_to_fabricate` -- at the merge, on the caller's dict (`Additional keys in the actual mapping: ['EPS']`), and at `_serve`, on the served value (`Tensor-likes are not close!`, `99.0` against the serialized `5.0`). Reverting each exit of `AOTCompiledModel.__call__` to the raw `fn` one at a time: the first pass fails most of the cases above, including `test_aot_compile_module_second_pass_rebind_is_served` at its accepted first-pass call; the `results[1:]` sweep fails only `test_aot_compile_module_sweep_rebind_is_served`; the re-check pass fails only `test_aot_compile_module_second_pass_rebind_is_served`, at the served value; the last resort fails `test_aot_compile_module_opted_out_load_rebind_is_served`, `test_aot_compile_module_global_bound_to_none_is_re_read` -- the exit that serves its `None` binding -- and, at its opted-out tail, `test_aot_compile_module_every_certified_global_is_re_read`. Reverting `AOTCompiledFunction.__call__` to the raw `fn` fails only `test_aot_compile_module_sweep_rebind_is_served`, at its direct call of `results[0]`, with `Tensor-likes are not close!`; with that call left out of the test, the same revert runs the whole file green, which is why the test makes it. The load-time merge is measured by the same battery. Deleting its `live` loop and the `extra_globals = {**(extra_globals or {}), **live}` line fails the cases above in two ways: the ones whose forward returns the global error at the load itself, `RuntimeError: Missing required external references: ['EPS']`, and the ones that go through `_load_armed_module` fail at its `assertIs` with `tensor(5.) is not tensor(6.)`, the pickled value where the scope's belongs. Making the merge read the artifact's own dict (`self._artifacts.runtime_env.used_globals`) instead of the guard scope fails the same cases the same way, the absent-name default swallowing the one name that dict does not have. Both of those were nearly invisible until the helper bound its names a second time before the load: the one failure they produced was an `assertIs` whose operands were numerically equal; restricting the merge to the last sorted name fails the two-name cases, as above. Every case named loads a module artifact rather than compiling one in this process, which is what arms the re-read. The one thing above no test reaches, the unreachable arm of `_serve`'s narrowing, was measured with a scratch script (not committed) that loads an armed `EpsOnly` module artifact through the same `keep_tensor_guards_unsafe` path: with `_guard_globals` patched to `None`, the call raises `AssertionError: _live_global_names recorded without a scope` here, where the `is not None` form this replaces, patched over the method, served `x * 9.0` -- the rebind the previous call had re-read -- with the scope binding `11.0`. `test_aot_compile_module_second_pass_rebind_is_served` forced its re-check with `_install_global_probe("EPS", misses=1)` until this round, and that made its `check()` count order-dependent. The count holds only if the scan's `check()` is the evaluation that spends the probe's one miss, and that miss is a budget EVERY reader of the module's `EPS` draws on: a reader that gets there first spends it, the scan then accepts, and the pass the case exists for never runs. The `matches_dict_tag` fast path, which lets a `DictGetItemGuardAccessor` skip its lookup altogether, is not a second defeater here -- it is gated on `_is_immutable_object && !_is_tensor` (`torch/csrc/dynamo/guards.cpp:5758`) and `EPS` is a tensor, so it is unreachable for this global; the shared miss budget is the whole reason this case stubs the scan's answer instead. Measured with the re-check exit reverted to the raw `fn`, which should fail the case on the served value: five whole-file runs of that mutant tree failed it four times there and once at `check.call_count`, `Expected 2 but got 1`. Re-arming the probe just before the call does not fix it -- that one failure was measured with the re-arm in place. Stubbing the scan's answer takes the count out of the dict's hands altogether: it is now a property of the stub, the same mutant fails the case at the served value, and the whole file is green at this commit in the loader's order, reversed, and in a seeded shuffle. The pre-existing cases that force a re-check through `_rescued_by_the_recheck`'s probe are untouched here; they assert the same `check()` count, `assertEqual(check.call_count, 2)`, under the same shared budget, and it holds there because the helper installs the probe on `AOT_BRANCH_SCALE` itself and makes exactly one call with it, so nothing can spend that miss between the install and the call it is meant for. ``` lintrunner --take RUFF,PYFMT torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py ``` Authored with the assistance of Claude Code. > **FAQ: the extra `_serve` frame is paid by every artifact, the ones that can > never use it included, and its measured 0.4us is a ~40% add on top of the > ~1us guard eval the module dispatch sites exist to avoid -- so hoist the > `if result._live_global_names` test to the call sites and keep the fast path > frame-free.** > > The premise about the test is right: it is call-invariant, so this is a cost > question and not a correctness one. `_live_global_names` has exactly one > assignment in the tree, in `__post_init__`, and the field is `init=False`, so > whether it is empty is fixed for an instance's lifetime; what changes per call > is what the loop in `_serve` READS out of the scope, which is the point of the > commit, and the hoist moves the gate, not the read. > > The arithmetic does not hold, because `0.4us` is the ARMED cost, not the > frame. The dispatch comment prices what the sites pay on an armed artifact > with one certified name -- the frame plus a scope read and a dict write for > that name -- and that re-read is the fix itself, which no gate can remove on > an armed artifact. What a per-site gate could save is the frame alone, on the > artifacts that are not armed, and that frame was timed paired: raw, `_serve` > and hoisted inside ONE loop iteration so host drift cancels, 25 rounds of > 20000 calls of a loaded one-op module under the default filter (not armed). > Medians of the per-round figures: raw `6.677us`, `_serve` `6.892us`, hoisted > `6.664us`, and the paired `_serve`-minus-raw difference `0.240us` as a median, > `0.235us` as a mean (min `0.124`, max `0.519`); a second run of the same > script read `0.252us` and `0.282us`. That is ~27% of the `0.879us` the > `check()` it follows costs and 3.6% of the raw call of a ONE-op eager graph -- > the floor, since any real graph shrinks the share further. Armed with one > name, the same paired method read `0.325us` and `0.373us` as medians on those > two runs, which is the figure the comment rounds to `0.4us` and sets against > that `check()` cost, which the comment states as `~0.85us` -- an earlier > figure for the same eval, not a rounding of the `0.879us` measured here. > > What the frame buys is that `_serve` is the only caller of the raw `fn`. The > hoist spreads the gate over five sites (`__call__` and the four exits of > `AOTCompiledModel.__call__`), and a site that gets it wrong serves the > load-time value on an armed artifact only -- silent wrong numerics, the exact > bug this commit fixes, and invisible to every test whose artifact is not armed, > which is most of the file. The commit's own history shows the shape of that > failure: with three exits on the raw `fn`, the whole file stayed green except > for the tests written to pin them. The frame-free variant that keeps one call > site, binding `self._serve` to `self.fn` in `__post_init__` when the set is > empty, is worse: it setattrs over a method on the instance, which the `fn` > field comment says this class deliberately does not do. Co-Authored-By: Claude Opus 5 <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #196897 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825
…tion artifact loaded with f_globals (#197218) **Summary.** `__post_init__` recorded `_live_global_names` under `_bytecode_reads_guard_scope and _has_global_guards`, and that flag is set by exactly one caller, `AOTCompiledModel.deserialize`, so on the function load path the per-call re-read #196897 introduced never armed. Yet `load_compiled_function` passes one dict as both `f_globals` and `guard_globals`, so a function artifact had the same two disagreeing dicts -- its kept guards read `f_globals` by reference while its bytecode read the load-time merge of that dict over the serialized globals -- and since a kept `TENSOR_MATCH` certifies the exact Python type, dtype, shape, device and requires_grad, not values, swapping a guarded global tensor for a DIFFERENT tensor with identical metadata PASSED the check while the graph went on computing with the tensor the load happened to see: wrong numerics, nothing raised, which `test_load_compiled_function_f_globals_accepted_rebind_is_not_used` pinned as intended behaviour and the `load_compiled_function` docstring and the user guide called "a known limitation rather than a contract to rely on". The change is the gate: `_live_global_names` is now recorded whenever a supplied scope has global guards, and the load-time merge of the bound names into the bytecode's globals moves under an inner `if self._bytecode_reads_guard_scope:`, so it still runs exactly where it did (the module load path, whose bytecode does not otherwise read the scope) and nowhere else; #196909, directly above, drops that flag and runs the merge on every live-scope load. BC: a `load_compiled_function(f_globals=...)` call whose guards accept a post-load rebind now computes with the rebound value where the parent served the load-time value, nothing that raised before stops raising, a global that is not itself a kept guard's source keeps its load-time value, a graph's own store to a guarded global is taken back before each call as a deliberate trade-off, and `disable_guard_check()` does not disarm the re-read. The `load_compiled_function`, `_serve` and both `deserialize` docstrings and the user guide now promise the per-call re-read and state the cross-thread hazard it introduces (load the artifact once per thread), and the four function-path tests listed under the Test Plan each fail on the parent's `aot_compile.py`. ## Where this sits in the stack Split from `[aot_compile] Re-read a guarded global before every call instead of serving the load-time value` (#196897, directly below) so each half fits the review budget: that commit introduced `_serve`, which re-takes the globals a kept guard's own source IS out of the guard scope before every call, and armed it under the gate the load-time pick already had; this commit widens the gate so every load handed a live scope arms it, which brings in `torch.compiler.load_compiled_function(f_globals=...)`. ## The gate ```python # parent, __post_init__ if self._bytecode_reads_guard_scope and self._has_global_guards: # module load path only certified = _guard_source_globals(output_graph) self._live_global_names = tuple(sorted(certified)) live = {...} # load-time merge extra_globals = {**(extra_globals or {}), **live} # now if self._has_global_guards: # every load handed a live scope certified = _guard_source_globals(output_graph) self._live_global_names = tuple(sorted(certified)) if self._bytecode_reads_guard_scope: # the merge stays where it was live = {...} extra_globals = {**(extra_globals or {}), **live} ``` The field's comment and the `deserialize` docstring now say which parameter does what: `guard_globals` arms the per-call re-read, `bytecode_reads_guard_scope` additionally runs the load-time merge. This commit leaves the flag alone. ## The bug on the function path ```python def fn(x): return x * EPS + AOT_UNGUARDED_PARAM # under keep_tensor_guards_unsafe: TENSOR_MATCH kept on EPS, # dropped on the Parameter scope = {"EPS": torch.tensor(3.0), "AOT_UNGUARDED_PARAM": load_time_param} loaded = torch.compiler.load_compiled_function(f, f_globals=scope) loaded(x) # x * 3.0 + load_time_param scope["EPS"] = torch.tensor(5.0) # same dtype/shape/device/requires_grad: the guard passes scope["AOT_UNGUARDED_PARAM"] = torch.nn.Parameter(torch.full((3,), 9.0)) loaded(x) # parent: x * 3.0 + load_time_param (load-time value served while the guard certified 5.0) # now: x * 5.0 + load_time_param (EPS re-read; the Parameter no kept guard reaches is not) ``` `test_load_compiled_function_f_globals_accepted_rebind_is_served` (the renamed and flipped `..._is_not_used`) pins that with an `nn.Parameter` no kept guard reaches, rebound next to the `EPS` the same call does follow, as its module analogue does with `AOT_UNGUARDED_PARAM`: it captures under `keep_tensor_guards_unsafe`, which drops the `TENSOR_MATCH` on a Parameter where `keep_global_guards` keeps it (measured: under `keep_global_guards` both names are rooted and both rebinds are followed), and asserts before saving that a kept guard is rooted at `EPS` and none reaches the Parameter. ## BC A `load_compiled_function(f_globals=...)` call whose guards accept a post-load rebind now computes with the rebound value; the parent served the load-time value. Nothing that raised before stops raising, and a global that is not itself a kept guard's source keeps its load-time value exactly as before. `test_load_compiled_function_f_globals_merges_for_the_bytecode` pins the same under the default filter, where `_live_global_names` is `()` and a rebind of the scope after the load is not followed. A name `f_globals` omits still resolves to the serialized value, which the docstring goes on saying, and so does a container a kept guard reaches only through a sub-path such as `D['a']`, which `test_load_compiled_function_sub_path_global_is_not_re_read` now pins on this path next to a root-sourced global the same call does follow, after asserting, as its module analogue does, that a kept guard reaches the container and only through a sub-path, so the carve-out has something to carve out. The module load path is unchanged, since it was armed already. The four tests listed under the Test Plan pin the change; each fails on the parent's `aot_compile.py`. ## A graph that stores to its own global ```python def fn(x): global EPS y = x * EPS EPS = EPS * 2 # Dynamo replays this as STORE_GLOBAL into fn.__globals__, never into f_globals return y scope = {"EPS": torch.tensor(3.0)} loaded = torch.compiler.load_compiled_function(f, f_globals=scope) loaded(x); loaded(x) # x * 3.0 both times; scope["EPS"] untouched; fn.__globals__["EPS"] == 6.0 scope["EPS"] = torch.tensor(5.0) loaded(x) # x * 5.0: the rebind the guards accepted, not the stored 6.0 or 12.0 ``` A graph that itself rebinds a guarded global (`global W; y = x * W; W = W * 2`) is served the same way, and that is a deliberate trade-off the `_serve` docstring now states rather than a coincidence of the mechanism. Dynamo replays the store as a `STORE_GLOBAL` into the bytecode's globals, never into the scope the guards read, so the stored value is one no guard certified; the re-read takes the scope's value back before each call, so such a forward serves the scope's value on every call where eager, whose store lands in the dict its guards read, counts up. The alternative of leaving a stored name out of the re-read would serve the stored value after a rebind of the scope the guards accepted -- the check certifying one value while the graph reads another, which is the stale read this commit removes -- and writing the store back into the scope is a behaviour neither load path has. Neither writes the scope, which eager would, and that is pre-existing. `test_load_compiled_function_graph_rebind_of_a_guarded_global_is_re_read` pins the served value, that the store landed in `fn.__globals__`, that the scope is untouched, and that a rebind of the scope after the store is what the next call computes with; it fails on the parent, with the re-take made a no-op, and with stored names left out of the re-read. ## The opt-out `disable_guard_check()` does not stop the per-call re-read on this path either: the name set is recorded by the load, before the opt-out flips anything, so an opted-out artifact goes on serving whatever `f_globals` binds, a value a kept guard would have rejected included. ```python scope["EPS"] = torch.nn.Parameter(torch.tensor(5.0), requires_grad=False) loaded(x) # RuntimeError: GuardManager check failed (the kept TENSOR_MATCH refuses a Parameter) loaded.disable_guard_check() loaded(x) # x * 5.0: the opted-out call follows the rebind the check refused del scope["EPS"] loaded(x) # still x * 5.0: an unbound name is skipped, not deleted or reverted ``` `test_load_compiled_function_opted_out_rebind_is_served_unchecked` swaps in the same `nn.Parameter` the kept `TENSOR_MATCH` refuses while the check is on, watches the opted-out call follow it, then deletes the name from the scope and watches the next call serve that same `Parameter` -- neither the serialized value nor the load-time one -- because `_serve` skips a name the scope does not bind rather than deleting or reverting it. That is the opt-out being unsafe by construction, not an accident, since holding those names at their load-time values would be no more checked, only stale; the user guide's `disable_guard_check()` entry now says so for a loaded artifact of either kind, the clause on a name the scope no longer binds that tail pins included. ## Docstrings and the guide The `load_compiled_function` docstring and the user guide's `f_globals` passage now promise the per-call re-read. The docstring carries the contract: - the re-read, stated for a global that is itself the source of a kept guard rather than for every global a kept guard reads -- under the default filter a symbolic-shape guard on a global with a dynamic dim reads that global and arms `_has_global_guards`, but it is rooted at the ShapeEnv, so `_live_global_names` stays `()` and a same-shape rebind of that global is not followed (measured: a float64 rebind still computes in float32); the `f_globals` entry names that global among the ones that keep their load-time value; - the sub-path carve-out; - that a store the function makes does not carry over; - and -- in its summary, where a caller reads it before the parameter list -- that, when `f_globals` is passed, the returned callable is not safe to share between threads that rebind a guarded global concurrently, with or without the GIL, so the artifact is loaded once per thread. A loaded artifact has exactly one scope, set once at load, so the hazard is that concurrent rebind and not threads "whose scopes differ"; `_serve`'s docstring and the guide condition their sentence the same way. `AOTCompiledModel.deserialize`'s docstring carries the same sentence for the module path, which #196897 armed and whose docstring described the re-take without its consequence; the guide has no module-load passage to carry it, since the private `_aot_compile` path appears in its API reference only in the `disable_guard_check()` entry, which covers a loaded artifact of either kind. The guide keeps the reasoning the docstring points at: the re-read is not atomic with the guard check before it, so a rebind landing between the two is served unchecked, the same window an eager compiled frame has between guard evaluation and its bytecode's global reads; the write lands in the loaded artifact's own `fn.__globals__`, which every call of it shares; and a store the function makes to a guarded global is replaced by the next call's re-read. ## Review order Review the `__post_init__` gate first, then the four function-path tests, then the prose (the `_serve`, both `deserialize` and the `load_compiled_function` docstrings, and the two user-guide passages). Test Plan: ``` python test/dynamo/test_aot_compile.py ``` The new cases, and the existing case that pinned the old behaviour: ``` python test/dynamo/test_aot_compile.py -k test_load_compiled_function_f_globals_accepted_rebind_is_served python test/dynamo/test_aot_compile.py -k test_load_compiled_function_graph_rebind_of_a_guarded_global_is_re_read python test/dynamo/test_aot_compile.py -k test_load_compiled_function_opted_out_rebind_is_served_unchecked python test/dynamo/test_aot_compile.py -k test_load_compiled_function_sub_path_global_is_not_re_read ``` Whole file at this commit: `Ran 227 tests ... OK (skipped=6)`, against the parent's 224 (`unittest`'s `countTestCases()` agrees, 227 and 224). With the parent's `torch/_dynamo/aot_compile.py` checked into the tree and this test file kept, the four cases report `FAILED (failures=4)`: `graph_rebind` and `sub_path` on their `_live_global_names` probe (`The length of the sequences mismatch: 0 != 1`, the parent recording nothing for a function artifact) and the other two with `Tensor-likes are not close!`; the fifth case of that run, `test_load_compiled_function_f_globals_merges_for_the_bytecode`, passes on both. Mutations at this commit: widening `_live_global_names` to every name the scope binds fails `accepted_rebind` on its Parameter leg and `test_aot_compile_module_rebind_after_load_is_served` on its (`Tensor-likes are not close!`, 100% mismatch), `merges_for_the_bytecode` on its `_live_global_names` probe (`1 != 0`) and the function sub-path case on its (`2 != 1`); making the `_serve` re-take a no-op fails these four cases and the module-path cases of walk a chained source up to its root fails both sub-path cases (the function one on its probe, `2 != 1`, the module one on the served dtype); leaving the names the bytecode `STORE_GLOBAL`s out of the re-read fails `graph_rebind` on its second call (`Tensor-likes are not close!`, 100% mismatch); clearing `_live_global_names` in `disable_guard_check()` fails only the two opted-out cases, `test_load_compiled_function_opted_out_rebind_is_served_unchecked` and `test_aot_compile_module_opted_out_load_rebind_is_served`. The two same-metadata swap cases load with a `3.0` scope value rather than `EPS.clone()`, as `graph_rebind` already did: with the file's `1e-7` `EPS`, `x * EPS` sits inside `assertEqual`'s tolerance of zero (`assertEqual(x * EPS, zeros_like(x))` passes), so their first-call assertion held for the serialized value, the scope's and zeros alike. With the load-time merge switched off and the re-take made a no-op together, both now fail on that first call, where the `EPS.clone()` versions failed only on their rebind leg. Making `["a"]` of the sub-path fixture a `Parameter`, so `keep_tensor_guards_unsafe` keeps no guard reaching `AOT_NESTED_GLOBAL`, fails the sub-path case on its `roots` assertion (`'AOT_NESTED_GLOBAL' not found in {None, 'EPS'}`), where without that assertion it passed. Making `_serve` delete a name the scope no longer binds instead of skipping it fails only the opted-out case, on its `del` leg (`NameError: name 'EPS' is not defined`); without that leg it passed. ``` lintrunner --take RUFF,PYFMT torch/_dynamo/aot_compile.py torch/compiler/__init__.py test/dynamo/test_aot_compile.py ``` Authored with the assistance of Claude Code. > **FAQ: a graph that itself rebinds a guarded global (`global W; y = x * W; W = W > * 2`) now has that rebind discarded before every call, where previously it > accumulated and matched eager; should the names the graph `STORE_GLOBAL`s be > left out of the re-read instead?** No; the trade-off is deliberate and is now > stated in `_serve`'s docstring, the `load_compiled_function` docstring and the > guide. Measured with `keep_global_guards` and `x = arange(4.0)`: eager returns > `x*3, x*6` and leaves the module's `W == 12`; at this commit a loaded artifact > returns `x*3, x*3` with the scope's `W` still `3.0` and `fn.__globals__['W'] == > 6`; the module load path returns the same `x*3, x*3` for the same forward, so > the function path now agrees with the path #196897 armed. The reviewer's > variant -- dropping the bytecode's `STORE_GLOBAL` names from `_live_global_names` > -- reproduces the parent's `x*3, x*6` only while nobody touches the scope: after > call 1, rebinding the scope's `W` to `tensor(5.0)` (which the kept `TENSOR_MATCH` > accepts) makes the variant compute `x*6` where eager and this commit both compute > `x*5`, the guard having certified `5.0` while the graph read `6.0`. That is the > exact stale read this commit exists to remove, re-opened for every forward that > stores; the parent's agreement with eager held only because the accumulation > lived in a dict the guards never read. The eager-faithful alternative -- writing > the store back into the scope after the call -- would write graph-produced > values into the caller's dict (the module's own `__dict__` on the module path) > on every call, on both load paths, which neither has today and which this > gate-widening commit does not add. Two facts bound the cost: under the default > filter, which drops every guard whose own source is a global, > `_live_global_names` is empty and such a store accumulates in `fn.__globals__` > exactly as at the parent (`x*3, x*6` measured), so only a caller who opted into > global guards and passed `f_globals` sees the constant; and that caller's scope > is left untouched by the graph either way, since `STORE_GLOBAL` never reached > it at the parent (`same dict? False`). > `test_load_compiled_function_graph_rebind_of_a_guarded_global_is_re_read` pins > the served value, the store's landing place, the untouched scope and the > followed rebind; it fails at the parent, under a no-op re-take and under the > reviewer's variant (all `Tensor-likes are not close!`, 100% mismatch), and it > uses a `3.0` scope value because with the file's `1e-7` `EPS` a doubling sits > inside `assertEqual`'s tolerance and the test would pass on the parent. > **FAQ: the cross-thread caveat deleted in an earlier round is still missing from > all three surfaces; the atomicity note does not cover it. And later: the > `f_globals` description is ~46 lines and duplicates the guide; state the thread > constraint where a reader hits it, and confirm it under free-threaded builds.** > Both, by splitting contract from reasoning. `forward_callable` builds a fresh > `f_globals` dict per load (`convert_frame.py:1134-1151`), so the per-call write > is into the loaded artifact's own `fn.__globals__`, shared by every call of that > artifact and by nothing else; two threads serving the same loaded artifact > while either rebinds a guarded global race on it, and loading once per thread > isolates. The `load_compiled_function` docstring now > says that in its summary, before `Args:`, in one sentence, and its `f_globals` > entry is cut to the contract (re-read, carve-out, no carry-over of a store, > one sentence naming the non-atomicity and the shared write and pointing at the > guide); the guide keeps the eager-window analogy and the race in full, and > `_serve`'s docstring keeps both for the maintainer. On free-threaded builds the > note stands unchanged: it never rested on the GIL, since even with the GIL a > thread switch can land between `_serve`'s store and the graph's `LOAD_GLOBAL` > of the same name, so the possible outcomes -- either thread's value, never a > torn dict, as a single `dict` store and load are each one operation on both > builds -- are the same; no free-threaded interpreter was available here to run > it, so this is reasoning, not a measurement. > **FAQ: the module path arms the same per-call write, but only the function > load path documents the cross-thread hazard, and the guide has the same > asymmetry.** The `AOTCompiledModel.deserialize` docstring now carries the > sentence -- the write into each compiled result's own `fn.__globals__`, the > race between two threads served by one loaded model while either rebinds a > guarded global, with or without the GIL, load once per thread -- right after > the passage that describes the re-take. The guide is left alone because it has > no passage a reader of `_load_aot_compiled_module` reaches: the private > `_aot_compile` path is not in its API reference (its "Compiling a module" > example loads through `load_compiled_function`), and the one entry that names > it, `disable_guard_check()`, already speaks of "a loaded artifact that opted > out", which covers both kinds; the developer-facing prose for that path lives in > the `AOTCompiledModel` docstrings. Co-Authored-By: Claude Fable 5.1 <[email protected]> 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #197218 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897
…path, drop bytecode_reads_guard_scope (#196909) **Summary.** `AOTCompiledFunction` carried a `_bytecode_reads_guard_scope` flag, a matching `deserialize(bytecode_reads_guard_scope=...)` parameter with its own docstring paragraph, and a block in `__post_init__` that, when the flag was set, copied the certified globals out of the supplied scope into the dict `forward_callable` builds for the bytecode, and only `AOTCompiledModel.deserialize` passed `True`. That merge is not redundant with `_serve`'s per-call re-take: `forward_callable` runs `_check_external_refs` at load, and a certified global the generated bytecode `LOAD_GLOBAL`s but the graph never lifted (the side-effect replay of a mutated global container, or the reconstruct of a returned global) is in `external_refs` and in no serialized scope, so without the merge a `guard_globals`-only load raises `Missing required external references`. What goes is the flag: the merge now runs whenever a live scope arms `_live_global_names`, and the field, the parameter, its docstring paragraph and the kwarg at the module load site are deleted. Against the parent this changes one path -- `AOTCompiledFunction.deserialize(data, guard_globals=G)` with no `f_globals` now loads such an artifact with `G`'s value bound where it failed before -- and one detail, a certified name both `f_globals` and `guard_globals` bind is taken from `guard_globals` from the load onwards rather than from the first call, observable only in `fn.__globals__` between load and first call; the module path, the public loader and the no-scope path are unchanged. All of the deleted surface came from #196818 of this stack, landed on main as 82c1f1e and in no release tag, and nothing outside `AOTCompiledModel.deserialize` ever passed the parameter, so deleting it breaks no released or in-tree caller. ## What is deleted ```python # parent class AOTCompiledFunction: _bytecode_reads_guard_scope: bool = False # deleted def __post_init__(self): ... certified = _guard_source_globals(output_graph) self._live_global_names = tuple(sorted(certified)) if self._bytecode_reads_guard_scope: # gate deleted; the merge below stays live = {} for name in certified: value = guard_scope.get(name, _UNBOUND) if value is not _UNBOUND: live[name] = value extra_globals = {**(extra_globals or {}), **live} @classmethod def deserialize(cls, data, f_globals=None, ..., *, guard_globals=None, bytecode_reads_guard_scope=False, # parameter deleted forward_not_resolved_reason=None): ... # now certified = _guard_source_globals(output_graph) self._live_global_names = tuple(sorted(certified)) live = {n: v for n in certified if (v := guard_scope.get(n, _UNBOUND)) is not _UNBOUND} extra_globals = {**(extra_globals or {}), **live} ``` `AOTCompiledModel.deserialize` drops the `bytecode_reads_guard_scope=True` kwarg at its `AOTCompiledFunction.deserialize` call, and the `deserialize` docstring paragraph that described the flag is folded into the `guard_globals` paragraph. ## Why the merge stays The merge is not redundant with `_serve`'s per-call re-take, even though both write the same names from the same dict: `forward_callable` runs `_check_external_refs` over `{**import_sources, **used_globals, **extra_globals}` at load, and `get_runtime_env` fills `used_globals` only from the graph inputs' global roots plus the builtins the bytecode reads. ```python AOT_GLOBAL_LOG: list[int] = [] def mutates_global_list(x): # side-effect replay: bytecode LOAD_GLOBALs AOT_GLOBAL_LOG AOT_GLOBAL_LOG.append(x.shape[0]) return x + 1 def returns_global_list(x): # reconstruct of a returned global: same return x + 1, AOT_GLOBAL_LOG # under keep_global_guards, after aot_compile: "AOT_GLOBAL_LOG" in runtime_env.external_refs # True "AOT_GLOBAL_LOG" in runtime_env.used_globals # False: the graph never lifted it "AOT_GLOBAL_LOG" in runtime_env.import_sources # False ``` A global the generated bytecode `LOAD_GLOBAL`s but the graph never lifted -- the side-effect replay of a mutated global container or object, or the reconstruct of a returned global -- is in `external_refs` and in no serialized scope, while a `guard_filter_fn` that keeps global guards leaves a serializable `TYPE_MATCH` or `SEQUENCE_LENGTH` rooted at its bare `GlobalSource`, so it is certified. On the module load path, which passes no `f_globals`, the merge was the only thing binding that name before the check; without it the load raises `Missing required external references`. So `_guard_source_globals(output_graph) <= used_globals | import_sources` does not hold, and the merge stays. ## What changes, per load path Against the parent: - **`AOTCompiledModel.deserialize` (`guard_globals` only).** The merge already ran there, so nothing changes. The module-shape test below passes on the parent as well; what it pins is that the merge cannot be deleted. - **`AOTCompiledFunction.deserialize(data, guard_globals=G)` with no `f_globals`.** An artifact whose bytecode reads an unlifted certified global failed to load with `Missing required external references`; it now loads with `G`'s value bound. For a certified global the serialized scope does carry, the parent bound the serialized value at load and took `G`'s only from the first call's `_serve` re-take; `G`'s is now bound from the load, so `fn.__globals__` agrees with the scope before the first call too. The function-shape test pins the first half and fails on the parent. ```python loaded = AOTCompiledFunction.deserialize(data, guard_globals=globals()) # parent: RuntimeError: Missing required external references: ['AOT_GLOBAL_LOG'] # now: loads; loaded.fn.__globals__["AOT_GLOBAL_LOG"] is AOT_GLOBAL_LOG ``` - **`deserialize(data, f_globals=X, guard_globals=G)` with two distinct dicts.** A certified name both bind is taken from `G` from the load onwards, where the parent bound `X`'s at load and `G`'s from the first call. Only `fn.__globals__` between load and first call can observe the difference; the call results are identical. The `deserialize` docstring now states this precedence. - **`torch.compiler.load_compiled_function(f, f_globals=X)`.** It passes `X` as both `f_globals` and `guard_globals`, so the set of names bound at load and their values are the same as before; the public loader is unchanged. - **No live scope (`guard_globals=None`, any `f_globals`).** Unchanged; the bind sits inside the `guard_scope is not None` branch. ## The `.get` form The loop body in `_serve` already takes the single `scope.get(name, _UNBOUND)` form: the commit below adopted it so a caller's `__missing__` hook is never asked to fabricate a value, and so a `del scope[name]` racing the read from another thread cannot raise `KeyError` out of a call whose guards already passed; the name is skipped rather than deleted, exactly as the docstring says. The load-time bind keeps that form for the same reason: it now runs on every live-scope load, including one against a live module dict, and an `in`-then-subscript two-step could raise `KeyError` out of `deserialize`. Neither touches the guard-check-to-re-read window, which stays non-atomic as `_serve`'s docstring says. ## Tests `test_aot_compile_module_load_binds_a_certified_global_the_graph_never_lifted` and `test_aot_compile_function_load_binds_a_certified_global_the_graph_never_lifted`, each parametrized over `mutates` and `returns` (a shape that mutates a global list and one that returns it), both under `keep_global_guards` -- four cases. Each asserts the name is in `external_refs` and in neither `used_globals` nor `import_sources`, that the load arms `_live_global_names` and binds the live list into `fn.__globals__`, and that the call mutates or returns that same list. The module-shape test loads through `_load_aot_compiled_module`; the function-shape test saves with `save_compiled_function` and loads with `AOTCompiledFunction.deserialize(data, guard_globals=globals())`, no `f_globals`. Test Plan: Two tests, each parametrized over a shape that mutates a global list and one that returns it, both under keep_global_guards -- four cases. Each asserts the name is in external_refs and in neither used_globals nor import_sources, that the load arms `_live_global_names` and binds the live list into fn.__globals__, and that the call mutates or returns that same list. The module-shape test loads through `_load_aot_compiled_module`; the function-shape test saves with `save_compiled_function` and loads with `AOTCompiledFunction.deserialize(data, guard_globals=globals())`, no `f_globals`. With the parent's `torch/_dynamo/aot_compile.py` checked into the tree and this test file kept, the four cases give `FAILED (errors=2)`: both function-shape cases error with `RuntimeError: Missing required external references: ['AOT_GLOBAL_LOG']` and both module-shape cases pass. With the `extra_globals = {**(extra_globals or {}), **live}` line deleted from this commit's file, all four fail at load with that same RuntimeError. ``` python test/dynamo/test_aot_compile.py -k binds_a_certified_global_the_graph_never_lifted python test/dynamo/test_aot_compile.py lintrunner --take RUFF,PYFMT -- torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py ``` The four cases report `Ran 4 tests ... OK`; the full file `Ran 242 tests ... OK (skipped=6)` against the parent's `Ran 238 tests ... OK (skipped=6)`; lint `ok No lint issues.` Authored with an AI assistant (Claude). Co-Authored-By: Claude Fable 5.1 <[email protected]> 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #196909 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218
#196826) **Problem.** A guard tree can raise instead of answering (a `DICT_NOT_CONTAINS` leaf whose dict key's `__eq__` raises surfaces as `SystemError`), and one raising tree killed the whole `AOTCompiledModel` call even when another result matched, while a raise inside the no-match report replaced the report with an unrelated traceback. **Fix.** Treat a raising tree as no answer: record it per result, keep dispatching, veto the opted-out last resort, re-raise interrupts hidden behind `SystemError`, and quote the raise as one line of the report, which is raised as `RuntimeError(report) from <first raise>`. **Summary.** A guard tree does not only return False -- it can raise, out of C++ and through pybind, on a value it never managed to compare: a module branching on `"foo" not in d` gets a `DICT_NOT_CONTAINS` guard whose C++ leaf runs `PyDict_Contains`, a colliding key whose `__eq__` raises leaves the exception set, the leaf returns normally anyway because `guards.cpp:2475` collapses its result through C `&&` (never the -1 the following check looks for), and CPython reports the still-set exception as `SystemError` at the boundary of the guard tree. Both stages of module dispatch handled that badly: in the dispatch passes the raise propagated out of `__call__`, so one artifact's raise killed the call outright even when another result's guards would have matched, and in the report an exception from `check_verbose` replaced the whole report, hiding every other input's reason behind an unrelated traceback. This commit treats a raising tree as no answer at all -- weaker than a match, and stronger than a plain non-match, since a non-match lets an opted-out result answer and a raise must not -- records it per index in `raised` and `unanswered`, re-raises a `KeyboardInterrupt` or `SystemExit` found on an unbroken chain of `SystemError` causes instead of reading it as an answer, and lets the report quote the record as one line like any other entry, so the report survives a raising tree, names the raiser, and still carries the reason from every entry that can explain itself. Against the parent four things change for a caller: a raise from one result no longer ends the call when another result's guards match, a result whose tree raised in the scan and accepted on the second pass is served on that accept, a no-match with some raising tree now surfaces as `RuntimeError(report) from <first raise>` rather than the tree's own `SystemError`, and an `AOTCompiledModel` holding no results ends in the report instead of `IndexError`. The single-result serving path keeps the parent's inline shape on purpose (measured at +0.33 to +0.36us over the parent's 4.6-4.7us dispatch overhead, against +0.77 to +0.88us for routing it through the closure), the opted-out last resort is vetoed by a raise from any result whose guards someone asked to check, and the two pre-existing C++ gaps (`LAMBDA_GUARD` clearing whatever its lambda raised, and the dead `result == -1` branches in `DICT_CONTAINS` and `SET_CONTAINS`) are declared in the class docstring rather than fixed by this Python-only stack. ## How a guard tree raises ```python class DictBranchModule(torch.nn.Module): def forward(self, x, d): if d is None: return x * 5 if "foo" not in d: # Dynamo installs a DICT_NOT_CONTAINS guard on d return x * 2 return x * 3 class RaisesOnCompare: # hashes into "foo"'s slot, so PyDict_Contains(d, "foo") compares against it def __init__(self, message="boom from __eq__"): self.message = message def __hash__(self): return hash("foo") def __eq__(self, other): raise ValueError(self.message) loaded(x, {RaisesOnCompare(): 1}) # the leaf leaves ValueError set and returns 0 or 1; CPython raises at the pybind boundary: # SystemError: <built-in method check of ...> returned a result with an exception set # __cause__: ValueError: boom from __eq__ ``` The `SET_CONTAINS` leaf has the identical shape at `guards.cpp:2505-2506`, so a `SET_NOT_CONTAINS` guard called with a set holding such a key produces the same report. Neither guard type is in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES`, so both survive serialization and a loaded artifact really can raise this way. A guarded global the loading process lacks is not such a case: `DictGetItemGuardAccessor` (`guards.cpp:5765-5781`) clears the error and returns false, so it arrives as the ordinary non-matching reason `KeyError on G['NAME']` and keeps its own advice. ## Recording a raise in dispatch A raise is recorded in two places with one shape: the inline check of the first result and `accepts()`, which the scan of the later results and the second pass go through. ```python raised: dict[int, Exception] = {} # the LAST exception per index, in first-raise order unanswered: set[int] = set() # indices whose LAST evaluation RAISED; a subset of raised's keys bound: dict[int, dict[str, object]] = {} def accepts(i, result): f_locals = bound.get(i) if f_locals is None: f_locals = bound[0] if shared else result.prepare_f_locals(self.model, *args, **kwargs) bound[i] = f_locals manager = result._live_guard_manager() # outside the try, like prepare_f_locals try: answer = manager.check(f_locals) # the try covers check() alone except Exception as e: if not _meant_an_exception(e): # an interrupt is not dispatch's to swallow raise raised[i] = e unanswered.add(i) return False unanswered.discard(i) return answer ``` `prepare_f_locals` and `_live_guard_manager()` stay outside each `try`, so a call the signature cannot bind still surfaces as the `TypeError` a plain module call would raise rather than as a tree that did not match, and the `try` covers `check()` alone -- not the serve, so a raise out of the graph is its own, and not the manager lookup, whose only raise is a pyrefly-narrowing assertion no constructed result reaches. The per-result bindings become a `dict[int, ...]` filled on first use, so the second pass and the report reuse the scan's binding of each result, where the parent's list was filled by the scan alone; the parent's `shared = len(results) > 1 and self._binds_alike(results)` stays as it was, below the inline check, so a call the first result serves never asks and `accepts()` only reads it (measured with a counting patch over ten dispatch shapes, from no result to three: `_binds_alike` runs once when the first of several results refused, as it did at the parent, and now also once when it raised, a shape the parent did not survive -- there a raise out of the first result's `check()` left `__call__` from the `if first._live_guard_manager().check(f_locals):` line (`80ec95a81f5:torch/_dynamo/aot_compile.py:1674`) and never reached the `shared` line eleven lines below it, so that call was never made). ### Interrupts are never an answer Each handler catches `Exception` and re-raises when what the tree meant to raise, `_meant_an_exception(e)`, is not one: a `KeyboardInterrupt` or `SystemExit` out of a guard tree is not an answer about this call and is not dispatch's to swallow. `except Exception` alone does not keep that promise, because the pybind boundary wraps WHATEVER a leaf left set into `SystemError` without looking at its type, so an interrupt raised inside a key's `__eq__` under `DICT_NOT_CONTAINS` arrives as `SystemError(__cause__=KeyboardInterrupt)`, which `except Exception` catches; an earlier revision of this commit read that as no answer and served the next matching result over a Ctrl-C. The interrupt now propagates as itself from a Python-level guard manager, or as the `SystemError` the boundary wrapped it in, and never as an answer; the test the handlers share checks each of the three on the real leaf. ```python def _unwrapped_raise(e): reason = e seen = {id(reason)} while isinstance(reason, SystemError) and reason.__cause__ is not None: reason = reason.__cause__ if id(reason) in seen: # a user-built chain can close on itself break seen.add(id(reason)) return type(reason).__name__, reason def _meant_an_exception(e): return isinstance(_unwrapped_raise(e)[1], Exception) ``` `_unwrapped_raise` follows an unbroken chain of `SystemError` causes rather than one hop, so an interrupt two hops down is not read as an answer either: a leaf's own `raise SystemError(...) from KeyboardInterrupt(...)` is wrapped again at the boundary, and one hop stopped on the inner `SystemError`, an ordinary `Exception` (`test_aot_compile_module_doubly_wrapped_interrupt_propagates`, on the real leaf). The walk stops at the first link that is not itself a `SystemError`, and so at an interrupt behind an ordinary exception: a key whose `__eq__` runs `raise ValueError("mid") from KeyboardInterrupt("ctrl-c")` ends the call in the report, with `[0] <guard check raised ValueError: mid (through the guard tree's pybind boundary)>` on its entry line and the chain `RuntimeError` -> `SystemError` -> `ValueError` -> `KeyboardInterrupt` (`test_aot_compile_module_raise_from_an_interrupt_reaches_the_report`, through the real `DICT_NOT_CONTAINS` leaf, no patching). Stopping there is the point: the `ValueError` is the answer the tree's own code chose to raise, and reading past it would report an interrupt that code had already converted. An interrupt the tree's own code caught and re-raised as something else is not reached either -- it sits on `__context__`, which the unwrap does not read -- so the docstring's promise is scoped to an unbroken chain of `SystemError` causes rather than to every interrupt. The walk is bounded by the links it has already passed rather than by reaching an end, because the chain it reads is user-built and can close on itself: three lines of `__eq__` make one `SystemError` the cause of its own cause, the boundary wraps that like any other raise, and `while isinstance(reason, SystemError) and reason.__cause__ is not None` then never returns -- inside dispatch, before any record exists, so nothing downstream can recover. It remembers each link's `id()` the way `TracebackException`'s own walk does, stops at the first repeat and quotes that link, which turns a cycle into an ordinary report line (`test_aot_compile_module_raise_chained_in_a_cycle_reaches_the_report`, on the real `DICT_NOT_CONTAINS` leaf and under a `SIGALRM` because the failure it pins is a hang and not a wrong answer: unbounded, the call spins past a 60s alarm where the parent, which read no chain at all, let the `SystemError` out in microseconds). Ids suffice for the chain CPython builds, whose `__cause__` is a strong reference: every link stays alive, held by the chain from the exception the handler caught, so none is freed and its id reused under the set. A subclass shadowing `__cause__` with a property that returns a fresh object escapes that, and the walk still ends, at the first id it sees twice. The bound costs the interrupt promise nothing: everything past a repeated link is a link already walked, so no interrupt an unbounded walk would have reached is missed. The `isinstance` runs only inside the `except`, so the accept path measured below pays nothing for it. The docstring's promise is about an interrupt that REACHES dispatch, and one leaf keeps it from arriving: `LAMBDA_GUARD::check_nopybind` (`guards.cpp:1918-1928`) clears whatever its lambda raised, of whatever type, and answers false, so an interrupt raised under a kept lambda guard is read as an ordinary mismatch, and `check_verbose_nopybind` (`:1930-1936`) puts `get_exception_message()`, the `PyObject_Str` of it (`:1382`), into the verbose parts, so a report quotes the interrupt's text as the guard's. Measured on a `RootGuardManager` holding one `add_lambda_guard` whose lambda raises `KeyboardInterrupt('inside a lambda guard')`: `check()` returns False with nothing set and `check_verbose()` returns `(False, ['inside a lambda guard'])`. `LAMBDA_GUARD` is a leaf of every tree here -- the leaves of an AOT-compiled `ScaleModule`, walked from its root, are `DEFAULT_DEVICE`, `DIMENSION_DYNAMIC_MARKING_GUARD`, `GLOBAL_STATE`, `LAMBDA_GUARD`, `TENSOR_MATCH` and `TORCH_FUNCTION_MODE_STACK` with `dynamic` off and on alike -- so this is a second pre-existing C++ gap beside the dead `result == -1` branch below, and no Python-side fix reaches it: the leaf clears the error before dispatch is given anything to inspect. The class docstring declares it rather than promising more than the code delivers. ### The two records A raise is remembered as two things, each read by a different line of the report. `raised` keeps the LAST exception per index, in first-raise order: the report is chained from its first value, and an index that raises in both passes is quoted for the second raise, since the second pass runs more of the tree than the first need have (`check()` can reject from the dict-tag fast path without running it). `unanswered` holds the indices whose LAST evaluation RAISED, a subset of `raised`'s keys: those are the only entries with nothing else to quote, so the report quotes `raised[i]` for the enabled ones and re-evaluates nothing, while an entry that raised in the scan and then rejected on the second pass has that rejection quoted like any other, its raise surviving in the chain when it was recorded first of all, and in the footer's fix-or-drop line when it was recorded first of the inputs nobody opted out. When it is neither, this report carries that raise nowhere. Measured on the `DictBranchModule` fixture with `ds=({}, None)`, [0] raising through the leaf in both passes and [1]'s `check` patched to raise `second boom` in the scan and reject cleanly on the second pass: ``` No AOT compiled graph matched this call. Tried 2 compiled input(s): [0] <guard check raised ValueError: boom from __eq__ (through the guard tree's pybind boundary)> [1] L['d'] is None [0]'s guard check raised while checking this call; fix or drop that artifact. ... ``` `second boom` is on no line, in no footer and nowhere on the `__cause__` chain. Enumerating every raiser in the footer here, or hanging a raise line off a raise-then-rejection, is not the fix: #197050 and #197257 above append a caveat to the advice that names exactly the trees whose rejection followed their own raise and quotes each raise from the same `raised` record, which is the entry the report is missing, and duplicating it here would leave two spellings of one caveat. Both records and the three invariants (subset, first-raise order, last exception) are stated in `_no_match_report`'s docstring, since its body relies on all three. Every exit that serves a graph clears both records first: nothing on that path reads them, and the stored exception keeps its traceback, which keeps this frame and so this call's `args` and `kwargs` alive until a cyclic collection runs -- so an artifact whose leaf raises on every call would hold a growing set of its own inputs, which is the steady state this commit is built for. That lifetime argument is `raised`'s alone. `unanswered` is a `set[int]`, holds no traceback and frees nothing, and dropping its three `clear()` calls leaves the whole file green (measured); they are kept, and the comment now says why, for the subset invariant `_no_match_report`'s docstring states -- clearing one record and not the other would leave an index unanswered with no exception recorded for it, a state no reader of either record should have to consider. Measured with `gc` off at each of the three exits, the key of the input dict is still alive after the call returned without that exit's `raised.clear()` and dies at the return with it (`test_aot_compile_module_serving_over_a_raise_frees_this_call_s_inputs`, one `subTest` per exit); the two `clear()` calls cost 29ns on empty containers. The inline serve of the first result skips them: the only check it ran is its own, and that one accepted. ## What changes for a caller Against the parent, four things change. **(a) A raise from one result no longer ends the call when another result's guards match:** the match is served (`test_aot_compile_module_serves_a_later_match_over_a_raising_leaf`: [0] raises through the leaf, [1] is patched to accept, and the call returns `x * 5` where the parent let the `SystemError` out and eager raises the `ValueError`). Nothing surfaces the raise on that path at this commit: no report is built where a graph is served, so the serve is deliberately silent until #197391, two commits above, adds the warning and its per-model dedup, together with the tests that read it. The class docstring says so in as many words, so a reader of this commit alone does not take the silence for an oversight. **(b) A result whose tree raised in the scan and accepted on the second pass is served on that accept.** Usually that accept is the tree's own answer about this call; it can also stand on the relational residue a C++ throw leaves (below). `SYMBOLIC_SHAPE_GUARD::check_nopybind` (`guards.cpp:2816-2841`) writes each shape arg into its slot by index but gates the evaluation on a running `_args_seen` counter, which the leaf itself clears on a complete evaluation (`:2836-2837`) and `reset_state()` (`:2887-2888`) otherwise, so a throw, skipping both, after `k` of its `n` args were visited leaves the count at `k`, and the next evaluation of that tree runs the shape function after `n - k` of this call's values over `k` stale slots, where it can answer true, resets, and then answers true for this call's remaining `k` args: an accept over shape args it never checked, which the second pass serves like any other. Reaching it needs `torch._dynamo.config.enable_cpp_symbolic_shape_guards`, which installs that leaf and is off by default (`config.py:560`, gated at `guards.py:3549`), and a raise that does not recur on the second pass (a key whose `__eq__` raises once, a transient `TORCH_CHECK`). The serve is kept anyway: dispatch cannot tell that accept from a real one, vetoing it would not contain the residue, since the evaluation that runs on it need not be in the same call at all, and the veto's comment states the residue in both directions. The second pass also re-runs a tree that raised in the scan, at whatever that raise cost -- the user `__eq__`, the boundary's `SystemError`, a second `TORCH_CHECK` -- and its comment prices that beside the ~1us re-run of a tree that genuinely failed. **(c) When nothing matches and some checked tree raised, the caller no longer sees the tree's own exception.** ```python loaded(x, {RaisesOnCompare(): 1}) # parent: SystemError (__cause__: ValueError from __eq__) escapes __call__ # now: RuntimeError(report) from <first raise> # .__cause__ -> the SystemError # .__cause__.__cause__ -> the ValueError from __eq__ ``` Measured on `DictBranchModule` with a colliding key at the parent: `__call__` lets the `SystemError` out, with the `ValueError` from `__eq__` as its `__cause__`. Now a caller catching `RuntimeError` (a `TORCH_CHECK` leaf) catches the report instead, one catching `SystemError` no longer catches a boundary wrap whose cause is an `Exception` -- a wrap around a `KeyboardInterrupt` or `SystemExit` still reaches it as itself, which `test_aot_compile_module_wrapped_interrupt_out_of_a_guard_tree_propagates` pins -- and either way the tree's exception is one hop down the chain. That is a behaviour change for anyone who wrote `except SystemError` around a module call after seeing the parent let one out, and `test_aot_compile_module_report_replaces_the_systemerror_a_caller_caught` pins it as such: an `except SystemError` clause ahead of an `except RuntimeError` one catches the report, whose `__cause__` is the `SystemError` and whose `__cause__.__cause__` is the `ValueError` from `__eq__`. The chain carries the last raise of the input recorded first, `next(iter(raised.values()))` over a record that overwrites per index, not the raiser the advice names: they differ when an opted-out result raised first, whose report line quotes no exception text, so the chain is the only place its raise survives. Neither is the lowest index that raised, since an input that raises for the first time only on the second pass is recorded after one that raised in the scan (`test_no_match_message_names_the_first_raise_recorded`: [0] rejects the dict inline and raises `zero boom` on the second pass, [1] raises through the leaf in the scan, and both the footer and the chain are [1]'s; building the raiser over `sorted(raised)` fails that test alone, on `"[1]'s guard check raised while checking this call" not found`). **(d) An `AOTCompiledModel` holding no results** -- `aot_compile_module` refuses an empty list, but the constructor and `deserialize()` take one -- raised `IndexError: tuple index out of range` at the parent's `results[0]`. Both passes and the last resort are now no-ops over nothing and the call ends in the report, `No AOT compiled graph matched this call. Tried 0 compiled input(s):` followed by the advice to add a `ModelInput`, which is the one advice that fits it. Reported rather than refused with a fresh error: the report already says what is wrong and what to do, and the class docstring now says so in place of "an empty one is the caller's error". The tests-only commit above pins it; nothing here reaches it. ## The single-result hot path The path a single-result model serves on is kept in the parent's shape on purpose, and what it still pays is measured. With `_serve` stubbed out and `__call__` variants exec'd into the module from their sources in one process (Python 3.12, 300k calls x 5 rounds, alternating): | variant | cost over the parent's 4.6-4.7us dispatch overhead | | --- | --- | | first result routed through `accepts()` like the others (an earlier revision) | +0.77 to +0.88us | | of which: building the closure and calling through its frame | ~0.45us | | of which: eight cell variables (every inline read a `LOAD_DEREF`, one `MAKE_CELL` each in the prologue) | ~0.2us | | of which: three empty records | ~0.13us | | `results[0]` checked inline (this commit) | +0.33 to +0.36us | | state through closure defaults, `shared` in a one-element list, records allocated after the inline check falls through (not taken) | within 0.05us | `__call__` now makes seven cells, exactly `accepts()`'s free variables: `results` left them when `shared` went back to the parent's eager line, and the eighth was `enabled`, cellified by the veto's generator expression for a comprehension no served call ever runs. Written `any(map(enabled.__getitem__, raised))` the veto needs no cell, and `AOTCompiledModel.__call__.__code__.co_cellvars` is `('self', 'args', 'kwargs', 'bound', 'raised', 'shared', 'unanswered')` with seven `MAKE_CELL` ops, where the parent's `__call__` had none; the numbers here were measured with eight, and one cell fewer costs no more. Checking `results[0]` inline, so a served call builds no closure and fills no record, leaves the cells and the allocations; the variant that removed both is not taken: it buys 0.3us with a shape the file has nowhere else. The residual is stated in the hot-path comment beside the `_serve` frame it already weighs. ## The opted-out last resort ```python enabled = [result._guard_check_enabled for result in results] # read once, after both passes if not any(map(enabled.__getitem__, raised)): # veto: a raise from a CHECKED result for i, result in enumerate(results): if not enabled[i]: raised.clear(); unanswered.clear() return result._serve(self.model, *args, **kwargs) report = self._no_match_report(results, raised=raised, unanswered=unanswered, bound=bound, enabled=enabled) if raised: raise RuntimeError(report) from next(iter(raised.values())) raise RuntimeError(report) # not `from None`: an ordinary no-match must not suppress a handled exception ``` `disable_guard_check()` keeps meaning what it means on the function path. The last-resort loop that serves an opted-out result is held back only by a raise from a result whose guards someone did ask to check: such a raise rejected nothing, so serving an unguarded graph on the strength of it would answer a call whose guards never passed. It stays held back when a later pass does get an answer out of that tree, because dispatch cannot tell that rejection from one standing on relational residue: a C++ throw skips the `_reset_relational_guard_state()` call the normal exits of `RootGuardManager::check_nopybind_template` run, so a tree holding a `NO_TENSOR_ALIASING`, `OBJECT_ALIASING`, `STORAGE_OVERLAPPING` or `SYMBOLIC_SHAPE_GUARD` can reject the re-check on the residue of the throwing evaluation rather than on this call (measured on `lambda a, b, c: a + b + c` called with a strided nested tensor in `c`: `check()` on the SAME call alternates between throwing and returning False), or, with `SYMBOLIC_SHAPE_GUARD`'s counter, accept it, as (b) says. That residue cannot be cleared from Python -- `RelationalGuard::reset_state` has no binding -- so it is documented in the veto's comment rather than fixed. A raise from the opted-out result itself holds back nothing (`test_aot_compile_module_raise_from_an_opted_out_result_withholds_nothing`: [0] opted out, its tree raising through the leaf in both passes since `check()` ignores the flag, [1] rejecting the dict, and the call serves [0]'s `x * 2`), and the report decides the opt-out line before the raise so that entry is described once, as the opt-out it is. The veto is the only way `_no_match_report` runs with an opted-out result present, and the report says what happened to it: quoting the guards nobody asked about would name the wrong thing, and no `ModelInput` covers it, so it reads `[1] <opted out of guard checks; withheld because [0]'s guard check raised>` and the report ends with the one instruction that would let it serve again, `[0]'s raise, not a guard failure, is what withheld the opted-out input(s) above; fix or drop that artifact.` Whether any opt-out was withheld is `not all(enabled)`, read once beside `raiser`; with no opt-out present the same advice reads `[k]'s guard check raised while checking this call; fix or drop that artifact.`, since a tree that raised has to be fixed whether or not its raise also cost the caller a graph. `raised` is the dispatch record alone, so a tree that answered in dispatch and raised only while EXPLAINING itself gets no fix-or-drop line: its guard check did answer, and the report already shows that raise as its entry line. `__call__` reads `_guard_check_enabled` once per result, into `enabled`, after both passes and before the veto, and hands the list to `_no_match_report` as a keyword-only argument: the veto, the last-resort loop, the raiser the report names, its opt-out branch and its footer's gate all read that one list. `disable_guard_check()` is a plain attribute store any thread can make mid-call, and `check_verbose` runs user code that could make it from inside the report's loop; a flag that flipped between two reads would otherwise let the report describe an opt-out the veto never saw, or interpolate `None` for `raiser` into the withheld line. The list is built only after both passes fail, so the served path pays nothing for it. ## The raise line ```python def _quoted(reason): try: return str(reason) # user code: a __str__ that raises must not take the report with it except Exception as exc: return f"<str() raised {type(exc).__name__}>" def _raised_line(index, e): kind, reason = _unwrapped_raise(e) boundary = "" if reason is e else " (through the guard tree's pybind boundary)" line = f" [{index}] <guard check raised {kind}: {_quoted(reason)}{boundary}>" return " ".join(line.splitlines()) # the report is read back with splitlines() # [0] <guard check raised ValueError: boom from __eq__ (through the guard tree's pybind boundary)> # [0] <guard check raised RuntimeError: __instancecheck__ raised> a raise with nothing chained # [0] <guard check raised Boom: <str() raised ValueError>> a __str__ that raised ``` The raise line reports the exception the `SystemError` was chained from and names the boundary once. The `SystemError`'s own `str()` is the bound method's repr and says nothing about what raised, and only one raise per call can be chained onto the `RuntimeError`, so the line has to carry it. `_unwrapped_raise` reads `__cause__`, which is what `_PyErr_FormatFromCause` sets, and not `__context__`, which the same call also sets but which PEP 3134 sets as well for ANY exception raised while another was being handled, so it would quote the exception the CALLER was handling for a `SystemError` that reached the tree some other way. The unwrap is conditional on the `SystemError`: a raise of any other type is quoted as itself even when it carries a `__cause__`, since an explicit `raise ... from ...` inside a Python-level guard manager is the tree's own chain, not the boundary's, and it follows that chain until a link repeats rather than taking one hop, since a leaf's own `raise SystemError(...) from <exc>` is wrapped again at the boundary and one hop would report the inner `SystemError` -- until a repeat and not to an end, since a chain a key builds can have no end. A raise that arrives with nothing chained -- a `TORCH_CHECK` inside the tree, which pybind translates at that same boundary into a plain `RuntimeError` -- gets the same line without the boundary clause: the clause explains why the line quotes a chained exception rather than the one the tree raised, so with nothing chained there is nothing to explain. The exception object is the tree's, user code down to its `__str__`, so the text is produced by `_quoted`, which turns a `__str__` that raises into `<str() raised TypeError>` instead of letting it take the report with it -- the failure mode this commit exists to remove, one layer down; the same file already guards `_resolve_guard_scope` this way. `_quoted` catches every `Exception`, one wrapping an interrupt included, and unwraps nothing: a `KeyboardInterrupt` or `SystemExit` the `__str__` raises itself propagates out of the report as itself rather than being folded into a `<str() raised KeyboardInterrupt>` line on a report that then serves as the call's answer, while a `__str__` that runs `raise SystemError(...) from KeyboardInterrupt(...)` is quoted `<str() raised SystemError>` (measured), the interrupt behind it left in that line -- one line of a report that already exists, not this call's answer. `test_no_match_message_quotes_a_raise_whose_str_raises` pins both: the real manager's `check` patched to raise `Boom(ValueError(...))`, whose `__str__` raises what it was given, gets the line `[0] <guard check raised Boom: <str() raised ValueError>>` with that very `Boom` chained (`assertIs`), and the same patch given an interrupt lets that very object out, `assertIs`, one `subTest` per interrupt type. `Boom` derives from `Exception`, not `RuntimeError`, so a `Boom` that escapes the call fails the test's `assertRaises(RuntimeError)` itself rather than the read of the report. `_quoted` stays a function of its own though `_raised_line` is its only caller here: inlined, its `try`/`except` cannot sit inside the f-string that builds the line, and the commit above that logs a served-over raise gives it a second caller. The line is then collapsed onto one line, because the report is read back with `splitlines()` and `str(reason)` is user text. ## The report's own re-check The report's own re-check is the third handler: `check_verbose` runs paths `check()` did not (the repr of a user object, for one), so one entry raising there gets a raise line of its own and must not cost the others theirs. That handler's pin, the report line without the boundary clause, the `__cause__` reading, the unwrap condition, the last-raise-wins record, the chain's first-raiser reading, the interrupt leaving `accepts()` as itself, the empty-results report and the serve in (b) are pinned by the tests-only commit directly above, which carries the stub-guard-manager tests -- one raising stub per dispatch semantics that does not depend on how a tree raised -- so that a fix to the dead `result == -1` leaf, which would turn the `DictBranchModule` tests here into ordinary mismatches (`PyErr_Clear()` looks at no type, so it would clear the interrupt as it clears the `ValueError`), costs those pins nothing; its stub pin of the serve in (a) repeats, without the leaf, the real-leaf pin here, and its `_quoted` pin repeats this commit's patched-`check` pin on a stub tree. This commit's other tests reach the raise through the real leaf on purpose and `RaisesOnCompare`'s comment says so of both keys. One report line lost a count it can no longer take. Before a raise was tolerated, an entry the report's re-check ACCEPTS had necessarily been rejected by both dispatch passes and the line said so; now the first pass can raise and the second reject, reaching the same line with one rejection on record. ```python # parent "<guards rejected this call twice and then accepted it here: a guard that does not answer consistently, or guarded state that changed between those evaluations>" # now "<guards did not accept this call in dispatch and accepted it here: a guard that does not answer consistently, or guarded state that changed between those evaluations>" ``` That is true of two rejections and of a raise followed by a rejection alike. The raise it does not mention is on the report's `from` chain only when it was the raise recorded first, and in the footer only when it was the first recorded of the inputs nobody opted out; when it is neither, nothing here carries it, and #197050 and #197257 above are what name that tree and quote its raise. `test_no_match_message_when_a_guard_answers_inconsistently`, the two-rejection case, has its assertion moved to the new line here through `_ACCEPTED_IN_THE_REPORT`, which #196823 below shares; the raise-then-reject case is the dispatch-record test in the commit above. ## Left in place The third place the same raise can surface, `AOTCompiledFunction.__call__` on the function path, still gets no report and still propagates the raise: building a report there would duplicate the report builder this commit changes, so that belongs in a commit that owns that path. The dead `result == -1` checks at `guards.cpp:2476` and `:2507` are pre-existing bugs this Python-only stack leaves in place -- touching guards.cpp would force a C++ rebuild and would change error semantics for guard evaluation itself -- and are worth fixing as a follow-up: `int result = PyDict_Check(value) ? PyDict_Contains(value, _key.ptr()) : 0;` and the `PySet_Contains` equivalent restore the -1 branch and turn both cases into an ordinary mismatch reason carrying the right advice. Tolerating a raise here stays correct either way, since an arbitrary guard tree can raise for reasons no fix to those two leaves covers. ## Existing tests and fixtures Existing tests change as well. The assertion shared by `test_no_match_message_when_a_guard_answers_inconsistently` and #196823's `test_no_match_message_when_guarded_state_changes_before_the_report`, both reading the `_ACCEPTED_IN_THE_REPORT` constant this commit rewords for the re-check line, follows that reword. `test_aot_compile_module_restores_torch_function_after_the_report_throws` is re-pinned: the `check_verbose` throw it stages no longer propagates in place of the report but is quoted as `[0] <guard check raised RuntimeError: __instancecheck__ raised>`, which it now asserts. `test_aot_compile_module_restores_torch_function_after_a_throw` is rewritten: the `TORCH_CHECK` out of a strided nested tensor's `TENSOR_MATCH` no longer propagates, so it now asserts the report the throw becomes -- one ` [` entry line for the one input, matched by shape -- the prefix `[0] <guard check raised RuntimeError: `, the closing `>`, and `doesn't support strides` between them, which is what the pre-diff assertion matched. The `TORCH_CHECK` sentence itself is ATen's, so a reword of it must not fail a Dynamo dispatch test, and the line is not pinned whole because `TORCH_SHOW_CPP_STACKTRACES=1`, which `run_test.py` sets for the single-test rerun of any failed test, appends the C++ backtrace to a `TORCH_CHECK`'s text, and a whole-line pin fails under it (measured, the entry reading `... Please file an issue. Exception raised from sym_strides_custom at .../NestedTensorImpl.cpp:286 ... >`) where this match passes with the variable set and unset. That line is the only report content in this file a test did not author and so the one place a raise text that split into two entries would show up; it also asserts no `GLOBAL_STATE changed` anywhere, which is the line [0] would carry if `GuardManagerWrapper.check`'s restore of the TorchFunction TLS, #197049's, were removed. This commit adds the fixtures its own tests use: ```python class RaisesOnCompare: # message defaults to "boom from __eq__"; pass another rather than restate the slot class InterruptsOnCompare: # raises the BaseException it is given (KeyboardInterrupt / SystemExit) class WrapsAnInterruptOnCompare: # raise SystemError("inner") from <interrupt>: the shape one unwrap hop misses class RaisesFromAnInterruptOnCompare: # raise ValueError("mid") from KeyboardInterrupt("ctrl-c") class CyclesOnCompare: # two SystemErrors, each the __cause__ of the other class DictBranchModule(torch.nn.Module): ... def _aot_compile_dict_branches(self, *ds): ... # one DictBranchModule result per d over torch.ones(3, 3) ``` `RaisesFromAnInterruptOnCompare` raises the tree's own `ValueError` `from` an interrupt so the stop at the first non-`SystemError` link is pinned rather than only measured. `RaisesOnCompare` and `DictBranchModule` the commits above use as well, and `_aot_compile_dict_branches(*ds)` sits beside `_aot_compile_mode_branches` for the tests that use it, the wrapped-interrupt test's three cases and the free-the-inputs test's three serving exits included. The file's other stubs and the shared `_model_with_stub_trees` helper arrive with the tests-only commit above. ## Order to review `_unwrapped_raise`, `_meant_an_exception`, `_quoted` and `_raised_line` at the top of the file; `AOTCompiledModel.__call__`, which checks the first result inline in the parent's shape and runs the rest of the scan and the whole second pass through the one `accepts(i, result)` closure; the veto on the opted-out last resort and the chained raise; then `_no_match_report`, whose three new keyword-only arguments are the dispatch record and the opt-out flags as the veto read them. Then the tests, on the real `DICT_NOT_CONTAINS` leaf: `test_no_match_message_survives_a_raising_guard` for the report, `test_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result` for the veto and `test_aot_compile_module_raise_from_an_opted_out_result_withholds_nothing` for its `enabled[i]` filter, `test_aot_compile_module_wrapped_interrupt_out_of_a_guard_tree_propagates` for the interrupt each of the three handlers re-raises and `test_aot_compile_module_doubly_wrapped_interrupt_propagates` for one two hops down, `test_aot_compile_module_serves_a_later_match_over_a_raising_leaf` for the serve in (a), `test_aot_compile_module_serving_over_a_raise_frees_this_call_s_inputs` for the record each of the three serving exits clears, `test_aot_compile_module_report_replaces_the_systemerror_a_caller_caught` for the caller-visible change in (c); and, on a `check` patched to raise rather than on the leaf, `test_no_match_message_quotes_a_raise_whose_str_raises` for `_quoted`. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_no_match_message_survives_a_raising_guard python test/dynamo/test_aot_compile.py -k test_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result python test/dynamo/test_aot_compile.py -k test_aot_compile_module_tree_that_raised_then_answered_still_withholds python test/dynamo/test_aot_compile.py -k test_aot_compile_module_raise_from_an_opted_out_result_withholds_nothing python test/dynamo/test_aot_compile.py -k test_no_match_message_when_a_guard_answers_inconsistently python test/dynamo/test_aot_compile.py -k test_aot_compile_module_restores_torch_function_after_a_throw python test/dynamo/test_aot_compile.py -k test_aot_compile_module_restores_torch_function_after_the_report_throws python test/dynamo/test_aot_compile.py -k test_aot_compile_module_wrapped_interrupt_out_of_a_guard_tree_propagates python test/dynamo/test_aot_compile.py -k test_aot_compile_module_doubly_wrapped_interrupt_propagates python test/dynamo/test_aot_compile.py -k test_aot_compile_module_raise_from_an_interrupt_reaches_the_report python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serves_a_later_match_over_a_raising_leaf python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serving_over_a_raise_frees_this_call_s_inputs python test/dynamo/test_aot_compile.py -k test_aot_compile_module_report_replaces_the_systemerror_a_caller_caught python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_a_raise_whose_str_raises python test/dynamo/test_aot_compile.py -k test_no_match_message_names_the_first_raise_recorded python test/dynamo/test_aot_compile.py -k test_no_match_message_when_guarded_state_changes_before_the_report python test/dynamo/test_aot_compile.py -k test_aot_compile_module_raise_chained_in_a_cycle_reaches_the_report python test/dynamo/test_aot_compile.py -k test_no_match_report_quotes_a_tree_that_raised_and_then_rejected python test/dynamo/test_aot_compile.py -k test_no_match_report_reads_an_opted_out_tree_that_raised_as_opted_out python test/dynamo/test_aot_compile.py -k test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators python test/dynamo/test_aot_compile.py -k test_no_match_report_reads_the_opt_out_flags_the_veto_read python test/dynamo/test_aot_compile.py ``` The whole file passes. The tests above were also run against the parent's `torch/_dynamo/aot_compile.py` under this test file, where they fail or error on what the parent does with a raise: the pybind boundary's `SystemError` escapes the call in place of a report or a serve (`ValueError: boom from __eq__` chained under it, and for the cycle test a pair of causes closed on itself that the parent never walks), a patched raise escapes in place of the report, the `except SystemError` test finds no `RuntimeError` to catch, the `_quoted` test's `Boom` escapes the call past its `assertRaises(RuntimeError)`, the TorchFunction tests read the propagated raise text as the whole message, and the tests that read the reworded re-check line read its pre-reword wording. The wrapped-interrupt test and the doubly-wrapped one pass at the parent, which propagated every raise, as negative pins should; against the revision of this commit whose handlers caught `Exception` with no re-raise it fails its cases: the inline check's on `SystemError not raised` (the raise swallowed, [1] accepts and `x * 5` is served), `accepts()`'s on the `RuntimeError` report arriving chained from the `SystemError`, and the report's on the report arriving with nothing chained, the interrupt surviving only as [0]'s quoted `<guard check raised KeyboardInterrupt: ...>` line. Each case pins the `SystemError` by the boundary's `returned a result with an exception set` text and its `__cause__` by identity, `assertIs` against the interrupt the test constructed: re-raising a fresh `SystemError` from a copy of the interrupt fails it on identity, `KeyboardInterrupt('inside __eq__') is not KeyboardInterrupt('inside __eq__')` for the Ctrl-C cases. Each fix below was then reverted on its own against the whole file; the tests named are the ones that pin each decision, not every test the revert fails. Making both dispatch handlers re-raise fails the tests whose trees raise in dispatch and expect a report or a serve, on the raise escaping the call; the wrapped-interrupt test and the doubly-wrapped one, which want the `SystemError` out, pass, as does the inconsistent-guard test, whose tree raises nowhere. Dropping the interrupt re-raise from any one of the three handlers fails exactly that handler's cases of the wrapped-interrupt test, the inline check's on `SystemError not raised` (the raise swallowed, [1] accepts) and `accepts()`'s and the report's on the report arriving in place of the `SystemError`. Reverting `_quoted` to a bare `str(reason)` fails the `_quoted` test on the `ValueError` its `Boom`'s `__str__` raises escaping the call in place of the report; widening it to `except BaseException` fails the same test's interrupt `subTest`s on the report arriving in place of the interrupt, which survives only as `<str() raised KeyboardInterrupt>` (or `SystemExit`) on [0]'s line. Making the report's `check_verbose` handler re-raise fails `test_aot_compile_module_restores_torch_function_after_the_report_throws`, its `[0] <guard check raised RuntimeError: __instancecheck__ raised>` line then missing from a message that is the throw's text alone. Removing the veto entirely, so any raise releases the last resort, serves the opted-out graph -- `x * 5` for a call whose correct answer is a raise -- and fails the tests that pin the veto, `test_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result` and `test_no_match_report_reads_an_opted_out_tree_that_raised_as_opted_out`, both with `RuntimeError not raised`. Removing the `enabled[i]` filter instead, `if not raised:`, so a raise from the opted-out result withholds too, fails `test_aot_compile_module_raise_from_an_opted_out_result_withholds_nothing` and the free-the-inputs test's `exit='last resort'` case, which needs that same serve, and nothing else in the file: the report arrives in place of `x * 2`, chained from the boundary's `SystemError`, its opt-out line reading `withheld because [None]'s guard check raised` since no checked input raised. Forcing `withheld` to `False` fails `test_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result`, the only test asserting that sentence, with `"[0]'s raise, not a guard failure, is what withheld" not found`, the footer reading `[0]'s guard check raised while checking this call` instead. Restoring the old "rejected this call twice and then accepted" wording fails `test_no_match_message_when_a_guard_answers_inconsistently` on the line it now matches (and #196823's `test_no_match_message_when_guarded_state_changes_before_the_report`, which asserts the same constant). Forcing `if i in unanswered:` to `if False:`, so the report re-evaluates a tree whose last evaluation raised, fails `test_aot_compile_module_restores_torch_function_after_a_throw`, whose re-check answers `dispatch key set mismatch` instead of throwing again, so [0]'s line no longer starts `<guard check raised RuntimeError: `, the `_quoted` test, whose `check` is patched to raise but whose `check_verbose` is real and accepts the `{}` it was traced on, so [0]'s line reads `<guards did not accept this call in dispatch and accepted it here: ...>` in place of the `Boom` line, and the first-recorded test, whose [0] rejects the dict when re-evaluated, so `L['d'] is None` replaces its `zero boom` line. Appending the boundary clause to every raise line -- dropping the `reason is e` condition -- fails the report-throws test and the `_quoted` test, whose raises reach the report with nothing chained, and the first-recorded test on its patched `zero boom`, each line then carrying a clause that explains a chain it does not have. Unwrapping one hop instead of the whole chain fails the doubly-wrapped interrupt test alone, the no-match `RuntimeError` arriving in place of the boundary `SystemError` with `[0] <guard check raised SystemError: inner (through the guard tree's pybind boundary)>` on its entry line. Dropping the walk's `isinstance(reason, SystemError)` gate -- `while reason.__cause__ is not None:` -- fails `test_aot_compile_module_raise_from_an_interrupt_reaches_the_report` alone, the boundary `SystemError` escaping the call in place of the report because the walk reads past the tree's own `ValueError` to the interrupt behind it. Reading `__context__` where the unwrap reads `__cause__` now fails that same test and nothing else: the inner `SystemError` was raised outside any handler, so its `__context__` is `None`, the walk stops on it and dispatch reads it as an ordinary raise -- where before the loop that revert failed nothing here. Dropping any one of the three serving exits' `raised.clear(); unanswered.clear()` pair fails `test_aot_compile_module_serving_over_a_raise_frees_this_call_s_inputs` alone, and only in that exit's `subTest` -- `exit='scan'`, `exit='second pass'` and `exit='last resort'` respectively -- the input dict's key still alive with `gc` off after the call returned, while dropping all three `unanswered.clear()` calls and keeping the `raised.clear()` ones leaves the whole file green, which is why the comment claims nothing about them beyond the invariant. Restoring the unbounded `while` in `_unwrapped_raise` fails `test_aot_compile_module_raise_chained_in_a_cycle_reaches_the_report` with `TimeoutError: dispatch did not return` at its 60s alarm, measured on that test: this is the one revert whose symptom is a hang rather than a wrong message. Dropping `unanswered.discard(i)` from `accepts()` fails `test_no_match_report_quotes_a_tree_that_raised_and_then_rejected` and nothing else, [0]'s line reading back the stale `<guard check raised ValueError: boom in the scan>` in place of the `L['d'] is None` guard it rejected on. Narrowing the veto on the opted-out last resort to `map(enabled.__getitem__, unanswered)` fails `test_aot_compile_module_tree_that_raised_then_answered_still_withholds` and nothing else in the file, [1]'s opted-out `x * 5` served to a call whose only enabled tree raised in the scan before rejecting on the second pass, on the strength of that second answer. Reporting the raise record before the opt-out -- the two `if` blocks swapped -- fails `test_no_match_report_reads_an_opted_out_tree_that_raised_as_opted_out` and nothing else, [1] reading as a raise the caller never asked about instead of as the opt-out the veto acted on. On the test side, giving the free-the-inputs test a `Mock(side_effect=...)` where it uses a plain function fails every one of its `subTest`s: the mock's call record holds the `f_locals` and so the key, which is what the assertion inside the patch scope now excludes. Dropping the raise line's separator collapse fails `test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators` and nothing else, the raised text's four separators splitting one entry over several report lines; writing that collapse as a pair of `replace()` calls instead fails the same test alone, on whichever separators the pair does not name. Reverting the report's two reads of the opt-out flags to fresh `result._guard_check_enabled` reads -- the `raiser` comprehension and the entry loop's branch -- fails `test_no_match_report_reads_the_opt_out_flags_the_veto_read` and nothing else in the file: with [1] opted out from inside [0]'s `check_verbose`, [1]'s raise line is replaced by `[1] <opted out of guard checks; withheld because [1]'s guard check raised>`, a withheld line naming the very input whose raise the veto had read as enabled. Authored with the assistance of Claude Code. > **FAQ: the report can lose a raise -- with [0] raising in both passes and > [1] raising in the scan and then rejecting cleanly, [1]'s raise reaches no > line, no footer and no link of the `__cause__` chain -- and the footer names > the input that raised first rather than the first one checked. Fix both > here: have the footer enumerate every enabled raiser, or keep a raise line > beside the rejection.** > > Both reproduce as described (the measurements are above, on the > `DictBranchModule` fixture), and what is wrong about them is the texts, not > the recording. An enumeration in this footer would be the third spelling of > a caveat the commits above own: #197050 appends to the advice the sentence > that says what it rests on after a raise, and #197257 names every tree whose > rejection followed its own raise and quotes each raise out of this same > `raised` record > (`test_no_match_message_names_every_tree_whose_raise_qualifies_the_advice`), > which is exactly the entry this report is missing -- but only inside that > caveat's gate, `if coverable and not trusted_rejection:`, so one enabled input > that rejects without ever raising, the ordinary shape for a multi-input > artifact, switches the caveat off and takes the quoted raise with it. The > shape where a clean rejection coexists with a raise-then-reject tree is > therefore carried nowhere in the stack as it stands, and is left as follow-up > work rather than fixed here. What an enumeration in this footer would break is > the assertions #197050, #197257 and #197390 place on the footer's singular > wording. A raise line beside a rejection is the > same duplication in the entry lines, and it would also contradict the > entry-line rule this commit sets: one line per input, quoting what the > evaluation dispatch acted on answered. The raiser-vs-`__cause__` divergence > the review asks to pin is pinned directly above, by > `test_aot_compile_module_two_raisers_in_the_report`, with the rest of the > stub-tree pins. What this commit owes is texts that say what its code does, > so the class docstring, the `unanswered` comment, the `raiser` comment and > this message now name "the first input that raised of those nobody opted > out", say that `raised` is in recording order and not index order, and say > that a raise which is neither the first recorded nor the first recorded of > the enabled inputs is carried nowhere here. > `test_no_match_message_names_the_first_raise_recorded` makes that wording > load-bearing on the real leaf, and both spellings of the index reading the > review proposes -- `sorted(raised)` for the raiser, `raised[min(raised)]` > for the chain -- fail that test and nothing else in the file. > **FAQ: an earlier revision of this commit carried more tests -- every > stub-guard-manager test, the warning and its dedup. Where are they?** > > Split off for review budget, into consecutive commits directly above, and > every decision this message makes is pinned by exactly one of them, on a > whole test file that was byte-identical to the unsplit commit's when the > split was made; the review rounds since have added tests here, this one's > `_aot_compile_dict_branches` helper and its opted-out-raise test among > them. The tests-only commit above this one carries the stub > tests of the dispatch and report semantics that do not depend on how a tree > raised: the serve of a later match and of a raise-then-accept (a) and (b), > the report's re-check handler, the `__cause__` reading, the `SystemError` > condition on the unwrap, the last-raise record, the chain's first-raiser > reading and the raise line's collapse (the two-raiser test), the interrupt > leaving `accepts()` as itself and the empty-results report (d), plus a stub > repeat of the `_quoted` guard this commit pins on a patched `check`. The > commit above that adds > the warning a served-over raise logs, with its per-model dedup and every > test that reads a log. #197188, > #197179, #197195 and #197219 further up add more report-line, warning and > exit pins on the same code. A review of this commit alone therefore sees > the real-leaf pins of the report, the veto and its `enabled[i]` filter and > the interrupt re-raise, and > the existing tests whose code it changes and the ones that read the > constant it rewords; the rest of the pins are one and two commits up. > **FAQ: `_unwrapped_raise` unwraps one hop, so a doubly-nested boundary > (`SystemError -> SystemError -> ValueError`) reports the wrong exception, > and it cannot tell `_PyErr_FormatFromCause`'s cause from an explicit `raise > ... from ...`. Make it a `while` loop.** Made, and an earlier revision of > this message was wrong about what reaches dispatch. A doubly-nested chain > does not need a Python-level guard manager: a colliding dict key whose > `__eq__` runs `raise SystemError("inner") from KeyboardInterrupt("ctrl-c")` > leaves that `SystemError` set, the real `DICT_NOT_CONTAINS` leaf returns > anyway, and the boundary wraps it in a second one, so with one hop the > unwrap stopped on the inner `SystemError` -- an ordinary `Exception` -- and > the interrupt was recorded as no answer and absorbed into the report > (measured, no patching: `[0] <guard check raised SystemError: inner (through > the guard tree's pybind boundary)>`, chained boundary `SystemError` -> > `SystemError("inner")` -> `KeyboardInterrupt`), which is what the class > docstring's interrupt promise disclaims. So the cost is not one clause in > one message line and the loop is applied; > `test_aot_compile_module_doubly_wrapped_interrupt_propagates` pins it on the > real leaf, and it is also what makes the `__context__`-for-`__cause__` > revert load-bearing in this file. A second PYBIND boundary is still not > producible -- a guard node calling Python clears rather than nests (the > `LAMBDA_GUARD` leaf's `check_nopybind`, `guards.cpp:1918-1924`, is `if (x == > nullptr) { PyErr_Clear(); return false; }`, and the `GetAttrGuardAccessor` > (`:5322`) and `PythonLambdaGuardAccessor` (`:7287`) accessors do the same), > so the nesting comes from the tree's own `raise ... from ...` and not from > two `_PyErr_FormatFromCause` hops. What the loop does not reach are the two > shapes whose chain is broken: an interrupt that code inside the tree caught > and re-raised as `SystemError` sits on `__context__`, which the unwrap > deliberately does not read, and an interrupt an ordinary exception was > raised `from` sits behind that exception, which the walk stops on (measured > above, on the real leaf). Each is the tree's own code answering with > something else, so the docstring promises only an interrupt on an unbroken > chain of `SystemError` causes. > **FAQ: `_quoted` catches only `Exception`, so a `__str__` raising > `KeyboardInterrupt` escapes it and destroys a half-built report. Catch > `BaseException` there: the fallback string discloses the type anyway.** > > Deliberate for an interrupt the `__str__` raises itself, and not the > handlers' unwrap repeated here. A `KeyboardInterrupt` or `SystemExit` raised > directly by the `__str__` is never folded into this call's answer: `except > Exception` does not catch it and it leaves the report as itself, the way the > handlers re-raise one that came out of the tree (wrapped in `SystemError` or > not). Catching it there would turn a Ctrl-C into the line `<str() raised > KeyboardInterrupt>` on a `RuntimeError` report the caller then handles as a > no-match, which is what the handlers exist to prevent one layer up; the > report being half-built when the interrupt arrives costs nothing, since an > interrupted call has no answer to give. Measured: > `test_no_match_message_quotes_a_raise_whose_str_raises` has the tree's > exception's `__str__` raise a `KeyboardInterrupt` and a `SystemExit` and > asserts the very object comes out of the call; with `except BaseException` in > `_quoted`, both cases fail on the `RuntimeError` report arriving instead. > `_quoted` stops there and does not unwrap what the raise chained: a `__str__` > that runs `raise SystemError("wrapped") from KeyboardInterrupt("in str")` is > quoted `<str() raised SystemError>` (measured), which is a line of a report > the caller reads and not an answer given in place of a Ctrl-C, and `except > BaseException` here would not separate the two shapes -- it would swallow the > bare interrupt too. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: https://github.com/pytorch/pytorch/pull/196826 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909
…s and exits on stub guard trees (#197390) **Problem.** #196826's own tests reach the raise-tolerant dispatch only through the real `DICT_NOT_CONTAINS` leaf, whose raise depends on a dead `result == -1` check in `guards.cpp` staying dead, so a C++ fix there would silently un-test the dispatch semantics. **Fix.** Nine tests on stub guard managers pin the records, serves and exits independently of how a tree raised. No source change. **Summary.** Tests only: the commit below, #196826, makes `AOTCompiledModel` dispatch read a guard tree that raises as no answer, and pins that through the real `DICT_NOT_CONTAINS` leaf -- the report over a raise and the veto on the opted-out last resort. Those two tests depend on the dead `result == -1` check in `guards.cpp` staying dead -- restoring it turns their raises into ordinary mismatches -- so the dispatch and report semantics that do not depend on how a tree raised are pinned here, each on a stub guard manager swapped in for a result's tree, which no fix to that leaf touches. Nine tests, three fixtures (`RaisingTree`, `Accepts`, `UnprintableError`) and one helper (`_model_with_stub_trees`); no source change. Every test here passes at #196826 and each is red under the one mutation of its code named below, measured on the whole file at this commit, and all nine fail or error against the parent of #196826's `aot_compile.py`. Order to review: the fixtures beside `DictBranchModule`, then the helper beside `_hide_leaked_dynamo_globals`, then the tests in file order. ## Fixtures and helper ```python class RaisingTree: # every check raises RuntimeError(text) and counts its calls def __init__(self, text): self.text = text self.checks = 0 def check(self, f_locals): self.checks += 1 raise RuntimeError(self.text) class Accepts: # every check matches def check(self, f_locals): return True class UnprintableError(RuntimeError): # a tree's exception is user code down to its __str__ def __str__(self): raise TypeError("str() of the tree's exception raised") def _model_with_stub_trees(self, *stubs): # one ScaleModule result per stub, each swapped in for the real guard tree model = torch.compile(ScaleModule(), fullgraph=True, backend="eager") model._aot_compile(inputs * len(stubs)) for result, stub in zip(model.forward.compiled_results, stubs): result._artifacts.guard_manager = stub return model ``` ## The report's own handler `test_no_match_report_describes_the_other_entries_when_one_raises` pins the report's own handler: two real trees, [0]'s `check_verbose` patched to raise `ValueError("boom")` and to opt [1] out from inside the report. ```python def raising_check_verbose(f_locals): second.disable_guard_check() # user code under the report flips [1]'s opt-out raise ValueError("boom") lines[1] == " [0] <guard check raised ValueError: boom>" # asserted whole; nothing chained, so no boundary clause lines[2].startswith(" [1] ") and "guard check raised" not in lines[2] # [1]'s own guard line, not withheld, not a raise ``` Making that handler re-raise fails this test on `ValueError: boom` escaping the call, and #196826's `test_aot_compile_module_restores_torch_function_after_the_report_throws` on its `[0]` raise line missing; reading `_guard_check_enabled` per entry in the report's loop instead of once fails it alone, [1]'s line reading `<opted out of guard checks; withheld because [None]'s guard check raised>`. ## `__cause__`, not `__context__` `test_no_match_message_reads_a_systemerror_cause_not_the_handled_exception` pins the `__cause__` reading: a stub raising a bare `SystemError` from inside an `except ValueError:` block, whose `__context__` is what the caller was handling. ```python try: raise ValueError("the caller was handling this") except ValueError: model(torch.randn(3, 3)) # the stub raises SystemError("stub tree is unhappy") here # expected: [0] <guard check raised SystemError: stub tree is unhappy> # "the caller was handling this" absent from the message ``` `__context__` for `__cause__` in the unwrapping loop fails it, quoting `ValueError: the caller was handling this (through the guard tree's pybind boundary)` where `<guard check raised SystemError: stub tree is unhappy>` is expected, and fails #196826's `test_aot_compile_module_doubly_wrapped_interrupt_propagates` too: the inner `SystemError("inner")` there has no `__context__`, so that read stops one hop short, takes the interrupt two hops down for an answer, and the call ends in a report reading `[0] <guard check raised SystemError: inner (through the guard tree's pybind boundary)>` where the boundary `SystemError` was to propagate. ## A raise whose `str()` raises `test_no_match_message_survives_a_raise_whose_str_raises` pins `_quoted`: a stub raising `UnprintableError`, whose line reads `<guard check raised UnprintableError: <str() raised TypeError>>` and whose `__cause__` is the exception itself. An unguarded `str(reason)` in `_raised_line` fails it alone, `TypeError: str() of the tree's exception raised` escaping the call with no report -- the failure mode #196826 removes, one layer down. ## An artifact with no results `test_aot_compile_module_with_no_results_raises_the_no_match_report` pins the fourth caller-visible change #196826 describes: `AOTCompiledModel(mod, [])`, which the constructor and `deserialize()` accept, ends in the report. ```python AOTCompiledModel(ScaleModule(), [])(torch.randn(3, 3)) # parent: IndexError: tuple index out of range (results[0] read unconditionally) # now: RuntimeError, lines[0] == "No AOT compiled graph matched this call. Tried 0 compiled input(s):" # no " [" entry line, __cause__ is None, last line advises adding a ModelInput ``` Dropping the `if results:` guard, so `results[0]` is read unconditionally as the parent read it, fails it alone on `IndexError: tuple index out of range`. ## The dispatch record after a raise `test_no_match_report_reads_the_dispatch_record_after_a_raise` pins three things about the record on two stubs: ```python class RaisesThenRejects: # [0]: raises in the scan, returns False on the second pass def check(self, f_locals): self.checks += 1 if self.checks == 1: raise RuntimeError("the first pass is unhappy") return False def check_verbose(self, f_locals): return types.SimpleNamespace(result=True, verbose_code_parts=[]) class RaisesTwice(RaisesThenRejects): # [1]: raises in both passes, chained on purpose def check(self, f_locals): self.checks += 1 raise RuntimeError(f"pass {self.checks} unhappy") from ValueError("x") ``` - [0]'s line is the accept line its `check_verbose` produces, not its raise line. - [1] is quoted for the LAST raise: ` [1] <guard check raised RuntimeError: pass 2 unhappy>`, with `pass 1 unhappy` and `ValueError` absent. - The chain carries [0]'s `the first pass is unhappy`, the FIRST index that raised, and that text is absent from the report; `[0]'s guard check raised while checking this call` is present. `stub.checks == [2, 2]` says the second pass ran both. `raised.setdefault(i, e)` fails it alone, quoting `pass 1 unhappy`; unwrapping every exception that has a cause rather than only a `SystemError` (dropping `isinstance(reason, SystemError)` from the unwrapping loop's condition) fails it alone, `'ValueError' unexpectedly found` in a [1] line reading `ValueError: x (through the guard tree's pybind boundary)`. ## Two raisers `test_aot_compile_module_two_raisers_in_the_report` pins the two records of a raise parting: [0] opted out and [1] enabled both raise, so the chain carries [0]'s exception, the FIRST index that raised, while the withheld line and the footer name [1], the first raiser whose guards someone asked about. ```python model = self._model_with_stub_trees( RaisingTree("the opted-out tree is unhappy"), RaisingTree("checked\x0ctree\x1eis unhappy"), # a form feed and a record separator ) results[0].disable_guard_check() model(x) # [0] <opted out of guard checks; withheld because [1]'s guard check raised> # [1] <guard check raised RuntimeError: checked tree is unhappy> # asserted whole: the collapse # lines[3] contains "[1]'s raise, not a guard failure, is what withheld" # str(__cause__) == "the opted-out tree is unhappy" results[1].disable_guard_check() model(x) # == x * 2, served by the first opted-out result ``` [1]'s text holds a form feed and a record separator, so its line asserted whole is the pin of `_raised_line`'s collapse. Chaining `raised[raiser]` fails it alone, `'checked\x0ctree\x1eis unhappy' != 'the opted-out tree is unhappy'` on the chained text; dropping the collapse (`return line`) fails it alone, the line arriving as three. Then [1] opts out too and the same call is served by the first opted-out result, `x * 2`: silently here, since the warning a served-over raise logs is the commit above's, which adds the reading of that warning to this test. ## An interrupt propagates `test_aot_compile_module_interrupt_out_of_a_guard_tree_propagates` is the negative pin of both dispatch handlers' type: a stub raising `KeyboardInterrupt("ctrl-c inside the tree")` leaves `__call__` as itself. ```python self._model_with_stub_trees(Interrupts(), Accepts())(x) # [0]: the inline handler sees it self._model_with_stub_trees(RaisingTree("unhappy"), Interrupts())(x) # [1]: accepts() does, with a raise on record # both: KeyboardInterrupt("ctrl-c inside the tree") propagates ``` Widening a handler's `except Exception` to `BaseException` alone fails nothing -- #196826's re-raise of a cause that is not an `Exception` still lets the interrupt out -- so the mutation is widening one handler and dropping its re-raise. On the inline handler that fails the first call, `KeyboardInterrupt not raised`: the interrupt read as no answer and [1] served over it. On `accepts()` it fails the second call, the interrupt quoted as [1]'s line in a report `Tried 2 compiled input(s):` chained from [0]'s `RuntimeError: unhappy`. Each also fails the wrapped-interrupt test's two cases for that handler, and nothing else. ## A later match after an earlier raise `test_aot_compile_module_serves_a_later_match_after_an_earlier_raise` pins change (a) of #196826, the one path where tolerating a raise changes an answer and not a message: `GlobalConfigModule` with two inputs, [0]'s tree a `RaisingTree`, [1]'s real guards matching the call, and the served value is [1]'s. ```python results[0]._artifacts.guard_manager = RaisingTree("guard tree is unhappy") with _set_pooling("mean"): served = model(x) # parent: [0]'s raise propagates, nothing served self.assertEqual(served, expected) # now: [1]'s graph self.assertEqual(results[0]._artifacts.guard_manager.checks, 1) ``` `checks == 1` pins the serve to the scan: withholding the scan's match once a raise is on record (`if accepts(i, result) and not raised:`) serves the same value on the second pass and fails only that count, `Expected 1 but got 2`. ## A tree that raised and then accepted `test_aot_compile_module_serves_a_tree_that_raised_and_then_accepted` pins change (b): one stub raising in the scan and accepting on the second pass is served on that accept, `checks == 2`, and the next call is served with no raise on record at all -- which is why a per-call veto is not what keeps a stale tree honest. ```python stub = RaisesThenAccepts() # check 1 raises RuntimeError("the scan is unhappy"), then True model(x) # == x * 2, stub.checks == 2: the serve is the second pass's model(x) # == x * 2 again, no raise on record ``` ## Cross-cutting mutations Making the dispatch handlers re-raise fails the seven tests here whose trees raise an `Exception` in dispatch -- the later-match, raised-then-accepted, `__cause__`, `__str__` and interrupt tests on the stub's raise escaping the call (the interrupt test on its second call's `RuntimeError: unhappy`), the two-raiser and dispatch-record tests on their entry-line and check counts (`Scalars are not equal!`) -- and the three in #196826, while the describer test, whose raise happens only in the report, and the empty-results test pass. Forcing `if i in unanswered:` to `if False:`, so the report re-evaluates a tree whose last evaluation raised, fails four here: the two-raiser, `__cause__` and `__str__` tests on a line reading `<guard check raised AttributeError: 'RaisingTree' object has no attribute 'check_verbose'>` (or `'Raises'`) where the raise line is expected -- these stubs define no `check_verbose`, so a report that re-checked them fails legibly enough, and #197188's `NeverReChecked` base makes the same regression fail on a message naming the re-check -- and the dispatch-record test, whose [1] then reads the accept line its inherited `check_verbose` produces. Appending the boundary clause to every raise line fails five here: the two-raiser, `__cause__`, `__str__`, describer and dispatch-record tests, each on a line asserted whole. Removing the veto's `_guard_check_enabled` gate fails the two-raiser test with `RuntimeError not raised` (and #196826's veto test); forcing `withheld` to `False` fails it on the footer (and the same test below). Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_no_match_report_describes_the_other_entries_when_one_raises python test/dynamo/test_aot_compile.py -k test_no_match_message_reads_a_systemerror_cause_not_the_handled_exception python test/dynamo/test_aot_compile.py -k test_no_match_message_survives_a_raise_whose_str_raises python test/dynamo/test_aot_compile.py -k test_aot_compile_module_with_no_results_raises_the_no_match_report python test/dynamo/test_aot_compile.py -k test_no_match_report_reads_the_dispatch_record_after_a_raise python test/dynamo/test_aot_compile.py -k test_aot_compile_module_two_raisers_in_the_report python test/dynamo/test_aot_compile.py -k test_aot_compile_module_interrupt_out_of_a_guard_tree_propagates python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serves_a_later_match_after_an_earlier_raise python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serves_a_tree_that_raised_and_then_accepted python test/dynamo/test_aot_compile.py ``` The whole file runs 257 tests, `OK (skipped=6)`; #196826 runs 248. The nine were also run against the parent of #196826's `torch/_dynamo/aot_compile.py` under this test file, and all nine fail or error: the later-match, raised-then-accepted, `__cause__` and `__str__` tests and the describer test on the raise escaping the call, the interrupt test on its second call's `RuntimeError: unhappy` escaping it, the two-raiser and dispatch-record tests on `Scalars are not equal!`, the empty-results test on `IndexError`. Each mutation above was applied on its own to `torch/_dynamo/aot_compile.py` at this commit and the whole file run; only the named tests failed. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: #197390 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826
…h over a raise (#197391) **Problem.** After #196826, dispatch that serves a graph over another result's raise does so silently, so a broken artifact that never costs the caller an answer is never noticed. **Fix.** Log one warning per (index, exception type, opt-out state) on the `torch._dynamo.aot_compile` logger whenever a graph is served with a raise on record, deduplicated per model, quoting the raise and advising a fix. **Summary.** Two commits below, #196826 made `AOTCompiledModel` dispatch read a guard tree that raises as no answer, so a match found beside the raise is served, and so is the raiser's own accept on the second pass, and both serves were silent: nothing else records the raise on a serving path (the report is never built), so a broken artifact that never costs the caller an answer is never seen, and the one thing a refusal would have bought -- that a raise dispatch served over cannot go unrecorded -- was not bought. This commit buys it with a warning: every path that RETURNS a graph with a raise on record logs one per index that raised on the `torch._dynamo.aot_compile` logger, quoting its last raise, naming the index served and what the raise left stale, and giving one sentence of advice whose shape depends on whether the raiser opted out of guard checks. Serving and warning beats refusing because the raise says nothing about the result that did answer and a refusal would not undo the relational residue a C++ throw leaves in the tree (a `NO_TENSOR_ALIASING` set, or under `enable_cpp_symbolic_shape_guards` a `SYMBOLIC_SHAPE_GUARD` count), which can bend the tree's NEXT check with no raise on record to veto. The warning is deduplicated per `(index, exception type name, opt-out state)` in a per-model set kept beside weak references to the results it was logged about, so a hot loop over a broken artifact logs once per defect rather than once per call, the set starts over when `compiled_results` holds other results, and the one-shot is spent only after `log.warning` returns and only when the logger's level would let the record through. Every decision here but the field's shape is pinned by a test, measured by reverting it on its own against the whole file, and the existing tests of #196826 and #197390 that reached a serving path now read the log. ## What the warning looks like ```python model = self._model_with_stub_trees(RaisingTree("guard tree is unhappy"), Accepts()) model(x) # served by [1]; parent: silent; now one WARNING on torch._dynamo.aot_compile: # AOT compiled input [0]'s guard check raised RuntimeError: guard tree is unhappy; dispatch served [1] # rather than propagating it. Fix or drop input [0]: its next check can reject a call it fits or # accept one it does not. model(x) # same defect, same results: silent ``` ## Order to review `_same_results`, hoisted out of `_binds_alike` because the warning's dedup asks the same question -- are these the results last judged? -- of a weak-reference tuple of its own; the `_warned` field beside `_binding_verdict`; `_warn_swallowed` beside `_binds_alike` and its three call sites in `__call__`, one per serving path -- a match in the scan, a match on the second pass, and the last resort serving the first opted-out result while an opted-out result's raise is on record; then `_model_with_stub_trees`'s `opt_out` keyword, whose first callers are here, the `Rejects` stub, now with the `check_verbose` a report path would quote, as `RaisesThenRejects` has, and `RaisesUnprintable`, and the tests, the new ones -- one of them parametrized over the three serving sites -- and the ones already here that now read the log: those the commit below added over stub trees, and those of #196826's whose raise arrives through the real pybind boundary, which is what pins the unwrap. ## The change ```python def _same_results(prior, results): return len(prior) == len(results) and all(w() is r for w, r in zip(prior, results)) class AOTCompiledModel: _warned: tuple[tuple[weakref.ref[AOTCompiledFunction], ...], set[tuple[int, str, bool]]] def _warn_swallowed(self, results, raised, served): if not log.isEnabledFor(logging.WARNING): # a dropped record must not spend the one-shot return over, warned = self._warned if not _same_results(over, results): # other results at these indices: start over warned = set() self._warned = (tuple(weakref.ref(r) for r in results), warned) for i, e in raised.items(): kind, reason = _unwrapped_raise(e) # the same unwrap the report line reads enabled = results[i]._guard_check_enabled if (i, kind, enabled) in warned: continue advice = ... if enabled else ... # the two sentences below log.warning("AOT compiled input [%d]'s guard check raised %s: %s; dispatch served [%d] " "rather than propagating it. %s", i, kind, _quoted(reason), served, advice) warned.add((i, kind, enabled)) # spent LAST: _quoted can let an interrupt out def __call__(self, *args, **kwargs): ... for i, result in enumerate(results[1:], 1): # the scan if accepts(i, result): if raised: self._warn_swallowed(results, raised, i) ... for i, result in enumerate(results): # the second pass if accepts(i, result): if raised: self._warn_swallowed(results, raised, i) ... if not any(map(enabled.__getitem__, raised)): # the last resort for i, result in enumerate(results): if not enabled[i]: if raised: self._warn_swallowed(results, raised, i) ... ``` ## Serve and warn, rather than refuse A match found after a raise is served, and warned about, rather than refused. The raise says nothing about the artifact that did answer, and refusing would not undo the relational residue a C++ throw leaves: by the time dispatch decides anything the throw has already happened, so a refusal costs the caller a graph whose guards passed and repairs nothing. That holds where the artifact that answered IS the one that raised, even though the residue can bend an accept and not only a rejection. **What a throw leaves stale.** A throw elsewhere in the tree unwinds past `RootGuardManager::_reset_relational_guard_state()`, which the root check calls only at its normal exits (`guards.cpp:4386-4415`, none under RAII) and which is every relational guard's only reset (`:4543-4547`). What that leaves in a default build, wherever the tree guards more than one tensor against aliasing, is the rejection: `NO_TENSOR_ALIASING` answers false for a tensor already in its `_unique_tensors` (`:2710-2718`), which is cleared in `reset_state()` alone (`:2730-2732`), so the set the throwing evaluation filled rejects a call the tree fits. That guard has one install site and one condition, `len(no_tensor_aliasing_names) > 1` (`torch/_dynamo/guards.py:5409-5416`), and that call is also what registers the resetter the throw unwinds past (`add_no_tensor_aliasing_guard`, `guards.cpp:4339-4344`), so an artifact whose tree checks a single tensor against aliasing has no such set to leave stale. The accept needs `enable_cpp_symbolic_shape_guards`, `False` by default (`torch/_dynamo/config.py:560`) -- the qualifier this file already carries on the veto's comment (`aot_compile.py:1991-1992`) and now on the class docstring too: with that config on, `SYMBOLIC_SHAPE_GUARD` keeps the `_args_seen` this evaluation reached, since `_reset_relational_guard_state` is the sole caller of its `reset_state()` (`guards.cpp:2887-2889`) and `check_nopybind` (`:2816-2843`) zeroes it only on the complete path (`:2837`), and the next evaluation reaches `_nargs` early and calls `_guard_check_fn` over an `_args_int` buffer whose remaining slots still hold the previous call's values. | residue | guard | needs | bends the next check toward | | --- | --- | --- | --- | | `_unique_tensors` left filled | `NO_TENSOR_ALIASING` | more than one tensor guarded against aliasing (default build) | a rejection of a call it fits | | `_args_seen` left counted | `SYMBOLIC_SHAPE_GUARD` | `enable_cpp_symbolic_shape_guards=True` (off by default) | an accept of a call it does not fit | The advice names both directions in either build: neither residue can be told from a real answer or cleared from Python, and the accept half is one config flag away. Nor would a per-call veto contain it: measured on a one-raise stub with two inputs, [0] raises inline, [1]'s real guards match, dispatch serves [1], and the NEXT call gets [0]'s post-throw answer with nothing on record -- no raise, so nothing to veto. ### The enabled advice So the warning for an enabled tree names both directions a stale tree can bend a later answer: ``` Fix or drop input [i]: its next check can reject a call it fits or accept one it does not. ``` It holds at any index and needs no qualification. ### The opted-out advice `check()` ignores the opt-out, so an opted-out tree's rejections and accepts are acted on in both passes like any other's. A stale rejection forfeits only the calls the last resort does not then hand it: the last resort serves the FIRST opted-out result, and only when no enabled input raised, so the rejection costs it the call when another opted-out result sits ahead of it (`[opted-out A, opted-out B]`, B's stale tree rejecting a call it fits: A's unguarded graph is served where B's accept would have served B) or when an enabled input's raise withholds the last resort (`[enabled E raising, opted-out B]`: B's stale rejection turns a serve into the no-match report). A stale accept serves its graph for a call it does not fit ahead of a later result whose guards would have matched, a cost the opt-out never promised (opt-out means the last resort, after the real matches), and one no later stage undoes. So the opted-out warning names that one direction: ``` Input [i] opted out of guard checks, but its next check can accept a call it does not fit ahead of a later match; fix or drop it. Input [i] opted out of guard checks, but its next check can accept a call it does not fit; fix or drop it. # from the last index ``` The `ahead of a later match` clause is appended only when `i + 1 < len(results)`, because the displaced match is positional: from the LAST index there is no later result to displace, and what a stale accept displaces there instead depends on the results ahead of it. Measured, case by case: | results | what a stale accept at the last index displaces | | --- | --- | | two opted-out, `Rejects` at [0], raiser at [1] | the last resort serves [0]; with [1]'s tree accepting on the second pass instead -- which is what a stale accept looks like -- [1] is served, so [0]'s unguarded graph is displaced by the very result the opt-out promised to serve last | | a lone opted-out raiser | nothing: the raiser is itself the first opted-out result, so the last resort would have served it anyway; warns `dispatch served [i]` for its own index | | enabled `Rejects` at [0], opted-out raiser at [1] | nothing, same reason; warns `dispatch served [1]` | | enabled raiser at [0], opted-out raiser at [1] | the no-match report: the pair raises the report, and with [1] accepting on the second pass it serves [1] | None of those is the harm the clause names, so from the last index the advice states the remedy alone, `accept a call it does not fit; fix or drop it.`, and the class docstring says what the accept displaces there instead. Each advice is one sentence; the reasoning above, and the cost the raise itself has for an opted-out tree -- its graph is reachable only through its own later accept or the last resort, which any enabled tree's raise withholds -- is in the class docstring, written once for the three sites that log it and beside the dispatch rules it explains, rather than repeated in every log line. The "its own later accept" is load-bearing there too: an opted-out tree that raises once and then accepts is served by that accept on the second pass with its first pass's raise on record, so "reachable only through the last resort" outright would be false on the very path the second-pass site logs from. ## The dedup key: `(index, exception type name, opt-out state)` **Why the opt-out state is in the key.** `disable_guard_check()` flips a field on the SAME result: the weak references still dereference to the results last warned about, `_same_results` answers true, and no reset runs, so a key of `(index, type)` alone would log the enabled advice for a raiser and never the opted-out one after the caller opts it out -- the advice that names the stale accept, which for an opted-out tree is the only cost -- though `check()` ignores the flag and the tree raises on, so the warning is still reached. ```python model = self._model_with_stub_trees(RaisingTree("unhappy"), Accepts()) model(x) # Fix or drop input [0] ... model.forward.compiled_results[0].disable_guard_check() model(x) # Input [0] opted out of guard checks, but ... dispatch served [1] model(x) # silent ``` **Why the type name is in the key, and what it buys.** The type name tells two defects at one index apart only when they raise different types, which real trees seldom do: a `TORCH_CHECK` that fires in a guard is a `c10::Error`, translated to `RuntimeError` at the pybind boundary (`CATCH_TH_ERRORS`, `torch/csrc/Exceptions.h:96`), and every plain `TORCH_CHECK` reached at check time in `guards.cpp` lands there. The one typed one that a check reaches is `FrameLocalsGuardAccessor::check_nopybind`'s `TORCH_CHECK_TYPE` (`guards.cpp:5655`), which `_CATCH_GENERIC_ERROR(TypeError, ...)` (`Exceptions.h:74`) takes before the `RuntimeError` arm, so it would key as `TypeError`; it needs an `f_locals` that is not a dict, which this path never passes -- `prepare_f_locals` returns one it built itself. Every other typed `TORCH_CHECK` in the file is in a constructor, a manager factory or `get_type_of_guarded_value`. So under real leaves "once per defect" is closer to "once per index and opt-out state"; the docstring says so. **Why the served index is not in the key.** The served index is in every warning but deliberately not in the key: the remedy is the raiser whichever result answered, so a defect whose serve moves is reported once, for whichever serve came first. `test_aot_compile_module_does_not_warn_again_when_the_serve_moves` pins that: a `RaisingTree` at [0] and two `Accepts`, the first call served by [1] and warning `dispatch served [1]`, and with [1]'s stub patched to refuse afterwards the next call, served by [2] over the same raise, silent. A key of `(i, kind, enabled, served)` fails it alone, `Unexpected logs found` quoting a second warning that says `dispatch served [2]`. The docstring says this too, so a reader who sees one served index does not take it for the whole story. ## When the one-shot is spent A one-shot is spent only by a warning the logger's level let through, which takes two things. **The level gate.** `_warn_swallowed` returns before anything else when `log.isEnabledFor(logging.WARNING)` is false: a logger whose effective level is above WARNING when the first serve happens -- a `TORCH_LOGS` setting, a library that raised the level at import, a `logging.disable` -- would otherwise record the key and drop the record, and lowering the level afterwards would never surface that defect for the model, a runtime-divergence warning about a broken artifact lost silently, the outcome the commit exists to prevent. That gate is the level and `logging.disable` and nothing further, which is why this says the logger's LEVEL rather than the log: measured directly, a `logging.Filter` on the logger and a handler whose own level is above WARNING each drop the record while `isEnabledFor(WARNING)` is still true, and nothing on this path can see either, so under those two the key is spent on a warning nobody reads. **`add` after `log.warning`.** `warned.add` is the loop body's LAST statement, after `log.warning`, because that call's argument list reaches user code once more: the text is `_quoted(reason)`, which catches `Exception` as the handlers do, so a `BaseException` out of the recorded exception's `__str__` leaves `_warn_swallowed` from there, discarding a graph whose guards passed, and a key added ahead of the call would silence that defect for the rest of the model's life. The two are independent and neither substitutes for the other: `log.warning` returns the same whether it emitted or filtered, so the ordering says nothing about the level, and the level gate is passed long before the quote runs. Each has its own test below, and each fails only its own. ## The unwrapped raise, quoted Both the type the warning names and the dedup key are read off the UNWRAPPED exception through `_unwrapped_raise`, the helper the report line already reads, so the two records of one raise cannot drift: ```python # a DICT_NOT_CONTAINS leaf raising ValueError("boom from __eq__") through the real pybind boundary # without the unwrap: "[0]'s guard check raised SystemError: <built-in method check of pybind11_builtins... returned a result with an exception set>" # key (0, "SystemError", enabled) for every raise at [0], so two defects collapse into one warning # with the unwrap: "[0]'s guard check raised ValueError: boom from __eq__" # a ValueError and a TypeError at one index log twice ``` The text is `_quoted(reason)`, the guarded `str()` the report line uses, and not the exception object: `logging` formats a record lazily, so an object whose `__str__` raises reaches the handler's `handleError` -- a traceback on stderr and no warning -- where the report line would have said `<str() raised TypeError>`. `_quoted` guards `Exception` and not `BaseException` on both paths, and its comment now says what that costs on each: the report's quote is built over a call that was already failing, the warning's over a graph about to be served, which is the ordering above. The warning's quote is otherwise raw; only `_raised_line` collapses separators, since only the report is read back with `splitlines()`. ## A per-model set beside weak references The dedup set is a field on the model, not `torch._logging.warning_once`, whose `functools.cache` key includes every argument -- passing the exception object defeats the dedup outright -- and whose cache is process-global, so the first model to log would silence every later one with the same defect. Measured on this file: with `_warn_swallowed` calling `warning_once` with the message it builds instead of consulting the per-model set, tests fail on `no logs of level WARNING or higher triggered` where a later test's model hits a defect an earlier test's model already logged, and `..._does_not_warn_again_when_the_serve_moves` on `Unexpected logs found` quoting `dispatch served [2]`, since a moved serve builds a different message and the cache is keyed on what it is passed. Any runner that runs a test twice in one process sees the same sharing -- `--repeat` loops `unittest.main` in place (`torch/testing/_internal/common_utils.py:1642-1645`). The key's index is a bare list position, and `compiled_results` is public: a list that changed can put another artifact at a warned-about index -- a `pop()` shifts every later result down one, and a one-result model can have its only artifact swapped in place -- whose raise the first warning never described. So the triples are kept beside weak references to the results they were logged about, one field on the terms `_binding_verdict` states, and `_warn_swallowed` starts the set over when the results it is about to log for are not those. That is judged where the warning is logged, not with the binding verdict, although the verdict is re-decided on the same change: it is re-decided only when a second result needs a binding, which a one-result model never reaches, so a reset tied to it never runs for the model that reaches the warning most simply -- one opted-out artifact whose tree raises -- and that model's first `(0, kind, False)` would silence every artifact later put at [0]. The cost is one repeat per mutation, not per call. The field is `init=False` and built by a factory: a caller-supplied set would share one dedup across models, the process-global behaviour it exists to avoid, and a class-level `default` would share one as surely, masked at runtime only by the reset above, which a model's first warning runs. Every decision above but the field's shape is pinned by a test here, measured by reverting it on its own against the whole file at this commit. The shape has no behavioural pin to give it: a class-level `default` is masked by the reset on every path that logs, and the per-model dedup itself is `test_aot_compile_module_warns_once_per_model_not_per_process`'s. ## A method, gated at three sites `_warn_swallowed` is a method beside `_binds_alike`, not a closure in `__call__`: its three call sites gate it on `if raised:`, so a closure there was built on every multi-result call and entered on none of the healthy ones. Measured on a replica of the scope shape (min of 7 x 2M): | variant | cost | | --- | --- | | building a three-cell annotated closure and dropping it | 140 ns per call over not building one | | a two-result dispatch itself | 22-25 us across runs of either version | Invisible in that noise, and paid on every call all the same; the method costs the healthy path nothing. Those gates are also what lets a results list be changed and changed back without losing the keys already in force: a serve with nothing on record never reaches `_warn_swallowed`, so it never compares the results it is serving against the ones last warned about and never installs a fresh set over them. `test_aot_compile_module_warning_survives_a_serve_that_does_not_warn` pins that -- warn about a `RaisingTree` at [0] with an `Accepts` at [1], then put a `(Rejects(), Accepts())` list in its place and serve it, which warns nothing, then put the warned-about results back and assert the serve of them is silent. The intermediate list has to reject at [0] so its serve reaches the scan site, the one the first call warned from; a lone `Accepts()` would be served by the inline first-result path, which calls none of the three. Deleting all three gates and calling `_warn_swallowed` unconditionally fails that test and only that test, `Unexpected logs found` quoting the first warning again. ## Tests The stubs: `Rejects` (refuses every call, with the `check_verbose` a report path would quote), `RaisesThenAccepts` (raises in the scan, accepts on the second pass; hoisted from the raised-then-accepted test to module level) and `RaisesUnprintable` (every check raises an `UnprintableError`), built into models by `_model_with_stub_trees(*stubs, opt_out=False)`. - `test_aot_compile_module_serves_a_later_match_after_an_earlier_raise` now reads the scan's warning and pins the whole line: `AOT compiled input [0]'s guard check raised RuntimeError: guard tree is unhappy; dispatch served [1] rather than propagating it. Fix or drop input [0]: its next check can reject a call it fits or accept one it does not.` Logging the raiser's index in the served slot fails that pin, the line coming out saying `dispatch served [0]`. - `test_aot_compile_module_serves_a_tree_that_raised_and_then_accepted` now reads the second pass's warning -- `[0]'s guard check raised RuntimeError: the scan is unhappy`, `dispatch served [0]`, both directions of the advice -- and asserts the next call, with no raise on record, is served under `assertNoLogs`. - `test_aot_compile_module_opted_out_advice_allows_the_raisers_own_accept` is the same shape opted out: the one call logs once, `checks == 2`, and the whole line is pinned -- `dispatch served [0]` and `Input [0] opted out of guard checks, but its next check can accept a call it does not fit; fix or drop it.`, so no `Fix or drop input` (the enabled advice's opening), no charge of a stale rejection, and, the one result being the last, no later match named. `served == i` at that site cannot tell this serve from the last resort's of the same one-result model, so the advice says nothing that is true on only one of the two paths. The clause's two branches are pinned against each other: this test and `..._warns_before_the_served_graph_runs`'s `last_resort` case, whose raiser is the last of two, assert it absent, and `test_aot_compile_module_warns_again_after_the_raiser_opts_out`, whose opted-out raiser at [0] has an `Accepts` behind it, asserts it present. Appending the clause unconditionally fails this one on its whole-line pin and the cases that assert it absent, `'accept a call it does not fit; fix or drop it.' not found`. Dropping the clause unconditionally fails `..._warns_again_after_the_raiser_opts_out` alone, `'does not fit ahead of a later match' not found`. - `test_aot_compile_module_warning_advice_follows_the_raiser_not_the_served` pins which result's opt-out the advice reads: an enabled `RaisingTree` at [0] served over by an opted-out `Accepts` at [1] -- `check()` ignores the flag, so [1] matches in the scan -- logs one warning with `dispatch served [1]` and `Fix or drop input [0]`, and not the last-resort advice. Reading `results[served]._guard_check_enabled` fails this test, `'Fix or drop input [0]' not found` in a warning reading `Input [0] opted out of guard checks, but`, and one other, `test_aot_compile_module_warns_again_after_the_raiser_opts_out`, whose served [1] stays enabled: its first call then records `(0, "RuntimeError", True)` and its second, after [0] opts out, is silent, `no logs of level WARNING or higher triggered`. Every other warning test's raiser and served result share an opt-out status. - `test_aot_compile_module_second_pass_warning_names_the_index_served` pins the second pass's site: a `RaisingTree` at [0] and a `RaisesThenAccepts` at [1], so [0] raises inline and again on the second pass, [1] raises in the scan and accepts on the second pass, and the call is served by [1] with raises on record for both: two warnings, each saying `dispatch served [1]`. The raised-then-accepted test reaches the same site with one result, where served, raiser and 0 coincide, so this is the test that fails when that site logs `0` for the served index -- `Expected 2 but got 0` on the `dispatch served [1]` count, both warnings saying `dispatch served [0]` -- and it fails under the served-as-raiser mutation too, `Expected 2 but got 1`. - `test_aot_compile_module_scan_warning_names_the_index_served` pins the scan site's served index at a value other than the one every other test reaches it with: a `RaisingTree` at [0], a `Rejects` at [1] and an `Accepts` at [2], so the scan serves [2] over [0]'s raise -- one warning, `dispatch served [2]` and `Fix or drop input [0]` -- and a constant `1` for that site fails it alone, `'dispatch served [2]' not found`. The last resort's index is pinned by `..._warns_before_the_served_graph_runs`'s `last_resort` case, whose stubs are a `Rejects` at [0], enabled and refusing in both passes, and an opted-out `RaisingTree` at [1]: no enabled tree raised, so the last resort serves the first opted-out result, [1], and the warning reads `[1]'s guard check raised RuntimeError: unhappy`, `dispatch served [1]` and `opted out of guard checks, but`; a constant `0` for that site fails that case alone, `'dispatch served [1]' not found`. Before these, every test that reached the scan's site was served by [1] and every one that reached the last resort's by [0], so either constant passed the whole file. - `test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning` (renamed from `..._in_the_report`) reaches the last resort with two opted-out raisers, so one call logs two warnings and the warning about [1] says `dispatch served [0]`, the served index and the raising index read each from its own source. [1]'s message holds a form feed and a record separator, and the warning is asserted with both in place: collapsing the warning's quote as the report line's is fails it alone. Its report call, before [1] opts out, runs under `assertNoLogs`: the report chains the raise and logs nothing about it. - `test_aot_compile_module_warns_once_per_model_not_per_process` pins the per-model set: two models with the same defect each log once, and a second call on the first logs nothing; it also pins the opted-out advice, since the helper's result opted out -- handing it the enabled tree's advice (forcing the `enabled` test in `_warn_swallowed` true) fails it with `'opted out of guard checks, but' not found` in a warning reading `Fix or drop input [0]`. - `test_aot_compile_module_warns_once_per_exception_type_at_one_index` pins the type name in the key on a stub raising `ValueError` and then `TypeError` with one text: two warnings, and a third call raising the `TypeError` again logs nothing, so a key of `(i, enabled)` fails it alone, `Expected 2 but got 1` on `len(logs.output)`; a key of `(i,)` fails it the same way and the opts-out test next on its second call. - `test_aot_compile_module_warns_again_after_the_raiser_opts_out` pins the opt-out state: a `RaisingTree` at [0] and an `Accepts` at [1] warn `Fix or drop input [0]` once, `disable_guard_check()` on [0] makes the next call warn once more with `Input [0] opted out of guard checks, but` and `dispatch served [1]`, and the call after that is silent. A key of `(i, kind)` fails it alone, `no logs of level WARNING or higher triggered` on the second call. - `test_aot_compile_module_warning_is_not_spent_while_the_logger_drops_it` pins the gate: the first call runs under `assertNoLogs(level="ERROR")`, which sets the logger's level to ERROR for its block, the second under `assertLogs(level="WARNING")` logs the one warning, and the third is silent. Deleting the `isEnabledFor` test fails it alone, `no logs of level WARNING or higher triggered` on the second call, with the `add` where it is. - `test_aot_compile_module_warning_not_spent_by_an_interrupt_from_str` pins the placement, and is the only test that does: a stub raising a `Boom` whose `__str__` raises a `KeyboardInterrupt` the first time it is called, beside an `Accepts`, so the first call leaves as that interrupt with the graph unserved and the call after it warns once, `[0]'s guard check raised Boom: boom from __str__` and `dispatch served [1]`. Moving the `add` back ahead of `log.warning` fails it alone, `no logs of level WARNING or higher triggered` on that second call. Deleting the dedup -- the `(i, kind, enabled) in warned` test and the `add` beside it -- does not fail this one, whose second call is the first warning it gets; it fails the tests whose repeat call has to be silent, `Unexpected logs found` quoting the repeated warning. - The unwrap -- both the type the warning names and the key's type name -- is pinned by the two tests of #196826's whose raise arrives through the real `DICT_NOT_CONTAINS` leaf and now read the log, `..._raise_from_an_opted_out_result_withholds_nothing`, where the last resort serves the opted-out raiser's own graph, and `..._serves_a_later_match_over_a_raising_leaf`, where the scan serves [1]: reading the type and the text off the `SystemError` pybind hands back fails both, `"[0]'s guard check raised ValueError: boom from __eq__" not found` in a warning reading `raised SystemError: <built-in method check of pybind11_builtins...`. #196826's third serving test, `..._serving_over_a_raise_frees_this_call_s_inputs`, reads the log under a bare `assertLogs`: the record it captures holds formatted ints and strings only, so the warning does not keep alive the input that test watches die with the cycle collector off. - `test_aot_compile_module_warns_again_about_a_replaced_single_result` is the test that tells the reset's placements apart: an opted-out artifact whose tree raises warns once, the next call is silent, `compiled_results[0] = <another such artifact>` makes the call after it warn once more, quoting the replacement's text, and the call after that is silent again. The displaced result is held in a local across the swap, so a dead weak reference cannot explain the reset and only the identity comparison in `_same_results` can: the swap would otherwise drop the last strong reference to the displaced result (a one-result model never sets `_binding_verdict`), and a `_same_results` that tested each prior reference for liveness instead of identity passed the test as it stood; held, that mutation fails it on the call after the swap, `no logs of level WARNING or higher triggered` (and, `_same_results` being `_binds_alike`'s test too, #197071's `test_module_dispatch_judges_a_replaced_result_on_its_own_binding`). Never starting the dedup over (forcing the `_same_results` test true) and gating the reset on two or more results each fail it alone with the same text on the same call; its multi-result twin, where a `pop(0)` moves a raising artifact to a warned-about index, is #197195's `test_aot_compile_module_warns_again_about_a_replaced_index`, which passes under either misplacement because a two-result model does re-decide the binding verdict. - `test_aot_compile_module_warning_survives_a_raise_whose_str_raises` pins `_quoted` on this path: an opted-out stub raising `UnprintableError` logs one warning reading `[0]'s guard check raised UnprintableError: <str() raised TypeError>`. Handing `log.warning` the exception object instead fails it alone, `TypeError: str() of the tree's exception raised` out of the capturing handler's `format`. - `test_aot_compile_module_warns_before_the_served_graph_runs` is `@parametrize`d over the three serving sites. A call that ends before dispatch picks a result leaves as the exception that ended it and records nothing: a later result's tree raising a `BaseException`, a later result's bind raising `TypeError`, `_binding_key` raising over a malformed artifact, and the report builder itself raising. The first two, the ones a guard manager can produce, are pinned in #197219 under `assertNoLogs`; the FAQ below says why none of the four warns. The warning is logged before `_serve` runs the graph, since it describes the dispatch decision, so a served graph that raises leaves with the warning logged. That is one decision at three sites, and the three cases differ only in the stubs, the served index and the opt-out -- each patching the served result's `_serve` to raise and reading the one warning out of the call that raised: | case | stubs | reads | | --- | --- | --- | | `scan` | `RaisingTree` at [0], `Accepts` at [1] | `dispatch served [1]` | | `second_pass` | a lone `RaisesThenAccepts` | `[0]'s guard check raised RuntimeError: the scan is unhappy`, `dispatch served [0]` | | `last_resort` | `Rejects` at [0], opted-out `RaisingTree` at [1] | `dispatch served [1]`, `opted out of guard checks, but` | Every other served graph here (`ScaleModule`'s, or `GlobalConfigModule`'s in the later-match test) returns, so moving one site's `_warn_swallowed` call after `_serve`, measured a site at a time against the whole file, passes the rest of it and fails that site's case alone, `no logs of level WARNING or higher triggered`. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serves_a_later_match_after_an_earlier_raise python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_before_the_served_graph_runs python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serves_a_tree_that_raised_and_then_accepted python test/dynamo/test_aot_compile.py -k test_aot_compile_module_opted_out_advice_allows_the_raisers_own_accept python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warning_advice_follows_the_raiser_not_the_served python test/dynamo/test_aot_compile.py -k test_aot_compile_module_second_pass_warning_names_the_index_served python test/dynamo/test_aot_compile.py -k test_aot_compile_module_scan_warning_names_the_index_served python test/dynamo/test_aot_compile.py -k test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_once_per_model_not_per_process python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_once_per_exception_type_at_one_index python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warning_survives_a_raise_whose_str_raises python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_again_about_a_replaced_single_result python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_again_after_the_raiser_opts_out python test/dynamo/test_aot_compile.py -k test_aot_compile_module_does_not_warn_again_when_the_serve_moves python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warning_not_spent_by_an_interrupt_from_str python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warning_survives_a_serve_that_does_not_warn python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warning_is_not_spent_while_the_logger_drops_it python test/dynamo/test_aot_compile.py -k test_aot_compile_module_raise_from_an_opted_out_result_withholds_nothing python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serves_a_later_match_over_a_raising_leaf python test/dynamo/test_aot_compile.py -k test_aot_compile_module_serving_over_a_raise_frees_this_call_s_inputs python test/dynamo/test_aot_compile.py lintrunner --take RUFF,PYFMT torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py ``` The tests above were also run against the commit below's `torch/_dynamo/aot_compile.py` under this test file: they fail on `no logs of level WARNING or higher triggered on torch._dynamo.aot_compile`, and the interrupt one on `KeyboardInterrupt not raised`, since with no warning built there the `Boom` is never printed. Authored with the assistance of Claude Code. > **FAQ: a recorded raise can be discarded with nothing logged -- when a > later result's tree raises a `BaseException`, when a later result's bind > raises `TypeError`, and on two more exits of the same class: `_binds_alike`, > called after the inline check and under no handler, so a raise from > `_binding_key` drops `raised` as the bind's `TypeError` does, and > `_no_match_report` runs under no handler, so a `BaseException` out of its > `check_verbose` re-check or anything out of `_missing_global_hint` drops it > too. Record it before it is lost?** > > Declined, and the claim above states the rule rather than instances of it: > every path that RETURNS a graph with a raise on record logs one per index > that raised, every path that builds a report chains one, and a call that > ends before dispatch picks a result leaves as the exception that ended it > and records nothing, whatever ended it. The > bind case was measured on two results that do not bind alike -- > `ScaleModule`'s `forward(x)` at [0] under a stub tree that raises, and a > `forward(y, z)` at [1] -- called with one tensor: [0] is bound and checked > once and its raise recorded, then [1]'s bind raises `TypeError: missing a > required argument: 'z'`, and that is what leaves `__call__`, with nothing > logged, `__cause__` `None` and `__context__` an incidental `StopIteration` > out of `inspect`'s bind rather than the recorded raise, which the `except` > around [0]'s check had already handled to completion. Chaining the raise there > would assert a `__cause__` that is false -- the raise did not make the bind > fail -- and warning would need a text for a dispatch that served nothing, > where the one warning says `dispatch served [i]`. The two exits a guard > manager can produce are pinned in #197219: an interrupt out of a later tree > leaves `__call__` as itself with nothing logged, and the next call, with > that tree back, serves and logs the earlier raise; a later result's bind > raising `TypeError: missing a required argument: 'z'` leaves `__call__` > with nothing logged. The other two exits have no test because nothing > reachable produces them: `_binding_key` reads the artifact's own signature > parameters, `co_freevars` and closure cells, `_missing_global_hint` builds > a string from the artifact's own record, and a guard tree's raise arrives > as an `Exception` that neither sees. All four exits are the caller's own -- > a Ctrl-C, a call the model cannot take, an artifact or a report that could > not be built -- and none served a graph or described the call, so a warning > about a third artifact on the way out would be advice about a dispatch that > did not happen, logged while the caller holds an exception to read. Nor is > the raise gone from the process: a tree that raises raises again on the > next call that reaches it, and is recorded then. One more exit of the same > class is this commit's own: an interrupt out of the recorded exception's > `__str__`, raised while the warning quotes it, leaves `_warn_swallowed` > and discards the graph whose guards had passed. That one IS reported, on the > next call, because the one-shot is spent after `log.warning` and not before > -- `..._warning_not_spent_by_an_interrupt_from_str`. > **FAQ: the `Rejects` stub grows a `check_verbose` that nothing in this > commit calls -- every path here reads `check_nopybind`. Dead code; drop it > until something needs it?** > > Kept deliberately, and it is dead here: instrumented to raise on entry, the > whole file still passes. It is on the stub because a round-2 review of this > commit asked for it, so the fixture has the shape a report path quotes rather > than half of one, and its first caller is two commits up: #197179's > `test_aot_compile_module_no_match_does_not_suppress_a_handled_exception` > drives the no-match report over a `Rejects()`, and the report re-checks each > result with `check_verbose` -- with the method instrumented, the report reads > `[0] <guard check raised AssertionError: Rejects.check_verbose was reached>`, > so the stub is answering the call that path makes. Moving it up would have > two commits editing the same three-line stub for one method, and the stub is > this commit's own fixture. > **FAQ: the swallowed raise is logged with `log.warning`. Why not > `trace_structured`, so a production job can pull it out with `tlparse`?** > > Because this fires at dispatch time, on a per-call path with no compile > context, which is the wrong shape for a tlparse artifact twice over. Read > directly in `torch/_logging/_internal.py`: with `expect_trace_id` at its > default (`:1521`), a `trace_structured` call that finds no current trace id > captures a full `CapturedTraceback` into the record (`:1572`) to diagnose the > missing frame id, so the artifact would arrive attached to no frame and > carrying a stack of the dispatch call rather than of anything compiled. And a > raising guard tree raises on EVERY call that reaches it, so the payload would > repeat per call instead of once per compile, which is the granularity tlparse > presents. `log.warning` on `torch._dynamo.aot_compile` is where this file's > other runtime-divergence warnings already go (the registered-hooks and > overridden-`__call__` warnings), it reaches the same job log, and it is what > the warning tests here and in #197195 assert on. > **FAQ: the dedup key was `(index, exception type name)`, and the advice > text branched on `_guard_check_enabled` read afterwards, so an opt-out flip > after a warning silenced the opted-out advice. Why put the flag in the key > rather than reset the set when it flips?** > > Because the set is reset on one condition, that the results are not the > ones last warned about, and the flag is not a change of results: it lives > on the same object, so no comparison of weak references sees it, and a > reset would need a second record of every result's flag beside the first. > The key already names what the message is computed from -- the index and > the type -- and the flag is the third thing it is computed from, so the key > covers it and nothing else changes. The cost is one more warning per index > at most, when the caller flips the flag, which is the warning the flip > changed. > **FAQ: the two advice strings were ~250 and ~450 characters of prose in one > log line. Why cut them to a sentence each instead of keeping the reasoning > where the reader sees it?** > > Because the reader of a job log needs the decision and the remedy -- which > input raised, what it raised, which input was served, fix or drop the > raiser, and which way its next check can be wrong -- and each sentence now > says exactly that, in the shape of this file's other warnings (one > divergence, one remedy). The reasoning -- why a raise is served over rather > than refused, what a C++ throw leaves stale, why an opted-out tree is > charged only with a stale accept -- is the same for every warning, so it is > written once in the class docstring, which is where `help(AOTCompiledModel)` > takes the reader, not hard-wrapped into every line of a hot loop's log. Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: #197391 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390
… second pass (#197188) **Problem.** #196826 left three of its tests out for review budget: how the report quotes a raise that never crossed pybind, that `_unwrapped_raise` reads `__cause__` and not `__context__`, and what the report says when a tree raised in the scan and rejected on the second pass. **Fix.** Add those three tests and the `RaisesThenHits` and `NeverReChecked` fixtures they use. No source change. **Summary.** Test-only, split for review budget from `[aot_compile] Tolerate a guard tree that raises during module dispatch` (#196826), the commit directly below, whose `torch/_dynamo/aot_compile.py` this commit does not touch: it carries three tests that were written with that commit, on how the no-match report quotes a raise and on what the report says when a tree that raised in the scan rejects on the second pass. It adds the two fixtures they are the first users of -- `RaisesThenHits`, a colliding dict key whose first `raises` compares raise and whose later ones answer, and `NeverReChecked`, the base for a stub whose LAST evaluation raises in a test that builds a report, whose `check_verbose` raises a message naming the re-check so a regression that re-evaluates such a tree fails on that message rather than on an `AttributeError` dressed up as the tree's own raise. The two raise-line tests pin that a raise which never crossed the pybind boundary is quoted as itself with no `(through the guard tree's pybind boundary)` clause, and that `_unwrapped_raise` reads a `SystemError`'s `__cause__` and not its `__context__`, the only test of the four commits that tells the two attributes apart. The raised-then-answered test pins that a tree which raised in the scan and rejected on the second pass has the guard it rejected on quoted and no raise line, that the raise still withholds the opted-out last resort, that both advice lines appear, that the raise survives in the `from` chain alone, and that the report asked a third time (`key.compares >= 3`). The one change to a test this commit did not write is one line, re-basing #196826's `RaisingTree` stub on `NeverReChecked`, so the convention the base's docstring states holds from the commit that states it, and #197179 and everything above it apply on this file unchanged. ## Where this sits in the stack #196826 keeps the tests that pin what a caller sees change -- a later match served over a raise, a tree that raised in the scan served on its own second-pass accept, an opted-out result withheld by a raise, the no-match report surviving one, and two raisers read first by the report and then by the warning -- with all three of the warning's call sites, its dedup, its reset and its `init=False` field, the report's own `check_verbose` handler and the raise line's collapse. #197179, directly above, carries the report's remaining lines after a raise, and #197195 above it the warning's other paths, the exits that record nothing and the negative pins. After this commit the test file is #196826's plus these three tests, the two fixtures and one changed line -- the stub re-based on `NeverReChecked`, below -- so #197179 and everything above it apply on it unchanged. ## The two fixtures ```python class RaisesThenHits: # The mirror of HitsThenRaises: the first `raises` compares raise and every # later one answers, so a tree that raises in the dispatch scan rejects the # call cleanly on the second pass and can explain itself in the report. def __init__(self, raises): self.raises, self.compares = raises, 0 def __hash__(self): return hash("foo") def __eq__(self, other): self.compares += 1 if self.compares <= self.raises: raise ValueError(f"boom on compare {self.compares}") return True class NeverReChecked: """Base for a stub guard manager whose LAST check() raises in a test that builds a no-match report. ...""" def check_verbose(self, f_locals): raise RuntimeError("the report re-checked a tree that raised in dispatch") class RaisingTree(NeverReChecked): # parent: class RaisingTree: -- the one changed line ... ``` ## How the report quotes a raise ```python class RaisingGuardManager(NeverReChecked): def check(self, f_locals): raise RuntimeError("guard tree is unhappy") # never reaches pybind artifacts.guard_manager = RaisingGuardManager() model(x) # report line, asserted as an exact line of message.splitlines(), indent included: # [0] <guard check raised RuntimeError: guard tree is unhappy> # and "pybind boundary" appears nowhere in the message ``` `test_no_match_message_when_a_raise_did_not_cross_the_pybind_boundary`: a `TORCH_CHECK` inside the tree surfaces as a plain `RuntimeError` pybind translated at the boundary, with nothing chained, and this stub's raise never reaches pybind at all; either way the line quotes the exception itself and leaves off `(through the guard tree's pybind boundary)`, a clause that exists only to explain why a line quotes a chained exception rather than the one the tree raised. Both this test and the next pin the raise line as an exact line of `message.splitlines()`, indent included, as `test_no_match_message_survives_a_raising_guard` does. ```python class RaisingGuardManager(NeverReChecked): def check(self, f_locals): raise SystemError("stub tree is unhappy") try: raise Boom("the caller was handling this") except Boom: # __context__ of the SystemError is now Boom model(x) # reading __context__ would print: [0] <guard check raised Boom: the caller was handling this (through the guard tree's pybind boundary)> # the test pins: [0] <guard check raised SystemError: stub tree is unhappy> ``` `test_no_match_message_reads_the_cause_not_the_handled_exception`: `_unwrapped_raise` reads a `SystemError`'s `__cause__`, which `_PyErr_FormatFromCause` sets at that boundary, and not `__context__`, which PEP 3134 sets for ANY exception raised while another is being handled. A stub raising a bare `SystemError` from inside an `except Boom:` block separates the two: `__context__` would put `[0] <guard check raised Boom: the caller was handling this (through the guard tree's pybind boundary)>` in the report, and the test pins `[0] <guard check raised SystemError: stub tree is unhappy>` with neither the handled exception's text nor the boundary clause present. It is the only test of the four commits that tells the two attributes apart; every entry that quotes a real pybind boundary reads the same either way, since that call sets both. ## When a tree that raised is evaluated again ```python model = torch.compile(DictBranchModule(), ...) # [0] compiled for d={}, [1] for d=None model.forward.compiled_results[1].disable_guard_check() # arms x * 5 for a call no artifact guards key = RaisesThenHits(raises=1) model(x, {key: 1}) # scan: [0] raises on compare 1 # second pass: [0] rejects on its DICT_NOT_CONTAINS leaf (compare 2 answers) # report: asks a third time -> key.compares >= 3 # [0] not ___dict_contains('foo', L['d']) (no "[0] <guard check raised" line) # [1] <opted out of guard checks; withheld because [0]'s guard check raised> # "[0]'s raise, not a guard failure, is what withheld" ... "Add a ModelInput" # ctx.exception.__cause__ chain contains "boom on compare 1" ``` `test_no_match_message_quotes_a_tree_that_raised_then_answered`: [0] raises in the scan and rejects on the second pass -- `RaisesThenHits(raises=1)` on `DictBranchModule`'s `DICT_NOT_CONTAINS` leaf -- and [1] is opted out. The raise still withholds the opt-out, since dispatch cannot tell a raise that left nothing stale from a C++ throw whose later rejection stands on relational residue, but the raise is no longer all the report can say about [0]: the report quotes the guard it rejected on, `[0] not ___dict_contains('foo', L['d'])`, and no raise line; [1]'s line is the withheld opt-out; the fix-or-drop and `ModelInput` advice both appear; and the raise survives in the `from` chain alone, walked from `ctx.exception.__cause__` so that a report which quoted the raise itself and chained nothing could not satisfy it. `key.compares >= 3` pins that the report asked a third time rather than treating the raise as the entry's last word; a lower bound, since how often codegen has one evaluation probe a key is not this commit's business, and `raises=1` rests the same way on one probe per evaluation, as the comment beside it says. The same stub shape read the other way -- a tree that raised in the scan and ACCEPTS on the second pass, and is served on that accept -- is `test_aot_compile_module_serves_a_tree_that_raised_and_then_accepted` in #196826: it pins the second pass's serve, one of `warn_swallowed`'s three call sites and a path of the source that commit owns, so it sits there with the other two. ## The `NeverReChecked` convention Both report stubs here derive from `NeverReChecked`, added here as the base for a stub whose LAST evaluation raises in a test that builds a report: its `check_verbose` raises a message naming the re-check, which the report never reaches today, so a regression that re-evaluates such a tree fails on that message rather than on an `AttributeError` dressed up as the tree's own raise -- and aliasing `check_verbose` to `check` would print the raise line the test expects and let that regression pass. #196826 has one such stub of its own, the `RaisingTree` that `test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning` builds its two raisers from, and this commit re-bases it on the same base -- one line, the only change here to a test it did not write -- so the convention holds from the commit that states it. Measured, with `if i in unanswered:` forced to `if False:`: | stub | result under the mutant | | --- | --- | | the three stubs derived from `NeverReChecked` | fail on `the report re-checked a tree that raised in dispatch` | | #196826's TorchFunction test | fails on `dispatch key set mismatch` in [0]'s line, its real tree's `check_verbose` answering instead of throwing again | | the two-raiser test at #196826 itself, before the re-basing | fails on an `AttributeError` line, `<guard check raised AttributeError: 'Raises' object has no attribute 'check_verbose'>`, where the raise line asserted whole is expected -- the regression caught, less legibly | | both derived stubs here, with `check_verbose` aliased to `check` | pass | The one test that catches the alias, by its exact `checks` count, is `test_no_match_message_quotes_the_last_raise_at_one_index` in #197179. The five stubs of #197179 and #197050's `RejectsOnceThenRaises` derive from the same base, and `RaisesThenHits` is used again by #197050's own test and named in #197179's `HitsThenRaises` as its mirror; #196826 has no user for `RaisesThenHits`, and apart from the stub re-based above its stubs sit on serving paths and meet no report, while its describer test patches `check_verbose` on a real tree that answered in dispatch -- which is why both fixtures are added here, with the tests they were written for. That convention -- a stub whose last evaluation raises derives from `NeverReChecked`, one that answers and reaches the report defines its own `check_verbose`, one on a serving path meets no report and needs neither -- is stated once, in `NeverReChecked`'s docstring. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_no_match_message_when_a_raise_did_not_cross_the_pybind_boundary python test/dynamo/test_aot_compile.py -k test_no_match_message_reads_the_cause_not_the_handled_exception python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_a_tree_that_raised_then_answered python test/dynamo/test_aot_compile.py ``` The whole file runs 260 tests, `OK (skipped=6)`; #196826 runs 3 fewer. The three were also run against the `torch/_dynamo/aot_compile.py` of #196826's parent under this test file, and all three fail or error: two on the tree's own raise escaping the call (`SystemError: stub tree is unhappy`, and the pybind boundary's `SystemError` over `ValueError: boom on compare 1`), and the no-boundary test finding `guard tree is unhappy` alone where the report line is expected. Each fix in #196826 was then reverted on its own against the same three (and against #196826's eleven, #197179's ten and #197195's twelve, whose messages list their own), and only the named tests failed: ``` python test/dynamo/test_aot_compile.py -k test_no_match_message_reads_the_cause_not_the_handled_exception python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_a_tree_that_raised_then_answered python test/dynamo/test_aot_compile.py -k test_no_match_message_when_a_raise_did_not_cross_the_pybind_boundary ``` Reading `__context__` for `__cause__` in `_unwrapped_raise` fails `test_no_match_message_reads_the_cause_not_the_handled_exception` with the report quoting `Boom: the caller was handling this`. Appending the boundary clause to every raise line fails the no-boundary test and the `__cause__` test, each on its exact line gaining ` (through the guard tree's pybind boundary)` (and #196826's describer and two-raiser tests, and six report tests in #197179). Skipping an index in `raised` on the second pass fails `test_no_match_message_quotes_a_tree_that_raised_then_answered` with `key.compares` reading 1 where at least 3 are expected (and #196826's raised-then-accepted test, and three report tests in #197179), since the call then falls through to a report about a tree that was never re-evaluated. Removing the veto's `_guard_check_enabled` gate fails the same raised-then-answered test with `dispatch served 5.0, not a raise` (and #196826's opted-out test, and three in #197179). Making the dispatch handler re-raise fails all three, on the raise escaping the call. Forcing `if i in unanswered:` to `if False:` fails `test_no_match_message_when_a_raise_did_not_cross_the_pybind_boundary` and `test_no_match_message_reads_the_cause_not_the_handled_exception` on `the report re-checked a tree that raised in dispatch` (and #196826's two-raiser test on the same message once its stub derives from the base here, and its TorchFunction test on `dispatch key set mismatch` in [0]'s line); with `check_verbose` aliased to `check` under the same mutation, nothing here fails, which is the hazard the base's docstring names. Widening either handler to `BaseException`, making the report's `check_verbose` handler re-raise, reading the warning's raiser off the served index, restoring the old `rejected this call twice` wording, never starting the dedup over and gating its reset on two or more results fail nothing here: the middle four are pinned by #196826's describer, later-match, inconsistent-guard and replaced-single-result tests, the first by #197195's interrupt test. Authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #197188 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391
…fter a raise (#197179) **Problem.** The no-match report's remaining lines after a raise were unpinned: the last raise per index, the advice kept beside a raise, a raise that happens only while explaining, and that an ordinary no-match does not suppress an exception the caller was handling. **Fix.** Four tests and two fixtures pin them, and three existing tests gain one reading each. No source change. **Summary.** This is a test-only commit, split for review budget from `[aot_compile] Tolerate a guard tree that raises during module dispatch` (#196826), four commits below, whose `torch/_dynamo/aot_compile.py` it does not touch. The tests here pin how the no-match report's other lines read once a raise is on record -- beyond the raise line itself and the second pass, which #197188, directly below, pins -- and one thing the parent already did that the report keeps doing: an ordinary no-match raises bare, so the exception a caller was handling stays in the traceback. Four tests are new (`test_no_match_message_quotes_the_last_raise_at_one_index`, `test_no_match_message_keeps_the_advice_beside_a_raise`, `test_no_match_message_when_only_the_report_raises` and `test_aot_compile_module_no_match_does_not_suppress_a_handled_exception`), backed by two fixtures with one user each, the key class `HitsThenRaises` and the stub tree `RaisesPerPass`. Three tests owned by commits below gain one reading each -- an `assertNotIn` on the opted-out raiser's text, a `__cause__ is None` reading, and a count of ` [` entry lines -- because each was already the construction a previous revision of this PR duplicated, and a mutant analysis found no reading the duplicates made that the existing tests did not (the FAQs below record each deletion). Every test listed under the Test Plan was run against the parent's `aot_compile.py` and against each fix in #196826 reverted on its own; the Test Plan names which test pins which decision. ## Where this sits in the stack The two fixtures: the key class `HitsThenRaises` sits between `RaisesOnCompare` (#196826) and `RaisesThenHits` (#197188), whose comment now states the rule over every key in that group rather than counting them, and the stub tree `RaisesPerPass` sits beside `RaisingTree`. ```python class HitsThenRaises: # the first `hits` compares answer; every later probe raises def __eq__(self, other): self.compares += 1 if self.compares > self.hits: raise ValueError(f"boom on compare {self.compares}") return True class RaisesPerPass(NeverReChecked): # every check() raises a message naming the pass it is on def check(self, f_locals): self.checks += 1 raise RuntimeError(f"pass {self.checks} unhappy") ``` Tests below gain one reading each: #197390's `test_aot_compile_module_two_raisers_in_the_report` (renamed by #197391 to `..._and_then_the_warning`), #197188's `test_no_match_message_quotes_a_tree_that_raised_then_answered` and #197390's `test_no_match_report_describes_the_other_entries_when_one_raises`. The warning's other paths and one more thing the parent already did are #197195, directly above, which adds its tests around these without touching them; the exits that record nothing are #197219, further up. Reviewed bottom-up, #197188 carries one forward reference to `HitsThenRaises`, which arrives here (FAQ below). ## The report, after a raise ### The last raise at one index ```python model = self._model_with_stub_trees(RaisesPerPass()) with self.assertRaises(RuntimeError) as ctx: model(torch.randn(3, 3)) lines = str(ctx.exception).splitlines() lines[1] # " [0] <guard check raised RuntimeError: pass 2 unhappy>" str(ctx.exception.__cause__) # "pass 2 unhappy" -- the chain reads the overwritten raise too ``` `test_no_match_message_quotes_the_last_raise_at_one_index`: both dispatch passes evaluate an enabled tree, so one index can raise twice with two exceptions; `raised[i]` is overwritten in place, so the report quotes the later one, `pass 2 unhappy`, read off the entry line at a fixed index. #197390's `test_no_match_report_reads_the_dispatch_record_after_a_raise`, which this commit files the test directly after, pins that entry line already, at its [1]; what this one-input twin adds is the chain. The report chains the first index that raised, so with one input `__cause__` is the overwritten exception and reads `pass 2` too -- a reading the two-input test cannot make, its chain being [0]'s only raise (measured below, and FAQ). The pass the text names is the stub's `check()` count, so the count needs no assertion of its own: every `check()` on this path is inside a handler that overwrites `raised[i]` or re-raises, and the report re-checks no index that was left unanswered, so one pass too few or too many moves the quoted text (measured below). ### The chain versus the advice The chain carrying the FIRST index that raised while the advice names the first ENABLED one is #197390's two-raisers test, which already pins the withheld line, the raise line asserted whole past two separators, the entry count, the advice at a fixed index and `__cause__`; this commit adds the one reading it lacked, that the opted-out raiser's text reaches the chain and nowhere in the report -- its line is the withheld opt-out and quotes no exception text, so `__cause__` is the only record of its raise: ```python self.assertNotIn("the opted-out tree is unhappy", str(ctx.exception)) # added here self.assertEqual(str(ctx.exception.__cause__), "the opted-out tree is unhappy") # already there ``` A previous revision had a test of its own for that shape; every assertion but one was that test's, so it is folded into it instead (FAQ below). ### The advice beside a raise ```python model, x = self._aot_compile_mode_branches() model.forward.compiled_results[0]._artifacts.guard_manager = RaisingTree("the scanned tree is unhappy") del globals()["AOT_BRANCH_SCALE"] # restore registered first, as _install_global_probe does with self.assertRaises(RuntimeError) as ctx: model(x, 2) lines = str(ctx.exception).splitlines() # exactly 6 lines # [0] header # [1] " [0] <guard check raised RuntimeError: the scanned tree is unhappy>" # [2] " [1] KeyError on G['AOT_BRANCH_SCALE'] ..." # [3] "For [1]: a guarded global is missing ..." # [4] "[0]'s guard check raised while checking this call ..." # [5] "Add a ModelInput covering this call ..." ``` `test_no_match_message_keeps_the_advice_beside_a_raise`: a missing global and a raiser in one report, where the missing global's own hint and the fix-or-drop line stand on disjoint entries while the `ModelInput` line, which every report ends with, stands on none -- it is about the uncovered `mode=2` call itself. It pins that order at fixed indices, a six-line report read at `lines[3]`, `[4]` and `[5]`, which pins that the three advice lines are adjacent and last as well and reads a dropped one as a message diff rather than as a search that finds the next line along, and then reads what those lines are about: the hint is addressed `For [1]:`, the entry that named the global, and the fix-or-drop line is the branch the report took with no opt-out in the list, `[0]'s guard check raised while checking this call`. It captures through the `_aot_compile_mode_branches` fixture, which hides the leaked Dynamo globals as the stub-tree tests here do, and registers the global's restore before deleting it, as `_install_global_probe` does and says, so an interrupt in between leaves it in place. The other branch of that advice, the withheld one a third opted-out input reaches, is pinned at a fixed index by #197390's two-raisers test and asserted in the message by #197188's raised-then-answered test; a previous revision had a three-input copy here for it, which no mutant separated from this test (FAQ below). The shape that made #196826 reword the re-check line -- pass 1 raised, pass 2 rejected, the report accepted, so the line has to count no second rejection -- is pinned by #197390's own `test_no_match_report_reads_the_dispatch_record_after_a_raise`; a previous revision of this PR carried a one-input copy of it whose every assertion that test already makes, so the copy is gone (FAQ below). ### A raise only in the report ```python model, x = self._aot_compile_dict_branches({}) key = HitsThenRaises(hits=2) # compares 1 and 2 answer (dispatch pass 1 and 2); compare 3 raises (the report) with self.assertRaises(RuntimeError) as ctx: model(x, {key: 1}) message = str(ctx.exception) " [0] <guard check raised ValueError: boom on compare 3 (through the guard tree's pybind boundary)>" in message.splitlines() "Add a ModelInput" in message # an ordinary mismatch missing its reason ctx.exception.__cause__ # None: only a dispatch raise is chained "fix or drop that artifact" not in message # nothing raised in dispatch names an artifact ``` `test_no_match_message_when_only_the_report_raises`: both dispatch passes got a clean rejection out of a live `DICT_NOT_CONTAINS` tree -- the guard found the key and rejected the call -- and only the re-check that explains why raised, so the entry carries the raise itself and the `ModelInput` advice still applies. The entry line is asserted whole against `splitlines()`, as every other entry-line assertion here is, and this is the file's only report-side raise that crosses the guard tree's pybind boundary, so the `(through the guard tree's pybind boundary)` clause on it is the report caller's own unwrap. `_raised_line` prints the same line from either of its two call sites -- the branch that quotes what dispatch's handler recorded, and the report's own handler around `check_verbose` -- so the test also pins the two readings a dispatch raise would change and a report raise does not: `__cause__` is None, since only a dispatch raise is chained, and no `fix or drop that artifact` line, since nothing raised in dispatch names an artifact. The first of those two is what this commit adds to #197390's `test_no_match_report_describes_the_other_entries_when_one_raises`, the stub-grade test of the same shape -- dispatch rejects cleanly, a patched `check_verbose` raises -- which pins the report line whole and the `Add a ModelInput` line at `lines[3]` but read neither; the fix-or-drop absence needs no assertion of its own there, that line being emitted immediately above the `ModelInput` one, so a report that emitted it moves `Add a ModelInput` off `lines[3]` (measured below). A previous revision had a stub twin of its own here instead, whose readings that test already made (FAQ below). `boom on compare 3` is the report's third evaluation of the key, the one it made rather than reusing a dispatch answer: `hits=2` rests on one probe per evaluation, and codegen that probed the key twice per `check()` would move the raise into dispatch pass 2 with that entry line reading the same, which is why the two readings above matter here. Measured, in an earlier revision of this PR, with a wrapper around the real guard manager that calls `check()` twice: | assertion | against the double-`check()` wrapper | | --- | --- | | entry line and `ModelInput` | pass | | `assertIsNone(__cause__)` | fails, the pybind `SystemError` as the cause | | `assertNotIn("fix or drop that artifact")` | fails, the report reading `[0]'s guard check raised while checking this call; fix or drop that artifact.` above the same entry line | ### One entry line per input #197188's raised-then-answered test -- [0] raises in the scan and rejects on the second pass, which still withholds opted-out [1], and the report quotes the rejection while the `from` chain keeps the raise -- gains one assertion, counting the report's ` [` entry lines against one per input: ```python self.assertEqual(sum(ln.startswith(" [") for ln in message.splitlines()), 2, message) ``` Dropping the `continue` in the report's withheld branch, so an opted-out result is described once as the opt-out it is and then again by the guards nobody asked about, shows up as the extra line it is (measured below). A previous revision had a stub twin of that test for this count; its assertions were the leaf test's, string for string, so the count lands there instead (FAQ below). The `NeverReChecked` convention itself is exercised here by the module-level `RaisesPerPass` in the last-raise test and by `RaisingTree` in the advice-order test, and below by #197390's two-raisers test and by #197188; what the trees here catch is measured below. ## One thing the parent already did, kept ```python try: raise Boom("the caller was handling this") except Boom: with self.assertRaises(RuntimeError) as ctx: model(torch.randn(3, 3)) # an ordinary no-match, stub tree Rejects() ctx.exception.__suppress_context__ # False: raised bare, not `from None` ctx.exception.__context__ # the Boom ``` `test_aot_compile_module_no_match_does_not_suppress_a_handled_exception`: an ordinary no-match raises bare rather than `from None`, so `__suppress_context__` is False and the exception a caller was handling stays in the traceback. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_the_last_raise_at_one_index python test/dynamo/test_aot_compile.py -k test_no_match_message_keeps_the_advice_beside_a_raise python test/dynamo/test_aot_compile.py -k test_no_match_message_when_only_the_report_raises python test/dynamo/test_aot_compile.py -k test_aot_compile_module_no_match_does_not_suppress_a_handled_exception python test/dynamo/test_aot_compile.py -k test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_a_tree_that_raised_then_answered python test/dynamo/test_aot_compile.py -k test_no_match_report_describes_the_other_entries_when_one_raises python test/dynamo/test_aot_compile.py ``` The whole test file passes, and `lintrunner --take RUFF,PYFMT test/dynamo/test_aot_compile.py` is clean. The tests here were also run against the `torch/_dynamo/aot_compile.py` of #196826's parent (#196909) under this test file: the report-raise test fails on `ValueError: boom on compare 3` escaping the call through the pybind `SystemError`; the advice test on the report line that is not there (`' [0] <guard check raised RuntimeError: the scanned tree is unhappy>' not found in ['the scanned tree is unhappy']`); and the last-raise test on the same reading, the message being the raise itself with no entry line to read at all (`IndexError` on `lines[1]`) -- while the one that pins what the parent already did passes, as it should; `raise RuntimeError(report) from None` fails it on `__suppress_context__`. Each fix in #196826 was then reverted on its own against the whole file; the tests named below are the ones that pin each decision, not every test the revert fails (#197195's message lists its own): ``` python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_the_last_raise_at_one_index python test/dynamo/test_aot_compile.py -k test_no_match_message_keeps_the_advice_beside_a_raise python test/dynamo/test_aot_compile.py -k test_no_match_message_when_only_the_report_raises python test/dynamo/test_aot_compile.py -k test_aot_compile_module_no_match_does_not_suppress_a_handled_exception python test/dynamo/test_aot_compile.py -k test_no_match_report_describes_the_other_entries_when_one_raises python test/dynamo/test_aot_compile.py -k test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_a_tree_that_raised_then_answered python test/dynamo/test_aot_compile.py -k test_no_match_report_reads_the_dispatch_record_after_a_raise python test/dynamo/test_aot_compile.py -k test_aot_compile_module_restores_torch_function_after_a_throw ``` Making the report's `check_verbose` handler re-raise fails the report-raise test on `ValueError: boom on compare 3` escaping as the pybind `SystemError`, and #197390's describer test on `ValueError: boom`. Recording a report-handler raise in `raised` fails the reading this commit adds to that describer test (`ValueError('boom') is not None` on `__cause__`) and the report-raise test on the same reading with the `SystemError` as the cause; it emits no fix-or-drop line, `raiser` being decided before the entry loop, so it is the mutant for `__cause__` and not for that line's absence. Emitting the fix-or-drop line for every raiser instead (`elif raiser is not None:` to `else:`) is: it fails the describer test on `assertIn("Add a ModelInput", lines[3])`, which reads `[None]'s guard check raised while checking this call; fix or drop that artifact.`, and the report-raise test on its own `assertNotIn`. Dropping the raise line's two-space indent fails every test here that asserts an entry line whole, and nothing else here. Dropping the raise line's separator collapse fails, in this file, #197390's two-raisers test alone, on its raise line asserted whole; narrowing the collapse to `line.replace("\x0c", " ").replace("\x1e", " ")` fails no test in this file, that test's message carrying those two separators and no others -- which is why the four-separator pin lives in #196826, beside the collapse (FAQ below). Making both dispatch handlers re-raise fails the advice test on the report line missing and the last-raise test on its entry line, the message being the raise itself with nothing to read there (`IndexError` on `lines[1]`), while the report-raise test and the negative pin pass, neither depending on a dispatch raise. Forcing `if i in unanswered:` to `if False:`, so nothing is re-checked, fails the `NeverReChecked` stub trees here on the re-check message (` [0] <guard check raised RuntimeError: the report re-checked a tree that raised in dispatch>`); with `NeverReChecked.check_verbose` delegating to `check()` under the same mutation, only the last-raise test still fails here, on `pass 3 unhappy` where `pass 2` is expected, the others passing. Skipping an index in `raised` on the second pass (`if i not in raised and accepts(i, result)`) fails the last-raise test here on its entry line reading `pass 1 unhappy`, the tree never re-evaluated, and `..._reads_the_dispatch_record...` on its `[stub.checks for stub in stubs]` count (`Expected 2 but got 1`). `raised.setdefault(i, e)` fails the last-raise test the same way and `..._reads_the_dispatch_record...` on its `pass 2 unhappy` entry line. Chaining each index's FIRST raise while the entry line quotes its last (a second dict filled by `setdefault`, chained instead of `raised`) fails the last-raise test alone, on `__cause__` reading `pass 1 unhappy`; the two-input test passes it, its chain being [0]'s only raise. Chaining `raised[raiser]` instead of `next(iter(raised.values()))` fails nothing here and the two-raisers test with `__cause__` reading `checked\x0ctree\x1eis unhappy` where `the opted-out tree is unhappy` should be. Hinting entry 0 instead of the entry that named the global (`hinted.setdefault(hint, []).append(0)`) fails the advice test on `lines[3]` reading `For [0]: a guarded global is missing ...`, and moving the hint loop below the advice fails it on the same line reading the fix-or-drop text. Widening the withheld sentence to every raiser (`if withheld:` to `if raiser is not None:`) fails the advice test on `lines[4]` reading `[0]'s raise, not a guard failure, is what withheld ...` and none of the others here; dropping the no-opt-out advice altogether (`elif False:`) fails it on `Expected 6 but got 5` lines and `..._reads_the_dispatch_record_after_a_raise` on the `[0]'s guard check raised` advice it asserts, and appending one more line to every report fails the advice test on `Expected 6 but got 7`, which the searched indices this test used before pass. Dropping the withheld sentence itself (`if withheld:` to `if False:`) fails the two-raisers and raised-then-answered tests on the advice line and no test here, this report having no opt-out in it; the same two are the tests that catch forcing the last-resort gate, `if not any(map(enabled.__getitem__, raised)):`, to `if True:` (`RuntimeError not raised` and `dispatch served 5.0, not a raise`), and the ones that catch dropping `withheld because [{raiser}]'s guard check raised` from the opt-out line. Dropping the `continue` in the report's withheld branch fails nothing here, #197188's raised-then-answered test on the count this commit adds to it (`Expected 2 but got 3`, its two inputs allowing two entry lines) and the two-raisers test on its own count; with that count and its fixed advice index taken out, the assertion this commit adds to it catches the same mutant on `'the opted-out tree is unhappy' unexpectedly found` in the report. Restoring the old "rejected this call twice and then accepted" wording fails nothing here: `..._reads_the_dispatch_record_after_a_raise` asserts that line whole, and #196823's two tests assert it through `_ACCEPTED_IN_THE_REPORT`. `raise RuntimeError(report) from None` fails the negative pin alone here, on `__suppress_context__`. The other reverts -- reading the warning's raiser off the served index, keying the warning on the `SystemError`, never starting the dedup over or gating its reset, deciding the dedup pair at the raise, widening `accepts()`' handler to `BaseException`, moving the bind inside its `try`, warning on a rejection, letting `_warned` into the constructor and rebinding every pass -- fail nothing here; each fails a named test in #197195 or #196826, whose messages list them. > **FAQ: #197390's two-raisers test already asserts a raise line whole past > two of these four separators; what does a test of its own for the collapse > add?** > > Nothing here any more: that test now lives in #196826, beside the > `_raised_line` collapse it pins, with its `\r` and `\u2028` readings. > **FAQ: #197188 below has a comment reading "The mirror of `HitsThenRaises`" > while `HitsThenRaises` is added here; why not move the class down or reword > that comment?** > > Because both of those rewrite #197188, which this review window treats as > landed: its latest review approved it, so its patch is frozen here. It holds > no `pytorchgreenlight[bot]` or human approval and its CI is gated by its > `[no-ci]` title, so what a new head there costs is not a dismissed approval > or a restarted CI run but another review pass on a commit whose patch has not > changed, for one word in a comment. So the ordering is recorded here > instead. Nothing below this commit > imports, subclasses or runs `HitsThenRaises` -- the reference is one word in > a comment on its mirror, whose own behaviour that comment describes in full > ("the first `raises` compares raise and every later one answers") -- and the > class sits directly above `RaisesThenHits` here, so the two read together > from this commit on. If #197188 is reopened for a reason of its own, the > class belongs in it. > **FAQ: the new `RaisesPerPass` counts `check()` calls and raises a message > per pass, which is what `class RaisesTwice(RaisesThenRejects)` in #197390's > `..._reads_the_dispatch_record_after_a_raise` does; why not reduce that one > onto it?** > > Because `RaisesTwice` chains its raise from a `ValueError` that test asserts > absent from the report, which `RaisesPerPass` does not, and it carries > `RaisesThenRejects`'s accepting `check_verbose` -- unreachable there, since a > stub that raises on every `check()` is never re-checked -- rather than > `NeverReChecked`'s raising one, the convention a re-check regression is meant > to trip (measured: giving `RaisesTwice` a `check_verbose` that raises leaves > that test passing). Rebasing it onto `RaisesPerPass` would have to re-add the > chained raise by hand, saving no lines, in a commit below that this round has > frozen. What the two tests did share and no longer do is the name > `RaisesTwice` and a transposed message; the module-level fixture here is > `RaisesPerPass` and both now read `pass N unhappy`, so the twins read as > twins. > **FAQ: a previous revision had > `test_no_match_message_keeps_the_advice_beside_a_withheld_opt_out`, a > three-input copy of the advice-order test whose report carried a withheld > opt-out; where did it go?** > > Deleted, because no mutant separates it from what is left. Its shape -- a > raiser, a missing global and an opted-out third input -- reads the withheld > branch of the fix-or-drop advice, and that branch is already pinned at a > fixed line index by #197390's two-raisers test and asserted in the message by > #197188's raised-then-answered test. Measured over the mutants it could > catch: dropping the withheld sentence and forcing the last-resort gate are > caught by those two tests below (readings above), and hinting entry 0, > widening the withheld sentence to every raiser and dropping the no-opt-out > advice are each caught by the two-input `..._keeps_the_advice_beside_a_raise` > that stays. Nothing it read was unique to three inputs, and its third input > cost a float64 dtype and a paragraph of comment to stay unsatisfiable, `mode` > having gone dynamic by that trace. > **FAQ: why does a test-only commit add a line to a test #197390 owns > instead of keeping its own test for the chain-versus-advice split?** > > Because that test and #197390's two-raisers test were the same > construction -- two `ScaleModule` inputs, a `RaisingTree` taking a message, > [0] opted out with `the opted-out tree is unhappy`, [1] raising -- and every > assertion but one (the withheld line, the raise line, the `not a guard > failure` advice, `__cause__`) was already made there, where the raise line > also carries two separators and the advice sits at a fixed index. Its one > new reading, that the opted-out raiser's text is absent from the report, is > one `assertNotIn` beside the `__cause__` assertion that already reads the > same exception; measured above under the dropped `continue` with the test's > count and index pins taken out, it catches that mutant on its own. The line > lands here rather than in #197390 because this is the commit that adds the > reading; folding it down would move a line across a PR under separate > review for no change in what either pins. > **FAQ: the re-check-only shape had a leaf/stub pair; why is the stub twin > gone, and why does the raised-then-answered shape get no stub twin of its > own?** > > Because #197390's > `test_no_match_report_describes_the_other_entries_when_one_raises` is already > the stub twin: it patches `check_verbose` to raise while dispatch rejects > cleanly, asserts the report line whole and the `Add a ModelInput` line at a > fixed index. A previous revision of this PR had > `test_no_match_report_quotes_a_stub_that_raises_only_in_the_re_check`, a > second copy of that construction, whose report readings that test already > made string for string; what it read past them was `__cause__`, which is the > one assertion this commit adds there instead -- measured above, it is what > catches recording a report-handler raise in `raised`, and the surviving leaf > test `test_no_match_message_when_only_the_report_raises` reads it too, with > the real guard tree under it. A stub twin of #197188's > `..._quotes_a_tree_that_raised_then_answered` would add less again: every > message reading in that shape is a string equality no leaf behaviour moves, > and its `key.compares` lower bound is already codegen-independent. A > previous revision had such a twin; its assertions were the leaf test's, and > its one new reading, the ` [` entry-line count, lands as well on the leaf > test's report -- measured above, it fails there on the extra entry line under > the dropped `continue`. > **FAQ: a previous revision had > `test_no_match_message_after_a_raise_counts_no_second_rejection`, a one-input > stub that raised, rejected and then accepted in the re-check; where did it > go?** > > Nowhere: #197390's > `test_no_match_report_reads_the_dispatch_record_after_a_raise` is the same > construction at its [0] -- a raise on the first `check()`, `False` after, > `check_verbose` answering `result=True` -- and makes every assertion the copy > made: the accept line whole, `checks` at 2, `__cause__` and the absence of > the raise's text from the report, the `[0]'s guard check raised` advice. One > input instead of two reaches no other branch for [0]: `unanswered.discard(0)` > runs on pass 2 in both, nothing is opted out in either, and the first index > that raised is 0 in both. Measured with the copy deleted: the wording, > skip-raised and never-re-checked mutants above each still fail that test on > the reading the copy pinned, and the accept line the copy carried as a > 200-character literal is asserted there and, through > `_ACCEPTED_IN_THE_REPORT`, in #196823's two tests. > **FAQ: `test_no_match_message_quotes_the_last_raise_at_one_index` reads the > same overwrite as that same test's entry line; why keep it rather than fold > its `__cause__` reading into it?** > > Because that test cannot make the reading. The report chains > `next(iter(raised.values()))`, the first index that raised, which there is > [0], a stub that raised once; its twice-raiser sits at [1] and reaches the > chain only if the stubs swap places, which relabels every entry line and the > `[0]'s guard check raised` advice that test asserts, and moves the accept > line to the second entry. A one-input twin puts the twice-raiser at the head > of the chain with no such churn; measured above, the mutant that chains each > index's first raise passes the two-input test and fails this one alone. The > shared entry-line assertion stays because it is what makes the test readable > on its own -- the same rule, entry line and chain agreeing, at one index -- > and its comment names the chain as the reading it adds. Authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #197179 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188
…aths, text and dedup (#197195) **Problem.** #197391's swallowed-raise warning had its main path covered but not the rest: which other serving paths log it, what it names behind a pybind `SystemError`, when it stays silent, and that its dedup resets when the results change. **Fix.** Five tests pin those, plus two assertions added to an existing test. No source change. **Summary.** Test-only, split for review budget from `[aot_compile] Warn once per defect when module dispatch serves a graph over a raise` (#197391), three commits below, whose `torch/_dynamo/aot_compile.py` this commit does not touch. The five tests here are the rest of the swallowed-raise warning's coverage: which serving paths log it and about which index (the second pass and the last resort), what it names (the exception behind a pybind `SystemError`, keyed into the dedup), when it is silent (an ordinary dispatch that walks past a non-matching input), and that it is logged once per defect and starts over when `compiled_results` changes. They are written on what the stack already has -- the `RaisingTree`, `Rejects` and `Accepts` stubs and the `_model_with_stub_trees` helper, as #197391's warning tests are -- except `ordinary_dispatch` and the unwrap test, which need the real trees, and the second-pass test's stub `RefusesThenAccepts`, the one with no twin. Two assertions land in #197391's `warns_once_per_model_not_per_process` (`dispatch served [0]`, and `_warned` absent from `AOTCompiledModel`'s constructor signature, the one pin `init=True` on that field fails), and #196826's `RaisesOnCompare` gains an `exc` parameter defaulting to the `ValueError` it raised before; those are this commit's only changes to existing tests and fixtures. Each fix in #197391 or #196826 that these tests cover was reverted on its own and the file run against it, and the Test Plan records which test each mutation fails and on what reading. ## Where this sits in the stack The tests about the exits that record a raise nowhere and the one bind per result are `[aot_compile] Pin the raise-tolerant module dispatch's exits and binding` (#197219), above. `[aot_compile] Tolerate a guard tree that raises during module dispatch` (#196826), five below, pins what a caller sees change; #197390 the records, serves and exits on stub trees; #197391 the warning's dedup on a one-result model and which index each serving site names; #197188 the raise line and the raised-then-answered report; #197179, directly below, the no-match report's other lines once a raise is on record. Only a pybind boundary produces the `SystemError` the unwrap test is about, so it takes the file's `_aot_compile_dict_branches` model, the one #196826's `raise_from_an_opted_out_result_withholds_nothing` calls, and extends that call with the warning half; that test stays where it is, being #196826's own reading of the change that stops the raise reaching the caller. Placement: two of the five tests sit among #197391's warning tests; the second-pass and last-resort tests sit just above #197390's `serves_a_tree_that_raised_and_then_accepted`, after #197049's function-side TorchFunction-restore test; the unwrap test sits directly after #197391's parametrized `warns_before_the_served_graph_runs`, last of that block. ## The second pass logs one line about the raiser ```python class RefusesThenAccepts: # RaisesThenAccepts with a rejection where its scan raise is. def check(self, f_locals): self.checks += 1 return self.checks > 1 stub = RefusesThenAccepts() model = self._model_with_stub_trees(RaisingTree("both passes are unhappy"), stub) with self.assertLogs("torch._dynamo.aot_compile", level="WARNING") as logs: model(x) # == x * 2, served by [1] on the second pass stub.checks # 2: rejected in the scan, accepted on the second pass len(logs.output) # 1: "[0]'s guard check raised RuntimeError: both passes are unhappy" ... "dispatch served [1]" ``` `test_aot_compile_module_second_pass_warns_that_it_served_over_a_raise`: nothing matched in the scan and the second pass found a match in a result other than the one that raised, so that call site's warning is the one that records the raise, and the stub's `checks` count says the serve was the second pass's. #197391's `second_pass_warning_names_the_index_served` has the same second pass serve [1] over [0]'s raise, with [1] raising in the scan as well and two warnings logged; here [1] rejected there instead. That a rejection logs nothing is already pinned by #197391 -- its scan and last-resort site tests each put a `Rejects()` beside the raiser and count one line -- so what this test adds is the SECOND-PASS site logging one line when the result it serves rejected in the scan rather than raised there. That is why it fails both `accepts()` mutations below, on its warning count and on `stub.checks`, where its named twin passes. ## The last resort names the raiser, not the served index ```python unhappy = RaisingTree("the second tree is unhappy") model = self._model_with_stub_trees(Rejects(), unhappy, opt_out=True) # both results opted out with self.assertLogs("torch._dynamo.aot_compile", level="WARNING") as logs: model(x) # == x * 2, the last resort serves the FIRST opted-out result, [0] unhappy.checks # 2: raised in the scan and again on the second pass len(logs.output) # 1: "[1]'s guard check raised RuntimeError: the second tree is unhappy" ... "dispatch served [0]" "[0]'s guard check raised" in warned # False: no warning made up for the served index ``` `test_aot_compile_module_last_resort_warns_about_another_index`: the last resort serves the FIRST opted-out result, which need not be the one that raised, so the warning reads the raiser off `raised` and the served index off the loop, and `[0]'s guard check raised` appears nowhere. `opt_out=True` opts out BOTH results, so [1]'s raise vetoes nothing; with [1] enabled that raise would veto the last resort and the call would raise the no-match report instead of reaching a serve. #197391's two-raisers test pins the same reading with both of its results raising; here [0] never raised, so that last assertion -- no warning made up for the served index -- is the one that test cannot make, and why this one stands on its own. [1] raises in the scan and again on the second pass -- `unhappy.checks == 2`, as the second-pass test reads its stub -- and `len(logs.output) == 1` is one line about those two raises. ## The warning unwraps the pybind boundary's `SystemError` ```python class RaisesOnCompare: def __init__(self, message="boom from __eq__", exc=ValueError): # parent: no exc; always ValueError ... def __eq__(self, other): raise self.exc(self.message) model, x = self._aot_compile_dict_branches({}, None) model.forward.compiled_results[0].disable_guard_check() with self.assertLogs("torch._dynamo.aot_compile", level="WARNING") as logs: model(x, {RaisesOnCompare(): 1}) # x * 2 model(x, {RaisesOnCompare(exc=TypeError): 1}) # x * 2 # two lines: "[0]'s guard check raised ValueError: boom from __eq__" and "... TypeError: boom from __eq__" "SystemError" in warned # False ``` `test_aot_compile_module_warning_unwraps_a_pybind_boundary_raise`: the warning names the exception behind the `SystemError` and keys its dedup on it, so a `ValueError` and a `TypeError` from two colliding keys at one index log twice and `SystemError` appears in neither line. The model and setup are `raise_from_an_opted_out_result_withholds_nothing`'s -- [0] raises through its `DICT_NOT_CONTAINS` leaf, [1] rejects the dict without probing it, so opting [0] out arms the last resort and its own raise vetoes nothing. The `TypeError` is `RaisesOnCompare(exc=TypeError)`: the class gains an `exc` parameter defaulting to the `ValueError` it raised before, so its seven existing callers are unchanged and the collision trick and its comment stay in one place. ## Once per defect, and again after `compiled_results` changes ```python zero, one = RaisingTree("zero is unhappy"), RaisingTree("one is unhappy") model = self._model_with_stub_trees(zero, one, Accepts()) results = model.forward.compiled_results model(x) # two warnings, each naming its raiser, both "dispatch served [2]" model(x) # silent: once per defect, not once per call results.pop(0) # compiled_results is public; the artifact at [0] is now `one` model(x) # one warning: "[0]'s guard check raised RuntimeError: one is unhappy" ... "dispatch served [1]" model(x) # silent again ``` `test_aot_compile_module_warns_again_about_a_replaced_index`: the model is `_model_with_stub_trees(zero, one, Accepts())`, two broken artifacts, so the first call is two warnings, each naming its raiser and `dispatch served [2]`, and the next call is silent -- once per defect, not once per call. Then `compiled_results` is public, so after a `pop(0)` the artifact at a warned-about index is a different one: the `(0, "RuntimeError", True)` on record described `zero`'s raise, not `one`'s, and it warns again, naming `one is unhappy` at [0] and `dispatch served [1]`; the call after that is silent. Its one-result twin in #197391 is what tells a reset judged at the warning from one tied to the binding verdict (two results are left after the pop, so a reset hung off the binding verdict would fire here too); this test is the many-result reading of the same reset. An earlier revision pinned the first two calls in a test of their own, `warns_about_every_input_that_raised`; it walked this test's first two blocks step for step under other stub texts, so its three text assertions moved here and it is gone. ## Ordinary dispatch is silent ```python model._aot_compile([ModelInput(args=(torch.randn(3, 3, dtype=torch.float64),), ...), ModelInput(args=(torch.randn(3, 3),), ...)]) first, later = (r._artifacts.guard_manager for r in model.forward.compiled_results) with (patch.object(first, "check", wraps=first.check) as first_check, patch.object(later, "check", wraps=later.check) as later_check, self.assertNoLogs("torch._dynamo.aot_compile", level="WARNING")): served = model(torch.randn(3, 3)) # x * 2 first_check.call_count, later_check.call_count # 1, 1: [0]'s float64 tree rejected, [1]'s accepted ``` One thing the parent already did, kept, and made observable. `test_aot_compile_module_ordinary_dispatch_warns_about_nothing`: the warning is about a raise, so walking past a non-matching input to a matching one logs nothing. Both captures compute `x * 2`, so the served value cannot say which result served; the two real guard managers' `check` is patched with `wraps=`, as the file's other check counters are, and the test asserts one call on each -- [0]'s float64 tree rejected the float32 call and [1]'s accepted it -- so a dispatch that served [0] outright would fail it rather than pass on the value. ## Two assertions added to #197391's `warns_once_per_model_not_per_process` ```python self.assertNotIn("_warned", inspect.signature(AOTCompiledModel).parameters) # the field is init=False ... self.assertIn("dispatch served [0]", logs.output[0]) # the opted-out result itself is what the last resort serves ``` That test's model is the one-result opted-out raiser from `_model_with_stub_trees(unhappy, opt_out=True)`. `dispatch served [0]`: an earlier revision's `last_resort_warns_that_its_own_tree_raised` rebuilt that model by hand and re-asserted its raise line, its last-resort advice and the absence of `Fix or drop input`, adding only this reading, which now sits where the rest already was. `_warned` not in `inspect.signature(AOTCompiledModel).parameters`: the dedup set is a field on the model for the reason that test's comment gives, and for the same reason it is not the caller's to hand in -- a set shared across models would silence the second model the way `warning_once`'s cache silences every later one -- so the field is `init=False`. An earlier revision pinned that with a `dataclasses.fields` walk and CPython's `takes 3 positional arguments but 4` text in a test of its own; the previous revision of this commit pinned it nowhere, and `init=True` on the field ran the whole file green. It is now one assertion in the test whose comment already says why, and the one test `init=True` fails. > **FAQ: Why does a split-off, tests-only PR edit a test that #197391 owns and a fixture that #196826 owns?** > Because the review asked for the duplicates to be folded rather than kept > side by side, and the test they duplicate lives in #197391. The edits are > two added assertions and their comments in `warns_once_per_model`, and an > `exc=ValueError` parameter on `RaisesOnCompare`, with a comment clause, > whose default keeps its callers below unchanged; `git diff` of this commit > against its parent changes no line outside the five tests, that test and > that fixture. Both are unapproved drafts; folding into them instead would > move the change three or five PRs down and re-review it there. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_aot_compile_module_second_pass_warns_that_it_served_over_a_raise python test/dynamo/test_aot_compile.py -k test_aot_compile_module_last_resort_warns_about_another_index python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warning_unwraps_a_pybind_boundary_raise python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_again_about_a_replaced_index python test/dynamo/test_aot_compile.py -k test_aot_compile_module_ordinary_dispatch_warns_about_nothing python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_once_per_model_not_per_process python test/dynamo/test_aot_compile.py ``` The whole file passes in a venv without triton. `lintrunner --take RUFF,PYFMT test/dynamo/test_aot_compile.py` is clean. The five tests and `warns_once_per_model` were also run against the `torch/_dynamo/aot_compile.py` of #197391's parent under this test file: the four warning tests here and `warns_once_per_model` fail with `no logs of level WARNING or higher triggered on torch._dynamo.aot_compile`, and `ordinary_dispatch` passes, as it should. Against #196826's parent's `aot_compile.py` the same five error on the tree's own raise escaping the call -- a stub's `RuntimeError` (`both passes are unhappy`, `the second tree is unhappy`, `zero is unhappy`, `guard tree is unhappy`) or, for the unwrap test, the pybind boundary's `SystemError` over `ValueError: boom from __eq__` -- and `ordinary_dispatch` passes. Each fix in #197391 or #196826 that these tests cover was then reverted on its own in this commit's `aot_compile.py`, and the whole file run against it. Reading the warning's raiser off the served index fails `test_aot_compile_module_last_resort_warns_about_another_index` on the log reading `input [0]'s guard check raised RuntimeError: the second tree is unhappy`, and with it the second-pass test on the same reading and the replaced-index test on its warning count (`Expected 2 but got 1`), every one a test whose served index differs from the raiser (and warning tests of #196826, #197390 and #197391 below, for the same reason). Keying the warning on the `SystemError` rather than the unwrapped raise fails `test_aot_compile_module_warning_unwraps_a_pybind_boundary_raise` with the log reading `raised SystemError: <built-in method check of pybind11_builtins...`, and the two tests below that #197391 gave the same reading, `raise_from_an_opted_out_result_withholds_nothing` and `serves_a_later_match_over_a_raising_leaf`. Never starting the dedup over (forcing the `_same_results` test in `_warn_swallowed` true) fails `test_aot_compile_module_warns_again_about_a_replaced_index` with `no logs of level WARNING or higher triggered` on the call after the `pop`, and the one-result twin in #197391, and nothing else; gating the reset on two or more results fails only the twin, this test passing. Deleting the dedup -- the `(i, kind, enabled) in warned` test and the `warned.add` that ends the loop body -- fails `test_aot_compile_module_warns_again_about_a_replaced_index` on the repeat call that has to be silent, with `Unexpected logs found` quoting both of the warnings that call re-emitted, and #197391's dedup tests below. Logging a warning for a result `accepts()` rejected fails `test_aot_compile_module_second_pass_warns_that_it_served_over_a_raise` and `test_aot_compile_module_last_resort_warns_about_another_index` on their warning count, `Expected 1 but got 2` -- [1] and, on the second pass, [0] rejected -- and the unwrap test on its, `Expected 2 but got 6` (and tests of #197391, #196826's `raise_from_an_opted_out_result_withholds_nothing` and the landed #197048's `test_no_match_report_survives_a_forward_resolve_that_raises`). The last-resort test's `len(logs.output) == 1` is what catches this mutation -- an earlier revision of that test had no count assertion; dropping it here and re-running leaves the test passing. Logged for the inline check of [0] as well, it also fails `test_aot_compile_module_ordinary_dispatch_warns_about_nothing` with `Unexpected logs found: [... input [0] rejected this call]` (the same tests the inline log alone fails: [0] rejects inline on far more calls than a later result does in `accepts()`); [0] is checked inline and never reaches `accepts()`, so the first mutation alone does not reach that test. `init=True` on `_warned` fails `test_aot_compile_module_warns_once_per_model_not_per_process` with `'_warned' unexpectedly found in mappingproxy(OrderedDict({'model': ... '_warned': <Parameter "_warned: ...` and nothing else. Making both dispatch handlers re-raise fails the four warning tests here and the raise tests below, `ordinary_dispatch` being the negative pin. Serving the first result whatever its tree answered (the inline `if answer:` made unconditional) fails `ordinary_dispatch` on [1]'s check count, 0 against 1, among many tests below. Making `accepts()` answer true whatever the tree said fails the last-resort test on `unhappy.checks` and the second-pass test on `stub.checks`, both `Expected 2 but got 1` -- the served result's own accept now settles the second pass before the later stub is reached again, under the same one warning line -- which without the last-resort assertion that test passes. Authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #197195 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179
…d the no-match report's call (#197220) **Problem.** When every checked guard tree raised, the no-match report still ended with `Add a ModelInput covering this call`, which contradicts its own `fix or drop that artifact` line: a new input would guard the same dict and raise the same way. **Fix.** Dispatch records which trees actually answered. The report advises a `ModelInput` only when some checked tree answered or the artifact holds no inputs, and otherwise says that every guard tree raised. **Summary.** The commit below tolerates a guard tree that raises during module dispatch and reports the raise as that entry's line, but leaves the report's closing advice as it was at the parent: `Add a ModelInput covering this call, or check whether guard_filter_fn kept a guard this call cannot satisfy` is appended to every report. When every tree whose guards were asked about raised, nothing rejected the call, and an input covering it would guard the same dict and raise the same way, so the report told the caller both to fix or drop the artifact and to add an input -- two instructions that contradict each other. Dispatch now records `answered`, the indices that reached an answer in either pass, written on a rejection only, and the report advises a `ModelInput` whenever some checked tree answered (`coverable`) or the artifact holds no input at all. When no checked tree ever answered and two or more trees raised, a footer saying every guard tree raised replaces the advice, unless an opted-out result's line has already said the raise withheld it; a single raiser's own `fix or drop that artifact` line already says as much. Nothing served or raised changes -- the same calls raise the same `RuntimeError` with the same `__cause__`, and the dispatch passes, the veto and the warning are untouched -- only the report's closing lines differ, and six of the eleven touched tests fail on the commit below's `aot_compile.py`. ## Where this sits in the stack Split from `[no-ci] [aot_compile] Say what the no-match report's advice rests on after a raise` (#197050, the commit above) for review budget: this commit decides WHETHER the report's closing advice applies, and the sibling qualifies it when every rejection it rests on followed a raise. ## The contradiction Measured on `DictBranchModule` with one input and a colliding key, the report at the commit below reads: ``` [0] <guard check raised ValueError: boom from __eq__ (through the guard tree's pybind boundary)> [0]'s guard check raised while checking this call; fix or drop that artifact. Add a ModelInput covering this call, or check whether guard_filter_fn kept a guard this call cannot satisfy -- ... ``` Nothing rejected the call, and an input covering it would guard the same dict and raise the same way. `test_no_match_message_drops_the_input_advice_when_the_one_tree_raised` pins that report now ending on the fix-or-drop line. ## Recording who answered ```python # AOTCompiledModel.__call__ raised: dict[int, Exception] = {} unanswered: set[int] = set() answered: set[int] = set() # new: indices that ever reached an answer try: answer = first._live_guard_manager().check(f_locals) except Exception as e: raised[0] = e; unanswered.add(0); answer = False else: answered.add(0) # new def accepts(i, result): try: answer = result._live_guard_manager().check(f_locals) except Exception as e: raised[i] = e; unanswered.add(i); return False if answer: return True # an accept serves and builds no report # Recorded on a rejection only. unanswered.discard(i) answered.add(i) # new return False ``` Dispatch now records which entries reached an answer, and records it where the order is known rather than reconstructing it afterwards. `answered` holds the indices that reached an answer in either dispatch pass, which is what the `ModelInput` advice reads: an entry that answered and then raised did reject this call, so an input covering the call is on the table even though its own report line is that later raise. Keying that advice on the last evaluation instead drops it for exactly those entries -- measured: `coverable` read off `answered - unanswered` fails `test_no_match_message_advises_an_input_after_an_answer_then_a_raise` with no `ModelInput` line at all. The write happens on a rejection only: an accept returns before it, since dispatch then serves and builds no report, so the result that accepts pays nothing for it. ## The two gated closing lines ```python # _no_match_report raiser = next((i for i in raised if enabled[i]), None) coverable = any(results[i]._guard_check_enabled for i in answered) # new withheld = not all(enabled) ... if raiser is not None: lines.append(f"[{raiser}]'s guard check raised while checking this call; fix or drop that artifact.") if coverable or not results: # parent: unconditional lines.append("Add a ModelInput covering this call, or check whether guard_filter_fn kept ...") if len(raised) > 1 and not withheld and not coverable: # new footer lines.append("Every guard tree raised while checking this call; the reasons above are those raises, not guards this call failed.") ``` **The `ModelInput` line.** The report advises a `ModelInput` whenever at least one checked tree reached an answer (`coverable`, `any(results[i]._guard_check_enabled for i in answered)`, the shape the last-resort veto already uses over `raised`). `deserialize` accepts an artifact holding no inputs at all, where `aot_compile_module` refuses one: with no entries there is no raise to describe and nothing that could have answered, so that report carries the `ModelInput` line alone -- adding an input is exactly its advice. Dropping `not results` from the `ModelInput` gate fails `test_no_match_report_claims_no_raise_for_an_artifact_with_no_inputs` on the line going missing. **The every-tree-raised footer.** When no checked tree ever answered, the entry lines above are all raises, and the one closing line a single raiser earns is the `fix or drop that artifact` line the commit below already emits for it: that raiser's entry line, that advice and a footer saying every tree raised would say `[0] raised` three times over, which is what the first version of this commit printed -- measured on `test_no_match_message_when_a_raise_did_not_cross_the_pybind_boundary`, whose four-line report closed with `[0]'s guard check raised while checking this call; fix or drop that artifact.` and then `Every guard tree raised while checking this call; ...`. So the footer that says the reasons above are the raises themselves, not guards this call failed, is added only once two or more trees raised and none answered: there the fix-or-drop line names one raiser of several, and without the footer nothing on the report says that no guard rejected the call. ``` # test_no_match_message_when_every_guard_tree_raised: two enabled trees, both raise, no opt-out No AOT compiled graph matched this call. Tried 2 compiled input(s): [0] <guard check raised RuntimeError: the first tree is unhappy> [1] <guard check raised RuntimeError: the second tree is unhappy> [0]'s guard check raised while checking this call; fix or drop that artifact. Every guard tree raised while checking this call; the reasons above are those raises, not guards this call failed. ``` Under that gate every entry raised -- each entry either raised or answered, and an opted-out entry reaches the report only because an enabled raise withheld it, which the `not withheld` term excludes -- so `len(raised) > 1` counts the raisers and the entries alike. The two gates are independent `if`s: they are already exclusive on `coverable`, and an `elif` would read as an ordering that does not exist. Each term of the footer's gate is pinned by a mutation: | mutation | fails | | --- | --- | | gate on `raised` instead of `len(raised) > 1` | `test_no_match_message_drops_the_input_advice_when_the_one_tree_raised`, `test_no_match_message_when_a_raise_did_not_cross_the_pybind_boundary`, `test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators` (footer under a single raiser's line) | | drop `not withheld` | `test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning` (a fifth line under its withheld line, which has already said what the raise cost) | | drop `not coverable` | `test_no_match_message_advises_an_input_when_one_of_two_raisers_answered` (footer beside the `ModelInput` advice it contradicts) | ## What changes against the commit below Nothing served or raised changes: the same calls raise the same `RuntimeError` with the same `__cause__`, and the dispatch passes, the veto and the warning are untouched. Only the report's closing lines differ: the `ModelInput` line is omitted when no checked tree ever answered and the artifact has inputs, so a single raiser's report ends on its fix-or-drop line, and an every-tree-raised line replaces the advice when two or more trees raised, none answered and no opt-out was withheld. Making the `ModelInput` line unconditional again fails `test_no_match_message_when_every_guard_tree_raised`, `test_no_match_message_drops_the_input_advice_when_the_one_tree_raised`, `test_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result`, `test_aot_compile_module_restores_torch_function_after_a_throw`, `test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning` and `test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators` on the line appearing. The `AOTCompiledModel` docstring listed that advice as part of every report; it now says when the advice is present, what replaces it when no checked tree answered AND two or more trees raised -- the empty artifact has neither and gets the advice, not the replacement, which is what `test_no_match_report_claims_no_raise_for_an_artifact_with_no_inputs` pins -- that a single raiser's own line already says as much, and that the replacement too stays off a report whose withheld line has already said the raise withheld an opt-out. ## Tests Five tests are new and six of the commit below's tests gain or change an assertion about the closing lines this commit adds or removes for their case. Of those eleven, six fail on the commit below's `aot_compile.py`: - `test_no_match_message_when_every_guard_tree_raised`, `test_no_match_message_drops_the_input_advice_when_the_one_tree_raised`, `test_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result`, `test_aot_compile_module_restores_torch_function_after_a_throw` and `test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning`, on the `ModelInput` line appearing; - `test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators`, on the four lines it counted there -- header, entry, fix-or-drop advice, `ModelInput` advice -- against the three a single raiser's report has now. The five that pass there do so because the parent's `ModelInput` line is unconditional and it has no every-tree-raised line to find; each is a pin here by the mutation named above: - `test_no_match_report_claims_no_raise_for_an_artifact_with_no_inputs` (`not results`); - `test_no_match_message_advises_an_input_after_an_answer_then_a_raise` (`coverable` over `answered`, not over the last evaluation); - `test_no_match_message_advises_an_input_when_one_of_two_raisers_answered` (`not coverable` on the footer's gate); - `test_no_match_message_when_a_raise_did_not_cross_the_pybind_boundary` (`len(raised) > 1`); - `test_no_match_message_when_only_the_report_raises`, which gains only an assertion that the every-tree-raised line is absent from its report, whose one tree answered. ## Review order Review `answered` and its update in `accepts()`; the report's `coverable`; the two gated lines at the end of `_no_match_report`, the comment on the empty artifact and the comment on the footer's gate; the sentence of the `AOTCompiledModel` docstring that describes the report's closing lines; then, in the test file, `test_no_match_message_drops_the_input_advice_when_the_one_tree_raised`, `test_no_match_message_when_every_guard_tree_raised`, `test_no_match_message_advises_an_input_when_one_of_two_raisers_answered`, `test_no_match_report_claims_no_raise_for_an_artifact_with_no_inputs` and `test_no_match_message_advises_an_input_after_an_answer_then_a_raise`. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_no_match_message_when_every_guard_tree_raised python test/dynamo/test_aot_compile.py -k test_no_match_message_drops_the_input_advice_when_the_one_tree_raised python test/dynamo/test_aot_compile.py -k test_no_match_message_advises_an_input_when_one_of_two_raisers_answered python test/dynamo/test_aot_compile.py -k test_no_match_report_claims_no_raise_for_an_artifact_with_no_inputs python test/dynamo/test_aot_compile.py -k test_no_match_message_advises_an_input_after_an_answer_then_a_raise python test/dynamo/test_aot_compile.py -k test_no_match_message_when_only_the_report_raises python test/dynamo/test_aot_compile.py -k test_no_match_message_when_a_raise_did_not_cross_the_pybind_boundary python test/dynamo/test_aot_compile.py -k test_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result python test/dynamo/test_aot_compile.py -k test_aot_compile_module_restores_torch_function_after_a_throw python test/dynamo/test_aot_compile.py -k test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning python test/dynamo/test_aot_compile.py -k test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators python test/dynamo/test_aot_compile.py lintrunner --take RUFF,PYFMT torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py ``` The eleven were also run against the commit below's `torch/_dynamo/aot_compile.py` (six fail, the five named above pass), and each gate was then mutated on its own -- `coverable` keyed on the last evaluation, `not results` dropped, the `ModelInput` line made unconditional, the footer gated on `raised` instead of `len(raised) > 1`, its `not withheld` dropped, its `not coverable` dropped -- and the eleven rerun; only the tests named above failed under each. Authored with the assistance of Claude Code. > **FAQ: `raiser` and `coverable` walk all results to filter by membership in > a small set, where `any(results[i]._guard_check_enabled for i in > answered)` is the same predicate in the shape already used at the veto.** > > Taken for `coverable`, which is exactly that line. Not for `raiser`: it does > not walk all results. It is > `next((i for i in raised if results[i]._guard_check_enabled), None)` > -- already a walk of the small dict, and it needs the first such index in > recording order rather than a bool, so there is no `any(...)` shape to move it > to. > **FAQ: `answered` never holds an accept -- the accept returns before the > write -- so `rejected` would name what the set holds and make `coverable` a > restatement rather than a derivation.** > > Kept as `answered`. It is the report's counterpart to `unanswered`, the > commit below's name for the same property keyed on the LAST evaluation: `i > in unanswered` decides whether an entry's line is its raise or a quoted > guard, `i in answered` whether a `ModelInput` could cover it, and what both > key on is that `check()` returned rather than raised. That every recorded > answer was a rejection is what a report existing means, and it is written at > the write (`Recorded on a rejection only`) and at `coverable` (`answered in > either dispatch pass rejected this call`), the two places the set is read. > The commit above adds `trusted` as a third set over the same indices and > reads `answered - trusted`; renaming here would ripple through its four > `answered` hunks for a word those two comments already supply. Co-Authored-By: Claude Fable 5.1 <[email protected]> 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #197220 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195
…ard for and which share a line (#197001) **Problem.** The no-match report decides, entry by entry, whether its missing-global hint names "this `Module` instance's forward" or stays neutral ("the live scope this artifact was loaded against"), by comparing the dict `forward` resolves to against the dict each entry's guards hold. Nothing pinned that a caller-supplied `guard_globals=` dict stays neutral, or that in a report with two entries holding different dicts only the entry holding the resolved one is told which forward. **Fix.** Two tests pin exactly that: one where no entry holds the resolved dict (and defining the name in the supplied dict then serves the call), and one where exactly one of two does, checked in both orders with a single resolve asserted. No source change. **Summary.** 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. Split twice more for review budget: the five-test revision of this commit died at the review bot's 60-minute ceiling, so the two tests that pin WHEN the report resolves `forward` -- only for a SUPPLIED scope, and once -- moved up into `[aot_compile] Pin when the no-match report resolves forward` (#197301), and the three-entry test that pins which entries share a hint line moved up into `[aot_compile] Pin that the no-match report shares one hint line across entries worded alike`. What stays here is the pair that pins WHICH entry the hint names a `forward` for: one where no entry is, and one where exactly one of two is. Both pass at the parent, whose report they pin, fail below the report commit (#196896) where no report exists, and each fails under a targeted edit of `_no_match_report` that no other test in the file catches, measured by editing the report and running the whole file. Two tests of the previous revision are gone, one because the footer gate it fenced is already fenced by two other tests and one because it is folded into the three-entry test's entry `[1]` in the commit above. ## What the report does at this tree The report decides its hint per entry. An entry whose verbose parts name a whole missing global gets `_missing_global_hint(forward=...)`, with `forward` set when `resolved is not None and resolved is result._guard_globals`; `resolved` is what one `_resolve_guard_scope(self.model)` returned, run at most once, at the first hinted entry whose scope is SUPPLIED, and reused for every entry after it (when it runs, and that it runs once, is #197301's). ``` # the two wordings the tests tell apart For [i]: a guarded global is missing from the live scope this artifact was loaded against; define it there ... # neutral For [i]: ... this GlobalConfigModule instance's forward resolves to ... # named ``` ## Both fail below the report commit Both tests pass at the parent, whose report they pin, and fail below the report commit (at #196896, the commit under it), where the no-match fall-through `results[0](self.model, *args, **kwargs)` raises the function path's `GuardManager check failed` message. That message 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` substring the tests also look for is present there; what it lacks is the `[i]` entry prefix, the `For [i]:` hint line and the `Tried N` header, and with no report there is no resolve. Measured with that tree's `aot_compile.py` under this tree's test file: | test | failure below the report commit | | --- | --- | | `..._hint_stays_neutral_for_a_supplied_scope` | `"[0] KeyError on G['AOT_HERMETIC_WEIGHT']" not found` | | `..._names_forward_only_for_the_dict_it_resolves_to` | `Expected '_resolve_guard_scope' to be called once. Called 0 times` | The one that compiles in its own body calls `_hide_leaked_dynamo_globals()` on entry, as the capture-only `test_aot_compile_fn_missing_global_hint_names_the_tracing_scope` does; the other shares `_two_input_global_guard_artifact` with `test_no_match_message_hints_each_scope_a_mixed_model_failed_in` and the landed `test_aot_compile_module_missing_global_hint_names_the_resolved_module` and, like them, does not, its kept guards being rooted at `GLOBAL_POOLING_CONFIG` alone. ## `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` ```python scope: dict[str, object] = {"__builtins__": builtins} # never had AOT_HERMETIC_WEIGHT compiled = AOTCompiledModel.deserialize(HermeticModule(), data, guard_globals=scope) with self.assertRaises(RuntimeError) as ctx: compiled(x) message = str(ctx.exception) self.assertIn("[0] KeyError on G['AOT_HERMETIC_WEIGHT']", message) self.assertIn("For [0]: a guarded global is missing from the live scope this artifact was loaded against; define it there", message) self.assertNotIn("instance's forward", message) # the advice, followed: the guards hold the supplied dict, and defining the name there serves the call self.assertIs(compiled.compiled_results[0]._guard_globals, scope) scope["AOT_HERMETIC_WEIGHT"] = AOT_HERMETIC_WEIGHT self.assertEqual(compiled(x), x @ AOT_HERMETIC_WEIGHT) ``` It 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 under its `For [0]:` prefix, 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. Reducing the compare to `resolved is not None` fails it with a report that names `this HermeticModule instance's forward`, and fails exactly two others: the landed #196818's `..._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`, and this commit's `names_forward_only_for_the_dict_it_resolves_to`, whose caller-supplied entry is then told which forward as well. #197048's `test_no_match_report_survives_a_forward_resolve_that_raises` reaches the neutral wording through `resolved is None`, and its `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_no_match_message_names_forward_only_for_the_dict_it_resolves_to` ```python by_forward = AOTCompiledModel.deserialize(GlobalConfigModule(), data) # resolves scope from model.forward: this module's dict by_caller = AOTCompiledModel.deserialize(GlobalConfigModule(), data, guard_globals=scope) # a dict that never had the name self.assertIs(by_forward.compiled_results[0]._guard_globals, globals()) self.assertIs(by_caller.compiled_results[0]._guard_globals, scope) del GLOBAL_POOLING_CONFIG pair = by_forward.compiled_results[:1] + by_caller.compiled_results[:1] cases = ((pair, [named, neutral]), (pair[::-1], [neutral, named])) # both orders for results, wording in cases: mixed = AOTCompiledModel(GlobalConfigModule(), results) with patch(target, wraps=_resolve_guard_scope) as resolves, self.assertRaises(RuntimeError) as ctx: mixed(x) resolves.assert_called_once_with(mixed.model) # one resolve, asked about the model the report is for hints = [line for line in message.splitlines() if line.startswith("For [")] self.assertEqual([line[:9] for line in hints], ["For [0]: ", "For [1]: "], message) for hint, want in zip(hints, wording): self.assertIn(want, hint) ``` This is the shape that tells a per-entry `forward` from one shared across the report. Two SUPPLIED results whose guards hold different dicts -- one from `deserialize(GlobalConfigModule(), data)`, which resolves the scope from `model.forward` and so holds this module's dict, the one `_resolve_guard_scope` returns; one from `deserialize(..., guard_globals=scope)` with a dict that never had the name -- go into one `AOTCompiledModel` by hand, as `hints_each_scope_a_mixed_model_failed_in` builds its CAPTURED + SUPPLIED pair, and are dispatched with `GLOBAL_POOLING_CONFIG` deleted, in both orders. Each order enters a fresh `patch(..., wraps=_resolve_guard_scope)`, so its count is that order's alone, and asserts `assert_called_once_with(mixed.model)` -- one resolve, asked about the model the report is for -- two `For [i]:` lines, and that the entry holding the resolved dict is the one told `this GlobalConfigModule instance's forward` while the other gets the live-scope wording. | edit to `_no_match_report` | fails | | --- | --- | | decide `forward` once, at the first hinted entry, and apply it to every entry | this test alone, on the second entry's wording (`'the live scope this artifact was loaded against; define it there' not found in "For [1]: ... this GlobalConfigModule instance's forward resolves to ..."`) | | resolve `_resolve_guard_scope(type(self.model)())` instead of `self.model` | this test on `expected call not found`, plus #197048's `covers_a_rebound_forward` and `survives_a_forward_resolve_that_raises` on wording | Nothing else in the file catches the first edit: `..._names_the_resolved_module`'s two entries share one dict in each half, and `hints_each_scope`'s SUPPLIED entry is its only one. The line count does not catch that edit, because the resolved dict carries a `__name__` and the supplied one does not, so the two hints stay two sentences either way; the wording does. The `_with(mixed.model)` is what pins which module is resolved: asking about a fresh instance resolves to the same dict here, so the wording cannot tell, and a fresh instance does not carry the `forward` the two #197048 tests rebind. ## Two tests of the previous revision are gone `test_no_match_message_advises_an_input_for_a_missing_global` and its `SelfModeBranchGlobalModule` fixture pinned the footer under a report whose every entry was hinted; the footer is unconditional, and returning before it when `sum(map(len, hinted.values())) == len(results)` fails two tests at this tree without it (both on `'Add a ModelInput' not found`): #196825's `test_aot_compile_module_absent_global_fails_guard` and #197048's `survives_a_forward_resolve_that_raises` (and, one commit up, #197301's `resolves_forward_only_for_a_supplied_scope`). Its other assertions -- that the `L['self'].mode` mismatch is absent from the first report and named by the second -- pinned the guard tree's install order and fail-count re-sort in guards.cpp, not the report. `test_missing_key_inside_a_present_global_is_not_a_missing_global` is folded into the three-entry test's entry `[1]`, which fences the same substring edit, and rides with it in the commit above. 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_no_match_message_names_forward_only_for_the_dict_it_resolves_to python test/dynamo/test_aot_compile.py ``` The whole file is green here and on the parent commit. ## FAQ > **FAQ: The review found that > `test_aot_compile_module_missing_global_hint_names_the_resolved_module`, in > the landed #196818, already fails under the edit that this commit's > `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` was once > 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 not None`: the failures are `..._names_the_resolved_module` > (`'loaded against; define it there' not found`), this test, and this commit's > `names_forward_only_for_the_dict_it_resolves_to`; every other test passes. So > the identity compare is fenced at #196818 as well, and the message says so > instead of crediting this test alone. 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. > **FAQ: The review found two of an earlier revision's five tests largely > redundant with the base, and two report branches -- where `tried_forward` is > set, and hint dedup keyed by text -- unpinned. What changed?** > > Both redundancies were measured and both tests are gone; both branches are > now pinned, one in the commit above and one in #197301. Gating the footer on > every entry being hinted, the edit > `test_no_match_message_advises_an_input_for_a_missing_global` fenced, fails > two tests at this tree without it -- #196825's `absent_global_fails_guard` > and #197048's `survives_a_forward_resolve_that_raises` -- so that test and > its fixture add no fence on the report, and its `L['self'].mode` assertions > pin guards.cpp's accessor order, not this function. Replacing the report's > whole-part predicate with a substring test, the edit > `test_missing_key_inside_a_present_global_is_not_a_missing_global` fenced > alone, and keying `hinted` by dict identity are both fenced by the > three-entry `shares_a_hint_line_across_entries_worded_alike` in the commit > above, so the fold loses no coverage and the module path still has its own > pin of the predicate. The `tried_forward` mark is pinned by #197301's > `resolves_forward_once_past_a_resolve_that_raises`. > **FAQ: Every new test passes at the parent commit. Where is the red-on-parent > evidence?** > > There is none by construction: this is a tests-only commit pinning the > report the parent already ships, so every test passes on the parent's tree. > The two measurements that stand in for it are above: each test fails under > the tree below the report commit (#196896), where no report exists, and each > fails under a targeted edit of `_no_match_report` that no other test in the > file catches -- the mutation table is what shows the pins are not vacuous. > **FAQ: The review listed `"; ".join(parts)` with more than one verbose code > part per entry as uncovered. Why is there no test for it here?** > > Because that join is #197134's (`Keep a no-match report entry to one line > that says what its guards answered`), whose > `test_no_match_report_keeps_an_entry_on_one_line_past_odd_separators` owns > the entry format; how many parts an entry quotes has no bearing on the hint, > which is what this commit pins. A multi-part entry test belongs next to that > one, in that PR. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: #197001 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220
…s entries worded alike (#197569) **Problem.** The no-match report from #196823 groups its missing-global hint by sentence, so two entries loaded against different caller dicts but worded alike share one `For [0, 2]:` line, and a nested-key `KeyError` stays off the hint; nothing in the file exercised a three-entry report, so none of that was pinned. **Fix.** Add `test_no_match_message_shares_a_hint_line_across_entries_worded_alike`, the report's only three-entry test, which pins the shared non-contiguous hint line, the nested-key exclusion, the single resolve of the model's own forward and the footer's placement. No source change. **Summary.** Tests only, for the no-match report the report commit (#196823) raises, split off the top of `[aot_compile] Pin which entries the no-match report's hint names forward for` (#197001) because that commit's five-test revision died at the review bot's 60-minute ceiling; the two tests that pin WHICH entry the hint names a `forward` for stay there, the two that pin WHEN the report resolves `forward` moved into #197301, and this one -- the report's only three-entry test, which reads the hint LINES rather than any one entry's wording -- comes here. It loads three SUPPLIED results from three `deserialize(GlobalConfigModule(), data, guard_globals=...)` calls, each holding a caller dict of its own, where `[0]` and `[2]` lack `GLOBAL_POOLING_CONFIG` and `[1]` has it bound to `{}` so its guard fails on the KEY. It pins four things at once: the hint lines are keyed by sentence and not by dict, so `[0]` and `[2]` share one non-contiguous `For [0, 2]:` line; `[1]`'s nested-key `KeyError on G['GLOBAL_POOLING_CONFIG']['pooling']` is the ordinary mismatch the whole-part match keeps off the hint; the report's one resolve is `assert_called_once_with(mixed.model)` on an `_unresolvable_forward_module()`, whose forward is a partial `get_traced_fn` refuses, so it returns `(None, reason)` without raising and no entry is told which forward; and the footer follows a report whose hinted list is non-contiguous. It passes at the parent, whose report it pins, and fails below the report commit (at #196896), where the no-match fall-through raises the function path's `GuardManager check failed` message with no `[i]` entry prefix, no `For [i]:` line and no `Tried N` header, on `Expected '_resolve_guard_scope' to be called once. Called 0 times`. Two targeted edits of `_no_match_report` that no other test in the file catches -- keying `hinted` by `(id(result._guard_globals), hint)`, and replacing `_names_a_missing_global` with a `"KeyError on G[" in part` substring test -- each fail this test alone, which is what shows the pin is not vacuous. ## Where this sits in the stack Tests only, for the no-match report the report commit (#196823) raises, split off the top of `[aot_compile] Pin which entries the no-match report's hint names forward for` (#197001) because that commit's five-test revision died at the review bot's 60-minute ceiling. The two tests that pin WHICH entry the hint names a `forward` for stay there, the two that pin WHEN the report resolves `forward` moved into #197301, and this one -- the report's only three-entry test, which reads the hint LINES rather than any one entry's wording -- comes here. ## The fixture and the report it pins ```python x = torch.randn(4, 8) data = self._two_input_global_guard_artifact(x) absent = {"__builtins__": builtins} # no GLOBAL_POOLING_CONFIG keyless = {**absent, "GLOBAL_POOLING_CONFIG": {}} # the global, without the key its guard reads loads = [AOTCompiledModel.deserialize(GlobalConfigModule(), data, guard_globals=s) for s in (absent, keyless, dict(absent))] # three SUPPLIED results, three distinct dicts results = [loaded.compiled_results[0] for loaded in loads] assert [r._guard_scope for r in results] == [_GuardScope.SUPPLIED] * 3 assert len({id(r._guard_globals) for r in results}) == 3 mixed = AOTCompiledModel(self._unresolvable_forward_module(), results) with patch("torch._dynamo.aot_compile._resolve_guard_scope", wraps=_resolve_guard_scope) as resolves: with self.assertRaises(RuntimeError) as ctx: mixed(x) resolves.assert_called_once_with(mixed.model) ``` The report the test asserts, line by line: ``` No AOT compiled graph matched this call. Tried 3 compiled input(s): [0] KeyError on G['GLOBAL_POOLING_CONFIG'] [1] KeyError on G['GLOBAL_POOLING_CONFIG']['pooling'] [2] KeyError on G['GLOBAL_POOLING_CONFIG'] For [0, 2]: a guarded global is missing from the live scope this artifact was loaded against; define it there ... Add a ModelInput ... ``` `test_no_match_message_shares_a_hint_line_across_entries_worded_alike` is the report's first three-entry test (`Tried 3` appears nowhere else in the file). The three entry lines are asserted exactly, `len(hints) == 1`, the one hint starts with `For [0, 2]:` and does not contain `instance's forward`, and `Add a ModelInput` is the last line. It shares `_two_input_global_guard_artifact` with `test_no_match_message_hints_each_scope_a_mixed_model_failed_in` and the landed `test_aot_compile_module_missing_global_hint_names_the_resolved_module` and, like them, does not call `_hide_leaked_dynamo_globals()`, its kept guards being rooted at `GLOBAL_POOLING_CONFIG` alone. ## The four things it pins **First, hint lines are keyed by sentence, not by dict.** `[0]` and `[2]` carry no `__name__`, so their neutral sentences are identical and they share one non-contiguous `For [0, 2]:` line. Keying `hinted` by `(id(result._guard_globals), hint)` instead fails it on the line count (`Expected 1 but got 2`) and nothing else in the file: `..._names_the_resolved_module`'s `For [0, 1]` entries share one dict object. The merge is the intended reading: a per-dict line would print the same sentence twice, and the sentence names no dict, so the reader could not tell the two lines apart; two entries that give one instruction get one line. **Second, the nested-key mismatch stays off the hint.** `[1]` is the nested-key mismatch the whole-part match keeps off the hint: replacing the report's `_names_a_missing_global` with a `"KeyError on G[" in part` substring test fails it on `For [0, 1, 2]:` and nothing else in the file, the fence the dropped `test_missing_key_inside_a_present_global_is_not_a_missing_global` carried (see the FAQ); the predicate itself is pinned on the function path by `test_aot_compile_fn_missing_nested_key_gets_no_missing_global_hint`. **Third, the report resolves the model's own forward, once.** The model is `_unresolvable_forward_module()`, whose forward is a partial `get_traced_fn` refuses, so the report's one resolve -- `assert_called_once_with(mixed.model)` -- returns `(None, reason)` without raising and no entry is told which forward; the fixture's three other uses pass no `guard_globals=`, so their results are RECONSTRUCTED and never reach the resolve. The `_with(mixed.model)` is what pins which model the report asks about: resolving `type(self.model)()` instead fails this test on `expected call not found`, along with #197048's `covers_a_rebound_forward` and `survives_a_forward_resolve_that_raises` and #197001's `names_forward_only_for_the_dict_it_resolves_to`. **Fourth, the footer follows a report whose hinted list is non-contiguous.** ## Where it is red It passes at the parent, whose report it pins, and fails below the report commit (at #196896, the commit under it), where the no-match fall-through `results[0](self.model, *args, **kwargs)` raises the function path's `GuardManager check failed` message: that message carries the missing-global hint sentence the test also looks for, but no `[i]` entry prefix, no `For [i]:` line and no `Tried N` header, and with no report there is no resolve. Measured with that tree's `aot_compile.py` under this tree's test file, it fails on `Expected '_resolve_guard_scope' to be called once. Called 0 times`. | mutation of `_no_match_report` | fails on | other tests in the file affected | | --- | --- | --- | | key `hinted` by `(id(result._guard_globals), hint)` | `Expected 1 but got 2` hint lines | none | | `_names_a_missing_global` -> `"KeyError on G[" in part` | `For [0, 1, 2]:` | none | | resolve `type(self.model)()` instead of `self.model` | `expected call not found` | #197048's `covers_a_rebound_forward` and `survives_a_forward_resolve_that_raises`, #197001's `names_forward_only_for_the_dict_it_resolves_to` | | tree below the report commit (#196896) | `Expected '_resolve_guard_scope' to be called once. Called 0 times` | -- | Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_no_match_message_shares_a_hint_line_across_entries_worded_alike python test/dynamo/test_aot_compile.py ``` The whole file is green here and on the parent commit. ## FAQ > **FAQ: The report's comment on `hinted` says entries that share a scope > share a sentence, but the dict is keyed by hint text, so two entries holding > different dicts with identical wording collapse into one `For [0, 2]:` line. > Is that intended, and why pin it rather than change it?** > > It is intended, and this commit changes no code. The hint sentence is the > whole of what the reader gets: it names a scope only when the dict carries a > `__name__` (`here vars(mod)`), and two caller-supplied dicts without one > yield the identical sentence, so a per-dict line would print that sentence > twice with nothing to tell the two lines apart. Two entries whose advice > reads the same get one line; two entries whose advice differs -- a resolved > module dict next to a supplied one, a CAPTURED entry next to a SUPPLIED one > -- keep their own, which #197001's > `names_forward_only_for_the_dict_it_resolves_to` and > `hints_each_scope_a_mixed_model_failed_in` pin. The comment's "share a > scope" is the common case of sharing a sentence, and belongs to #197149. > **FAQ: An earlier revision had a separate > `test_missing_key_inside_a_present_global_is_not_a_missing_global`. Where did > it go?** > > Into this test's entry `[1]`, which fences the same edit: replacing the > whole-part predicate with a substring test fails this test alone in the whole > file, so the fold loses no coverage, and it buys the nested-key mismatch a > place next to two whole-global ones in one report, where the point is that > the hint skips it while the entry line still quotes it. The module path also > keeps its own pin of the predicate on the function side. > **FAQ: The test passes at the parent commit. Where is the red-on-parent > evidence?** > > There is none by construction: this is a tests-only commit pinning the report > the parent already ships, so it passes on the parent's tree. The two > measurements that stand in for it are above: it fails under the tree below the > report commit (#196896), where no report exists, and it fails under two > targeted edits of `_no_match_report` that no other test in the file catches -- > the mutations are what show the pin is not vacuous. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: #197569 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220, #197001
**Problem.** The no-match report (#196823) resolves `self.model`'s `forward` to name the scope a missing global should be defined in, but nothing pinned WHEN it does so: only for an entry whose scope was SUPPLIED, at the first such entry whatever its index, and at most once even when the resolve raises. Each of those decisions could be silently loosened without any existing test noticing, because the report's wording reads the same either way. **Fix.** Four tests that count calls into `_resolve_guard_scope` through a `patch(..., wraps=...)` instead of reading the text: no resolve for a CAPTURED scope, none for a RECONSTRUCTED one, one resolve at the first SUPPLIED entry even at index 1, and one resolve when it raises. No source change. **Summary.** Tests only, for the no-match report the report commit (#196823) raises, split out of `[aot_compile] Pin which entries the no-match report's hint names forward for and which share a line` (#197001) for review budget after that commit's five-test revision died at the review bot's 60-minute ceiling: the four tests that pin WHEN the report resolves `forward` -- for a SUPPLIED scope only, and at most once -- are this commit, and the three that pin which entries the hint names it for stay below. The report at this tree resolves `forward` at most once per report: at the first hinted entry whose scope is SUPPLIED it marks the attempt (`tried_forward = True`) before the `try`, calls `_resolve_guard_scope(self.model)`, keeps what came back for every entry after it, never triggers for a CAPTURED or RECONSTRUCTED entry (neither hint names `forward`), and swallows a raising resolve once rather than re-running it for a later entry. Because the CAPTURED and RECONSTRUCTED hints never name `forward` and both entries after a raise read the same neutral sentence, the wording cannot pin any of that, so each test wraps `_resolve_guard_scope` in a `patch(..., wraps=...)` and asserts the call count and, where it matters, which module instance was asked. Each of the four passes at the parent, whose report it pins, and fails below the report commit, where the no-match fall-through `results[0](self.model, *args, **kwargs)` raises the function path's `GuardManager check failed` message with no `[i]` prefix, no `For [i]:` line and no `Tried N` header. What each catches, and which other tests in the file would catch the same edit, was measured by editing the report and running the whole file; every targeted edit fails exactly the test written for it and nothing else outside this commit. ## Where this sits in the stack Split out of #197001 for review budget: that commit's five-test revision died at the review bot's 60-minute ceiling. The four tests that pin WHEN the report resolves `forward` are here; the three that pin which entries the hint names it for stay below in #197001. Which entries the resolved result is then applied to is #197001's business. ## What the report does at this tree ```python # _no_match_report, as the tests below pin it tried_forward = False for i, result in enumerate(results): ... if any(map(_names_a_missing_global, parts)): # a hinted entry if result._guard_scope is _GuardScope.SUPPLIED and not tried_forward: tried_forward = True # marked BEFORE the try: a raise is swallowed once try: resolved, unresolved = _resolve_guard_scope(self.model) except Exception as exc: unresolved = f"resolving it raised {type(exc).__name__}" # the type only: str(exc) can raise again # CAPTURED and RECONSTRUCTED entries never reach the resolve: neither hint names forward ``` The report resolves `forward` at most once per report. At the first hinted entry whose scope is SUPPLIED it marks the attempt before the `try`, calls `_resolve_guard_scope(self.model)`, and keeps what came back for every entry after it; a CAPTURED or RECONSTRUCTED entry never triggers it, since neither hint names `forward` -- the first names the tracing module, the second the rebuilt scope; and a resolve that raises is swallowed once rather than re-run for a later entry. Review the three gate tests first, then the once test. ## Below the report commit Each of the four passes at the parent, whose report it pins, and fails below the report commit (the commit under it raises no report), where the no-match fall-through `results[0](self.model, *args, **kwargs)` raises the function path's `GuardManager check failed` message. That message quotes the guard's `KeyError on G[...]` part and, for a whole missing global, appends the function path's hint sentence, so the `the module the compiled function was traced in` substring the first test also looks for is present there; what it lacks is the `[i]` entry prefix, the `For [i]:` hint line and the `Tried N` header, and with no report there is no resolve. Measured with that tree's `aot_compile.py` under this tree's test file: | test | fails below the report commit on | | --- | --- | | `resolves_forward_only_for_a_supplied_scope` | `"[0] KeyError on G['AOT_HERMETIC_WEIGHT']" not found` | | `resolves_no_forward_for_a_reconstructed_scope` | hint-line count, `Expected 1 but got 0` -- no `For [` line at all | | `resolves_forward_once_past_a_resolve_that_raises` | resolve count, `Expected 1 but got 0` | | `resolves_forward_at_the_first_supplied_entry` | the same count | The two that capture compile in their own body and call `_hide_leaked_dynamo_globals()` on entry, as the capture-only `test_aot_compile_fn_missing_global_hint_names_the_tracing_scope` does; the third only loads, and the fourth copies the mixed-scope arrangement of `test_no_match_message_hints_each_scope_a_mixed_model_failed_in`, which compiles without hiding them. ## Gate 1: no resolve for a CAPTURED scope `test_no_match_report_resolves_forward_only_for_a_supplied_scope` is the CAPTURED half of the pair whose SUPPLIED half, #197048's `test_no_match_report_survives_a_forward_resolve_that_raises`, stays with the report. ```python model = torch.compile(HermeticModule(), fullgraph=True, backend="eager", options={"guard_filter_fn": keep_global_guards}) model._aot_compile([ModelInput(args=(x,), kwargs={}, contexts=[])]) assert model.forward.compiled_results[0]._guard_scope is _GuardScope.CAPTURED resolve = patch("torch._dynamo.aot_compile._resolve_guard_scope", wraps=_resolve_guard_scope) saved = globals().pop("AOT_HERMETIC_WEIGHT") try: with resolve as resolves, self.assertRaises(RuntimeError) as ctx: model(x) finally: globals()["AOT_HERMETIC_WEIGHT"] = saved resolves.assert_not_called() # the count is the pin # message carries: "[0] KeyError on G['AOT_HERMETIC_WEIGHT']", exactly one "For [0]: ..." line # naming "the module the compiled function was traced in", no "instance's forward", "Add a ModelInput" ``` It captures a plain `HermeticModule` in-process, pops the global, and asserts the CAPTURED wording arrives on the report's one `For [0]:` line 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, and resolving it runs user code (`get_traced_fn` formats a forward it refuses). Dropping the SUPPLIED half of the gate, `if not tried_forward:`, fails it on the count, `Expected '_resolve_guard_scope' to not have been called. Called 1 times`, and in this file fails only it and the RECONSTRUCTED test below (`failures=2`): the CAPTURED hint ignores `forward`, and every SUPPLIED report test resolves either way. ## Gate 2: no resolve for a RECONSTRUCTED scope `test_no_match_report_resolves_no_forward_for_a_reconstructed_scope` is the gate's other exclusion: it reads SUPPLIED, not "anything but CAPTURED", and a RECONSTRUCTED hint ignores `forward` too, so resolving there would run that user code for a sentence that cannot name it. ```python data = self._two_input_global_guard_artifact(x) with self.assertLogs("torch._dynamo.aot_compile", level="WARNING"): loaded = AOTCompiledModel.deserialize(self._unresolvable_forward_module(), data) # forward is a functools.partial results = loaded.compiled_results[:1] assert results[0]._guard_scope is _GuardScope.RECONSTRUCTED with resolve as resolves, self.assertRaises(RuntimeError) as ctx: AOTCompiledModel(loaded.model, results)(x) resolves.assert_not_called() # exactly one "For [0]: ..." line, naming "missing from the scope rebuilt from the artifact" ``` It loads the two-input artifact against a module whose `forward` is a `functools.partial` -- the load that rebuilds the scope rather than resolving one -- keeps the first result, and asserts the rebuilt-scope hint arrives on one `For [0]:` line with no resolve. No global is popped: the rebuilt scope never carried the name its guard reads. Loosening the gate to `is not _GuardScope.CAPTURED` fails this test alone in the file (`failures=1`, on the same never-called count), and no other test here catches that edit. ## Gate 3: the first SUPPLIED entry, not index 0 `test_no_match_report_resolves_forward_at_the_first_supplied_entry` pins that the gate fires at the first SUPPLIED entry whatever its index, which is what `not tried_forward` buys over an index test. ```python loaded = AOTCompiledModel.deserialize(GlobalConfigModule(), self._two_input_global_guard_artifact(x)) captured = torch.compile(GlobalConfigModule(), ...); captured._aot_compile([...]) results = captured.forward.compiled_results + loaded.compiled_results[:1] assert [r._guard_scope for r in results] == [_GuardScope.CAPTURED, _GuardScope.SUPPLIED] inst = GlobalConfigModule() mixed = AOTCompiledModel(inst, results) saved = globals().pop("GLOBAL_POOLING_CONFIG") try: with resolve as resolves, self.assertRaises(RuntimeError): mixed(x) finally: globals()["GLOBAL_POOLING_CONFIG"] = saved assert resolves.call_count == 1 assert resolves.call_args.args[0] is inst # asked about the instance it was constructed with ``` Over a `[CAPTURED, SUPPLIED]` pair, built the way `test_no_match_message_hints_each_scope_a_mixed_model_failed_in` builds one, the report still resolves once and asks about the instance it was constructed with. Rewriting the gate as `i == 0 and result._guard_scope is _GuardScope.SUPPLIED` fails this test alone in the file (`failures=1`, `Expected 1 but got 0`): that mixed-scope test never patches `_resolve_guard_scope`, and both arms of `_missing_global_hint` append the same `, here vars(...)`, so its wording survives the edit even though `[1]` loses the `instance's forward` naming. ## Once: the attempt is marked before the resolve `test_no_match_report_resolves_forward_once_past_a_resolve_that_raises` pins where the attempt is marked. ```python loads = [AOTCompiledModel.deserialize(inst, data) for _ in range(2)] # two SUPPLIED results, this module's dict results = [loaded.compiled_results[0] for loaded in loads] mixed = AOTCompiledModel(inst, results) inst.forward = functools.partial(HermeticModule.forward, inst) # get_traced_fn refuses it... with self.assertRaises(ValueError): _resolve_guard_scope(inst) # ...and formatting it reaches extra_repr, which raises saved = globals().pop("AOT_HERMETIC_WEIGHT") try: with resolve as resolves, self.assertRaises(RuntimeError) as ctx: mixed(x) finally: globals()["AOT_HERMETIC_WEIGHT"] = saved # Not assert_called_once_with: a failure would repr inst, which raises. assert resolves.call_count == 1 assert resolves.call_args.args[0] is inst # message: "[0] KeyError on G[...]", "[1] KeyError on G[...]", one neutral # "For [0, 1]: a guarded global is missing from the live scope this artifact was loaded against, here vars(<module>); define it there" ``` Two `deserialize(inst, data)` loads of one `RaisingReprModule` artifact give two SUPPLIED results holding this module's dict; `inst.forward` is then rebound to a `functools.partial`, which `get_traced_fn` refuses and formats into its error, reaching the module's `extra_repr` -- the test asserts `_resolve_guard_scope(inst)` itself raises `ValueError`. With the global popped, both entries are hinted and SUPPLIED, and the report resolves once (`call_count == 1`, asked about `inst`), swallows the raise, and words both `For [0, 1]:` neutral. Moving `tried_forward = True` below the resolve, inside the `try`, leaves it unset after the raise, so `[1]` re-runs the raising user code: that fails this test on the count (`Expected 1 but got 2`) and nothing else (`failures=1`). #197001's `names_forward_only` cannot see that edit, because its resolve succeeds and the mark is set either way, and `survives_a_forward_resolve_that_raises` has one result. The count carries the assertion, because the wording cannot: both entries read the same neutral sentence whether the resolve ran once or twice. It is checked as `call_count` and `call_args.args[0]` rather than `assert_called_once_with(inst)`, because mock formats a failed match with `repr(inst)`, which is the raise. The `args[0] is inst` check is what pins which module is asked: resolving `type(self.model)()` instead fails it (`failures=5` in the file: the others are #197048's `covers_a_rebound_forward` and `survives_a_forward_resolve_that_raises` on wording, since a fresh instance does not carry the `forward` those rebind, and #197001's `names_forward_only` and `shares_a_hint_line`, which check the same). ## Mutations, summarized | edit to `_no_match_report` | fails in the whole file | | --- | --- | | drop the SUPPLIED half of the gate (`if not tried_forward:`) | `resolves_forward_only_for_a_supplied_scope`, `resolves_no_forward_for_a_reconstructed_scope` (`failures=2`) | | loosen the gate to `is not _GuardScope.CAPTURED` | `resolves_no_forward_for_a_reconstructed_scope` alone (`failures=1`) | | gate on `i == 0 and ... is _GuardScope.SUPPLIED` | `resolves_forward_at_the_first_supplied_entry` alone (`failures=1`, `Expected 1 but got 0`) | | move `tried_forward = True` inside the `try` | `resolves_forward_once_past_a_resolve_that_raises` alone (`failures=1`, `Expected 1 but got 2`) | | resolve `type(self.model)()` instead of `self.model` | `resolves_forward_once_past_a_resolve_that_raises` plus four wording tests in #197048 and #197001 (`failures=5`) | Test Plan: ``` 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 -k test_no_match_report_resolves_no_forward_for_a_reconstructed_scope python test/dynamo/test_aot_compile.py -k test_no_match_report_resolves_forward_at_the_first_supplied_entry python test/dynamo/test_aot_compile.py -k test_no_match_report_resolves_forward_once_past_a_resolve_that_raises python test/dynamo/test_aot_compile.py ``` ## FAQ > **FAQ: Every new test passes at the parent commit. Where is the red-on-parent > evidence?** > > There is none by construction: this is a tests-only commit pinning the > report the parent already ships, so every test passes on the parent's tree. > The measurements that stand in for it are above: each test fails under the > tree below the report commit, where no report exists, and each fails under a > targeted edit of `_no_match_report` that no test outside this commit catches > -- moving the `tried_forward` mark below the resolve fails only > `resolves_forward_once_past_a_resolve_that_raises`, dropping the SUPPLIED > gate only the two tests that assert no resolve at all, loosening it to > `is not _GuardScope.CAPTURED` only > `resolves_no_forward_for_a_reconstructed_scope`, and pinning it to `i == 0` > only `resolves_forward_at_the_first_supplied_entry`. > **FAQ: Why pin the resolve with call counts instead of the report's text?** > > Because the text is the same on both sides of each edit. The CAPTURED hint > never names `forward`, so `resolves_forward_only` reads identically whether > the resolve ran or not, and so does the rebuilt-scope hint for > `resolves_no_forward_for_a_reconstructed_scope`; and after a resolve that > raises, both entries get > the neutral sentence whether the raise happened once or twice, so > `resolves_forward_once` reads identically too. Both edits are visible only > as extra calls into user code -- `get_traced_fn` formatting a `forward` it > refuses -- which is what the report avoids, and what `patch(..., > wraps=_resolve_guard_scope)` counts without changing what the report does. > **FAQ: Why `try/finally` around the popped global rather than `addCleanup`?** > > Both forms are in this file and neither is a correctness difference: the pop > is undone before the next test either way. `try/finally` keeps the restore > beside the pop, so the whole window the name is missing in reads in one > place, which is what these two tests are about. Rewriting them to > `addCleanup` would change no measurement, so it is churn on a tests-only > diff. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: #197301 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220, #197001, #197569
…own wrappers (#196908) **Problem.** Loading an AOT-compiled module onto an instance whose `forward` is `torch.compile(mod.forward)` (or a `torch._dynamo.disable`, `run`, `optimize` or `wrap_top_frame` wrapper over it) refused the live guard scope, because the wrapper is a plain function whose `__globals__` is `torch._dynamo.eval_frame`'s namespace; every result fell back to the rebuilt scope and a kept guard on a user global then failed every call with `KeyError on G['CFG']` and advice the pattern cannot follow. **Fix.** `_resolve_guard_scope` now resolves THROUGH Dynamo's own wrappers -- `innermost_fn` over the `_torchdynamo_orig_callable` chain, then one `__wrapped__` hop per function that owns `external_utils`' dict -- so the scope is the user forward's module and the load serves; a wrapper that reaches the module's dispatch rather than its forward is refused with a reason naming what was reached. **Summary.** `_resolve_guard_scope` hands `model.forward` to `get_traced_fn`, takes the resolved function's `__globals__` as the live guard scope, and refuses a scope that is a torch module's namespace; the documented compile-a-method pattern, `mod.forward = torch.compile(mod.forward)`, binds eval_frame's `functools.wraps`'d `compile_wrapper`, a plain function that is neither an `OptimizedModule` nor an `nn.Module` and whose own `__globals__` is `torch._dynamo.eval_frame`'s namespace, so on the parent the torch-namespace rule refused it, every result was RECONSTRUCTED, and a kept guard on a user global failed every call with `KeyError on G['CFG']`. The fix resolves through the wrapper: `innermost_fn` follows the `_torchdynamo_orig_callable` chain the wrappers `torch.compile`, both `torch._dynamo.disable` forms, `run`, `optimize` and `optimize_assert` return, and a `while` loop then follows `__wrapped__` from any function whose `__globals__` IS `vars(external_utils)`, one hop per stacked compile, which is what `config.wrap_top_frame` or a `trace_rules.check` skip wraps the target in (`wrap_inline`'s inner). The predicate is the dict's identity read through `_static_getattr` (`object.__getattribute__`), not `__module__` (which `functools.wraps` copies) and not "defined under `torch._dynamo`" (the decorators' `wraps`'d wrappers are the root frame a capture traces, so hopping through them would disagree with it), and a bound method owns no `__globals__` for that read, so it is never hopped. What the hop reaches is re-checked: an `nn.Module` (the module's dispatch under `wrap_top_frame`) is refused with a new reason, a function torch itself defines (`Module._wrapped_call_impl`, `Linear.forward`) is refused by the namespace rule with "resolves through a Dynamo wrapper to" in its reason, a `functools.partial` or C-implemented bound method falls into the shared `try` and gets the cannot-resolve reason, and a wraps-less `external_utils` function (`error_on_graph_break`'s inner) ends the loop where it stands and is refused byte-identically to the parent. The only behaviour change is that the compiled-forward, disabled, `run`/`optimize`, `wrap_top_frame` (depth 1 and 2), user-decorator-over-compiled and instance-rebound `wrap_numpy` shapes go from refused to served with the forward's own module as the scope; every other shape is still refused, with the reason now naming the target the wrapper reached, and `inspect.unwrap` and a one-hop `_torchdynamo_orig_callable` read were rejected as alternatives on measured mismatches with what a capture records. ## The bug ```python class M(torch.nn.Module): def forward(self, x): return x * CFG.scale # CFG is a module global; keep_global_guards keeps a guard on it mod = M() mod.forward = torch.compile(mod.forward, backend="eager") # the documented compile-a-method pattern wrapper = torch.compile(mod, fullgraph=True, backend="eager") wrapper._load_aot_compiled_module(data) # parent: every result RECONSTRUCTED, warning logged, reason: # "M.forward (function named M.forward) resolves to M.forward, whose globals are # torch._dynamo.eval_frame's namespace ...; bind the module's own forward, defined outside torch, as model.forward instead" # parent: wrapper(x) -> KeyError on G['CFG'] and a hint repeating that advice # now: SUPPLIED scope = M's module dict; wrapper(x) follows CFG live ``` `mod.forward = torch.compile(mod.forward)` binds a plain function on the instance: eval_frame's `functools.wraps`'d `compile_wrapper`. It is neither an `OptimizedModule` (so `_unwrap_optimized_module` does not see it) nor an `nn.Module` (so that refusal does not either), and its own `__globals__` is `torch._dynamo.eval_frame`'s namespace, so on the parent the torch-namespace rule refuses it. Because `functools.wraps` copied the qualname, the reason reads "M.forward (function named M.forward) resolves to M.forward, whose globals are torch._dynamo.eval_frame's namespace ...; bind the module's own forward, defined outside torch, as model.forward instead": every result is RECONSTRUCTED and the load logs the no-live-scope warning. A kept guard on a global that rebuilt scope does not carry then fails every call with `KeyError on G['CFG']` and a hint repeating that advice, which the pattern cannot follow (the module's own forward is what was bound); a kept guard on a global the graph lifted compares against the serialized value and cannot fail, so the call answers with the captured value. Nothing is seeded into eval_frame's dict. `torch._dynamo.disable` (both wrappers), `torch._dynamo.run`, `optimize` and `config.wrap_top_frame` stacks are refused the same way, naming eval_frame's or `external_utils`' namespace. The capture side cannot produce any of these shapes (tracing a `compile_wrapper` dies on `set_eval_frame`), so this is a load-side mismatch only. ## The fix: resolve through the wrapper ```python # _resolve_guard_scope, now from torch._dynamo.eval_frame import _static_getattr, innermost_fn forward = model.forward described = ... # describes forward AS GIVEN, not what the hop reaches resolved = innermost_fn(forward) # follows the _torchdynamo_orig_callable chain while _static_getattr(resolved, "__globals__") is vars(external_utils): wrapped = _static_getattr(resolved, "__wrapped__") if wrapped is None: break # a wraps-less external_utils function ends the loop where it stands resolved = wrapped # one hop per stacked compile if isinstance(resolved, torch.nn.Module): return None, f"{described} resolves through a Dynamo wrapper to an nn.Module, the module's dispatch rather than its forward; ..." try: traced_fn = convert_frame.get_traced_fn(resolved)[0] # parent: get_traced_fn(forward) scope = traced_fn.__globals__ except (RuntimeError, AttributeError): return None, <the parent's cannot-resolve reason> namespace = _module_namespace_name(scope) if namespace is not None and namespace.partition(".")[0] == "torch": via = "resolves through a Dynamo wrapper to" if resolved is not forward else "resolves to" return None, f"{described} {via} {traced_fn.__qualname__}, whose globals are {namespace}'s namespace, ..." return scope, None ``` `innermost_fn` runs on a non-Module forward before `get_traced_fn`: it is what `_TorchDynamoContext.__call__` runs on everything it compiles, follows the `_torchdynamo_orig_callable` chain by `_torchdynamo_wrapper_id == id(fn)` and so stops at a wrapper Dynamo did not mint, and covers both disable wrappers, `run`, `optimize` and `optimize_assert`, which set the same pair. That is not always the user's forward: when the compile wrapped its target in `external_utils.wrap_inline` (`config.wrap_top_frame`, or `trace_rules.check` true for a forward DEFINED under `torch/`), the chain ends on `wrap_inline`'s inner, a `functools.wraps` copy of the bound method that carries neither `_torchdynamo_orig_callable` nor a matching wrapper id. `inner` only calls the forward it wraps, and the module capture (`aot_compile_module` -> `aot_compile_fullgraph` on `model.forward`) never wraps, so the load follows `__wrapped__` while the resolved function OWNS `external_utils`' dict as its `__globals__`, one hop per stacked compile. ```python # test_aot_compile_module_deserialize_unwraps_a_wrap_inline_forward, depth=2 with torch._dynamo.config.patch(wrap_top_frame=True): mod.forward = torch.compile(mod.forward, backend="eager") mod.forward = torch.compile(mod.forward, backend="eager") resolved = innermost_fn(mod.forward) # chain: [("inner", vars(external_utils)), ("inner", vars(external_utils))], then the bound forward ``` **The predicate.** It is that dict's identity, not "defined under `torch._dynamo`": `functools.wraps` copies `__module__`, so `inner` reports the forward's; and `torch._dynamo.decorators`' `wraps`'d wrappers (`nonstrict_trace`, `leaf_function`) are what the capture traces as its root frame, so hopping through them would disagree with it. The reads go through eval_frame's `_static_getattr`, which is `object.__getattribute__`: a bound method's `__globals__` is supplied by `method_getattro`'s delegation to `__func__`, not by the generic slot, so a bound method is never hopped (measured: `object.__getattribute__(bound, "__globals__")` raises `AttributeError` while `bound.__globals__` answers). ## What the hop can land on **A wraps-less `external_utils` function.** One that carries no `__wrapped__` ends the loop where it stands, since the hop cannot reach the forward it stands in front of: `wrap_dunder_call_ctx_manager`'s inner, which `error_on_graph_break`, `patch_dynamo_config`, `disable_nested_graph_breaks` and `override_cudagraphs` all bind (measured: each yields a function of that qualname owning `external_utils`' dict with no `__wrapped__`), skips `functools.wraps` on purpose. Here it falls through to the namespace rule, which refuses it exactly as the parent does -- "inner resolves to inner, whose globals are torch._dynamo.external_utils's namespace ...; bind the module's own forward, defined outside torch" (byte-identical to the parent's reason; the forward in `inner`'s closure IS defined outside torch, so that advice is one the shape had already followed) -- and the commit above gives the shape its own reason. **An `nn.Module`.** The `nn.Module` refusal then runs again on what the hop reached: under `config.wrap_top_frame` or a skip rule, `torch.compile(mod).forward` wraps the module itself (`OptimizedModule._initialize` hands it to `wrap_inline`), the module's dispatch rather than its forward, and without this refusal `get_traced_fn`'s Module branch would resolve that module to its forward and serve the dispatch shape. ```python # test_aot_compile_module_deserialize_refuses_a_compiled_module_forward with torch._dynamo.config.patch(wrap_top_frame=wrap_top_frame): inst.forward = torch.compile(inst, backend="eager").forward # wrap_top_frame=True: innermost_fn(...).__wrapped__ is inst -> "... resolves through a Dynamo wrapper to an nn.Module, # the module's dispatch rather than its forward; bind that module's forward, or a wrapper over the # forward rather than over the module, as model.forward instead" # wrap_top_frame=False: innermost_fn(...) == inst.__call__ -> "... resolves through a Dynamo wrapper to Module._wrapped_call_impl, # whose globals are torch.nn.modules.module's namespace, ..." ``` **A target `get_traced_fn` cannot resolve.** `get_traced_fn` and the `__globals__` read share one `try` -- `RuntimeError` for a callable that is neither function nor method (a hopped-to `functools.partial`), `AttributeError` for a C-implemented bound method (`torch.compile(t.sum)` hops to the builtin, whose `__func__` read raises) -- and the `except` returns the parent's cannot-resolve reason, which describes the forward as given ("get_traced_fn cannot resolve M.forward (function named wrap_inline.<locals>.inner) to a Python function; make model.forward a plain function or bound method"); for a hopped-to target that advice describes the `compile_wrapper`, a plain function that resolves fine, and the commit above names what the wrapper reached instead. **A torch-defined function.** The torch-namespace reason says "resolves through a Dynamo wrapper to" when the hop was taken (`test_aot_compile_module_deserialize_hops_to_a_compiled_torch_forward`: `Linear.forward (function named Linear.forward) resolves through a Dynamo wrapper to Linear.forward, whose globals are torch.nn.modules.linear's namespace`, refused silently since the artifact roots no guard at a user global). `innermost_fn`'s `AssertionError` on a non-callable `_torchdynamo_orig_callable` is not caught: every Dynamo site that sets the pair on a function checks `callable(fn)` first, and the `OptimizedModule` sites sit behind the as-given `nn.Module` refusal. ## Behaviour against the parent, per forward shape "Refused" = `(None, reason)`, RECONSTRUCTED, no match at call for every kept guard on a global the rebuilt scope lacks; "served" = SUPPLIED with the named dict, guards re-read there, `__import_*` aliases seeded there. | forward shape | parent | now | | --- | --- | --- | | `torch.compile(mod.forward)`, `torch._dynamo.run` / `optimize`, both `torch._dynamo.disable` wrappers, `config.wrap_top_frame` stacks of depth 1 and 2, `torch.compile(user_deco(mod.forward))`, `mod.forward = torch.compiler.wrap_numpy(mod.forward)` | refused (eval_frame's or external_utils' namespace) | served, the dict of the forward the wrapper wraps (the user module's; the decorator's module for `user_deco`, which is what a capture of that shape records). **The only behaviour change.** | | `torch.compile(nn.Linear(..).forward)` | refused | refused; the reason now names `Linear.forward` in `torch.nn.modules.linear` instead of eval_frame | | `inst.forward = torch.compile(inst).forward` | refused | refused; the reason now names `Module._wrapped_call_impl` (`wrap_top_frame` off) or "an nn.Module, the module's dispatch" (`wrap_top_frame` on) instead of eval_frame | | `torch.compile(functools.partial(...))`, `torch.compile(x.sum)` | refused ("inner resolves to inner" / "Tensor.sum resolves to Tensor.sum, whose globals are eval_frame's namespace", measured) | refused; the reason is now the cannot-resolve one, since `get_traced_fn` fails on the partial / builtin the hop reached. Its advice describes the `compile_wrapper`; the commit above names the reached target | | `torch._dynamo.error_on_graph_break(True)(mod.forward)` and the other three `wrap_dunder_call_ctx_manager` binders, a class-body `@torch.compiler.wrap_numpy` forward, `mod.forward = inst.__call__` after `torch.compile(Cls)`, `torch.compile(LazyLinear).forward`, `mod.forward = other.__call__`, an `nn.Module` bound as forward, an un-hopped builtin | refused | unchanged, byte-identical reason (measured). A bound method owns no `__globals__`, so the hop leaves it alone, and the wraps-less inner is left where it stands. The first three are reworded by the commit above | ## The instance-rebound `wrap_numpy` hop The instance-rebound `wrap_numpy` hop is the one place the load sees through a wrapper the caller applied, and the class docstring says so inline: `wrap` is a plain function owning `external_utils`' dict and a `__wrapped__`, so it is hopped to the bound method, which a capture of that shape (root frame `wrap`) would not record. No such artifact exists -- `wrap`'s closure holds the bound method and with it the module instance, which `serialize` refuses -- and the one loadable combination, an artifact captured from the undecorated forward loaded onto that shape, resolves the user module, which is what that capture recorded. The `other.__call__` shape stays refused although a capture of it did record `nn.Module`'s namespace: accepting would seed a process-wide torch namespace, and a same-shape artifact still reports no match on its self guard. ## Two shorter unwraps, rejected Both were rejected on measured behaviour. - `inspect.unwrap` follows every `functools.wraps` chain, including a user decorator, but the capture traces the outermost plain function and records its `__globals__` as the scope (for `mod.forward = user_deco(mod.forward)` that is the decorator's module), so it would mismatch the capture for exactly that shape. - A one-hop `getattr(forward, "_torchdynamo_orig_callable", forward)` is defeated by the same `wraps`: the copied `__dict__` carries `_torchdynamo_orig_callable`, so one hop jumps past a user wrapper over a compiled forward to the bound method, and a nested `torch.compile(torch.compile(f))` stays in eval_frame after one hop. ## The `deserialize` docstring The docstring states the rule -- the function `model.forward` resolves to is the one bound as `forward` seen through the wrappers `torch.compile`, `torch._dynamo.disable`, `run`, `optimize` and `optimize_assert` return and through any function DEFINED IN `external_utils` that carries `__wrapped__` -- and flags the caller-applied exception inline, where the rule is stated ("of which torch.compiler.wrap_numpy and torch._dynamo.disable(recursive=False) are the two a caller applies -- but not through any other wrapper the caller applied"), so no sentence is false until a later one corrects it; the sentence after the rule gives `wrap_numpy`'s two forms, the forward's own module when rebound on the instance and a refused `external_utils` namespace when applied in the class body, where it binds a method that is not seen through. The docstring's list of no-live-scope causes gains the wraps-less `external_utils` function, the post-hop `nn.Module` and the hopped-target paths, each of which this commit refuses. The SUPPLIED no-match hint is untouched: it still says the guards hold the globals of "the function this <Type> instance's forward resolves to, since that is the one the load resolved", true of the resolution but silent about the wrapper it went through; the commit above sends it through too. The fallback reasons keep the shape-specific advice `_missing_global_hint` already splices after "rebuilt because" (pre-existing). ## Tests Five new tests, eight cases with parametrization, each described under the Test Plan with the mutations that fail it: - `test_aot_compile_module_deserialize_unwraps_a_compiled_forward`: the served result for `mod.forward = torch.compile(mod.forward)`, the SUPPLIED scope being this module's dict, and eval_frame's namespace gaining nothing. - `test_aot_compile_module_deserialize_unwraps_a_wrap_inline_forward` (depth 1, 2): the same under `wrap_top_frame`, pinning the `("inner", vars(external_utils))` chain per stacked compile. - `test_aot_compile_module_deserialize_unwraps_a_disabled_forward` (recursive True, False): the same for both disable wrappers, recording which mechanism reaches the bound method first. - `test_aot_compile_module_deserialize_refuses_a_compiled_module_forward` (wrap_top_frame False, True): the two dispatch reasons, and that `vars(torch.nn.modules.module)` gains nothing. - `test_aot_compile_module_deserialize_hops_to_a_compiled_torch_forward`: the hop lands on `Linear.forward`, refused silently since it reads no user global. Test Plan: Five new tests, 8 cases with parametrization, all failing with the parent's aot_compile.py (`git show <parent>:torch/_dynamo/aot_compile.py` checked out under this commit's test file: 5 errors, 3 failures). The five served-shape cases error there with `No AOT compiled graph matched` (the refused load rebuilt the scope, which lacks GLOBAL_POOLING_CONFIG); the three reason-text cases fail on the reason string. `..._deserialize_unwraps_a_compiled_forward` rebinds `mod.forward = torch.compile(mod.forward)` and loads through `_load_aot_compiled_module`, pinning the served result, the SUPPLIED scope being this module's dict and eval_frame's namespace gaining nothing (a fence; the parent seeds nothing either); `..._unwraps_a_wrap_inline_forward` (depth 1, 2) and `..._unwraps_a_disabled_forward` (recursive True, False) pin the same for those shapes and the wrapper chain they resolve through; `..._deserialize_refuses_a_compiled_module_forward` (wrap_top_frame False, True) pins the two dispatch reasons and that vars(torch.nn.modules.module) gains nothing; `..._deserialize_hops_to_a_compiled_torch_forward` pins that the hop lands on Linear.forward, refused silently since it reads no user global. Mutations at this commit, each run over the 8 cases the -k patterns below select: with the hop's `while` made a single `if` (one hop) the depth_2 wrap_inline case reports no match and `..._refuses_a_compiled_module_forward_wrap_top_frame_True` fails on the reason (one hop lands on the second wrap_inline inner, in external_utils' namespace; _initialize wraps the module, then __call__ wraps that inner); with the post-hop nn.Module refusal removed only `..._refuses_a_compiled_module_forward_wrap_top_frame_True` fails, on the reason; with innermost_fn dropped (`resolved = forward`, hop kept) 7 of the 8 fail as on the parent and `..._unwraps_a_disabled_forward_recursive_False` passes, because that wrapper owns external_utils' dict and carries __wrapped__, so the hop alone reaches the bound method. ``` python test/dynamo/test_aot_compile.py -k deserialize_unwraps_a python test/dynamo/test_aot_compile.py -k deserialize_hops_to python test/dynamo/test_aot_compile.py -k deserialize_refuses_a_compiled_module_forward python test/dynamo/test_aot_compile.py lintrunner --take RUFF,PYFMT -- torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py ``` The full file reports `OK (skipped=6)` (311 tests). > **FAQ: The `recursive` parametrization of `..._unwraps_a_disabled_forward` > is over-determined: deleting `resolved = innermost_fn(forward)` from > `_resolve_guard_scope` fails `recursive_True` only, because the non-recursive > wrapper owns external_utils' dict and carries `__wrapped__`, so the hop > rescues it; and the assertion that isolates the mechanism calls > `eval_frame.innermost_fn` directly, a contract test for that function.** > > Both measured and both kept. The `recursive_False` case is not there to > isolate a mechanism; it pins the served result for the one shape whose > wrapper is an external_utils function that ALSO carries the > `_torchdynamo_orig_callable` pair, which no other served case has, so a > regression in either mechanism's handling of that shape would show here > first. The case also pins `mod.forward.__wrapped__ == bound_forward`, which > states that the hop would fire. The `innermost_fn(mod.forward) == > bound_forward` assertion records > which mechanism reaches the bound method first (measured: with `innermost_fn` > mutated to stop on external_utils-owned wrappers, `recursive_False` fails on > that assertion and, with it removed, passes on the hop); the test's comment > says that, and that only `recursive_True` catches a load that drops > `innermost_fn`. Making the case discriminate against that mutation would > mean asserting the hop did NOT fire, which is not a property the load has or > should promise. > **FAQ: `mod.forward = other.__call__` resolves to `Module._wrapped_call_impl` > with no Dynamo wrapper in front, and a capture of that same shape records > `vars(torch.nn.modules.module)` as `_extra_globals`. Why refuse a dict the > capture agreed on?** > > Because accepting it seeds a process-wide torch namespace, and buys nothing: > measured, a same-shape artifact (root frame `_wrapped_call_impl`, kept guards > rooted at `G['_global_forward_hooks']` and `G['__import_npmod2']`) loaded onto > a fresh `m.forward = other.__call__` module with > `guard_globals=vars(torch.nn.modules.module)` still reports no match on every > call -- the capture traced `other` as `self`, so its guard `not > ___dict_contains('forward', L['self'].__dict__)` fails against the loaded > model, whose `__dict__` carries the rebind. The refusal costs nothing served > and keeps `__import_*` aliases and the `__builtins_dict___N` key out of > nn.Module's dict; > `test_aot_compile_module_deserialize_refuses_a_bound_module_call_forward` pins > the shape one commit up (#197319); the refusal and the comment stating the > tradeoff are here, and measured at this commit the shape is refused naming > `torch.nn.modules.module`'s namespace. > **FAQ: The comment says a `torch.compiler.wrap_numpy` forward is not hopped > because a bound method owns no `__globals__`. An instance rebind `mod.forward > = wrap_numpy(mod.forward)` stores the plain function `wrap`, which owns > `vars(external_utils)` and `__wrapped__`, so it IS hopped -- and a capture of > that shape records `external_utils`. Is that a live capture/load > disagreement?** > > Real at the resolution level, unreachable end to end, so the comment now > states both halves precisely and the hop is unchanged. Measured: the capture > of the rebound shape records `_extra_globals = torch._dynamo.external_utils` > (root code `wrap`) while `_resolve_guard_scope` on the same shape resolves the > user module through one hop. But `_save_aot_compiled_module` on that capture > raises `Failed to serialize the following objects: [PlainNp()]` -- `wrap`'s > closure holds the bound method and with it the module instance -- so no such > artifact exists. A class-body `@wrap_numpy` capture serializes but no load of > it gets as far as the scope: `deserialize` dies in GraphPickler (`module > 'torch._dynamo.utils' has no attribute 'wrapped_sum'`). The one loadable > combination, an artifact captured from the undecorated forward loaded onto the > instance-rebound shape, resolves the user module, which is exactly what that > capture recorded, and serves. Stopping the hop on `wrap` (matching > `wrap_inline`'s inner by code identity) would make THAT case disagree instead, > for a shape nothing can observe. > **FAQ: Is `resolved: Any` needed for pyrefly?** > > No; it was dropped. `lintrunner --take PYREFLY -- > torch/_dynamo/aot_compile.py` at this commit reports the identical set of > eight pre-existing `_torch_function_state` missing-attribute diagnostics with > and without the annotation. `innermost_fn` returns `Callable[..., Any]` and > `_static_getattr` returns `Any`, so the `__wrapped__` reassignment already > type-checks. > **FAQ: The `torch.compile(torch.nn.Linear(8, 3))` test used to pin the load > resolving `vars(torch.nn.modules.linear)` as the SUPPLIED scope; now it pins a > refusal. Why did the behaviour change?** > > The introducing commit below now refuses any resolution whose `__globals__` is > a torch module's live namespace, so a torch-defined forward is refused after > the hop lands on it. The test > (`..._deserialize_hops_to_a_compiled_torch_forward`) still proves what it was > for -- the hop lands on `Linear.forward` and not on external_utils' inner, > which the reason names -- and additionally pins that the fallback is silent: > `Linear.forward` reads only torch's own globals, `_has_global_guards` is False > under both filters, the call answers, and external_utils' namespace gains > nothing. > **FAQ: Why drop the `AssertionError` arm instead of giving it a reason?** > > Measured unreachable from any Dynamo-minted wrapper: > `eval_frame.py:1337`/`:1571` and `decorators.py:119` set > `_torchdynamo_orig_callable` only after `callable(fn)` passed, and the > OptimizedModule sites (`eval_frame.py:1062`, `:1500`) are only reached when > forward is an OptimizedModule, which the nn.Module refusal returns before > `innermost_fn`. A hand-stamped pair now raises `innermost_fn`'s own > `AssertionError` ("A callable function is expected, but <class 'int'> is > provided") rather than a reason blaming `get_traced_fn`, which was never > called. > **FAQ: Is the fourth dispatch shape (`torch.compile(Cls)` rebinding > `Cls.__call__`) pinned?** > > Yes, bound directly as `mod.forward = inst.__call__` > (`test_aot_compile_module_deserialize_refuses_a_class_compiled_call_forward`, > one commit up in #197319; measured here, the shape is refused with the > torch-namespace reason naming `torch._dynamo.eval_frame`, byte-identical to > the parent's). The reviewer's > route `torch.compile(inst)` after `torch.compile(Cls)` raises `compile_wrapper > already has a get_compiler_config attribute` in eval_frame, and > `torch.compile(OptimizedModule)` does not re-wrap `__call__` (`innermost_fn` > unwraps it to `_orig_mod.forward`), so neither is reachable; > `torch._dynamo.disable(inst).forward` is refused the same way (measured). > **FAQ: A previous revision of this PR returned three shape-specific reasons > that this one does not -- the wraps-less external_utils function's own > reason, a hopped-to target's own cannot-resolve reason, and the > `co_qualname` naming of a `functools.wraps`'d wrapper. Were they dropped?** > > No: this commit was split in two, and all three, with the tests that pin > them (`..._refuses_a_targetless_dynamo_wrapper`, > `..._refuses_a_class_body_wrap_numpy_forward`, > `..._refuses_a_class_compiled_call_forward`, > `..._fallback_names_a_compiled_partial_forward`, > `..._fallback_names_a_compiled_builtin_forward` and the three > `..._hint_sees_through_a_wrapped_rebound_forward` cases), are the commit > directly above, #197319. Measured at this commit against its parent, nothing > served changes and no reason regresses: > `error_on_graph_break(True)(mod.forward)`, a class-body > `@torch.compiler.wrap_numpy` forward and `mod.forward = inst.__call__` after > `torch.compile(Cls)` are refused with reasons byte-identical to the > parent's, and `torch.compile(functools.partial(...))` / > `torch.compile(x.sum)` are refused with the cannot-resolve text where the > parent said "inner resolves to inner" / "Tensor.sum resolves to Tensor.sum" > -- neither names the target the hop reached, which is what the commit above > adds. > **FAQ: The docstring's no-live-scope list names a > `torch._dynamo.external_utils` function with no `__wrapped__` and a target > reached by the hop that does not resolve itself, but this commit has no > branch for either: the first falls through to the namespace rule and the > second shares the cannot-resolve reason. Is the list wrong?** > > No -- it enumerates the causes of there being no live scope, not the reason > strings, and both hold here (measured: > `error_on_graph_break(True)(mod.forward)` is refused naming external_utils' > namespace, and a hopped-to `functools.partial` is refused because > `get_traced_fn` raises on it). Each cause is one the caller can act on; > which of them gets a reason of its own is the commit above. > **FAQ: Nothing in `test_aot_compile.py` mentions `wrap_numpy` at this > commit, yet the docstring makes two claims about it.** > > The class-body arm is pinned one commit up by > `..._deserialize_refuses_a_class_body_wrap_numpy_forward` (#197319); > measured here, that shape is refused with the parent's reason. The arm that > rebinds on the instance has no end-to-end test because no artifact reaches > it -- > `serialize` refuses `wrap`'s closure, which holds the module instance, and a > class-body capture dies in GraphPickler, both measured in the FAQ above -- > so the only half that could be asserted is a direct `_resolve_guard_scope` > call on a shape no load can use. This commit was authored with the assistance of an AI coding assistant. Co-Authored-By: Claude Fable 5.1 <[email protected]> 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #196908 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220, #197001, #197569, #197301
…usals and the no-match hint (#197319) **Problem.** #196908 taught the module load to resolve `model.forward` through Dynamo's own wrappers, but left three refusal messages describing the forward as if no wrapper were there (one even gave advice the shape had already followed, another attributed the wrong namespace) and left the missing-global hint silent about the wrapper the load saw through. **Fix.** Wording only: refuse a wraps-less `external_utils` function with its own reason naming the decorators that produce it, name what a hopped wrapper reached when `get_traced_fn` cannot resolve it, name a `functools.wraps`'d wrapper by its code object instead of the copied `__qualname__`, and make the hint say the forward is seen through those wrappers. No shape flips between served and refused. **Summary.** The commit below resolves `model.forward` through Dynamo's own wrappers (`innermost_fn`, then one `__wrapped__` hop per `external_utils`-owned function) but leaves three refusals describing the forward as the parent did, and leaves the SUPPLIED no-match hint silent about the wrapper the load went through. This commit changes wording only: no shape flips between served and refused (measured: `_resolve_guard_scope` returns None for the same shapes before and after, with the same scope for the served ones). A wraps-less `external_utils` function -- the `inner` that `error_on_graph_break`, `patch_dynamo_config`, `dont_skip_tracing`, `disable_nested_graph_breaks` and `override_cudagraphs` bind -- is refused with its own reason instead of falling through to the namespace rule, which rendered "inner resolves to inner ...; bind the module's own forward, defined outside torch", advice the shape had already followed; a hop that reaches something `get_traced_fn` cannot resolve (a `functools.partial` or a C-implemented bound method under `torch.compile`) names what the wrapper reached instead of advising "make model.forward a plain function or bound method", which described the `compile_wrapper`, a plain function that resolves fine. The torch-namespace reason names a function carrying a `__wrapped__` by its code object (`co_qualname`, falling back to `co_name`), because `functools.wraps` copied the wrappee's `__qualname__` onto it and the copied name would read "M.forward resolves to M.forward" or, worse, attribute the wrapper's namespace to the wrappee. The SUPPLIED hint now says the forward is seen "through the wrappers torch.compile, torch._dynamo.disable, run and optimize return and through any functools.wraps'd torch._dynamo.external_utils function to the function they wrap", the rule the `deserialize` docstring already states, so a reader is not sent to define the name in the wrapper's namespace, where it restores nothing. ## The wraps-less `external_utils` function ```python # _resolve_guard_scope, the hop loop while _static_getattr(resolved, "__globals__") is vars(external_utils): wrapped = _static_getattr(resolved, "__wrapped__") if wrapped is None: # parent: break, then fall through to the namespace rule hopped = resolved is not forward via = "resolves through a Dynamo wrapper to" if hopped else "is" return None, ( f"{described} {via} a torch._dynamo.external_utils function with " "no __wrapped__ to see through to the forward it wraps -- the " "wrapper torch._dynamo.error_on_graph_break, patch_dynamo_config, " "dont_skip_tracing, disable_nested_graph_breaks and " "override_cudagraphs return skips functools.wraps; bind the " "forward that decorator wrapped as model.forward instead" ) resolved = wrapped ``` `wrap_dunder_call_ctx_manager`'s inner, which `error_on_graph_break`, `patch_dynamo_config`, `dont_skip_tracing`, `disable_nested_graph_breaks` and `override_cudagraphs` all bind (measured: each yields a function of that qualname owning `external_utils`' dict with no `__wrapped__`), skips `functools.wraps` on purpose, as does `wrap_inline_with_error_on_graph_break`'s wrapper, which only ever lives on `compile_wrapper._torchdynamo_inline`, an attribute `innermost_fn` does not follow, so no public API binds it as a forward. The namespace rule rendered "inner resolves to inner ...; bind the module's own forward, defined outside torch", because `described` and `traced_fn` are the same un-wraps'd function and the forward in inner's closure IS defined outside torch, so the advice was one the shape had already followed. ```python mod.forward = torch._dynamo.error_on_graph_break(True)(mod.forward) # parent: GlobalConfigModule.forward (function named wrap_dunder_call_ctx_manager.<locals>.inner) # resolves to wrap_dunder_call_ctx_manager.<locals>.inner, whose globals are # torch._dynamo.external_utils's namespace ...; bind the module's own forward, defined outside torch # now: GlobalConfigModule.forward (function named wrap_dunder_call_ctx_manager.<locals>.inner) is a # torch._dynamo.external_utils function with no __wrapped__ to see through to the forward it # wraps -- the wrapper torch._dynamo.error_on_graph_break, patch_dynamo_config, dont_skip_tracing, # disable_nested_graph_breaks and override_cudagraphs return skips functools.wraps; bind the # forward that decorator wrapped as model.forward instead ``` The reason now describes the function as what it is, names the decorators that return such a wrapper, and advises binding the forward that decorator wrapped, which is where the user's forward actually is. It says "resolves through a Dynamo wrapper to" instead of "is" when `innermost_fn` or an earlier hop moved before the loop stopped. ## What a hopped wrapper reached ```python try: traced_fn = convert_frame.get_traced_fn(resolved)[0] scope = traced_fn.__globals__ except (RuntimeError, AttributeError): if resolved is forward: # the un-hopped shape keeps the parent's reason return None, (f"get_traced_fn cannot resolve {described} to a Python function; " "make model.forward a plain function or bound method so its own " "globals are used instead") return None, ( f"{described} resolves through a Dynamo wrapper to an instance of " f"{type(resolved).__name__}, which get_traced_fn cannot resolve to " "a Python function; bind a plain function or bound method as " "model.forward instead" ) ``` When the hop reached something `get_traced_fn` cannot resolve -- `RuntimeError` for a callable that is neither function nor method (`torch.compile` over a `functools.partial` wraps it in `wrap_inline`, so the hop lands on the partial), `AttributeError` for a C-implemented bound method (`torch.compile(t.sum)` hops to the builtin, whose `__func__` read raises) -- the reason names what the wrapper reached. The cannot-resolve advice the commit below returned for both, "make model.forward a plain function or bound method", described the `compile_wrapper`, a plain function that resolves fine; the un-hopped builtin, bound as forward directly, keeps it. ```python mod.forward = torch.compile(functools.partial(GlobalConfigModule.forward, mod), backend="eager") # now: GlobalConfigModule.forward (function named wrap_inline.<locals>.inner) resolves through a # Dynamo wrapper to an instance of partial, which get_traced_fn cannot resolve to a Python # function; bind a plain function or bound method as model.forward instead mod.forward = torch.compile(x.sum, backend="eager") # now: ... (function named Tensor.sum) resolves through a Dynamo wrapper to an instance of # builtin_function_or_method, which get_traced_fn cannot resolve ... mod.forward = x.sum # unchanged: cannot resolve GlobalConfigModule.forward (builtin_function_or_method named Tensor.sum) # to a Python function; make model.forward a plain function or bound method ... ``` ## A wraps'd wrapper, named by its code object ```python what = traced_fn.__qualname__ wrapped = _static_getattr(traced_fn, "__wrapped__") code = _static_getattr(traced_fn, "__code__") if wrapped is not None and code is not None: what = (f"{getattr(code, 'co_qualname', code.co_name)}, a functools.wraps'd " f"wrapper over {getattr(wrapped, '__qualname__', what)}") return None, (f"{described} {via} {what}, whose globals are {namespace}'s namespace, " "a torch module a load neither roots guards in nor seeds; bind the ...") ``` The torch-namespace reason names the function it refuses by its code object when that function carries a `__wrapped__`: `functools.wraps` copied the wrappee's `__qualname__` onto it, so the copied name would read "M.forward resolves to M.forward" (a class-body `torch.compiler.wrap_numpy` forward is a bound method of `external_utils`' `wrap`; `torch.compile(Cls)` rebinds `Cls.__call__` to a `compile_wrapper` over `Module._wrapped_call_impl`) or, worse, attribute the wrapper's namespace to the wrappee. Such a function is named "<co_qualname>, a functools.wraps'd wrapper over <wrappee qualname>"; `co_qualname` is 3.11+ and falls back to `co_name`, the convention this file already uses for the dropped-attribute warning. That code object is read with `_static_getattr`, like the `__wrapped__` probe above it, so a forward carrying one and not the other keeps the plain-qualname wording instead of raising (measured: a carrier with `__globals__`, `__wrapped__` and `__qualname__` but no `__code__` is refused by name here, where a plain `traced_fn.__code__` read raises `AttributeError` on it). ```python class NumpyForwardModule(torch.nn.Module): @torch.compiler.wrap_numpy def forward(self, x): return x.sum(1) # parent: NumpyForwardModule.forward (method named NumpyForwardModule.forward) resolves to # NumpyForwardModule.forward, whose globals are torch._dynamo.external_utils's namespace ... # now: ... resolves to wrap_numpy.<locals>.wrap, a functools.wraps'd wrapper over # NumpyForwardModule.forward, whose globals are torch._dynamo.external_utils's namespace ... torch.compile(Compiled, backend="eager"); mod.forward = Compiled().__call__ # parent: ... resolves to Module._wrapped_call_impl, whose globals are torch._dynamo.eval_frame's # namespace (false: _wrapped_call_impl's globals are torch.nn.modules.module's) # now: ... resolves to _TorchDynamoContext.__call__.<locals>.compile_wrapper, a functools.wraps'd # wrapper over Module._wrapped_call_impl, whose globals are torch._dynamo.eval_frame's namespace ``` ## The SUPPLIED hint follows the resolution ```python # _missing_global_hint where = ( # parent: f"the globals of the function {forward} resolves to, which is the dict the guards hold{named}" f"the globals of the function {forward} resolves to, seen through " "the wrappers torch.compile, torch._dynamo.disable, run and " "optimize return and through any functools.wraps'd " "torch._dynamo.external_utils function to the function they wrap, " f"which is the dict the guards hold{named}" if forward is not None else f"the live scope this artifact was loaded against{named}" ) ``` The hint said the guards hold the globals of "the function this <Type> instance's forward resolves to, since that is the one the load resolved", which for `mod.forward = torch.compile(mod.forward)` would name `compile_wrapper`. It now names the wrappers `innermost_fn` follows (every `_TorchDynamoContext` subclass sets the pair: `OptimizeContext` for `optimize`, `RunOnlyContext` for `run`, `DisableContext` for `disable`) and the hop's predicate, so it neither claims decorators' wrappers (`nonstrict_trace`, `leaf_function`, `substitute_in_graph`: not crossed, refused as torch namespaces) nor omits `wrap_numpy` (crossed, `external_utils`' `wrap`). This is the rule the `deserialize` docstring already states, in the same terms. The fallback reasons keep the shape-specific advice `_missing_global_hint` already splices after "rebuilt because" (pre-existing). ```python inst.forward = torch.compile(inst.forward, backend="eager") # or torch._dynamo.disable(..., recursive=...) reloaded._load_aot_compiled_module(data); reloaded(x) # [0] KeyError on G['AOT_HERMETIC_WEIGHT'] ... this HermeticModule instance's forward resolves to, # seen through the wrappers torch.compile, torch._dynamo.disable, run and optimize return and through # any functools.wraps'd torch._dynamo.external_utils function to the function they wrap, which is the # dict the guards hold inst.forward.__globals__["AOT_HERMETIC_WEIGHT"] = saved # the wrapper's namespace: restores nothing globals()["AOT_HERMETIC_WEIGHT"] = saved # the resolved function's: served ``` ## Behaviour vs the commit below, per forward shape Every shape is refused there and here; only the reason text moves. | forward shape | commit below | this commit | | --- | --- | --- | | `torch._dynamo.error_on_graph_break(True)(mod.forward)` and the other four `wrap_dunder_call_ctx_manager` binders | "inner resolves to inner ...; bind the module's own forward, defined outside torch", advice the shape had already followed | an `external_utils` function with no `__wrapped__`; names those decorators; advises binding the forward the decorator wrapped | | a class-body `torch.compiler.wrap_numpy` forward | "M.forward resolves to M.forward, whose globals are torch._dynamo.external_utils's namespace" | "resolves to wrap_numpy.<locals>.wrap, a functools.wraps'd wrapper over M.forward, whose globals are torch._dynamo.external_utils's namespace" | | `mod.forward = inst.__call__` after `torch.compile(Cls)` | "Module._wrapped_call_impl, whose globals are torch._dynamo.eval_frame's namespace" -- false, `_wrapped_call_impl`'s globals are `torch.nn.modules.module`'s | "_TorchDynamoContext.__call__.<locals>.compile_wrapper, a functools.wraps'd wrapper over Module._wrapped_call_impl, whose globals are torch._dynamo.eval_frame's namespace" | | `torch.compile(functools.partial(...))`, `torch.compile(x.sum)` | "get_traced_fn cannot resolve ... to a Python function; make model.forward a plain function or bound method" | names the `partial` / `builtin_function_or_method` the wrapper reached | | no-match hint for a served-through-a-wrapper forward whose guarded global is missing | names the function the forward resolves to | names the wrappers the load saw through | | `torch.compile(LazyLinear).forward`, `mod.forward = other.__call__`, an un-hopped builtin, every served shape | unchanged | byte-identical reason or scope | A bound method owns no `__globals__`, so the hop leaves it alone, and none of the unchanged shapes resolve to a wraps'd function. ## Tests - `test_no_match_message_hint_sees_through_a_wrapped_rebound_forward` (`compile`, `disable`, `disable_nonrecursive`) pins the hint's wording and that defining the name in the wrapper's namespace restores nothing. - `test_aot_compile_module_deserialize_refuses_a_targetless_dynamo_wrapper` pins the wraps-less `external_utils` reason whole, that `dont_skip_tracing` binds the same inner (the shape `torch/export/_unlift.py` already assigns as an `nn.Module`'s forward), and that `external_utils`' namespace gains nothing. - `test_aot_compile_module_deserialize_refuses_a_class_body_wrap_numpy_forward` (module-level `NumpyForwardModule`) pins the wraps-aware naming of `wrap` and the same fence. - `test_aot_compile_module_deserialize_refuses_a_class_compiled_call_forward` pins the wraps-aware naming of the `compile_wrapper` that `torch.compile(Cls)` rebinds as `Cls.__call__`. - `test_aot_compile_module_fallback_names_a_compiled_partial_forward` and `test_aot_compile_module_fallback_names_a_compiled_builtin_forward` pin the hopped-target reason whole through `_assert_forward_refused`; the latter also pins that the un-hopped builtin keeps the as-given cannot-resolve reason. - `test_aot_compile_module_deserialize_refuses_a_lazy_module_forward` (both `wrap_top_frame` settings) and `test_aot_compile_module_deserialize_refuses_a_bound_module_call_forward` are regression fences for the hop's reach: a bound method is not hopped and its reason still reads "resolves to". They pass unchanged on the commit below. The two wraps-aware pins compute the expected name with the same `getattr(code, "co_qualname", code.co_name)` the load uses, so they hold on 3.10 as well. Every wording case fails with the commit below's `aot_compile.py`; the Test Plan lists the mutations and which cases each one fails. Test Plan: New tests, some parametrized. Every wording case fails with the commit below's aot_compile.py (`git show HEAD~1:torch/_dynamo/aot_compile.py` checked out under this commit's test file), the hint cases on the hint's wording and the reason cases on the reason string. `..._hint_sees_through_a_wrapped_rebound_forward` (compile, disable, disable_nonrecursive) pins the hint's wording and that defining the name in the wrapper's namespace restores nothing; `..._deserialize_refuses_a_targetless_dynamo_wrapper` pins the wraps-less external_utils reason whole (error_on_graph_break's inner: owns external_utils' dict, no __wrapped__), that dont_skip_tracing binds that same inner -- the shape torch/export/_unlift.py already assigns as an nn.Module's forward -- and that external_utils' namespace gains nothing; `..._deserialize_refuses_a_class_body_wrap_numpy_forward` (module-level NumpyForwardModule, its forward decorated in the class body) pins the wraps-aware naming of `wrap` and the same fence; `..._deserialize_refuses_a_class_compiled_call_forward` pins the wraps-aware naming of the compile_wrapper torch.compile(Cls) rebinds as Cls.__call__; `..._fallback_names_a_compiled_partial_forward` and `..._fallback_names_a_compiled_builtin_forward` pin the hopped-target reason whole, through _assert_forward_refused (full-string assertEqual on _forward_not_resolved_reason, the warning, the hint's "rebuilt because" splice, and eval_frame's namespace gaining nothing), the latter also that the un-hopped builtin keeps the as-given cannot-resolve one. The two wraps-aware pins compute the expected name with the same `getattr(code, "co_qualname", code.co_name)` the load uses, so they hold on 3.10 as well. Three cases are regression fences for the hop's reach rather than proofs of a change and pass unchanged on the commit below: `..._deserialize_refuses_a_lazy_module_forward` (both params; the bound _call_lazy_check on either setting) and `..._deserialize_refuses_a_bound_module_call_forward` pin that a bound method is not hopped and its reason still reads "resolves to". Mutations at this commit, each run over the cases the -k patterns below select: with the wraps-less return removed (the hop walks onto None, which the hopped-target branch then names as "an instance of NoneType") only the targetless-wrapper case fails, on the reason; with the hopped-target branch removed (every get_traced_fn failure returns the as-given cannot-resolve reason) exactly the two fallback cases fail, on the reason; with the wraps-aware naming removed exactly the class-body wrap_numpy and class-compiled __call__ cases fail, on the reason; with the hint's wording reverted exactly the three hint cases fail. The three fences pass under every mutation. ``` python test/dynamo/test_aot_compile.py -k hint_sees_through python test/dynamo/test_aot_compile.py -k deserialize_refuses_a_targetless python test/dynamo/test_aot_compile.py -k deserialize_refuses_a_class_body python test/dynamo/test_aot_compile.py -k deserialize_refuses_a_class_compiled python test/dynamo/test_aot_compile.py -k deserialize_refuses_a_lazy python test/dynamo/test_aot_compile.py -k deserialize_refuses_a_bound python test/dynamo/test_aot_compile.py -k fallback_names_a python test/dynamo/test_aot_compile.py lintrunner --take RUFF,PYFMT -- torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py ``` The full file reports `OK (skipped=6)`. > **FAQ: A wraps-less external_utils function used to be refused as "a Dynamo > wrapper without a resolvable target", then fell through to the namespace > rule, and now has a reason again. Why not the earlier wording?** > > Because nothing short of code identity tells wrap_dunder_call_ctx_manager's > inner from any other function owning external_utils' dict (normalize_as_list, > is_compiling), so a reason that calls the function "a Dynamo wrapper" is not > true of every function that reaches it, and the fall-through rendered "inner > resolves to inner" with advice the shape had already followed. The reason now > describes the function as what every function on this path is -- an > external_utils function with no __wrapped__ to see through -- and names the > decorators that return one; for a bare helper bound as forward, a > shape no API produces, that description holds and only the advice is moot. > **FAQ: Why name a wraps'd wrapper by `co_qualname`, which 3.10 lacks?** > > Because `__qualname__` is exactly what functools.wraps copied, so it cannot > name the wrapper; the code object's name can, and `co_qualname` (3.11+) also > names the decorator (`wrap_numpy.<locals>.wrap`). The fallback to `co_name` > on 3.10 renders `wrap, a functools.wraps'd wrapper over M.forward`, still > not a tautology, and is the convention this file already uses for the > dropped-attribute warning. The two tests that pin the wording compute the > expected name the same way. > **FAQ: Why keep "the wrapper <decorators> return skips functools.wraps" > rather than "the wrapper returned by <decorators> skips functools.wraps"?** > > Because the elided-that relative clause is this file's idiom for exactly this > list: the comment above the hop and the SUPPLIED hint both read "the wrappers > torch.compile, torch._dynamo.disable, run and optimize return". Rewording > only this site would state the same thing in two grammars three lines apart, > and it churns the golden string for no change in behaviour. This commit was authored with the assistance of an AI coding assistant. Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: #197319 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220, #197001, #197569, #197301, #196908
…ing (#197219) **Problem.** #196826 made `AOTCompiledModel` dispatch record a guard tree that raises and either serve over it (with a warning) or fold it into the no-match report, but three exits that leave `__call__` with a raise on record and nothing logged -- a bare `SystemExit` out of a later tree, a later result whose signature cannot take the call, a call the one signature cannot take -- were unpinned, as was the promise that a call binds once per result across both dispatch passes and the report. **Fix.** Three tests and one two-signature helper pin those exits, and two assertions are folded into the landed per-result binding test. No source change. **Summary.** Test-only, split for review budget from `[aot_compile] Tolerate a guard tree that raises during module dispatch` (#196826), four commits below, whose `torch/_dynamo/aot_compile.py` this commit does not touch. The three tests here were three of the twelve of `[aot_compile] Pin the raise-tolerant module dispatch's warning: its paths, text and dedup` (#197195), directly below; this commit adds them without touching the eight that stayed there, and folds a fourth's two assertions into the landed test whose setup it repeated. They pin the exits of `AOTCompiledModel.__call__` that record a raise nowhere -- a `SystemExit` out of a later tree, a later result whose signature cannot take the call, a call the one signature cannot take -- and that a call binds once per result across both dispatch passes and the report. One module-level helper, `compile_two_signatures`, builds the two-signature model the landed binding test and the cannot-bind test assemble, and the stub guard manager both raise tests need is the file's own module-level `RaisingTree(text)`, adopted at the two sites where each had an inline copy. The two negative pins each fail a mutant of their own and the two raise tests each error against #196826's parent, measured as the Test Plan records. ## Where they sit The two about binding join the landed `test_module_dispatch_*` tests on how a call binds, directly after `test_module_dispatch_binds_per_result_when_signatures_differ`, under that prefix, and, like that cluster, without `_hide_leaked_dynamo_globals`; `test_aot_compile_module_system_exit_out_of_a_later_tree_propagates` stays among #197195's dedup tests, because its last call is a dedup pin, and calls it as they all do. ## The helper and the stub ```python def compile_two_signatures(x, second_forward, *second_call): # One module, two results: [0] is ScaleModule's own forward compiled for `x`, # [1] is `second_forward` compiled for `second_call`. They bind alike iff # `second_forward`'s parameters (names, kinds, defaults) and closure cells # match forward's, so a caller wanting a non-shared binding varies one. mod = ScaleModule() doubled = aot_compile_forward(mod, ScaleModule.forward, x) second = aot_compile_forward(mod, second_forward, *second_call) return AOTCompiledModel(mod, [doubled, second]) ``` One module-level helper beside `compile_mode_defaults` serves them: `compile_two_signatures`, the two-signature model that landed test and the cannot-bind test assemble, built from the same `aot_compile_forward`. Its comment states when the two results bind alike -- iff `second_forward`'s parameters and closure cells match forward's, measured: a `(self, x)` second forward binds alike, one named `(self, y)` or given a default does not -- rather than promising they never do. The stub guard manager both tests need for the result whose tree raises is the file's own module-level `RaisingTree(text)`, adopted at the two sites where each had an inline copy; neither reads its `checks` counter, so this commit adds no second always-raising class beside it (FAQ below). ## The exits that record nothing Every path in #196826 that RETURNS a graph with a raise on record logs one, every path that builds a report chains one, and a call that ends in neither leaves as the exception that ended it; its FAQ says why nothing is logged on the way out. ### A bare `SystemExit` out of a later tree ```python class Exits: def check(self, f_locals): raise SystemExit("inside the tree") results[0]._artifacts.guard_manager = RaisingTree("zero is unhappy") results[1]._artifacts.guard_manager = Exits() with self.assertNoLogs(logger, level="WARNING"): with self.assertRaisesRegex(SystemExit, "inside the tree"): model(x) # leaves __call__ as the SystemExit, nothing logged results[1]._artifacts.guard_manager = real with self.assertLogs(logger, level="WARNING") as logs: self.assertEqual(model(x), x * 2) # serves [1] # exactly one line: "[0]'s guard check raised RuntimeError: zero is unhappy" ... "dispatch served [1]" ``` `test_aot_compile_module_system_exit_out_of_a_later_tree_propagates`: two results, [0]'s tree raising `RuntimeError` and [1]'s raising `SystemExit`; that call leaves `__call__` as the `SystemExit` with nothing logged, and the next call, with [1]'s real tree back, serves [1] and logs `[0]'s guard check raised RuntimeError: zero is unhappy`. That last call pins WHERE the dedup is judged (FAQ below). `SystemExit` and not `KeyboardInterrupt`, which the landed `test_aot_compile_module_interrupt_out_of_a_guard_tree_propagates` already drives out of this same handler behind a raiser: what no other test in the file has is a BARE `SystemExit`, where `accepts()`' `except Exception` decides on its own -- the `SystemExit` cases of the landed `test_aot_compile_module_wrapped_interrupt_out_of_a_guard_tree_propagates` arrive wrapped in the pybind boundary's `SystemError`, which the handler does catch and `_meant_an_exception` then re-raises -- and the `AOTCompiledModel` docstring promises both propagate. ### A later result that cannot bind ```python def needs_z(self, y, z): return y * z combined = compile_two_signatures(x, needs_z, x, x) results[0]._artifacts.guard_manager = RaisingTree("zero is unhappy") self.assertFalse(combined._binds_alike(tuple(results))) # premise: [1] binds inside its own accepts() with self.assertRaisesRegex(RuntimeError, "zero is unhappy"): results[0].guard_check(combined.model, x) # premise: [0] does raise with self.assertNoLogs("torch._dynamo.aot_compile", level="WARNING"): with self.assertRaisesRegex(TypeError, "missing a required argument: 'z'"): combined(x) ``` `test_module_dispatch_later_result_that_cannot_bind_raises_type_error`: two results that cannot share a binding, [0]'s tree raising and [1]'s signature needing an argument the call lacks; `TypeError: missing a required argument: 'z'` leaves `__call__` with nothing logged. It pins its premises before the call -- `_binds_alike` is False, so [1] binds inside its own `accepts()`, and [0]'s `guard_check` raises `RuntimeError: zero is unhappy` -- so a stub that stopped raising fails it with `RuntimeError not raised` (measured below) instead of leaving the case it names unexercised. Both keep `assertNoLogs` outermost (FAQ below). ### A call the one signature cannot take ```python model = torch.compile(ScaleModule(), fullgraph=True, backend="eager") model._aot_compile([ModelInput(args=(torch.randn(3, 3),), kwargs={}, contexts=[])]) with self.assertRaisesRegex(TypeError, "too many positional arguments"): model(x, x) with self.assertRaisesRegex(TypeError, "missing a required argument: 'x'"): model() ``` `test_module_dispatch_wrong_arity_raises_type_error` is the one-result form of the same exit, and the source before #196826 already had it right: a call the signature cannot bind is the `TypeError` a plain module call raises, with no report folded around it -- `prepare_f_locals` stays outside `accepts()`' `try`. The type is the whole pin: the report is raised as a `RuntimeError`, so `assertRaisesRegex(TypeError, ...)` excludes it and nothing else about the exception needs reading. ## One bind per result, across both passes and the report ```python # folded into test_module_dispatch_binds_per_result_when_signatures_differ binds = [] def counted(result, *args, **kwargs): binds.append(result) return bind(result, *args, **kwargs) with patch.object(AOTCompiledFunction, "prepare_f_locals", counted): with checks[0] as check0, checks[1] as check1, no_match: combined(x.half()) # no result matches: the no-match report self.assertEqual((check0.call_count, check1.call_count), (2, 2)) # both passes checked both results self.assertEqual(len(binds), len(results)) # bound once per result for i, (bind_of, result) in enumerate(zip(binds, results)): self.assertIs(bind_of, result, f"bind {i} is not of result [{i}]") # in index order, the same objects ``` One more thing the source before #196826 already did, kept, pinned in the landed `test_module_dispatch_binds_per_result_when_signatures_differ`, which already builds the two-signature model and shows each result binding on its own: a third call, `x.half()`, that no result matches ends in the no-match report (`assertRaisesRegex(RuntimeError, "No AOT compiled graph matched")`) having bound once per result -- in index order, the same objects, asserted per position so a wrong-order failure names the position -- while both passes checked each result (`check` wrapped and counted: two per result); that source's per-result list already satisfied it, and #196826's `bound` dict keeps it. The report's entry count is not asserted here: the report reads `bound[i]`, so it adds nothing to the bind count, and seven other tests count those lines. ## What each test pins, by mutation | mutation of #196826's `aot_compile.py` | fails | | --- | --- | | bind moved inside `accepts()`' `try` | `test_module_dispatch_wrong_arity_raises_type_error`, `test_module_dispatch_later_result_that_cannot_bind_raises_type_error`, nothing else: the `TypeError` is read as a raise and each call ends in a no-match report | | rebind on every pass (`f_locals = None` for `bound.get(i)`) | `test_module_dispatch_binds_per_result_when_signatures_differ` on `len(binds)`: `Expected 2 but got 4`, nothing else | | second pass deleted | the same test on its `check` counts, `(2, 2)` read as `(2, 1)`, plus 23 other re-check tests | | handler AND `_meant_an_exception` widened to admit `SystemExit` | `test_aot_compile_module_system_exit_out_of_a_later_tree_propagates` (a no-match report where the exit was asked for); widening the handler alone changes nothing | | dedup pair decided in `accepts()`' handler, not `warn_swallowed` | the same test on its last call's `assertLogs`, `test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning`, and six others | | dispatch handlers re-raise | the system-exit and cannot-bind tests on [0]'s `RuntimeError` escaping | | warning's raiser read off the served index | the system-exit test's last call, whose log then names `[1]` (#197195's mutant) | | [0]'s `RaisingTree` replaced by a stub returning False | the cannot-bind test on its premise, `RuntimeError not raised` | The Test Plan gives each measurement in full, including the parent run: the system-exit and cannot-bind tests both error on [0]'s `RuntimeError: zero is unhappy` escaping the call before the exit they pin is reached, and the two that pin what that source already did pass, as they should. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_aot_compile_module_system_exit_out_of_a_later_tree_propagates python test/dynamo/test_aot_compile.py -k test_module_dispatch_later_result_that_cannot_bind_raises_type_error python test/dynamo/test_aot_compile.py -k test_module_dispatch_wrong_arity_raises_type_error python test/dynamo/test_aot_compile.py -k test_module_dispatch_binds_per_result_when_signatures_differ python test/dynamo/test_aot_compile.py ``` The whole file is green, `OK (skipped=6)`. `lintrunner --take RUFF,PYFMT test/dynamo/test_aot_compile.py` is clean. The four were also run against the `torch/_dynamo/aot_compile.py` of #196826's parent under this test file: the system-exit and cannot-bind tests both error on [0]'s `RuntimeError: zero is unhappy` escaping the call before the exit they pin is reached, and the two that pin what that source already did pass, as they should. Each of the two negative pins fails a mutant of its own, each run against the whole file at this commit. Moving the bind inside `accepts()`' `try` fails `test_module_dispatch_wrong_arity_raises_type_error` and `test_module_dispatch_later_result_that_cannot_bind_raises_type_error`, and nothing else: the `TypeError` is read as a raise and each call ends in a no-match report (`No AOT compiled graph matched this call. Tried 1 compiled input(s)` with `[0] <guard check raised TypeError: too many positional arguments>`, and `Tried 2`) where the `TypeError` was expected. Rebinding on every pass (`f_locals = None` in place of `bound.get(i)`) fails `test_module_dispatch_binds_per_result_when_signatures_differ`, and nothing else, on `len(binds)`: `Expected 2 but got 4`. Deleting the second pass fails it on its `check` counts, `(2, 2)` read as `(2, 1)` -- its bind count alone reads the same with one pass as with two -- along with 23 other tests of the file that pin the re-check. Each fix in #196826 that the other two cover was then reverted on its own against the same file. A bare `SystemExit` reaches the record only if BOTH `accepts()`' handler and `_meant_an_exception` are widened to admit it: widening the handler alone, to `BaseException` or to `(Exception, SystemExit)`, changes nothing, because the gate re-raises whatever a tree meant that is not an `Exception` (measured: this test and the file's five other interrupt tests stay green). Widened in both places, `test_aot_compile_module_system_exit_out_of_a_later_tree_propagates` gets `RuntimeError: No AOT compiled graph matched this call. Tried 2 compiled input(s)` where it asked for the exit, with only the three `SystemExit` cases of the wrapped-interrupt test above failing beside it. Deciding the dedup's `(index, exception type)` pair in `accepts()`' handler, as the raise is recorded, rather than in `warn_swallowed` fails the same test on its last call's `assertLogs` (`no logs of level WARNING or higher triggered`), #196826's `test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning` the same way, and six others that read the record or the one-shot (FAQ below). Making the dispatch handlers re-raise fails the system-exit and cannot-bind tests on [0]'s `RuntimeError` escaping, the two pins of the older behaviour passing. Reading the warning's raiser off the served index fails the system-exit test's last call, whose log then names `[1]`; that mutant is #197195's, whose message lists the tests it fails there. Replacing [0]'s `RaisingTree` in `test_module_dispatch_later_result_that_cannot_bind_raises_type_error` with a stub that returns False fails it on its premise assertion, `RuntimeError not raised`. > **FAQ: > `test_aot_compile_module_system_exit_out_of_a_later_tree_propagates` > and `test_module_dispatch_later_result_that_cannot_bind_raises_type_error` > nest `assertNoLogs` outside `assertRaisesRegex`, so a spurious warning on a > call that also fails the raise assertion is reported as the raise failure. > Swap them so `assertRaisesRegex` is outermost?** > > Declined, because the swap makes the log pin vacuous, measured here. > `unittest`'s `_AssertLogsContext.__exit__` returns False without reading its > records whenever an exception is passing through it ("let unexpected > exceptions pass through"), and on these two tests' expected path the call > ALWAYS raises, so an `assertNoLogs` nested inside the raise assertion exits > by exception every time and checks nothing. With `log.warning("spurious > warning on record")` added where both tests' aborted call records [0]'s > raise -- the inline handler, not `accepts()`, which neither aborted call > reaches: as written, both tests fail with `AssertionError: Unexpected logs > found: ['WARNING:torch._dynamo.aot_compile:spurious warning on record']`; > with `assertRaisesRegex` outermost, the cannot-bind test PASSES and the > system-exit test fails only on its last call, on `len(logs.output)` reading > 2 where 1 is expected -- the swapped blocks let the warning through on the > aborted call. The masking the finding describes happens only on a call that > has already failed the raise assertion, where the test fails either way. > The order as written is the one on which the silence is checked at all, and > a one-line comment at each site says so; that line is the one note about > the test framework the two tests keep, because it is what stops the swap. > **FAQ: the system-exit test's last call -- [1]'s real tree restored, the > next call serving [1] and warning about [0] -- asserts the two substrings > `test_aot_compile_module_warns_again_about_a_replaced_index` (#197195) > already asserts, and a regression that populated `_warned` while logging > already fails the aborted call's `assertNoLogs`. Is the exit the test is > named for not the test?** > > The exit is, and the last call pins WHERE the dedup is judged, which the > aborted call cannot. Measured by moving it: deciding the `(index, exception > type)` pair in `accepts()`' handler as the raise is recorded, and leaving > `warn_swallowed` to log the pairs so collected, passes the aborted call > (nothing is logged; the exit still escapes), #197195's pop and every-input > tests and #196826's single-result and once-per-model tests alike, and fails > this last call, with `no logs of level WARNING or higher triggered`, because > the aborted call had already consumed `(0, "RuntimeError")`; #196826's > `test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning`, > whose first call ends in a no-match report rather than an exit and whose > second call is silent for the same reason; and six more that read the > record the mutant drops or the one-shot it spends. That is a restructuring > a later reader could plausibly make -- the handler is where the pair is > first known -- and it would make every aborted call a silent one for the > raise on its record. The test's comment names both tests the move fails. > **FAQ: the file's inline raiser stubs -- four `class Raises`, two > `class RaisingGuardManager`, and the `Interrupts` of > `test_aot_compile_module_interrupt_out_of_a_guard_tree_propagates` -- all > duplicate the module-level `RaisingTree` these two tests adopt. Why not > convert them too?** > > `git blame` puts every one of them in a test of #197188, #197220, #197390 > or #197391 below, and #197188, #197220 and #197390 are already approved, > so the conversion cannot be folded into the commits that own the stubs > either; doing it here would put edits to four other PRs' tests in a commit > whose diff is otherwise three tests and one helper, and would shift the > hunks #197050 and #197257 apply above. `RaisingTree` is module level and > already adopted at 21 sites, so those owners can adopt it in one line each. Authored with the assistance of Claude Code. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #197219 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220, #197001, #197569, #197301, #196908, #197319
…a missing-global failure (#197580) **Problem.** `_no_match_report` only resolves `forward` (running `get_traced_fn` over user code that can raise) when a SUPPLIED entry failed on a missing global, but no test pinned that an ordinary guard mismatch skips the resolve; hoisting the gate out of the missing-global branch left the whole file green. **Fix.** One test builds a SUPPLIED entry whose guard fails on an ordinary `KeyError` mismatch and asserts the report has no hint line and `_resolve_guard_scope` is never called. No source change. **Summary.** One test, `test_no_match_report_resolves_no_forward_for_an_ordinary_mismatch`, pins the branch `AOTCompiledModel._no_match_report`'s resolve gate sits in. The gate (`result._guard_scope is _GuardScope.SUPPLIED and not tried_forward`) is nested under `if any(map(_names_a_missing_global, parts)):`, so a SUPPLIED entry whose guard failed on an ordinary mismatch never resolves `forward`. That matters because resolving runs `get_traced_fn` over user code that can raise, the same cost the other gate tests in #197301 exist to avoid; those tests all reach a SUPPLIED missing-global entry first, so hoisting the gate out of the missing-global branch left every one of them green. The new test loads the two-input artifact against a caller dict that binds `GLOBAL_POOLING_CONFIG` to a dict without the key its guard reads, so the report fails on a `KeyError` that `_names_a_missing_global` rejects whole, there is no hint sentence, and the resolve is never called. It sits as its own commit rather than in #197301 because the commit between them (#197319) is approved and must not move; it belongs with the gate tests and can fold into #197301 if that stack order changes. ## The gate under test ```python # AOTCompiledModel._no_match_report if any(map(_names_a_missing_global, parts)): # the missing-global branch if result._guard_scope is _GuardScope.SUPPLIED and not tried_forward: # the resolve gate ... # resolve forward: get_traced_fn over user code ``` A SUPPLIED entry that fails on an ordinary mismatch never reaches the inner `if`, so `forward` is never resolved for it. Hoisting the gate out of the outer branch fails this test alone (`Called 1 times`). ## The test ```python def test_no_match_report_resolves_no_forward_for_an_ordinary_mismatch(self): data = self._two_input_global_guard_artifact(x) keyless = {"__builtins__": builtins, "GLOBAL_POOLING_CONFIG": {}} # bound, but without the key the guard reads loaded = AOTCompiledModel.deserialize(GlobalConfigModule(), data, guard_globals=keyless) results = loaded.compiled_results[:1] # keep one result self.assertIs(results[0]._guard_scope, _GuardScope.SUPPLIED) resolve = patch("torch._dynamo.aot_compile._resolve_guard_scope", wraps=_resolve_guard_scope) with resolve as resolves, self.assertRaises(RuntimeError) as ctx: AOTCompiledModel(loaded.model, results)(x) resolves.assert_not_called() lines = str(ctx.exception).splitlines() self.assertEqual(lines[1], " [0] KeyError on G['GLOBAL_POOLING_CONFIG']['pooling']") self.assertEqual([line for line in lines if line.startswith("For [")], []) ``` The report fails on ` [0] KeyError on G['GLOBAL_POOLING_CONFIG']['pooling']`, which `_names_a_missing_global` rejects whole (the global is bound; only its key is missing), so there is no hint sentence and the resolve is never called. The test asserts that entry line, the absence of any `For [` line, and `assert_not_called()`. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_no_match_report_resolves_no_forward_for_an_ordinary_mismatch python test/dynamo/test_aot_compile.py ``` The whole file is green, `OK (skipped=6)`. With the gate hoisted out of the missing-global branch the new test is the file's only failure. This PR was authored with an AI assistant (Claude). Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: #197580 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220, #197001, #197569, #197301, #196908, #197319, #197219
…raise (#197050) **Problem.** After #197220, the no-match report advises "Add a ModelInput covering this call" whenever some guard tree rejected the call, without saying how that rejection came about. When the only rejection came from a tree that had raised on the pass before, the rejection may be about the stale relational state a C++ throw left behind rather than about this call, and the report said nothing about it. **Fix.** Dispatch records `trusted`, the indices that rejected with no raise of their own on record at that moment. When every rejection the advice rests on followed a raise from its own tree, the advice paragraph gains one more sentence: fix the raise first, since a C++ throw can leave that tree's relational guard state stale. **Summary.** The commit below, #197220, advises a `ModelInput` whenever some checked tree rejected the call and says nothing about how that rejection came about, so when the only rejection dispatch got out of a tree FOLLOWED a raise from the same tree, the advice stands on the answer the last-resort veto below refuses to act on: a C++ throw skips `_reset_relational_guard_state()`, so that rejection can be about the stale relational state rather than about this call. Dispatch now records one more set, `trusted`, the indices that answered with no raise of their own on record at that moment (`if i not in raised`), written on the rejection-only path of `accepts()` so an accept pays nothing for it, and the report computes `trusted_rejection` over the enabled ones the way it already computes `coverable` over `answered`. When `coverable and not trusted_rejection`, the `ModelInput` paragraph goes on to say so -- fix the raise first, since every rejection this advice rests on followed a raise from its own tree, and a C++ throw can leave that tree's relational guard state stale -- with the stale-state clause hedged (`can leave`) and held in a constant, `_STALE_AFTER_THROW`, because it is emitted for both flavours of raise and is a fact about only the throw that unwinds past the reset. The caveat keys on what dispatch recorded rather than on the lines the report printed, does not yet say WHICH tree's raise it means (#197257, the commit above, makes it name and quote them), and one trusted rejection is enough to leave the advice unqualified. Against the commit below nothing served or raised changes -- same `RuntimeError`, same `__cause__`, same entry lines, same gates -- only the `ModelInput` paragraph differs, and the four new tests plus the existing ones that now assert the caveat fail on the commit below's `aot_compile.py`. ## Where this sits in the stack Split from `[no-ci] [aot_compile] Advise a ModelInput only when some checked tree answered the no-match report's call` (#197220, the commit below) for review budget: that commit decides whether the report's closing advice applies at all, and this one says what the advice rests on when it does. Split again, for the same budget, from `[aot_compile] Name and quote the raises the no-match report's caveat means` (#197257, the commit above): this commit adds the caveat and the bookkeeping it keys on, and that one makes the caveat name the trees it means and quote their raises. ## The report the commit below prints Measured on `ScaleModule` with one input and a stub tree that raises on the scan and rejects on the second pass, the report at the commit below reads: ``` [0] stub guard rejected [0]'s guard check raised while checking this call; fix or drop that artifact. Add a ModelInput covering this call, or check whether guard_filter_fn kept a guard this call cannot satisfy -- ... ``` The `ModelInput` advice stands on a rejection that followed the same tree's raise, which the last-resort veto below refuses to act on, and nothing on the report says so. ## Recording `trusted` ```python # AOTCompiledModel.__call__ answered: set[int] = set() trusted: set[int] = set() # new: answered with no raise of their own on record # inline first result else: answered.add(0) trusted.add(0) # new def accepts(i, result): ... if answer: return True # an accept serves and builds no report # Recorded on a rejection only. Measured 0.06us for the four against a 1.3us check(). unanswered.discard(i) answered.add(i) if i not in raised: # new trusted.add(i) return False ``` Dispatch now records one more thing about a rejection, and records it where the order is known rather than reconstructing it afterwards. `trusted` holds the indices that answered with no raise of their own on record at that moment (`if i not in raised`), so it does not depend on dispatch running exactly two passes: under a third pass an answer-raise-answer tree would still be in it and a raise-answer-raise tree still out of it, where a predicate over `answered`, `raised` and `unanswered` can only tell those two apart by counting passes. Recording `trusted` without the `raised` check -- every answer trusted -- fails `test_no_match_message_qualifies_a_rejection_that_followed_a_raise`, `test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw`, `test_no_match_message_qualifies_the_advice_when_the_re_check_raises`, `test_no_match_message_quotes_a_tree_that_raised_then_answered` and `test_no_match_message_advises_an_input_when_one_of_two_raisers_answered`, all on the caveat going missing. The two lines that record it sit on the rejection-only path the commit below made of the answer exit of `accepts()`: an accept returns before them, since dispatch then serves and builds no report, so the result that accepts pays nothing for them, and a rejection pays the four set operations now on that path -- `unanswered.discard(i)`, `answered.add(i)`, `i not in raised`, `trusted.add(i)`: | operation | cost | | --- | --- | | the four set operations on the rejection path | 0.06us (timeit) | | one `check()` of a one-input `ScaleModule` tree through `GuardManagerWrapper`, the call dispatch makes | 1.3us | The comment at that block gives the same two numbers. ## The caveat ```python # _no_match_report coverable = any(results[i]._guard_check_enabled for i in answered) trusted_rejection = any(results[i]._guard_check_enabled for i in trusted) # new ... if coverable or not results: advice = "Add a ModelInput covering this call, or check whether guard_filter_fn kept ..." if coverable and not trusted_rejection: advice += (" Fix the raise first: every rejection this advice rests on " f"followed a raise from its own tree, and {_STALE_AFTER_THROW}.") lines.append(advice) ``` The report says what it knows rather than choosing. The commit below advises a `ModelInput` whenever at least one checked tree reached an answer (`coverable`); when none of those answers came before its own tree raised (`not trusted_rejection`) the same paragraph now goes on to say so: fix the raise first, since every rejection the advice rests on followed a raise from its own tree, and a C++ throw out of a tree can leave that tree's relational guard state stale. ``` Add a ModelInput covering this call, or check whether guard_filter_fn kept a guard this call cannot satisfy -- both belong to the process that compiles the artifacts, which need not be the one that loaded them. Fix the raise first: every rejection this advice rests on followed a raise from its own tree, and a C++ throw out of a tree can leave that tree's relational guard state stale, so its next check can reject a call it fits or accept one it does not. ``` The caveat does not say WHICH tree's raise it means: on the one-input reports here the raiser line above it names that tree, and the commit above makes the caveat name and quote the raises itself, since the two diverge as soon as another enabled tree raised first -- measured on the report of `test_no_match_message_advises_an_input_when_one_of_two_raisers_answered`, from a commit below, where [0] raises on both passes and [1] raises on the scan and rejects after: the raiser line and the `__cause__` are [0]'s, the advice rests on [1]'s rejection alone, and [1]'s raise appears nowhere on the report (its entry line is its `check_verbose` rejection). That test now also pins that the caveat is emitted there, on a clause the commit above keeps. The two texts that promised a caveat naming those trees -- the last sentence of the `AOTCompiledModel` docstring and the comment on the report's `unanswered` branch -- now say what this caveat does say and leave the naming to that commit. ## Why the stale-state clause is hedged ```python _STALE_AFTER_THROW = ( "a C++ throw out of a tree can leave that tree's relational guard state " "stale, so its next check can reject a call it fits or accept one it does not" ) ``` The clause is hedged (`can leave`, not `leaves`) because it is emitted for both flavours of raise and is a fact about only one of them: `_reset_relational_guard_state()` runs on every return path of `RootGuardManager::check_nopybind_template` and `check_verbose_nopybind` (`torch/csrc/dynamo/guards.cpp`), so only a throw that unwinds past them skips it, and a tree that returns to pybind with an error merely set -- the `SystemError` whose chained cause `_unwrapped_raise` quotes, which is how `DICT_CONTAINS` raises, its `result == -1` branch being dead -- ran the reset on its way out. | flavour of raise | how it reaches Python | ran the reset? | | --- | --- | --- | | C++ throw (`TORCH_CHECK`) unwinding past the root's exits | pybind translates it into a plain `RuntimeError`, no `__cause__` | no: state can be stale | | error left set, normal return | `SystemError` at the pybind boundary, cause quoted by `_unwrapped_raise`; `(through the guard tree's pybind boundary)` on the entry line | yes | The caveat is still emitted after the second flavour, and the veto below still withholds on it, because dispatch does not tell the two apart (`test_no_match_message_quotes_a_tree_that_raised_then_answered`, from a commit below, says so in as many words), and a report that called clean a rejection dispatch refused to act on would contradict the veto it explains; so the clause states what a raise can have cost, and the entry line's `(through the guard tree's pybind boundary)` is where a reader tells which flavour this one was. The clause is a constant, `_STALE_AFTER_THROW`, so that it sits beside the comment explaining that hedge rather than inside the f-string that appends it, and so that the commit above can rewrite the caveat around it without touching it. Nothing else shares it: the class docstring states the same fact of an actual throw, unhedged, in its own prose, and the warning `_warn_swallowed` logs states the defect in its own words and is untouched here -- a caller on the report path never sees that warning anyway, since it runs only when dispatch served something and a report is built only when nothing was, so the report is the only place such a caller learns this. The constant is phrased `a C++ throw out of a tree can leave that tree's` rather than the docstring's `out of it leaves its relational guard state stale` because the caveat's own sentence names no tree, so `it` would have no antecedent in it. ## What the caveat keys on The caveat keys on what dispatch recorded, not on the lines the report printed: the re-check is a third evaluation, and where it raises instead of rejecting -- `test_no_match_message_qualifies_the_advice_when_the_re_check_raises` -- or accepts -- the shape of #196826's `test_no_match_report_reads_the_dispatch_record_after_a_raise` -- the report quotes no rejection, but the `ModelInput` line still stands on the one dispatch got, so the caveat is emitted whatever the entry line reads. ```python # test_no_match_message_qualifies_the_advice_when_the_re_check_raises class RaisesThenRejectsThenRaises(RaisesOnceThenRejects): def check_verbose(self, f_locals): raise RuntimeError("the re-check is unhappy") # report: " [0] <guard check raised RuntimeError: the re-check is unhappy>" (the only entry line) # "[0]'s guard check raised while checking this call; ..." # "Add a ModelInput ... every rejection this advice rests on ..." (still qualified) # __cause__: "the first pass is unhappy" ``` It is emitted with an opted-out entry on the report too, and after the error-set flavour of raise: `test_no_match_message_quotes_a_tree_that_raised_then_answered` puts `RaisesThenHits(raises=1)` on a checked [0] beside an opted-out [1], and its withheld line says only why the opt-out was withheld. One trusted rejection is enough to leave the advice unqualified, even beside a rejection that followed a raise: `trusted_rejection` is an `any`, pinned by `test_no_match_message_trusts_one_rejection_taken_before_a_raise`, where [0] rejected then raised and [1] raised then rejected: ```python results[0]._artifacts.guard_manager = RejectsOnceThenRaises("the second pass is unhappy") results[1]._artifacts.guard_manager = RaisesOnceThenRejects("the scan is unhappy") # " [0] <guard check raised RuntimeError: the second pass is unhappy>" # " [1] stub guard rejected" # "[1]'s guard check raised while checking this call ..." (raised is in recording order; [1]'s scan raise came first) # __cause__: "the scan is unhappy" # "Add a ModelInput ..." with NO caveat: [0]'s rejection came before its raise ``` Requiring every enabled entry in `answered` to be in `trusted` instead fails only that test. Dropping `trusted_rejection` from the caveat gate fails it, `test_no_match_message_survives_a_raising_guard` and `test_no_match_message_advises_an_input_after_an_answer_then_a_raise` on the caveat appearing. The gate's other term is `coverable`, which is what keeps the caveat off a report about an artifact with no inputs at all, where the advice is printed by the `not results` disjunct beside it and no rejection exists to have followed anything: `test_no_match_report_claims_no_raise_for_an_artifact_with_no_inputs` now also asserts the caveat's absence, and dropping `coverable` from the inner gate fails that test alone. | mutation | fails | | --- | --- | | `trusted` recorded without the `raised` check | the five caveat-present tests above, on the caveat going missing | | `trusted_rejection` made an `all` over the enabled entries of `answered` | `test_no_match_message_trusts_one_rejection_taken_before_a_raise` only | | `trusted_rejection` dropped from the caveat gate | `..._trusts_one_rejection_taken_before_a_raise`, `test_no_match_message_survives_a_raising_guard`, `test_no_match_message_advises_an_input_after_an_answer_then_a_raise`, on the caveat appearing | | `coverable` dropped from the inner gate | `test_no_match_report_claims_no_raise_for_an_artifact_with_no_inputs` only | ## The one real throw: `test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw` The one flavour the clause is a fact about has a test on a real tree. ```python class PairModule(torch.nn.Module): def forward(self, x, y): # two tensors, so Dynamo installs NO_TENSOR_ALIASING over both return x + y model._aot_compile([ModelInput(args=(torch.randn(3, 3), torch.randn(3, 3)), ...)]) nested = torch.nested.nested_tensor([torch.randn(2, 3), torch.randn(3, 3)], layout=torch.strided) model(x, nested) # scan: TENSOR_MATCH on y fires TORCH_CHECK "NestedTensorImpl doesn't support strides"; # the throw skips the reset, so NO_TENSOR_ALIASING still holds L['x'] # second pass: visits x's manager first, finds the duplicate, rejects there -- before reaching y's leaf; # that clean return resets the state # re-check: quotes y's dispatch-key mismatch, not a raise # report: one entry line naming L['y'], no raise line, the raiser line, the advice ending in the caveat # __cause__: the strides error, with nothing chained behind it (pybind translated a throw) # probed AFTER the dispatch under test, on the same tree: tree.check(f_locals) # raises "doesn't support strides" tree.check_verbose(f_locals).verbose_code_parts # ["Duplicate tensor found where not expected!"] ``` `PairModule` (`forward(self, x, y)`, so Dynamo installs `NO_TENSOR_ALIASING` over both) is compiled on two dense tensors and called with a strided nested tensor as `y`. `TENSOR_MATCH` on it fires a `TORCH_CHECK` (`NestedTensorImpl doesn't support strides`), pybind translates the throw into a plain `RuntimeError` with no `__cause__`, and the throw skips the reset, so the scan leaves `x` recorded in the aliasing guard; the second pass visits x's manager first, finds the duplicate and rejects there, before reaching the leaf that threw; that clean return resets the state; and the report's re-check quotes y's dispatch-key mismatch rather than a raise. Measured on that tree directly, which the test also pins: `check()` throws, and the `check_verbose()` right after it answers `Duplicate tensor found where not expected!`. The report carries one entry line naming `L['y']` and no raise line, the raiser line, and the `ModelInput` advice ending in the caveat; the `__cause__` is the strides error with nothing chained behind it. The two probes of the tree run AFTER the dispatch under test, so that dispatch ran on a tree the test had not touched; the residue they pin is the same on the tree dispatch and the report have been through, since a `check()` after a throw still fails on x as a duplicate. The test's comment names the two orderings the shape rests on besides the skipped reset: root accessors stay in `Guard.sort_key` order, `L['x']` before `L['y']`, because the throw leaves `check_accessors_nopybind` before its fail-count bump and sort; and `TensorCheck::check_verbose` compares dispatch key sets before it reads strides, which is why the re-check names `L['y']` instead of throwing a second time. Every other test that asserts the caveat drives it with a stub whose `check()` raises from Python and touches no relational state, and the only other real throw in the suite (`test_aot_compile_module_restores_torch_function_after_a_throw`, one tensor) raises on every pass, reaches no answer, and so gets no `ModelInput` advice to qualify. ## What does not change Against the commit below, nothing served or raised changes: the same calls raise the same `RuntimeError` with the same `__cause__`, and the dispatch passes, the veto, the warning `_warn_swallowed` logs, every entry line and the gates on the report's closing lines are untouched. Only the `ModelInput` paragraph differs: it carries the caveat sentence when every rejection it stands on came after a raise from its own tree. ## Stubs and the golden ```python class RaisesOnceThenRejects: # raises on the first check(), rejects after; def check_verbose(self, f_locals): # check_verbose quotes "stub guard rejected" return types.SimpleNamespace(result=False, verbose_code_parts=["stub guard rejected"]) class RejectsOnceThenRaises(NeverReChecked): # the mirror: rejects first, raises after; ... # on NeverReChecked since its last evaluation raised CAVEAT_AFTER_A_RAISE = "which need not be the one that loaded them. Fix the raise first: every rejection this advice rests on followed a raise from its own tree, and a C++ throw out of a tree can leave that tree's relational guard state stale, so its next check can reject a call it fits or accept one it does not." ``` The stubs that drive the caveat are two module-scope classes next to `NeverReChecked`, each taking its raise message: `RaisesOnceThenRejects` (raises on the first `check()`, rejects after, quotes a rejection in `check_verbose`) and `RejectsOnceThenRaises` (the mirror, on `NeverReChecked` since its last evaluation raised). Each replaces a local copy from the commits below -- `RaisesThenRejects` in `test_no_match_message_advises_an_input_when_one_of_two_raisers_answered`, whose entry line now reads the shared stub's `stub guard rejected`, and `RejectsThenRaises` in `test_no_match_message_advises_an_input_after_an_answer_then_a_raise` -- and the one local stub of the first shape, `RaisesThenRejectsThenRaises` in the new re-check test, subclasses `RaisesOnceThenRejects` and overrides only `check_verbose`, which is the one thing that differs. The one same-named local stub left, in `test_no_match_report_reads_the_dispatch_record_after_a_raise`, is not collapsible: its `check_verbose` accepts, and the `RaisesTwice` beside it inherits that. Every `checks` count the tests assert is unchanged. The caveat's text is one golden, `CAVEAT_AFTER_A_RAISE`, which starts in the advice's own last clause and runs through the caveat, so the two tests that assert it with `endswith` pin the junction of the two rather than the caveat alone. ## Tests Four tests are new, and tests of the commits below gain an assertion about the caveat for their case. The ones that assert the caveat is present fail on the commit below's `aot_compile.py`: - `test_no_match_message_qualifies_the_advice_when_the_re_check_raises` - `test_no_match_message_qualifies_a_rejection_that_followed_a_raise` - `test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw` - `test_no_match_message_quotes_a_tree_that_raised_then_answered` - `test_no_match_message_advises_an_input_when_one_of_two_raisers_answered` The rest pass there because the parent's `ModelInput` line has no caveat to find; each is a pin here by a mutation named above. ## Order to review `_STALE_AFTER_THROW` and the comment on why it is hedged; `trusted` and its update in `accepts()`; the report's `trusted_rejection`; the caveat appended to the `ModelInput` advice at the end of `_no_match_report`; the sentence of the `AOTCompiledModel` docstring that describes the report's closing lines, and the two texts -- its last sentence and the comment on the report's `unanswered` branch -- that said what this caveat would carry; then, in the test file, the two stubs next to `NeverReChecked` and the one that subclasses one of them, `PairModule`, `CAVEAT_AFTER_A_RAISE`, `test_no_match_message_qualifies_a_rejection_that_followed_a_raise`, `test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw`, `test_no_match_message_trusts_one_rejection_taken_before_a_raise` and `test_no_match_message_qualifies_the_advice_when_the_re_check_raises`. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_no_match_message_qualifies_the_advice_when_the_re_check_raises python test/dynamo/test_aot_compile.py -k test_no_match_message_qualifies_a_rejection_that_followed_a_raise python test/dynamo/test_aot_compile.py -k test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw python test/dynamo/test_aot_compile.py -k test_no_match_message_trusts_one_rejection_taken_before_a_raise TORCH_SHOW_CPP_STACKTRACES=1 python test/dynamo/test_aot_compile.py -k test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw python test/dynamo/test_aot_compile.py -k test_no_match_message_survives_a_raising_guard python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_a_tree_that_raised_then_answered python test/dynamo/test_aot_compile.py -k test_no_match_message_advises_an_input_after_an_answer_then_a_raise python test/dynamo/test_aot_compile.py -k test_no_match_message_advises_an_input_when_one_of_two_raisers_answered python test/dynamo/test_aot_compile.py -k test_no_match_report_claims_no_raise_for_an_artifact_with_no_inputs python test/dynamo/test_aot_compile.py lintrunner --take RUFF,PYFMT torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py ``` The caveat tests were also run against the commit below's `torch/_dynamo/aot_compile.py`, and each gate was then mutated on its own -- `trusted_rejection` dropped from the caveat gate, `coverable` dropped from it, `trusted_rejection` made an `all` over the enabled entries of `answered`, `trusted_rejection` made a literal `all` over `trusted`, `trusted` recorded without the `raised` check -- and those tests rerun; only the tests named above failed under each. Authored with the assistance of Claude Code. ## FAQ > **FAQ: `_STALE_AFTER_THROW` asserts the stale relational state as a fact > about the raise on record, but only a genuine C++ unwind skips the reset; > for the `SystemError`-with-a-chained-cause flavour the reset ran. Hedge the > verb, or key the clause on the `boundary` signal `_raised_line` already > computes (`reason is not e`).** > > Hedged, to `can leave`; not keyed. The signal is real -- a `SystemError` > whose `__cause__` is set is a tree that returned to pybind with an error > set, and every return path of `check_nopybind_template` and > `check_verbose_nopybind` resets -- but the caveat qualifies a rejection the > last-resort veto refused to act on, and that veto withholds on either > flavour without telling them apart > (`test_no_match_message_quotes_a_tree_that_raised_then_answered`, from a > commit below, states that as its premise). A clause keyed on the flavour > would have the report call a rejection clean where dispatch just refused to > serve an opt-out on it, and dropping the clause for that flavour would leave > `fix the raise first` with no stated reason. So the clause says what a raise > of either flavour can have cost -- true of the throw, vacuous of the > error-set return -- and the entry line's `(through the guard tree's pybind > boundary)` tells a reader which this one was. The one case the clause is a > fact about has a real-tree test, > `test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw`, > which pins both the residue (`Duplicate tensor found where not expected!` > from the evaluation right after the throw) and the caveat on the report > that residue's rejection produces. > **FAQ: The caveat restates what `warn_swallowed` already says, in other > words, on another channel, and with no action the raiser line does not > already give; demote it to a `log.warning` beside that text, or fold it into > the raiser line rather than adding a fourth trailing paragraph.** > > Folded, into the `ModelInput` paragraph rather than the raiser line. A > caller on the report path never sees `warn_swallowed`: it runs only when > dispatch served something, and a report is built only when nothing was, so a > warning beside the report would be the second channel, not the report. The > sentence qualifies the `ModelInput` advice, so it lives in that paragraph; > the raiser line is the wrong home because an opted-out entry on the report > replaces it with the withheld line > (`test_no_match_message_quotes_a_tree_that_raised_then_answered`), which > would have lost the caveat exactly there. It carries an action of its own -- > fix the raise before adding an input -- and its stale-state clause is one > named constant, `_STALE_AFTER_THROW`, beside the comment on why that clause > is hedged. > **FAQ: A mutation of the `any` in the caveat gate to `all` would pass the > whole suite.** > > Measured, both readings. The literal > `all(results[i]._guard_check_enabled for i in trusted)` fails four tests > (`test_no_match_message_qualifies_a_rejection_that_followed_a_raise`, > `test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw`, > `test_no_match_message_qualifies_the_advice_when_the_re_check_raises`, > `test_no_match_message_advises_an_input_when_one_of_two_raisers_answered`) because > `all` of an empty `trusted` is `True` and the caveat vanishes; it never > reaches the one-trusted-beside-one-untrusted case the finding is about. That > case is `all(i in trusted for i in answered if > results[i]._guard_check_enabled)`, which fails exactly > `test_no_match_message_trusts_one_rejection_taken_before_a_raise` and > nothing else. That test passes on the parent for the same reason the other > two do (no caveat to find), so it is a pin of this commit's `any`, not a > red-on-parent. > **FAQ: An entry that raised on one pass and rejected on the other is not in > `unanswered`, so its line quotes a third evaluation, `check_verbose(bound[i])`, > which runs under the same stale relational state the caveat warns about; and > since `trusted_rejection` is an `any`, one clean rejection elsewhere > suppresses the caveat and that line stands unqualified ([1]'s `stub guard > rejected` in `test_no_match_message_trusts_one_rejection_taken_before_a_raise`). > Mark such entries per line -- an index in `raised` and `answered` but not in > `trusted` -- reusing `_STALE_AFTER_THROW`.** > > Declined: the third evaluation is not the stale one, measured. > `_reset_relational_guard_state()` runs on every return path of > `RootGuardManager::check_nopybind_template` and `check_verbose_nopybind` > (`torch/csrc/dynamo/guards.cpp`) and only a throw skips it, so the one > evaluation that runs on stale state is the first to complete after the throw > -- dispatch's second-pass `check()`, the rejection the advice rests on -- and > that evaluation's own return resets the state before the report's > `check_verbose` runs. On a hand-built tree (`install_no_tensor_aliasing_guard` > over `x` and `y`, `add_tensor_match_guard` on `y`): `check(x, nested)` throws > `NestedTensorImpl doesn't support strides` out of the C++ leaf after the > aliasing guard has recorded `x`; the next `check(x, y)` returns `False` for a > call the fresh tree accepts (the stale rejection); the `check_verbose(x, y)` > after it returns `True`; and a `check_verbose(x, y)` made directly after the > throw instead returns `False` with `Duplicate tensor found where not > expected!`. The same sequence on Dynamo's own `PairModule` tree is what > `test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw` > pins. So the reason quoted on such a line is the clean verdict on the > same f_locals, and a marker saying it came out of stale state would be > false. What the reader needs is on the report already: the raiser line says > a checked tree raised and to fix or drop it, and the answer that may be > stale is dispatch's, which is the one the caveat qualifies; where that > stale rejection was spurious the clean re-check accepts and the entry line > reports that disagreement in so many words. > **FAQ: The caveat's `Fix the raise first` names no index, and the nearest > indexed raise on the report can be the wrong one: with [0] enabled raising > on both passes and [1] enabled raising on the scan then rejecting, the > raiser line names [0], the `__cause__` is [0]'s, and [1]'s raise -- the sole > reason the caveat is emitted -- appears nowhere. Name the indices whose > raise made the rejection untrusted and quote each one's raise from > `raised[i]`, and add a test for that two-entry shape.** > > Measured, and done in the commit above, `[aot_compile] Name and quote the > raises the no-match report's caveat means` (#197257). At this commit that > shape is the report of > `test_no_match_message_advises_an_input_when_one_of_two_raisers_answered`: > `[0] <guard check raised RuntimeError: the first tree is unhappy>`, `[1] > stub guard rejected`, `[0]'s guard check raised while checking this call`, > the advice ending in `Fix the raise first: ...`, `__cause__` = > `RuntimeError('the first tree is unhappy')`, and `the second tree's first > pass is unhappy` on the report zero times. The same dispatch under the > commit above's `aot_compile.py` ends the advice in `Fix the raise out of > [1] <RuntimeError: the second tree's first pass is unhappy> first: ...`, > that text once, with the raiser line and the `__cause__` unchanged, and the > commit above's test for that two-entry shape pins all of it. Not here, > because naming needs `_raise_text` split out of `_raised_line` and the list > over the enabled entries of `answered`, which with their tests are what this > commit was split from for review budget; what this commit owns is WHETHER > the caveat is emitted, and the two-raiser test now pins that it is in this > shape too, on the clause `followed a raise from its own tree` that the named > caveat keeps. That assertion fails on the commit below, and fails here with > `trusted` recorded without the `raised` check or with the gate's `any` made > a literal `all` over `trusted`. Co-Authored-By: Claude Fable 5.1 <[email protected]> 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #197050 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220, #197001, #197569, #197301, #196908, #197319, #197219, #197580
…means (#197257) Split from `[aot_compile] Say what the no-match report's advice rests on after a raise` (#197050, the commit below) for review budget: that commit appends a caveat to the report's `ModelInput` advice when every rejection the advice rests on followed a raise from its own tree, and this one makes the caveat name the trees it means and quote their raises. At the commit below the caveat reads `Fix the raise first: every rejection this advice rests on followed a raise from its own tree, and ...`, and the only raise the report names above it is the raiser line's: `[i]'s guard check raised while checking this call`, where `i` is the FIRST enabled index in `raised`, and the chain carries the first raise recorded of all. The tree the caveat means is an entry in `answered` but not in `trusted`, whose own entry line quotes its rejection, not its raise. Those coincide on a one-input report and diverge as soon as another enabled tree raised before it, so there `the raise` points at the wrong tree and the raise the caveat means is printed nowhere -- measured on `ScaleModule` with two inputs, a tree that raises on every pass at [0] and `RaisesOnceThenRejects("the scan is unhappy")` at [1]: the report at the commit below carries `[0] <guard check raised RuntimeError: every pass is unhappy>`, `[1] stub guard rejected`, `[0]'s guard check raised while checking this call`, and the advice ending in `Fix the raise first: ...`, with `the scan is unhappy` nowhere on it. Order to review: `_raise_text`, split out of `_raised_line`, and the caveat's caller added to the reachability comment on `_quoted`; the caveat's `untrusted` list, its `plural` and its join at the end of `_no_match_report`, the `coverable` and `trusted_rejection` gates it hangs off, and the comment on the list; the sentence added to the comment on `_STALE_AFTER_THROW`; the `AOTCompiledModel` docstring's clause about the report's closing lines; then, in the test file, the two placeholders added to `CAVEAT_AFTER_A_RAISE`, `test_no_match_message_names_the_tree_whose_raise_qualifies_the_advice`, `test_no_match_message_names_every_tree_whose_raise_qualifies_the_advice`, `test_no_match_message_caveat_quotes_a_raise_through_the_pybind_boundary`, `test_no_match_message_caveat_skips_an_opted_out_raise_then_rejection`, `test_no_match_message_caveat_reads_the_opt_out_snapshot`, and the quoting assertions added to `test_no_match_message_qualifies_a_rejection_that_followed_a_raise`, `test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw`, `test_no_match_report_reads_the_dispatch_record_after_a_raise` and `test_no_match_message_qualifies_the_advice_when_the_re_check_raises`, and the trailing separator and the odd exception kind added to `test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators`. The caveat now names those trees by index and quotes each one's raise -- `Fix the raise out of [1] <RuntimeError: the scan is unhappy> first` -- because nothing else on the report carries such a raise. `test_no_match_message_names_the_tree_whose_raise_qualifies_the_advice` is the shape above, and pins that [0]'s line, the raiser line and the `__cause__` are all [0]'s while the caveat names [1] and quotes its raise, the one place on the report that text appears. Building the caveat over `[raiser]` instead of the enabled entries of `answered` fails that test and `test_no_match_message_names_every_tree_whose_raise_qualifies_the_advice`, whose [1] the raiser line never names. The entries are the ENABLED ones: an opted-out tree that raised and then rejected is in `answered` too, since recording never reads the flag, but nobody asked about its guards, its own line is the withheld one blaming the raiser, and quoting its raise here would contradict that line and the withheld advice, which both say the raiser's raise is what withheld it. `test_no_match_message_caveat_skips_an_opted_out_raise_then_rejection` puts `RaisesOnceThenRejects` on an enabled [0] and on an opted-out [1], where [0] being an enabled raiser is what keeps the last resort from serving [1], and pins that the caveat names and quotes only [0], singular, with [1]'s message nowhere on the report; dropping the `enabled[i]` filter fails that test, on `Fix the raises out of [0] <RuntimeError: the checked scan is unhappy>; [1] <RuntimeError: the opted-out scan is unhappy> first`. Enabled means the `enabled` snapshot the entry lines read, not a fresh read of the flag: the report runs user code between the veto's read and this list -- an entry's `check_verbose`, or a `disable_guard_check()` from another thread, which is a plain store -- so a fresh read can drop an entry this same report printed as a rejection, and where it was the only one the sentence loses its subject, nothing left between `Fix the raise out of` and `first` and a doubled space where the tree should be. `test_no_match_message_caveat_reads_the_opt_out_snapshot` is that shape, the two-input report above with [1]'s `check_verbose` opting [1] out before it returns the rejection the advice rests on: the snapshot leaves `Fix the raise out of [1] <RuntimeError: the scan is unhappy> first`, and this filter made a fresh read leaves exactly the subjectless sentence and fails that test, the only test in the file it fails. The `coverable` and `trusted_rejection` gates that decide whether the caveat fires read that same snapshot, so what they found and what the list keeps cannot disagree: a `coverable and not trusted_rejection` report has an answered entry enabled in the snapshot and outside `trusted`, which is an entry `accepts()` recorded a raise for, so the list is never empty and `trusted` need not be subtracted. Off the flag the gates were two reads of it, and a store landing between them on the only answered entry left `coverable` true, `trusted_rejection` false and the subjectless sentence above over an empty list. Dropping the `enabled[i]` filter errors `test_no_match_message_quotes_a_tree_that_raised_then_answered` with `KeyError: 1` as well, its opted-out [1] having rejected with no raise on record. The quoted text comes from `_raise_text`, the part of `_raised_line` that turns a recorded raise into `Kind: reason`, with the same pybind-boundary clause and the same newline collapse, so an entry line and the caveat cannot describe one raise differently. The collapse covers the kind as well as the reason, which is why it wraps `Kind: reason` rather than the reason alone: `kind` is `type(reason).__name__`, and a class built with `type()` may hold a separator in its name, so interpolating it raw splits an entry line and the caveat over lines -- the failure the collapse exists to prevent, and one the caveat can multiply, a report carrying a kind per tree it names. An entry line that quotes a raise reads as before unless that text ends in a separator `splitlines()` breaks on: `_raised_line` collapsed the whole line after appending the bracket, so `...abc\n>` came out `...abc >`, while `_raise_text` collapses before the boundary clause and the bracket are appended and emits `...abc>`, which is also what keeps the C++-throw golden below clean. `test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators`, from a commit below, now ends its message in a fifth separator and raises a class named `Odd\nKind`, and pins the whole line, ` [0] <guard check raised Odd Kind: page break rec sep line (through the guard tree's pybind boundary)>`: on the commit below it fails on `sep line (through`, and with `kind` interpolated raw it fails on a report of four lines where it reads three, the entry split after `Odd`. The caveat is one sentence whichever number of trees it names. Each entry is bracketed as on the entry line, `[i] <Kind: reason>`, and the entries are joined with `; `: the quoted text is arbitrary user text that may hold commas, and `_raise_text`'s pybind-boundary clause is a parenthetical of its own, so parentheses around an entry nest it (`[0] (ValueError: boom on compare 1 (through the guard tree's pybind boundary))`) and a comma join puts a user comma where a boundary between entries reads. With two such trees it reads `Fix the raises out of [0] <RuntimeError: a>; [1] <RuntimeError: b> first`, and `_STALE_AFTER_THROW`, unchanged here, is already phrased for one tree or several -- `a C++ throw out of a tree can leave that tree's relational guard state stale, so its next check ...` -- so the clause has an antecedent however many trees precede it; its comment now says that is one reason for the phrasing. `test_no_match_message_names_every_tree_whose_raise_qualifies_the_advice` installs `RaisesOnceThenRejects` on both enabled results with different messages, one holding a comma, and pins the plural, both bracketed entries, and that each message appears exactly once on the report (the raiser line and the chain carry only [0]'s, the first recorded). The order the entries come in is incidental rather than pinned: `answered` holds small ints, whose set iteration is value-ordered at these table sizes, so dropping the `sorted` leaves the whole file green (`Ran 337 tests ... OK (skipped=6)`). Mutating `plural` to `""`, the join to `untrusted[0]` or the joiner to `, ` fails that test; parentheses around the entry fail it, the seven other tests that pin a whole caveat, and `test_no_match_report_reads_the_dispatch_record_after_a_raise`, which pins its one bracketed entry. `test_no_match_message_caveat_quotes_a_raise_through_the_pybind_boundary` renders the caveat for the other flavour of raise: a `RaisesThenHits(raises=1)` key on `DictBranchModule` raises through pybind on the scan and answers after it (`RaisesOnCompare` raises on every compare, so a tree keyed on it never gives the rejection the caveat rests on), and the test pins `[0] <ValueError: boom on compare 1 (through the guard tree's pybind boundary)>` inside the caveat, quoted exactly once on the report. A commit below's `test_no_match_message_quotes_a_tree_that_raised_then_answered` has that shape too and said no line of the report quotes its raise; the caveat now does, and its comment says so. `test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw`, from the commit below, drives the caveat with a real `TORCH_CHECK` throw out of `TENSOR_MATCH` (`NestedTensorImpl doesn't support strides`), and now pins the caveat quoting it as `[0] <RuntimeError: ...>` with no boundary clause, since pybind translated a throw with nothing chained. The golden collapses `str(cause)` as `_raise_text` collapses the reason, `" ".join(str(cause).splitlines())`: under `TORCH_SHOW_CPP_STACKTRACES=1`, which `test/run_test.py` sets when it retries a failed test, pybind takes `e.what()` over `e.what_without_backtrace()` and the message carries the C++ backtrace, one frame per line and each line newline-terminated, while the report is one line per paragraph, so an uncollapsed golden can never be the advice's suffix and the test would be red on exactly a retry: measured red with the variable set and the collapse removed from `_raise_text`, green with it, and green either way with the variable unset. The collapse is of `str(cause)` alone, not of the whole `[0] <RuntimeError: ...>` entry, because the last frame's newline sits right before the closing bracket and collapsing the whole entry leaves `... >` where `_raise_text`, which collapses the reason before the bracket is appended, emits `...>`. Against the commit below, nothing served or raised changes: the same calls raise the same `RuntimeError` with the same `__cause__`, and the dispatch passes, the veto, the warning and `trusted` are untouched, and the gates on the report's closing lines, the caveat's included, now read the `enabled` snapshot rather than the flag: nothing between the veto's read and them runs user code, so no call of its own accord tells the two apart, and the whole file is green under either read. Two texts differ: the caveat's, where `Fix the raise first` becomes `Fix the raise(s) out of [i] <Kind: reason>; ... first`, naming and quoting every enabled tree whose rejection the advice rests on, and a raise entry line whose reason ends in a separator, which loses the stray space before its closing bracket. The `AOTCompiledModel` docstring said the advice says to fix the raise first; it now says the advice names and quotes those raises, and the two comments that called the caveat a follow-up change -- that docstring's closing sentences and the one on the report's raise entry line, both accurate at the commit below -- say what it does today. The sentence that followed it -- reading a dispatch-recorded raise's entry line and `__cause__` onto the caveat -- is deleted rather than qualified again: the entry-line shapes, the caveat's gate and the `__cause__` rule are each stated once earlier in the same docstring, and the sentence only restated them. Both texts state that gate as `trusted` keys it, per tree rather than over every raise on the report -- a tree that rejected and THEN raised is trusted, and its own line quotes that raise -- and the entry-line comment keeps the commit below's reading for the shape the gate leaves out, an enabled tree that rejected before any raise from its own tree switching the caveat off, and then no line of that report carries the raise. One tree can put two raises on the report, in two bracketed forms: `test_no_match_message_qualifies_the_advice_when_the_re_check_raises`, from the commit below, has dispatch record `the first pass is unhappy` and then a rejection at [0], and the report's `check_verbose` raise `the re-check is unhappy`, so [0]'s entry line is `<guard check raised RuntimeError: the re-check is unhappy>` and the caveat quotes `[0] <RuntimeError: the first pass is unhappy>`. That is the intended reading, not a side effect: the caveat quotes the raise the rejection the advice rests on followed, which is dispatch's, and the re-check's raise is the report's own, already on the entry line. The test pins the whole caveat and that dispatch's message appears exactly once on the report, where it asserted only that the caveat was present. Five tests are new; five of the commits below's gain an assertion: three the assertion that the caveat quotes the raise for their case (`test_no_match_message_qualifies_a_rejection_that_followed_a_raise` and `test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw` pin the named entry through `CAVEAT_AFTER_A_RAISE`'s placeholders, and `test_no_match_report_reads_the_dispatch_record_after_a_raise`, whose [0] raised on the scan, rejected on the second pass and accepted on the re-check, pins the caveat's `Fix the raise out of [0] <RuntimeError: the first pass is unhappy> first`, and that it appears exactly once on the report, where it asserted that text absent), `test_no_match_message_qualifies_the_advice_when_the_re_check_raises` the whole caveat, and `test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators` the trailing separator and the odd kind; and a commit below's `test_no_match_message_quotes_a_tree_that_raised_then_answered` changes only its comment. Of those eleven, ten fail on the commit below's `aot_compile.py`, all but the comment-only one. The caveat's text stays one golden, `CAVEAT_AFTER_A_RAISE`, now with two placeholders, the plural of `raise` and the bracketed entries it names, that the eight tests pinning the whole paragraph share. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_no_match_message_names_the_tree_whose_raise_qualifies_the_advice python test/dynamo/test_aot_compile.py -k test_no_match_message_names_every_tree_whose_raise_qualifies_the_advice python test/dynamo/test_aot_compile.py -k test_no_match_message_caveat_quotes_a_raise_through_the_pybind_boundary python test/dynamo/test_aot_compile.py -k test_no_match_message_caveat_skips_an_opted_out_raise_then_rejection python test/dynamo/test_aot_compile.py -k test_no_match_message_caveat_reads_the_opt_out_snapshot python test/dynamo/test_aot_compile.py -k test_no_match_message_qualifies_a_rejection_that_followed_a_raise python test/dynamo/test_aot_compile.py -k test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw TORCH_SHOW_CPP_STACKTRACES=1 python test/dynamo/test_aot_compile.py -k test_no_match_message_qualifies_a_rejection_that_followed_a_cpp_throw python test/dynamo/test_aot_compile.py -k test_no_match_report_reads_the_dispatch_record_after_a_raise python test/dynamo/test_aot_compile.py -k test_no_match_message_quotes_a_tree_that_raised_then_answered python test/dynamo/test_aot_compile.py -k test_no_match_message_qualifies_the_advice_when_the_re_check_raises python test/dynamo/test_aot_compile.py -k test_no_match_report_keeps_a_raise_on_one_line_past_odd_separators python test/dynamo/test_aot_compile.py lintrunner --take RUFF,PYFMT torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py ``` The eleven were also run against the commit below's `torch/_dynamo/aot_compile.py` (ten fail, the comment-only one passes), and the caveat's construction was then mutated one term at a time -- built over `[raiser]` instead of the enabled entries of `answered`, the `enabled[i]` filter dropped, that filter made a fresh `results[i]._guard_check_enabled` read, both gates made fresh reads of the flag, `plural` made `""`, the join made `untrusted[0]`, the joiner made `, `, the entries parenthesized, and `kind` interpolated raw in `_raise_text` -- and the tests that name the caveat rerun; only the tests named above failed under each, the gates' fresh reads leaving the whole file green and the filter's fresh read failing `test_no_match_message_caveat_reads_the_opt_out_snapshot` alone. Authored with the assistance of Claude Code. > **FAQ: The trailing-separator improvement is exact only for one trailing > separator: two leave `...abc >` still, since collapsing a text that ends in > two of them yields a trailing space of its own.** > > True, and left as is: the collapse puts a space between the pieces > `splitlines()` returns, so a text ending in N separators keeps N-1 spaces > before the bracket. What the format rests on is the entry staying on one > line, which holds for any N, and no golden reads the residue; stripping it > would be a rule the report applies to no other quoted text. Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: #197257 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220, #197001, #197569, #197301, #196908, #197319, #197219, #197580, #197050
…as (#197745) **Problem.** `IMPORT_NAME` checked that `__import__`'s result was a module only after `import_source` had already bound the result into the traced globals and a process-wide cache, so a non-module `sys.modules` entry was left behind in both, and a later trace with a real module in the entry crashed with an `InternalTorchDynamoError` instead of compiling. **Fix.** Move the module-type check ahead of the `import_source` call, so a non-module never reaches the traced globals or the cache and the graph break happens first; the replay arm needs no check and pushes as-is. **Summary.** `IMPORT_NAME` tested `__import__`'s result with `isinstance(value, (types.ModuleType, DummyModule))` at push time, after `import_source` had already minted `__import_<mangled>` for the name and written that result into `self.output.global_scope` -- the root frame's real globals, a live module `__dict__` that nothing unwinds -- and into `_import_module`'s process-wide cache. `sys.modules` accepts any object and `__import__` hands it back verbatim, so a non-module entry was bound under the alias and only then graph-broken on (`Bad import result`), and a later trace, after a real module had replaced the entry, passed the push-time check on the module `__import__` returned while `import_source` served the cached non-module: the alias kept the non-module, the pushed variable held the module, and the guards built on the alias read `VALUE` off an `object()`, an `InternalTorchDynamoError` on a trace that should have compiled. Hoisting the check ahead of the `import_source` call keeps the non-module out of the traced globals and out of the cache, since the call that filled it no longer runs, so a later trace with a real module in the entry binds the alias to that module and compiles. The hoisted test is `isinstance(value, types.ModuleType)` alone and sits on the import arm only, because a replayed value is a `DummyModule`, a plain dataclass that is not a `ModuleType`, which `add_local_mod` already rejected non-modules for when the record was written, so the replay arm pushes with no type test and the `DummyModule` import goes away. Two behaviours change against the parent, both pinned or explained below: `IMPORT_NAME` of a non-module entry no longer writes the alias before breaking, and with `replay_record_enabled` on such an entry reaches the graph break instead of `add_local_mod`'s `AssertionError`. ## The bug: bind first, check second ```python # parent, IMPORT_NAME value = __import__(module_name, ...) # sys.modules[name] handed back verbatim source = self.import_source(module_name) # mints __import_<mangled>, writes value into # self.output.global_scope AND _import_module's cache if isinstance(value, (types.ModuleType, DummyModule)): # checked only now self.push(PythonModuleVariable(value, source=source)) else: unimplemented(gb_type="Bad import result", ...) # too late: the alias is already bound ``` `self.output.global_scope` is the root frame's real globals, a live module `__dict__` that nothing unwinds, so the non-module stayed bound under the alias for good. The second failure follows from the cache: ```python sys.modules[name] = object() torch.compile(fn)(x) # parent: Unsupported: Bad import result -- but fn.__globals__["__import_..."] is the object() torch._dynamo.reset() sys.modules[name] = module # a real module now torch.compile(fn)(x) # parent: InternalTorchDynamoError -- the guards read VALUE off the cached object() # now: compiles, agrees with eager, alias bound to `module` ``` On the parent's second trace, `__import__` returned the module, so the push-time check passed, but `import_source` served the cached non-module: the alias kept the non-module, the pushed variable held the module, and the guards built on the alias read `VALUE` off an `object()`. ## The fix: check before `import_source` ```python # now, IMPORT_NAME, import arm value = __import__(module_name, ...) if not isinstance(value, types.ModuleType): unimplemented(gb_type="Bad import result", context=typestr(value), explanation="Import result is not a Python module.", hints=[]) ... source = self.import_source(module_name) # never reached with a non-module ... self.push(PythonModuleVariable(value, source=source)) # no type test on either arm ``` Hoisting the check ahead of the `import_source` call keeps the non-module out of the traced globals and out of the cache, since the call that filled it no longer runs: a later trace with a real module in the entry binds the alias to that module and compiles. **Why `ModuleType` alone, on the import arm only.** A replayed value is a `DummyModule`, a plain dataclass that is not a `ModuleType`, so a check on that arm would refuse every replay -- and needs none, `add_local_mod` having rejected non-modules when the record was written. That is why the replay arm now pushes with no type test at all, and why the `DummyModule` half of the old condition, which existed only for it, goes away with the import from `replay_record`. ## The other nine `import_source` callers The check guards this one call site. The other nine `import_source` callers reach it with no module-type test, and a non-module entry under one of their names is still bound verbatim there, unchanged here -- though `get_globals_source_and_value` already brings its own test, since `_registered_module_for_globals` returns a name only for a `types.ModuleType` whose `__dict__` is the frame's globals. Those names are torch's own and stdlib ones, or a class's `__module__`; a non-module under one of them is a broken process, not a trace to save. `IMPORT_NAME` is the one caller resolving a name the traced bytecode chose, which is what makes its result worth checking. ## Behaviour changes against the parent - **`IMPORT_NAME` of a non-module `sys.modules` entry no longer writes the alias before breaking.** `test_import_alias_is_not_bound_to_a_non_module_import` pins it by planting a non-module, requiring the `Bad import result` graph break and an unbound alias, and then, with a real module in the entry, a compile that agrees with eager and an alias bound to that module. - **With `replay_record_enabled` on (off by default), such an entry now reaches that graph break** instead of the `AssertionError` `add_local_mod` raised first when it ran ahead of the check. That one is untested, since the path is the parent's `add_local_mod` and the config is off by default. ## The test ```python name = "torch_test_package_import_alias_non_module" alias = f"__import_{name}" def fn(x): import torch_test_package_import_alias_non_module as taken return x + taken.VALUE sys.modules[name] = object() with self.assertRaisesRegex(Unsupported, "Bad import result"): torch.compile(fn, backend="eager", fullgraph=True)(*args) self.assertNotIn(alias, fn.__globals__) # parent: the alias is bound to the object() torch._dynamo.reset() sys.modules[name] = module # types.ModuleType(name) with VALUE = 1 compiled = torch.compile(fn, backend="eager", fullgraph=True) self.assertEqual(fn(*args), compiled(*args)) # parent: InternalTorchDynamoError from the guard build self.assertIs(fn.__globals__[alias], module) ``` The cleanup clears `_import_module`'s cache as well as `sys.modules` and the alias, since the memo outlives the `sys.modules` entry and a same-process rerun would otherwise resolve this run's module from it. The test lives in `test_package.py` rather than `test_misc.py` because the alias binding this is about is the one `CompilePackage` records and `install()` rebinds, and that file already owns the rest of the `import_sources` coverage. Test Plan: ``` python test/dynamo/test_package.py -k test_import_alias_is_not_bound_to_a_non_module_import python test/dynamo/test_package.py ``` The new test is red on the parent's `torch/_dynamo/symbolic_convert.py`, on the alias the parent wrote before breaking, and its second half fails there too, with the guard-build `AttributeError` on the cached `object()`; restoring the push-time `isinstance` in place of the hoisted one reproduces the first failure. The whole file is green at this commit. ``` lintrunner --take RUFF,PYFMT,CODESPELL,GB_REGISTRY torch/_dynamo/symbolic_convert.py torch/_dynamo/graph_break_registry.json test/dynamo/test_package.py ``` The `Bad import result` registry entry is unchanged: the call moves, its strings do not. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: #197745 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220, #197001, #197569, #197301, #196908, #197319, #197219, #197580, #197050, #197257
…197746) A refactor with no behaviour change, to make room for the commit directly above, which gives `import_source` a second argument: `graph_break_ok`, the flag that decides whether an alias slot already holding something else is a graph break or a hard error. `cache_method` keys on the whole argument tuple, so that flag would silently become part of the key, and a module name that two callers on one translator both resolve would run the body once per distinct flag value instead of once. Nothing about the second run would be wrong -- `f_globals[alias] is value` holds by then, so the check is skipped, and the package record and `update_co_names` are idempotent -- but the memo exists to make resolution happen once, and the flag cannot change the answer a memo hit returns: it is read only when the slot is taken, which a hit rules out, because the memo is written only past that check. First-caller-wins is therefore the same source any caller would have got. Keying on `module_name` alone also lets the new argument be passed by keyword at the call sites, which the decorator forbade. So the decorator gives way to an explicit `_import_source_memo` dict declared in `InstructionTranslatorBase.__init__`, read at the top of the method and written just before the return. Its lifetime is the decorator's: it lives on the translator and dies with it, which is what made the cache safe in the first place -- the alias it hands back names a global in the globals of the compile that minted it. The comment above the method now says why the key is one argument rather than the signature. Test Plan: ``` python test/dynamo/test_package.py -k import_alias python test/dynamo/test_package.py ``` Behaviour-neutrality was also measured directly on this tree, on a frame doing `from torch.autograd.profiler import profile` with `config.record_runtime_overhead` on, so that `IMPORT_NAME` and codegen's pregraph marker both resolve `torch.autograd.profiler`: the sequence of aliases `import_source` resolves across the compile is identical before and after this commit. ``` lintrunner --take RUFF,PYFMT,CODESPELL,GB_REGISTRY torch/_dynamo/symbolic_convert.py torch/_dynamo/graph_break_registry.json test/dynamo/test_package.py ``` Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: #197746 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220, #197001, #197569, #197301, #196908, #197319, #197219, #197580, #197050, #197257, #197745
Stack from ghstack (oldest at bottom):
The commit below raises a report when no compiled graph matches, and when an
entry's guards failed on a global the process does not have it appends the
function path's
_missing_global_hintfor that entry on aFor [i, j]:line,one per distinct sentence, naming the entries that share it. For
a result whose scope is SUPPLIED -- a module load that resolved its guard scope
itself -- that sentence read
a guarded global is missing from the live scope this artifact was loaded against, here vars(<module>), which names the dictonly when it is a module's namespace and otherwise says nothing about where the
name has to go. This commit has the report name the attribute the load resolved
the scope from:
the globals of the function this <Type> instance's forward resolves to, since that is the one the load resolved, keeping the, here vars(<module>)suffix when that dict is a module's namespace.The name is passed only when the guards really hold the dict that attribute
resolves to.
deserializeskips_resolve_guard_scopeentirely for acaller-supplied
guard_globals=, so a result loaded that way holds a dict noforward resolves to and keeps the scope-neutral wording -- naming the class's
forward there would send the reader to a dict where the name is already defined
and dispatch still fails. The report decides by comparing the dict the guards
hold against a fresh resolution rather than a bit recorded at load, which costs
a
get_traced_fnon the raise path only and also covers a rebind made afterthe load. It asks only of a result whose scope is SUPPLIED: the CAPTURED and
RECONSTRUCTED wordings never name
forward, and resolving it runs user code --get_traced_fnformats a forward it refuses into its error before raising(
Unsupported model code type {mod}in convert_frame.py), and for afunctools.partialover the module that repr reaches the user'sextra_repr,outside the
(RuntimeError, AttributeError)the helper catches. Dispatch callsresult.fn(self.model, ...)and never the instance'sforward, so a rebindafter the load reaches only the report -- and on a SUPPLIED result the report
does resolve it, so that resolve is wrapped: any exception it raises degrades
the wording to the scope-neutral one rather than replacing the report with
itself. The gate narrows the window; the catch closes it.
The printed name is
this <Type> instance's forward, the attribute the loadresolved the scope from, and not the class's
<Type>.forward: the two are onelookup until an instance rebinds
forward, after which the guards read thatother function object's globals, so naming the class attribute would need a
second clause hedging for the rebind -- one that, for the rebound test below,
points at a dict where defining the name does not restore dispatch. Defining
the absent name in the resolved dict is what restores dispatch -- the guards
hold the dict by reference, so a name defined after the load resolves, while
the graph goes on reading the value serialized at capture, since the bytecode
globals are built once at load and a live value is substituted only for a name
the scope had then -- and defining it beside the class definition need not,
which
test_no_match_message_hint_covers_a_rebound_forwardasserts both waysround for a rebind over foreign globals. An un-rebound load prints the same
forward-naming hint plus a
, here vars(<module>)suffix; the reboundfunction's dict is no module's namespace, so
_module_namespace_namenamesnothing and the suffix is absent. That is also why the rebound load is the test
that tells the instance attribute from the class's: defining the name beside
the class definition serves an un-rebound load, so nothing there distinguishes
the two.
The name is decided per entry, since the public constructor accepts results
of differing scopes:
_resolve_guard_scope(self.model)runs at most once perreport, on the first SUPPLIED entry that named a missing global, and each
SUPPLIED entry compares that dict against its own
_guard_globals; entrieswhose sentences match then share one
For [i, j]:line.Behaviour change vs the commit below, on the module path only: for a load
(
AOTCompiledModel.deserializeor_load_aot_compiled_module) that passed noguard_globals=and whose instanceforwardstill resolves to the dict theload used, the
For [i, j]:line reads... the globals of the function this <Type> instance's forward resolves to, since that is the one the load resolved, here vars(m); define it there ...instead of... the live scope this artifact was loaded against, here vars(m); define it there .... Every other wording --the
guard_globals=case, CAPTURED, RECONSTRUCTED, and the function path -- isunchanged. The landed
test_aot_compile_module_missing_global_hint_names_the_resolved_moduleasserts, here vars(<module>); define it therefor the first andloaded against; define it therefor aguard_globals=copy of the namespace, and passes atboth commits.
Order to review:
_missing_global_hint'sforward=keyword and thewhereternary in its SUPPLIED branch; then the report site in
_no_match_report(the SUPPLIED gate, the wrapped
_resolve_guard_scope, the identity comparethat clears
forward); thenRaisingReprModuleand the two tests.Test Plan:
The whole file runs 189 tests,
OK (skipped=6), two more than the commitbelow. Run against the commit below's
aot_compile.py,test_no_match_message_hint_covers_a_rebound_forwardfails:"the function this HermeticModule instance's forward resolves to" not found, the reportcarrying the neutral
the live scope this artifact was loaded againstinstead.test_no_match_report_survives_a_forward_resolve_that_raisesPASSES there --the neutral wording is what that commit prints for every SUPPLIED result -- so
it pins nothing about the commit below and exactly one thing about this one,
the catch: removing the
except Exceptionaround the resolve fails it withValueError: extra_represcaping in place of the report. Never clearingforward(dropping the identity compare) fails it on the scope-neutralassertion, with a report that names
this RaisingReprModule instance's forward, and fails the landedtest_aot_compile_module_missing_global_hint_names_the_resolved_moduleon itsguard_globals=half,'loaded against; define it there' not found. Bothmutations measured at this commit.
test_no_match_message_hint_covers_a_rebound_forwardsaves an artifactcaptured from an un-rebound
HermeticModule, then loads it into an instancewhose
forwardis the same code object over a foreign globals dictns, withAOT_HERMETIC_WEIGHTpopped from this module. The report namesthis HermeticModule instance's forward; restoring the name in this module -- whereHermeticModule.forward, the class attribute, is defined -- still raises theKeyError on G['AOT_HERMETIC_WEIGHT']report, asserted withassertRaisesRegexon that text so that a differentRuntimeErrorwould notpass; defining it in
nsserves the call withx @ saved.test_no_match_report_survives_a_forward_resolve_that_raisesloads throughAOTCompiledModel.deserialize(inst, data)with noguard_globals=, so everyresult is SUPPLIED and the report does resolve
forward; it then rebinds theinstance's
forwardto afunctools.partialover a module whoseextra_reprraises
ValueError, assertsrepr(inst.forward)raises it, and asserts thereport still arrives worded for
the live scope this artifact was loaded against, since the rebound forward resolves to no dict the guards hold.Four more tests of this hint sit in #197001, the test-only commit directly
above: the hint stays scope-neutral for a caller-supplied
guard_globals=, aCAPTURED result's report names no
forwardand never resolves it, the advicestill reaches a report whose every entry named a missing global, and a missing
KEY inside a present global is not a missing global; three of them pin the gate
and the compare added here, and that commit's message says which edit to this
report each one catches.
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