Skip to content

[dynamo] Replace a same-named import alias binding only when the resolved module is live - #197256

Closed
bobrenjc93 wants to merge 34 commits into
gh/bobrenjc93/1212/basefrom
gh/bobrenjc93/1212/head
Closed

bobrenjc93 wants to merge 34 commits into
gh/bobrenjc93/1212/basefrom
gh/bobrenjc93/1212/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Split from [dynamo] Rebind a stale module alias instead of failing the trace
(#196896) for the review budget, as the top of three: [dynamo] Graph-break instead of asserting when an import alias is already bound (#196896) turns
the alias collision into a graph break, #196896 directly below accepts a module
object of the right name in the slot and writes the resolved module over it,
and this commit decides which module stays: the resolved module replaces a
writer's same-named binding only when it is the live sys.modules entry.

Below this commit, import_source writes the module it resolved into the
alias slot whenever the check passes, and value is _import_module's memo,
the first object the process resolved under this name, functools.cached and
never invalidated. A writer that resolves the name itself --
CompilePackage.install binding a recorded alias to
importlib.import_module(module_name), or AOTCompiledFunction._seed_guard_scope
seeding a guard scope -- bound the live entry at the time it ran, and after a
sys.modules handover the memo and that binding are two module objects of the
same name, either of which can be the older one, depending on whether the
handover happened before or after the first trace of the name. When the
handover came first, install() bound the live module and the memo is the
older object; #196896 then puts the memo back over install()'s binding, and
the graph -- specialized on what IMPORT_NAME pushed, which is what
__import__ returned, the live entry -- is guarded through the alias on a
module the program no longer holds under that name, so a change to the live
module's attributes goes unseen by the guards. That is the direction the
review of #196896 called harmful, and it is what this commit removes.

Which object the slot holds afterwards now depends on whether the module
resolved here is the live one, decided where it is resolved, on each branch by
its own means. On the normal branch value is live when module_name in sys.modules and sys.modules[module_name] is value. On the torch_package
branch value is a lookup in _package_imported_modules, the importer
registry keyed by the module's own mangled __name__, not a memo: it is the
module the name resolves to now, live by construction, and a mangled name is
never a sys.modules key (install()'s importlib.import_module cannot bind
one: ModuleNotFoundError: No module named '<torch_package_0>'), so this
method is the only writer of such an alias in practice. The write is
f_globals[alias] = value when the slot is empty, already holds value, or
value is live; a writer's same-named module that is not value stays in the
slot otherwise. In the code that is two names read at the write: conflict = alias in f_globals and f_globals[alias] is not value gates the name check,
which is #196896's unchanged, and write_value = not conflict or live, set
once after it, is what the write tests, so the three outcomes -- an empty or
same-object slot written, a same-named conflict written only when the memo is
live, a name mismatch graph-broken -- read at the site.

Concretely: when a shim hands over to the real module after install() bound
the shim, the next trace rebinds the alias to the real module it resolves (the
memo, taken at that trace); when the memo is the shim and install() bound the
real module after the handover, the trace leaves install()'s binding alone.
test_import_alias_keeps_the_installed_live_module pins the second case and
the difference from #196896: with that commit's symbolic_convert.py under
this test file the alias is the memoized module after the trace, and the
assertIs against install()'s module fails; here the alias keeps the live
module, and setting that module's VALUE recompiles, pinned with a
CompileCounter going from 1 to 2. When neither is live -- memo, install()'s
module and live entry all distinct, a second handover having followed the
install -- the writer's module stays, since the memo would be no less stale,
and the guards then read that module while the graph holds the live one's
values: test_import_alias_keeps_the_installed_module_when_neither_is_live
pins that the alias still holds install()'s module after the trace, that the
compiled function keeps returning the live module's x * 9 after that
module's VALUE is set to 10 with no recompile -- a divergence from eager
pinned as one with assertNotEqual -- and that setting the installed module's
VALUE recompiles. That blindness is the memo's own: an empty slot has it
below these commits and here alike whenever the memo is not the live entry
(the alias then holds the memo and the graph the live module), and the
refusal of an occupied slot was no guard against it. On the
get_globals_source_and_value path that empty slot has a write side too: an
inlined STORE_GLOBAL replays through the alias onto the memo while the trace
read the live module, the one whose __dict__ is the frame's globals
(_registered_module_for_globals returns no other), and the comment at the
write says so alongside the guard reads.
test_import_alias_of_an_empty_slot_is_the_memo_even_when_stale pins that
empty-slot form as the accepted residual: the memo is taken with one module
live, the alias popped and the name handed to a second module, and the next
trace binds the memo into the empty slot -- the compiled function keeps
returning the live module's x + 7 after that module's VALUE is set to 8,
diverging from eager with frame_count still 1, and recompiles when the
memo's VALUE changes. It passes on the parent, which has the same write for
an empty slot; it fails on the mutant that binds the live entry (below), which
is the outcome of #197046 higher in this stack, and that commit rewrites the
pin into a recompile. Resolving the live entry for every caller, and what a
name that has since left sys.modules should resolve to, is that commit.

The record does not follow the write: an alias the check accepted but the
trace left alone -- a writer's live module in the slot, the memo older -- is
recorded for the CompilePackage entry all the same, because the graph's
guards read through the alias whoever bound it, and a process that loads the
package has no writer but install(); without the record it binds nothing
there and the loaded guards fail on KeyError on G['__import_<name>'].
test_import_alias_the_trace_left_alone_is_recorded_for_install builds that
round trip: the second function is traced under its own CompilePackage on
the skip arm, its entry is pinned to record the alias while the writer's
binding stays, and after a save the alias is deleted and the name handed to a
third module before the load, so install() binds a module distinct from both
the slot the trace left alone and the module its graph was built from. That
third module carries a VALUE of its own, 99 against the 7 the graph was
built from, and the loaded function serves x * 7 under fail_on_recompile,
diverging from eager: its EQUALS_MATCH on VALUE is rebuilt at load against
the installed module, as G['__import_<name>'].VALUE == 99, so it compares
that module against itself. That is what a module pickled by name gives any
loaded guard -- the artifact carries the value its graph baked and not the
module -- present below these commits and outside what the record decides
(first FAQ). The record's part is that the third module is behind the alias
at all, where the guard reads it live: setting its VALUE to 5 fails that
guard, and the test pins the RuntimeError by the guard's own text.

_import_module keeps its behaviour; its docstring now says what the memo is
-- the process's first resolution, never invalidated -- and where
import_source binds it -- into an empty slot regardless, over another
writer's same-named binding only when it is the live entry -- in place of an
import-cost claim that holds only for a name importlib has not yet seen.
nn_modules_globals_vt keeps building its VariableTracker from the memo
while its source is the alias, which can now hold a writer's same-named module
on the skip arm; the comment there says so, and the FAQ below says why the
value is not read back through the alias.

Behaviour changes against the parent, each pinned by a test below. (a) A
writer's same-named module in the slot stays when the resolved module is an
older memo, whether the writer's module is the live entry
(test_import_alias_keeps_the_installed_live_module,
test_import_alias_the_trace_left_alone_is_recorded_for_install) or a second
handover has since replaced it too
(test_import_alias_keeps_the_installed_module_when_neither_is_live); on the
parent the memo was written over it. (b) An alias accepted but left alone is
recorded for install
(test_import_alias_the_trace_left_alone_is_recorded_for_install; on the
parent every accepted alias was written, so the case did not arise). An empty
slot takes the resolved module as on the parent, live or not
(test_import_alias_of_an_empty_slot_is_the_memo_even_when_stale), and the
torch_package branch's replacement stays unconditional
(test_import_alias_accepts_a_stale_torch_package_module, from #196896, pins
it against the mutant below).

Order to review: import_source in torch/_dynamo/symbolic_convert.py
(live on each branch, conflict, the comment at the write and
write_value), then _import_module's docstring and the comment in
nn_modules_globals_vt, then the four tests in test/dynamo/test_package.py
in the order above.

Test Plan:

python test/dynamo/test_package.py -k test_import_alias
python test/dynamo/test_package.py

Four tests. Three are red on the parent's torch/_dynamo/symbolic_convert.py
under this commit's test file (Ran 13 tests, FAILED (failures=3), each on
the assertIs of the alias against install()'s module, the parent having
put the memo back; the nine instances of the two commits below pass), and one,
test_import_alias_of_an_empty_slot_is_the_memo_even_when_stale, passes on
the parent by design, pinning the empty-slot write this commit keeps; it fails
on the mutant that binds the live entry (below). One builds the memo-is-older
sequence end to end: a function is compiled with a CompilePackage and saved
while sys.modules holds a module with VALUE = 2, the entry is handed to a
second module with VALUE = 7, the package is loaded and install()ed so the
alias binds that second module, a second function in the same globals is
compiled through import of the name with a CompileCounter, and the alias
is pinned to still hold install()'s module; then the live module's VALUE is
set to 8 and the compiled function is pinned to agree with eager with
frame_count gone from 1 to 2, the recompile the guard through the live
module buys. One extends that sequence by a second handover, to a third module
with VALUE = 9, before the second function is compiled: the alias is pinned
to still hold install()'s module, the compiled result to be x * 9 and to
stay x * 9 after the live module's VALUE is set to 10 -- a divergence from
eager's x * 10, pinned as one with assertNotEqual -- with frame_count
still 1, and a change to the installed module's VALUE to recompile. One runs
the memo-is-older sequence with a CompilePackage on the second function too:
after install() binds the live module, the second function is traced under
its own package, its entry is pinned to record the alias with the writer's
module still in the slot, the package is saved, the alias deleted and the name
handed to a third module with VALUE = 99, and the second package is loaded
and install()ed: the alias is pinned to hold the third module, the loaded
function to serve x * 7 under fail_on_recompile -- the value its graph was
built from, diverging from eager's x * 99, pinned with assertNotEqual --
and a change of the third module's VALUE to fail the loaded guard, the
RuntimeError pinned by the guard's text G['__import_<name>'].VALUE == 99.
One takes the memo with one module live, pops the alias, resets, hands the
name to a second module with VALUE = 7 and compiles with a CompileCounter:
the alias is pinned to hold the memo, the result to be x + 7 and to stay
x + 7 after the live module's VALUE is set to 8 -- a divergence from eager
pinned with assertNotEqual, frame_count still 1 -- and a change to the
memo's VALUE to recompile and agree with eager again.

python test/dynamo/test_package.py -k test_import_alias_keeps_the_installed_live_module
python test/dynamo/test_package.py -k test_import_alias_keeps_the_installed_module_when_neither_is_live
python test/dynamo/test_package.py -k test_import_alias_the_trace_left_alone_is_recorded_for_install
python test/dynamo/test_package.py -k test_import_alias_of_an_empty_slot_is_the_memo_even_when_stale

Each is load-bearing, measured on this tree by mutation (-k test_import_alias, all thirteen instances, after each). Writing the resolved
module unconditionally (write_value = True, the parent's write) fails the
three installed-module cases on their assertIs of the alias against
install()'s module. Binding the live entry whenever the memo is not live
(value = sys.modules.get(module_name, value) with live = True, the outcome
of #197046) fails test_import_alias_keeps_the_installed_module_when_neither_is_live
and test_import_alias_of_an_empty_slot_is_the_memo_even_when_stale on their
assertIs of the alias against install()'s module and against the memo:
each accepted divergence is pinned as a divergence, so the commit that removes
it has to rewrite the pin. Recording the alias only when it is written (if self.package is not None and write_value:) errors
test_import_alias_the_trace_left_alone_is_recorded_for_install with
KeyError on the entry's import_sources. Declaring the torch_package
branch's resolution not live (live = False) errors
test_import_alias_accepts_a_stale_torch_package_module with
InternalTorchDynamoError: AttributeError: module '<torch_package_0>.torch_test_package_import_alias_packaged' has no attribute 'SCALE', the guard build reading SCALE off the planted module left in the
slot. No other test of the thirteen failed under any of these. All four tests
call _import_module.cache_clear() in finally, next to the sys.modules
pop, so that a same-process re-execution does not resolve the first run's
object; #196896's message carries the measurement over all thirteen instances
(26 runs OK, 10 of the 26 failing without the calls). The three
installed-module cases are covered by the write rule itself on a rerun (a
second run resolves run 1's object, which is not the live entry, so
install()'s binding stays), but clear it too, so no test leaves a dead object
in the memo. The whole file at this commit: 91 tests, OK (skipped=40, expected
failures=1).

They live in test_package.py rather than test_misc.py because the writer
that empirically reaches the collision path is CompilePackage.install, and
that file already owns the DiskDynamoStore save/load/install idiom and the
rest of the import_sources coverage.

lintrunner --take RUFF,PYFMT,GB_REGISTRY torch/_dynamo/symbolic_convert.py test/dynamo/test_package.py torch/_dynamo/graph_break_registry.json

FAQ: with the resolution reverted, the relaxation actively converts install's correct binding into a stale one, and the direction is the harmful one: install() binds the alias to the live module, the next trace finds the memoized object under value, accepts the same-named live one in the slot and overwrites it with the memo; the installed artifact's serialized guards then read the alias out of that same dict, MODULE_MATCH is unserializable so no identity guard catches it, and the artifact keeps serving a graph built against a module the program no longer holds. Pre-PR that sequence raised the AssertionError, which is loud and safe. The relaxation should not land on its own.

The overwrite is fixed here: a writer's same-named binding is replaced only when the module this method resolved is the live sys.modules entry, so in the sequence described the alias stays on the module install() bound, and test_import_alias_keeps_the_installed_live_module pins that, with the recompile-on-change it buys (third paragraph). The rest of the sequence was read off the code rather than run, and run it does not end that way on any tree. Measured with one script on the graph-break commit two below, on #196896 and on this commit (a module M resolved and saved against at VALUE = 2, sys.modules[M] handed to a second object with VALUE = 7, the CompilePackage loaded and install()ed so the alias binds that second object, a second function in the same globals traced through import M, then the installed artifact called): the artifact returns 3.0 where eager returns 8.0 on the graph-break commit (where the second trace is refused) and here (where the alias stays on the live module), under fail_on_recompile and under the default stance alike. What makes it silent is that a loaded EQUALS_MATCH guard's expected value is re-read through the guard scope when the artifact is installed (TORCH_LOGS=guards shows the saved G['__import_M'].VALUE == 2 rebuilt at install() as ... == 7), so against whichever module the alias holds at install time the guard is trivially true. That is a property of how loaded guards are built, present below all three commits, untouched by them, and the same whether the trace of the other function died (the graph-break commit) or completed (here). #196896, which writes the memo over install()'s binding, is the one tree of the three on which that artifact fails its guard instead -- RuntimeError: Detected recompile under fail_on_recompile, a recompile to eager's 8.0 under the default stance -- an accident of the wrong direction, the alias holding a module the program no longer imports by that name, not a merit, and gone here. The AssertionError the bottom commit removes was neither a guard on that artifact nor safe: it killed the trace of a different function, with no eager fallback, and left the artifact serving its stale 3.0.

FAQ: in the three-way case (memo, bound object and live entry all distinct) nothing is written, and the graph is then specialized on one module while its guards read another; the parent raised there. Either write the live entry when the names matched but neither is live, or say that the divergence is accepted.

Said, in the third paragraph and in the comment at the write rule, and pinned by test_import_alias_keeps_the_installed_module_when_neither_is_live: the installed module stays, the compiled function returns the live module's x * 9 and keeps returning it, with no recompile, after that module's VALUE is set to 10 -- diverging from eager's x * 10, which the test pins with assertNotEqual as the divergence accepted here -- while a change to the installed module recompiles. Not written, because the divergence is not one this case creates: it is the memo's, and an empty slot has it on the parent and here alike whenever the memo is not the live entry -- the alias then holds the memo and the graph the live module, blind in exactly the same way, which test_import_alias_of_an_empty_slot_is_the_memo_even_when_stale pins -- so the AssertionError on an occupied slot below these commits guarded nothing, and a write of the live entry in this one arm would resolve live for a slot a writer has touched and memoize for one nobody has. Resolving the live entry is #197046's change, for every caller and every slot, and its test_import_alias_survives_a_sys_modules_rebind is the empty-slot form of this test.

FAQ: import_source now reads sys.modules to decide the write; if the live entry is known here, why not bind it, which is what #197046 does?

Because resolving the live entry changes what every import_source caller binds, and needs the rest of #197046 to be correct: a name that has since left sys.modules or been blocked with None must keep resolving to something (its _import_source_cache), an entry whose __spec__._initializing is set must be waited for, and nn_modules_globals_vt stops agreeing with its source once the alias can hold a module other than torch.nn.modules.module. The read here decides one thing only, whether this method's own resolution may replace a module another writer bound under the same name, and it changes nothing for a slot that is empty or already holds the resolved object. With #197046's resolution in place the resolved object is the live entry by construction whenever there is one, so live is true in every reachable case and that commit can drop it.

FAQ: sys.modules.get(module_name, value) is value is trivially true whenever module_name is absent from sys.modules, because value is its own default; on the torch_package branch that is always, since mangled names are deliberately absent from sys.modules, so the write is unconditional there and cannot preserve an install() or _seed_guard_scope binding for a packaged module. Split the two tests and add a test for a mangled name whose slot holds a different same-named module.

Split: each branch now decides live where it resolves -- module_name in sys.modules and sys.modules[module_name] is value on the normal branch, True on the torch_package branch with the reason next to it -- and the slot check is alias not in f_globals or f_globals[alias] is value rather than a .get default, so neither test says two things. The write on the torch_package branch is meant to be unconditional, and now says so rather than falling out of a default: _package_imported_modules is keyed by the module's own mangled __name__ (package_importer.py sets module.__name__ = self._mangler.mangle(name) and stores the module under it, asserting the key unique), and the lookup is not memoized, so value is the module the name resolves to now -- the live one, in the only sense a packaged module has. There is no install() binding to preserve: a mangled name is not importable, importlib.import_module("<torch_package_0>.x") raises ModuleNotFoundError: No module named '<torch_package_0>', so install() and _seed_guard_scope cannot bind one, and a same-named different module in such a slot is hand-planted. test_import_alias_accepts_a_stale_torch_package_module plants one and pins the rebind, reaching the branch as a trace does: a function calling into a torch.package module is compiled, the inlined callee's global read roots at its own module through _registered_module_for_globals, and the alias lands in the outer frame's globals. Declaring that branch not live errors it with InternalTorchDynamoError: AttributeError: module '<torch_package_0>....' has no attribute 'SCALE', the guard build reading SCALE off the planted module.

FAQ: nn_modules_globals_vt can now build its VariableTracker from a different object than its own source points at, which the base made impossible: it takes import_source(module_name) as the source and _import_module(module_name) as the value, and on the skip arm the alias holds the writer's module while the VT wraps the memo. Read the value back from the alias slot, or say the divergence is accepted and why.

Accepted here, said in a comment at nn_modules_globals_vt, and repaired by #197135 higher in this stack, on the side the review's one-liner would not fix. Reaching it takes three things at once: sys.modules["torch.nn.modules.module"] rebound to another module object, a writer -- CompilePackage.install or _seed_guard_scope, both resolving with importlib.import_module -- binding the alias while that rebind is in effect, and a trace after it; absent the rebind both writers hand back the memo for a core torch module, since it is imported before any trace can run. Measured with that sequence built by hand (the alias assigned the shim as install() would, the shim carrying empty hook dicts): with no global hook registered the compile matches eager and its hook-dict guards read the shim's dicts, which is the TYPE_MATCH-only blindness to a later-registered global hook the parent has on every path; with a forward hook registered on the defining module, guard construction raises InternalTorchDynamoError: KeyError: 0 out of CLOSURE_MATCH on G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[0], resolved on the shim. Below the three commits the same sequence is the AssertionError the bottom one removes, and on #196896 the alias is written back to the memo, so nothing observable is lost here; on #197046 alone it is the same KeyError: 0, and #197135 is the fix: the source follows the value, rooting the guards at the torch package's alias walking .nn.modules.module once the alias holds another module. fglobals_value = f_globals[alias] goes the other way and is wrong: measured as a mutant of this tree, the trace then reads the shim's empty dicts, bypasses _call_impl, and the compiled function skips the hook eager runs (eq eager False, the hook fired once per eager call and never under compile), which is the value-side alternative #197135's message measures and rejects for the same reason -- _call_impl reads those dicts through its own __globals__, the defining module's, never through the alias.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Fable 5.1 [email protected]

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/197256

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

⏳ 4 Pending, 2 Unrelated Failures

As of commit 921b87d with merge base 51d4378 (image):

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 16, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 16, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

This was referenced Sep 16, 2026
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head 280f7f000ba7; the PR has been re-sliced twice since this
review, and most of it has landed in the meantime: the deleted empty-slot test is back, the two
loose exception assertions are tightened, the three-way test is split, and the site-list comment
is gone. What is left is description arithmetic and the stack-ordering item, which #197135 owns.

1. > Correction to my earlier review on this PR. I claimed the skip arm turns a previously-impossible AttributeError at guard-build time into a reachable hard error. [...]

Already addressed at 280f7f000ba7: the attribute case is now a test of its own,
test_import_alias_of_a_stale_memo_lacking_a_read_attribute_is_a_hard_error
(test_package.py:1479), and its comment attributes it where you put it - "The memo's own, not
the skip arm's: the parent has it for every empty slot, and an installed module left in the slot
is only a second object the guards may read." No action taken beyond the split, which is item 8
below.

2. > nn_modules_globals_vt is newly broken and stays broken for four commits. [...]

Owned by #197135: the divergence is real at 280f7f000ba7 - nn_modules_globals_vt
(symbolic_convert.py:2382-2390) still builds from the memo while its source is the alias, and
test_import_alias_nn_hook_guards_read_the_module_left_in_the_slot (test_package.py:1533)
pins the CLOSURE_MATCH KeyError on G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[handle.id].
#197046 does not repair it (it swaps the value to torch.nn.modules.module while the source
stays the alias, which by then binds the live shim); #197135 does, by re-rooting the source at
the torch alias walked to .nn.modules.module when the slot holds another module. The reason
it is not reordered below this commit is that the base tree hard-errors on the same sequence too

3. > symbolic_convert.py:2434 - live = module_name in sys.modules and sys.modules[module_name] is value. [...]

Already addressed at 280f7f000ba7, in the second form you offered: the key-only test now carries
its reason inline at symbolic_convert.py:2446-2448 - "Under the key alone, whatever the
module's own __name__: that entry is what __import__ hands IMPORT_NAME" - which is the
property the guards rooted at this alias have to track, so accepting value_name here would be
wrong rather than symmetric. #197046 replaces the computation with a sys.modules.get on the
same key, so the asymmetry does not outlive this commit either.

4. > symbolic_convert.py:2492 - the comment names three call sites ("codegen.py, reconstruct_type, call_apply") that will rot as reconstruction moves around. [...]

Already addressed at 280f7f000ba7: the comment at the write (symbolic_convert.py:2517-2522) names
no call site and keeps only the load-bearing half - "The guards this alias roots and the
bytecode reconstructed through it then read the module left in the slot rather than the one the
graph was built from."

5. > The empty-slot write this commit keeps is now unpinned. [...]

Already addressed at 280f7f000ba7: test_import_alias_of_an_empty_slot_is_the_memo_even_when_stale
is back at test_package.py:1429 and passes in -k import_alias (19 instances, OK). It is
load-bearing again by measurement: the "bind the live entry" mutant
(value = sys.modules.get(module_name, _import_module(module_name)), live = True) fails it
along with the three-way test and the stale-attribute test.

6. > The PR description no longer matches the tests. [...]

Open: still true, in the opposite direction, and description-only. Re-measured on 280f7f000ba7, the
description needs six tests rather than four (adding the split-out stale-attribute test and the
nn-hook test to the behaviour list and to the -k block), Ran 19 tests /
FAILED (failures=4) for the parent's write rather than 13/3, nineteen instances rather than
thirteen, 97 tests for the whole file rather than 91, three victims rather than two for the
live-entry mutant and four rather than three for the unconditional write, and "five of the six
tests" for the cache_clear() note. The description edits are queued for the author to apply on the PR, since amending the ghstack message does not move the body.

7. > test_import_alias_nn_hook_guards_read_the_module_left_in_the_slot:1484 - bare assertRaises(InternalTorchDynamoError) with no message. [...]

Already addressed at 280f7f000ba7: the nn-hook test asserts KeyError: \d+ and then matches the
torch._guards ERROR log against Name: "G['<alias>']._global_forward_hooks[{handle.id}]" with
Create Function: CLOSURE_MATCH (test_package.py:1579-1585), with the index taken from the
live handle.id rather than the literal 0, and the comment reworded to "the dict key is the
handle's id, a process-global counter" as you asked. The EXTRA assertion is tightened the same
way: AttributeError: module '<name>' has no attribute 'EXTRA' plus
Error while creating guard:\nName: "G['<alias>'].EXTRA" (:1518-1524).

8. > test_import_alias_keeps_the_installed_module_when_neither_is_live now pins two independent things. [...]

Already addressed at 280f7f000ba7: the hard error is its own test with its own fn3,
test_import_alias_of_a_stale_memo_lacking_a_read_attribute_is_a_hard_error
(test_package.py:1479), attributed to the memo and to the empty slot rather than to the skip
arm. ..._when_neither_is_live (:1198-1262) now pins only the skip decision, the accepted
divergence (assertNotEqual with frame_count 1) and the recompile on the installed module.

9. > test_import_alias_taken_at_codegen_skips_the_frame:1576 and test_import_alias_graph_break_is_cached_until_reset:1536 both exercise behaviour this commit does not change. [...]

Already addressed at 280f7f000ba7: both tests live below this commit now, and neither appears in
git diff <base> 280f7f000ba7 -- test/dynamo/test_package.py, which also contains no
record_runtime_overhead patch. This commit's test churn is one rename plus five new tests.

10. > Recommendation: Request Changes [...]

Already addressed at 280f7f000ba7 for two of the three blocking items - the empty-slot pin is
restored and both exception assertions are tightened - and the third is the description, for which the re-measured counts in item 6 are queued for the author. The nn_modules_globals_vt ordering stands
as designed, with #197135 as the repair and the base tree's own AssertionError on the same
sequence as the reason no intermediate tree regresses a working path.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 40m 32s —— View job


One factual correction that matters: the justification given for deferring the nn_modules_globals_vt repair to #197135 compares against pre-stack main, but this PR's actual parent (#196896) writes the memo over the shim and so compiles that sequence consistently — meaning this commit, not the base, is what turns a working path into a hard error; separately, import_source's docstring still claims an occupied slot is always a hard error, which this commit made untrue.

Full review

PR Review: #197256

Summary

import_source now replaces a writer's same-named binding in the alias slot only when the module it resolved is the live sys.modules entry. The write rule at symbolic_convert.py:2523 reads correctly and the churn from the two earlier rounds is resolved — the empty-slot pin is back at test_package.py:1429, the exception assertions are tightened (:1518-1525, :1579-1587), the three-way test is split, write_value is inlined, and the call-site list is gone from the comment. Four things remain, one of which is a correction to the author's own rebuttal.

Code Quality

  • The stack-ordering justification for nn_modules_globals_vt rests on the wrong baseline, and against the real parent this commit is a regression. The reply says the reorder is unnecessary because "the base tree hard-errors on the same sequence too - import_source there raises AssertionError with no eager fallback". That is true of pre-stack main (import_source there raises unconditionally on any mismatch), but not of origin/gh/bobrenjc93/1212/base, which already carries [dynamo] Rebind a stale module alias instead of failing the trace #196896's name-acceptance relaxation. On that tree the shim's __name__ is torch.nn.modules.module, so it is in accepted, the check passes, and the unconditional f_globals[alias] = value writes the memo over the shim — source and value agree, and the sequence compiles with no error at all. Verified by reading the parent's import_source directly: the name check (bound_name / accepted / if bound_name not in accepted:) is present, and the write below it is unconditional. Since ghstack lands each commit as its own commit in main, the tree between [dynamo] Rebind a stale module alias instead of failing the trace #196896 and [dynamo] Root the global nn.Module hook guards at the defining module when the alias binds another #197135 is a real point in history where torch.compile on an nn.Module raises InternalTorchDynamoError: KeyError on a path that worked one commit earlier — which is exactly the bisect hazard raised before. Either reorder [dynamo] Root the global nn.Module hook guards at the defining module when the alias binds another #197135 below this commit, or restate the justification against the parent rather than against main and say why the intermediate tree is acceptable. Fix this →

  • torch/_dynamo/symbolic_convert.py:2427-2431 — the docstring is now false. It says "A slot already holding something other than the resolved module is a hard error unless graph_break_ok says the caller can graph break there," which enumerates two outcomes; this commit adds a third, and it is the one the whole PR is about. When the bound object is a module whose __name__ is in accepted and live is False, the method neither raises nor graph-breaks: it returns GlobalSource(alias) naming a slot bound to an object that is not the value it resolved. Every caller reading this docstring is entitled to assume the returned source and the resolved module are the same object, and four of them (codegen.py:781, :792, :848, variables/misc.py:1311) rely on that for reconstruction. This is the method's stated contract and it needs one sentence for the skip arm. Fix this →

  • torch/_dynamo/symbolic_convert.py:262-266 — _import_module's docstring replaced the reason the @functools.cache is there ("importlib.import_module() seems to do some filesystem checking to validate the name so not caching this can be slow") with a description of the memo's staleness. The staleness is worth saying, but dropping the cost note removes the only record of why the decorator exists, and the next commit in this stack is the one that reaches for the live entry instead — precisely the reader who needs to know that bypassing the memo has a compile-time price. Keep both; it is one clause.

  • Five comments name positions in the stack rather than behaviour: test_package.py:1208 and :1489 ("the commit directly above binds the live entry"), :1436 ("the parent has this for every empty slot and this commit keeps it; the commit directly above..."), :1541 ("the state two commits above this one changes"). ghstack lands each of these as its own main commit, so once the stack is in, "the commit directly above" names a change that is already present in the tree the comment sits in, and the comment asserts the opposite of the code beside it. Name the behaviour or cite the PR number instead. Fix this →

Testing

  • test_import_alias_nn_hook_guards_read_the_module_left_in_the_slot:1571-1573 pins that the no-hook case agrees with eager, but not the thing that agreement is standing on. With the shim in the slot the hook-dict guards are built by reading the shim's four empty dicts, so a global hook registered after that compile is not guarded at all and the cached graph keeps skipping it — the silent half of the same defect, and the half that has no loud counterpart on the parent (where the memo was written back and the guards read the real module's dicts). The test registers its hook only after torch._dynamo.reset(), so it never exercises the compile-then-register order. Add that ordering and pin whatever the intended outcome is; as written the assertion at :1572 reads as "this case is fine". Fix this →

  • The PR description is still the stale one: "Four tests", Ran 13 tests, FAILED (failures=3), 91 file tests, and a -k block that omits two of the six. The re-measured figures in the reply (6 tests, 19 instances, 97 file tests) match what is on disk — I count 18 test_import_alias methods plus one parametrized ×2 = 19 instances. Since amending a ghstack message is a no-op, the body needs editing on the PR directly; for a stack this size the mutation table is the evidence for the write rule, so it should not land describing a different test set.

Recommendation

Request Changes

Narrow. The write rule is right and the earlier rounds converged. What blocks is the nn_modules_globals_vt ordering — whose stated justification is measured against main rather than against this PR's parent, where the sequence compiles cleanly, so the intermediate tree does regress a working path — plus the docstring at symbolic_convert.py:2427, which now states the opposite of what the method does on the arm this commit added.

| Branch: `gh/bobrenjc93/1212/head`

[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head 0f07da03d67f; the docstring, the _import_module cost note and the stack-position comments are folded, the description is queued for the author, and the nn_modules_globals_vt ordering is the author's call and is left open here.

1. > The stack-ordering justification for nn_modules_globals_vt rests on the wrong baseline, and against the real parent this commit is a regression. [...]

Open, for the author to decide: the point that the parent (#196896) compiles the shim sequence cleanly, so the intermediate tree regresses a working path until #197135 re-roots the guards, is taken; the options are to move #197135's re-rooting below or into this commit, or to keep the order with the FAQ re-measured against the parent. No code changed on this arm at 0f07da03d67f.

2. > torch/_dynamo/symbolic_convert.py:2427-2431 -- the docstring is now false. [...]

Fixed in 0f07da03d67f: the docstring's third outcome now ends "replaced by the resolved module only when that module is the live sys.modules entry".

3. > torch/_dynamo/symbolic_convert.py:262-266 -- _import_module's docstring replaced the reason the @functools.cache is there [...]

Fixed in 0f07da03d67f: the cost sentence is restored and the staleness sentence kept after it; the commit message's clause about the docstring follows.

4. > Five comments name positions in the stack rather than behaviour [...]

Fixed in 0f07da03d67f: the four cited comments name the behaviour and the PR (#197046 binds the live entry; #197135 re-roots the hook guards) instead of "the commit directly above" or "two commits above".

5. > test_import_alias_nn_hook_guards_read_the_module_left_in_the_slot:1571-1573 pins that the no-hook case agrees with eager, but not the thing that agreement is standing on. [...]

Open with item 1: a hook registered after the compile is the silent half of the same ordering question, so it is decided together with it rather than pinned here first.

6. > The PR description is still the stale one [...]

Queued for the author with the re-measured figures (six tests, nineteen instances, 97 file tests, the -k block); the body is hand-maintained, so it is not rewritten by script.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 36m 5s —— View job


The head commit 0f07da03d67f changed import_source to resolve the live sys.modules entry instead of the memo — that is #197046's change, not this PR's — which makes three of this PR's own tests fail on their assertIs, turns several of its comments false, and drops the live-entry resolution in without the _initializing guardrail the PR's own FAQ said it requires.

Full review

PR Review: #197256

Summary

The PR is titled and described as "replace a same-named import alias binding only when the resolved module is live", i.e. keep the memo as the resolved value and use sys.modules only to decide the write. At 0f07da03d67f the code no longer does that: symbolic_convert.py:2455-2458 now makes the live sys.modules entry the resolved value itself. That is the change the description repeatedly attributes to #197046 ("Resolving the live entry is #197046's change, for every caller and every slot"), and it arrived without the tests, comments, or description following.

Code Quality

  • symbolic_convert.py:2455-2458 implements [dynamo] Bind the import alias to the live sys.modules entry #197046, not this PR. Compare the previous head (git show 280f7f0:torch/_dynamo/symbolic_convert.py):

    value = _import_module(module_name)
    live = module_name in sys.modules and sys.modules[module_name] is value

    against 0f07da0:

    memo = _import_module(module_name)
    entry = sys.modules.get(module_name)
    live = entry is not None
    value = entry if live else memo

    This is the mutant the description's own measurement table names as a different commit's behaviour — "Binding the live entry whenever the memo is not live (value = sys.modules.get(module_name, value) with live = True, the outcome of [dynamo] Bind the import alias to the live sys.modules entry #197046)" — and predicts will fail two tests. It now fails three (below). Two consequences follow immediately:

    1. live is true whenever the key exists, so conflict and not live is reachable only for a warm memo plus a name since removed from sys.modules or blocked there with None. The rule the PR exists to introduce — "a writer's same-named module stays in the slot unless value is the live entry" — is therefore near-vacuous on the normal branch, and no test in the file reaches the skip arm. If the intent is the live-entry resolution, the write condition, the boolean, the title and the description all want rewriting around it; if the intent is the write rule, this hunk is the accidental one.
    2. The guardrails the FAQ said the live resolution needs are not here. The FAQ answers "why not bind it, which is what [dynamo] Bind the import alias to the live sys.modules entry #197046 does?" with "it needs the rest of [dynamo] Bind the import alias to the live sys.modules entry #197046 to be correct: ... an entry whose __spec__._initializing is set must be waited for". sys.modules.get() returns a partially-initialized module during a circular import, where importlib.import_module waits on the module lock (_bootstrap._find_and_load re-enters _find_and_load_unlocked when spec._initializing is set). The priming call on the line above does that waiting only when the memo is cold; on a warm memo the value is taken straight out of sys.modules with no _initializing check. Lower confidence on reachability, but it is exactly the hole the FAQ named. Fix this →
  • symbolic_convert.py:2434 and :2455 bind two different types to the same local name: the walrus at :2434 makes memo an Optional[GlobalSource], and :2455 reassigns it to a types.ModuleType. Independent of the type-checker's verdict, a reader hitting memo at :2455 has to re-derive that the early return at :2435 means the first binding is dead. Name the module imported or similar.

  • symbolic_convert.py:2427-2432 — the docstring's "replaced by the resolved module only when that module is the live sys.modules entry" reads as a meaningful restriction, but under :2455-2458 the resolved module is the live entry whenever there is one, so the clause is true by construction and tells a caller nothing. It also still omits the outcome the method actually has on the skip arm: a returned GlobalSource naming a slot that holds an object other than the resolved value, which the reconstruction callers (codegen.py:781, :792, :848, variables/misc.py:1311) rely on not happening.

  • nn_modules_globals_vt (symbolic_convert.py:2382-2388) now takes its value from the attribute torch.nn.modules.module — correct as the defining module, and a sys.modules rebind does not move the parent-package attribute (CPython sets it once in _find_and_load_unlocked; torch/nn/modules/__init__.py does not shadow module and there is no PEP 562 __getattr__ on the path) — but it does not close the value/source gap, it inverts it. The source is still import_source("torch.nn.modules.module"), and import_source now writes the live entry into that alias. So with a shim in sys.modules the VT wraps the real module while the alias holds the shim, and the hook-dict guards (variables/nn_module.py:1391-1397 → variables/misc.py:2023-2039, which reads the attribute off the VT's value but sources it at AttrSource(GlobalSource(alias), ...)) still resolve on the shim. Worse than before on one arm: for an empty slot the base bound the memo (the real module) and value and source agreed, whereas now the shim is bound and they diverge. The comment at :2383-2385 explains why the value is the defining module but not that the source no longer points at it.

  • Stale comments, all describing the previous head's resolution:

    • test_package.py:1145-1148 — "A later trace in the same globals finds the two disagreeing and must not put the memoized module back." Nothing disagrees now; the memo is never a write candidate. "The sibling below pins the memo written back" points at a test that now fails.
    • test_package.py:1349 — "The skip arm under a CompilePackage ... the trace leaves that binding alone." The skip arm is not taken; value is what install() bound, conflict is False, and the write is an identity rewrite.
    • test_package.py:1434-1441 — "An empty slot takes the memo without consulting the live entry"; it consults it first now.
    • test_package.py:1537-1544 — "builds its value from the memo" (it builds from the attribute) and "On the skip arm the alias holds a writer's same-named shim" (not the skip arm; conflict is False because the slot already holds the live shim). The setup comment at :1559 ("Compiled once first, so the memo holds the defining module") is now inert.
    • symbolic_convert.py:2527-2532 — "unless value is the live entry ... when neither is live it stays too, the memo being no less stale" describes a three-way case that :2455-2458 has removed.

Testing

Three tests fail at 0f07da0. Traced independently twice; python is not runnable in this sandbox, so these are static traces, and CI on this head has not reported yet.

  • test_import_alias_of_an_empty_slot_is_the_memo_even_when_stale:1467 — compile 1 primes the memo to old and binds it; the slot is deleted, sys.modules[name] = new. Compile 2: entry = new, live = True, value = new, empty slot so conflict = False → the slot is bound to new. assertIs(fn.__globals__[alias], old) fails. The three assertions the test exists for (:1470 == args[0] + 7, :1471 assertNotEqual, :1472 frame_count == 1) all flip too, since the guards now root at the module the graph was built from. This is precisely the mutant the description says this test is there to catch.

  • test_import_alias_of_a_stale_memo_lacking_a_read_attribute_is_a_hard_error:1522-1526 — same sequence, and new has EXTRA, so value = new, the slot takes new, the G[alias].EXTRA guard resolves, and no AttributeError is raised. assertRaisesRegex(InternalTorchDynamoError, ...) fails with "not raised"; :1528 and :1529 would fail after it.

  • test_import_alias_keeps_the_installed_module_when_neither_is_live:1250 — install() binds mid, then sys.modules[name] = new. The fn2 trace gets value = new, live = True; conflict is True but bound_name == value_name == name so the name check passes, and not conflict or live is True → the slot is rebound to new. assertIs(..., mid) fails, and :1252 / :1254 flip with it. The test's own comment already anticipates this as [dynamo] Bind the import alias to the live sys.modules entry #197046's behaviour ("PR [dynamo] Bind the import alias to the live sys.modules entry #197046 binds the live entry and turns it into a recompile").

    The remaining test_import_alias* tests still pass: keeps_the_installed_live_module (value == new == install()'s binding, so the rewrite is an identity), the_trace_left_alone_is_recorded_for_install (same, though its name and comment no longer describe what happens), accepts_a_stale_module_of_either_accepted_name (the value_name widening survives — a sys.modules entry can still carry a different __name__), of_a_dotted_name..., check_with_a_non_module_value_accepts_the_key_alone, and nn_hook_guards_read_the_module_left_in_the_slot (the slot is pre-bound to the shim, which is now also value, so guard-build state is byte-identical to the base).

  • The skip arm has no test. After :2455-2458 it is reachable only for a warm memo plus a name absent from or None-blocked in sys.modules — no test in the file builds that, so the one branch this PR adds is uncovered. If the live resolution stays, add a test that pops the key after the memo is warm; if it is reverted, the three tests above come back to life.

  • The PR description is still the pre-re-slice one — "Four tests", Ran 13 tests, FAILED (failures=3), 91 file tests, and a -k block omitting two of the six — and its mutation table now describes the tree as a mutant of itself. Since the description is the review artifact for a stack this size, it needs re-measuring against whatever resolution lands; amending the ghstack message is a no-op, so edit the body on the PR.

  • test_import_alias_nn_hook_guards_read_the_module_left_in_the_slot:1571-1573 (carried over from the last round, still open): it pins that the no-hook case agrees with eager but never exercises compile-then-register, which is the silent half — the hook-dict guards are built off the shim's empty dicts, so a global hook registered after that compile is unguarded and the cached graph keeps skipping it.

Recommendation

Request Changes

Blocking: symbolic_convert.py:2455-2458 is the live-entry resolution the description assigns to #197046, and against it three of this PR's four load-bearing tests fail on their assertIs. Decide which change this commit is — revert to the memo and keep the write rule, or keep the live resolution and rewrite the tests, comments, title and mutation table around it (plus the _initializing wait the FAQ says it needs) — and note that nn_modules_globals_vt diverges value from source either way, now including the empty-slot case the base got right.

| Branch: `gh/bobrenjc93/1212/head`

[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Confirmed, and fixed at head e386f8d1fba6: the tree you reviewed at 0f07da03d67f was a rebuild error on my side, not an intended change -- a cherry-pick chain rebuild applied a recorded conflict resolution that carried #197046's import_source resolution (memo/entry/live = entry is not None) into this position, which is why three of the tests this commit adds failed there, exactly as you traced. The current head has this commit's own code again: value = _import_module(module_name), live = module_name in sys.modules and sys.modules[module_name] is value, and the conditional write; the nineteen -k import_alias instances pass at this position and the whole file passes at the top of the stack. The round-before-last dispositions (docstring third outcome, _import_module cost note, the stack-position comments) are all in this head; the nn_modules_globals_vt ordering question remains the author's call, as noted there.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 21m 5s —— View job


Confirmed: e386f8d1fba6 has this commit's own resolution back (value = _import_module(...), key-only live, conditional write), and I re-traced all six new/renamed tests against it — they hold. Two new items: a comment at test_package.py:1149 still describes the pre-fix "memo written back" behaviour, and there is one direction in which the skip arm alone creates the guard-build hard error, which the stale-attribute test's attribution rules out and no test covers.

Full review

PR Review: #197256

Summary

The rebuild error is fixed. At e386f8d1fba6 symbolic_convert.py:2449-2452 resolves the memo and computes live from the sys.modules key, and the write at :2531 is if not conflict or live. I re-derived each of the six tests against this tree and each one's assertIs follows from the code as written; the items from the round before last (docstring third outcome, _import_module's cost note, the PR #197046/#197135 comment rewrites) are all in. Note I could not execute anything — this sandbox has no built torch and no .venv — so the traces below are static and CI on this head had not reported when I looked.

Code Quality

  • test/dynamo/test_package.py:1149 describes the behaviour this commit removes. test_import_alias_keeps_the_installed_live_module ends its comment with "The sibling below pins the memo written back and the change unseen." Nothing below writes the memo back: the sibling at :1198 keeps install()'s module (assertIs(..., mid) at :1250), and the empty-slot test at :1433 binds the memo into a slot that was empty, which is not a write-back over anything. Write-back over an occupied slot is precisely what this commit deletes, so the one sentence pointing forward from the headline test names the parent's rule. It reads as a leftover from the pre-rename pairing (the base's version of this comment said "the sibling above leaves the live module in the slot and flips these assertions"). Fix this →

  • Two relative-position phrasings survive the round that fixed the others: :1439-1440 ("The parent has this for every empty slot and this commit keeps it") and :1490-1491 ("the parent has it for every empty slot"). Milder than "the commit directly above" — a reader can still tell what is being contrasted — but after landing "the parent" names a main commit rather than the base of a stack, so the same rot applies.

  • symbolic_convert.py:2452 computes live for every new alias including the common case where the slot is empty and conflict is False, where it is never read. A sys.modules lookup, so the cost is noise; mentioned only because the two locals are read fourteen lines apart and the reader has to hold live across the whole check block. Moving the computation next to the write would put the rule and both its inputs in one place. Not worth churn if you prefer live computed where each branch resolves, which is the reason it is where it is.

Testing

  • One direction of the guard-build hard error is the skip arm's own, and it is both untested and explicitly disclaimed. test_import_alias_of_a_stale_memo_lacking_a_read_attribute_is_a_hard_error:1490-1492 says the hard error is "The memo's own, not the skip arm's: the parent has it for every empty slot, and an installed module left in the slot is only a second object the guards may read." That is right for the sequence the test builds and for the three-way test's EXTRA-free mid, but it is not universal. Take the three-way sequence with the attribute present on the memo and on the live entry and absent from install()'s module — old.EXTRA and new.EXTRA set, mid with VALUE only, and a traced read of EXTRA:

    • on the parent, f_globals[alias] = value writes old, the G[alias].EXTRA guard resolves on old, and the compile succeeds;
    • here, live is False (the live entry is new, the memo is old), so mid stays, and the guard build reads mid.EXTRA → AttributeError → InternalTorchDynamoError with no eager fallback (_compile_inner at convert_frame.py:2243, not soft-failed at :2434).

    So in this one direction the skip arm converts a working compile into a hard error, independent of nn_modules_globals_vt. It cannot arise in the two-way case — there the slot keeps the live module, which is the one IMPORT_NAME pushed, so every attribute the trace read is present — which is what makes the three-way arm the only place it lives. Narrow (two handovers with an install between them), but it is the same class of regression as the nn one and the comment currently rules it out. Either qualify the attribution or add the case; the existing three-way test is two setattrs and one fn away from it. Fix this →

  • nn_modules_globals_vt ordering (open, your call). Unchanged at this head and the analysis holds: symbolic_convert.py:2386-2390 sources at the alias and values at the memo, and with sys.modules["torch.nn.modules.module"] handed to a shim that a writer bound, live is False, the shim stays, and the CLOSURE_MATCH on _global_forward_hooks[handle.id] resolves against the shim's empty dict. The base of this PR writes the memo over that shim and compiles the same sequence cleanly, so the tree that lands between this commit and [dynamo] Root the global nn.Module hook guards at the defining module when the alias binds another #197135 is where a working path hard-errors. Reordering the re-rooting below this commit is the only option that leaves no such tree; restating the FAQ against the parent is the other, and the test at :1536 at least pins the state either way.

  • The silent half of the same defect is still unpinned (open). :1574-1576 asserts the no-hook compile agrees with eager, but the hook-dict guards were built off the shim's four empty dicts, so a global hook registered after that compile is unguarded and the cached graph keeps skipping it. The test registers its hook only after torch._dynamo.reset() at :1577, so compile-then-register is never exercised and the assertion at :1575 reads as "this arm is fine". Agreed it is decided with the ordering question rather than before it.

  • Description arithmetic (open). Still the pre-re-slice body: "Four tests", Ran 13 tests, FAILED (failures=3), 91 file tests, and a -k block naming four of the six. Your re-measured figures match the tree: I count 18 test_import_alias* methods with one @parametrized ×2 = 19 instances, and the behaviour list needs the split-out stale-attribute test and the nn hook test. The mutation table is the evidence for the write rule, so it should not land describing a different test set; since amending the ghstack message is a no-op, it needs editing on the PR body.

Recommendation

Request Changes — narrowly, and none of it is the write rule, which is right and is now correctly implemented on this head. The blocking items are the stale forward reference at test_package.py:1149, the skip-arm direction of the hard error that the attribution comment rules out, and the description. The nn_modules_globals_vt ordering and its silent half remain yours to decide.

| Branch: `gh/bobrenjc93/1212/head`

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head 5fd68cb3f63d; the two comment items are folded, the ordering question and the description stay with the author.

1. > test/dynamo/test_package.py:1149 describes the behaviour this commit removes. [...] Two relative-position phrasings survive [...]

Fixed in 5fd68cb3f63d: the sentence now says the sibling below keeps install()'s module when neither it nor the memo is the live entry, and both "the parent has this" phrasings read "every empty slot has this before and after this commit".

2. > One direction of the guard-build hard error is the skip arm's own, and it is both untested and explicitly disclaimed. [...] Either qualify the attribution or add the case [...]

Fixed in 5fd68cb3f63d by qualifying the attribution: the comment now says the skip arm adds one direction of the error -- an attribute the memo and the live entry have and the installed module lacks dies the same way where the parent's write-back compiled -- rather than ruling it out. No new case added, since the two-handovers-with-an-install-between shape is the three-way test's and the ordering question below decides how much of the skip arm survives.

3. > nn_modules_globals_vt ordering (open, your call). [...] > The silent half of the same defect is still unpinned (open). [...]

Open, for the author to decide, as before; unchanged at 5fd68cb3f63d.

4. > Description arithmetic (open). [...]

Queued for the author with the re-measured figures; the body is hand-maintained, so it is not rewritten by script.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 23m 37s —— View job


The write rule is correctly implemented again at 5fd68cb3f63d and the two comment items from the last round are folded, but the predicate the rule turns on (live, identity against sys.modules) is justified for IMPORT_NAME only, and for the eight other import_source callers — which use the returned source for bytecode reconstruction, not just guards — the skip arm newly lets generated bytecode read a different object than the trace resolved.

Full review

PR Review: #197256

Summary

import_source (symbolic_convert.py:2426-2536) now replaces a writer's same-named binding in the alias slot only when the module it resolved is the live sys.modules entry. The rebuild error is gone — :2449-2452 resolves the memo and computes live from the key, and :2531 is if not conflict or live — and I re-derived each of the six new/renamed tests against this tree; each one's assertIs follows from the code. Both items from the last round are in (test_package.py:1149-1150 now names what the sibling pins, :1492-1496 qualifies the attribution instead of ruling the skip-arm direction out). Nothing below is a re-raise of a resolved item. I could not execute anything — no built torch and no .venv in this sandbox — so the traces are static.

Code Quality

  • live is the right predicate for one caller out of nine, and the comment at :2525-2530 names only that one. The justification is that the live entry "is what IMPORT_NAME pushed and the graph is built from". True at IMPORT_NAME (:2594, __import__ returns the sys.modules entry). It is false for every other caller, because none of them resolves through sys.modules in the first place:

    • nn_modules_globals_vt (:2386-2390) values the VT at _import_module(module_name) — the memo, explicitly not the live entry on the arm this commit adds.
    • get_globals_source_and_value (:6553-6563) values at _registered_module_for_globals, the module whose __dict__ is the frame's globals, and builds AttrSource(module_source, name) for a STORE_GLOBAL replay.
    • variables/misc.py:1311, variables/torch_function.py:220, variables/ctx_manager.py:118 derive module_name from an already-resolved object's __module__; what matters is whether the slot holds the module that object came from, which live does not test.
    • codegen.py:781, :792, :848 (load_import_from, the shared path for ~40 call sites in side_effects.py / source.py), and variables/functions.py:3005 want the module they named.

    For all of these the skip arm can leave an object in the slot that the trace never resolved, and on the parent that was impossible (f_globals[alias] = value unconditional, so post-return f_globals[alias] is value always held). The consequence is wider than the guard read the comment mentions: GlobalSource.reconstruct (source.py:251-252) emits a live LOAD_GLOBAL and AttrSource.reconstruct (:318-320) chains LOAD_ATTR, so load_import_from codegens a read of the attribute off whatever object occupies the slot at runtime. No guard covers those: PyCodegen installs none, and the one MODULE_MATCH that exists (variables/builder.py:1931) is id_match_unchecked (guards.py:3122), whose expected value is read out of the live scope at build time. misc.py:1311 is tx.import_source(self.fn_cls.__module__) for an autograd.Function subclass (reachable for any user class per variables/builder.py:1475), so unlike the rest it needs no core-torch sys.modules rebind to reach. Either widen live to "the slot will hold what this resolution produced" for the callers whose value is not the sys.modules entry, or say in the comment that the rule is IMPORT_NAME's and that the other callers inherit it. Fix this →

  • symbolic_convert.py:2389 states an identity the same PR's docstring contradicts. The new comment ends "the value stays the memo, the module whose __globals__ _call_impl reads the hook dicts through". The memo is _import_module's @functools.cache entry, and this PR's own docstring at :262-266 says it is "the process's first resolution of the name ... after a sys.modules handover it is an older object than the live entry". Nothing calls _import_module("torch.nn.modules.module") during import torch — the only two call sites are :2390 and :2449, both on trace paths — so a process that swaps that sys.modules entry before its first nn.Module compile memoizes the shim, and the comment's appositive is then false. The PR's own test has to work around this: test_package.py:1562-1563 compiles once up front "so the memo holds the defining module". The clause is load-bearing (it is the stated reason not to read the value back through the alias), so it should say the memo is normally the defining module rather than that it is. Fix this →

  • symbolic_convert.py:2420-2425 — the method comment's claim "an inlined translator's miss finds f_globals[alias] is value" is now false on the skip arm: _import_source_memo is per-translator (:5602), so an inlined translator re-runs the body, recomputes conflict = True against the module the root left in the slot, and reaches the name check rather than the quiet path the comment describes. It does not raise (bound_name is in accepted, since that is how the slot survived), so the conclusion the comment draws — that graph_break_ok need not be in the key — still holds; only the stated reason has rotted.

Testing

  • No test covers the skip arm through a reconstruction caller. All six new/renamed tests reach import_source through IMPORT_NAME, the one caller whose value is the live entry, plus nn_modules_globals_vt at :1539. Nothing exercises the case in the first finding — the slot left holding a module that the emitted bytecode then reads an attribute off. load_import_from is the natural target since side_effects.py reaches it on ordinary replay paths. Given the first finding is about consequences the comment does not claim, a test is what would settle whether the arm is reachable there at all. Fix this →

  • nn_modules_globals_vt ordering (open, your call — unchanged). The analysis stands at this head: :2386-2390 sources at the alias and values at the memo, live is False with a writer-bound shim, the shim stays, and the CLOSURE_MATCH on _global_forward_hooks[handle.id] resolves against its empty dict. Confirmed the parent writes the memo over that shim unconditionally, so the same sequence compiles cleanly there and the tree between this commit and [dynamo] Root the global nn.Module hook guards at the defining module when the alias binds another #197135 is where it hard-errors. test_package.py:1539 pins the state either way.

  • The silent half is still unpinned (open, with the above). Now grounded: variables/nn_module.py:1380-1402 takes has_hooks from those four dict lengths and, when all are empty, rewrites the call target from _call_impl to forward, so with the shim in the slot the compiled code skips hooks outright. A global hook registered after that compile is unguarded, and the cached graph keeps skipping it while eager runs it — Module._call_impl reads those dicts through its own __globals__, the real module's. test_package.py:1574-1576 asserts the no-hook compile agrees with eager but resets before registering (:1580), so compile-then-register is never exercised and that assertion reads as "this arm is fine".

  • Description arithmetic (open). Still the pre-re-slice body: "Four tests", Ran 13 tests, FAILED (failures=3), 91 file tests, and a -k block naming four of the six. Your re-measured figures match the tree — 18 test_import_alias* methods with one @parametrized ×2 = 19 instances. The mutation table is the evidence for the write rule, so it should not land describing a different test set; amending the ghstack message is a no-op, so it needs editing on the PR body.

Recommendation

Request Changes — narrowly, and not against the write rule, which is right and correctly implemented on this head. Blocking: the live predicate is justified for IMPORT_NAME only while eight other callers inherit it, with reconstruction (not just guards) reading the slot and no test covering that path; and the nn_modules_globals_vt comment at :2389 states an identity this PR's own docstring and test contradict. The ordering question and its silent half remain yours.

| Branch: `gh/bobrenjc93/1212/head`

[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head 921b87dbd42c; the two comment items are folded, the skip-arm question joins the ordering question as the author's decision, and the description stays queued.

1. > live is the right predicate for one caller out of nine, and the comment at :2525-2530 names only that one. [...]

Open, for the author to decide, together with the ordering question below: whether the skip arm should apply to the reconstruction and tracing-phase callers at all, or only to IMPORT_NAME, given that a slot left holding a module the trace never resolved is then read by reconstructed bytecode and by the guards. No code changed on this arm at 921b87dbd42c; the consequence you trace is recorded here and in the FAQ list for the author.

2. > symbolic_convert.py:2389 states an identity the same PR's docstring contradicts. [...]

Fixed in 921b87dbd42c: the comment now says the value stays the memo, "which is the defining module unless the entry was swapped before its first resolution here".

3. > symbolic_convert.py:2420-2425 -- the method comment's claim "an inlined translator's miss finds f_globals[alias] is value" is now false on the skip arm [...]

Fixed below, in #197255, where that comment lives: the clause is cut; the sentence keeps the memo-hit and taken-slot halves.

4. > No test covers the skip arm through a reconstruction caller. [...]

Open with item 1: which callers the skip arm should cover decides what such a test pins, so it is written once that is settled.

5. > nn_modules_globals_vt ordering (open, your call -- unchanged). [...] > The silent half is still unpinned (open, with the above). [...] > Description arithmetic (open). [...]

Open, for the author, as before; the description figures are queued.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 20, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 54m 20s —— View job


Confirmed the two comment items from the last round are folded at 921b87dbd42c; the one new finding is that the skip arm reaches a value channel nobody has traced yet — a graph input rooted at the alias is captured into used_globals at trace time, and forward_callable spreads used_globals after the freshly-imported import_sources, so a precompile artifact's globals actively discard the correct live module in favour of the object the skip arm left in the slot, with TENSOR_MATCH (not ID_MATCH) as the only guard.

Full review

PR Review: #197256

Summary

import_source (symbolic_convert.py:2426-2535) replaces a writer's same-named binding in the alias slot only when the module it resolved is the live sys.modules entry. The write rule is correctly implemented at this head, and I verified both items from the last round are in: the nn_modules_globals_vt comment at :2387-2389 now hedges the memo/defining-module identity, and the false inlined translator's miss finds f_globals[alias] is value clause is gone from :2422-2425. I also independently confirmed the torch_package branch's live = True (:2444): _package_imported_modules is keyed by the mangled __name__ (package_importer.py:390-394) and package_importer.py never writes sys.modules, so there is no install() binding to preserve there. One new finding below; the rest is the open set you already itemized, stated briefly so it does not crowd it out. Nothing here is a re-raise of a resolved item. Static analysis only — no built torch and no .venv in this sandbox, and CI on this head had not reported when I looked.

Code Quality

  • The skip arm breaks a value-channel invariant the parent guaranteed, and the artifact path discards the live module to honour it. The comment at :2527-2529 names two readers of the slot (guards, reconstructed bytecode). There is a third, and it is not a runtime read of the slot but a trace-time capture of whatever object is in it:

    1. A tensor attribute of an imported module becomes a real graph input: IMPORT_NAME pushes PythonModuleVariable(value, source=GlobalSource(alias)) (:2630-2639), PythonModuleVariable.tp_getattro_impl chains AttrSource(self.source, name) (variables/misc.py:2038), install_free_tensors defaults to False (config.py:598) so wrap_tensor takes the graph-input arm, and compile_subgraph records graph_input_idx_to_local_source[idx] = arg.source (output_graph.py:3172).
    2. get_runtime_env walks exactly that mapping, resolves each source to its root global name via get_global_source_name (which recurses through ChainedSource, source.py:1329-1334), and snapshots used_globals[alias] = self.f_globals[alias] (convert_frame.py:1262-1266). That f_globals is the same dict object import_source writes into — tracer_output.f_globals is the root translator's globals (convert_frame.py:1089, output_graph.py:3704), which is also passed as global_scope (symbolic_convert.py:5740).
    3. forward_callable then builds the artifact's globals as {**import_sources, **self.used_globals, ...} (convert_frame.py:1134-1139), where import_sources is {alias: importlib.import_module(module_name)} (:1130-1133). used_globals is spread second, so the trace-time snapshot wins over the fresh import.

    On the parent the write was unconditional, so f_globals[alias] is value held on return and the snapshot was necessarily the module the graph was traced against. On the skip arm it is the writer's module instead, so the artifact reads its graph inputs off a third object — neither the traced module nor the live entry that forward_callable had already imported correctly and then overwrote. The guard does not catch it: the source is not a dict key and not a specialized nn module, so match_on_id_for_tensor is False (guards.py:1116-1126) and TENSOR_MATCH checks dtype/device/shape/strides rather than identity, and it is built against the live root-frame globals, i.e. against the same writer's module. Two same-shaped tensors therefore diverge numerically and silently. Serialization launders the in-process case — AOTCompilePickler.reducer_override reduces modules by __name__ (aot_compile.py:304-305), so a save/load re-resolves the name — which leaves the exposure on the non-serialized AOT path and on the plain torch.compile frame. Either extend the comment to name the used_globals capture (it is materially different from "reads the slot at runtime": the correct module is imported and then discarded), or treat it as part of the caller-scope decision in the next item. Fix this →

  • live is justified for IMPORT_NAME only (open, yours — restating the target, not re-arguing it). The finding above is the concrete form of it: the callers whose value is not the sys.modules entry — nn_modules_globals_vt (:2386-2390), get_globals_source_and_value (:6549-6579), codegen.py:781/792/848, variables/misc.py:1311, variables/torch_function.py:220, variables/ctx_manager.py:118, variables/functions.py:3005 — inherit a predicate that does not test the thing they need, which is whether the slot will hold what this resolution produced. Whichever way you decide it, the used_globals precedence is the sharpest case to decide against, since there the wrong object is frozen into an artifact rather than read live.

Testing

  • The value channel is untested, and the existing tests cannot reach it. All six new/renamed tests read integer attributes (VALUE, EXTRA), so nothing becomes a graph input and used_globals never sees the alias; the nn test reaches nn_modules_globals_vt but through guard construction. A test that puts a torch.Tensor on the module and reads it inside the compiled function would pin whether the skip arm's slot occupant reaches the graph's inputs, and whether an AOT-compiled callable built in the same process picks it up over the fresh import. This is the same open question as the reconstruction-caller test from the last round, with a concrete target. Fix this →

  • nn_modules_globals_vt ordering and its silent half (open, yours — unchanged). No new evidence this round. I did confirm the silent half's mechanism once more: variables/nn_module.py:1380-1398 derives has_hooks from the four global hook-dict lengths read through globals_vt, and when they are all empty :1400-1402 rewrites the call target from _call_impl to forward, so with the shim in the slot the compiled code skips hooks outright. test_package.py:1574-1576 asserts that arm agrees with eager and then resets at :1577 before registering, so compile-then-register is never exercised.

  • Description arithmetic (open). Unchanged: "Four tests", Ran 13 tests, FAILED (failures=3), 91 file tests, and a -k block naming four of six. Your re-measured figures match the tree (18 test_import_alias* methods, one @parametrized ×2 = 19 instances). The mutation table is the evidence for the write rule, so it should not land describing a different test set; amending the ghstack message is a no-op, so it needs editing on the PR body.

Recommendation

Request Changes — for the new finding only. The write rule is right and correctly implemented here, and the test hygiene of the six new tests checks out (all mutations restored in finally, the omitted _import_module.cache_clear() in the nn test is correct since the memo is warmed with the real module before the swap, and _codes[...]/two-saves-per-store are both precedented in the file). What blocks is the value channel: used_globals captures the slot occupant at trace time and overrides the correct fresh import in forward_callable, which the parent's unconditional write made impossible, and no test reaches it.

| Branch: `gh/bobrenjc93/1212/head`

@bobrenjc93 bobrenjc93 closed this Sep 20, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1212/head branch November 24, 2026 01:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant