Skip to content

[dynamo] Bind the import alias to the live sys.modules entry - #197046

Closed
bobrenjc93 wants to merge 51 commits into
gh/bobrenjc93/1191/basefrom
gh/bobrenjc93/1191/head
Closed

bobrenjc93 wants to merge 51 commits into
gh/bobrenjc93/1191/basefrom
gh/bobrenjc93/1191/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Split for review budget from [dynamo] Root the global nn.Module hook guards at the defining module when the alias binds another (#197135), the commit
directly above: this one changes what import_source binds; that one changes
where nn_modules_globals_vt roots its guards once the alias can bind a module
other than the one whose dicts it reads.

import_source mints __import_<mangled>, resolves the module it names and
writes it into self.output.global_scope, the traced frame's real globals.
That alias roots the guards for every attribute the trace reads off the module,
while the graph is specialized on the object IMPORT_NAME pushed, which is
whatever __import__ returned: live sys.modules. The value written was
_import_module(module_name), and _import_module was functools.cached for
the life of the process with nothing clearing it, so once a name had been
resolved anywhere in the process the helper kept handing back that first
object. After a sys.modules rebind -- a lazy-import shim handing over, a
mock.patch.dict(sys.modules, ...), a test fixture -- the two disagree: the
graph is built against the module the program actually uses and the guard
watches one nobody holds any more, so it is blind to every later change to the
live one and the compiled function keeps returning a value computed from the
abandoned module. The previous commit's collision check has no part in this: it
reproduces just as well with the alias absent from f_globals, where no check
runs at all. Its write condition -- a writer's same-named module replaced only
when the module resolved here was the live entry -- is dropped: the value bound
is that entry whenever sys.modules holds a module under the name, which is
the case the condition let through, and for a name gone from sys.modules or
blocked there with None it is what this process's traces last bound. There
the condition treated the two alike in one direction only: .get(module_name, value) returned the default for an absent name, so a writer's module was
replaced, and None for a blocked one, so it was kept. Now both replace it;
neither the writer's module nor the cached one is live, and the cached one is
the object the guards this alias roots were built against.
The previous commit's three-way test flips here and is renamed for what it
now asserts, test_import_alias_rebinds_the_installed_module_to_the_live_entry:
the alias binds the live entry, a change to the live module recompiles, and a
change to the installed one no longer does. Its empty-slot test flips the same
way and is renamed too,
test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache: an empty
slot binds the live entry rather than the module the process's earlier trace of
the name bound, a change to the live module recompiles, and a change to that
earlier module, which nothing guards, does not.

Read the live sys.modules entry, which is what __import__ handed
IMPORT_NAME, so the alias binds the same object the graph was specialized on.
It is read from sys.modules directly rather than through
importlib.import_module, because what that call costs for a present name
depends on the interpreter: on 3.12 _find_and_load
(importlib/_bootstrap.py:1349-1356) returns without touching a lock unless
the entry is missing or its __spec__._initializing is set, but 3.10's
(:1022-1034) has no such gate -- it enters _ModuleLockManager and calls
_lock_unlock_module for every name, each through _get_module_lock, which
brackets its body with the global import lock (:185, :211), all of it under
compile_lock. Measured with spies on _get_module_lock and
_imp.acquire_lock, resolving a present, initialized name through
import_module: 3.10.20, two module-lock and four global-import-lock
acquisitions and 5.5 us per call; 3.12.14, none and 388 ns. The sys.modules
read takes no lock on either and costs 244 ns and 159 ns, against 73 ns and
52 ns for the memo, once per name per translator (import_source is
@cache_method). The import machinery is entered in three cases only: a name
absent from sys.modules that no trace has resolved before (a first import, as
before); a name blocked with None that no trace has resolved before (which
raises ModuleNotFoundError, as before); and an entry whose
__spec__._initializing is set -- _load_unlocked (:911-950) sets it around
a first-time execution of the module body -- where import_module waits on the
module lock the way an import statement would, two lock acquisitions on both
versions. Measured with a scratch module whose body starts a thread that
compiles a __main__ function inlining one of its functions (the inlining
translator's _load_global -> get_globals_source_and_value ->
import_source(M)) and then sleeps 3 s, after a warm-up compile: the compile
finished 31 ms after the body ended here and 33 ms after on the parent, both
binding the module; with the _initializing test removed it finished 2921 ms
before the body ended and bound a module whose spec was still _initializing.
The wait itself is a two-thread timing scenario, so that measurement stands in
for it; the dispatch is pinned single-threaded by
test_import_alias_of_an_initializing_module_waits_on_its_import, which plants
an entry whose instance-dict __spec__ has _initializing set and, under a
spy on importlib.import_module, pins that the name is asked for and that the
alias binds what the call returned (with the lock free, the entry itself).

The entry's __spec__ is read out of its instance dict through
object.__getattribute__, the way the alias check below reads __name__, and
only for a types.ModuleType (sys.modules accepts any object; a non-module
entry has no spec and is served as is). An attribute read would run a PEP 562
__getattr__ or a class-level __getattribute__ inside the trace, and
importlib.util._LazyModule.__getattribute__ (importlib/util.py:172-221 on
3.12) executes the module body on any read, __spec__ included. _init_module_attrs
writes __spec__ into the dict (_bootstrap.py:778) before _load_unlocked
marks it _initializing and publishes the module, so the dict read sees the
same flag. The flag is read the same way, out of the spec's instance dict, and
only when the spec is an importlib.machinery.ModuleSpec: _load_unlocked
writes _initializing as a plain instance attribute (spec._initializing = True at :926, = False at :950) on the spec _find_spec returned, and
ModuleSpec declares no __slots__, no class-level default and no descriptor
for it, so for every real spec the dict read answers what getattr did --
None for one that never went through _load_unlocked (measured: a fresh
ModuleSpec's dict has no such key), else the flag. spec is whatever the
module body assigned to __spec__, so a plain getattr would run a
descriptor or a __getattr__ on an object outside Dynamo's control inside guard
construction, and a MagicMock in that slot answers it with a truthy child and
sends a fully-loaded module through import_module (measured: getattr(mock, "_initializing", False) is True; the dict read is None). The isinstance
gate rather than an is not None one is a choice, not a guarantee the import
system gives: _find_spec (_bootstrap.py:1240-1280) returns whatever a
sys.meta_path finder handed back, checking only is not None (:1263), and
_load_unlocked sets spec._initializing on that object unqualified, so a
duck-typed spec can carry the flag. Every finder in the stdlib and in this
repo returns a ModuleSpec -- torch.package's importer builds one at
package_importer.py:372, and the find_specs under test/ delegate to
importlib.util.find_spec or go through spec_from_loader -- and an object of
another type need not have a __dict__ to read: measured,
object.__getattribute__(5, "__dict__") raises AttributeError, which the
gate turns into "not initializing", as getattr(5, "_initializing", False)
was. The pair is deliberately narrower than the gate _find_and_load applies,
getattr(getattr(module, "__spec__", None), "_initializing", False)
(_bootstrap.py:1355-1356), in three ways: a module whose body has deleted
__spec__ from its dict, or a ModuleType subclass serving __spec__ from a
class-level __getattribute__ or a PEP 562 __getattr__, or a spec serving
the flag from a property, reads as not initializing here; so does a module
whose finder returned a spec of another type that _load_unlocked then
flagged. Each is served as is where an import statement would wait on it. That
is what not running user code inside the trace costs, and the comment at the
read says so, listing all three. Two things make the read
cheap to get right and worth getting right: __import__ itself forces a LazyLoader-installed module on both 3.10
and 3.12 (measured: __import__(name), import name and, on 3.12,
import_module(name) all leave the body run and the class swapped back to
module; only the dict read leaves it lazy), so a traced import never hands
import_source an unexecuted lazy module, and the parent's import_module
made the same getattr(module, "__spec__", None) on 3.11+ (_find_and_load,
:1356) on the first resolution of each name per process, none on 3.10. Here
no version reads an attribute off the module or its spec, and
test_import_alias_check_does_not_run_a_module_getattribute pins the
resolution as well as the check: its module class raises on any read made with
import_source on the stack, its spec's _initializing is a property that
raises the same way, and on the parent, on 3.12, the test errors with the
module's raise reached from _find_and_load.

The resolved object is remembered per name in _import_source_cache when it
is a module -- sys.modules accepts any object, and a non-module entry, which
the callers without a module check bind verbatim, is never written to the
cache, so its dict[str, types.ModuleType] annotation holds by construction --
and only once the alias check below has passed, alongside the package record
and output.import_sources, so a trace the check refuses with Import alias already bound remembers nothing: the cache is never cleared, and a write made
before the check would pin a module the process may later drop on behalf of a
trace that bound nothing. Each resolution overwrites the entry, so the cache
holds what import_source last bound under the name, not what the process
first resolved as the memo did;
test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache pins that
after its handover with the entry popped, and a setdefault write in place of
the assignment fails it there. Whether the name is one the cache can serve is
decided where import_source branches on it and carried to the write in a
local, cacheable: False in the torch_package arm, True in the
sys.modules arm. The torch_package arm's names resolve through
_package_imported_modules, a WeakValueDictionary
(package_importer.py:731) that holds a packaged module only while its
importer or the user does, and the cache is never cleared, so a cache entry
would pin a torch.package module the user has dropped for the rest of the
process; that is the hazard the arm's comment names, and the arm's names are
never read back from the cache in any case, the read being in the other arm. A
second
"torch_package" in module_name test at the write, a hundred lines below the
first, would have to be kept in step with it by hand; the local cannot drift.
test_import_alias_accepts_a_stale_torch_package_module, whose function
inlines a helper from a torch.package-imported module, pins it: the mangled
name is absent from the cache after the compile, and with the arm's flag
flipped the test fails there, the name found. A name whose sys.modules entry has since gone -- del sys.modules[...], a
mock.patch.dict(sys.modules) scope -- or been set to None, the import
system's blocked-module sentinel that makes any import of the name raise
ModuleNotFoundError, is served from the cache instead of going back through
the import machinery, which would execute the module body again inside the
trace and bind a second copy of a module the program still holds, or for
None raise out of guard construction. ModuleNotFoundError is not in
_compile's pass-through tuple, so that raise would surface as
InternalTorchDynamoError with no eager fallback; measured, testing liveness
by key presence, which holds for a None entry, does exactly that. The cache is
never cleared, not by torch._dynamo.reset() either, so a module the process
has dropped stays alive in it; the memoized _import_module retained modules
the same way, so this is not new retention. reset() promises a fresh process
and clears its other process-globals in one place, so a comment closing the
clear group there, set off by a blank line from the unrelated statement below
it, names this one and why it stays, rather than leaving the exception to the
declaration alone; a reset() that did clear it fails the removed-name test,
whose deleted and blocked compiles follow a reset() (measured: the deleted
case fails on the spy, 'torch.autograd.profiler' unexpectedly found in [...], the blocked case errors with InternalTorchDynamoError: ModuleNotFoundError: import of torch.autograd.profiler halted; None in sys.modules). Only names the traced bytecode
never imported can arrive absent or blocked: IMPORT_NAME's own __import__
has just put its name back or raised, get_globals_source_and_value resolves
only a module it has just found live under the frame's __name__, and the
other callers pass torch's own or stdlib names for codegen.
torch.autograd.profiler is such a name: codegen.py resolves it on every
compile under config.record_runtime_overhead (on by default) for the
runtime-overhead record in the compiled frame's prologue, and the only
function-scope import of it in torch/ (torch/profiler/_utils.py) is off the
compile path, so a trace with the entry deleted has no other reason to
re-import it. The removed-name test uses it for that reason: an earlier
functools fixture asserted that nothing in the process first-imports a
functools user during the compile, which held on Linux and failed on macOS
trunk CI, where the re-executed functools.py also left the alias on a copy.

_import_module is deleted. Its one remaining caller, nn_modules_globals_vt,
reads the four global hook dicts to decide whether a module call may bypass
_call_impl, and it has to read the dicts _call_impl itself reads through
its own __globals__: the defining module's, which no sys.modules rebind
moves. The plain attribute chain torch.nn.modules.module is that module for
the same reason a memo would be: _find_and_load_unlocked does
setattr(parent_module, child, module) once (_bootstrap.py:1339) and never
revisits it, and import torch binds the submodule unconditionally
(torch/nn/__init__.py:8 -> torch/nn/modules/__init__.py:1);
convert_frame.py:1372-1375 already reads the same four dicts through it. The
source stays the alias, as before. That leaves one case this commit does not
finish: with sys.modules["torch.nn.modules.module"] rebound to another
module, the alias now binds that module while the value is the defining one,
and a hook registered on the defining module installs a CLOSURE_MATCH on
G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[0],
which resolves on the other module and raises KeyError: 0 out of guard
construction as an InternalTorchDynamoError. Measured with a shim carrying
empty hook dicts and forwarding every other read to the defining module, in
both orders -- shim installed after a first compile in the process, and before
any: this commit raises in both. The parent is right in one order only: with
the name resolved before the rebind its memo holds the defining module and the
hook runs, but with the shim installed before the process's first compile the
memo holds the shim, the hook dicts read empty, the call bypasses _call_impl
and the compiled function skips the hook and returns a tensor eager does not,
with nothing raised. The commit above roots the source at the defining module
whenever the alias binds another, which makes both orders right, and pins it
with test_import_alias_rebind_keeps_the_global_nn_hooks_visible; in a
process that has not rebound sys.modules for torch's own module nothing
changes on this path, so the guard shape and the recorded import_sources are
as before (test_aot_compile.py pins
{"__import_torch_dot_nn_dot_modules_dot_module"} as that set in two places;
both pass here).

Which module object a compiled artifact was built against is pinned by its
guards, not by this write: no identity guard on the alias survives
serialization (MODULE_MATCH is in UNSUPPORTED_SERIALIZATION_GUARD_TYPES),
so a rebind that hands the slot a different object of the same name leaves a
loaded artifact passing its guards. A rebind therefore costs a recompile only
when the live module answers differently, i.e. when the artifact is stale --
and on a path that never recompiles, a loaded AOT artifact or
fail_on_recompile, that staleness is reported instead of served: with the
alias left on the abandoned module the same guards pass and the artifact
answers out of a module nobody holds.

Behaviour change against the parent, pinned below: the alias binds the live
sys.modules entry rather than the first object the process resolved, so a
program that rebinds a module between compiles recompiles where its guards used
to watch the abandoned object silently
(test_import_alias_binds_the_live_module,
test_import_alias_survives_a_sys_modules_rebind,
test_import_alias_rebind_makes_a_stale_artifact_visible), and so does one
whose alias slot is empty while _import_source_cache holds the module an
earlier trace bound, where the parent put that module into the slot
(test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache, which
then pops the entry and pins that the cache serves that live module, the last
one bound, and not the earlier one). Not a
change: a name removed from or blocked in sys.modules between two traces
still binds the module the program holds, as the memo did
(test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module, which
passes on the parent and pins this commit against the two ways live resolution
alone would break it); and an alias install() bound to the live entry, which
the trace then resolves too, is recorded for the package exactly as when the
parent's trace found its memo older and left the slot alone
(test_import_alias_the_trace_left_alone_is_recorded_for_install, which passes
on the parent). Also pinned: the resolution reads no attribute off the
module it resolves or off its spec, which the parent did on 3.11+ for the first
resolution of a name (test_import_alias_check_does_not_run_a_module_getattribute).

Test Plan:

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

Five cases join the previous commit's twelve (thirteen tests, its accepted-names
fixture being parametrized over two); five of the twelve are extended, one is
renamed, and its empty-slot case and its recorded-skip case are rewritten for
what this commit binds. One compiles a function importing a scratch module,
resets, hands the sys.modules entry to a second module object and compiles
again, pinning that the alias
follows the handover and that the guard then sees a mutation of the live
module. One saves a CompilePackage, loads and installs it -- install()
binds the alias to the live module -- then hands the module over once more
before tracing a fresh function in those same globals, and pins that the alias
follows and the installed artifact still serves under fail_on_recompile. One
hands the module over to one answering differently and pins that the rebound
alias makes a loaded artifact's staleness visible -- a guard miss under
fail_on_recompile, and the live answer once the default stance recompiles.
One deletes torch.autograd.profiler from sys.modules between two traces and
then blocks it with None, and pins under a spy on importlib.import_module
that neither trace asks for the name, the entry stays absent (assertNotIn)
or None (assertIsNone, the two arms checked separately so a trace that
re-added the name bound to None cannot pass the absent arm), and the alias
still holds the module the program holds; the alias is deleted before each of
the two compiles, so the binding checked afterwards is that compile's write and
not the warm-up's, and a compile that did not run cannot pass the block (every
other assertion in it holds with no compile); it is decorated with
record_runtime_overhead=True so its premise -- that codegen resolves the name
on every compile -- is pinned rather than inherited from the default. One
plants a module whose instance-dict __spec__ is a ModuleSpec with
_initializing = True, compiles a function importing it under a spy on
importlib.import_module, and pins that the spy was asked for the name and
that the alias binds the module; the lock is free, so the call returns at once
and the test pins the dispatch, not the wait. The extended one is the alias
check's _ImportAliasHookedModule test: its module class used to raise on a
__dict__ read anywhere, and now raises on any read made with
InstructionTranslatorBase.import_source on the Python stack, matched by
function name and by the frame's module (__import__ and
PythonModuleVariable read __spec__ and __name__ off a module by design,
so the stack is the discriminator), which covers the resolution's __spec__
read as well as the check's __name__ reads. The live module's __spec__ is a
ModuleSpec subclass whose _initializing is a property that raises under the
same frame walk and otherwise answers out of the instance dict, where the test
writes False the way _load_unlocked would (a property has no setter, so
through vars(spec)); __import__ reads the flag off a present module's spec
by design (measured: the property runs once under IMPORT_NAME's
__import__, from the importing frame, and answers False), so a resolution
that reads it with getattr raises out of guard construction and one that
reads the dict serves the entry without reaching import_module. With no read
left for a hook to observe, the frame walk's positive control is static: the
test asserts that InstructionTranslatorBase.import_source.__wrapped__ (the
cache_method wrapper keeps the function under __wrapped__) has the
co_name and __module__ the walk matches, so a renamed or inlined
import_source fails there rather than letting every read through. The other
two extended ones are the refused-alias tests:
test_import_alias_taken_by_a_non_module_graph_breaks pins, per case, that
neither the fullgraph refusal nor the skipped frame leaves the name in
_import_source_cache and that the compile which finally binds the alias
does, and test_import_alias_the_trace_refused_is_not_recorded_for_install
pins the name absent from the cache after the checkpointed refusal and again
after install(). The last two extended are the two tests that reach the cache
write with a value one of its guards refuses, each gaining one assertNotIn
on the cache, described with their mutants below. The previous commit's
empty-slot case, renamed
test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache, compiles
with one module live, pops the alias, resets, hands the name over to a second
module and compiles again under a CompileCounter: the alias binds the second
module, a change to it recompiles (equal to eager, frame_count 2), and a
change to the first, which _import_source_cache still holds, does nothing
(equal to eager, frame_count still 2); the previous commit pinned the
opposite there -- the first module bound, the change to the live one unseen and
the change to the first one recompiling. It then pins the cache's contents:
_import_source_cache[name] is the second module, and with the entry popped
and the alias deleted, import_source binds the second module, not the first.
That resolution is driven on a stub translator over fn's globals, the way
test_import_alias_check_with_a_non_module_value_accepts_the_key_alone drives
it, because fn's own import statement cannot run once the entry is gone
(measured: eager raises ModuleNotFoundError, and the compile graph-breaks
with Unsupported: Import failure and binds nothing); only a name the traced
bytecode never imports reaches the cache read from a compile, which is the
removed-name test's path, and that test sees one module object for its name.
Its recorded case,
test_import_alias_the_trace_left_alone_is_recorded_for_install, keeps its
body: install() bound the live module after a handover, a second function
under its own CompilePackage traces the name and finds the alias holding the
very entry it resolved, the record is made all the same, and a fresh process's
install() binds a third module and the loaded function serves under
fail_on_recompile; its header no longer says the memo is older, since there is
no memo, and both tests' finally pop the name from _import_source_cache as
the other eleven do (the previous commit's _import_module.cache_clear() names
the helper this commit deletes). The removed-name test mutates the one sys.modules key it is about and puts the
module back in finally, rather than snapshotting sys.modules with
mock.patch.dict, whose exit clears the dict and restores the snapshot, so a
module first imported inside the block -- and the two compiles inside it take
branches the warm-up compile did not -- would be dropped from sys.modules
for the rest of the process while live references to it survive, the
duplicate-module failure the functools fixture hit on macOS; measured after
the test, sys.modules["torch.autograd.profiler"] and
torch.autograd.profiler are both the module the test started with. Every
test_import_alias test whose scratch name gets cached pops it from
_import_source_cache in finally, alongside the alias and the entry --
thirteen at this commit: the pop only matters where a later compile runs with the
name absent or blocked, but one teardown shape keeps a test-minted module from
outliving its test either way. Four have nothing to pop:
test_import_alias_the_trace_refused_is_not_recorded_for_install, whose one
trace is refused before the write and which asserts the name absent instead;
test_import_alias_is_not_bound_to_a_non_module_import, whose entry
IMPORT_NAME rejects before import_source runs, and a non-module is never
cached in any case; test_import_alias_accepts_a_stale_torch_package_module,
whose name takes the torch_package arm, which never writes the cache, and
which asserts that instead; and the removed-name test, whose name is
torch.autograd.profiler and whose cached object is the process's own module,
which a pop would not free and the next compile re-caches.

The first three fail on the parent (measured with the parent's
symbolic_convert.py checked out under this test file, plus a stub
_import_source_cache = {} on it so the file imports; the parent's
import_source never reads it) on assertIs(fn.__globals__[alias], ...), the
alias holding the module of the earlier compile; the third also fails with that
assertion removed, on RuntimeError not raised, the stale artifact having been
served. So does the second variant of the previous commit's accepted-names
fixture, ..._stale_named_for_target, on the parent's source under this file:
the memo hands it the first variant's module, the first-resolution staleness
this commit removes, in an inherited test. The renamed test fails on the parent
on assertIs(fn.__globals__[alias], new), the alias holding install()'s
module, which is what its old name
promised. The empty-slot test fails on the parent the same way, on
assertIs(fn.__globals__[alias], new) after its second compile, the alias
holding the module the first compile bound, which is what its old name
promised; at this tree, with an empty slot made to take the cached module when
the cache has the name -- the parent's empty-slot write, as a mutant -- it is
the one failure among the eighteen test_import_alias tests, on that same
assertion. With the cache write made _import_source_cache.setdefault(module_name, value) -- a first-resolution memo one indirection further in -- it is again the
one failure among the eighteen, on assertIs(_import_source_cache[name], new)
after the handover, and with that assertion removed on assertIs(scope[alias], new) after the stub-translator resolution; every other test but the removed-name
one keeps its name live across its compiles, so the cache is write-only there,
and that one sees a single module object for its name. The recorded test passes
on the parent, whose skip arm made the record too, and is load-bearing here by
mutation: with the package record made
only when the write changes the binding (f_globals.get(alias) is not value),
it is the one failure, erroring with KeyError: '__import_torch_test_package_import_alias_recorded' on
pkg2._codes[fn2.__code__].import_sources[alias]. The extended test errors on the parent on 3.12 with
InternalTorchDynamoError: RuntimeError: module __getattribute__ read __spec__ inside a trace, the read made by _find_and_load (_bootstrap.py:1356)
under _import_module; with this commit's resolution written as a plain
getattr(value, "__spec__", None) it errors the same way from import_source
itself; with the flag read as getattr(spec, "_initializing", False) it errors
with InternalTorchDynamoError: RuntimeError: spec _initializing property ran inside a trace, raised from import_source (the initializing test, whose spec
is a plain ModuleSpec, passes under that mutant, so the probe is what pins
the read); and with import_source renamed to import_source_impl and the
old name kept as a class attribute it fails on 'import_source_impl' != 'import_source', where the same rename with that assertion removed passes it
with every read let through. The removed-name test passes on the
parent and is load-bearing here by mutation, measured at this tree: dropping
the cache and importing whenever the entry is absent fails its deleted case on
the spy ('torch.autograd.profiler' unexpectedly found in [...], the trace
having re-imported it) and errors its blocked case with
InternalTorchDynamoError: ModuleNotFoundError: import of torch.autograd.profiler halted; None in sys.modules; testing liveness by key
presence instead of by value binds the blocked case's None and the compiled
frame's runtime-overhead prologue errors on AttributeError: 'NoneType' object has no attribute '_is_profiler_enabled'; and with the reset() before each of
its compiles removed, so that no compile runs, its deleted case errors with
NameError: name '__import_torch_dot_autograd_dot_profiler' is not defined
from the compiled frame's prologue and its blocked case with KeyError on the
delete, where the same test without the delete passes, every assertion in its
block holding with no compile. The
initializing test passes on the parent too, whose cold memo calls
import_module for every first resolution, and pins this commit's dispatch:
with the _initializing test removed it fails on assertIn(name, asked), the
entry having been served without asking. The refused-alias tests' cache
assertions fail with the cache write moved back above the check, the previous
push's order, measured at this tree: 'torch_test_package_import_alias_taken' unexpectedly found in {...} on assertNotIn in each of the three cases, and
'torch_test_package_import_alias_refused' unexpectedly found in {...} in the
install test, four failures. The cache write's two guards are each pinned by
the one test that reaches the write with a value that guard refuses.
test_import_alias_is_not_bound_to_a_non_module_import cannot: IMPORT_NAME
is the one caller that hands import_source a name the traced code chose, and
it rejects a non-module first, and the callers without that check carry
torch's own names or a class's __module__ at reconstruction, where a
non-module in the slot fails on G[alias].<Name> regardless. So
test_import_alias_check_with_a_non_module_value_accepts_the_key_alone, which
drives import_source on a stub translator with a SimpleNamespace under the
key, asserts the key absent from _import_source_cache after the accepted
call: with the isinstance(value, types.ModuleType) conjunct dropped from the
write it fails there ('torch_test_package_import_alias_non_module_value' unexpectedly found in {...: namespace(VALUE=1)}), and without that assertion
the mutant passed all eighteen. The torch_package arm is covered by
test_import_alias_accepts_a_stale_torch_package_module here and
test_torch_package_working_with_trace in test_misc.py, both green at this
tree; the first asserts the mangled name absent from the cache after its
compile, and with the arm's cacheable flipped to True it fails there
('<torch_package_0>.torch_test_package_import_alias_packaged' unexpectedly found in {...}), where without that assertion the mutant passed all eighteen.
Neither mutant changes what a compile binds today -- one pins a dropped
torch.package module for the process, the other opens a path IMPORT_NAME
blocks -- so the annotation and the comments at the write are held by those
two assertions and by nothing else. The whole file:
96 tests, OK (skipped=40, expected failures=1); test_aot_compile.py whole:
294 tests, OK (skipped=6).

python test/dynamo/test_package.py -k test_import_alias_binds_the_live_module
python test/dynamo/test_package.py -k test_import_alias_survives_a_sys_modules_rebind
python test/dynamo/test_package.py -k test_import_alias_rebind_makes_a_stale_artifact_visible
python test/dynamo/test_package.py -k test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module
python test/dynamo/test_package.py -k test_import_alias_of_an_initializing_module_waits_on_its_import
python test/dynamo/test_package.py -k test_import_alias_check_does_not_run_a_module_getattribute
python test/dynamo/test_package.py -k test_import_alias_rebinds_the_installed_module_to_the_live_entry
python test/dynamo/test_package.py -k test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache
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_taken_by_a_non_module_graph_breaks -k test_import_alias_the_trace_refused_is_not_recorded_for_install
python test/dynamo/test_package.py -k test_import_alias_accepts_a_stale_torch_package_module
python test/dynamo/test_misc.py -k test_torch_package_working_with_trace
python test/dynamo/test_aot_compile.py
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_deserialize_unwraps_optimized_module -k test_aot_compile_module_deserialize_takes_a_guard_globals_scope
lintrunner --take RUFF,PYFMT,GB_REGISTRY torch/_dynamo/symbolic_convert.py torch/_dynamo/__init__.py test/dynamo/test_package.py
lintrunner --take PYREFLY torch/_dynamo/symbolic_convert.py torch/_dynamo/__init__.py

PYREFLY reports nothing in the files this commit touches; its findings are in
torch/_dynamo/guards.py and torch/_native/cutedsl/hw_caps.py, neither of
which this commit changes.

FAQ: spec = getattr(value, "__spec__", None) is a plain attribute read on an arbitrary sys.modules object inside guard construction under compile_lock, the exact read the alias check 15 lines below avoids through object.__getattribute__(bound, "__dict__"): importlib.util._LazyModule.__getattribute__ runs exec_module for any attribute, __spec__ included, and torch's own PropModule shims in torch/backends define __getattr__ and carry no real spec, so the probe reaches __getattr__ there. Read __spec__ out of the instance dict under the same isinstance(value, types.ModuleType) test, and only in the branch that needs it.

Done in that shape (symbolic_convert.py:2437-2464): the dict read, under the isinstance test, in the elif a present entry reaches, so nothing is computed for an absent or None one. The measured exposure was narrower than the finding says, which is why the message does not call this a behaviour change. The torch.backends shims are types.ModuleType subclasses whose __init__ runs ModuleType.__init__, which writes __spec__ = None into the instance dict, so getattr(value, "__spec__", None) found it there and never reached __getattr__: measured, "__spec__" in object.__getattribute__(m, "__dict__") is True for torch.backends (GenericModule), torch.backends.cudnn (CudnnModule) and torch.backends.mkldnn (MkldnnModule), each holding None. A _LazyModule is the real case, and __import__ forces it before import_source runs: measured on 3.10.20 and 3.12.14 with a LazyLoader-installed scratch module, __import__(name) and import name both leave the body executed and the class swapped back to module, as does importlib.import_module(name) on 3.12 (not on 3.10, whose _find_and_load reads no attribute), while object.__getattribute__(mod, "__dict__").get("__spec__") leaves it lazy. So IMPORT_NAME never handed import_source an unexecuted lazy module, and the parent's _import_module forced one on 3.11+ for the first resolution of a name per process. What the fix buys is the callers that resolve a name without an __import__ of their own -- get_globals_source_and_value, the __module__-derived and codegen names -- and one promise for the whole function on every version; test_import_alias_check_does_not_run_a_module_getattribute pins it, erroring on the parent (3.12) with the read coming from _find_and_load, and with the plain getattr restored here, from import_source.

FAQ: nothing pins that _import_source_cache holds what import_source last bound under a name rather than the first thing it resolved: _import_source_cache.setdefault(module_name, value) passes the whole test_import_alias family. Extend the empty-slot test, which already hands a name over from old to new, with one more compile after sys.modules.pop(name), asserting the alias binds new and not old.

Pinned there, with the resolution driven directly rather than by a compile. The test's function imports the name with an import statement, and once the entry is popped that statement cannot run: measured at this tree, eager raises ModuleNotFoundError and the compile graph-breaks with Unsupported: Import failure before import_source runs, binding nothing. The cache read is reached from a compile only for a name the traced bytecode never imports -- codegen's torch.autograd.profiler, which the removed-name test uses and which is one module object throughout -- so the empty-slot test asserts _import_source_cache[name] is new after its handover and then, with the entry popped and the alias deleted, calls InstructionTranslatorBase.import_source on a stub translator over fn's globals, the shape test_import_alias_check_with_a_non_module_value_accepts_the_key_alone already uses, and asserts the alias binds new. The setdefault mutant is the one failure among the eighteen on the first assertion, and with that assertion removed on the second.

FAQ: the message says this commit leaves nn_modules_globals_vt raising KeyError: 0 as an InternalTorchDynamoError under a sys.modules rebind with a global hook registered, repaired by the commit above. That is real and new; ghstack commits land and are bisected individually, so either fold the source-rooting fix into this commit or reorder so #197135 lands first.

Kept as two commits, with the intermediate state measured rather than assumed. The scenario needs sys.modules["torch.nn.modules.module"] rebound to a module that is not torch's own while a hook is registered on torch's own, and there the parent is not right either; it is right in one order. Measured with a shim carrying empty hook dicts and forwarding every other read to the defining module: with the name resolved by a compile before the rebind, the parent's memo holds the defining module and the hook runs; with the shim installed before the process's first compile, the memo holds the shim, the hook dicts read empty, the call bypasses _call_impl and the compiled function skips the hook, returning a tensor eager does not, with nothing raised. This commit raises InternalTorchDynamoError: KeyError: 0 in both orders, and the commit above runs the hook in both. So a bisect that lands on this commit sees a loud error where the parent gave an order-dependent wrong answer, in a scenario reachable only by rebinding torch's own module in sys.modules. The rooting fix is a separate PR because it mints a new global-name family (___nn_modules_module) whose own review is about aot_compile.py's enumeration of minted prefixes, a discussion this commit's diff has no part in; whether #197135 lands below this one instead is a stack-order question the two messages are written to survive either way.

FAQ: "A writer's same-named module is replaced: value is the live entry whenever there is one" licenses dropping the old if bound is value or sys.modules.get(module_name, value) is value gate, and it is not true in one reachable case: for a name blocked with None, .get returned None, which is not value, so the old code kept a writer's binding of a different same-named object and this code overwrites it. Say "whenever there is a module one" and note that a None-blocked name has no binding worth preserving.

Reworded, in the comment (symbolic_convert.py:2533-2538) and in the message. The case is as described: two writers (install(), an AOT load seeding its guard scope) resolve independently through import_module, so a None-blocked name can find the alias bound to one same-named object while the cache holds another, and the name check passes since both answer the same __name__. The old gate replaced the writer's module for an absent name (the .get default made the test true) and kept it for a None one; now both replace it, and the comment says which object wins and why: neither is live, and the cached one is what this process's traces bound and built guards against.

FAQ: five pre-existing tests lost _import_module.cache_clear() from their finally without gaining _import_source_cache.pop(name, None), while the three new tests pop; the missing pops are functionally no-ops (every one keeps the name live across its compiles), but that is two teardown conventions in one file and a process-lifetime strong reference to each test-minted ModuleType. Pop in all eight, or say in one comment that the pop matters only where a compile runs with the name absent.

Every test whose scratch name gets cached pops now -- thirteen at this commit, the previous commit's accepted-names fixture and stub-translator test among them -- and the message says when the pop is load-bearing: only where a later compile runs with the name absent or blocked. Four test_import_alias tests have no pop, deliberately: the refused-alias install test's one trace is refused before the cache write, which now sits below the alias check, and the test asserts the name absent from the cache instead; the removed-name test's name is torch.autograd.profiler and the object cached is the process's own module, which the pop would not free and the next test re-caches; the non-module test's entry never reaches import_source, IMPORT_NAME rejecting it first, and would not be cached if it did; and the torch_package test's name takes the arm that never writes the cache.

FAQ: _import_source_cache: dict[str, types.ModuleType] is not what the code stores: sys.modules accepts any object, the isinstance test at the __spec__ read exists because a present entry may not be a module, yet the write below it caches value unconditionally, so a non-module can be cached and later served and bound -- the one thing the non-module test says the traced globals never hold. Annotate the cache dict[str, Any] and say why, or hoist the isinstance so a non-module is never cached.

Hoisted, in the sense that keeps the annotation honest: the cache write is guarded by isinstance(value, types.ModuleType), on the value finally resolved rather than on the sys.modules entry alone, together with the cacheable local the sys.modules arm sets, and sits below the alias check with the package record and output.import_sources, so a non-module reaching import_source is bound as is by the callers that make no module check and remembered by nothing. test_import_alias_check_with_a_non_module_value_accepts_the_key_alone pins it, reaching the write on a stub translator with a SimpleNamespace under the key and asserting the key absent from _import_source_cache after the accepted call; with the conjunct dropped it fails there. It is not pinned by the existing non-module test, which cannot reach the write: IMPORT_NAME is the one caller whose name the traced code chose, and it graph-breaks on Bad import result before import_source runs (that test's own point). The callers without such a check resolve torch's own and stdlib names, or a class's __module__ at reconstruction time (ctx_manager.py, misc.py, torch_function.py), where a non-module under that name fails the emitted G[alias].<Name> read on any tree, so a test through them would pin the wrong thing.

FAQ: the "zero lock acquisitions" measurement and the deadlock argument built on it rest on the _initializing gate at _bootstrap.py:1355-1356, which does not exist before CPython 3.11; on 3.10, a supported and dynamo-tested interpreter, _find_and_load takes the module lock and calls _lock_unlock_module unconditionally, each through _get_module_lock and the global import lock, under compile_lock, on every compile. Either measure it there or serve a live initialized sys.modules entry directly.

Right, and the second option is taken. The earlier answer was measured on 3.12 only, and 3.10.20 gives the opposite result: importlib.import_module of a present, initialized name is two _get_module_lock calls and four _imp.acquire_lock calls (two from _get_module_lock's own bracket, two from the weakref callback that drops the lock, _bootstrap.py:185/199/207/211) and 5.5 us per call, against none and 388 ns on 3.12.14. import_source now reads sys.modules itself (symbolic_convert.py:2437-2464): a present entry whose __spec__._initializing is not set is served as is, with no lock on either version (spied: zero _get_module_lock calls for five names on both), at 244 ns and 159 ns per call. import_module is reached only for an absent or None entry the cache has not seen -- a first import or the blocked-module raise, both as before -- and for an entry still executing its body, where it waits on the module lock as an import statement would (two acquisitions on both versions); the body is _find_and_load's 3.12 gate written at the call site, with the spec read out of the instance dict, so the cost is the same on every supported interpreter.

FAQ: dropping the process-wide memo means every compile re-enters CPython's module-lock path, which can raise _DeadlockError or hang while compile_lock is held: thread A executes module M's body, thread B compiles a frame whose globals are M.__dict__ and blocks on M's lock under compile_lock, and if A's body compiles the two deadlock. The window is not new, but its frequency is. If the _initializing wait is the only reason for import_module, serve a live-and-initialized entry from sys.modules and fall back to import_module only when absent or initializing.

Taken in that form, once the round-54 review showed the measurement behind the earlier answer was 3.11+-specific (previous FAQ). The frequency claim still does not hold: the lock is now reachable only for an entry whose __spec__._initializing is set, which _load_unlocked (_bootstrap.py:911-950) sets around a first-time execution of a module body, so once per incarnation of M; within that window compile_lock admits one compile at a time, and on the parent that compile calls the cold _import_module(M), which is importlib.import_module(M) and blocks identically -- functools.cache stores nothing until the call returns. Measured with a scratch module whose body starts a thread that compiles a __main__ function inlining one of its functions and then sleeps 3 s: thread B's compile finished 31 ms after the body ended here and 33 ms after it on the parent, both binding the module being initialized; with the _initializing test removed it finished 2921 ms before the body ended, on a module still marked _initializing. The dispatch into that wait is pinned single-threaded by test_import_alias_of_an_initializing_module_waits_on_its_import. The parent skips the wait in exactly one situation: M was fully imported before, removed from sys.modules and imported again, so its memo holds the previous incarnation and the alias binds a module the program no longer holds, which is the bug this commit fixes. The deadlock the review describes -- B blocked on M's lock under compile_lock while A's body wants compile_lock -- needs that same cold first compile on the parent. _DeadlockError itself needs A to be blocked on a module lock B holds (_ModuleLock.has_deadlock walks _blocking_on), which B, holding no module lock, cannot cause; measured, no error was raised on either tree.

FAQ: _import_module has one caller resolving one hardcoded name; the plain attribute chain torch.nn.modules.module is fixed for the process for the same reason. Delete it and write the value directly.

Done, as described above: nn_modules_globals_vt reads torch.nn.modules.module, the helper and its docstring are gone, and the first test pre-warms the resolution the way any program does, with an earlier compile of the same function followed by torch._dynamo.reset(), rather than by calling a private. _import_source_cache is not poisoned by the test: it holds the earlier compile's module because that compile ran, and the stale # as any earlier compile in the process does comment went with the call it annotated.

FAQ: CompilePackage.install() is the other writer of the same __import_* alias, and it resolves with a bare importlib.import_module(module_name), so a name gone from sys.modules at install time raises ModuleNotFoundError out of install(), the failure mode the removed-name test rules out for the tracing side. Share the resolution helper, or say why install() is exempt.

Exempt, because neither hazard the cache guards against exists at install time. The cache exists so that a trace never runs a module body -- import_source is called from guard construction, inside the compile -- and never turns ModuleNotFoundError into an InternalTorchDynamoError with no eager fallback. install() runs in the user's own call, outside any trace: measured, with the name deleted it raises builtins.ModuleNotFoundError: No module named '...', and blocked with None it raises import of ... halted; None in sys.modules, both plain, both what the program's own import statement raises at that point, and a re-import there is an ordinary import at an ordinary time. Sharing the cache would also change nothing in the case the finding describes: a process that only loads has traced nothing, so the cache is empty -- measured, [] before and after install() in a load-only process with torch.autograd.profiler deleted -- and the helper would fall through to import_module exactly as install() does today. What that import does is the live-entry premise, not a breach of it: install() re-imports the name, and afterwards sys.modules, the alias and the torch.autograd.profiler attribute chain all hold the same fresh object (_find_and_load_unlocked re-runs setattr(parent_module, child, module)); only a reference held from before the deletion differs, as it would after any re-import. The tracing-side cache is about a trace's view of a name the program still holds; install() has no trace and no such view.

FAQ: "costs at most a recompile" is false for a loaded AOT artifact, which has no recompile path; the rebind converts a trace-time crash into a call-time crash in another function.

Measured on the one load path whose guard scope really is a live user namespace (_resolve_guard_scope -> model.forward.__globals__, aot_compile.py:1327): save a module artifact against a shim with VALUE=2, load it (the load does seed the alias into the module's live globals), hand sys.modules over, trace another function in those globals so the alias is rebound, then call the artifact. With the handover answering the same, the artifact runs fine (match=True) even though the slot now holds a different module object -- there is no identity guard to fail, because MODULE_MATCH is unserializable (guards.py:5110). It raises only when the live module answers differently, and the same run with no rebinding trace shows what that alternative buys: guards pass and the artifact serves 2.78 where the model's own eager forward returns 7.78. So the rebind does not create a failure; it makes an already-stale artifact detectable, and on a path that recompiles it costs a recompile (measured: the divergent case under the default stance recompiles and returns the live 7.046, equal to eager). The commit message says this explicitly instead of "at most a recompile", and test_import_alias_rebind_makes_a_stale_artifact_visible pins both halves: the guard miss under fail_on_recompile, and the live answer after the recompile. Separately, for load_compiled_function the write never reaches a shared dict at all: guard_scope = self.fn.__globals__ is the rebuilt callable's scope (aot_compile.py:765), and measured, nothing was seeded into the defining module in any filter/value combination.

FAQ: the resolution change lands on all eleven import_source callers, and callers that derive module_name from an object's __module__ may now raise AttributeError out of guard construction; that behavior change is undescribed and uncovered.

The count is right (codegen.py:781/792/848, symbolic_convert.py:2382/2610/2612/6535, torch_function.py:220, misc.py:1311, functions.py:3005, ctx_manager.py:118), and five of those are codegen sites where live resolution is required rather than merely defensible: load_import_from emits bytecode that reads G[alias].object_name at runtime (codegen.py:847-854), so the alias must hold the object the program's own attribute read would find. For the guard-rooting sites the premise is the one this commit argues, and the measured alternative is not a quieter failure but a wrong answer: with the alias left on the memoized module the loaded artifact's guards pass and it returns 2.046 where eager returns 7.046. A live module that lacks an attribute the abandoned one had is the loud version of that same staleness, and a mock.patch.dict stand-in synthesizes attributes rather than missing them. misc.py:1311 is additionally gated on source is None and not is_setup_ctx_defined.

FAQ: add package.uninstall() to the rebind test's finally; the backend-id bindings survive into the next test.

One binding does, and it is inert. Instrumented, the torch._dynamo.reset() already in that finally clears the functional state -- precompile entries on fn.__code__ go 1 -> 0 -- and takes the CleanupHook'd __compiled_fn_3_*/__builtins_dict___2 names with it. Adding uninstall() after it removes exactly one further name, the uuid-suffixed __compiled_fn_1_<uuid> that nothing else reads or can collide with, and five names remain either way: __builtins_dict___0 plus four __import_torch* aliases, which uninstall() deliberately does not remove (_install_global's record_only_if_new, package.py:1253-1268, exists so a loaded artifact's guards can keep holding an alias by reference). So the call does not buy hermeticity; it deletes a dead binding while adding a finally that can raise NameError over the real failure if package is not yet bound. The full file is green with the leak in place.

FAQ: dropping the functools.cached _import_module means a name resolved earlier and then removed from sys.modules re-runs the import machinery inside the trace, executing the module body again or raising ImportError as an InternalTorchDynamoError; keep both properties with importlib.import_module when the name is in sys.modules and _import_module otherwise.

Fixed, though not with that shape: _import_module is gone, and a fallback to a second memo would have re-imported once for every name import_source had resolved live. import_source remembers what it last bound per name (_import_source_cache, symbolic_convert.py:264) and serves that when the name is gone from sys.modules or blocked there with None (:2437-2464); a live entry is read from sys.modules. Measured before the fix with functools, which codegen resolves for a partial built in the frame: import_source('functools') in sys.modules=False, then name back in sys.modules: True and alias is functools: False -- the trace had re-executed functools.py and bound a copy the program does not hold; after, the same trace binds the original and sys.modules stays without the name. The reach is narrower than ten call sites suggest, and only codegen names can arrive absent: IMPORT_NAME's __import__ has just put its own name back (measured with a scratch module: the body re-ran under __import__, as it does in eager, and the alias bound that re-imported object, the one the bytecode pushed), get_globals_source_and_value resolves only a module it has just found live under the frame's __name__, and probing the user-controlled paths -- a sourceless context manager returned from the frame or live across a graph break, an autograd.Function via a call result or an attribute -- found each resolving only torch, torch._dynamo.utils, torch._dynamo.graph_bytecode_inputs and torch.autograd.profiler, all present. The ImportError half therefore needs a torch or stdlib module deleted from sys.modules whose file is also gone; nothing reaches it, and a name the cache has seen no longer imports at all. test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module pins the case; it has since moved from functools to torch.autograd.profiler, because the functools fixture also asserted that nothing in the process first-imports a functools user mid-compile, which failed on macOS trunk CI, and it now spies on importlib.import_module instead so unrelated imports cannot fail it.

FAQ: test_import_alias_survives_a_sys_modules_rebind and test_import_alias_rebind_makes_a_stale_artifact_visible share most of their save/reset/load/install/rebind/trace skeleton; a private helper taking the handover values would remove that.

Kept inline. The file has no such helper today -- test_basic_fn, test_lazy_backward and seven more inline the same save/load/install skeleton -- and the two tests differ in what a helper would have to parameterize: the number of handovers (three module objects against two), the handover's VALUE, whether the second compile happens before or after the install, and the closing assertions, which are the whole point of each test. A helper yielding to the caller for those would be shorter by a dozen lines and longer to read, since the sequence a reader has to follow -- which object the alias holds at each step -- is exactly the part that would move out of sight. Each test reads top to bottom as the scenario its comment describes.

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ 6 Pending, 2 Unrelated Failures

As of commit 370c1d1 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 15, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

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


Reviewed — the core change (bind the alias to the live sys.modules entry) is right, but dropping the process-wide memo means every compile now re-enters CPython's module-lock path, which can raise _DeadlockError or hang while compile_lock is held, and _import_module is left as cache machinery for a single hardcoded name that the plain attribute chain already provides for free.

Full review

PR Review: #197046

Summary

import_source now resolves through importlib.import_module (memoized into a new _import_source_cache) so the __import_* alias binds the live sys.modules entry the graph was specialized on, rather than the first object functools.cache ever saw. The premise is correct and well-argued. Three concerns: a thread-safety regression from removing the process-wide memo, leftover cache machinery that now serves one constant name, and comment volume in the production hunk.

Thread Safety

  • torch/_dynamo/symbolic_convert.py:2451-2453 — the commit message treats "waits out a module another thread is still executing" as a feature, but that wait is now taken on every translator instead of once per name per process, and its failure mode is not a graph break. _find_and_load (/usr/lib/python3.12/importlib/_bootstrap.py:1354-1357) skips locking only for a fully initialized module; when __spec__._initializing is set it enters _ModuleLockManager(name), and _ModuleLock.acquire raises _DeadlockError straight out of __enter__ — CPython's own comment at _bootstrap.py:336-346 says it "will just propagate up to application code", unlike _lock_unlock_module which catches it at :472.

    The reachable scenario: thread A is executing module M's body; thread B compiles a frame whose globals are M.__dict__ (get_globals_source_and_value → _registered_module_for_globals, symbolic_convert.py:6538-6543) and calls import_source("M"). B blocks on M's module lock while holding compile_lock (convert_frame.py:2708 wraps the whole tracer call), so if A's module body itself triggers a compile the two deadlock permanently — and has_deadlock() cannot see it, since it only tracks module locks. Otherwise _DeadlockError (a RuntimeError) surfaces out of import_source, and the codegen callers (codegen.py:781/792/848, ctx_manager.py:118) are outside break_graph_if_unsupported, so it is a hard compile failure with no eager fallback. Same-thread module-import-time compiles are fine (acquire returns early on self.owner == tid, _bootstrap.py:317-326).

    Worth stating explicitly in the commit message at minimum: the window is not new, but its frequency is, and the PR's own justification for choosing import_module over sys.modules.get is exactly the code path that carries it. If the _initializing wait is the only reason for import_module here, consider whether serving a live-and-initialized entry straight from sys.modules (falling back to import_module only when the entry is absent or initializing) gets the same semantics without re-entering the lock on every compile.

    Not a concern, having checked: the _import_source_cache check-then-set at :2452-2453 is not a data race, since all Dynamo compiles hold compile_lock (convert_frame.py:2708).

Code Quality

  • torch/_dynamo/symbolic_convert.py:260-269 and :2395-2398 — after this change _import_module has exactly one caller, resolving one hardcoded name. A functools.cache plus a six-line docstring now exists solely to guarantee "one fixed module object for the process" for "torch.nn.modules.module" — but the plain attribute chain torch.nn.modules.module already has that property, and for the same reason: importlib/_bootstrap.py:1339 does setattr(parent_module, child, module) once at first import and never revisits it, so a sys.modules rebind cannot move it, while _find_and_load re-reads sys.modules on every call. import torch unconditionally imports the submodule (torch/__init__.py:2739 → torch/nn/__init__.py:8 → torch/nn/modules/__init__.py:1), and convert_frame.py:1371-1376 already uses the plain chain in this same hook-count role.

    Deleting _import_module and writing the value directly would be behavior-preserving, would remove the docstring that only exists to explain a memo you get for free, and — more usefully — would make the deliberate source/value asymmetry at :2395-2398 self-evident rather than something a comment has to assert. It also dissolves the "why does this one caller not follow the live entry?" question the added comment has to answer. The cost is rewriting test_import_alias_binds_the_live_module to poison _import_source_cache (or pre-warm via a real compile) instead of _import_module, and dropping the cache_clear() at test/dynamo/test_package.py:1020. Fix this →

  • torch/_dynamo/symbolic_convert.py:2441-2450 and :272-276 — the production diff is 30 added lines, roughly 20 of them comment, and the ten-line block at :2441-2450 reproduces the commit-message argument at the call site. CLAUDE.md asks for minimal comments that supply non-obvious global context. The load-bearing facts here are two: live entry, because that is what IMPORT_NAME pushed, and cache fallback, because re-importing inside a trace re-executes the body. Both fit in two or three lines; the __import__-parity and blocked-module-sentinel exposition belongs in the commit message, where it already is.

  • test/dynamo/test_package.py:1006 — _import_module(name) # as any earlier compile in the process does is false as of this commit: no compile calls _import_module for an arbitrary name any more. The call itself is load-bearing (it is what makes the test fail against the parent), only the trailing comment is stale.

Testing

  • test/dynamo/test_package.py:1374 — assertIs(sys.modules.get(name), None) runs for both arms of for blocked in (False, True) (:1363), but .get() cannot distinguish "absent" from "present with value None". In the blocked=False arm (del sys.modules[name] at :1370) the assertion would still pass if the trace re-added the name bound to None, which is the precise thing that arm exists to rule out. Wants a branch-dependent check — assertNotIn(name, sys.modules) when not blocked, the current assertIs when blocked. The realistic failure (a re-import re-adding the real module) is caught either way, so this is a precision gap rather than a hole.

  • test/dynamo/test_package.py:1023-1135 — test_import_alias_survives_a_sys_modules_rebind and test_import_alias_rebind_makes_a_stale_artifact_visible share 29 of ~37-40 code lines: identical DiskDynamoStore save / reset / load_package / install / rebind / trace-fn2 skeleton, differing in the handover count (three module objects vs two), the handover's VALUE, and the closing assertions. A private helper taking the handover values and yielding to the caller for the assertions would remove that. Noting the counter-argument: the file has no such helper today — test_basic_fn:332, test_lazy_backward:376, :423, :487, :537, :577, :684, :756, :861 all inline the same skeleton — so this is consistent with local practice, and a helper here is a judgment call rather than a clear win.

  • Neither new packaging test clears _import_source_cache in its finally, so the fresh/newer/real ModuleType objects they mint are retained process-wide for the rest of the run. Harmless (the names are unique, so no cross-test interference) but out of step with the otherwise careful teardown in these tests, which pops the alias and the sys.modules entry.

  • :1124 discards the fn2 result while its twin at :1071-1072 asserts it; make the two consistent.

Recommendation

Needs Discussion

The alias/graph-identity argument is sound and the tests pin the behavior change on both sides. What needs a decision before merge is the thread-safety item: removing the memo moves the module-lock wait from once-per-name-per-process to once-per-compile, and its failure mode there is _DeadlockError or a hang under compile_lock, not a graph break. If that trade is intended, say so in the commit message; if not, resolving a live-and-initialized entry from sys.modules directly avoids it. The _import_module deletion and the comment trim are straightforward follow-ups.

Note on verification: PyTorch is not built in this checkout (no torch/_C*.so, no .venv), so I could not run python test/dynamo/test_package.py -k test_import_alias. All findings are from reading the diff, the surrounding Dynamo code, and CPython's importlib/_bootstrap.py on this machine.

| branch `gh/bobrenjc93/1191/head`

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93 bobrenjc93 changed the title [dynamo] Bind the import alias to the live sys.modules entry [no-ci] [dynamo] Bind the import alias to the live sys.modules entry Sep 15, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

bobrenjc93 added a commit that referenced this pull request Sep 19, 2026
…ast bound

Split for review budget from `[dynamo] Bind the import alias to the live
sys.modules entry` (#197046), the commit directly below: that one makes
`import_source` bind the live `sys.modules` entry whenever there is one and
keeps the memoized `_import_module` in front of that read, for a name since
removed from `sys.modules` or blocked there with `None`; this one replaces the
memo with a cache of what `import_source` last bound, written only once the
alias check has passed, and reads `sys.modules` with nothing in front of it.

`_import_module` is `functools.cache`d for the life of the process: it holds
the first object the process resolved under each name, and nothing clears it.
Below this commit it is what a name binds once the name has left `sys.modules`
-- `del sys.modules[...]`, a `mock.patch.dict(sys.modules)` scope -- or been
set to `None`, the import system's blocked-module sentinel that makes any
import of the name raise `ModuleNotFoundError`, because importing such a name
again would execute the module body inside the trace and bind a second copy of
a module the program still holds, or for `None` raise out of guard
construction (`ModuleNotFoundError` is not in `_compile`'s pass-through tuple,
so that raise surfaces as `InternalTorchDynamoError` with no eager fallback).
But the first resolution is the wrong object to fall back on for the same
reason it was the wrong object to bind: after a handover the traces have been
binding the live module and building guards against it, and the memo still
holds the module before the handover. And the memo is only warm for a name
some trace resolved while it was live: the commit below measures that a memo
cold for a deleted or blocked name imports inside guard construction all the
same, whichever order it and `sys.modules` are read in. `_import_source_cache`
replaces it, keyed by name, holding what `import_source` last bound: each
accepted resolution overwrites the entry, so a name that then leaves
`sys.modules` binds the module the guards this alias roots were built against,
not the one the process saw first.
`test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache`,
inherited from the commit below, gains that pin: after its handover
`_import_source_cache[name]` is the second module, and with the entry popped
and the alias deleted a resolution binds the second module, not the first.
The memo was also written at resolution, before the alias check, so a trace
the check refused with `Import alias already bound` remembered the name all
the same. The cache is written only once the check has passed, alongside the
package record and `output.import_sources`: it is never cleared, so a write
before the check would pin a module the process may later drop on behalf of a
trace that bound nothing. Whether a name is one the cache can serve is decided
where `import_source` branches on it and carried to the write in a local,
`cacheable`: `False` in the `torch_package` arm, whose names resolve through
`_package_imported_modules`, a `WeakValueDictionary`
(`package_importer.py:731`) that holds a packaged module only while its
importer or the user does, so an entry would pin a `torch.package` module the
user has dropped for the rest of the process, and whose names are never read
back from the cache in any case, the read being in the other arm; `True` in
the `sys.modules` arm. A second `"torch_package" in module_name` test at the
write, a hundred lines below the first, would have to be kept in step with it
by hand; the local cannot drift. The write is further guarded by
`isinstance(value, types.ModuleType)`: `sys.modules` accepts any object, and a
non-module entry, which the callers without a module check bind verbatim, is
never remembered, so the cache's `dict[str, types.ModuleType]` annotation holds
by construction.

The live entry is read from `sys.modules` itself, and the memo no longer runs
in front of the read. What the memo's call cost for a present name depended on
the interpreter, since a cold memo is `importlib.import_module`: on 3.12
`_find_and_load` (`importlib/_bootstrap.py:1349-1356`) returns without
touching a lock unless the entry is missing or its `__spec__._initializing` is
set, but 3.10's (`:1022-1034`) has no such gate -- it enters
`_ModuleLockManager` and calls `_lock_unlock_module` for every name, each
through `_get_module_lock`, which brackets its body with the global import
lock (`:185`, `:211`), all of it under `compile_lock`. Measured in an earlier
revision of this commit with spies on `_get_module_lock` and
`_imp.acquire_lock`, resolving a present, initialized name through
`import_module`: 3.10.20, two module-lock and four global-import-lock
acquisitions and 5.5 us per call; 3.12.14, none and 388 ns. The `sys.modules`
read takes no lock on either. The import machinery is now entered in two
cases only: a name absent from `sys.modules` that no trace has resolved before
(a first import, as before), and a name blocked with `None` that no trace has
resolved before (which raises `ModuleNotFoundError`, as before). An entry
whose `__spec__._initializing` is set -- `_load_unlocked` (`:911-950`) sets it
around a first-time execution of the module body -- is served as is. An
earlier revision handed such an entry to `import_module` so the trace would
wait on the module lock as an import statement does; that branch is gone, for
the reason its review gave. From `IMPORT_NAME`, the one caller whose name the
traced bytecode chose, `__import__` has just returned the entry, and
`_find_and_load` already waited out a cross-thread initialization; what can
still be `_initializing` there is same-thread re-entrancy, a module body that
compiles a function importing the module itself, where `_ModuleLock.acquire`
short-circuits on its owner and `import_module` returns the same
half-initialized object, so the branch changed nothing (measured with such a
module at this tree: the spec's flag is set when the compile runs, the compile
succeeds, and the alias and the cache both hold the module itself). The only
caller family the branch could change a value for resolves a name without an
`__import__` of its own -- `get_globals_source_and_value`, the codegen names --
while another thread executes that module's body, and there `import_module`
blocks on that module's lock with `compile_lock` held; if the other thread's
body re-enters Dynamo it blocks on `compile_lock`, and importlib's deadlock
detection, which walks module-lock edges only, cannot see the cycle. The
comment at the read says so, so the next reader does not put the wait back.
The commit below waited in that case only while its memo was cold and served
the previous incarnation once warm; this commit serves the live entry as it
stands, which is what the same-thread case always got. No test pins it: the
observable difference is a two-thread timing, and the single-threaded dispatch
pin an earlier revision had (`..._waits_on_its_import`, which asserted the
`import_module` call, not a wait) went with the branch.

The resolution reads nothing off the module it resolves. The commit below's
`_import_module` made `_find_and_load`'s `getattr(module, "__spec__", None)`
on 3.11+ for the first resolution of each name per process, none on 3.10; here
no version reads an attribute off the module, and the alias check below reads
`__name__` out of the instance dicts as before.
`test_import_alias_check_does_not_run_a_module_getattribute` pins the
resolution as well as the check: its module class now raises on any read made
with `import_source` on the stack, matched by function name and module, and on
the commit below, on 3.12, the test errors with the module's raise reached from
`_find_and_load` under `_import_module`.

The write rule loses its condition. Below this commit a writer's same-named
module -- `CompilePackage.install()`, an artifact load seeding its guard scope
-- is replaced when the name is live and left in the slot when the name is
gone or blocked, the memo being no less stale than the writer's module. Now
`f_globals[alias] = value` runs unconditionally: `value` is the live entry
whenever `sys.modules` holds a module under the name, or the one a first import
has just put there, and what this process's traces last bound when the name is
gone or blocked with `None`; there neither module is the live entry, and the
cached one is the object the guards this alias roots were built against.
`test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`
pins it: a trace binds and caches one module, `install()` in the same globals
binds a second of the same name, and with the entry then popped, and again
with it set to `None`, a resolution replaces the installed module by the cached
one; on the commit below the installed module stays in the slot, both arms.

`_import_module` is deleted; its last caller is this read. The cache is never
cleared, not by `torch._dynamo.reset()` either, so a module the process has
dropped stays alive in it; the memo retained modules the same way, so this is
not new retention. The declaration comment is the one place that says so; an
earlier revision repeated it in `reset()`, next to nothing that read it. A
`reset()` that did clear the cache fails the removed-name test, whose deleted
and blocked compiles follow a `reset()`. Only names the traced bytecode never
imported can arrive absent or blocked: `IMPORT_NAME`'s own `__import__` has
just put its name back or raised, `get_globals_source_and_value` resolves only
a module it has just found live under the frame's `__name__`, and the other
callers pass torch's own or stdlib names for codegen. `torch.autograd.profiler`
is such a name: `codegen.py` resolves it on every compile under
`config.record_runtime_overhead` (on by default) for the runtime-overhead
record in the compiled frame's prologue, and the only function-scope import of
it in torch/ (`torch/profiler/_utils.py`) is off the compile path, so a trace
with the entry deleted has no other reason to re-import it. The removed-name
test, inherited from the commit below, uses it for that reason.

Order to review: `symbolic_convert.py`, the `_import_source_cache` declaration
replacing `_import_module`, then the `sys.modules` arm of `import_source` (the
read, the cache fallback, the `import_module` fallback and the comment on the
entry still initializing), the `cacheable` local in both arms, and the write
block (record, cache write, unconditional alias write); then `test_package.py`:
the gone-name test (the one new case), the frame-walk probe at the top of the
file and the extended getattribute test, the empty-slot test's cache pin and
comptime-driven resolution, the cache assertions in the refused-alias tests,
the `torch_package` test and the non-module-value test, and the teardowns,
where `_import_module.cache_clear()` becomes `_import_source_cache.pop(name,
None)` or goes.

Behaviour change against the commit below, pinned below: a name gone from
`sys.modules` or blocked there with `None` binds what `import_source` last
bound under it rather than the first object the process resolved
(`test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache`, its
resolution after the pop); a writer's same-named module in the slot is
replaced for a name gone or blocked
(`test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`);
the resolution reads no attribute off the module it resolves, where the memo's
`import_module` did on 3.11+ for the first resolution of a name
(`test_import_alias_check_does_not_run_a_module_getattribute`); a refused trace
remembers nothing under the name (`test_import_alias_taken_by_a_non_module_graph_breaks`,
`test_import_alias_the_trace_refused_is_not_recorded_for_install`, by mutation:
with the write moved above the check, five failures); a `torch_package` name
and a non-module value are bound but never remembered
(`test_import_alias_accepts_a_stale_torch_package_module`,
`test_import_alias_check_with_a_non_module_value_accepts_the_key_alone`, each
by mutation of the guard it pins); and an entry still executing its body is
served as is rather than waited on when the name is one no trace resolved
before, which no test pins (above). Not a change: a name removed from or
blocked in `sys.modules` between two traces still binds the module the program
holds, and the import machinery is not entered for it
(`test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module`,
which passes on the commit below, whose memo serves the name, and pins this
commit against a cache read dropped).

Test Plan:

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

One case joins the commit below's twenty-two: twenty-three `test_import_alias`
instances. Seven of the inherited ones gain cache assertions or a cache-driven
leg, three have comments reworded, and every teardown changes. The new one,
`test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`,
compiles a function importing a scratch module under a `CompilePackage`, saves
it, hands the `sys.modules` entry to a second module of the same name and
loads and installs the package, so `install()` binds the alias to the second
module while the cache holds the first; then, in two `subTest` arms with the
alias put back on the installed module before each, pops the entry, and sets
it to `None`, and compiles a probe whose bytecode never imports the name and
whose comptime callback calls `import_source(name, True)` on the live
translator as `IMPORT_NAME` does -- the function's own import statement cannot
run once the entry is gone -- pinning that the alias holds the first module
afterwards and, at the end, that the cache still does. The empty-slot test,
after its handover, asserts `_import_source_cache[name]` is the second module
and then, with the entry popped and the alias deleted, drives `import_source`
the same way from a probe compiled in the same globals, and asserts the
returned source names the alias and the alias binds the second module; an
earlier revision called the unbound method on a `types.SimpleNamespace`
translator, which bypassed the real `OutputGraph` and `CompilePackage`. Its
scratch name is now `torch_test_package_import_alias_handed_over`. The
extended getattribute test's `_ImportAliasHookedModule` used to raise on a
`__dict__` read anywhere, and now raises on any read made with
`InstructionTranslatorBase.import_source` on the Python stack, matched by
function name and by the frame's module (`__import__` and
`PythonModuleVariable` read `__spec__` and `__name__` off a module by design,
so the stack is the discriminator); with no read left for the hook to observe,
its positive control is static: the test asserts that
`InstructionTranslatorBase.import_source.__wrapped__` (the `cache_method`
wrapper keeps the function under `__wrapped__`) has the `co_name` and
`__module__` the walk matches, so a renamed or inlined `import_source` fails
there rather than letting every read through. The refused-alias tests:
`test_import_alias_taken_by_a_non_module_graph_breaks` pins, per case, that
neither the `fullgraph` refusal nor the skipped frame leaves the name in
`_import_source_cache`, and `test_import_alias_graph_break_is_cached_until_reset`
pins the name absent after the refusal and present, as the module, after the
compile that binds the alias; `test_import_alias_the_trace_refused_is_not_recorded_for_install`
pins the name absent from the cache after the checkpointed refusal and again
after `install()`. The two tests that reach the cache write with a value one
of its guards refuses each gain one `assertNotIn` on the cache:
`test_import_alias_accepts_a_stale_torch_package_module` asserts the mangled
name absent after its compile, and
`test_import_alias_check_with_a_non_module_value_accepts_the_key_alone` asserts
the key absent after its accepted call. The removed-name test's comment and
teardown lose the memo, and the installed-live-module test's and the nn hook
test's comments no longer say "memo", the helper being gone.
Every `test_import_alias` test whose scratch name gets cached pops it from
`_import_source_cache` in `finally`, alongside the alias and the entry --
sixteen at this commit, in place of the `_import_module.cache_clear()` that
named the deleted helper: the pop only matters where a later compile runs with
the name absent or blocked, but one teardown shape keeps a test-minted module
from outliving its test either way. Six have nothing to pop, and the commit
below's `cache_clear()` simply goes: `test_import_alias_the_trace_refused_is_not_recorded_for_install`,
whose one trace is refused before the write and which asserts the name absent
instead; `test_import_alias_is_not_bound_to_a_non_module_import`, whose entry
`IMPORT_NAME` rejects before `import_source` runs, and a non-module is never
cached in any case; `test_import_alias_accepts_a_stale_torch_package_module`
and `test_import_alias_taken_in_a_torch_package_slot_is_a_hard_error`, whose
names take the `torch_package` arm, which never writes the cache (the first
asserts that); and `test_import_alias_taken_at_codegen_is_a_hard_error` and
the removed-name test, whose name is `torch.autograd.profiler` and whose
cached object is the process's own module, which a pop would not free and the
next compile re-caches.

Measured against the commit below's `symbolic_convert.py`, checked out under
this test file with a stub `_import_source_cache = {}` added so the file
imports: four of the twenty-three fail there. The getattribute test errors on
3.12 with `InternalTorchDynamoError: RuntimeError: module __getattribute__
read __spec__ inside a trace`, the read made by `_find_and_load`
(`_bootstrap.py:1356`) under `_import_module`; the gone-name test fails both
arms on `assertIs(fn.__globals__[alias], old)`, the installed module left in
the slot, and then errors on its closing cache pin against the empty stub; the
empty-slot test errors with `KeyError` on `_import_source_cache[name]`,
nothing having written the cache; and
`test_import_alias_graph_break_is_cached_until_reset` errors the same way on
its `assertIs(_import_source_cache[name], module)` after the compile that binds
the alias. The other nineteen pass there, the removed-name test, whose memo
serves the name, and the `assertNotIn`s on an empty stub among them. Those are
pinned at this tree by mutation of `symbolic_convert.py`, each mutant run
against the twenty-three and restored afterwards: with the write gated as the
commit below gates it (alias absent, or holding the value, or the name live),
the gone-name test fails both arms (and the `torch_package` test errors, that
gate reading its name, which is never in `sys.modules`, as not live); with the
cache write made `_import_source_cache.setdefault(module_name, value)` -- a
first-resolution memo one indirection further in -- the empty-slot test alone
fails, on `assertIs(_import_source_cache[name], new)` after the handover; with
the cache read dropped, importing whenever the entry is absent, the
removed-name test fails its deleted case on the spy (`'torch.autograd.profiler'
unexpectedly found in ['torch.autograd.profiler']`) and errors its blocked
case with `InternalTorchDynamoError: ModuleNotFoundError: import of
torch.autograd.profiler halted; None in sys.modules`, and the empty-slot and
gone-name resolutions error with `ModuleNotFoundError` for their scratch
names; with the `torch_package` arm's `cacheable` flipped to `True`, the
`torch_package` test alone fails; with the `isinstance(value,
types.ModuleType)` conjunct dropped from the write, the non-module-value test
alone fails; with the cache write moved above the alias check, five failures,
`assertNotIn` in each of the three `taken_by_a_non_module` cases, in
`cached_until_reset` and in the install test; and with a
`getattr(value, "__spec__", None)` added to the resolution, the getattribute
test alone errors, with the hook's `RuntimeError`. Neither of the two guard
mutants changes what a compile binds today -- one pins a dropped
`torch.package` module for the process, the other opens a path `IMPORT_NAME`
blocks -- so the annotation and the comments at the write are held by those
two assertions and by nothing else. On this commit the twenty-three pass and
the whole file is 101 tests, OK (skipped=40, expected failures=1).

```
python test/dynamo/test_package.py -k test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache
python test/dynamo/test_package.py -k test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module
python test/dynamo/test_package.py -k test_import_alias_check_does_not_run_a_module_getattribute
python test/dynamo/test_package.py -k test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache
python test/dynamo/test_package.py -k test_import_alias_taken_by_a_non_module_graph_breaks -k test_import_alias_graph_break_is_cached_until_reset -k test_import_alias_the_trace_refused_is_not_recorded_for_install
python test/dynamo/test_package.py -k test_import_alias_accepts_a_stale_torch_package_module
python test/dynamo/test_package.py -k test_import_alias_check_with_a_non_module_value_accepts_the_key_alone
```

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

> **FAQ: the `_initializing` -> `importlib.import_module` branch cannot change `value` on the one caller that can reach it from traced bytecode, since `IMPORT_NAME`'s `__import__` has just waited, and its one effectful path -- a codegen or `get_globals_source_and_value` caller resolving a name another thread is executing -- blocks on that module's lock under `compile_lock`, a lock-order cross `_has_deadlocked` cannot see. Drop it and serve the entry as is, or state the hazard at the call site.**
>
> Dropped, and the hazard is stated where the wait would go. Reachability was probed at this tree with a scratch module whose body compiles a function that imports the module itself: `IMPORT_NAME`'s `__import__` hands back the entry with `__spec__._initializing` still `True`, the compile succeeds, and the alias and `_import_source_cache` both hold that module -- the object `import_module` would have returned too, its lock being owned by the same thread. So from `IMPORT_NAME` the branch was two lock acquisitions for nothing, and from the callers with no `__import__` of their own it was the wait the finding describes, per compile rather than once per process. What is given up is the single-threaded dispatch pin (`..._waits_on_its_import` asserted that `import_module` was asked, not that anything waited) and the two-thread measurement an earlier revision made; the commit below waited in that case only while its memo was cold, and once warm served the previous incarnation, so no tree in this stack has made that wait reliably. `test_import_alias_check_does_not_run_a_module_getattribute` no longer plants a spec with a raising `_initializing` property, since nothing reads a spec. With the branch went `import importlib.machinery` in both files and the `_ImportAliasProbeSpec` helper.

> **FAQ: dropping the `if not conflict or live:` gate for an unconditional `f_globals[alias] = value` is a reachable behaviour change no test covers: the alias bound by `install()` or `_seed_guard_scope()` to a same-named but different module, which the name check accepts, and the name then absent from `sys.modules` or blocked with `None`. Add a pin.**
>
> Added: `test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`, two independent resolutions of one name (a trace under a `CompilePackage`, then `install()` of that package after a handover) and its removal, in a deleted arm and a `None` arm. On the commit below both arms fail on `assertIs(fn.__globals__[alias], old)`, the installed module left in the slot; here both pass, and with this tree's write gated the way the commit below gates it, both fail again. The write is reached through the live translator from a comptime callback, because the traced function's own import cannot run with the entry gone.

> **FAQ: the empty-slot test hand-rolls a `types.SimpleNamespace` translator and calls the unbound `InstructionTranslatorBase.import_source(tx, name)`, bypassing the real `OutputGraph` and `CompilePackage`; the file already drives `import_source` on a resolution no bytecode reaches through a comptime callback on the live translator. Use that shape.**
>
> Done: after the handover and the pop, a probe function whose bytecode never imports the name is compiled in the same globals, and its comptime callback calls `tx.import_source(name, True)` on the live translator, as `IMPORT_NAME` would; the test asserts the returned source's `global_name` is the alias and that the alias binds the second module. The new gone-name test uses the same shape. The `setdefault` mutant is still the one failure among the twenty-three, on the cache pin after the handover.

> **FAQ: the comment in `torch/_dynamo/__init__.py:171-174` restates the declaration comment and dangles above an unrelated call; the 16-line and 9-line comments at the read and the write restate CPython internals. Drop the first, trim the others to the load-bearing facts.**
>
> The `__init__.py` comment is gone, and this commit no longer touches that file; the declaration says the cache is never cleared, `reset()` included. The read's comment is down to what a reader needs at the site -- the live entry is what `IMPORT_NAME` pushed, `import_module` takes the module lock for a present name on 3.10, a removed or blocked name keeps what it last resolved to because re-importing would run the module body inside the trace, and an initializing entry is served as is with the lock-order reason -- and the write's to which module wins and why. The derivations are in this message.

> **FAQ: nothing pins that `_import_source_cache` holds what `import_source` last bound under a name rather than the first thing it resolved: `_import_source_cache.setdefault(module_name, value)` passes the whole `test_import_alias` family. Extend the empty-slot test, which already hands a name over from `old` to `new`, with one more compile after `sys.modules.pop(name)`, asserting the alias binds `new` and not `old`.**
>
> Pinned there, with the resolution driven from a probe rather than by the test function's own import. That import statement cannot run once the entry is popped: measured at this tree, eager raises `ModuleNotFoundError` and the compile raises `Unsupported: Import failure` before `import_source` runs, binding nothing. The cache read is reached from a compile only for a name the traced bytecode never imports -- codegen's `torch.autograd.profiler`, which the removed-name test uses and which is one module object throughout -- so the empty-slot test asserts `_import_source_cache[name] is new` after its handover and then, with the entry popped and the alias deleted, compiles a probe whose comptime callback calls `import_source(name, True)` on the live translator, and asserts the alias binds `new`. The `setdefault` mutant is the one failure among the twenty-three, on the first assertion.

> **FAQ: "A writer's same-named module is replaced: value is the live entry whenever there is one" licenses dropping the old gate, and it is not true in one reachable case: for a name blocked with `None`, `.get` returned `None`, which `is not value`, so the old code kept a writer's binding of a different same-named object and this code overwrites it.**
>
> The case is as described, and it is now pinned by the gone-name test's `None` arm as well as its deleted arm: two writers (`install()`, an AOT load seeding its guard scope) resolve independently through `import_module`, so a `None`-blocked name can find the alias bound to one same-named object while the cache holds another, and the name check passes since both answer the same `__name__`. The commit below kept the writer's module in both absent forms (its gate is `live`, an entry present under the name); now both replace it, and the comment at the write says which object wins and why: neither is live, and the cached one is what this process's traces bound and built guards against.

> **FAQ: five pre-existing tests lost `_import_module.cache_clear()` from their `finally` without gaining `_import_source_cache.pop(name, None)`, while the new tests pop; that is two teardown conventions in one file and a process-lifetime strong reference to each test-minted `ModuleType`.**
>
> Every test whose scratch name gets cached pops now -- sixteen at this commit, the accepted-names fixture and the non-module-value test among them -- and the message says when the pop is load-bearing: only where a later compile runs with the name absent or blocked. Six `test_import_alias` tests have no pop, deliberately: the refused-alias install test's one trace is refused before the cache write, which sits below the alias check, and the test asserts the name absent from the cache instead; the removed-name test's and the codegen test's name is `torch.autograd.profiler` and the object cached is the process's own module, which the pop would not free and the next test re-caches; the non-module import test's entry never reaches `import_source`, `IMPORT_NAME` rejecting it first, and would not be cached if it did; and the two `torch_package` tests' names take the arm that never writes the cache. The commit below cleared the memo in all of those; the line simply goes here.

> **FAQ: `_import_source_cache: dict[str, types.ModuleType]` is not what the code stores: `sys.modules` accepts any object, yet the write caches `value` unconditionally, so a non-module can be cached and later served and bound. Annotate the cache `dict[str, Any]` and say why, or hoist the `isinstance` so a non-module is never cached.**
>
> Hoisted, in the sense that keeps the annotation honest: the cache write is guarded by `isinstance(value, types.ModuleType)`, on the value finally resolved, together with the `cacheable` local the `sys.modules` arm sets, and sits below the alias check with the package record and `output.import_sources`, so a non-module reaching `import_source` is bound as is by the callers that make no module check and remembered by nothing. `test_import_alias_check_with_a_non_module_value_accepts_the_key_alone` pins it, reaching the write from a comptime callback on the live translator with a `SimpleNamespace` under the key and asserting the key absent from `_import_source_cache` after the accepted call; with the conjunct dropped it fails there. It is not pinned by the existing non-module test, which cannot reach the write: `IMPORT_NAME` is the one caller whose name the traced code chose, and it graph-breaks on `Bad import result` before `import_source` runs (that test's own point).

> **FAQ: the "zero lock acquisitions" measurement rests on the `_initializing` gate at `_bootstrap.py:1355-1356`, which does not exist before CPython 3.11; on 3.10 `_find_and_load` takes the module lock and calls `_lock_unlock_module` unconditionally, under `compile_lock`, on every compile. Either measure it there or serve a live initialized `sys.modules` entry directly.**
>
> The second option is taken. The earlier answer was measured on 3.12 only, and 3.10.20 gives the opposite result: `importlib.import_module` of a present, initialized name is two `_get_module_lock` calls and four `_imp.acquire_lock` calls and 5.5 us per call, against none and 388 ns on 3.12.14. `import_source` now reads `sys.modules` itself: a present entry is served as is, with no lock on either version, and `import_module` is reached only for an absent or `None` entry the cache has not seen -- a first import or the blocked-module raise, both as before -- so the cost is the same on every supported interpreter.

> **FAQ: dropping the process-wide memo means every compile re-enters CPython's module-lock path, which can raise `_DeadlockError` or hang while `compile_lock` is held: thread A executes module `M`'s body, thread B compiles a frame whose globals are `M.__dict__` and blocks on `M`'s lock under `compile_lock`, and if A's body compiles the two deadlock.**
>
> No compile enters the module-lock path for a present entry now, initializing or not: `import_source` reads `sys.modules` and serves what it finds, and `import_module` is reached only for a name absent or blocked that no trace has resolved before, exactly where the commit below's cold memo reached it. The scenario the finding describes -- B blocked on `M`'s lock under `compile_lock` while A's body wants `compile_lock` -- is the one the dropped `_initializing` branch would have walked into per compile, and the comment at the read names it as the reason the entry is served as is. `_DeadlockError` itself needs A to be blocked on a module lock B holds (`_ModuleLock.has_deadlock` walks `_blocking_on`), which B, holding no module lock, cannot cause; a wait on `compile_lock` is invisible to that walk, so the outcome of the dropped branch was a hang, not an error.

> **FAQ: `CompilePackage.install()` is the other writer of the same `__import_*` alias, and it resolves with a bare `importlib.import_module(module_name)`, so a name gone from `sys.modules` at install time raises `ModuleNotFoundError` out of `install()`, the failure mode the removed-name test rules out for the tracing side. Share the resolution helper, or say why `install()` is exempt.**
>
> Exempt, because neither hazard the cache guards against exists at install time. The cache exists so that a trace never runs a module body -- `import_source` is called from guard construction, inside the compile -- and never turns `ModuleNotFoundError` into an `InternalTorchDynamoError` with no eager fallback. `install()` runs in the user's own call, outside any trace: measured in an earlier revision, with the name deleted it raises `builtins.ModuleNotFoundError: No module named '...'`, and blocked with `None` it raises `import of ... halted; None in sys.modules`, both plain, both what the program's own `import` statement raises at that point, and a re-import there is an ordinary import at an ordinary time. Sharing the cache would also change nothing in the case the finding describes: a process that only loads has traced nothing, so the cache is empty, and the helper would fall through to `import_module` exactly as `install()` does today. The tracing-side cache is about a trace's view of a name the program still holds; `install()` has no trace and no such view.

> **FAQ: dropping the `functools.cache`d `_import_module` means a name resolved earlier and then removed from `sys.modules` re-runs the import machinery inside the trace, executing the module body again or raising `ImportError` as an `InternalTorchDynamoError`; keep both properties with `importlib.import_module` when the name is in `sys.modules` and `_import_module` otherwise.**
>
> Fixed, though not with that shape: `_import_module` is gone, and a fallback to a second memo would have re-imported once for every name `import_source` had resolved live (the commit below measures exactly that order). `import_source` remembers what it last bound per name (`_import_source_cache`) and serves that when the name is gone from `sys.modules` or blocked there with `None`; a live entry is read from `sys.modules`. The reach is narrower than ten call sites suggest, and only codegen names can arrive absent: `IMPORT_NAME`'s `__import__` has just put its own name back, `get_globals_source_and_value` resolves only a module it has just found live under the frame's `__name__`, and probing the user-controlled paths in an earlier revision -- a sourceless context manager returned from the frame or live across a graph break, an `autograd.Function` via a call result or an attribute -- found each resolving only `torch`, `torch._dynamo.utils`, `torch._dynamo.graph_bytecode_inputs` and `torch.autograd.profiler`, all present. `test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module` pins the case with `torch.autograd.profiler` and a spy on `importlib.import_module`, so unrelated imports cannot fail it.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 9b49eed
Pull-Request: #197303
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 19, 2026
…ast bound

Split for review budget from `[dynamo] Bind the import alias to the live
sys.modules entry` (#197046), the commit directly below: that one makes
`import_source` bind the live `sys.modules` entry whenever there is one and
keeps the memoized `_import_module` in front of that read, for a name since
removed from `sys.modules` or blocked there with `None`; this one replaces the
memo with a cache of what `import_source` last bound, written only once the
alias check has passed, and reads `sys.modules` with nothing in front of it.

`_import_module` is `functools.cache`d for the life of the process: it holds
the first object the process resolved under each name, and nothing clears it.
Below this commit it is what a name binds once the name has left `sys.modules`
-- `del sys.modules[...]`, a `mock.patch.dict(sys.modules)` scope -- or been
set to `None`, the import system's blocked-module sentinel that makes any
import of the name raise `ModuleNotFoundError`, because importing such a name
again would execute the module body inside the trace and bind a second copy of
a module the program still holds, or for `None` raise out of guard
construction (`ModuleNotFoundError` is not in `_compile`'s pass-through tuple,
so that raise surfaces as `InternalTorchDynamoError` with no eager fallback).
But the first resolution is the wrong object to fall back on for the same
reason it was the wrong object to bind: after a handover the traces have been
binding the live module and building guards against it, and the memo still
holds the module before the handover. And the memo is only warm for a name
some trace resolved while it was live: the commit below measures that a memo
cold for a deleted or blocked name imports inside guard construction all the
same, whichever order it and `sys.modules` are read in. `_import_source_cache`
replaces it, keyed by name, holding what `import_source` last bound: each
accepted resolution overwrites the entry, so a name that then leaves
`sys.modules` binds the module the guards this alias roots were built against,
not the one the process saw first.
`test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache`,
inherited from the commit below, gains that pin: after its handover
`_import_source_cache[name]` is the second module, and with the entry popped
and the alias deleted a resolution binds the second module, not the first.
The memo was also written at resolution, before the alias check, so a trace
the check refused with `Import alias already bound` remembered the name all
the same. The cache is written only once the check has passed, alongside the
package record and `output.import_sources`: it is never cleared, so a write
before the check would pin a module the process may later drop on behalf of a
trace that bound nothing. Whether a name is one the cache can serve is decided
where `import_source` branches on it and carried to the write in a local,
`cacheable`: `False` in the `torch_package` arm, whose names resolve through
`_package_imported_modules`, a `WeakValueDictionary`
(`package_importer.py:731`) that holds a packaged module only while its
importer or the user does, so an entry would pin a `torch.package` module the
user has dropped for the rest of the process, and whose names are never read
back from the cache in any case, the read being in the other arm; `True` in
the `sys.modules` arm. A second `"torch_package" in module_name` test at the
write, a hundred lines below the first, would have to be kept in step with it
by hand; the local cannot drift. The write is further guarded by
`isinstance(value, types.ModuleType)`: `sys.modules` accepts any object, and a
non-module entry, which the callers without a module check bind verbatim, is
never remembered, so the cache's `dict[str, types.ModuleType]` annotation holds
by construction.

The live entry is read from `sys.modules` itself, and the memo no longer runs
in front of the read. What the memo's call cost for a present name depended on
the interpreter, since a cold memo is `importlib.import_module`: on 3.12
`_find_and_load` (`importlib/_bootstrap.py:1349-1356`) returns without
touching a lock unless the entry is missing or its `__spec__._initializing` is
set, but 3.10's (`:1022-1034`) has no such gate -- it enters
`_ModuleLockManager` and calls `_lock_unlock_module` for every name, each
through `_get_module_lock`, which brackets its body with the global import
lock (`:185`, `:211`), all of it under `compile_lock`. Measured in an earlier
revision of this commit with spies on `_get_module_lock` and
`_imp.acquire_lock`, resolving a present, initialized name through
`import_module`: 3.10.20, two module-lock and four global-import-lock
acquisitions and 5.5 us per call; 3.12.14, none and 388 ns. The `sys.modules`
read takes no lock on either. The import machinery is now entered in two
cases only: a name absent from `sys.modules` that no trace has resolved before
(a first import, as before), and a name blocked with `None` that no trace has
resolved before (which raises `ModuleNotFoundError`, as before). An entry
whose `__spec__._initializing` is set -- `_load_unlocked` (`:911-950`) sets it
around a first-time execution of the module body -- is served as is. An
earlier revision handed such an entry to `import_module` so the trace would
wait on the module lock as an import statement does; that branch is gone, for
the reason its review gave. From `IMPORT_NAME`, the one caller whose name the
traced bytecode chose, `__import__` has just returned the entry, and
`_find_and_load` already waited out a cross-thread initialization; what can
still be `_initializing` there is same-thread re-entrancy, a module body that
compiles a function importing the module itself, where `_ModuleLock.acquire`
short-circuits on its owner and `import_module` returns the same
half-initialized object, so the branch changed nothing (measured with such a
module at this tree: the spec's flag is set when the compile runs, the compile
succeeds, and the alias and the cache both hold the module itself). The only
caller family the branch could change a value for resolves a name without an
`__import__` of its own -- `get_globals_source_and_value`, the codegen names --
while another thread executes that module's body, and there `import_module`
blocks on that module's lock with `compile_lock` held; if the other thread's
body re-enters Dynamo it blocks on `compile_lock`, and importlib's deadlock
detection, which walks module-lock edges only, cannot see the cycle. The
comment at the read says so, so the next reader does not put the wait back.
The commit below waited in that case only while its memo was cold and served
the previous incarnation once warm; this commit serves the live entry as it
stands, which is what the same-thread case always got. No test pins it: the
observable difference is a two-thread timing, and the single-threaded dispatch
pin an earlier revision had (`..._waits_on_its_import`, which asserted the
`import_module` call, not a wait) went with the branch.

The resolution reads nothing off the module it resolves. The commit below's
`_import_module` made `_find_and_load`'s `getattr(module, "__spec__", None)`
on 3.11+ for the first resolution of each name per process, none on 3.10; here
no version reads an attribute off the module, and the alias check below reads
`__name__` out of the instance dicts as before.
`test_import_alias_check_does_not_run_a_module_getattribute` pins the
resolution as well as the check: its module class now raises on any read made
with `import_source` on the stack, matched by function name and module, and on
the commit below, on 3.12, the test errors with the module's raise reached from
`_find_and_load` under `_import_module`.

The write rule loses its condition. Below this commit a writer's same-named
module -- `CompilePackage.install()`, an artifact load seeding its guard scope
-- is replaced when the name is live and left in the slot when the name is
gone or blocked, the memo being no less stale than the writer's module. Now
`f_globals[alias] = value` runs unconditionally: `value` is the live entry
whenever `sys.modules` holds a module under the name, or the one a first import
has just put there, and what this process's traces last bound when the name is
gone or blocked with `None`; there neither module is the live entry, and the
cached one is the object the guards this alias roots were built against.
`test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`
pins it: a trace binds and caches one module, `install()` in the same globals
binds a second of the same name, and with the entry then popped, and again
with it set to `None`, a resolution replaces the installed module by the cached
one; on the commit below the installed module stays in the slot, both arms.

`_import_module` is deleted; its last caller is this read. The cache is never
cleared, not by `torch._dynamo.reset()` either, so a module the process has
dropped stays alive in it; the memo retained modules the same way, so this is
not new retention. The declaration comment is the one place that says so; an
earlier revision repeated it in `reset()`, next to nothing that read it. A
`reset()` that did clear the cache fails the removed-name test, whose deleted
and blocked compiles follow a `reset()`. Only names the traced bytecode never
imported can arrive absent or blocked: `IMPORT_NAME`'s own `__import__` has
just put its name back or raised, `get_globals_source_and_value` resolves only
a module it has just found live under the frame's `__name__`, and the other
callers pass torch's own or stdlib names for codegen. `torch.autograd.profiler`
is such a name: `codegen.py` resolves it on every compile under
`config.record_runtime_overhead` (on by default) for the runtime-overhead
record in the compiled frame's prologue, and the only function-scope import of
it in torch/ (`torch/profiler/_utils.py`) is off the compile path, so a trace
with the entry deleted has no other reason to re-import it. The removed-name
test, inherited from the commit below, uses it for that reason.

Order to review: `symbolic_convert.py`, the `_import_source_cache` declaration
replacing `_import_module`, then the `sys.modules` arm of `import_source` (the
read, the cache fallback, the `import_module` fallback and the comment on the
entry still initializing), the `cacheable` local in both arms, and the write
block (record, cache write, unconditional alias write); then `test_package.py`:
the gone-name test (the one new case), the frame-walk probe at the top of the
file and the extended getattribute test, the empty-slot test's cache pin and
comptime-driven resolution, the cache assertions in the refused-alias tests,
the `torch_package` test and the non-module-value test, and the teardowns,
where `_import_module.cache_clear()` becomes `_import_source_cache.pop(name,
None)` or goes.

Behaviour change against the commit below, pinned below: a name gone from
`sys.modules` or blocked there with `None` binds what `import_source` last
bound under it rather than the first object the process resolved
(`test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache`, its
resolution after the pop); a writer's same-named module in the slot is
replaced for a name gone or blocked
(`test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`);
the resolution reads no attribute off the module it resolves, where the memo's
`import_module` did on 3.11+ for the first resolution of a name
(`test_import_alias_check_does_not_run_a_module_getattribute`); a refused trace
remembers nothing under the name (`test_import_alias_taken_by_a_non_module_graph_breaks`,
`test_import_alias_the_trace_refused_is_not_recorded_for_install`, by mutation:
with the write moved above the check, five failures); a `torch_package` name
and a non-module value are bound but never remembered
(`test_import_alias_accepts_a_stale_torch_package_module`,
`test_import_alias_check_with_a_non_module_value_accepts_the_key_alone`, each
by mutation of the guard it pins); and an entry still executing its body is
served as is rather than waited on when the name is one no trace resolved
before, which no test pins (above). Not a change: a name removed from or
blocked in `sys.modules` between two traces still binds the module the program
holds, and the import machinery is not entered for it
(`test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module`,
which passes on the commit below, whose memo serves the name, and pins this
commit against a cache read dropped).

Test Plan:

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

One case joins the commit below's twenty-two: twenty-three `test_import_alias`
instances. Seven of the inherited ones gain cache assertions or a cache-driven
leg, three have comments reworded, and every teardown changes. The new one,
`test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`,
compiles a function importing a scratch module under a `CompilePackage`, saves
it, hands the `sys.modules` entry to a second module of the same name and
loads and installs the package, so `install()` binds the alias to the second
module while the cache holds the first; then, in two `subTest` arms with the
alias put back on the installed module before each, pops the entry, and sets
it to `None`, and compiles a probe whose bytecode never imports the name and
whose comptime callback calls `import_source(name, True)` on the live
translator as `IMPORT_NAME` does -- the function's own import statement cannot
run once the entry is gone -- pinning that the alias holds the first module
afterwards and, at the end, that the cache still does. The empty-slot test,
after its handover, asserts `_import_source_cache[name]` is the second module
and then, with the entry popped and the alias deleted, drives `import_source`
the same way from a probe compiled in the same globals, and asserts the
returned source names the alias and the alias binds the second module; an
earlier revision called the unbound method on a `types.SimpleNamespace`
translator, which bypassed the real `OutputGraph` and `CompilePackage`. Its
scratch name is now `torch_test_package_import_alias_handed_over`. The
extended getattribute test's `_ImportAliasHookedModule` used to raise on a
`__dict__` read anywhere, and now raises on any read made with
`InstructionTranslatorBase.import_source` on the Python stack, matched by
function name and by the frame's module (`__import__` and
`PythonModuleVariable` read `__spec__` and `__name__` off a module by design,
so the stack is the discriminator); with no read left for the hook to observe,
its positive control is static: the test asserts that
`InstructionTranslatorBase.import_source.__wrapped__` (the `cache_method`
wrapper keeps the function under `__wrapped__`) has the `co_name` and
`__module__` the walk matches, so a renamed or inlined `import_source` fails
there rather than letting every read through. The refused-alias tests:
`test_import_alias_taken_by_a_non_module_graph_breaks` pins, per case, that
neither the `fullgraph` refusal nor the skipped frame leaves the name in
`_import_source_cache`, and `test_import_alias_graph_break_is_cached_until_reset`
pins the name absent after the refusal and present, as the module, after the
compile that binds the alias; `test_import_alias_the_trace_refused_is_not_recorded_for_install`
pins the name absent from the cache after the checkpointed refusal and again
after `install()`. The two tests that reach the cache write with a value one
of its guards refuses each gain one `assertNotIn` on the cache:
`test_import_alias_accepts_a_stale_torch_package_module` asserts the mangled
name absent after its compile, and
`test_import_alias_check_with_a_non_module_value_accepts_the_key_alone` asserts
the key absent after its accepted call. The removed-name test's comment and
teardown lose the memo, and the installed-live-module test's and the nn hook
test's comments no longer say "memo", the helper being gone.
Every `test_import_alias` test whose scratch name gets cached pops it from
`_import_source_cache` in `finally`, alongside the alias and the entry --
sixteen at this commit, in place of the `_import_module.cache_clear()` that
named the deleted helper: the pop only matters where a later compile runs with
the name absent or blocked, but one teardown shape keeps a test-minted module
from outliving its test either way. Six have nothing to pop, and the commit
below's `cache_clear()` simply goes: `test_import_alias_the_trace_refused_is_not_recorded_for_install`,
whose one trace is refused before the write and which asserts the name absent
instead; `test_import_alias_is_not_bound_to_a_non_module_import`, whose entry
`IMPORT_NAME` rejects before `import_source` runs, and a non-module is never
cached in any case; `test_import_alias_accepts_a_stale_torch_package_module`
and `test_import_alias_taken_in_a_torch_package_slot_is_a_hard_error`, whose
names take the `torch_package` arm, which never writes the cache (the first
asserts that); and `test_import_alias_taken_at_codegen_is_a_hard_error` and
the removed-name test, whose name is `torch.autograd.profiler` and whose
cached object is the process's own module, which a pop would not free and the
next compile re-caches.

Measured against the commit below's `symbolic_convert.py`, checked out under
this test file with a stub `_import_source_cache = {}` added so the file
imports: four of the twenty-three fail there. The getattribute test errors on
3.12 with `InternalTorchDynamoError: RuntimeError: module __getattribute__
read __spec__ inside a trace`, the read made by `_find_and_load`
(`_bootstrap.py:1356`) under `_import_module`; the gone-name test fails both
arms on `assertIs(fn.__globals__[alias], old)`, the installed module left in
the slot, and then errors on its closing cache pin against the empty stub; the
empty-slot test errors with `KeyError` on `_import_source_cache[name]`,
nothing having written the cache; and
`test_import_alias_graph_break_is_cached_until_reset` errors the same way on
its `assertIs(_import_source_cache[name], module)` after the compile that binds
the alias. The other nineteen pass there, the removed-name test, whose memo
serves the name, and the `assertNotIn`s on an empty stub among them. Those are
pinned at this tree by mutation of `symbolic_convert.py`, each mutant run
against the twenty-three and restored afterwards: with the write gated as the
commit below gates it (alias absent, or holding the value, or the name live),
the gone-name test fails both arms (and the `torch_package` test errors, that
gate reading its name, which is never in `sys.modules`, as not live); with the
cache write made `_import_source_cache.setdefault(module_name, value)` -- a
first-resolution memo one indirection further in -- the empty-slot test alone
fails, on `assertIs(_import_source_cache[name], new)` after the handover; with
the cache read dropped, importing whenever the entry is absent, the
removed-name test fails its deleted case on the spy (`'torch.autograd.profiler'
unexpectedly found in ['torch.autograd.profiler']`) and errors its blocked
case with `InternalTorchDynamoError: ModuleNotFoundError: import of
torch.autograd.profiler halted; None in sys.modules`, and the empty-slot and
gone-name resolutions error with `ModuleNotFoundError` for their scratch
names; with the `torch_package` arm's `cacheable` flipped to `True`, the
`torch_package` test alone fails; with the `isinstance(value,
types.ModuleType)` conjunct dropped from the write, the non-module-value test
alone fails; with the cache write moved above the alias check, five failures,
`assertNotIn` in each of the three `taken_by_a_non_module` cases, in
`cached_until_reset` and in the install test; and with a
`getattr(value, "__spec__", None)` added to the resolution, the getattribute
test alone errors, with the hook's `RuntimeError`. Neither of the two guard
mutants changes what a compile binds today -- one pins a dropped
`torch.package` module for the process, the other opens a path `IMPORT_NAME`
blocks -- so the annotation and the comments at the write are held by those
two assertions and by nothing else. On this commit the twenty-three pass and
the whole file is 101 tests, OK (skipped=40, expected failures=1).

```
python test/dynamo/test_package.py -k test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache
python test/dynamo/test_package.py -k test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module
python test/dynamo/test_package.py -k test_import_alias_check_does_not_run_a_module_getattribute
python test/dynamo/test_package.py -k test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache
python test/dynamo/test_package.py -k test_import_alias_taken_by_a_non_module_graph_breaks -k test_import_alias_graph_break_is_cached_until_reset -k test_import_alias_the_trace_refused_is_not_recorded_for_install
python test/dynamo/test_package.py -k test_import_alias_accepts_a_stale_torch_package_module
python test/dynamo/test_package.py -k test_import_alias_check_with_a_non_module_value_accepts_the_key_alone
```

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

> **FAQ: the `_initializing` -> `importlib.import_module` branch cannot change `value` on the one caller that can reach it from traced bytecode, since `IMPORT_NAME`'s `__import__` has just waited, and its one effectful path -- a codegen or `get_globals_source_and_value` caller resolving a name another thread is executing -- blocks on that module's lock under `compile_lock`, a lock-order cross `_has_deadlocked` cannot see. Drop it and serve the entry as is, or state the hazard at the call site.**
>
> Dropped, and the hazard is stated where the wait would go. Reachability was probed at this tree with a scratch module whose body compiles a function that imports the module itself: `IMPORT_NAME`'s `__import__` hands back the entry with `__spec__._initializing` still `True`, the compile succeeds, and the alias and `_import_source_cache` both hold that module -- the object `import_module` would have returned too, its lock being owned by the same thread. So from `IMPORT_NAME` the branch was two lock acquisitions for nothing, and from the callers with no `__import__` of their own it was the wait the finding describes, per compile rather than once per process. What is given up is the single-threaded dispatch pin (`..._waits_on_its_import` asserted that `import_module` was asked, not that anything waited) and the two-thread measurement an earlier revision made; the commit below waited in that case only while its memo was cold, and once warm served the previous incarnation, so no tree in this stack has made that wait reliably. `test_import_alias_check_does_not_run_a_module_getattribute` no longer plants a spec with a raising `_initializing` property, since nothing reads a spec. With the branch went `import importlib.machinery` in both files and the `_ImportAliasProbeSpec` helper.

> **FAQ: dropping the `if not conflict or live:` gate for an unconditional `f_globals[alias] = value` is a reachable behaviour change no test covers: the alias bound by `install()` or `_seed_guard_scope()` to a same-named but different module, which the name check accepts, and the name then absent from `sys.modules` or blocked with `None`. Add a pin.**
>
> Added: `test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`, two independent resolutions of one name (a trace under a `CompilePackage`, then `install()` of that package after a handover) and its removal, in a deleted arm and a `None` arm. On the commit below both arms fail on `assertIs(fn.__globals__[alias], old)`, the installed module left in the slot; here both pass, and with this tree's write gated the way the commit below gates it, both fail again. The write is reached through the live translator from a comptime callback, because the traced function's own import cannot run with the entry gone.

> **FAQ: the empty-slot test hand-rolls a `types.SimpleNamespace` translator and calls the unbound `InstructionTranslatorBase.import_source(tx, name)`, bypassing the real `OutputGraph` and `CompilePackage`; the file already drives `import_source` on a resolution no bytecode reaches through a comptime callback on the live translator. Use that shape.**
>
> Done: after the handover and the pop, a probe function whose bytecode never imports the name is compiled in the same globals, and its comptime callback calls `tx.import_source(name, True)` on the live translator, as `IMPORT_NAME` would; the test asserts the returned source's `global_name` is the alias and that the alias binds the second module. The new gone-name test uses the same shape. The `setdefault` mutant is still the one failure among the twenty-three, on the cache pin after the handover.

> **FAQ: the comment in `torch/_dynamo/__init__.py:171-174` restates the declaration comment and dangles above an unrelated call; the 16-line and 9-line comments at the read and the write restate CPython internals. Drop the first, trim the others to the load-bearing facts.**
>
> The `__init__.py` comment is gone, and this commit no longer touches that file; the declaration says the cache is never cleared, `reset()` included. The read's comment is down to what a reader needs at the site -- the live entry is what `IMPORT_NAME` pushed, `import_module` takes the module lock for a present name on 3.10, a removed or blocked name keeps what it last resolved to because re-importing would run the module body inside the trace, and an initializing entry is served as is with the lock-order reason -- and the write's to which module wins and why. The derivations are in this message.

> **FAQ: nothing pins that `_import_source_cache` holds what `import_source` last bound under a name rather than the first thing it resolved: `_import_source_cache.setdefault(module_name, value)` passes the whole `test_import_alias` family. Extend the empty-slot test, which already hands a name over from `old` to `new`, with one more compile after `sys.modules.pop(name)`, asserting the alias binds `new` and not `old`.**
>
> Pinned there, with the resolution driven from a probe rather than by the test function's own import. That import statement cannot run once the entry is popped: measured at this tree, eager raises `ModuleNotFoundError` and the compile raises `Unsupported: Import failure` before `import_source` runs, binding nothing. The cache read is reached from a compile only for a name the traced bytecode never imports -- codegen's `torch.autograd.profiler`, which the removed-name test uses and which is one module object throughout -- so the empty-slot test asserts `_import_source_cache[name] is new` after its handover and then, with the entry popped and the alias deleted, compiles a probe whose comptime callback calls `import_source(name, True)` on the live translator, and asserts the alias binds `new`. The `setdefault` mutant is the one failure among the twenty-three, on the first assertion.

> **FAQ: "A writer's same-named module is replaced: value is the live entry whenever there is one" licenses dropping the old gate, and it is not true in one reachable case: for a name blocked with `None`, `.get` returned `None`, which `is not value`, so the old code kept a writer's binding of a different same-named object and this code overwrites it.**
>
> The case is as described, and it is now pinned by the gone-name test's `None` arm as well as its deleted arm: two writers (`install()`, an AOT load seeding its guard scope) resolve independently through `import_module`, so a `None`-blocked name can find the alias bound to one same-named object while the cache holds another, and the name check passes since both answer the same `__name__`. The commit below kept the writer's module in both absent forms (its gate is `live`, an entry present under the name); now both replace it, and the comment at the write says which object wins and why: neither is live, and the cached one is what this process's traces bound and built guards against.

> **FAQ: five pre-existing tests lost `_import_module.cache_clear()` from their `finally` without gaining `_import_source_cache.pop(name, None)`, while the new tests pop; that is two teardown conventions in one file and a process-lifetime strong reference to each test-minted `ModuleType`.**
>
> Every test whose scratch name gets cached pops now -- sixteen at this commit, the accepted-names fixture and the non-module-value test among them -- and the message says when the pop is load-bearing: only where a later compile runs with the name absent or blocked. Six `test_import_alias` tests have no pop, deliberately: the refused-alias install test's one trace is refused before the cache write, which sits below the alias check, and the test asserts the name absent from the cache instead; the removed-name test's and the codegen test's name is `torch.autograd.profiler` and the object cached is the process's own module, which the pop would not free and the next test re-caches; the non-module import test's entry never reaches `import_source`, `IMPORT_NAME` rejecting it first, and would not be cached if it did; and the two `torch_package` tests' names take the arm that never writes the cache. The commit below cleared the memo in all of those; the line simply goes here.

> **FAQ: `_import_source_cache: dict[str, types.ModuleType]` is not what the code stores: `sys.modules` accepts any object, yet the write caches `value` unconditionally, so a non-module can be cached and later served and bound. Annotate the cache `dict[str, Any]` and say why, or hoist the `isinstance` so a non-module is never cached.**
>
> Hoisted, in the sense that keeps the annotation honest: the cache write is guarded by `isinstance(value, types.ModuleType)`, on the value finally resolved, together with the `cacheable` local the `sys.modules` arm sets, and sits below the alias check with the package record and `output.import_sources`, so a non-module reaching `import_source` is bound as is by the callers that make no module check and remembered by nothing. `test_import_alias_check_with_a_non_module_value_accepts_the_key_alone` pins it, reaching the write from a comptime callback on the live translator with a `SimpleNamespace` under the key and asserting the key absent from `_import_source_cache` after the accepted call; with the conjunct dropped it fails there. It is not pinned by the existing non-module test, which cannot reach the write: `IMPORT_NAME` is the one caller whose name the traced code chose, and it graph-breaks on `Bad import result` before `import_source` runs (that test's own point).

> **FAQ: the "zero lock acquisitions" measurement rests on the `_initializing` gate at `_bootstrap.py:1355-1356`, which does not exist before CPython 3.11; on 3.10 `_find_and_load` takes the module lock and calls `_lock_unlock_module` unconditionally, under `compile_lock`, on every compile. Either measure it there or serve a live initialized `sys.modules` entry directly.**
>
> The second option is taken. The earlier answer was measured on 3.12 only, and 3.10.20 gives the opposite result: `importlib.import_module` of a present, initialized name is two `_get_module_lock` calls and four `_imp.acquire_lock` calls and 5.5 us per call, against none and 388 ns on 3.12.14. `import_source` now reads `sys.modules` itself: a present entry is served as is, with no lock on either version, and `import_module` is reached only for an absent or `None` entry the cache has not seen -- a first import or the blocked-module raise, both as before -- so the cost is the same on every supported interpreter.

> **FAQ: dropping the process-wide memo means every compile re-enters CPython's module-lock path, which can raise `_DeadlockError` or hang while `compile_lock` is held: thread A executes module `M`'s body, thread B compiles a frame whose globals are `M.__dict__` and blocks on `M`'s lock under `compile_lock`, and if A's body compiles the two deadlock.**
>
> No compile enters the module-lock path for a present entry now, initializing or not: `import_source` reads `sys.modules` and serves what it finds, and `import_module` is reached only for a name absent or blocked that no trace has resolved before, exactly where the commit below's cold memo reached it. The scenario the finding describes -- B blocked on `M`'s lock under `compile_lock` while A's body wants `compile_lock` -- is the one the dropped `_initializing` branch would have walked into per compile, and the comment at the read names it as the reason the entry is served as is. `_DeadlockError` itself needs A to be blocked on a module lock B holds (`_ModuleLock.has_deadlock` walks `_blocking_on`), which B, holding no module lock, cannot cause; a wait on `compile_lock` is invisible to that walk, so the outcome of the dropped branch was a hang, not an error.

> **FAQ: `CompilePackage.install()` is the other writer of the same `__import_*` alias, and it resolves with a bare `importlib.import_module(module_name)`, so a name gone from `sys.modules` at install time raises `ModuleNotFoundError` out of `install()`, the failure mode the removed-name test rules out for the tracing side. Share the resolution helper, or say why `install()` is exempt.**
>
> Exempt, because neither hazard the cache guards against exists at install time. The cache exists so that a trace never runs a module body -- `import_source` is called from guard construction, inside the compile -- and never turns `ModuleNotFoundError` into an `InternalTorchDynamoError` with no eager fallback. `install()` runs in the user's own call, outside any trace: measured in an earlier revision, with the name deleted it raises `builtins.ModuleNotFoundError: No module named '...'`, and blocked with `None` it raises `import of ... halted; None in sys.modules`, both plain, both what the program's own `import` statement raises at that point, and a re-import there is an ordinary import at an ordinary time. Sharing the cache would also change nothing in the case the finding describes: a process that only loads has traced nothing, so the cache is empty, and the helper would fall through to `import_module` exactly as `install()` does today. The tracing-side cache is about a trace's view of a name the program still holds; `install()` has no trace and no such view.

> **FAQ: dropping the `functools.cache`d `_import_module` means a name resolved earlier and then removed from `sys.modules` re-runs the import machinery inside the trace, executing the module body again or raising `ImportError` as an `InternalTorchDynamoError`; keep both properties with `importlib.import_module` when the name is in `sys.modules` and `_import_module` otherwise.**
>
> Fixed, though not with that shape: `_import_module` is gone, and a fallback to a second memo would have re-imported once for every name `import_source` had resolved live (the commit below measures exactly that order). `import_source` remembers what it last bound per name (`_import_source_cache`) and serves that when the name is gone from `sys.modules` or blocked there with `None`; a live entry is read from `sys.modules`. The reach is narrower than ten call sites suggest, and only codegen names can arrive absent: `IMPORT_NAME`'s `__import__` has just put its own name back, `get_globals_source_and_value` resolves only a module it has just found live under the frame's `__name__`, and probing the user-controlled paths in an earlier revision -- a sourceless context manager returned from the frame or live across a graph break, an `autograd.Function` via a call result or an attribute -- found each resolving only `torch`, `torch._dynamo.utils`, `torch._dynamo.graph_bytecode_inputs` and `torch.autograd.profiler`, all present. `test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module` pins the case with `torch.autograd.profiler` and a spy on `importlib.import_module`, so unrelated imports cannot fail it.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 834e470
Pull-Request: #197303
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 19, 2026
…ast bound

Split for review budget from `[dynamo] Bind the import alias to the live
sys.modules entry` (#197046), the commit directly below: that one makes
`import_source` bind the live `sys.modules` entry whenever there is one and
keeps the memoized `_import_module` in front of that read, for a name since
removed from `sys.modules` or blocked there with `None`; this one replaces the
memo with a cache of what `import_source` last bound, written only once the
alias check has passed, and reads `sys.modules` with nothing in front of it.

`_import_module` is `functools.cache`d for the life of the process: it holds
the first object the process resolved under each name, and nothing clears it.
Below this commit it is what a name binds once the name has left `sys.modules`
-- `del sys.modules[...]`, a `mock.patch.dict(sys.modules)` scope -- or been
set to `None`, the import system's blocked-module sentinel that makes any
import of the name raise `ModuleNotFoundError`, because importing such a name
again would execute the module body inside the trace and bind a second copy of
a module the program still holds, or for `None` raise out of guard
construction (`ModuleNotFoundError` is not in `_compile`'s pass-through tuple,
so that raise surfaces as `InternalTorchDynamoError` with no eager fallback).
But the first resolution is the wrong object to fall back on for the same
reason it was the wrong object to bind: after a handover the traces have been
binding the live module and building guards against it, and the memo still
holds the module before the handover. And the memo is only warm for a name
some trace resolved while it was live: the commit below measures that a memo
cold for a deleted or blocked name imports inside guard construction all the
same, whichever order it and `sys.modules` are read in. `_import_source_cache`
replaces it, keyed by name, holding what `import_source` last bound: each
accepted resolution overwrites the entry, so a name that then leaves
`sys.modules` binds the module the guards this alias roots were built against,
not the one the process saw first.
`test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache`,
inherited from the commit below, gains that pin: after its handover
`_import_source_cache[name]` is the second module, and with the entry popped
and the alias deleted a resolution binds the second module, not the first.
The memo was also written at resolution, before the alias check, so a trace
the check refused with `Import alias already bound` remembered the name all
the same. The cache is written only once the check has passed, alongside the
package record and `output.import_sources`: it is never cleared, so a write
before the check would pin a module the process may later drop on behalf of a
trace that bound nothing. Whether a name is one the cache can serve is decided
where `import_source` branches on it and carried to the write in a local,
`cacheable`: `False` in the `torch_package` arm, whose names resolve through
`_package_imported_modules`, a `WeakValueDictionary`
(`package_importer.py:731`) that holds a packaged module only while its
importer or the user does, so an entry would pin a `torch.package` module the
user has dropped for the rest of the process, and whose names are never read
back from the cache in any case, the read being in the other arm; `True` in
the `sys.modules` arm. A second `"torch_package" in module_name` test at the
write, a hundred lines below the first, would have to be kept in step with it
by hand; the local cannot drift. The write is further guarded by
`isinstance(value, types.ModuleType)`: `sys.modules` accepts any object, and a
non-module entry, which the callers without a module check bind verbatim, is
never remembered, so the cache's `dict[str, types.ModuleType]` annotation holds
by construction.

The live entry is read from `sys.modules` itself, and the memo no longer runs
in front of the read. What the memo's call cost for a present name depended on
the interpreter, since a cold memo is `importlib.import_module`: on 3.12
`_find_and_load` (`importlib/_bootstrap.py:1349-1356`) returns without
touching a lock unless the entry is missing or its `__spec__._initializing` is
set, but 3.10's (`:1022-1034`) has no such gate -- it enters
`_ModuleLockManager` and calls `_lock_unlock_module` for every name, each
through `_get_module_lock`, which brackets its body with the global import
lock (`:185`, `:211`), all of it under `compile_lock`. Measured in an earlier
revision of this commit with spies on `_get_module_lock` and
`_imp.acquire_lock`, resolving a present, initialized name through
`import_module`: 3.10.20, two module-lock and four global-import-lock
acquisitions and 5.5 us per call; 3.12.14, none and 388 ns. The `sys.modules`
read takes no lock on either. The import machinery is now entered in two
cases only: a name absent from `sys.modules` that no trace has resolved before
(a first import, as before), and a name blocked with `None` that no trace has
resolved before (which raises `ModuleNotFoundError`, as before). An entry
whose `__spec__._initializing` is set -- `_load_unlocked` (`:911-950`) sets it
around a first-time execution of the module body -- is served as is. An
earlier revision handed such an entry to `import_module` so the trace would
wait on the module lock as an import statement does; that branch is gone, for
the reason its review gave. From `IMPORT_NAME`, the one caller whose name the
traced bytecode chose, `__import__` has just returned the entry, and
`_find_and_load` already waited out a cross-thread initialization; what can
still be `_initializing` there is same-thread re-entrancy, a module body that
compiles a function importing the module itself, where `_ModuleLock.acquire`
short-circuits on its owner and `import_module` returns the same
half-initialized object, so the branch changed nothing (measured with such a
module at this tree: the spec's flag is set when the compile runs, the compile
succeeds, and the alias and the cache both hold the module itself). The only
caller family the branch could change a value for resolves a name without an
`__import__` of its own -- `get_globals_source_and_value`, the codegen names --
while another thread executes that module's body, and there `import_module`
blocks on that module's lock with `compile_lock` held; if the other thread's
body re-enters Dynamo it blocks on `compile_lock`, and importlib's deadlock
detection, which walks module-lock edges only, cannot see the cycle. The
comment at the read says so, so the next reader does not put the wait back.
The commit below waited in that case only while its memo was cold and served
the previous incarnation once warm; this commit serves the live entry as it
stands, which is what the same-thread case always got. No test pins it: the
observable difference is a two-thread timing, and the single-threaded dispatch
pin an earlier revision had (`..._waits_on_its_import`, which asserted the
`import_module` call, not a wait) went with the branch.

The resolution reads nothing off the module it resolves. The commit below's
`_import_module` made `_find_and_load`'s `getattr(module, "__spec__", None)`
on 3.11+ for the first resolution of each name per process, none on 3.10; here
no version reads an attribute off the module, and the alias check below reads
`__name__` out of the instance dicts as before.
`test_import_alias_check_does_not_run_a_module_getattribute` pins the
resolution as well as the check: its module class now raises on any read made
with `import_source` on the stack, matched by function name and module, and on
the commit below, on 3.12, the test errors with the module's raise reached from
`_find_and_load` under `_import_module`.

The write rule loses its condition. Below this commit a writer's same-named
module -- `CompilePackage.install()`, an artifact load seeding its guard scope
-- is replaced when the name is live and left in the slot when the name is
gone or blocked, the memo being no less stale than the writer's module. Now
`f_globals[alias] = value` runs unconditionally: `value` is the live entry
whenever `sys.modules` holds a module under the name, or the one a first import
has just put there, and what this process's traces last bound when the name is
gone or blocked with `None`; there neither module is the live entry, and the
cached one is the object the guards this alias roots were built against.
`test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`
pins it: a trace binds and caches one module, `install()` in the same globals
binds a second of the same name, and with the entry then popped, and again
with it set to `None`, a resolution replaces the installed module by the cached
one; on the commit below the installed module stays in the slot, both arms.

`_import_module` is deleted; its last caller is this read. The cache is never
cleared, not by `torch._dynamo.reset()` either, so a module the process has
dropped stays alive in it; the memo retained modules the same way, so this is
not new retention. The declaration comment is the one place that says so; an
earlier revision repeated it in `reset()`, next to nothing that read it. A
`reset()` that did clear the cache fails the removed-name test, whose deleted
and blocked compiles follow a `reset()`. Only names the traced bytecode never
imported can arrive absent or blocked: `IMPORT_NAME`'s own `__import__` has
just put its name back or raised, `get_globals_source_and_value` resolves only
a module it has just found live under the frame's `__name__`, and the other
callers pass torch's own or stdlib names for codegen. `torch.autograd.profiler`
is such a name: `codegen.py` resolves it on every compile under
`config.record_runtime_overhead` (on by default) for the runtime-overhead
record in the compiled frame's prologue, and the only function-scope import of
it in torch/ (`torch/profiler/_utils.py`) is off the compile path, so a trace
with the entry deleted has no other reason to re-import it. The removed-name
test, inherited from the commit below, uses it for that reason.

Order to review: `symbolic_convert.py`, the `_import_source_cache` declaration
replacing `_import_module`, then the `sys.modules` arm of `import_source` (the
read, the cache fallback, the `import_module` fallback and the comment on the
entry still initializing), the `cacheable` local in both arms, and the write
block (record, cache write, unconditional alias write); then `test_package.py`:
the gone-name test (the one new case), the frame-walk probe at the top of the
file and the extended getattribute test, the empty-slot test's cache pin and
comptime-driven resolution, the cache assertions in the refused-alias tests,
the `torch_package` test and the non-module-value test, and the teardowns,
where `_import_module.cache_clear()` becomes `_import_source_cache.pop(name,
None)` or goes.

Behaviour change against the commit below, pinned below: a name gone from
`sys.modules` or blocked there with `None` binds what `import_source` last
bound under it rather than the first object the process resolved
(`test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache`, its
resolution after the pop); a writer's same-named module in the slot is
replaced for a name gone or blocked
(`test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`);
the resolution reads no attribute off the module it resolves, where the memo's
`import_module` did on 3.11+ for the first resolution of a name
(`test_import_alias_check_does_not_run_a_module_getattribute`); a refused trace
remembers nothing under the name (`test_import_alias_taken_by_a_non_module_graph_breaks`,
`test_import_alias_the_trace_refused_is_not_recorded_for_install`, by mutation:
with the write moved above the check, five failures); a `torch_package` name
and a non-module value are bound but never remembered
(`test_import_alias_accepts_a_stale_torch_package_module`,
`test_import_alias_check_with_a_non_module_value_accepts_the_key_alone`, each
by mutation of the guard it pins); and an entry still executing its body is
served as is rather than waited on when the name is one no trace resolved
before, which no test pins (above). Not a change: a name removed from or
blocked in `sys.modules` between two traces still binds the module the program
holds, and the import machinery is not entered for it
(`test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module`,
which passes on the commit below, whose memo serves the name, and pins this
commit against a cache read dropped).

Test Plan:

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

One case joins the commit below's twenty-two: twenty-three `test_import_alias`
instances. Seven of the inherited ones gain cache assertions or a cache-driven
leg, three have comments reworded, and every teardown changes. The new one,
`test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`,
compiles a function importing a scratch module under a `CompilePackage`, saves
it, hands the `sys.modules` entry to a second module of the same name and
loads and installs the package, so `install()` binds the alias to the second
module while the cache holds the first; then, in two `subTest` arms with the
alias put back on the installed module before each, pops the entry, and sets
it to `None`, and compiles a probe whose bytecode never imports the name and
whose comptime callback calls `import_source(name, True)` on the live
translator as `IMPORT_NAME` does -- the function's own import statement cannot
run once the entry is gone -- pinning that the alias holds the first module
afterwards and, at the end, that the cache still does. The empty-slot test,
after its handover, asserts `_import_source_cache[name]` is the second module
and then, with the entry popped and the alias deleted, drives `import_source`
the same way from a probe compiled in the same globals, and asserts the
returned source names the alias and the alias binds the second module; an
earlier revision called the unbound method on a `types.SimpleNamespace`
translator, which bypassed the real `OutputGraph` and `CompilePackage`. Its
scratch name is now `torch_test_package_import_alias_handed_over`. The
extended getattribute test's `_ImportAliasHookedModule` used to raise on a
`__dict__` read anywhere, and now raises on any read made with
`InstructionTranslatorBase.import_source` on the Python stack, matched by
function name and by the frame's module (`__import__` and
`PythonModuleVariable` read `__spec__` and `__name__` off a module by design,
so the stack is the discriminator); with no read left for the hook to observe,
its positive control is static: the test asserts that
`InstructionTranslatorBase.import_source.__wrapped__` (the `cache_method`
wrapper keeps the function under `__wrapped__`) has the `co_name` and
`__module__` the walk matches, so a renamed or inlined `import_source` fails
there rather than letting every read through. The refused-alias tests:
`test_import_alias_taken_by_a_non_module_graph_breaks` pins, per case, that
neither the `fullgraph` refusal nor the skipped frame leaves the name in
`_import_source_cache`, and `test_import_alias_graph_break_is_cached_until_reset`
pins the name absent after the refusal and present, as the module, after the
compile that binds the alias; `test_import_alias_the_trace_refused_is_not_recorded_for_install`
pins the name absent from the cache after the checkpointed refusal and again
after `install()`. The two tests that reach the cache write with a value one
of its guards refuses each gain one `assertNotIn` on the cache:
`test_import_alias_accepts_a_stale_torch_package_module` asserts the mangled
name absent after its compile, and
`test_import_alias_check_with_a_non_module_value_accepts_the_key_alone` asserts
the key absent after its accepted call. The removed-name test's comment and
teardown lose the memo, and the installed-live-module test's and the nn hook
test's comments no longer say "memo", the helper being gone.
Every `test_import_alias` test whose scratch name gets cached pops it from
`_import_source_cache` in `finally`, alongside the alias and the entry --
sixteen at this commit, in place of the `_import_module.cache_clear()` that
named the deleted helper: the pop only matters where a later compile runs with
the name absent or blocked, but one teardown shape keeps a test-minted module
from outliving its test either way. Six have nothing to pop, and the commit
below's `cache_clear()` simply goes: `test_import_alias_the_trace_refused_is_not_recorded_for_install`,
whose one trace is refused before the write and which asserts the name absent
instead; `test_import_alias_is_not_bound_to_a_non_module_import`, whose entry
`IMPORT_NAME` rejects before `import_source` runs, and a non-module is never
cached in any case; `test_import_alias_accepts_a_stale_torch_package_module`
and `test_import_alias_taken_in_a_torch_package_slot_is_a_hard_error`, whose
names take the `torch_package` arm, which never writes the cache (the first
asserts that); and `test_import_alias_taken_at_codegen_is_a_hard_error` and
the removed-name test, whose name is `torch.autograd.profiler` and whose
cached object is the process's own module, which a pop would not free and the
next compile re-caches.

Measured against the commit below's `symbolic_convert.py`, checked out under
this test file with a stub `_import_source_cache = {}` added so the file
imports: four of the twenty-three fail there. The getattribute test errors on
3.12 with `InternalTorchDynamoError: RuntimeError: module __getattribute__
read __spec__ inside a trace`, the read made by `_find_and_load`
(`_bootstrap.py:1356`) under `_import_module`; the gone-name test fails both
arms on `assertIs(fn.__globals__[alias], old)`, the installed module left in
the slot, and then errors on its closing cache pin against the empty stub; the
empty-slot test errors with `KeyError` on `_import_source_cache[name]`,
nothing having written the cache; and
`test_import_alias_graph_break_is_cached_until_reset` errors the same way on
its `assertIs(_import_source_cache[name], module)` after the compile that binds
the alias. The other nineteen pass there, the removed-name test, whose memo
serves the name, and the `assertNotIn`s on an empty stub among them. Those are
pinned at this tree by mutation of `symbolic_convert.py`, each mutant run
against the twenty-three and restored afterwards: with the write gated as the
commit below gates it (alias absent, or holding the value, or the name live),
the gone-name test fails both arms (and the `torch_package` test errors, that
gate reading its name, which is never in `sys.modules`, as not live); with the
cache write made `_import_source_cache.setdefault(module_name, value)` -- a
first-resolution memo one indirection further in -- the empty-slot test alone
fails, on `assertIs(_import_source_cache[name], new)` after the handover; with
the cache read dropped, importing whenever the entry is absent, the
removed-name test fails its deleted case on the spy (`'torch.autograd.profiler'
unexpectedly found in ['torch.autograd.profiler']`) and errors its blocked
case with `InternalTorchDynamoError: ModuleNotFoundError: import of
torch.autograd.profiler halted; None in sys.modules`, and the empty-slot and
gone-name resolutions error with `ModuleNotFoundError` for their scratch
names; with the `torch_package` arm's `cacheable` flipped to `True`, the
`torch_package` test alone fails; with the `isinstance(value,
types.ModuleType)` conjunct dropped from the write, the non-module-value test
alone fails; with the cache write moved above the alias check, five failures,
`assertNotIn` in each of the three `taken_by_a_non_module` cases, in
`cached_until_reset` and in the install test; and with a
`getattr(value, "__spec__", None)` added to the resolution, the getattribute
test alone errors, with the hook's `RuntimeError`. Neither of the two guard
mutants changes what a compile binds today -- one pins a dropped
`torch.package` module for the process, the other opens a path `IMPORT_NAME`
blocks -- so the annotation and the comments at the write are held by those
two assertions and by nothing else. On this commit the twenty-three pass and
the whole file is 101 tests, OK (skipped=40, expected failures=1).

```
python test/dynamo/test_package.py -k test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache
python test/dynamo/test_package.py -k test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module
python test/dynamo/test_package.py -k test_import_alias_check_does_not_run_a_module_getattribute
python test/dynamo/test_package.py -k test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache
python test/dynamo/test_package.py -k test_import_alias_taken_by_a_non_module_graph_breaks -k test_import_alias_graph_break_is_cached_until_reset -k test_import_alias_the_trace_refused_is_not_recorded_for_install
python test/dynamo/test_package.py -k test_import_alias_accepts_a_stale_torch_package_module
python test/dynamo/test_package.py -k test_import_alias_check_with_a_non_module_value_accepts_the_key_alone
```

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

> **FAQ: the `_initializing` -> `importlib.import_module` branch cannot change `value` on the one caller that can reach it from traced bytecode, since `IMPORT_NAME`'s `__import__` has just waited, and its one effectful path -- a codegen or `get_globals_source_and_value` caller resolving a name another thread is executing -- blocks on that module's lock under `compile_lock`, a lock-order cross `_has_deadlocked` cannot see. Drop it and serve the entry as is, or state the hazard at the call site.**
>
> Dropped, and the hazard is stated where the wait would go. Reachability was probed at this tree with a scratch module whose body compiles a function that imports the module itself: `IMPORT_NAME`'s `__import__` hands back the entry with `__spec__._initializing` still `True`, the compile succeeds, and the alias and `_import_source_cache` both hold that module -- the object `import_module` would have returned too, its lock being owned by the same thread. So from `IMPORT_NAME` the branch was two lock acquisitions for nothing, and from the callers with no `__import__` of their own it was the wait the finding describes, per compile rather than once per process. What is given up is the single-threaded dispatch pin (`..._waits_on_its_import` asserted that `import_module` was asked, not that anything waited) and the two-thread measurement an earlier revision made; the commit below waited in that case only while its memo was cold, and once warm served the previous incarnation, so no tree in this stack has made that wait reliably. `test_import_alias_check_does_not_run_a_module_getattribute` no longer plants a spec with a raising `_initializing` property, since nothing reads a spec. With the branch went `import importlib.machinery` in both files and the `_ImportAliasProbeSpec` helper.

> **FAQ: dropping the `if not conflict or live:` gate for an unconditional `f_globals[alias] = value` is a reachable behaviour change no test covers: the alias bound by `install()` or `_seed_guard_scope()` to a same-named but different module, which the name check accepts, and the name then absent from `sys.modules` or blocked with `None`. Add a pin.**
>
> Added: `test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`, two independent resolutions of one name (a trace under a `CompilePackage`, then `install()` of that package after a handover) and its removal, in a deleted arm and a `None` arm. On the commit below both arms fail on `assertIs(fn.__globals__[alias], old)`, the installed module left in the slot; here both pass, and with this tree's write gated the way the commit below gates it, both fail again. The write is reached through the live translator from a comptime callback, because the traced function's own import cannot run with the entry gone.

> **FAQ: the empty-slot test hand-rolls a `types.SimpleNamespace` translator and calls the unbound `InstructionTranslatorBase.import_source(tx, name)`, bypassing the real `OutputGraph` and `CompilePackage`; the file already drives `import_source` on a resolution no bytecode reaches through a comptime callback on the live translator. Use that shape.**
>
> Done: after the handover and the pop, a probe function whose bytecode never imports the name is compiled in the same globals, and its comptime callback calls `tx.import_source(name, True)` on the live translator, as `IMPORT_NAME` would; the test asserts the returned source's `global_name` is the alias and that the alias binds the second module. The new gone-name test uses the same shape. The `setdefault` mutant is still the one failure among the twenty-three, on the cache pin after the handover.

> **FAQ: the comment in `torch/_dynamo/__init__.py:171-174` restates the declaration comment and dangles above an unrelated call; the 16-line and 9-line comments at the read and the write restate CPython internals. Drop the first, trim the others to the load-bearing facts.**
>
> The `__init__.py` comment is gone, and this commit no longer touches that file; the declaration says the cache is never cleared, `reset()` included. The read's comment is down to what a reader needs at the site -- the live entry is what `IMPORT_NAME` pushed, `import_module` takes the module lock for a present name on 3.10, a removed or blocked name keeps what it last resolved to because re-importing would run the module body inside the trace, and an initializing entry is served as is with the lock-order reason -- and the write's to which module wins and why. The derivations are in this message.

> **FAQ: nothing pins that `_import_source_cache` holds what `import_source` last bound under a name rather than the first thing it resolved: `_import_source_cache.setdefault(module_name, value)` passes the whole `test_import_alias` family. Extend the empty-slot test, which already hands a name over from `old` to `new`, with one more compile after `sys.modules.pop(name)`, asserting the alias binds `new` and not `old`.**
>
> Pinned there, with the resolution driven from a probe rather than by the test function's own import. That import statement cannot run once the entry is popped: measured at this tree, eager raises `ModuleNotFoundError` and the compile raises `Unsupported: Import failure` before `import_source` runs, binding nothing. The cache read is reached from a compile only for a name the traced bytecode never imports -- codegen's `torch.autograd.profiler`, which the removed-name test uses and which is one module object throughout -- so the empty-slot test asserts `_import_source_cache[name] is new` after its handover and then, with the entry popped and the alias deleted, compiles a probe whose comptime callback calls `import_source(name, True)` on the live translator, and asserts the alias binds `new`. The `setdefault` mutant is the one failure among the twenty-three, on the first assertion.

> **FAQ: "A writer's same-named module is replaced: value is the live entry whenever there is one" licenses dropping the old gate, and it is not true in one reachable case: for a name blocked with `None`, `.get` returned `None`, which `is not value`, so the old code kept a writer's binding of a different same-named object and this code overwrites it.**
>
> The case is as described, and it is now pinned by the gone-name test's `None` arm as well as its deleted arm: two writers (`install()`, an AOT load seeding its guard scope) resolve independently through `import_module`, so a `None`-blocked name can find the alias bound to one same-named object while the cache holds another, and the name check passes since both answer the same `__name__`. The commit below kept the writer's module in both absent forms (its gate is `live`, an entry present under the name); now both replace it, and the comment at the write says which object wins and why: neither is live, and the cached one is what this process's traces bound and built guards against.

> **FAQ: five pre-existing tests lost `_import_module.cache_clear()` from their `finally` without gaining `_import_source_cache.pop(name, None)`, while the new tests pop; that is two teardown conventions in one file and a process-lifetime strong reference to each test-minted `ModuleType`.**
>
> Every test whose scratch name gets cached pops now -- sixteen at this commit, the accepted-names fixture and the non-module-value test among them -- and the message says when the pop is load-bearing: only where a later compile runs with the name absent or blocked. Six `test_import_alias` tests have no pop, deliberately: the refused-alias install test's one trace is refused before the cache write, which sits below the alias check, and the test asserts the name absent from the cache instead; the removed-name test's and the codegen test's name is `torch.autograd.profiler` and the object cached is the process's own module, which the pop would not free and the next test re-caches; the non-module import test's entry never reaches `import_source`, `IMPORT_NAME` rejecting it first, and would not be cached if it did; and the two `torch_package` tests' names take the arm that never writes the cache. The commit below cleared the memo in all of those; the line simply goes here.

> **FAQ: `_import_source_cache: dict[str, types.ModuleType]` is not what the code stores: `sys.modules` accepts any object, yet the write caches `value` unconditionally, so a non-module can be cached and later served and bound. Annotate the cache `dict[str, Any]` and say why, or hoist the `isinstance` so a non-module is never cached.**
>
> Hoisted, in the sense that keeps the annotation honest: the cache write is guarded by `isinstance(value, types.ModuleType)`, on the value finally resolved, together with the `cacheable` local the `sys.modules` arm sets, and sits below the alias check with the package record and `output.import_sources`, so a non-module reaching `import_source` is bound as is by the callers that make no module check and remembered by nothing. `test_import_alias_check_with_a_non_module_value_accepts_the_key_alone` pins it, reaching the write from a comptime callback on the live translator with a `SimpleNamespace` under the key and asserting the key absent from `_import_source_cache` after the accepted call; with the conjunct dropped it fails there. It is not pinned by the existing non-module test, which cannot reach the write: `IMPORT_NAME` is the one caller whose name the traced code chose, and it graph-breaks on `Bad import result` before `import_source` runs (that test's own point).

> **FAQ: the "zero lock acquisitions" measurement rests on the `_initializing` gate at `_bootstrap.py:1355-1356`, which does not exist before CPython 3.11; on 3.10 `_find_and_load` takes the module lock and calls `_lock_unlock_module` unconditionally, under `compile_lock`, on every compile. Either measure it there or serve a live initialized `sys.modules` entry directly.**
>
> The second option is taken. The earlier answer was measured on 3.12 only, and 3.10.20 gives the opposite result: `importlib.import_module` of a present, initialized name is two `_get_module_lock` calls and four `_imp.acquire_lock` calls and 5.5 us per call, against none and 388 ns on 3.12.14. `import_source` now reads `sys.modules` itself: a present entry is served as is, with no lock on either version, and `import_module` is reached only for an absent or `None` entry the cache has not seen -- a first import or the blocked-module raise, both as before -- so the cost is the same on every supported interpreter.

> **FAQ: dropping the process-wide memo means every compile re-enters CPython's module-lock path, which can raise `_DeadlockError` or hang while `compile_lock` is held: thread A executes module `M`'s body, thread B compiles a frame whose globals are `M.__dict__` and blocks on `M`'s lock under `compile_lock`, and if A's body compiles the two deadlock.**
>
> No compile enters the module-lock path for a present entry now, initializing or not: `import_source` reads `sys.modules` and serves what it finds, and `import_module` is reached only for a name absent or blocked that no trace has resolved before, exactly where the commit below's cold memo reached it. The scenario the finding describes -- B blocked on `M`'s lock under `compile_lock` while A's body wants `compile_lock` -- is the one the dropped `_initializing` branch would have walked into per compile, and the comment at the read names it as the reason the entry is served as is. `_DeadlockError` itself needs A to be blocked on a module lock B holds (`_ModuleLock.has_deadlock` walks `_blocking_on`), which B, holding no module lock, cannot cause; a wait on `compile_lock` is invisible to that walk, so the outcome of the dropped branch was a hang, not an error.

> **FAQ: `CompilePackage.install()` is the other writer of the same `__import_*` alias, and it resolves with a bare `importlib.import_module(module_name)`, so a name gone from `sys.modules` at install time raises `ModuleNotFoundError` out of `install()`, the failure mode the removed-name test rules out for the tracing side. Share the resolution helper, or say why `install()` is exempt.**
>
> Exempt, because neither hazard the cache guards against exists at install time. The cache exists so that a trace never runs a module body -- `import_source` is called from guard construction, inside the compile -- and never turns `ModuleNotFoundError` into an `InternalTorchDynamoError` with no eager fallback. `install()` runs in the user's own call, outside any trace: measured in an earlier revision, with the name deleted it raises `builtins.ModuleNotFoundError: No module named '...'`, and blocked with `None` it raises `import of ... halted; None in sys.modules`, both plain, both what the program's own `import` statement raises at that point, and a re-import there is an ordinary import at an ordinary time. Sharing the cache would also change nothing in the case the finding describes: a process that only loads has traced nothing, so the cache is empty, and the helper would fall through to `import_module` exactly as `install()` does today. The tracing-side cache is about a trace's view of a name the program still holds; `install()` has no trace and no such view.

> **FAQ: dropping the `functools.cache`d `_import_module` means a name resolved earlier and then removed from `sys.modules` re-runs the import machinery inside the trace, executing the module body again or raising `ImportError` as an `InternalTorchDynamoError`; keep both properties with `importlib.import_module` when the name is in `sys.modules` and `_import_module` otherwise.**
>
> Fixed, though not with that shape: `_import_module` is gone, and a fallback to a second memo would have re-imported once for every name `import_source` had resolved live (the commit below measures exactly that order). `import_source` remembers what it last bound per name (`_import_source_cache`) and serves that when the name is gone from `sys.modules` or blocked there with `None`; a live entry is read from `sys.modules`. The reach is narrower than ten call sites suggest, and only codegen names can arrive absent: `IMPORT_NAME`'s `__import__` has just put its own name back, `get_globals_source_and_value` resolves only a module it has just found live under the frame's `__name__`, and probing the user-controlled paths in an earlier revision -- a sourceless context manager returned from the frame or live across a graph break, an `autograd.Function` via a call result or an attribute -- found each resolving only `torch`, `torch._dynamo.utils`, `torch._dynamo.graph_bytecode_inputs` and `torch.autograd.profiler`, all present. `test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module` pins the case with `torch.autograd.profiler` and a spy on `importlib.import_module`, so unrelated imports cannot fail it.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: ecad603
Pull-Request: #197303
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 19, 2026
…ast bound

Split for review budget from `[dynamo] Bind the import alias to the live
sys.modules entry` (#197046), the commit directly below: that one makes
`import_source` bind the live `sys.modules` entry whenever there is one and
keeps the memoized `_import_module` in front of that read, for a name since
removed from `sys.modules` or blocked there with `None`; this one replaces the
memo with a cache of what `import_source` last bound, written only once the
alias check has passed, and reads `sys.modules` with nothing in front of it.

`_import_module` is `functools.cache`d for the life of the process: it holds
the first object the process resolved under each name, and nothing clears it.
Below this commit it is what a name binds once the name has left `sys.modules`
-- `del sys.modules[...]`, a `mock.patch.dict(sys.modules)` scope -- or been
set to `None`, the import system's blocked-module sentinel that makes any
import of the name raise `ModuleNotFoundError`, because importing such a name
again would execute the module body inside the trace and bind a second copy of
a module the program still holds, or for `None` raise out of guard
construction (`ModuleNotFoundError` is not in `_compile`'s pass-through tuple,
so that raise surfaces as `InternalTorchDynamoError` with no eager fallback).
But the first resolution is the wrong object to fall back on for the same
reason it was the wrong object to bind: after a handover the traces have been
binding the live module and building guards against it, and the memo still
holds the module before the handover. And the memo is only warm for a name
some trace resolved while it was live: the commit below measures that a memo
cold for a deleted or blocked name imports inside guard construction all the
same, whichever order it and `sys.modules` are read in. `_import_source_cache`
replaces it, keyed by name, holding what `import_source` last bound: each
accepted resolution overwrites the entry, so a name that then leaves
`sys.modules` binds the module the guards this alias roots were built against,
not the one the process saw first.
`test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache`,
inherited from the commit below, gains that pin: after its handover
`_import_source_cache[name]` is the second module, and with the entry popped
and the alias deleted a resolution binds the second module, not the first.
The memo was also written at resolution, before the alias check, so a trace
the check refused with `Import alias already bound` remembered the name all
the same. The cache is written only once the check has passed, alongside the
package record and `output.import_sources`: it is never cleared, so a write
before the check would pin a module the process may later drop on behalf of a
trace that bound nothing. Whether a name is one the cache can serve is decided
where `import_source` branches on it and carried to the write in a local,
`cacheable`: `False` in the `torch_package` arm, whose names resolve through
`_package_imported_modules`, a `WeakValueDictionary`
(`package_importer.py:731`) that holds a packaged module only while its
importer or the user does, so an entry would pin a `torch.package` module the
user has dropped for the rest of the process, and whose names are never read
back from the cache in any case, the read being in the other arm; `True` in
the `sys.modules` arm. A second `"torch_package" in module_name` test at the
write, a hundred lines below the first, would have to be kept in step with it
by hand; the local cannot drift. The write is further guarded by
`isinstance(value, types.ModuleType)`: `sys.modules` accepts any object, and a
non-module entry, which the callers without a module check bind verbatim, is
never remembered, so the cache's `dict[str, types.ModuleType]` annotation holds
by construction.

The live entry is read from `sys.modules` itself, and the memo no longer runs
in front of the read. What the memo's call cost for a present name depended on
the interpreter, since a cold memo is `importlib.import_module`: on 3.12
`_find_and_load` (`importlib/_bootstrap.py:1349-1356`) returns without
touching a lock unless the entry is missing or its `__spec__._initializing` is
set, but 3.10's (`:1022-1034`) has no such gate -- it enters
`_ModuleLockManager` and calls `_lock_unlock_module` for every name, each
through `_get_module_lock`, which brackets its body with the global import
lock (`:185`, `:211`), all of it under `compile_lock`. Measured in an earlier
revision of this commit with spies on `_get_module_lock` and
`_imp.acquire_lock`, resolving a present, initialized name through
`import_module`: 3.10.20, two module-lock and four global-import-lock
acquisitions and 5.5 us per call; 3.12.14, none and 388 ns. The `sys.modules`
read takes no lock on either. The import machinery is now entered in two
cases only: a name absent from `sys.modules` that no trace has resolved before
(a first import, as before), and a name blocked with `None` that no trace has
resolved before (which raises `ModuleNotFoundError`, as before). An entry
whose `__spec__._initializing` is set -- `_load_unlocked` (`:911-950`) sets it
around a first-time execution of the module body -- is served as is. An
earlier revision handed such an entry to `import_module` so the trace would
wait on the module lock as an import statement does; that branch is gone, for
the reason its review gave. From `IMPORT_NAME`, the one caller whose name the
traced bytecode chose, `__import__` has just returned the entry, and
`_find_and_load` already waited out a cross-thread initialization; what can
still be `_initializing` there is same-thread re-entrancy, a module body that
compiles a function importing the module itself, where `_ModuleLock.acquire`
short-circuits on its owner and `import_module` returns the same
half-initialized object, so the branch changed nothing (measured with such a
module at this tree: the spec's flag is set when the compile runs, the compile
succeeds, and the alias and the cache both hold the module itself). The only
caller family the branch could change a value for resolves a name without an
`__import__` of its own -- `get_globals_source_and_value`, the codegen names --
while another thread executes that module's body, and there `import_module`
blocks on that module's lock with `compile_lock` held; if the other thread's
body re-enters Dynamo it blocks on `compile_lock`, and importlib's deadlock
detection, which walks module-lock edges only, cannot see the cycle. The
comment at the read says so, so the next reader does not put the wait back.
The commit below waited in that case only while its memo was cold and served
the previous incarnation once warm; this commit serves the live entry as it
stands, which is what the same-thread case always got. No test pins it: the
observable difference is a two-thread timing, and the single-threaded dispatch
pin an earlier revision had (`..._waits_on_its_import`, which asserted the
`import_module` call, not a wait) went with the branch.

The resolution reads nothing off the module it resolves. The commit below's
`_import_module` made `_find_and_load`'s `getattr(module, "__spec__", None)`
on 3.11+ for the first resolution of each name per process, none on 3.10; here
no version reads an attribute off the module, and the alias check below reads
`__name__` out of the instance dicts as before.
`test_import_alias_check_does_not_run_a_module_getattribute` pins the
resolution as well as the check: its module class now raises on any read made
with `import_source` on the stack, matched by function name and module, and on
the commit below, on 3.12, the test errors with the module's raise reached from
`_find_and_load` under `_import_module`.

The write rule loses its condition. Below this commit a writer's same-named
module -- `CompilePackage.install()`, an artifact load seeding its guard scope
-- is replaced when the name is live and left in the slot when the name is
gone or blocked, the memo being no less stale than the writer's module. Now
`f_globals[alias] = value` runs unconditionally: `value` is the live entry
whenever `sys.modules` holds a module under the name, or the one a first import
has just put there, and what this process's traces last bound when the name is
gone or blocked with `None`; there neither module is the live entry, and the
cached one is the object the guards this alias roots were built against.
`test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`
pins it: a trace binds and caches one module, `install()` in the same globals
binds a second of the same name, and with the entry then popped, and again
with it set to `None`, a resolution replaces the installed module by the cached
one; on the commit below the installed module stays in the slot, both arms.

`_import_module` is deleted; its last caller is this read. The cache is never
cleared, not by `torch._dynamo.reset()` either, so a module the process has
dropped stays alive in it; the memo retained modules the same way, so this is
not new retention. The declaration comment is the one place that says so; an
earlier revision repeated it in `reset()`, next to nothing that read it. A
`reset()` that did clear the cache fails the removed-name test, whose deleted
and blocked compiles follow a `reset()`. Only names the traced bytecode never
imported can arrive absent or blocked: `IMPORT_NAME`'s own `__import__` has
just put its name back or raised, `get_globals_source_and_value` resolves only
a module it has just found live under the frame's `__name__`, and the other
callers pass torch's own or stdlib names for codegen. `torch.autograd.profiler`
is such a name: `codegen.py` resolves it on every compile under
`config.record_runtime_overhead` (on by default) for the runtime-overhead
record in the compiled frame's prologue, and the only function-scope import of
it in torch/ (`torch/profiler/_utils.py`) is off the compile path, so a trace
with the entry deleted has no other reason to re-import it. The removed-name
test, inherited from the commit below, uses it for that reason.

Order to review: `symbolic_convert.py`, the `_import_source_cache` declaration
replacing `_import_module`, then the `sys.modules` arm of `import_source` (the
read, the cache fallback, the `import_module` fallback and the comment on the
entry still initializing), the `cacheable` local in both arms, and the write
block (record, cache write, unconditional alias write); then `test_package.py`:
the gone-name test (the one new case), the frame-walk probe at the top of the
file and the extended getattribute test, the empty-slot test's cache pin and
comptime-driven resolution, the cache assertions in the refused-alias tests,
the `torch_package` test and the non-module-value test, and the teardowns,
where `_import_module.cache_clear()` becomes `_import_source_cache.pop(name,
None)` or goes.

Behaviour change against the commit below, pinned below: a name gone from
`sys.modules` or blocked there with `None` binds what `import_source` last
bound under it rather than the first object the process resolved
(`test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache`, its
resolution after the pop); a writer's same-named module in the slot is
replaced for a name gone or blocked
(`test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`);
the resolution reads no attribute off the module it resolves, where the memo's
`import_module` did on 3.11+ for the first resolution of a name
(`test_import_alias_check_does_not_run_a_module_getattribute`); a refused trace
remembers nothing under the name (`test_import_alias_taken_by_a_non_module_graph_breaks`,
`test_import_alias_the_trace_refused_is_not_recorded_for_install`, by mutation:
with the write moved above the check, five failures); a `torch_package` name
and a non-module value are bound but never remembered
(`test_import_alias_accepts_a_stale_torch_package_module`,
`test_import_alias_check_with_a_non_module_value_accepts_the_key_alone`, each
by mutation of the guard it pins); and an entry still executing its body is
served as is rather than waited on when the name is one no trace resolved
before, which no test pins (above). Not a change: a name removed from or
blocked in `sys.modules` between two traces still binds the module the program
holds, and the import machinery is not entered for it
(`test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module`,
which passes on the commit below, whose memo serves the name, and pins this
commit against a cache read dropped).

Test Plan:

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

One case joins the commit below's twenty-two: twenty-three `test_import_alias`
instances. Seven of the inherited ones gain cache assertions or a cache-driven
leg, three have comments reworded, and every teardown changes. The new one,
`test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`,
compiles a function importing a scratch module under a `CompilePackage`, saves
it, hands the `sys.modules` entry to a second module of the same name and
loads and installs the package, so `install()` binds the alias to the second
module while the cache holds the first; then, in two `subTest` arms with the
alias put back on the installed module before each, pops the entry, and sets
it to `None`, and compiles a probe whose bytecode never imports the name and
whose comptime callback calls `import_source(name, True)` on the live
translator as `IMPORT_NAME` does -- the function's own import statement cannot
run once the entry is gone -- pinning that the alias holds the first module
afterwards and, at the end, that the cache still does. The empty-slot test,
after its handover, asserts `_import_source_cache[name]` is the second module
and then, with the entry popped and the alias deleted, drives `import_source`
the same way from a probe compiled in the same globals, and asserts the
returned source names the alias and the alias binds the second module; an
earlier revision called the unbound method on a `types.SimpleNamespace`
translator, which bypassed the real `OutputGraph` and `CompilePackage`. Its
scratch name is now `torch_test_package_import_alias_handed_over`. The
extended getattribute test's `_ImportAliasHookedModule` used to raise on a
`__dict__` read anywhere, and now raises on any read made with
`InstructionTranslatorBase.import_source` on the Python stack, matched by
function name and by the frame's module (`__import__` and
`PythonModuleVariable` read `__spec__` and `__name__` off a module by design,
so the stack is the discriminator); with no read left for the hook to observe,
its positive control is static: the test asserts that
`InstructionTranslatorBase.import_source.__wrapped__` (the `cache_method`
wrapper keeps the function under `__wrapped__`) has the `co_name` and
`__module__` the walk matches, so a renamed or inlined `import_source` fails
there rather than letting every read through. The refused-alias tests:
`test_import_alias_taken_by_a_non_module_graph_breaks` pins, per case, that
neither the `fullgraph` refusal nor the skipped frame leaves the name in
`_import_source_cache`, and `test_import_alias_graph_break_is_cached_until_reset`
pins the name absent after the refusal and present, as the module, after the
compile that binds the alias; `test_import_alias_the_trace_refused_is_not_recorded_for_install`
pins the name absent from the cache after the checkpointed refusal and again
after `install()`. The two tests that reach the cache write with a value one
of its guards refuses each gain one `assertNotIn` on the cache:
`test_import_alias_accepts_a_stale_torch_package_module` asserts the mangled
name absent after its compile, and
`test_import_alias_check_with_a_non_module_value_accepts_the_key_alone` asserts
the key absent after its accepted call. The removed-name test's comment and
teardown lose the memo, and the installed-live-module test's and the nn hook
test's comments no longer say "memo", the helper being gone.
Every `test_import_alias` test whose scratch name gets cached pops it from
`_import_source_cache` in `finally`, alongside the alias and the entry --
sixteen at this commit, in place of the `_import_module.cache_clear()` that
named the deleted helper: the pop only matters where a later compile runs with
the name absent or blocked, but one teardown shape keeps a test-minted module
from outliving its test either way. Six have nothing to pop, and the commit
below's `cache_clear()` simply goes: `test_import_alias_the_trace_refused_is_not_recorded_for_install`,
whose one trace is refused before the write and which asserts the name absent
instead; `test_import_alias_is_not_bound_to_a_non_module_import`, whose entry
`IMPORT_NAME` rejects before `import_source` runs, and a non-module is never
cached in any case; `test_import_alias_accepts_a_stale_torch_package_module`
and `test_import_alias_taken_in_a_torch_package_slot_is_a_hard_error`, whose
names take the `torch_package` arm, which never writes the cache (the first
asserts that); and `test_import_alias_taken_at_codegen_is_a_hard_error` and
the removed-name test, whose name is `torch.autograd.profiler` and whose
cached object is the process's own module, which a pop would not free and the
next compile re-caches.

Measured against the commit below's `symbolic_convert.py`, checked out under
this test file with a stub `_import_source_cache = {}` added so the file
imports: four of the twenty-three fail there. The getattribute test errors on
3.12 with `InternalTorchDynamoError: RuntimeError: module __getattribute__
read __spec__ inside a trace`, the read made by `_find_and_load`
(`_bootstrap.py:1356`) under `_import_module`; the gone-name test fails both
arms on `assertIs(fn.__globals__[alias], old)`, the installed module left in
the slot, and then errors on its closing cache pin against the empty stub; the
empty-slot test errors with `KeyError` on `_import_source_cache[name]`,
nothing having written the cache; and
`test_import_alias_graph_break_is_cached_until_reset` errors the same way on
its `assertIs(_import_source_cache[name], module)` after the compile that binds
the alias. The other nineteen pass there, the removed-name test, whose memo
serves the name, and the `assertNotIn`s on an empty stub among them. Those are
pinned at this tree by mutation of `symbolic_convert.py`, each mutant run
against the twenty-three and restored afterwards: with the write gated as the
commit below gates it (alias absent, or holding the value, or the name live),
the gone-name test fails both arms (and the `torch_package` test errors, that
gate reading its name, which is never in `sys.modules`, as not live); with the
cache write made `_import_source_cache.setdefault(module_name, value)` -- a
first-resolution memo one indirection further in -- the empty-slot test alone
fails, on `assertIs(_import_source_cache[name], new)` after the handover; with
the cache read dropped, importing whenever the entry is absent, the
removed-name test fails its deleted case on the spy (`'torch.autograd.profiler'
unexpectedly found in ['torch.autograd.profiler']`) and errors its blocked
case with `InternalTorchDynamoError: ModuleNotFoundError: import of
torch.autograd.profiler halted; None in sys.modules`, and the empty-slot and
gone-name resolutions error with `ModuleNotFoundError` for their scratch
names; with the `torch_package` arm's `cacheable` flipped to `True`, the
`torch_package` test alone fails; with the `isinstance(value,
types.ModuleType)` conjunct dropped from the write, the non-module-value test
alone fails; with the cache write moved above the alias check, five failures,
`assertNotIn` in each of the three `taken_by_a_non_module` cases, in
`cached_until_reset` and in the install test; and with a
`getattr(value, "__spec__", None)` added to the resolution, the getattribute
test alone errors, with the hook's `RuntimeError`. Neither of the two guard
mutants changes what a compile binds today -- one pins a dropped
`torch.package` module for the process, the other opens a path `IMPORT_NAME`
blocks -- so the annotation and the comments at the write are held by those
two assertions and by nothing else. On this commit the twenty-three pass and
the whole file is 101 tests, OK (skipped=40, expected failures=1).

```
python test/dynamo/test_package.py -k test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache
python test/dynamo/test_package.py -k test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module
python test/dynamo/test_package.py -k test_import_alias_check_does_not_run_a_module_getattribute
python test/dynamo/test_package.py -k test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache
python test/dynamo/test_package.py -k test_import_alias_taken_by_a_non_module_graph_breaks -k test_import_alias_graph_break_is_cached_until_reset -k test_import_alias_the_trace_refused_is_not_recorded_for_install
python test/dynamo/test_package.py -k test_import_alias_accepts_a_stale_torch_package_module
python test/dynamo/test_package.py -k test_import_alias_check_with_a_non_module_value_accepts_the_key_alone
```

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

> **FAQ: the `_initializing` -> `importlib.import_module` branch cannot change `value` on the one caller that can reach it from traced bytecode, since `IMPORT_NAME`'s `__import__` has just waited, and its one effectful path -- a codegen or `get_globals_source_and_value` caller resolving a name another thread is executing -- blocks on that module's lock under `compile_lock`, a lock-order cross `_has_deadlocked` cannot see. Drop it and serve the entry as is, or state the hazard at the call site.**
>
> Dropped, and the hazard is stated where the wait would go. Reachability was probed at this tree with a scratch module whose body compiles a function that imports the module itself: `IMPORT_NAME`'s `__import__` hands back the entry with `__spec__._initializing` still `True`, the compile succeeds, and the alias and `_import_source_cache` both hold that module -- the object `import_module` would have returned too, its lock being owned by the same thread. So from `IMPORT_NAME` the branch was two lock acquisitions for nothing, and from the callers with no `__import__` of their own it was the wait the finding describes, per compile rather than once per process. What is given up is the single-threaded dispatch pin (`..._waits_on_its_import` asserted that `import_module` was asked, not that anything waited) and the two-thread measurement an earlier revision made; the commit below waited in that case only while its memo was cold, and once warm served the previous incarnation, so no tree in this stack has made that wait reliably. `test_import_alias_check_does_not_run_a_module_getattribute` no longer plants a spec with a raising `_initializing` property, since nothing reads a spec. With the branch went `import importlib.machinery` in both files and the `_ImportAliasProbeSpec` helper.

> **FAQ: dropping the `if not conflict or live:` gate for an unconditional `f_globals[alias] = value` is a reachable behaviour change no test covers: the alias bound by `install()` or `_seed_guard_scope()` to a same-named but different module, which the name check accepts, and the name then absent from `sys.modules` or blocked with `None`. Add a pin.**
>
> Added: `test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`, two independent resolutions of one name (a trace under a `CompilePackage`, then `install()` of that package after a handover) and its removal, in a deleted arm and a `None` arm. On the commit below both arms fail on `assertIs(fn.__globals__[alias], old)`, the installed module left in the slot; here both pass, and with this tree's write gated the way the commit below gates it, both fail again. The write is reached through the live translator from a comptime callback, because the traced function's own import cannot run with the entry gone.

> **FAQ: the empty-slot test hand-rolls a `types.SimpleNamespace` translator and calls the unbound `InstructionTranslatorBase.import_source(tx, name)`, bypassing the real `OutputGraph` and `CompilePackage`; the file already drives `import_source` on a resolution no bytecode reaches through a comptime callback on the live translator. Use that shape.**
>
> Done: after the handover and the pop, a probe function whose bytecode never imports the name is compiled in the same globals, and its comptime callback calls `tx.import_source(name, True)` on the live translator, as `IMPORT_NAME` would; the test asserts the returned source's `global_name` is the alias and that the alias binds the second module. The new gone-name test uses the same shape. The `setdefault` mutant is still the one failure among the twenty-three, on the cache pin after the handover.

> **FAQ: the comment in `torch/_dynamo/__init__.py:171-174` restates the declaration comment and dangles above an unrelated call; the 16-line and 9-line comments at the read and the write restate CPython internals. Drop the first, trim the others to the load-bearing facts.**
>
> The `__init__.py` comment is gone, and this commit no longer touches that file; the declaration says the cache is never cleared, `reset()` included. The read's comment is down to what a reader needs at the site -- the live entry is what `IMPORT_NAME` pushed, `import_module` takes the module lock for a present name on 3.10, a removed or blocked name keeps what it last resolved to because re-importing would run the module body inside the trace, and an initializing entry is served as is with the lock-order reason -- and the write's to which module wins and why. The derivations are in this message.

> **FAQ: nothing pins that `_import_source_cache` holds what `import_source` last bound under a name rather than the first thing it resolved: `_import_source_cache.setdefault(module_name, value)` passes the whole `test_import_alias` family. Extend the empty-slot test, which already hands a name over from `old` to `new`, with one more compile after `sys.modules.pop(name)`, asserting the alias binds `new` and not `old`.**
>
> Pinned there, with the resolution driven from a probe rather than by the test function's own import. That import statement cannot run once the entry is popped: measured at this tree, eager raises `ModuleNotFoundError` and the compile raises `Unsupported: Import failure` before `import_source` runs, binding nothing. The cache read is reached from a compile only for a name the traced bytecode never imports -- codegen's `torch.autograd.profiler`, which the removed-name test uses and which is one module object throughout -- so the empty-slot test asserts `_import_source_cache[name] is new` after its handover and then, with the entry popped and the alias deleted, compiles a probe whose comptime callback calls `import_source(name, True)` on the live translator, and asserts the alias binds `new`. The `setdefault` mutant is the one failure among the twenty-three, on the first assertion.

> **FAQ: "A writer's same-named module is replaced: value is the live entry whenever there is one" licenses dropping the old gate, and it is not true in one reachable case: for a name blocked with `None`, `.get` returned `None`, which `is not value`, so the old code kept a writer's binding of a different same-named object and this code overwrites it.**
>
> The case is as described, and it is now pinned by the gone-name test's `None` arm as well as its deleted arm: two writers (`install()`, an AOT load seeding its guard scope) resolve independently through `import_module`, so a `None`-blocked name can find the alias bound to one same-named object while the cache holds another, and the name check passes since both answer the same `__name__`. The commit below kept the writer's module in both absent forms (its gate is `live`, an entry present under the name); now both replace it, and the comment at the write says which object wins and why: neither is live, and the cached one is what this process's traces bound and built guards against.

> **FAQ: five pre-existing tests lost `_import_module.cache_clear()` from their `finally` without gaining `_import_source_cache.pop(name, None)`, while the new tests pop; that is two teardown conventions in one file and a process-lifetime strong reference to each test-minted `ModuleType`.**
>
> Every test whose scratch name gets cached pops now -- sixteen at this commit, the accepted-names fixture and the non-module-value test among them -- and the message says when the pop is load-bearing: only where a later compile runs with the name absent or blocked. Six `test_import_alias` tests have no pop, deliberately: the refused-alias install test's one trace is refused before the cache write, which sits below the alias check, and the test asserts the name absent from the cache instead; the removed-name test's and the codegen test's name is `torch.autograd.profiler` and the object cached is the process's own module, which the pop would not free and the next test re-caches; the non-module import test's entry never reaches `import_source`, `IMPORT_NAME` rejecting it first, and would not be cached if it did; and the two `torch_package` tests' names take the arm that never writes the cache. The commit below cleared the memo in all of those; the line simply goes here.

> **FAQ: `_import_source_cache: dict[str, types.ModuleType]` is not what the code stores: `sys.modules` accepts any object, yet the write caches `value` unconditionally, so a non-module can be cached and later served and bound. Annotate the cache `dict[str, Any]` and say why, or hoist the `isinstance` so a non-module is never cached.**
>
> Hoisted, in the sense that keeps the annotation honest: the cache write is guarded by `isinstance(value, types.ModuleType)`, on the value finally resolved, together with the `cacheable` local the `sys.modules` arm sets, and sits below the alias check with the package record and `output.import_sources`, so a non-module reaching `import_source` is bound as is by the callers that make no module check and remembered by nothing. `test_import_alias_check_with_a_non_module_value_accepts_the_key_alone` pins it, reaching the write from a comptime callback on the live translator with a `SimpleNamespace` under the key and asserting the key absent from `_import_source_cache` after the accepted call; with the conjunct dropped it fails there. It is not pinned by the existing non-module test, which cannot reach the write: `IMPORT_NAME` is the one caller whose name the traced code chose, and it graph-breaks on `Bad import result` before `import_source` runs (that test's own point).

> **FAQ: the "zero lock acquisitions" measurement rests on the `_initializing` gate at `_bootstrap.py:1355-1356`, which does not exist before CPython 3.11; on 3.10 `_find_and_load` takes the module lock and calls `_lock_unlock_module` unconditionally, under `compile_lock`, on every compile. Either measure it there or serve a live initialized `sys.modules` entry directly.**
>
> The second option is taken. The earlier answer was measured on 3.12 only, and 3.10.20 gives the opposite result: `importlib.import_module` of a present, initialized name is two `_get_module_lock` calls and four `_imp.acquire_lock` calls and 5.5 us per call, against none and 388 ns on 3.12.14. `import_source` now reads `sys.modules` itself: a present entry is served as is, with no lock on either version, and `import_module` is reached only for an absent or `None` entry the cache has not seen -- a first import or the blocked-module raise, both as before -- so the cost is the same on every supported interpreter.

> **FAQ: dropping the process-wide memo means every compile re-enters CPython's module-lock path, which can raise `_DeadlockError` or hang while `compile_lock` is held: thread A executes module `M`'s body, thread B compiles a frame whose globals are `M.__dict__` and blocks on `M`'s lock under `compile_lock`, and if A's body compiles the two deadlock.**
>
> No compile enters the module-lock path for a present entry now, initializing or not: `import_source` reads `sys.modules` and serves what it finds, and `import_module` is reached only for a name absent or blocked that no trace has resolved before, exactly where the commit below's cold memo reached it. The scenario the finding describes -- B blocked on `M`'s lock under `compile_lock` while A's body wants `compile_lock` -- is the one the dropped `_initializing` branch would have walked into per compile, and the comment at the read names it as the reason the entry is served as is. `_DeadlockError` itself needs A to be blocked on a module lock B holds (`_ModuleLock.has_deadlock` walks `_blocking_on`), which B, holding no module lock, cannot cause; a wait on `compile_lock` is invisible to that walk, so the outcome of the dropped branch was a hang, not an error.

> **FAQ: `CompilePackage.install()` is the other writer of the same `__import_*` alias, and it resolves with a bare `importlib.import_module(module_name)`, so a name gone from `sys.modules` at install time raises `ModuleNotFoundError` out of `install()`, the failure mode the removed-name test rules out for the tracing side. Share the resolution helper, or say why `install()` is exempt.**
>
> Exempt, because neither hazard the cache guards against exists at install time. The cache exists so that a trace never runs a module body -- `import_source` is called from guard construction, inside the compile -- and never turns `ModuleNotFoundError` into an `InternalTorchDynamoError` with no eager fallback. `install()` runs in the user's own call, outside any trace: measured in an earlier revision, with the name deleted it raises `builtins.ModuleNotFoundError: No module named '...'`, and blocked with `None` it raises `import of ... halted; None in sys.modules`, both plain, both what the program's own `import` statement raises at that point, and a re-import there is an ordinary import at an ordinary time. Sharing the cache would also change nothing in the case the finding describes: a process that only loads has traced nothing, so the cache is empty, and the helper would fall through to `import_module` exactly as `install()` does today. The tracing-side cache is about a trace's view of a name the program still holds; `install()` has no trace and no such view.

> **FAQ: dropping the `functools.cache`d `_import_module` means a name resolved earlier and then removed from `sys.modules` re-runs the import machinery inside the trace, executing the module body again or raising `ImportError` as an `InternalTorchDynamoError`; keep both properties with `importlib.import_module` when the name is in `sys.modules` and `_import_module` otherwise.**
>
> Fixed, though not with that shape: `_import_module` is gone, and a fallback to a second memo would have re-imported once for every name `import_source` had resolved live (the commit below measures exactly that order). `import_source` remembers what it last bound per name (`_import_source_cache`) and serves that when the name is gone from `sys.modules` or blocked there with `None`; a live entry is read from `sys.modules`. The reach is narrower than ten call sites suggest, and only codegen names can arrive absent: `IMPORT_NAME`'s `__import__` has just put its own name back, `get_globals_source_and_value` resolves only a module it has just found live under the frame's `__name__`, and probing the user-controlled paths in an earlier revision -- a sourceless context manager returned from the frame or live across a graph break, an `autograd.Function` via a call result or an attribute -- found each resolving only `torch`, `torch._dynamo.utils`, `torch._dynamo.graph_bytecode_inputs` and `torch.autograd.profiler`, all present. `test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module` pins the case with `torch.autograd.profiler` and a spy on `importlib.import_module`, so unrelated imports cannot fail it.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 3e19efa
Pull-Request: #197303
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 19, 2026
…ast bound

Split for review budget from `[dynamo] Bind the import alias to the live
sys.modules entry` (#197046), the commit directly below: that one makes
`import_source` bind the live `sys.modules` entry whenever there is one and
keeps the memoized `_import_module` in front of that read, for a name since
removed from `sys.modules` or blocked there with `None`; this one replaces the
memo with a cache of what `import_source` last bound, written only once the
alias check has passed, and reads `sys.modules` with nothing in front of it.

`_import_module` is `functools.cache`d for the life of the process: it holds
the first object the process resolved under each name, and nothing clears it.
Below this commit it is what a name binds once the name has left `sys.modules`
-- `del sys.modules[...]`, a `mock.patch.dict(sys.modules)` scope -- or been
set to `None`, the import system's blocked-module sentinel that makes any
import of the name raise `ModuleNotFoundError`, because importing such a name
again would execute the module body inside the trace and bind a second copy of
a module the program still holds, or for `None` raise out of guard
construction (`ModuleNotFoundError` is not in `_compile`'s pass-through tuple,
so that raise surfaces as `InternalTorchDynamoError` with no eager fallback).
But the first resolution is the wrong object to fall back on for the same
reason it was the wrong object to bind: after a handover the traces have been
binding the live module and building guards against it, and the memo still
holds the module before the handover. And the memo is only warm for a name
some trace resolved while it was live: the commit below measures that a memo
cold for a deleted or blocked name imports inside guard construction all the
same, whichever order it and `sys.modules` are read in. `_import_source_cache`
replaces it, keyed by name, holding what `import_source` last bound: each
accepted resolution overwrites the entry, so a name that then leaves
`sys.modules` binds the module the guards this alias roots were built against,
not the one the process saw first.
`test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache`,
inherited from the commit below, gains that pin: after its handover
`_import_source_cache[name]` is the second module, and with the entry popped
and the alias deleted a resolution binds the second module, not the first.
The memo was also written at resolution, before the alias check, so a trace
the check refused with `Import alias already bound` remembered the name all
the same. The cache is written only once the check has passed, alongside the
package record and `output.import_sources`: it is never cleared, so a write
before the check would pin a module the process may later drop on behalf of a
trace that bound nothing. Whether a name is one the cache can serve is decided
where `import_source` branches on it and carried to the write in a local,
`cacheable`: `False` in the `torch_package` arm, whose names resolve through
`_package_imported_modules`, a `WeakValueDictionary`
(`package_importer.py:731`) that holds a packaged module only while its
importer or the user does, so an entry would pin a `torch.package` module the
user has dropped for the rest of the process, and whose names are never read
back from the cache in any case, the read being in the other arm; `True` in
the `sys.modules` arm. A second `"torch_package" in module_name` test at the
write, a hundred lines below the first, would have to be kept in step with it
by hand; the local cannot drift. The write is further guarded by
`isinstance(value, types.ModuleType)`: `sys.modules` accepts any object, and a
non-module entry, which the callers without a module check bind verbatim, is
never remembered, so the cache's `dict[str, types.ModuleType]` annotation holds
by construction.

The live entry is read from `sys.modules` itself, and the memo no longer runs
in front of the read. What the memo's call cost for a present name depended on
the interpreter, since a cold memo is `importlib.import_module`: on 3.12
`_find_and_load` (`importlib/_bootstrap.py:1349-1356`) returns without
touching a lock unless the entry is missing or its `__spec__._initializing` is
set, but 3.10's (`:1022-1034`) has no such gate -- it enters
`_ModuleLockManager` and calls `_lock_unlock_module` for every name, each
through `_get_module_lock`, which brackets its body with the global import
lock (`:185`, `:211`), all of it under `compile_lock`. Measured in an earlier
revision of this commit with spies on `_get_module_lock` and
`_imp.acquire_lock`, resolving a present, initialized name through
`import_module`: 3.10.20, two module-lock and four global-import-lock
acquisitions and 5.5 us per call; 3.12.14, none and 388 ns. The `sys.modules`
read takes no lock on either. The import machinery is now entered in two
cases only: a name absent from `sys.modules` that no trace has resolved before
(a first import, as before), and a name blocked with `None` that no trace has
resolved before (which raises `ModuleNotFoundError`, as before). An entry
whose `__spec__._initializing` is set -- `_load_unlocked` (`:911-950`) sets it
around a first-time execution of the module body -- is served as is. An
earlier revision handed such an entry to `import_module` so the trace would
wait on the module lock as an import statement does; that branch is gone, for
the reason its review gave. From `IMPORT_NAME`, the one caller whose name the
traced bytecode chose, `__import__` has just returned the entry, and
`_find_and_load` already waited out a cross-thread initialization; what can
still be `_initializing` there is same-thread re-entrancy, a module body that
compiles a function importing the module itself, where `_ModuleLock.acquire`
short-circuits on its owner and `import_module` returns the same
half-initialized object, so the branch changed nothing (measured with such a
module at this tree: the spec's flag is set when the compile runs, the compile
succeeds, and the alias and the cache both hold the module itself). The only
caller family the branch could change a value for resolves a name without an
`__import__` of its own -- `get_globals_source_and_value`, the codegen names --
while another thread executes that module's body, and there `import_module`
blocks on that module's lock with `compile_lock` held; if the other thread's
body re-enters Dynamo it blocks on `compile_lock`, and importlib's deadlock
detection, which walks module-lock edges only, cannot see the cycle. The
comment at the read says so, so the next reader does not put the wait back.
The commit below waited in that case only while its memo was cold and served
the previous incarnation once warm; this commit serves the live entry as it
stands, which is what the same-thread case always got. No test pins it: the
observable difference is a two-thread timing, and the single-threaded dispatch
pin an earlier revision had (`..._waits_on_its_import`, which asserted the
`import_module` call, not a wait) went with the branch.

The resolution reads nothing off the module it resolves. The commit below's
`_import_module` made `_find_and_load`'s `getattr(module, "__spec__", None)`
on 3.11+ for the first resolution of each name per process, none on 3.10; here
no version reads an attribute off the module, and the alias check below reads
`__name__` out of the instance dicts as before.
`test_import_alias_check_does_not_run_a_module_getattribute` pins the
resolution as well as the check: its module class now raises on any read made
with `import_source` on the stack, matched by function name and module, and on
the commit below, on 3.12, the test errors with the module's raise reached from
`_find_and_load` under `_import_module`.

The write rule loses its condition. Below this commit a writer's same-named
module -- `CompilePackage.install()`, an artifact load seeding its guard scope
-- is replaced when the name is live and left in the slot when the name is
gone or blocked, the memo being no less stale than the writer's module. Now
`f_globals[alias] = value` runs unconditionally: `value` is the live entry
whenever `sys.modules` holds a module under the name, or the one a first import
has just put there, and what this process's traces last bound when the name is
gone or blocked with `None`; there neither module is the live entry, and the
cached one is the object the guards this alias roots were built against.
`test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`
pins it: a trace binds and caches one module, `install()` in the same globals
binds a second of the same name, and with the entry then popped, and again
with it set to `None`, a resolution replaces the installed module by the cached
one; on the commit below the installed module stays in the slot, both arms.

`_import_module` is deleted; its last caller is this read. The cache is never
cleared, not by `torch._dynamo.reset()` either, so a module the process has
dropped stays alive in it; the memo retained modules the same way, so this is
not new retention. The declaration comment is the one place that says so; an
earlier revision repeated it in `reset()`, next to nothing that read it. A
`reset()` that did clear the cache fails the removed-name test, whose deleted
and blocked compiles follow a `reset()`. Only names the traced bytecode never
imported can arrive absent or blocked: `IMPORT_NAME`'s own `__import__` has
just put its name back or raised, `get_globals_source_and_value` resolves only
a module it has just found live under the frame's `__name__`, and the other
callers pass torch's own or stdlib names for codegen. `torch.autograd.profiler`
is such a name: `codegen.py` resolves it on every compile under
`config.record_runtime_overhead` (on by default) for the runtime-overhead
record in the compiled frame's prologue, and the only function-scope import of
it in torch/ (`torch/profiler/_utils.py`) is off the compile path, so a trace
with the entry deleted has no other reason to re-import it. The removed-name
test, inherited from the commit below, uses it for that reason.

Order to review: `symbolic_convert.py`, the `_import_source_cache` declaration
replacing `_import_module`, then the `sys.modules` arm of `import_source` (the
read, the cache fallback, the `import_module` fallback and the comment on the
entry still initializing), the `cacheable` local in both arms, and the write
block (record, cache write, unconditional alias write); then `test_package.py`:
the gone-name test (the one new case), the frame-walk probe at the top of the
file and the extended getattribute test, the empty-slot test's cache pin and
comptime-driven resolution, the cache assertions in the refused-alias tests,
the `torch_package` test and the non-module-value test, and the teardowns,
where `_import_module.cache_clear()` becomes `_import_source_cache.pop(name,
None)` or goes.

Behaviour change against the commit below, pinned below: a name gone from
`sys.modules` or blocked there with `None` binds what `import_source` last
bound under it rather than the first object the process resolved
(`test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache`, its
resolution after the pop); a writer's same-named module in the slot is
replaced for a name gone or blocked
(`test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`);
the resolution reads no attribute off the module it resolves, where the memo's
`import_module` did on 3.11+ for the first resolution of a name
(`test_import_alias_check_does_not_run_a_module_getattribute`); a refused trace
remembers nothing under the name (`test_import_alias_taken_by_a_non_module_graph_breaks`,
`test_import_alias_the_trace_refused_is_not_recorded_for_install`, by mutation:
with the write moved above the check, five failures); a `torch_package` name
and a non-module value are bound but never remembered
(`test_import_alias_accepts_a_stale_torch_package_module`,
`test_import_alias_check_with_a_non_module_value_accepts_the_key_alone`, each
by mutation of the guard it pins); and an entry still executing its body is
served as is rather than waited on when the name is one no trace resolved
before, which no test pins (above). Not a change: a name removed from or
blocked in `sys.modules` between two traces still binds the module the program
holds, and the import machinery is not entered for it
(`test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module`,
which passes on the commit below, whose memo serves the name, and pins this
commit against a cache read dropped).

Test Plan:

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

One case joins the commit below's twenty-two: twenty-three `test_import_alias`
instances. Seven of the inherited ones gain cache assertions or a cache-driven
leg, three have comments reworded, and every teardown changes. The new one,
`test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`,
compiles a function importing a scratch module under a `CompilePackage`, saves
it, hands the `sys.modules` entry to a second module of the same name and
loads and installs the package, so `install()` binds the alias to the second
module while the cache holds the first; then, in two `subTest` arms with the
alias put back on the installed module before each, pops the entry, and sets
it to `None`, and compiles a probe whose bytecode never imports the name and
whose comptime callback calls `import_source(name, True)` on the live
translator as `IMPORT_NAME` does -- the function's own import statement cannot
run once the entry is gone -- pinning that the alias holds the first module
afterwards and, at the end, that the cache still does. The empty-slot test,
after its handover, asserts `_import_source_cache[name]` is the second module
and then, with the entry popped and the alias deleted, drives `import_source`
the same way from a probe compiled in the same globals, and asserts the
returned source names the alias and the alias binds the second module; an
earlier revision called the unbound method on a `types.SimpleNamespace`
translator, which bypassed the real `OutputGraph` and `CompilePackage`. Its
scratch name is now `torch_test_package_import_alias_handed_over`. The
extended getattribute test's `_ImportAliasHookedModule` used to raise on a
`__dict__` read anywhere, and now raises on any read made with
`InstructionTranslatorBase.import_source` on the Python stack, matched by
function name and by the frame's module (`__import__` and
`PythonModuleVariable` read `__spec__` and `__name__` off a module by design,
so the stack is the discriminator); with no read left for the hook to observe,
its positive control is static: the test asserts that
`InstructionTranslatorBase.import_source.__wrapped__` (the `cache_method`
wrapper keeps the function under `__wrapped__`) has the `co_name` and
`__module__` the walk matches, so a renamed or inlined `import_source` fails
there rather than letting every read through. The refused-alias tests:
`test_import_alias_taken_by_a_non_module_graph_breaks` pins, per case, that
neither the `fullgraph` refusal nor the skipped frame leaves the name in
`_import_source_cache`, and `test_import_alias_graph_break_is_cached_until_reset`
pins the name absent after the refusal and present, as the module, after the
compile that binds the alias; `test_import_alias_the_trace_refused_is_not_recorded_for_install`
pins the name absent from the cache after the checkpointed refusal and again
after `install()`. The two tests that reach the cache write with a value one
of its guards refuses each gain one `assertNotIn` on the cache:
`test_import_alias_accepts_a_stale_torch_package_module` asserts the mangled
name absent after its compile, and
`test_import_alias_check_with_a_non_module_value_accepts_the_key_alone` asserts
the key absent after its accepted call. The removed-name test's comment and
teardown lose the memo, and the installed-live-module test's and the nn hook
test's comments no longer say "memo", the helper being gone.
Every `test_import_alias` test whose scratch name gets cached pops it from
`_import_source_cache` in `finally`, alongside the alias and the entry --
sixteen at this commit, in place of the `_import_module.cache_clear()` that
named the deleted helper: the pop only matters where a later compile runs with
the name absent or blocked, but one teardown shape keeps a test-minted module
from outliving its test either way. Six have nothing to pop, and the commit
below's `cache_clear()` simply goes: `test_import_alias_the_trace_refused_is_not_recorded_for_install`,
whose one trace is refused before the write and which asserts the name absent
instead; `test_import_alias_is_not_bound_to_a_non_module_import`, whose entry
`IMPORT_NAME` rejects before `import_source` runs, and a non-module is never
cached in any case; `test_import_alias_accepts_a_stale_torch_package_module`
and `test_import_alias_taken_in_a_torch_package_slot_is_a_hard_error`, whose
names take the `torch_package` arm, which never writes the cache (the first
asserts that); and `test_import_alias_taken_at_codegen_is_a_hard_error` and
the removed-name test, whose name is `torch.autograd.profiler` and whose
cached object is the process's own module, which a pop would not free and the
next compile re-caches.

Measured against the commit below's `symbolic_convert.py`, checked out under
this test file with a stub `_import_source_cache = {}` added so the file
imports: four of the twenty-three fail there. The getattribute test errors on
3.12 with `InternalTorchDynamoError: RuntimeError: module __getattribute__
read __spec__ inside a trace`, the read made by `_find_and_load`
(`_bootstrap.py:1356`) under `_import_module`; the gone-name test fails both
arms on `assertIs(fn.__globals__[alias], old)`, the installed module left in
the slot, and then errors on its closing cache pin against the empty stub; the
empty-slot test errors with `KeyError` on `_import_source_cache[name]`,
nothing having written the cache; and
`test_import_alias_graph_break_is_cached_until_reset` errors the same way on
its `assertIs(_import_source_cache[name], module)` after the compile that binds
the alias. The other nineteen pass there, the removed-name test, whose memo
serves the name, and the `assertNotIn`s on an empty stub among them. Those are
pinned at this tree by mutation of `symbolic_convert.py`, each mutant run
against the twenty-three and restored afterwards: with the write gated as the
commit below gates it (alias absent, or holding the value, or the name live),
the gone-name test fails both arms (and the `torch_package` test errors, that
gate reading its name, which is never in `sys.modules`, as not live); with the
cache write made `_import_source_cache.setdefault(module_name, value)` -- a
first-resolution memo one indirection further in -- the empty-slot test alone
fails, on `assertIs(_import_source_cache[name], new)` after the handover; with
the cache read dropped, importing whenever the entry is absent, the
removed-name test fails its deleted case on the spy (`'torch.autograd.profiler'
unexpectedly found in ['torch.autograd.profiler']`) and errors its blocked
case with `InternalTorchDynamoError: ModuleNotFoundError: import of
torch.autograd.profiler halted; None in sys.modules`, and the empty-slot and
gone-name resolutions error with `ModuleNotFoundError` for their scratch
names; with the `torch_package` arm's `cacheable` flipped to `True`, the
`torch_package` test alone fails; with the `isinstance(value,
types.ModuleType)` conjunct dropped from the write, the non-module-value test
alone fails; with the cache write moved above the alias check, five failures,
`assertNotIn` in each of the three `taken_by_a_non_module` cases, in
`cached_until_reset` and in the install test; and with a
`getattr(value, "__spec__", None)` added to the resolution, the getattribute
test alone errors, with the hook's `RuntimeError`. Neither of the two guard
mutants changes what a compile binds today -- one pins a dropped
`torch.package` module for the process, the other opens a path `IMPORT_NAME`
blocks -- so the annotation and the comments at the write are held by those
two assertions and by nothing else. On this commit the twenty-three pass and
the whole file is 101 tests, OK (skipped=40, expected failures=1).

```
python test/dynamo/test_package.py -k test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache
python test/dynamo/test_package.py -k test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module
python test/dynamo/test_package.py -k test_import_alias_check_does_not_run_a_module_getattribute
python test/dynamo/test_package.py -k test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache
python test/dynamo/test_package.py -k test_import_alias_taken_by_a_non_module_graph_breaks -k test_import_alias_graph_break_is_cached_until_reset -k test_import_alias_the_trace_refused_is_not_recorded_for_install
python test/dynamo/test_package.py -k test_import_alias_accepts_a_stale_torch_package_module
python test/dynamo/test_package.py -k test_import_alias_check_with_a_non_module_value_accepts_the_key_alone
```

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

> **FAQ: the `_initializing` -> `importlib.import_module` branch cannot change `value` on the one caller that can reach it from traced bytecode, since `IMPORT_NAME`'s `__import__` has just waited, and its one effectful path -- a codegen or `get_globals_source_and_value` caller resolving a name another thread is executing -- blocks on that module's lock under `compile_lock`, a lock-order cross `_has_deadlocked` cannot see. Drop it and serve the entry as is, or state the hazard at the call site.**
>
> Dropped, and the hazard is stated where the wait would go. Reachability was probed at this tree with a scratch module whose body compiles a function that imports the module itself: `IMPORT_NAME`'s `__import__` hands back the entry with `__spec__._initializing` still `True`, the compile succeeds, and the alias and `_import_source_cache` both hold that module -- the object `import_module` would have returned too, its lock being owned by the same thread. So from `IMPORT_NAME` the branch was two lock acquisitions for nothing, and from the callers with no `__import__` of their own it was the wait the finding describes, per compile rather than once per process. What is given up is the single-threaded dispatch pin (`..._waits_on_its_import` asserted that `import_module` was asked, not that anything waited) and the two-thread measurement an earlier revision made; the commit below waited in that case only while its memo was cold, and once warm served the previous incarnation, so no tree in this stack has made that wait reliably. `test_import_alias_check_does_not_run_a_module_getattribute` no longer plants a spec with a raising `_initializing` property, since nothing reads a spec. With the branch went `import importlib.machinery` in both files and the `_ImportAliasProbeSpec` helper.

> **FAQ: dropping the `if not conflict or live:` gate for an unconditional `f_globals[alias] = value` is a reachable behaviour change no test covers: the alias bound by `install()` or `_seed_guard_scope()` to a same-named but different module, which the name check accepts, and the name then absent from `sys.modules` or blocked with `None`. Add a pin.**
>
> Added: `test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`, two independent resolutions of one name (a trace under a `CompilePackage`, then `install()` of that package after a handover) and its removal, in a deleted arm and a `None` arm. On the commit below both arms fail on `assertIs(fn.__globals__[alias], old)`, the installed module left in the slot; here both pass, and with this tree's write gated the way the commit below gates it, both fail again. The write is reached through the live translator from a comptime callback, because the traced function's own import cannot run with the entry gone.

> **FAQ: the empty-slot test hand-rolls a `types.SimpleNamespace` translator and calls the unbound `InstructionTranslatorBase.import_source(tx, name)`, bypassing the real `OutputGraph` and `CompilePackage`; the file already drives `import_source` on a resolution no bytecode reaches through a comptime callback on the live translator. Use that shape.**
>
> Done: after the handover and the pop, a probe function whose bytecode never imports the name is compiled in the same globals, and its comptime callback calls `tx.import_source(name, True)` on the live translator, as `IMPORT_NAME` would; the test asserts the returned source's `global_name` is the alias and that the alias binds the second module. The new gone-name test uses the same shape. The `setdefault` mutant is still the one failure among the twenty-three, on the cache pin after the handover.

> **FAQ: the comment in `torch/_dynamo/__init__.py:171-174` restates the declaration comment and dangles above an unrelated call; the 16-line and 9-line comments at the read and the write restate CPython internals. Drop the first, trim the others to the load-bearing facts.**
>
> The `__init__.py` comment is gone, and this commit no longer touches that file; the declaration says the cache is never cleared, `reset()` included. The read's comment is down to what a reader needs at the site -- the live entry is what `IMPORT_NAME` pushed, `import_module` takes the module lock for a present name on 3.10, a removed or blocked name keeps what it last resolved to because re-importing would run the module body inside the trace, and an initializing entry is served as is with the lock-order reason -- and the write's to which module wins and why. The derivations are in this message.

> **FAQ: nothing pins that `_import_source_cache` holds what `import_source` last bound under a name rather than the first thing it resolved: `_import_source_cache.setdefault(module_name, value)` passes the whole `test_import_alias` family. Extend the empty-slot test, which already hands a name over from `old` to `new`, with one more compile after `sys.modules.pop(name)`, asserting the alias binds `new` and not `old`.**
>
> Pinned there, with the resolution driven from a probe rather than by the test function's own import. That import statement cannot run once the entry is popped: measured at this tree, eager raises `ModuleNotFoundError` and the compile raises `Unsupported: Import failure` before `import_source` runs, binding nothing. The cache read is reached from a compile only for a name the traced bytecode never imports -- codegen's `torch.autograd.profiler`, which the removed-name test uses and which is one module object throughout -- so the empty-slot test asserts `_import_source_cache[name] is new` after its handover and then, with the entry popped and the alias deleted, compiles a probe whose comptime callback calls `import_source(name, True)` on the live translator, and asserts the alias binds `new`. The `setdefault` mutant is the one failure among the twenty-three, on the first assertion.

> **FAQ: "A writer's same-named module is replaced: value is the live entry whenever there is one" licenses dropping the old gate, and it is not true in one reachable case: for a name blocked with `None`, `.get` returned `None`, which `is not value`, so the old code kept a writer's binding of a different same-named object and this code overwrites it.**
>
> The case is as described, and it is now pinned by the gone-name test's `None` arm as well as its deleted arm: two writers (`install()`, an AOT load seeding its guard scope) resolve independently through `import_module`, so a `None`-blocked name can find the alias bound to one same-named object while the cache holds another, and the name check passes since both answer the same `__name__`. The commit below kept the writer's module in both absent forms (its gate is `live`, an entry present under the name); now both replace it, and the comment at the write says which object wins and why: neither is live, and the cached one is what this process's traces bound and built guards against.

> **FAQ: five pre-existing tests lost `_import_module.cache_clear()` from their `finally` without gaining `_import_source_cache.pop(name, None)`, while the new tests pop; that is two teardown conventions in one file and a process-lifetime strong reference to each test-minted `ModuleType`.**
>
> Every test whose scratch name gets cached pops now -- sixteen at this commit, the accepted-names fixture and the non-module-value test among them -- and the message says when the pop is load-bearing: only where a later compile runs with the name absent or blocked. Six `test_import_alias` tests have no pop, deliberately: the refused-alias install test's one trace is refused before the cache write, which sits below the alias check, and the test asserts the name absent from the cache instead; the removed-name test's and the codegen test's name is `torch.autograd.profiler` and the object cached is the process's own module, which the pop would not free and the next test re-caches; the non-module import test's entry never reaches `import_source`, `IMPORT_NAME` rejecting it first, and would not be cached if it did; and the two `torch_package` tests' names take the arm that never writes the cache. The commit below cleared the memo in all of those; the line simply goes here.

> **FAQ: `_import_source_cache: dict[str, types.ModuleType]` is not what the code stores: `sys.modules` accepts any object, yet the write caches `value` unconditionally, so a non-module can be cached and later served and bound. Annotate the cache `dict[str, Any]` and say why, or hoist the `isinstance` so a non-module is never cached.**
>
> Hoisted, in the sense that keeps the annotation honest: the cache write is guarded by `isinstance(value, types.ModuleType)`, on the value finally resolved, together with the `cacheable` local the `sys.modules` arm sets, and sits below the alias check with the package record and `output.import_sources`, so a non-module reaching `import_source` is bound as is by the callers that make no module check and remembered by nothing. `test_import_alias_check_with_a_non_module_value_accepts_the_key_alone` pins it, reaching the write from a comptime callback on the live translator with a `SimpleNamespace` under the key and asserting the key absent from `_import_source_cache` after the accepted call; with the conjunct dropped it fails there. It is not pinned by the existing non-module test, which cannot reach the write: `IMPORT_NAME` is the one caller whose name the traced code chose, and it graph-breaks on `Bad import result` before `import_source` runs (that test's own point).

> **FAQ: the "zero lock acquisitions" measurement rests on the `_initializing` gate at `_bootstrap.py:1355-1356`, which does not exist before CPython 3.11; on 3.10 `_find_and_load` takes the module lock and calls `_lock_unlock_module` unconditionally, under `compile_lock`, on every compile. Either measure it there or serve a live initialized `sys.modules` entry directly.**
>
> The second option is taken. The earlier answer was measured on 3.12 only, and 3.10.20 gives the opposite result: `importlib.import_module` of a present, initialized name is two `_get_module_lock` calls and four `_imp.acquire_lock` calls and 5.5 us per call, against none and 388 ns on 3.12.14. `import_source` now reads `sys.modules` itself: a present entry is served as is, with no lock on either version, and `import_module` is reached only for an absent or `None` entry the cache has not seen -- a first import or the blocked-module raise, both as before -- so the cost is the same on every supported interpreter.

> **FAQ: dropping the process-wide memo means every compile re-enters CPython's module-lock path, which can raise `_DeadlockError` or hang while `compile_lock` is held: thread A executes module `M`'s body, thread B compiles a frame whose globals are `M.__dict__` and blocks on `M`'s lock under `compile_lock`, and if A's body compiles the two deadlock.**
>
> No compile enters the module-lock path for a present entry now, initializing or not: `import_source` reads `sys.modules` and serves what it finds, and `import_module` is reached only for a name absent or blocked that no trace has resolved before, exactly where the commit below's cold memo reached it. The scenario the finding describes -- B blocked on `M`'s lock under `compile_lock` while A's body wants `compile_lock` -- is the one the dropped `_initializing` branch would have walked into per compile, and the comment at the read names it as the reason the entry is served as is. `_DeadlockError` itself needs A to be blocked on a module lock B holds (`_ModuleLock.has_deadlock` walks `_blocking_on`), which B, holding no module lock, cannot cause; a wait on `compile_lock` is invisible to that walk, so the outcome of the dropped branch was a hang, not an error.

> **FAQ: `CompilePackage.install()` is the other writer of the same `__import_*` alias, and it resolves with a bare `importlib.import_module(module_name)`, so a name gone from `sys.modules` at install time raises `ModuleNotFoundError` out of `install()`, the failure mode the removed-name test rules out for the tracing side. Share the resolution helper, or say why `install()` is exempt.**
>
> Exempt, because neither hazard the cache guards against exists at install time. The cache exists so that a trace never runs a module body -- `import_source` is called from guard construction, inside the compile -- and never turns `ModuleNotFoundError` into an `InternalTorchDynamoError` with no eager fallback. `install()` runs in the user's own call, outside any trace: measured in an earlier revision, with the name deleted it raises `builtins.ModuleNotFoundError: No module named '...'`, and blocked with `None` it raises `import of ... halted; None in sys.modules`, both plain, both what the program's own `import` statement raises at that point, and a re-import there is an ordinary import at an ordinary time. Sharing the cache would also change nothing in the case the finding describes: a process that only loads has traced nothing, so the cache is empty, and the helper would fall through to `import_module` exactly as `install()` does today. The tracing-side cache is about a trace's view of a name the program still holds; `install()` has no trace and no such view.

> **FAQ: dropping the `functools.cache`d `_import_module` means a name resolved earlier and then removed from `sys.modules` re-runs the import machinery inside the trace, executing the module body again or raising `ImportError` as an `InternalTorchDynamoError`; keep both properties with `importlib.import_module` when the name is in `sys.modules` and `_import_module` otherwise.**
>
> Fixed, though not with that shape: `_import_module` is gone, and a fallback to a second memo would have re-imported once for every name `import_source` had resolved live (the commit below measures exactly that order). `import_source` remembers what it last bound per name (`_import_source_cache`) and serves that when the name is gone from `sys.modules` or blocked there with `None`; a live entry is read from `sys.modules`. The reach is narrower than ten call sites suggest, and only codegen names can arrive absent: `IMPORT_NAME`'s `__import__` has just put its own name back, `get_globals_source_and_value` resolves only a module it has just found live under the frame's `__name__`, and probing the user-controlled paths in an earlier revision -- a sourceless context manager returned from the frame or live across a graph break, an `autograd.Function` via a call result or an attribute -- found each resolving only `torch`, `torch._dynamo.utils`, `torch._dynamo.graph_bytecode_inputs` and `torch.autograd.profiler`, all present. `test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module` pins the case with `torch.autograd.profiler` and a spy on `importlib.import_module`, so unrelated imports cannot fail it.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: ec6aec8
Pull-Request: #197303
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 19, 2026
…ast bound

Split for review budget from `[dynamo] Bind the import alias to the live
sys.modules entry` (#197046), the commit directly below: that one makes
`import_source` bind the live `sys.modules` entry whenever there is one and
keeps the memoized `_import_module` in front of that read, for a name since
removed from `sys.modules` or blocked there with `None`; this one replaces the
memo with a cache of what `import_source` last bound, written only once the
alias check has passed, and reads `sys.modules` with nothing in front of it.

`_import_module` is `functools.cache`d for the life of the process: it holds
the first object the process resolved under each name, and nothing clears it.
Below this commit it is what a name binds once the name has left `sys.modules`
-- `del sys.modules[...]`, a `mock.patch.dict(sys.modules)` scope -- or been
set to `None`, the import system's blocked-module sentinel that makes any
import of the name raise `ModuleNotFoundError`, because importing such a name
again would execute the module body inside the trace and bind a second copy of
a module the program still holds, or for `None` raise out of guard
construction (`ModuleNotFoundError` is not in `_compile`'s pass-through tuple,
so that raise surfaces as `InternalTorchDynamoError` with no eager fallback).
But the first resolution is the wrong object to fall back on for the same
reason it was the wrong object to bind: after a handover the traces have been
binding the live module and building guards against it, and the memo still
holds the module before the handover. And the memo is only warm for a name
some trace resolved while it was live: the commit below measures that a memo
cold for a deleted or blocked name imports inside guard construction all the
same, whichever order it and `sys.modules` are read in. `_import_source_cache`
replaces it, keyed by name, holding what `import_source` last bound: each
accepted resolution overwrites the entry, so a name that then leaves
`sys.modules` binds the module the guards this alias roots were built against,
not the one the process saw first.
`test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache`,
inherited from the commit below, gains that pin: after its handover
`_import_source_cache[name]` is the second module, and with the entry popped
and the alias deleted a resolution binds the second module, not the first.
The memo was also written at resolution, before the alias check, so a trace
the check refused with `Import alias already bound` remembered the name all
the same. The cache is written only once the check has passed, alongside the
package record and `output.import_sources`: it is never cleared, so a write
before the check would pin a module the process may later drop on behalf of a
trace that bound nothing. Whether a name is one the cache can serve is decided
where `import_source` branches on it and carried to the write in a local,
`cacheable`: `False` in the `torch_package` arm, whose names resolve through
`_package_imported_modules`, a `WeakValueDictionary`
(`package_importer.py:731`) that holds a packaged module only while its
importer or the user does, so an entry would pin a `torch.package` module the
user has dropped for the rest of the process, and whose names are never read
back from the cache in any case, the read being in the other arm; `True` in
the `sys.modules` arm. A second `"torch_package" in module_name` test at the
write, a hundred lines below the first, would have to be kept in step with it
by hand; the local cannot drift. The write is further guarded by
`isinstance(value, types.ModuleType)`: `sys.modules` accepts any object, and a
non-module entry, which the callers without a module check bind verbatim, is
never remembered, so the cache's `dict[str, types.ModuleType]` annotation holds
by construction.

The live entry is read from `sys.modules` itself, and the memo no longer runs
in front of the read. What the memo's call cost for a present name depended on
the interpreter, since a cold memo is `importlib.import_module`: on 3.12
`_find_and_load` (`importlib/_bootstrap.py:1349-1356`) returns without
touching a lock unless the entry is missing or its `__spec__._initializing` is
set, but 3.10's (`:1022-1034`) has no such gate -- it enters
`_ModuleLockManager` and calls `_lock_unlock_module` for every name, each
through `_get_module_lock`, which brackets its body with the global import
lock (`:185`, `:211`), all of it under `compile_lock`. Measured in an earlier
revision of this commit with spies on `_get_module_lock` and
`_imp.acquire_lock`, resolving a present, initialized name through
`import_module`: 3.10.20, two module-lock and four global-import-lock
acquisitions and 5.5 us per call; 3.12.14, none and 388 ns. The `sys.modules`
read takes no lock on either. The import machinery is now entered in two
cases only: a name absent from `sys.modules` that no trace has resolved before
(a first import, as before), and a name blocked with `None` that no trace has
resolved before (which raises `ModuleNotFoundError`, as before). An entry
whose `__spec__._initializing` is set -- `_load_unlocked` (`:911-950`) sets it
around a first-time execution of the module body -- is served as is. An
earlier revision handed such an entry to `import_module` so the trace would
wait on the module lock as an import statement does; that branch is gone, for
the reason its review gave. From `IMPORT_NAME`, the one caller whose name the
traced bytecode chose, `__import__` has just returned the entry, and
`_find_and_load` already waited out a cross-thread initialization; what can
still be `_initializing` there is same-thread re-entrancy, a module body that
compiles a function importing the module itself, where `_ModuleLock.acquire`
short-circuits on its owner and `import_module` returns the same
half-initialized object, so the branch changed nothing (measured with such a
module at this tree: the spec's flag is set when the compile runs, the compile
succeeds, and the alias and the cache both hold the module itself). The only
caller family the branch could change a value for resolves a name without an
`__import__` of its own -- `get_globals_source_and_value`, the codegen names --
while another thread executes that module's body, and there `import_module`
blocks on that module's lock with `compile_lock` held; if the other thread's
body re-enters Dynamo it blocks on `compile_lock`, and importlib's deadlock
detection, which walks module-lock edges only, cannot see the cycle. The
comment at the read says so, so the next reader does not put the wait back.
The commit below waited in that case only while its memo was cold and served
the previous incarnation once warm; this commit serves the live entry as it
stands, which is what the same-thread case always got. No test pins it: the
observable difference is a two-thread timing, and the single-threaded dispatch
pin an earlier revision had (`..._waits_on_its_import`, which asserted the
`import_module` call, not a wait) went with the branch.

The resolution reads nothing off the module it resolves. The commit below's
`_import_module` made `_find_and_load`'s `getattr(module, "__spec__", None)`
on 3.11+ for the first resolution of each name per process, none on 3.10; here
no version reads an attribute off the module, and the alias check below reads
`__name__` out of the instance dicts as before.
`test_import_alias_check_does_not_run_a_module_getattribute` pins the
resolution as well as the check: its module class now raises on any read made
with `import_source` on the stack, matched by function name and module, and on
the commit below, on 3.12, the test errors with the module's raise reached from
`_find_and_load` under `_import_module`.

The write rule loses its condition. Below this commit a writer's same-named
module -- `CompilePackage.install()`, an artifact load seeding its guard scope
-- is replaced when the name is live and left in the slot when the name is
gone or blocked, the memo being no less stale than the writer's module. Now
`f_globals[alias] = value` runs unconditionally: `value` is the live entry
whenever `sys.modules` holds a module under the name, or the one a first import
has just put there, and what this process's traces last bound when the name is
gone or blocked with `None`; there neither module is the live entry, and the
cached one is the object the guards this alias roots were built against.
`test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`
pins it: a trace binds and caches one module, `install()` in the same globals
binds a second of the same name, and with the entry then popped, and again
with it set to `None`, a resolution replaces the installed module by the cached
one; on the commit below the installed module stays in the slot, both arms.

`_import_module` is deleted; its last caller is this read. The cache is never
cleared, not by `torch._dynamo.reset()` either, so a module the process has
dropped stays alive in it; the memo retained modules the same way, so this is
not new retention. The declaration comment is the one place that says so; an
earlier revision repeated it in `reset()`, next to nothing that read it. A
`reset()` that did clear the cache fails the removed-name test, whose deleted
and blocked compiles follow a `reset()`. Only names the traced bytecode never
imported can arrive absent or blocked: `IMPORT_NAME`'s own `__import__` has
just put its name back or raised, `get_globals_source_and_value` resolves only
a module it has just found live under the frame's `__name__`, and the other
callers pass torch's own or stdlib names for codegen. `torch.autograd.profiler`
is such a name: `codegen.py` resolves it on every compile under
`config.record_runtime_overhead` (on by default) for the runtime-overhead
record in the compiled frame's prologue, and the only function-scope import of
it in torch/ (`torch/profiler/_utils.py`) is off the compile path, so a trace
with the entry deleted has no other reason to re-import it. The removed-name
test, inherited from the commit below, uses it for that reason.

Order to review: `symbolic_convert.py`, the `_import_source_cache` declaration
replacing `_import_module`, then the `sys.modules` arm of `import_source` (the
read, the cache fallback, the `import_module` fallback and the comment on the
entry still initializing), the `cacheable` local in both arms, and the write
block (record, cache write, unconditional alias write); then `test_package.py`:
the gone-name test (the one new case), the frame-walk probe at the top of the
file and the extended getattribute test, the empty-slot test's cache pin and
comptime-driven resolution, the cache assertions in the refused-alias tests,
the `torch_package` test and the non-module-value test, and the teardowns,
where `_import_module.cache_clear()` becomes `_import_source_cache.pop(name,
None)` or goes.

Behaviour change against the commit below, pinned below: a name gone from
`sys.modules` or blocked there with `None` binds what `import_source` last
bound under it rather than the first object the process resolved
(`test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache`, its
resolution after the pop); a writer's same-named module in the slot is
replaced for a name gone or blocked
(`test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`);
the resolution reads no attribute off the module it resolves, where the memo's
`import_module` did on 3.11+ for the first resolution of a name
(`test_import_alias_check_does_not_run_a_module_getattribute`); a refused trace
remembers nothing under the name (`test_import_alias_taken_by_a_non_module_graph_breaks`,
`test_import_alias_the_trace_refused_is_not_recorded_for_install`, by mutation:
with the write moved above the check, five failures); a `torch_package` name
and a non-module value are bound but never remembered
(`test_import_alias_accepts_a_stale_torch_package_module`,
`test_import_alias_check_with_a_non_module_value_accepts_the_key_alone`, each
by mutation of the guard it pins); and an entry still executing its body is
served as is rather than waited on when the name is one no trace resolved
before, which no test pins (above). Not a change: a name removed from or
blocked in `sys.modules` between two traces still binds the module the program
holds, and the import machinery is not entered for it
(`test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module`,
which passes on the commit below, whose memo serves the name, and pins this
commit against a cache read dropped).

Test Plan:

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

One case joins the commit below's twenty-two: twenty-three `test_import_alias`
instances. Seven of the inherited ones gain cache assertions or a cache-driven
leg, three have comments reworded, and every teardown changes. The new one,
`test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`,
compiles a function importing a scratch module under a `CompilePackage`, saves
it, hands the `sys.modules` entry to a second module of the same name and
loads and installs the package, so `install()` binds the alias to the second
module while the cache holds the first; then, in two `subTest` arms with the
alias put back on the installed module before each, pops the entry, and sets
it to `None`, and compiles a probe whose bytecode never imports the name and
whose comptime callback calls `import_source(name, True)` on the live
translator as `IMPORT_NAME` does -- the function's own import statement cannot
run once the entry is gone -- pinning that the alias holds the first module
afterwards and, at the end, that the cache still does. The empty-slot test,
after its handover, asserts `_import_source_cache[name]` is the second module
and then, with the entry popped and the alias deleted, drives `import_source`
the same way from a probe compiled in the same globals, and asserts the
returned source names the alias and the alias binds the second module; an
earlier revision called the unbound method on a `types.SimpleNamespace`
translator, which bypassed the real `OutputGraph` and `CompilePackage`. Its
scratch name is now `torch_test_package_import_alias_handed_over`. The
extended getattribute test's `_ImportAliasHookedModule` used to raise on a
`__dict__` read anywhere, and now raises on any read made with
`InstructionTranslatorBase.import_source` on the Python stack, matched by
function name and by the frame's module (`__import__` and
`PythonModuleVariable` read `__spec__` and `__name__` off a module by design,
so the stack is the discriminator); with no read left for the hook to observe,
its positive control is static: the test asserts that
`InstructionTranslatorBase.import_source.__wrapped__` (the `cache_method`
wrapper keeps the function under `__wrapped__`) has the `co_name` and
`__module__` the walk matches, so a renamed or inlined `import_source` fails
there rather than letting every read through. The refused-alias tests:
`test_import_alias_taken_by_a_non_module_graph_breaks` pins, per case, that
neither the `fullgraph` refusal nor the skipped frame leaves the name in
`_import_source_cache`, and `test_import_alias_graph_break_is_cached_until_reset`
pins the name absent after the refusal and present, as the module, after the
compile that binds the alias; `test_import_alias_the_trace_refused_is_not_recorded_for_install`
pins the name absent from the cache after the checkpointed refusal and again
after `install()`. The two tests that reach the cache write with a value one
of its guards refuses each gain one `assertNotIn` on the cache:
`test_import_alias_accepts_a_stale_torch_package_module` asserts the mangled
name absent after its compile, and
`test_import_alias_check_with_a_non_module_value_accepts_the_key_alone` asserts
the key absent after its accepted call. The removed-name test's comment and
teardown lose the memo, and the installed-live-module test's and the nn hook
test's comments no longer say "memo", the helper being gone.
Every `test_import_alias` test whose scratch name gets cached pops it from
`_import_source_cache` in `finally`, alongside the alias and the entry --
sixteen at this commit, in place of the `_import_module.cache_clear()` that
named the deleted helper: the pop only matters where a later compile runs with
the name absent or blocked, but one teardown shape keeps a test-minted module
from outliving its test either way. Six have nothing to pop, and the commit
below's `cache_clear()` simply goes: `test_import_alias_the_trace_refused_is_not_recorded_for_install`,
whose one trace is refused before the write and which asserts the name absent
instead; `test_import_alias_is_not_bound_to_a_non_module_import`, whose entry
`IMPORT_NAME` rejects before `import_source` runs, and a non-module is never
cached in any case; `test_import_alias_accepts_a_stale_torch_package_module`
and `test_import_alias_taken_in_a_torch_package_slot_is_a_hard_error`, whose
names take the `torch_package` arm, which never writes the cache (the first
asserts that); and `test_import_alias_taken_at_codegen_is_a_hard_error` and
the removed-name test, whose name is `torch.autograd.profiler` and whose
cached object is the process's own module, which a pop would not free and the
next compile re-caches.

Measured against the commit below's `symbolic_convert.py`, checked out under
this test file with a stub `_import_source_cache = {}` added so the file
imports: four of the twenty-three fail there. The getattribute test errors on
3.12 with `InternalTorchDynamoError: RuntimeError: module __getattribute__
read __spec__ inside a trace`, the read made by `_find_and_load`
(`_bootstrap.py:1356`) under `_import_module`; the gone-name test fails both
arms on `assertIs(fn.__globals__[alias], old)`, the installed module left in
the slot, and then errors on its closing cache pin against the empty stub; the
empty-slot test errors with `KeyError` on `_import_source_cache[name]`,
nothing having written the cache; and
`test_import_alias_graph_break_is_cached_until_reset` errors the same way on
its `assertIs(_import_source_cache[name], module)` after the compile that binds
the alias. The other nineteen pass there, the removed-name test, whose memo
serves the name, and the `assertNotIn`s on an empty stub among them. Those are
pinned at this tree by mutation of `symbolic_convert.py`, each mutant run
against the twenty-three and restored afterwards: with the write gated as the
commit below gates it (alias absent, or holding the value, or the name live),
the gone-name test fails both arms (and the `torch_package` test errors, that
gate reading its name, which is never in `sys.modules`, as not live); with the
cache write made `_import_source_cache.setdefault(module_name, value)` -- a
first-resolution memo one indirection further in -- the empty-slot test alone
fails, on `assertIs(_import_source_cache[name], new)` after the handover; with
the cache read dropped, importing whenever the entry is absent, the
removed-name test fails its deleted case on the spy (`'torch.autograd.profiler'
unexpectedly found in ['torch.autograd.profiler']`) and errors its blocked
case with `InternalTorchDynamoError: ModuleNotFoundError: import of
torch.autograd.profiler halted; None in sys.modules`, and the empty-slot and
gone-name resolutions error with `ModuleNotFoundError` for their scratch
names; with the `torch_package` arm's `cacheable` flipped to `True`, the
`torch_package` test alone fails; with the `isinstance(value,
types.ModuleType)` conjunct dropped from the write, the non-module-value test
alone fails; with the cache write moved above the alias check, five failures,
`assertNotIn` in each of the three `taken_by_a_non_module` cases, in
`cached_until_reset` and in the install test; and with a
`getattr(value, "__spec__", None)` added to the resolution, the getattribute
test alone errors, with the hook's `RuntimeError`. Neither of the two guard
mutants changes what a compile binds today -- one pins a dropped
`torch.package` module for the process, the other opens a path `IMPORT_NAME`
blocks -- so the annotation and the comments at the write are held by those
two assertions and by nothing else. On this commit the twenty-three pass and
the whole file is 101 tests, OK (skipped=40, expected failures=1).

```
python test/dynamo/test_package.py -k test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache
python test/dynamo/test_package.py -k test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module
python test/dynamo/test_package.py -k test_import_alias_check_does_not_run_a_module_getattribute
python test/dynamo/test_package.py -k test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache
python test/dynamo/test_package.py -k test_import_alias_taken_by_a_non_module_graph_breaks -k test_import_alias_graph_break_is_cached_until_reset -k test_import_alias_the_trace_refused_is_not_recorded_for_install
python test/dynamo/test_package.py -k test_import_alias_accepts_a_stale_torch_package_module
python test/dynamo/test_package.py -k test_import_alias_check_with_a_non_module_value_accepts_the_key_alone
```

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

> **FAQ: the `_initializing` -> `importlib.import_module` branch cannot change `value` on the one caller that can reach it from traced bytecode, since `IMPORT_NAME`'s `__import__` has just waited, and its one effectful path -- a codegen or `get_globals_source_and_value` caller resolving a name another thread is executing -- blocks on that module's lock under `compile_lock`, a lock-order cross `_has_deadlocked` cannot see. Drop it and serve the entry as is, or state the hazard at the call site.**
>
> Dropped, and the hazard is stated where the wait would go. Reachability was probed at this tree with a scratch module whose body compiles a function that imports the module itself: `IMPORT_NAME`'s `__import__` hands back the entry with `__spec__._initializing` still `True`, the compile succeeds, and the alias and `_import_source_cache` both hold that module -- the object `import_module` would have returned too, its lock being owned by the same thread. So from `IMPORT_NAME` the branch was two lock acquisitions for nothing, and from the callers with no `__import__` of their own it was the wait the finding describes, per compile rather than once per process. What is given up is the single-threaded dispatch pin (`..._waits_on_its_import` asserted that `import_module` was asked, not that anything waited) and the two-thread measurement an earlier revision made; the commit below waited in that case only while its memo was cold, and once warm served the previous incarnation, so no tree in this stack has made that wait reliably. `test_import_alias_check_does_not_run_a_module_getattribute` no longer plants a spec with a raising `_initializing` property, since nothing reads a spec. With the branch went `import importlib.machinery` in both files and the `_ImportAliasProbeSpec` helper.

> **FAQ: dropping the `if not conflict or live:` gate for an unconditional `f_globals[alias] = value` is a reachable behaviour change no test covers: the alias bound by `install()` or `_seed_guard_scope()` to a same-named but different module, which the name check accepts, and the name then absent from `sys.modules` or blocked with `None`. Add a pin.**
>
> Added: `test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache`, two independent resolutions of one name (a trace under a `CompilePackage`, then `install()` of that package after a handover) and its removal, in a deleted arm and a `None` arm. On the commit below both arms fail on `assertIs(fn.__globals__[alias], old)`, the installed module left in the slot; here both pass, and with this tree's write gated the way the commit below gates it, both fail again. The write is reached through the live translator from a comptime callback, because the traced function's own import cannot run with the entry gone.

> **FAQ: the empty-slot test hand-rolls a `types.SimpleNamespace` translator and calls the unbound `InstructionTranslatorBase.import_source(tx, name)`, bypassing the real `OutputGraph` and `CompilePackage`; the file already drives `import_source` on a resolution no bytecode reaches through a comptime callback on the live translator. Use that shape.**
>
> Done: after the handover and the pop, a probe function whose bytecode never imports the name is compiled in the same globals, and its comptime callback calls `tx.import_source(name, True)` on the live translator, as `IMPORT_NAME` would; the test asserts the returned source's `global_name` is the alias and that the alias binds the second module. The new gone-name test uses the same shape. The `setdefault` mutant is still the one failure among the twenty-three, on the cache pin after the handover.

> **FAQ: the comment in `torch/_dynamo/__init__.py:171-174` restates the declaration comment and dangles above an unrelated call; the 16-line and 9-line comments at the read and the write restate CPython internals. Drop the first, trim the others to the load-bearing facts.**
>
> The `__init__.py` comment is gone, and this commit no longer touches that file; the declaration says the cache is never cleared, `reset()` included. The read's comment is down to what a reader needs at the site -- the live entry is what `IMPORT_NAME` pushed, `import_module` takes the module lock for a present name on 3.10, a removed or blocked name keeps what it last resolved to because re-importing would run the module body inside the trace, and an initializing entry is served as is with the lock-order reason -- and the write's to which module wins and why. The derivations are in this message.

> **FAQ: nothing pins that `_import_source_cache` holds what `import_source` last bound under a name rather than the first thing it resolved: `_import_source_cache.setdefault(module_name, value)` passes the whole `test_import_alias` family. Extend the empty-slot test, which already hands a name over from `old` to `new`, with one more compile after `sys.modules.pop(name)`, asserting the alias binds `new` and not `old`.**
>
> Pinned there, with the resolution driven from a probe rather than by the test function's own import. That import statement cannot run once the entry is popped: measured at this tree, eager raises `ModuleNotFoundError` and the compile raises `Unsupported: Import failure` before `import_source` runs, binding nothing. The cache read is reached from a compile only for a name the traced bytecode never imports -- codegen's `torch.autograd.profiler`, which the removed-name test uses and which is one module object throughout -- so the empty-slot test asserts `_import_source_cache[name] is new` after its handover and then, with the entry popped and the alias deleted, compiles a probe whose comptime callback calls `import_source(name, True)` on the live translator, and asserts the alias binds `new`. The `setdefault` mutant is the one failure among the twenty-three, on the first assertion.

> **FAQ: "A writer's same-named module is replaced: value is the live entry whenever there is one" licenses dropping the old gate, and it is not true in one reachable case: for a name blocked with `None`, `.get` returned `None`, which `is not value`, so the old code kept a writer's binding of a different same-named object and this code overwrites it.**
>
> The case is as described, and it is now pinned by the gone-name test's `None` arm as well as its deleted arm: two writers (`install()`, an AOT load seeding its guard scope) resolve independently through `import_module`, so a `None`-blocked name can find the alias bound to one same-named object while the cache holds another, and the name check passes since both answer the same `__name__`. The commit below kept the writer's module in both absent forms (its gate is `live`, an entry present under the name); now both replace it, and the comment at the write says which object wins and why: neither is live, and the cached one is what this process's traces bound and built guards against.

> **FAQ: five pre-existing tests lost `_import_module.cache_clear()` from their `finally` without gaining `_import_source_cache.pop(name, None)`, while the new tests pop; that is two teardown conventions in one file and a process-lifetime strong reference to each test-minted `ModuleType`.**
>
> Every test whose scratch name gets cached pops now -- sixteen at this commit, the accepted-names fixture and the non-module-value test among them -- and the message says when the pop is load-bearing: only where a later compile runs with the name absent or blocked. Six `test_import_alias` tests have no pop, deliberately: the refused-alias install test's one trace is refused before the cache write, which sits below the alias check, and the test asserts the name absent from the cache instead; the removed-name test's and the codegen test's name is `torch.autograd.profiler` and the object cached is the process's own module, which the pop would not free and the next test re-caches; the non-module import test's entry never reaches `import_source`, `IMPORT_NAME` rejecting it first, and would not be cached if it did; and the two `torch_package` tests' names take the arm that never writes the cache. The commit below cleared the memo in all of those; the line simply goes here.

> **FAQ: `_import_source_cache: dict[str, types.ModuleType]` is not what the code stores: `sys.modules` accepts any object, yet the write caches `value` unconditionally, so a non-module can be cached and later served and bound. Annotate the cache `dict[str, Any]` and say why, or hoist the `isinstance` so a non-module is never cached.**
>
> Hoisted, in the sense that keeps the annotation honest: the cache write is guarded by `isinstance(value, types.ModuleType)`, on the value finally resolved, together with the `cacheable` local the `sys.modules` arm sets, and sits below the alias check with the package record and `output.import_sources`, so a non-module reaching `import_source` is bound as is by the callers that make no module check and remembered by nothing. `test_import_alias_check_with_a_non_module_value_accepts_the_key_alone` pins it, reaching the write from a comptime callback on the live translator with a `SimpleNamespace` under the key and asserting the key absent from `_import_source_cache` after the accepted call; with the conjunct dropped it fails there. It is not pinned by the existing non-module test, which cannot reach the write: `IMPORT_NAME` is the one caller whose name the traced code chose, and it graph-breaks on `Bad import result` before `import_source` runs (that test's own point).

> **FAQ: the "zero lock acquisitions" measurement rests on the `_initializing` gate at `_bootstrap.py:1355-1356`, which does not exist before CPython 3.11; on 3.10 `_find_and_load` takes the module lock and calls `_lock_unlock_module` unconditionally, under `compile_lock`, on every compile. Either measure it there or serve a live initialized `sys.modules` entry directly.**
>
> The second option is taken. The earlier answer was measured on 3.12 only, and 3.10.20 gives the opposite result: `importlib.import_module` of a present, initialized name is two `_get_module_lock` calls and four `_imp.acquire_lock` calls and 5.5 us per call, against none and 388 ns on 3.12.14. `import_source` now reads `sys.modules` itself: a present entry is served as is, with no lock on either version, and `import_module` is reached only for an absent or `None` entry the cache has not seen -- a first import or the blocked-module raise, both as before -- so the cost is the same on every supported interpreter.

> **FAQ: dropping the process-wide memo means every compile re-enters CPython's module-lock path, which can raise `_DeadlockError` or hang while `compile_lock` is held: thread A executes module `M`'s body, thread B compiles a frame whose globals are `M.__dict__` and blocks on `M`'s lock under `compile_lock`, and if A's body compiles the two deadlock.**
>
> No compile enters the module-lock path for a present entry now, initializing or not: `import_source` reads `sys.modules` and serves what it finds, and `import_module` is reached only for a name absent or blocked that no trace has resolved before, exactly where the commit below's cold memo reached it. The scenario the finding describes -- B blocked on `M`'s lock under `compile_lock` while A's body wants `compile_lock` -- is the one the dropped `_initializing` branch would have walked into per compile, and the comment at the read names it as the reason the entry is served as is. `_DeadlockError` itself needs A to be blocked on a module lock B holds (`_ModuleLock.has_deadlock` walks `_blocking_on`), which B, holding no module lock, cannot cause; a wait on `compile_lock` is invisible to that walk, so the outcome of the dropped branch was a hang, not an error.

> **FAQ: `CompilePackage.install()` is the other writer of the same `__import_*` alias, and it resolves with a bare `importlib.import_module(module_name)`, so a name gone from `sys.modules` at install time raises `ModuleNotFoundError` out of `install()`, the failure mode the removed-name test rules out for the tracing side. Share the resolution helper, or say why `install()` is exempt.**
>
> Exempt, because neither hazard the cache guards against exists at install time. The cache exists so that a trace never runs a module body -- `import_source` is called from guard construction, inside the compile -- and never turns `ModuleNotFoundError` into an `InternalTorchDynamoError` with no eager fallback. `install()` runs in the user's own call, outside any trace: measured in an earlier revision, with the name deleted it raises `builtins.ModuleNotFoundError: No module named '...'`, and blocked with `None` it raises `import of ... halted; None in sys.modules`, both plain, both what the program's own `import` statement raises at that point, and a re-import there is an ordinary import at an ordinary time. Sharing the cache would also change nothing in the case the finding describes: a process that only loads has traced nothing, so the cache is empty, and the helper would fall through to `import_module` exactly as `install()` does today. The tracing-side cache is about a trace's view of a name the program still holds; `install()` has no trace and no such view.

> **FAQ: dropping the `functools.cache`d `_import_module` means a name resolved earlier and then removed from `sys.modules` re-runs the import machinery inside the trace, executing the module body again or raising `ImportError` as an `InternalTorchDynamoError`; keep both properties with `importlib.import_module` when the name is in `sys.modules` and `_import_module` otherwise.**
>
> Fixed, though not with that shape: `_import_module` is gone, and a fallback to a second memo would have re-imported once for every name `import_source` had resolved live (the commit below measures exactly that order). `import_source` remembers what it last bound per name (`_import_source_cache`) and serves that when the name is gone from `sys.modules` or blocked there with `None`; a live entry is read from `sys.modules`. The reach is narrower than ten call sites suggest, and only codegen names can arrive absent: `IMPORT_NAME`'s `__import__` has just put its own name back, `get_globals_source_and_value` resolves only a module it has just found live under the frame's `__name__`, and probing the user-controlled paths in an earlier revision -- a sourceless context manager returned from the frame or live across a graph break, an `autograd.Function` via a call result or an attribute -- found each resolving only `torch`, `torch._dynamo.utils`, `torch._dynamo.graph_bytecode_inputs` and `torch.autograd.profiler`, all present. `test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module` pins the case with `torch.autograd.profiler` and a spy on `importlib.import_module`, so unrelated imports cannot fail it.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 6ac6add
Pull-Request: #197303
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head f9bf2afd51ff; this PR was deliberately re-sliced after 7fed4fa, and the design this review reads as missing -- _import_source_cache, the sys.modules-first read, the cacheable local and the non-module cache guard -- was moved up into #197303, so #197046 is now the smaller "bind the live entry" step. Fifteen of the findings are addressed at f9bf2afd51ff, ten are owned by #197303 or #197135, five are declined as non-blocking, and one is open: the published body is still the pre-reslice text. Verified against a real build: test/dynamo/test_package.py -k import_alias is 23 tests OK, the whole file 101 OK (skipped=40, expected failures=1), test/dynamo/test_aot_compile.py 337 OK (skipped=6), the seven parent failures the message names reproduce exactly when the parent's symbolic_convert.py is checked out under this test file, and each mutant below was run and restored.

1. > The description and the tree have diverged. [...]

Open, for the body and not the commit message: the message at f9bf2afd51ff was rewritten for the re-sliced scope, names #197303 as the commit above, keeps _import_module and says so, and its three load-bearing claims all reproduce (the seven parent failures, all ten -k selectors resolving, every test_import_alias test clearing the memo). The published body, though, is still the pre-reslice text -- _import_source_cache, __spec__._initializing, "eighteen test_import_alias tests", the refs to symbolic_convert.py:264 / :2437-2464 / :2533-2538, and a Test Plan line for test_import_alias_of_an_initializing_module_waits_on_its_import -- none of which is in this tree. The body prose is queued for the author to replace with the head commit message at f9bf2afd51ff, with the four cache/_initializing FAQ answers moved to #197303. On the individual rows: the removed-name test is back at test_package.py:2105 with its importlib.import_module spy and both the deleted and None-blocked arms, all ten Test Plan selectors match, and the two counts that are still off by one at f9bf2afd51ff ("twenty-two instances" for 23, "100 tests" for 101, plus a stale "207" for test_aot_compile.py's 337) go with the body rewrite.

2. > torch/_dynamo/symbolic_convert.py:2435 -- memo = _import_module(module_name) runs before entry = sys.modules.get(module_name) at :2436, unconditionally, on every resolution. [...]

Owned by #197303, and the order here is deliberate: the parent resolves through value = _import_module(module_name) with no sys.modules read at all, so the cold-memo import, the None-blocked InternalTorchDynamoError and the initializing-entry wait are all reachable at 875857937ff exactly as they are here -- this commit does not widen them. The reorder you prescribe is measured worse and now fails a test: applying value = entry if entry is not None else _import_module(module_name) at f9bf2afd51ff breaks test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module in both arms (2 failures), because the memo is then never primed by a live resolution and the ordinary sequence -- a name resolved live, deleted before the next compile -- re-imports inside the trace. What removes the hazard is not a read order but a fallback holding what this process's traces bound, which is #197303's _import_source_cache; that commit deletes _import_module outright and reads sys.modules first. The cold case is documented at the call rather than papered over.

3. > Related, same lines: the comment at :2430-2434 says "The memo is called first so that it holds every name resolved here: it serves one since removed from sys.modules or blocked there with None, where importing again would run the module body inside the trace." [...]

Already addressed at f9bf2afd51ff: the comment at symbolic_convert.py:2441-2448 no longer claims the call keeps the memo fresh. It now says the call primes the memo, states the functools.cache semantics inline ("keeps the first return and never recomputes"), and ends with the residual you identified -- "A memo still cold for such a name imports all the same, as it did before" -- so the comment asserts only properties the code has.

4. > torch/_dynamo/symbolic_convert.py:2381-2386 -- nn_modules_globals_vt's value is now torch.nn.modules.module while its guard root is the alias, which import_source now points at the live sys.modules entry, so the two can be different objects. [...]

Owned by #197135, which roots the source at the defining module whenever the alias binds another; as you note, keeping it a separate commit is a human decision that is on the record, and the intermediate state is measured rather than assumed. The two sub-points are addressed here: the hand-seeded fn.__globals__[alias] = shim is gone, the test sets only sys.modules[name] = shim and now asserts the alias binds it (test_package.py:1663, :1678), and the comment at :1625-1633 was rewritten for a value that is the defining module read directly. The test also pins the failure text itself, the CLOSURE_MATCH guard-construction error on G[alias]._global_forward_hooks[<id>].

5. > test/dynamo/test_package.py -- no test in the file runs a compile while its target name is absent from sys.modules or blocked with None, which is the entire domain of the value = entry if live else memo fallback at symbolic_convert.py:2438. [...]

Already addressed at f9bf2afd51ff: test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module (test_package.py:2105) compiles under record_runtime_overhead=True against torch.autograd.profiler, then in two subTest arms deletes the sys.modules entry and sets it to None, each under a mock.patch.object(importlib, "import_module", wraps=...) spy, asserting the name was never asked for, that the entry is still absent or still None, and that the alias holds the module the program holds -- with the alias deleted first so the binding checked is that compile's write. It restores the single sys.modules key in finally rather than snapshotting the dict, for the reason you gave in an earlier round.

6. > Deleting the fallback entirely (value = entry) fails nothing -- binding None into the alias is unobservable here. [...]

Already addressed at f9bf2afd51ff: that mutant now fails, 2 errors, both arms erroring with AttributeError: 'NoneType' object has no attribute '_is_profiler_enabled' as the prologue reads the None bound into the alias. Run in a worktree at f9bf2afd51ff against the 23 test_import_alias instances and restored afterwards.

7. > Deleting _import_module and reading sys.modules[module_name] directly fails nothing, including test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache (:1640), whose name promises to distinguish the live entry from the cache. [...]

Already addressed at f9bf2afd51ff: that mutant now fails too, 2 errors, on the removed-name test's deleted arm where the plain subscript raises for a name that is no longer in sys.modules. Your reading of the empty-slot test was right -- it distinguishes "not a stale object" -- and the distinction you asked for is pinned by the removed-name test instead, which is the only place a compile reaches import_source with the name absent.

8. > Making the memo call lazy (option C above, the fix) fails nothing -- so the suite cannot tell the safe ordering from the unsafe one. [...]

Already addressed at f9bf2afd51ff, in the direction the measurements support: the lazy mutant fails 2 tests, both arms of the removed-name test, the deleted arm on the spy ('torch.autograd.profiler' unexpectedly found) and the blocked arm on the alias holding a re-imported copy. So the suite now does distinguish the two orderings; see item 2 for why the eager order is the one kept.

9. > The if not conflict or live: write condition at :2498 guards "alias holds another writer's same-named module and the name absent from sys.modules" -- unreachable, since no test compiles with the name absent. [...]

Declined: still accurate -- dropping the gate for an unconditional f_globals[alias] = value passes all 23 instances, since the removed-name test deletes the alias before each compile and so never sets up the conflict -- but the gate is the parent's, this commit only redefines live, and #197303 deletes it outright in favour of an unconditional write. A test written for it here would pin code that is gone one commit up.

10. > test/dynamo/test_package.py:1920 -- test_import_alias_check_with_a_non_module_value_accepts_the_key_alone puts a types.SimpleNamespace under its sys.modules key (:1938, :1957) and reaches import_source, so the eager call at symbolic_convert.py:2435 memoizes that non-module under _import_module's -> types.ModuleType annotation (:261). [...]

Declined as non-blocking, though confirmed: importlib.import_module does return a non-module sys.modules entry verbatim, so the annotation is violated during that test's run and the _import_module.cache_clear() in its finally (:2100) is what contains it. The annotation is pre-existing on a helper that has no runtime type check and that #197303 deletes, along with the assertNotIn(key, _import_source_cache) half of your point, which needs that commit's cache to exist. Narrowing the annotation here would churn a function that is about to be removed.

11. > test/dynamo/test_package.py:1471, :1587, :1770, :1893 -- four test_import_alias tests mint a sys.modules entry or resolve a name and do not call _import_module.cache_clear() in finally, where the other fourteen do. [...]

Already addressed at f9bf2afd51ff: all 22 test_import_alias methods now clear the memo in finally, checked by enumerating the family. The nn-hook test, where you flagged the omission as load-bearing, clears it at :1683 and its comment says why ("cleared in finally so the shim cannot be left in it"), so the shim can no longer be memoized for the rest of the process. The two out-of-family cases you name, test_uninstall_keeps_a_global_it_did_not_bind (:752) and test_file_change (:861), still do not clear it; they are pre-existing, keep their names live across their compiles, and are moot at #197303 where the memo is gone.

12. > Two things block. [...]

The first stands against the body and is queued for the author to replace with the commit message at f9bf2afd51ff (item 1); the commit message at f9bf2afd51ff is accurate and independently verified, so the tree/message half no longer holds. The second is resolved or relocated: the comment no longer claims the functools.cache property (item 3), both deleted tests are back with the removed-name test mutation-pinned against three separate mutants of the resolution (items 5-8), and the ordering hazard is the parent's, is unchanged by this commit, and is removed by #197303 rather than by a read order (item 2). On your verification note: I could run everything this round -- 23 import_alias instances OK, the whole file 101 OK, test_aot_compile.py 337 OK, the seven parent failures reproduced, and four mutants run and reverted.

@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 27m 17s —— View job


Re-reviewed at f9bf2afd — the re-sliced tree is much smaller than the one rounds 3-11 read, I found no correctness problem in it, and what is left is two comments/names inside test_package.py that the re-slice falsified, plus the two items the author already owns (the published body and the landing order).

Full review

PR Review: #197046

Summary

After the re-slice, the production change is 22 lines in one file: import_source binds the __import_* alias to the live sys.modules entry (symbolic_convert.py:2450-2453), keeping the functools.cached _import_module as the fallback for a name since deleted or blocked with None, and nn_modules_globals_vt reads torch.nn.modules.module directly instead of through that memo (:2382-2387). The _import_source_cache / __spec__._initializing / cacheable design that rounds 3-8 reviewed is not in this tree — it moved up to #197303 — so most of those rounds' conclusions no longer apply here, as the author's round-11 reply says. I re-derived the remaining hunks from scratch rather than carrying forward.

Three things I checked and found clean, since two of them were raised as suspicions in earlier rounds and one was raised by a sub-agent this round:

  • live's meaning did not drift. It reads as "value is the live sys.modules entry" in both versions: the parent set it to sys.modules[name] is value, and here live = entry is not None is paired with value = entry if live else memo, so live still implies value is sys.modules[name]. The write comment at :2522-2527 and the gate if not conflict or live are consistent with that.
  • No new in-trace import. The parent also called _import_module(module_name) unconditionally, so the cold-memo import, the None-blocked ModuleNotFoundError, and the initializing-entry module-lock wait are all reachable on the base at the same frequency. This commit narrows what that value is used for; it does not widen when the call happens.
  • The removed-name test's reused patcher does not leak calls between its two arms. _patch.__enter__ builds a fresh MagicMock on every entry (/usr/lib/python3.12/unittest/mock.py:1512, with self.new left at DEFAULT), so call_args_list is empty at each with spy as import_module:. A sub-agent reported the opposite; it is wrong, and assertNotIn(name, asked) (test_package.py:2141) is per-arm as intended.

Also verified the value side of the nn_modules_globals_vt change: torch/nn/__init__.py:8 does from torch.nn.modules import * and torch/nn/modules/__init__.py:1 does from .module import Module, nn is absent from _lazy_modules (torch/__init__.py:3413-3419), neither package defines a module-level __getattr__, and nothing in torch/nn/modules/__init__.py shadows the name module, so the attribute chain is the defining module unconditionally after import torch.

Code Quality

  • test/dynamo/test_package.py:1298-1304 — the comment on test_import_alias_keeps_the_installed_live_module is pre-reslice and its last sentence is now false. It describes the mechanism as a memo comparison — "The memo is taken at the first trace of the name ... A later trace in the same globals finds the two disagreeing and must not put the memoized module back" — but at this tree the memo is never compared against the slot for a live name: value is the sys.modules entry and the alias is simply bound to it. And "The sibling below pins the memo written back and the change unseen" points at test_import_alias_rebinds_the_installed_module_to_the_live_entry (:1353), which this PR renamed and inverted to pin the opposite — the alias rebound to the live entry (:1398) and a change to the live module recompiling (:1399-1401). Worth noting this test is itself inherited and passes on the base (I traced it: with value = memo = old, live is False and conflict is True, so the parent skips the write and the alias keeps new either way), so it is the comment and not the test that this PR made wrong. A reader who follows that cross-reference lands on a test asserting the negation of what they were sent to find. Fix this →

  • test/dynamo/test_package.py:1579 — test_import_alias_of_an_empty_slot_reads_an_attribute_the_cached_module_lacks names its setup instead of its outcome, and the setup it names is the parent's failure mode. The body now asserts the compile succeeds and agrees with eager (:1616) with the alias holding the live module (:1617); the cached module lacking EXTRA is precisely the thing the test proves is not consulted. Every other name in this family states a conclusion — ..._is_the_live_entry_not_the_cache, ..._keeps_its_module, ..._is_a_hard_error, ..._graph_breaks — so someone grepping for what happens when the cached module lacks a read attribute finds this test and has to read the whole body to learn the answer is "nothing". Something like test_import_alias_of_an_empty_slot_reads_an_attribute_only_the_live_module_has says what the assertions say. Fix this →

Backward Compatibility

  • torch/_dynamo/symbolic_convert.py:2382-2387 — restating once for the record, not re-arguing: the value (torch.nn.modules.module) and its guard root (the alias, now the live sys.modules entry) can be two different objects, and with a global forward hook registered on the defining module plus that entry rebound, the CLOSURE_MATCH on G[alias]._global_forward_hooks[<id>] raises out of guard construction as an InternalTorchDynamoError — pinned deliberately by test_import_alias_nn_hook_guards_read_the_live_entry_the_alias_binds (test_package.py:1624-1685), which now asserts the alias binds the shim (:1663) rather than hand-seeding it, and repaired only by [dynamo] Root the global nn.Module hook guards at the defining module when the alias binds another #197135. The author's position is on the record across six rounds and the intermediate state is measured; whether a red middle commit is acceptable to bisect through remains the human call. One narrower note on that test: the no-hook arm's assertEqual(fn(*args), compiled_fn(*args)) (:1662) would pass whether the value were the defining module or the shim, since both have no hooks registered at that point — it is the hook arm's raise that distinguishes them, so the two arms are not independent coverage of the value change.

Recommendation

Needs Discussion

No blocking code finding: the re-sliced hunks hold up under an independent re-derivation, the three suspicions I carried in (the live rename, a new in-trace import, the reused mock patcher) are all unfounded, and the fallback and the write-condition change are each pinned by a test that discriminates against the base. What is left is two stale test comments/names from the re-slice, plus the two items the author already flagged as open: the published PR body is still the pre-reslice text describing _import_source_cache and __spec__._initializing, neither of which exists in this tree (0 hits for both), which matters because for a ghstack PR that body is the landed commit message; and the nn_modules_globals_vt landing order.

Note on verification: PyTorch is not built in this checkout (no torch/_C*.so, no .venv), so I could not run python test/dynamo/test_package.py -k test_import_alias or reproduce the mutants; the author reports running all of it against a real build this round. My findings come from reading the diff, torch/nn/__init__.py and torch/nn/modules/__init__.py, the base's import_source via git show, and CPython 3.12's unittest/mock.py.

| branch `gh/bobrenjc93/1191/head`

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

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head 1d577349b8ee; both test items are folded, the description is queued for the author, and the nn_modules_globals_vt value/guard-root item stays as recorded.

1. > test/dynamo/test_package.py:1298-1304 -- the comment on test_import_alias_keeps_the_installed_live_module is pre-reslice and its last sentence is now false. [...]

Fixed in 1d577349b8ee: the comment describes what the test pins at this tree -- install() binds the live entry, a later trace resolves that entry too, the alias keeps it and roots the guards, so a change to the live module recompiles -- and the sibling cross-reference is gone.

2. > test/dynamo/test_package.py:1579 -- test_import_alias_of_an_empty_slot_reads_an_attribute_the_cached_module_lacks names its setup instead of its outcome [...]

Fixed in 1d577349b8ee: renamed test_import_alias_of_an_empty_slot_reads_an_attribute_only_the_live_module_has, with the commit message's mentions and its -k line following.

3. > torch/_dynamo/symbolic_convert.py:2382-2387 -- restating once for the record, not re-arguing: the value (torch.nn.modules.module) and its guard root (the alias, now the live sys.modules entry) can be two different objects [...]

Recorded as you state it; the repair is #197135 and the ordering is the author's decision, raised with them together with the same question on #197256.

4. > Recommendation [...] the published PR body is still the pre-reslice text [...]

Queued for the author: the replacement body is the commit message at 1d577349b8ee (which describes this tree and reproduces its claims), with the cache and _initializing FAQ answers moved to #197303; the body is hand-maintained, so it is not rewritten by script.

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

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

Re-reviewing PR #197046

  • Gather context (diff vs origin/gh/bobrenjc93/1191/base, delta since round 12)
  • Run the /pr-review checks
  • Post findings

View job run | branch gh/bobrenjc93/1191/head

[ghstack-poisoned]
@claude

claude Bot commented Sep 20, 2026 •

Copy link
Copy Markdown

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


Re-reviewed at 331a0ca9 — the production change is unchanged from round 12, I found no correctness problem in it, and what is left is two small defects this PR introduced in passing (a local name reused for two types in import_source, a dead cache_clear() in a test) plus the two items already owned by the author.

Full review

PR Review: #197046

Summary

The production change against origin/gh/bobrenjc93/1191/base is two hunks in one file: import_source binds the __import_* alias to the live sys.modules entry, keeping the process-global functools.cached _import_module as the fallback for a name since deleted or blocked with None (symbolic_convert.py:2445-2457), and nn_modules_globals_vt reads torch.nn.modules.module directly (:2385-2388). Two findings below, both introduced by this PR and both local.

The delta since round 12's 1d57734 is mostly base churn — the base moved twice (82766f8b → c204135c → 754f9c78), which is why git diff 1d57734..HEAD shows an import_source docstring/comment rewrite, the owner/type(owner) is str scope guard, the graph-break hint rewording, the re.escape hardening and the addCleanup conversion. Confirmed by diffing this PR's own production hunks at both commits: byte-identical. So the only tree churn belonging to this PR since round 12 is in test_package.py.

I re-derived the resolution rather than carrying round 12's conclusions forward, and found three things clean that were worth re-checking:

  • The live rename does not change the write gate's meaning. Base had live = module_name in sys.modules and sys.modules[module_name] is value with value = _import_module(...); head has live = entry is not None with value = entry if live else memo. Since value is defined as the entry whenever one exists, live still holds exactly when value is sys.modules[module_name], so if not conflict or live (:2534) skips in the same (conflict, not live) case as before. What moved is which object value is — the PR's point.
  • No new in-trace import. _import_module is called unconditionally at base too, so the cold-memo import, the None-blocked ModuleNotFoundError out of guard construction, and the initializing-entry module-lock wait are all reachable on the base at the same frequency. This commit narrows what that value is used for; it does not widen when the call happens.
  • importlib.import_module was never a module-type filter. _find_and_load returns sys.modules[name] verbatim for any non-None entry (/usr/lib/python3.12/importlib/_bootstrap.py:1349-1372), so a non-module value was already reachable at base with a cold memo. The case this commit newly exposes is narrow — memo primed with a real module, entry since replaced by a non-module — and downstream is well-behaved, since value_name is isinstance-guarded (:2483-2487) so accepted degrades to the key alone. test_import_alias_check_with_a_non_module_value_accepts_the_key_alone (test_package.py:2057) covers exactly that arm.

Also re-verified the nn_modules_globals_vt value side: torch/nn/__init__.py:8 does from torch.nn.modules import *, torch/nn/modules/__init__.py:1 imports .module, nn is absent from _lazy_modules (torch/__init__.py:3413-3419), and nothing in that package shadows the name, so the attribute chain is the defining module unconditionally after import torch.

Code Quality

  • torch/_dynamo/symbolic_convert.py:2453 — the new line names its local memo, which is already the name of a different thing of a different type eleven lines up. At :2432 the walrus if (memo := self._import_source_memo.get(module_name)) is not None: binds a GlobalSource out of the per-translator source memo (declared dict[str, GlobalSource] at :5600); at :2453 memo = _import_module(module_name) rebinds the same name to a types.ModuleType out of the process-global functools.cache. Two different caches, two different types, one name, in one twenty-line span — and the base did not have this, it wrote value = _import_module(module_name).

    There is no bug: the walrus binding only survives when the .get() returned None, every non-None path returns at :2433, and nothing reads the walrus value after :2453 (:2456 and :2533 are the only later reads, and :2533 uses source). So this is readability only — but it is readability in the one function this PR exists to change, and the docstring block directly above (:2417-2421) discusses the source memo under the same word, so a reader arriving at :2453 has just been told what "the memo" means and then finds it meaning something else. module or imported for the _import_module result, or cached_source for the walrus, disambiguates. Fix this →

Testing

  • test/dynamo/test_package.py:2050 — this PR adds a second _import_module.cache_clear() to test_import_alias_is_not_bound_to_a_non_module_import's finally, leaving the block calling it twice:

    2048        finally:
    2049            sys.modules.pop(name, None)
    2050            _import_module.cache_clear()          # added by this PR
    2051            fn.__globals__.pop(alias, None)
    2052            # The memo outlives the sys.modules entry: a same-process rerun would
    2053            # otherwise resolve this run's module from it.
    2054            _import_module.cache_clear()          # pre-existing

    The only statement between them is a dict pop, which cannot resolve a name, so the second call is dead — and worse, the insertion orphans the pre-existing call from the comment that explains it, so the block now reads as if the commented one were the load-bearing one. The base had only the call at what is now :2054. Delete :2050, or keep it and move the comment up with it. Auditing the whole family for this: all 22 test_import_alias* tests clear the memo in finally, and this is the only one that does it twice, so it is an editing artifact rather than a convention. Fix this →

Backward Compatibility

  • torch/_dynamo/symbolic_convert.py:2385-2388 — restating once for the record, not re-arguing: the value (torch.nn.modules.module) and its guard root (the alias, now the live sys.modules entry) can be two different objects, and with a global forward hook registered on the defining module plus that entry rebound, the CLOSURE_MATCH on G[alias]._global_forward_hooks[<id>] raises out of guard construction as an InternalTorchDynamoError — pinned deliberately by test_import_alias_nn_hook_guards_read_the_live_entry_the_alias_binds (test_package.py:1626-1687), which asserts the alias binds the shim (:1665) and now matches the guard-construction error text and the CLOSURE_MATCH create function (:1674-1679) rather than hand-seeding the slot. Repaired only by [dynamo] Root the global nn.Module hook guards at the defining module when the alias binds another #197135. The author's position is on the record across seven rounds and the intermediate state is measured; whether a red middle commit is acceptable to bisect through remains the human call.

Recommendation

Needs Discussion

No correctness finding in the production hunk, which has not changed since round 12; the three suspicions I carried in (the live rename, a new in-trace import, non-module values newly reaching the binding) are all either unfounded or narrower than they look, and the teardown convention the author claimed is now uniform across all 22 tests. The two findings above are a reused local name and a dead line, both introduced by this PR and both a one-line fix. What keeps this from a plain approve is unchanged: the published PR body is still the pre-reslice text describing _import_source_cache and __spec__._initializing (0 hits for either in this tree) and naming five tests that do not exist here, which matters because for a ghstack PR that body becomes the landed commit message; and the nn_modules_globals_vt landing order.

Note on verification: PyTorch is not built in this checkout (no torch/_C*.so, no .venv), so I could not run python test/dynamo/test_package.py -k test_import_alias or reproduce mutants; the author reports running all of it against a real build. My findings come from reading the diff, the base version of import_source via git show, torch/nn/__init__.py and torch/nn/modules/__init__.py, and CPython 3.12's importlib/_bootstrap.py, with each finding independently re-verified by a separate pass.

| branch `gh/bobrenjc93/1191/head`

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head 370c1d1cf212; both items are folded.

1. > torch/_dynamo/symbolic_convert.py:2453 -- the new line names its local memo, which is already the name of a different thing of a different type eleven lines up. [...]

Fixed in 370c1d1cf212: the _import_module result is imported; memo is the source memo only.

2. > test/dynamo/test_package.py:2050 -- this PR adds a second _import_module.cache_clear() to test_import_alias_is_not_bound_to_a_non_module_import's finally, leaving the block calling it twice [...]

Fixed in 370c1d1cf212: the duplicate is gone; the base's single, commented call remains.

@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 43m 6s —— View job


Re-reviewed at 370c1d1c — round 13's two items are fixed, the production hunks are byte-identical to round 12's apart from the memo→imported rename, and the one new finding is a pair of pre-existing teardown comments that this PR's change falsified.

Full review

PR Review: #197046

Summary

The production change against origin/gh/bobrenjc93/1191/base is two hunks in one file: import_source binds the __import_* alias to the live sys.modules entry, keeping the process-global functools.cached _import_module as the fallback for a name since deleted or blocked with None (symbolic_convert.py:2444-2457), and nn_modules_globals_vt reads torch.nn.modules.module directly (:2383-2388). One finding below, plus the two items the author already owns.

Round 13's two items are fixed: the _import_module result is imported and memo is the source-memo walrus only (:2432, :2453), and the duplicate _import_module.cache_clear() is gone from test_import_alias_is_not_bound_to_a_non_module_import's finally — the base's single commented call remains at :2053. git diff 331a0ca9..HEAD is exactly those two edits and nothing else.

I re-derived the change from scratch rather than carrying prior rounds forward, and confirmed three things clean:

  • No new failure shape in value. importlib.import_module returns an existing sys.modules[name] verbatim (_find_and_load), so a non-module value was already reachable at base whenever the memo was cold; head makes it the current entry instead of the first-resolved one. Downstream, value_name is isinstance-guarded (:2483-2487) and the conflict test is an identity comparison (:2465), so nothing new arrives that the check cannot handle. For a None entry head is bit-identical to base: live=False, value=imported, and a cold memo raises ModuleNotFoundError on both.
  • The write gate's reachable behaviour changes only where intended. Head's value differs from base's only when the memo is stale against a non-None live entry. Then either the slot is empty — base (conflict=False, live=False) wrote the stale memo, head (False, True) writes the live entry — or it holds the stale same-named module — base (True, False) skipped the write, head (True, True) overwrites. There is no case where head skips a write base performed.
  • No new in-trace import, module lock, or exception path. _import_module is still called unconditionally and first, exactly as at base; sys.modules.get replaces an in plus a subscript, so it is strictly fewer dunder calls and no user code.

And the nn_modules_globals_vt value side: nn is eagerly imported and absent from _lazy_modules (torch/__init__.py:3413-3419), torch/nn/__init__.py:13 binds modules, torch/nn/modules/__init__.py:1 binds module via from .module import Module, and module.py has no module-level __getattr__, so torch.nn.modules.module.__name__ is "torch.nn.modules.module" out of the instance dict and a sys.modules rebind cannot move it.

Code Quality

  • test/dynamo/test_package.py:1291-1292 and :2051-2052 — two finally blocks justify their _import_module.cache_clear() with a rationale this PR's change has made false. Both read, in substance, "the memo outlives the sys.modules entry, and a same-process rerun would otherwise resolve this run's module [from it]". That was a correctness statement at base, and I traced both:

    • test_import_alias_accepts_a_stale_module_of_either_accepted_name (:1248): at base, on a second run in one process with the clear removed, value = _import_module(key) returns run 1's module, so live is False, the slot holding an accepted same-named stale makes conflict True, the write is skipped, and assertIs(fn.__globals__[alias], live) at :1281 fails.
    • test_import_alias_is_not_bound_to_a_non_module_import (:2021): at base, phase 1 graph-breaks in IMPORT_NAME before import_source runs, so the memo is primed only in phase 2; on a rerun phase 2 binds run 1's module and assertIs(fn.__globals__[alias], module) at :2047 fails.

    At head neither can reach the memo. _import_module's only caller is :2453 (the PR deleted the second one in nn_modules_globals_vt), its result is used only via value = entry if live else imported, and both tests set sys.modules[key] before every compile and pop it only in finally — so entry is always the current run's module and imported is discarded. The cache_clear() is now hygiene (dropping a process-lifetime strong reference to a test-minted ModuleType), which is a fine reason to keep the call, but it is not the reason written next to it. Both comments are byte-identical on base, so they were carried over rather than written for this tree; worth rewording to say the clear keeps a test-minted module from outliving its test, which is also what would let a future reader decide correctly whether a new test needs one. Fix this →

Backward Compatibility

  • torch/_dynamo/symbolic_convert.py:2383-2388 — restating once for the record, not re-arguing: the value (torch.nn.modules.module) and its guard root (the alias, now the live sys.modules entry) can be two different objects, and with a global forward hook registered on the defining module plus that entry rebound, the CLOSURE_MATCH on G[alias]._global_forward_hooks[<id>] raises out of guard construction as an InternalTorchDynamoError — pinned deliberately by test_import_alias_nn_hook_guards_read_the_live_entry_the_alias_binds (test_package.py:1626-1687), which asserts the alias binds the shim (:1665) and matches the guard-construction error text and create function (:1674-1679), and repaired only by [dynamo] Root the global nn.Module hook guards at the defining module when the alias binds another #197135. The author's position is on the record across eight rounds and the intermediate state is measured; whether a red middle commit is acceptable to bisect through remains the human call.

Recommendation

Needs Discussion

No correctness finding in the production hunk — third consecutive round, and this time the hunks are unchanged apart from a rename, with the resolution ladder, the write gate's reachable delta, and the nn.modules.module attribute chain all re-derived independently. The one finding is a pair of teardown comments whose stated reason no longer holds; the calls themselves are fine to keep. What is unchanged from round 12: the published PR body is still the pre-reslice text describing _import_source_cache and __spec__._initializing (0 hits for either in this tree) and naming tests that do not exist here, which matters because for a ghstack PR that body becomes the landed commit message; and the nn_modules_globals_vt landing order.

Note on verification: PyTorch is not built in this checkout (no torch/_C*.so, no .venv), so I could not run python test/dynamo/test_package.py -k test_import_alias or reproduce mutants; the author reports running all of it against a real build. Findings come from reading the diff, the base versions of symbolic_convert.py and test_package.py via git show, torch/nn/__init__.py and torch/nn/modules/__init__.py, torch/_dynamo/codegen.py, torch/_dynamo/variables/nn_module.py, and CPython 3.12's importlib/_bootstrap.py and unittest/mock.py, with each finding independently re-verified by a separate pass.

| branch `gh/bobrenjc93/1191/head`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request module: dynamo topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant