Repository navigation
[aot_compile] Advise a ModelInput only when some checked tree answered the no-match report's call - #197220
Closed
bobrenjc93 wants to merge 18 commits into
Closed
[aot_compile] Advise a ModelInput only when some checked tree answered the no-match report's call#197220bobrenjc93 wants to merge 18 commits into
bobrenjc93 wants to merge 18 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/197220
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (2 Unrelated Failures)As of commit fddb74b with merge base 51d4378 ( GREEN LIGHT - PR approved to be merged without human review:
reason: UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This was referenced Sep 16, 2026
Closed
Closed
bobrenjc93
added a commit
that referenced
this pull request
Sep 16, 2026
…d the no-match report's call Split from `[no-ci] [aot_compile] Say what the no-match report's advice rests on after a raise` (#<sibling>, 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 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 -- 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.` and then `Add a ModelInput ...`, two instructions that contradict each other. Order to review: `answered` and its update in `accepts()`; the report's `coverable`; the two gated lines at the end of `_no_match_report` and the comment on the empty artifact; the sentence of the `AOTCompiledModel` docstring that describes the report's closing lines; then, in the test file, `test_no_match_message_when_every_guard_tree_raised`, `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`. 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 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`). Only when no checked tree ever answered does it say instead that the reasons above are the raises themselves, since an input covering that call would guard the same dict and raise the same way -- and it says so only when a raise is actually on record and there is no withheld opt-out to contradict, because that entry's own line has already said what happened to it. Dropping `not withheld` from that gate fails `test_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result` on the report contradicting its own withheld line. `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 two gates are independent `if`s: they are already exclusive on `coverable`, and an `elif` would read as an ordering that does not exist. 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, and an every-tree-raised line replaces it when the reasons above are all raises and no opt-out was withheld. Making the `ModelInput` line unconditional again fails `test_no_match_message_when_every_guard_tree_raised`, `test_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result` and `test_aot_compile_module_restores_torch_function_after_a_throw` 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 some tree 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 -- and that the replacement too stays off a report whose withheld line has already said the raise withheld an opt-out. Three tests are new and five of the commit below's tests gain an assertion about the line this commit adds or removes for their case. Of those eight, four fail on the commit below's `aot_compile.py`: `test_no_match_message_when_every_guard_tree_raised`, `test_no_match_message_when_a_raise_did_not_cross_the_pybind_boundary`, `test_aot_compile_module_raising_tree_does_not_reach_an_opted_out_result` and `test_aot_compile_module_restores_torch_function_after_a_throw`. The four 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), and `test_no_match_message_when_only_the_report_raises` and `test_no_match_message_after_a_raise_counts_no_second_rejection`, which gain only an assertion that the every-tree-raised line is absent from their reports, whose one tree answered. 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_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_no_match_message_after_a_raise_counts_no_second_rejection 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 lintrunner --take RUFF,PYFMT torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py ``` The eight were also run against the commit below's `torch/_dynamo/aot_compile.py` (four fail, the four named above pass), and each gate was then mutated on its own -- `coverable` keyed on the last evaluation, `not results` dropped, `not withheld` dropped, the `ModelInput` line made unconditional -- and the eight rerun; only the tests named above failed under each. Authored with the assistance of Claude Code. ## FAQ > **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. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: 16bf741 Pull-Request: #197220
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
bobrenjc93
marked this pull request as ready for review
September 18, 2026 14:13
Contributor
Author
|
@pytorchbot merge -i |
Collaborator
bobrenjc93
added a commit
that referenced
this pull request
Sep 18, 2026
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 `KeyboardInterrupt` or `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. 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_interrupt_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. Two module-level helpers beside `compile_mode_defaults` serve 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), and `AlwaysRaises(message)`, the stub guard manager whose every `check()` raises, subclassing `NeverReChecked` so a regression that re-checks it in a report fails on that class's message; the interrupt and cannot-bind tests use it where each had its own copy. 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. `test_aot_compile_module_interrupt_out_of_a_later_tree_propagates`: two results, [0]'s tree raising `RuntimeError` and [1]'s raising, on one call each, `KeyboardInterrupt` and then `SystemExit`; each leaves `__call__` as itself 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` travels the same path as `KeyboardInterrupt` today -- one `except Exception` in `accepts()` is the only handler between the tree and the caller, and the comment says so -- and is there because the `AOTCompiledModel` docstring promises both propagate: without it an `except (Exception, SystemExit)` added later would pass every test in the file (measured below). The order of the two iterations is not load-bearing (FAQ below). `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). `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 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. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_aot_compile_module_interrupt_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 runs 283 tests, `OK (skipped=6)`, three more than #197195's file loads. `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 interrupt 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, run against the whole 283-test file at this commit; the tests named are the only ones that failed. 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`: 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)` 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` with `Expected 2 but got 4` binds (and the landed `test_module_dispatch_decides_a_shared_binding_past_the_first_result`, on `_binds_alike` being called). Deleting the second pass fails it on its `check` counts, `Expected 2 but got 1` -- its bind count alone reads the same with one pass as with two -- along with 14 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. Widening `accepts()`' handler to `BaseException` fails only `test_aot_compile_module_interrupt_out_of_a_later_tree_propagates`, whose `KeyboardInterrupt` call gets a `RuntimeError: No AOT compiled graph matched this call. Tried 2 compiled input(s)` report where it asked for the interrupt; widening it to `(Exception, SystemExit)` fails only the same test, on its `SystemExit` call, the same way. 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`), and one other test in the file, #196826's `test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning`, the same way (FAQ below). Making the dispatch handler re-raise fails the interrupt 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 interrupt test's last call, whose log then names `[1]`; that mutant is #197195's, whose message lists the four tests it fails there. Replacing [0]'s `AlwaysRaises` 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_interrupt_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 to `accepts()`' handler: > 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 > interrupt 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 all > three aborted calls. 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 interrupt 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 calls' `assertNoLogs`. Are the aborted calls not > the test?** > > The last call pins WHERE the dedup is judged. 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 calls (nothing is logged; the interrupts > still escape), #197195's pop and every-input tests and #196826's > single-result and once-per-model tests alike, and fails exactly two of the > file's 283 tests: this last call, with `no logs of level WARNING or higher > triggered`, because the aborted calls had already consumed `(0, > "RuntimeError")`, and #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 interrupt and > whose second call is silent for the same reason. 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: `unittest`'s `testPartExecutor` re-raises `KeyboardInterrupt` but > catches `SystemExit`, so does the interrupt test's iteration order -- > `KeyboardInterrupt` first -- decide whether a regression aborts the whole > run or is reported as one failure?** > > No, measured. The only `KeyboardInterrupt` the test raises is the stub's, > inside `assertRaisesRegex(KeyboardInterrupt, ...)`, which catches it on the > expected path and turns a wrong message into an `AssertionError`; a > regression that swallows it hands the test the no-match report, a > `RuntimeError`, which `assertRaisesRegex` lets through as this test's > error. With `accepts()`' handler widened to `BaseException`, the whole > file ran to completion in either order: 283 tests, `FAILED (errors=1)`, > the one error this test's `KeyboardInterrupt` iteration getting > `RuntimeError: No AOT compiled graph matched this call. Tried 2 compiled > input(s)`, both as written and with the tuple reversed to `(SystemExit, > KeyboardInterrupt)`. No `KeyboardInterrupt` reaches `testPartExecutor` on > any path this test has, so the order says nothing and the comment claims > nothing about it. > **FAQ: `AlwaysRaises` replaces this commit's two inline `Raises` stubs; > the file's twelve other inline raisers (eight `Raises`, four > `RaisingGuardManager`, two of them already taking the message as a > constructor argument) are left in place. Why not convert them too?** > > `git blame` puts every one of them in a test of #196826, #197179, #197188 > or #197195 below, and this commit's one claim about #197195's eight tests > is that it does not touch them; converting their stubs here would put > edits to four other PRs' tests in a commit whose diff is otherwise three > tests and two helpers, and would shift the hunks #197220, #197050 and > #197257 apply above. `AlwaysRaises` is module level so those owners can > adopt it in one line each; the two message-taking copies are drop-ins for > it already. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: 4b8ef1f Pull-Request: #197219
bobrenjc93
added a commit
that referenced
this pull request
Sep 18, 2026
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 `KeyboardInterrupt` or `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. 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_interrupt_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. Two module-level helpers beside `compile_mode_defaults` serve 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), and `AlwaysRaises(message)`, the stub guard manager whose every `check()` raises, subclassing `NeverReChecked` so a regression that re-checks it in a report fails on that class's message; the interrupt and cannot-bind tests use it where each had its own copy. 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. `test_aot_compile_module_interrupt_out_of_a_later_tree_propagates`: two results, [0]'s tree raising `RuntimeError` and [1]'s raising, on one call each, `KeyboardInterrupt` and then `SystemExit`; each leaves `__call__` as itself 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` travels the same path as `KeyboardInterrupt` today -- one `except Exception` in `accepts()` is the only handler between the tree and the caller, and the comment says so -- and is there because the `AOTCompiledModel` docstring promises both propagate: without it an `except (Exception, SystemExit)` added later would pass every test in the file (measured below). The order of the two iterations is not load-bearing (FAQ below). `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). `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 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. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_aot_compile_module_interrupt_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 runs 283 tests, `OK (skipped=6)`, three more than #197195's file loads. `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 interrupt 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, run against the whole 283-test file at this commit; the tests named are the only ones that failed. 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`: 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)` 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` with `Expected 2 but got 4` binds (and the landed `test_module_dispatch_decides_a_shared_binding_past_the_first_result`, on `_binds_alike` being called). Deleting the second pass fails it on its `check` counts, `Expected 2 but got 1` -- its bind count alone reads the same with one pass as with two -- along with 14 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. Widening `accepts()`' handler to `BaseException` fails only `test_aot_compile_module_interrupt_out_of_a_later_tree_propagates`, whose `KeyboardInterrupt` call gets a `RuntimeError: No AOT compiled graph matched this call. Tried 2 compiled input(s)` report where it asked for the interrupt; widening it to `(Exception, SystemExit)` fails only the same test, on its `SystemExit` call, the same way. 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`), and one other test in the file, #196826's `test_aot_compile_module_two_raisers_in_the_report_and_then_the_warning`, the same way (FAQ below). Making the dispatch handler re-raise fails the interrupt 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 interrupt test's last call, whose log then names `[1]`; that mutant is #197195's, whose message lists the four tests it fails there. Replacing [0]'s `AlwaysRaises` 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_interrupt_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 to `accepts()`' handler: > 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 > interrupt 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 all > three aborted calls. 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 interrupt 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 calls' `assertNoLogs`. Are the aborted calls not > the test?** > > The last call pins WHERE the dedup is judged. 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 calls (nothing is logged; the interrupts > still escape), #197195's pop and every-input tests and #196826's > single-result and once-per-model tests alike, and fails exactly two of the > file's 283 tests: this last call, with `no logs of level WARNING or higher > triggered`, because the aborted calls had already consumed `(0, > "RuntimeError")`, and #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 interrupt and > whose second call is silent for the same reason. 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: `unittest`'s `testPartExecutor` re-raises `KeyboardInterrupt` but > catches `SystemExit`, so does the interrupt test's iteration order -- > `KeyboardInterrupt` first -- decide whether a regression aborts the whole > run or is reported as one failure?** > > No, measured. The only `KeyboardInterrupt` the test raises is the stub's, > inside `assertRaisesRegex(KeyboardInterrupt, ...)`, which catches it on the > expected path and turns a wrong message into an `AssertionError`; a > regression that swallows it hands the test the no-match report, a > `RuntimeError`, which `assertRaisesRegex` lets through as this test's > error. With `accepts()`' handler widened to `BaseException`, the whole > file ran to completion in either order: 283 tests, `FAILED (errors=1)`, > the one error this test's `KeyboardInterrupt` iteration getting > `RuntimeError: No AOT compiled graph matched this call. Tried 2 compiled > input(s)`, both as written and with the tuple reversed to `(SystemExit, > KeyboardInterrupt)`. No `KeyboardInterrupt` reaches `testPartExecutor` on > any path this test has, so the order says nothing and the comment claims > nothing about it. > **FAQ: `AlwaysRaises` replaces this commit's two inline `Raises` stubs; > the file's twelve other inline raisers (eight `Raises`, four > `RaisingGuardManager`, two of them already taking the message as a > constructor argument) are left in place. Why not convert them too?** > > `git blame` puts every one of them in a test of #196826, #197179, #197188 > or #197195 below, and this commit's one claim about #197195's eight tests > is that it does not touch them; converting their stubs here would put > edits to four other PRs' tests in a commit whose diff is otherwise three > tests and two helpers, and would shift the hunks #197220, #197050 and > #197257 apply above. `AlwaysRaises` is module level so those owners can > adopt it in one line each; the two message-taking copies are drop-ins for > it already. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: 02f1b6b Pull-Request: #197219
Contributor
|
@pytorchbot drci |
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 19, 2026
…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
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 19, 2026
…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
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 19, 2026
**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
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 19, 2026
…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
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 19, 2026
…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
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 19, 2026
…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
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 19, 2026
…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
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 19, 2026
…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
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 20, 2026
…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
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 20, 2026
…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
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 20, 2026
…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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):
Problem. When every checked guard tree raised, the no-match report still ended with
Add a ModelInput covering this call, which contradicts its ownfix or drop that artifactline: a new input would guard the same dict and raise the same way.Fix. Dispatch records which trees actually answered. The report advises a
ModelInputonly 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 satisfyis 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 recordsanswered, the indices that reached an answer in either pass, written on a rejection only, and the report advises aModelInputwhenever 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 ownfix or drop that artifactline already says as much. Nothing served or raised changes -- the same calls raise the sameRuntimeErrorwith 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'saot_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
DictBranchModulewith one input and a colliding key, the report at the commit below reads: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_raisedpins that report now ending on the fix-or-drop line.Recording who answered
Dispatch now records which entries reached an answer, and records it where the order is known rather than reconstructing it afterwards.
answeredholds the indices that reached an answer in either dispatch pass, which is what theModelInputadvice 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:coverableread offanswered - unansweredfailstest_no_match_message_advises_an_input_after_an_answer_then_a_raisewith noModelInputline 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
The
ModelInputline. The report advises aModelInputwhenever 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 overraised).deserializeaccepts an artifact holding no inputs at all, whereaot_compile_modulerefuses one: with no entries there is no raise to describe and nothing that could have answered, so that report carries theModelInputline alone -- adding an input is exactly its advice. Droppingnot resultsfrom theModelInputgate failstest_no_match_report_claims_no_raise_for_an_artifact_with_no_inputson 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 artifactline the commit below already emits for it: that raiser's entry line, that advice and a footer saying every tree raised would say[0] raisedthree times over, which is what the first version of this commit printed -- measured ontest_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 thenEvery 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.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 withheldterm excludes -- solen(raised) > 1counts the raisers and the entries alike. The two gates are independentifs: they are already exclusive oncoverable, and anelifwould read as an ordering that does not exist.Each term of the footer's gate is pinned by a mutation:
raisedinstead oflen(raised) > 1test_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)not withheldtest_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)not coverabletest_no_match_message_advises_an_input_when_one_of_two_raisers_answered(footer beside theModelInputadvice it contradicts)What changes against the commit below
Nothing served or raised changes: the same calls raise the same
RuntimeErrorwith the same__cause__, and the dispatch passes, the veto and the warning are untouched. Only the report's closing lines differ: theModelInputline 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 theModelInputline unconditional again failstest_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_warningandtest_no_match_report_keeps_a_raise_on_one_line_past_odd_separatorson the line appearing.The
AOTCompiledModeldocstring 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 whattest_no_match_report_claims_no_raise_for_an_artifact_with_no_inputspins -- 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_throwandtest_aot_compile_module_two_raisers_in_the_report_and_then_the_warning, on theModelInputline 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,ModelInputadvice -- against the three a single raiser's report has now.The five that pass there do so because the parent's
ModelInputline 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(coverableoveranswered, not over the last evaluation);test_no_match_message_advises_an_input_when_one_of_two_raisers_answered(not coverableon 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
answeredand its update inaccepts(); the report'scoverable; 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 theAOTCompiledModeldocstring 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_inputsandtest_no_match_message_advises_an_input_after_an_answer_then_a_raise.Test Plan:
The eleven were also run against the commit below's
torch/_dynamo/aot_compile.py(six fail, the five named above pass), andeach gate was then mutated on its own --
coverablekeyed on the lastevaluation,
not resultsdropped, theModelInputline made unconditional,the footer gated on
raisedinstead oflen(raised) > 1, itsnot withhelddropped, itsnot coverabledropped -- and the eleven rerun; onlythe tests named above failed under each.
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