Repository navigation
[dynamo] Rebind a stale module alias instead of failing the trace - #196896
bobrenjc93 wants to merge 74 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/196896
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 124f988 with merge base 51d4378 ( 🟡 GREEN LIGHT - PR requires human review:
reason: UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
[ghstack-poisoned]
|
Claude finished @bobrenjc93's task in 39m 28s —— View job Reviewed — the relaxation looks unsound to me: the object it rebinds the alias to is the process-memoized (possibly stale) module, while the trace specializes on the live one, so guards end up watching a different object than the graph was built from; details below. Full reviewPR Review: #196896SummaryRelaxes Infrastructure
So in exactly the scenario the PR targets — first compile memoizes A, Worse for the precompile path the change is written for: The test masks this by construction: If it reproduces, the minimal fix is to keep one object for both the write and the trace, e.g. resolve Code Quality
Testing
RecommendationNeeds Discussion — the design question in Infrastructure needs to be settled first. If the stale/live divergence reproduces as described, this trades a loud crash for a silent wrong answer on the precompile path, and the fix belongs in which object gets bound rather than in how the collision is classified. The Note: I reviewed statically and did not run |
[ghstack-poisoned]
|
Claude finished @bobrenjc93's task in 38m 21s —— View job Re-reviewed: the earlier stale-vs-live finding is fixed for Full reviewPR Review: #196896SummaryTwo changes to Infrastructure
module_source = self.import_source(module_name) # binds sys.modules[...] (live, after this PR)
fglobals_value = _import_module(module_name) # memoized -- possibly a different object
return VariableTracker.build(self, fglobals_value, module_source)
What remains rooted at the alias are attribute guards, and the scope they read is held by reference: So the alias is a single slot with two consumers that want different objects — the running trace wants live, a previously-loaded artifact wants the one its guards were seeded against — and this PR resolves that in favor of the trace without saying so. I think favoring the trace is the right call (the alternative reintroduces the first bug), but the comment and PR description should state the actual cost, and the AOT-artifact-breaks-at-call-time case deserves either a test or an explicit note that it is accepted.
Minor, same line: the Testing
RecommendationRequest Changes — Note: reviewed statically; no built |
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
…ard for and which share a line (#197001) **Problem.** The no-match report decides, entry by entry, whether its missing-global hint names "this `Module` instance's forward" or stays neutral ("the live scope this artifact was loaded against"), by comparing the dict `forward` resolves to against the dict each entry's guards hold. Nothing pinned that a caller-supplied `guard_globals=` dict stays neutral, or that in a report with two entries holding different dicts only the entry holding the resolved one is told which forward. **Fix.** Two tests pin exactly that: one where no entry holds the resolved dict (and defining the name in the supplied dict then serves the call), and one where exactly one of two does, checked in both orders with a single resolve asserted. No source change. **Summary.** Tests only, for the no-match report the report commit (#196823) raises, split out of it so that its review fits in one pass -- the pattern of #196824 and #196825, which pin the dispatch's last resort and a guarded global the loading process does not have from test-only commits. Split twice more for review budget: the five-test revision of this commit died at the review bot's 60-minute ceiling, so the two tests that pin WHEN the report resolves `forward` -- only for a SUPPLIED scope, and once -- moved up into `[aot_compile] Pin when the no-match report resolves forward` (#197301), and the three-entry test that pins which entries share a hint line moved up into `[aot_compile] Pin that the no-match report shares one hint line across entries worded alike`. What stays here is the pair that pins WHICH entry the hint names a `forward` for: one where no entry is, and one where exactly one of two is. Both pass at the parent, whose report they pin, fail below the report commit (#196896) where no report exists, and each fails under a targeted edit of `_no_match_report` that no other test in the file catches, measured by editing the report and running the whole file. Two tests of the previous revision are gone, one because the footer gate it fenced is already fenced by two other tests and one because it is folded into the three-entry test's entry `[1]` in the commit above. ## What the report does at this tree The report decides its hint per entry. An entry whose verbose parts name a whole missing global gets `_missing_global_hint(forward=...)`, with `forward` set when `resolved is not None and resolved is result._guard_globals`; `resolved` is what one `_resolve_guard_scope(self.model)` returned, run at most once, at the first hinted entry whose scope is SUPPLIED, and reused for every entry after it (when it runs, and that it runs once, is #197301's). ``` # the two wordings the tests tell apart For [i]: a guarded global is missing from the live scope this artifact was loaded against; define it there ... # neutral For [i]: ... this GlobalConfigModule instance's forward resolves to ... # named ``` ## Both fail below the report commit Both tests pass at the parent, whose report they pin, and fail below the report commit (at #196896, the commit under it), where the no-match fall-through `results[0](self.model, *args, **kwargs)` raises the function path's `GuardManager check failed` message. That message quotes the guard's `KeyError on G[...]` part and, for a whole missing global, appends the function path's hint sentence, so the `loaded against; define it there` substring the tests also look for is present there; what it lacks is the `[i]` entry prefix, the `For [i]:` hint line and the `Tried N` header, and with no report there is no resolve. Measured with that tree's `aot_compile.py` under this tree's test file: | test | failure below the report commit | | --- | --- | | `..._hint_stays_neutral_for_a_supplied_scope` | `"[0] KeyError on G['AOT_HERMETIC_WEIGHT']" not found` | | `..._names_forward_only_for_the_dict_it_resolves_to` | `Expected '_resolve_guard_scope' to be called once. Called 0 times` | The one that compiles in its own body calls `_hide_leaked_dynamo_globals()` on entry, as the capture-only `test_aot_compile_fn_missing_global_hint_names_the_tracing_scope` does; the other shares `_two_input_global_guard_artifact` with `test_no_match_message_hints_each_scope_a_mixed_model_failed_in` and the landed `test_aot_compile_module_missing_global_hint_names_the_resolved_module` and, like them, does not, its kept guards being rooted at `GLOBAL_POOLING_CONFIG` alone. ## `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` ```python scope: dict[str, object] = {"__builtins__": builtins} # never had AOT_HERMETIC_WEIGHT compiled = AOTCompiledModel.deserialize(HermeticModule(), data, guard_globals=scope) with self.assertRaises(RuntimeError) as ctx: compiled(x) message = str(ctx.exception) self.assertIn("[0] KeyError on G['AOT_HERMETIC_WEIGHT']", message) self.assertIn("For [0]: a guarded global is missing from the live scope this artifact was loaded against; define it there", message) self.assertNotIn("instance's forward", message) # the advice, followed: the guards hold the supplied dict, and defining the name there serves the call self.assertIs(compiled.compiled_results[0]._guard_globals, scope) scope["AOT_HERMETIC_WEIGHT"] = AOT_HERMETIC_WEIGHT self.assertEqual(compiled(x), x @ AOT_HERMETIC_WEIGHT) ``` It loads through `AOTCompiledModel.deserialize(..., guard_globals=...)` with a dict that never had the guarded name, so the guards hold a dict no `forward` resolves to, asserts the scope-neutral wording under its `For [0]:` prefix, and then the advice it gives: `compiled_results[0]._guard_globals is scope`, and defining the name in that dict serves the call -- with `AOT_HERMETIC_WEIGHT` defined in this module's dict, where the class's `forward` lives, the whole time. Reducing the compare to `resolved is not None` fails it with a report that names `this HermeticModule instance's forward`, and fails exactly two others: the landed #196818's `..._names_the_resolved_module`, whose second half loads with `guard_globals=dict(globals())` -- a copy of the module dict, taken while the module itself lacked the name, that is not the dict `forward` resolves to -- and asserts `loaded against; define it there`, and this commit's `names_forward_only_for_the_dict_it_resolves_to`, whose caller-supplied entry is then told which forward as well. #197048's `test_no_match_report_survives_a_forward_resolve_that_raises` reaches the neutral wording through `resolved is None`, and its `test_no_match_message_hint_covers_a_rebound_forward` through a resolve that IS the dict the guards hold, so both pass under that edit. What this test adds over `..._names_the_resolved_module` is the other way to the wording, a supplied dict that never had the name rather than a stale copy carrying the module's `__name__`, and the recovery: no other `AOTCompiledModel.deserialize(..., guard_globals=)` test defines a missing name in the supplied dict and asserts the call is served (`..._deserialize_takes_a_guard_globals_scope` supplies a copy that already carries its names, and `covers_a_rebound_forward` defines the name in the dict the load RESOLVED, not one the caller passed). ## `test_no_match_message_names_forward_only_for_the_dict_it_resolves_to` ```python by_forward = AOTCompiledModel.deserialize(GlobalConfigModule(), data) # resolves scope from model.forward: this module's dict by_caller = AOTCompiledModel.deserialize(GlobalConfigModule(), data, guard_globals=scope) # a dict that never had the name self.assertIs(by_forward.compiled_results[0]._guard_globals, globals()) self.assertIs(by_caller.compiled_results[0]._guard_globals, scope) del GLOBAL_POOLING_CONFIG pair = by_forward.compiled_results[:1] + by_caller.compiled_results[:1] cases = ((pair, [named, neutral]), (pair[::-1], [neutral, named])) # both orders for results, wording in cases: mixed = AOTCompiledModel(GlobalConfigModule(), results) with patch(target, wraps=_resolve_guard_scope) as resolves, self.assertRaises(RuntimeError) as ctx: mixed(x) resolves.assert_called_once_with(mixed.model) # one resolve, asked about the model the report is for hints = [line for line in message.splitlines() if line.startswith("For [")] self.assertEqual([line[:9] for line in hints], ["For [0]: ", "For [1]: "], message) for hint, want in zip(hints, wording): self.assertIn(want, hint) ``` This is the shape that tells a per-entry `forward` from one shared across the report. Two SUPPLIED results whose guards hold different dicts -- one from `deserialize(GlobalConfigModule(), data)`, which resolves the scope from `model.forward` and so holds this module's dict, the one `_resolve_guard_scope` returns; one from `deserialize(..., guard_globals=scope)` with a dict that never had the name -- go into one `AOTCompiledModel` by hand, as `hints_each_scope_a_mixed_model_failed_in` builds its CAPTURED + SUPPLIED pair, and are dispatched with `GLOBAL_POOLING_CONFIG` deleted, in both orders. Each order enters a fresh `patch(..., wraps=_resolve_guard_scope)`, so its count is that order's alone, and asserts `assert_called_once_with(mixed.model)` -- one resolve, asked about the model the report is for -- two `For [i]:` lines, and that the entry holding the resolved dict is the one told `this GlobalConfigModule instance's forward` while the other gets the live-scope wording. | edit to `_no_match_report` | fails | | --- | --- | | decide `forward` once, at the first hinted entry, and apply it to every entry | this test alone, on the second entry's wording (`'the live scope this artifact was loaded against; define it there' not found in "For [1]: ... this GlobalConfigModule instance's forward resolves to ..."`) | | resolve `_resolve_guard_scope(type(self.model)())` instead of `self.model` | this test on `expected call not found`, plus #197048's `covers_a_rebound_forward` and `survives_a_forward_resolve_that_raises` on wording | Nothing else in the file catches the first edit: `..._names_the_resolved_module`'s two entries share one dict in each half, and `hints_each_scope`'s SUPPLIED entry is its only one. The line count does not catch that edit, because the resolved dict carries a `__name__` and the supplied one does not, so the two hints stay two sentences either way; the wording does. The `_with(mixed.model)` is what pins which module is resolved: asking about a fresh instance resolves to the same dict here, so the wording cannot tell, and a fresh instance does not carry the `forward` the two #197048 tests rebind. ## Two tests of the previous revision are gone `test_no_match_message_advises_an_input_for_a_missing_global` and its `SelfModeBranchGlobalModule` fixture pinned the footer under a report whose every entry was hinted; the footer is unconditional, and returning before it when `sum(map(len, hinted.values())) == len(results)` fails two tests at this tree without it (both on `'Add a ModelInput' not found`): #196825's `test_aot_compile_module_absent_global_fails_guard` and #197048's `survives_a_forward_resolve_that_raises` (and, one commit up, #197301's `resolves_forward_only_for_a_supplied_scope`). Its other assertions -- that the `L['self'].mode` mismatch is absent from the first report and named by the second -- pinned the guard tree's install order and fail-count re-sort in guards.cpp, not the report. `test_missing_key_inside_a_present_global_is_not_a_missing_global` is folded into the three-entry test's entry `[1]`, which fences the same substring edit, and rides with it in the commit above. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_no_match_message_hint_stays_neutral_for_a_supplied_scope python test/dynamo/test_aot_compile.py -k test_no_match_message_names_forward_only_for_the_dict_it_resolves_to python test/dynamo/test_aot_compile.py ``` The whole file is green here and on the parent commit. ## FAQ > **FAQ: The review found that > `test_aot_compile_module_missing_global_hint_names_the_resolved_module`, in > the landed #196818, already fails under the edit that this commit's > `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` was once > described as the one test to catch. Why keep the test?** > > Because the coverage claim was wrong, and the test's other half is not pinned > anywhere else. Re-measured on the whole file with the compare reduced to > `resolved is not None`: the failures are `..._names_the_resolved_module` > (`'loaded against; define it there' not found`), this test, and this commit's > `names_forward_only_for_the_dict_it_resolves_to`; every other test passes. So > the identity compare is fenced at #196818 as well, and the message says so > instead of crediting this test alone. What this test alone covers is a > `guard_globals=` dict that never had the name -- > `..._names_the_resolved_module` reaches the same wording through > `dict(globals())`, a copy taken while the module itself lacked the name -- > and the recovery, defining the name in that dict and asserting the call is > served, which no other `AOTCompiledModel.deserialize(..., guard_globals=)` > test does. > **FAQ: The review found two of an earlier revision's five tests largely > redundant with the base, and two report branches -- where `tried_forward` is > set, and hint dedup keyed by text -- unpinned. What changed?** > > Both redundancies were measured and both tests are gone; both branches are > now pinned, one in the commit above and one in #197301. Gating the footer on > every entry being hinted, the edit > `test_no_match_message_advises_an_input_for_a_missing_global` fenced, fails > two tests at this tree without it -- #196825's `absent_global_fails_guard` > and #197048's `survives_a_forward_resolve_that_raises` -- so that test and > its fixture add no fence on the report, and its `L['self'].mode` assertions > pin guards.cpp's accessor order, not this function. Replacing the report's > whole-part predicate with a substring test, the edit > `test_missing_key_inside_a_present_global_is_not_a_missing_global` fenced > alone, and keying `hinted` by dict identity are both fenced by the > three-entry `shares_a_hint_line_across_entries_worded_alike` in the commit > above, so the fold loses no coverage and the module path still has its own > pin of the predicate. The `tried_forward` mark is pinned by #197301's > `resolves_forward_once_past_a_resolve_that_raises`. > **FAQ: Every new test passes at the parent commit. Where is the red-on-parent > evidence?** > > There is none by construction: this is a tests-only commit pinning the > report the parent already ships, so every test passes on the parent's tree. > The two measurements that stand in for it are above: each test fails under > the tree below the report commit (#196896), where no report exists, and each > fails under a targeted edit of `_no_match_report` that no other test in the > file catches -- the mutation table is what shows the pins are not vacuous. > **FAQ: The review listed `"; ".join(parts)` with more than one verbose code > part per entry as uncovered. Why is there no test for it here?** > > Because that join is #197134's (`Keep a no-match report entry to one line > that says what its guards answered`), whose > `test_no_match_report_keeps_an_entry_on_one_line_past_odd_separators` owns > the entry format; how many parts an entry quotes has no bearing on the hint, > which is what this commit pins. A multi-part entry test belongs next to that > one, in that PR. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: #197001 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220
…s entries worded alike (#197569) **Problem.** The no-match report from #196823 groups its missing-global hint by sentence, so two entries loaded against different caller dicts but worded alike share one `For [0, 2]:` line, and a nested-key `KeyError` stays off the hint; nothing in the file exercised a three-entry report, so none of that was pinned. **Fix.** Add `test_no_match_message_shares_a_hint_line_across_entries_worded_alike`, the report's only three-entry test, which pins the shared non-contiguous hint line, the nested-key exclusion, the single resolve of the model's own forward and the footer's placement. No source change. **Summary.** Tests only, for the no-match report the report commit (#196823) raises, split off the top of `[aot_compile] Pin which entries the no-match report's hint names forward for` (#197001) because that commit's five-test revision died at the review bot's 60-minute ceiling; the two tests that pin WHICH entry the hint names a `forward` for stay there, the two that pin WHEN the report resolves `forward` moved into #197301, and this one -- the report's only three-entry test, which reads the hint LINES rather than any one entry's wording -- comes here. It loads three SUPPLIED results from three `deserialize(GlobalConfigModule(), data, guard_globals=...)` calls, each holding a caller dict of its own, where `[0]` and `[2]` lack `GLOBAL_POOLING_CONFIG` and `[1]` has it bound to `{}` so its guard fails on the KEY. It pins four things at once: the hint lines are keyed by sentence and not by dict, so `[0]` and `[2]` share one non-contiguous `For [0, 2]:` line; `[1]`'s nested-key `KeyError on G['GLOBAL_POOLING_CONFIG']['pooling']` is the ordinary mismatch the whole-part match keeps off the hint; the report's one resolve is `assert_called_once_with(mixed.model)` on an `_unresolvable_forward_module()`, whose forward is a partial `get_traced_fn` refuses, so it returns `(None, reason)` without raising and no entry is told which forward; and the footer follows a report whose hinted list is non-contiguous. It passes at the parent, whose report it pins, and fails below the report commit (at #196896), where the no-match fall-through raises the function path's `GuardManager check failed` message with no `[i]` entry prefix, no `For [i]:` line and no `Tried N` header, on `Expected '_resolve_guard_scope' to be called once. Called 0 times`. Two targeted edits of `_no_match_report` that no other test in the file catches -- keying `hinted` by `(id(result._guard_globals), hint)`, and replacing `_names_a_missing_global` with a `"KeyError on G[" in part` substring test -- each fail this test alone, which is what shows the pin is not vacuous. ## Where this sits in the stack Tests only, for the no-match report the report commit (#196823) raises, split off the top of `[aot_compile] Pin which entries the no-match report's hint names forward for` (#197001) because that commit's five-test revision died at the review bot's 60-minute ceiling. The two tests that pin WHICH entry the hint names a `forward` for stay there, the two that pin WHEN the report resolves `forward` moved into #197301, and this one -- the report's only three-entry test, which reads the hint LINES rather than any one entry's wording -- comes here. ## The fixture and the report it pins ```python x = torch.randn(4, 8) data = self._two_input_global_guard_artifact(x) absent = {"__builtins__": builtins} # no GLOBAL_POOLING_CONFIG keyless = {**absent, "GLOBAL_POOLING_CONFIG": {}} # the global, without the key its guard reads loads = [AOTCompiledModel.deserialize(GlobalConfigModule(), data, guard_globals=s) for s in (absent, keyless, dict(absent))] # three SUPPLIED results, three distinct dicts results = [loaded.compiled_results[0] for loaded in loads] assert [r._guard_scope for r in results] == [_GuardScope.SUPPLIED] * 3 assert len({id(r._guard_globals) for r in results}) == 3 mixed = AOTCompiledModel(self._unresolvable_forward_module(), results) with patch("torch._dynamo.aot_compile._resolve_guard_scope", wraps=_resolve_guard_scope) as resolves: with self.assertRaises(RuntimeError) as ctx: mixed(x) resolves.assert_called_once_with(mixed.model) ``` The report the test asserts, line by line: ``` No AOT compiled graph matched this call. Tried 3 compiled input(s): [0] KeyError on G['GLOBAL_POOLING_CONFIG'] [1] KeyError on G['GLOBAL_POOLING_CONFIG']['pooling'] [2] KeyError on G['GLOBAL_POOLING_CONFIG'] For [0, 2]: a guarded global is missing from the live scope this artifact was loaded against; define it there ... Add a ModelInput ... ``` `test_no_match_message_shares_a_hint_line_across_entries_worded_alike` is the report's first three-entry test (`Tried 3` appears nowhere else in the file). The three entry lines are asserted exactly, `len(hints) == 1`, the one hint starts with `For [0, 2]:` and does not contain `instance's forward`, and `Add a ModelInput` is the last line. It shares `_two_input_global_guard_artifact` with `test_no_match_message_hints_each_scope_a_mixed_model_failed_in` and the landed `test_aot_compile_module_missing_global_hint_names_the_resolved_module` and, like them, does not call `_hide_leaked_dynamo_globals()`, its kept guards being rooted at `GLOBAL_POOLING_CONFIG` alone. ## The four things it pins **First, hint lines are keyed by sentence, not by dict.** `[0]` and `[2]` carry no `__name__`, so their neutral sentences are identical and they share one non-contiguous `For [0, 2]:` line. Keying `hinted` by `(id(result._guard_globals), hint)` instead fails it on the line count (`Expected 1 but got 2`) and nothing else in the file: `..._names_the_resolved_module`'s `For [0, 1]` entries share one dict object. The merge is the intended reading: a per-dict line would print the same sentence twice, and the sentence names no dict, so the reader could not tell the two lines apart; two entries that give one instruction get one line. **Second, the nested-key mismatch stays off the hint.** `[1]` is the nested-key mismatch the whole-part match keeps off the hint: replacing the report's `_names_a_missing_global` with a `"KeyError on G[" in part` substring test fails it on `For [0, 1, 2]:` and nothing else in the file, the fence the dropped `test_missing_key_inside_a_present_global_is_not_a_missing_global` carried (see the FAQ); the predicate itself is pinned on the function path by `test_aot_compile_fn_missing_nested_key_gets_no_missing_global_hint`. **Third, the report resolves the model's own forward, once.** The model is `_unresolvable_forward_module()`, whose forward is a partial `get_traced_fn` refuses, so the report's one resolve -- `assert_called_once_with(mixed.model)` -- returns `(None, reason)` without raising and no entry is told which forward; the fixture's three other uses pass no `guard_globals=`, so their results are RECONSTRUCTED and never reach the resolve. The `_with(mixed.model)` is what pins which model the report asks about: resolving `type(self.model)()` instead fails this test on `expected call not found`, along with #197048's `covers_a_rebound_forward` and `survives_a_forward_resolve_that_raises` and #197001's `names_forward_only_for_the_dict_it_resolves_to`. **Fourth, the footer follows a report whose hinted list is non-contiguous.** ## Where it is red It passes at the parent, whose report it pins, and fails below the report commit (at #196896, the commit under it), where the no-match fall-through `results[0](self.model, *args, **kwargs)` raises the function path's `GuardManager check failed` message: that message carries the missing-global hint sentence the test also looks for, but no `[i]` entry prefix, no `For [i]:` line and no `Tried N` header, and with no report there is no resolve. Measured with that tree's `aot_compile.py` under this tree's test file, it fails on `Expected '_resolve_guard_scope' to be called once. Called 0 times`. | mutation of `_no_match_report` | fails on | other tests in the file affected | | --- | --- | --- | | key `hinted` by `(id(result._guard_globals), hint)` | `Expected 1 but got 2` hint lines | none | | `_names_a_missing_global` -> `"KeyError on G[" in part` | `For [0, 1, 2]:` | none | | resolve `type(self.model)()` instead of `self.model` | `expected call not found` | #197048's `covers_a_rebound_forward` and `survives_a_forward_resolve_that_raises`, #197001's `names_forward_only_for_the_dict_it_resolves_to` | | tree below the report commit (#196896) | `Expected '_resolve_guard_scope' to be called once. Called 0 times` | -- | Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_no_match_message_shares_a_hint_line_across_entries_worded_alike python test/dynamo/test_aot_compile.py ``` The whole file is green here and on the parent commit. ## FAQ > **FAQ: The report's comment on `hinted` says entries that share a scope > share a sentence, but the dict is keyed by hint text, so two entries holding > different dicts with identical wording collapse into one `For [0, 2]:` line. > Is that intended, and why pin it rather than change it?** > > It is intended, and this commit changes no code. The hint sentence is the > whole of what the reader gets: it names a scope only when the dict carries a > `__name__` (`here vars(mod)`), and two caller-supplied dicts without one > yield the identical sentence, so a per-dict line would print that sentence > twice with nothing to tell the two lines apart. Two entries whose advice > reads the same get one line; two entries whose advice differs -- a resolved > module dict next to a supplied one, a CAPTURED entry next to a SUPPLIED one > -- keep their own, which #197001's > `names_forward_only_for_the_dict_it_resolves_to` and > `hints_each_scope_a_mixed_model_failed_in` pin. The comment's "share a > scope" is the common case of sharing a sentence, and belongs to #197149. > **FAQ: An earlier revision had a separate > `test_missing_key_inside_a_present_global_is_not_a_missing_global`. Where did > it go?** > > Into this test's entry `[1]`, which fences the same edit: replacing the > whole-part predicate with a substring test fails this test alone in the whole > file, so the fold loses no coverage, and it buys the nested-key mismatch a > place next to two whole-global ones in one report, where the point is that > the hint skips it while the entry line still quotes it. The module path also > keeps its own pin of the predicate on the function side. > **FAQ: The test passes at the parent commit. Where is the red-on-parent > evidence?** > > There is none by construction: this is a tests-only commit pinning the report > the parent already ships, so it passes on the parent's tree. The two > measurements that stand in for it are above: it fails under the tree below the > report commit (#196896), where no report exists, and it fails under two > targeted edits of `_no_match_report` that no other test in the file catches -- > the mutations are what show the pin is not vacuous. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: #197569 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220, #197001
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
|
Re-reviewed against the current head 1. > I wrote that "the base already accepts a stale module whose Already addressed at 2. > Owned by #197256: that commit is exactly the conditional write you offered as the 3. > The description attributes to this commit five things that are in its base, and its Test Plan names no test that this commit adds except one. [...] Open: still true at 4. > No test has the memo and the live entry differ, so the arm the first finding is about is uncovered. [...] Already addressed at 5. > The Already addressed at 6. > Already addressed at 7. > Needs Discussion -- ... Two things need settling. [...] Owned by #197256 and open on the description: the first item, the accept path's |
|
Claude finished @bobrenjc93's task in 18m 57s —— View job Twenty-fourth pass: round twenty-three's finding is now pinned as intended behaviour — the new Full reviewPR Review: #196896Summary
Infrastructure
So on this exact arm the delta is not "loud The description's third paragraph discloses the direction and says #197046 closes it, and the test comment says the same — so this is not hidden. The problem is that the argument for shipping it is measured against a tree that no longer exists: the FAQ's "Pre-PR that sequence raised the The description attributes to this commit five things that are in its base. At Code Quality
Testing
Same test, cleanup asymmetry: its sibling
RecommendationNeeds Discussion — the Note: reviewed statically. No built torch extension in this checkout ( |
[ghstack-poisoned]
[ghstack-poisoned]
|
Re-reviewed against the current head 1. > Open, for the author to decide: whether this commit should stop writing the memo back over an accepted same-named binding (which is what #197256 directly above does conditionally, and #197046 removes by resolving the live entry), or keep the two-step shape with the FAQ re-measured against the current base, where the sequence graph-breaks rather than raising 2. > The description attributes to this commit five things that are in its base. [...] Queued for the author: the description edits are listed (drop the base-owned sections and behaviour changes, replace the 3. > Fixed in 4. > Fixed in 5. > Fixed in |
|
Claude finished @bobrenjc93's task in 27m 2s —— View job Twenty-fifth pass: the round-24 items are folded and I re-verified each. The new finding is that the acceptance arm sits above the Full reviewPR Review: #196896Summary
Infrastructure
That is a defensible call, but it is the exact case the comment at
One correction to a claim earlier rounds have made about this path, since it changes the severity: the alias lives in Reachability needs a handover plus a writer having pre-bound the live module plus the inlined-callee shape, so I am not asking for the acceptance to be narrowed. What I would want is one clause in the TestingNo test covers same-named acceptance on the That gap matters more than a missing case usually would, because it is the arm where the base's behaviour was a deliberate Code Quality
What I verified as fixed since round twenty-four
Infrastructure (description)The description still attributes to this commit five things present at base — the RecommendationApprove with comments — the predicate is correct, both of its arms plus the Note: reviewed statically. No built torch extension in this checkout ( |
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
Stack from ghstack (oldest at bottom):
import_sourcemints__import_<mangled>, resolves the module it names andwrites it into
self.output.global_scope, which is the traced frame's realglobals, a live module
__dict__. Nothing removes that binding, so it outlivesthe compile that minted it, and any later compile of any function in the same
module re-enters with the alias already bound. A writer other than this method
can have bound it, too:
CompilePackage.installbinds each recorded alias toimportlib.import_module(module_name)in the traced module's globals, andAOTCompiledFunction._seed_guard_scopedoes the same into a scope its owncomment describes as possibly a user module's live namespace.
The write's collision check was an identity test against a memoized object:
So after a
sys.moduleshandover, the moduleinstall()bound into the slotand the memoized object the next trace compares it against are two module
objects of the same name, and tracing died on a hard
AssertionErrorthatrestated the condition and named nothing:
Accept a same-name module and rebind; graph-break only on a real collision
A stale module object of the right name is not the collision the check exists
to catch, so accept it and rebind. The check is now
if alias in f_globals,and it graph-breaks only when the bound value is neither the object just
resolved nor a module whose own
__name__is this module name or the resolvedmodule's own
__name__:That still catches a non-module in the alias name and two module names
mangling onto one alias:
The resolved module's name counts because a
sys.moduleskey need not be themodule's own
__name__:os.pathis namedposixpath, and torch's own BCshim entries are all of that shape, so under such a key a stale object never
answers to the key itself:
Both
__name__reads go throughobject.__getattribute__(x, "__dict__"): amodule's PEP 562
__getattr__and a class-level__getattribute__(
importlib.util._LazyModule's imports the module on any attribute read,__dict__included) are user code that must not run inside a trace on the wayto a verdict. The offender is named by type, plus its
__name__when it hasone so the message names the offending module, and never repr'd, for the same
reason. The residual case is a graph break rather than an
AssertionErrorbecause the condition is the user's globals, and
IMPORT_NAMEalready reportsa non-module import result with
unimplemented.Which object the alias is rebound to here
This commit leaves
import_sourceresolving through the memoized_import_module, so the object it compares the bound alias against, andrebinds the alias to, is still the one first resolved in the process. The check
does not depend on which (a same-name module in the slot is accepted either
way, and each test here plants a fresh name, so first resolution and live entry
coincide), but the rebind's direction does: where a writer has bound the live
module and the memo is older, this commit's rebind takes the slot back to the
memoized module, and the graph, specialized on the object
IMPORT_NAMEpushed,is then guarded through a module the program no longer holds. That divergence
is the parent's whenever the memo and the live entry differ, with or without
anything in the slot, and the next commit in the stack (#197046) closes it by
resolving the live
sys.modulesentry; what it costs in the meantime ismeasured in the FAQ below, and the answer is not the one the naive reading
gives.
Two smaller moves that go with the check
The module-type check runs before the alias is written.
IMPORT_NAMEranit on
__import__'s result at push time, afterimport_sourcehad alreadybound the alias. It now runs before the
import_sourcecall, so on that path,the one caller resolving a name the traced bytecode chose, a non-module
sys.modulesentry is never written into the traced globals:The other eight callers (
nn_modules_globals_vt,codegen.py's three sites,torch_function.py,ctx_manager.py,misc.py,functions.py) reachimport_sourcewith no module-type test, so a non-module entry under one oftheir names, torch's own and stdlib names or a class's
__module__, is stillbound verbatim there, unchanged by this commit;
get_globals_source_and_valuealready has one, since
_registered_module_for_globalsreturns a name only fora
types.ModuleTypewhose__dict__is the frame's globals. The hoisted checkis
isinstance(value, types.ModuleType)alone:DummyModuleonly ever arriveson the replay arm, where
add_local_modrejected non-modules when the recordwas written, so that import goes.
The alias is recorded only once the binding is made. The check can now
fail recoverably, and the package entry is entered outside the trace that fails
(
code_contextwraps the whole compile, and a frame that skips or restartsleaves its entry in
_codes), so a record written before the check shipped inthe saved entry, and
install()then bound the alias over the very global thecheck refused to touch:
_install_globalwrites unconditionally;record_only_if_newgates only theuninstall bookkeeping. With the old
AssertionErrorthis was unreachable,since the compile died before anything was serialized.
Behaviour changes against the parent
Each is pinned by a test below.
non-module or a module of another name, is an
Unsupportedgraph break whereit was an
AssertionError. BecauseIMPORT_NAMEhas nobreak_graph_if_unsupported, theUnsupportedlands instep(): the frameis skipped outright unless an empty-stack checkpoint (two or more ops)
precedes the import, and compiled up to that checkpoint otherwise, with
either outcome cached on the code object and nothing guarding the alias, so
fixing the global afterwards does not retrace the frame until
torch._dynamo.reset()(
test_import_alias_taken_by_a_non_module_graph_breaks,test_import_alias_the_trace_refused_is_not_recorded_for_install).alias rebound where the parent raised
(
test_import_alias_accepts_a_stale_module_under_an_aliased_key,test_import_alias_check_does_not_run_a_module_getattribute).IMPORT_NAMEof a non-modulesys.modulesentry no longer writesthe alias before breaking
(
test_import_alias_is_not_bound_to_a_non_module_import).(
test_import_alias_the_trace_refused_is_not_recorded_for_install).graph_break_registry.jsongains theImport alias already boundentry, withone hint per case: the global of that name for a non-module or nameless module
in the slot, renaming a module for two names mangling onto one alias, and
calling
torch._dynamo.reset()after fixing the global, for the caching in (a).Test Plan:
Five cases, all of which fail on the parent -- four on the old
AssertionError,test_import_alias_is_not_bound_to_a_non_module_importonthe alias the parent wrote. One plants a
str, a module namedother.nameanda nameless module (with a PEP 562
__getattr__that raises) in the alias slotin turn and pins the graph break's wording for each, then, with a
CompileCounterand nofullgraph, thatframe_countstays 0 across therefused call and a second call after the global is removed, and goes to 1 with
the alias bound only after
torch._dynamo.reset(). One traces with aCompilePackagewhile astrholds the alias -- two ops before the import, sothe trace restarts and compiles up to that checkpoint rather than skipping --
saves, loads and installs, and pins that no entry recorded the alias and the
stris still there. One plants a module whose class raises on a__dict__read in both slots and traces through it. One plants two successive non-module
sys.modulesentries and pins that neither is bound. One pins that a stalemodule left under a key that is not its own
__name__is accepted rather thanraising, and that a module of some third name still graph-breaks.
The four cases that plant a module under a fixed name and trace through it
call
_import_module.cache_clear()infinally, next to thesys.modulespop: the memo outlives the entry, so on a same-process re-execution -- the
default
--reruns=2ofrun_test.py-- the second run'simport_sourcewould resolve the first run's module object and the
assertIsagainst thefreshly planted one would fail. Measured by running each of the five tests
twice in one
unittestprocess: without the calls, 5 failures, every one anassertIson a module of the right name that is not the one just planted;with them, 10 tests
OK.test_import_alias_is_not_bound_to_a_non_module_importneeds none, since the hoisted check graph-breaks before
import_sourcerunsand the memo never sees its name -- it passed both runs without one.
Each is load-bearing, measured on this tree by mutation. Restoring the
identity-only test errors
test_import_alias_accepts_a_stale_module_under_an_aliased_keyandtest_import_alias_check_does_not_run_a_module_getattributewithUnsupported: Import alias already bound; narrowing the accepted names back tothe
sys.moduleskey alone errors the first of those the same way. Reading thebound module's name with
getattr(bound, "__name__", None)errors thenameless-module subtest of
test_import_alias_taken_by_a_non_module_graph_breakswith
RuntimeError: module __getattr__ ran inside a trace for __name__, thePEP 562 hook the fixture installs; reading either module's
__dict__as anattribute errors
test_import_alias_check_does_not_run_a_module_getattributewith
module __getattribute__ ran inside a trace. Dropping thenamed {bound_name}half of the message fails theother.namesubtest and thealiased-key case on their
assertRaisesRegex. RaisingAssertionErrorinplace of
unimplementedfails five cases -- the three subtests, the aliased-keycase, the refused case -- on the exception type. Recording the alias above the
check fails the refused case on
assertNotIn(alias, entry.import_sources).Un-hoisting the module check fails
test_import_alias_is_not_bound_to_a_non_module_importon the alias it wrote.On the test side, one op instead of two before the refused import fails its
len(guarded_codes) == 1pin with 0, the frame having been skipped for wantof a checkpoint; two ops before the import in the skipped-frame case fail its
frame_count == 0pin with 1, and dropping itstorch._dynamo.reset()failsthe
frame_count == 1pin with 0. The whole file: 79 tests, OK (skipped=40,expected failures=1).
They live in
test_package.pyrather thantest_misc.pybecause the writerthat empirically reaches the collision path is
CompilePackage.install, andthat file already owns the
DiskDynamoStoresave/load/install idiom and therest of the
import_sourcescoverage.Authored with the assistance of Claude Code.
Co-Authored-By: Claude Opus 5 [email protected]
Co-Authored-By: Claude Fable 5.1 [email protected]
🤖 Generated with Claude Code