Skip to content

[dynamo] Serve a removed or blocked import name from what the alias last bound - #197303

Closed
bobrenjc93 wants to merge 33 commits into
gh/bobrenjc93/1253/basefrom
gh/bobrenjc93/1253/head
Closed

bobrenjc93 wants to merge 33 commits into
gh/bobrenjc93/1253/basefrom
gh/bobrenjc93/1253/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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, reads sys.modules with nothing in front of it, and
hands an entry still executing its body to importlib.import_module so the
trace waits on it as an import statement would.

_import_module is functools.cached 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. _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 import_source 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 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. Below this commit that wait happened only while
the memo was cold, and a warm memo served the previous incarnation of a module
removed from sys.modules and imported again while a trace resolved it, or
the live read served the new one half-initialized; here the flag decides.
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 a tree with the cold memo, 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 (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 memo'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 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. The
old condition treated the two absent forms 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. No test reaches that case -- it needs a writer's
same-named module in the slot, the cache holding another, and the name gone or
blocked, that is two independent resolutions of one name followed by its
removal -- and the comment at the write says which object wins and why.

_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. 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 on the original commit: 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.

Order to review: symbolic_convert.py, the _import_source_cache declaration
replacing _import_module, then the sys.modules arm of import_source (the
cache read, the import_module fallbacks, the __spec__ gate and its
comment), the cacheable local in both arms, and the write block (record,
cache write, unconditional alias write); torch/_dynamo/__init__.py, the
reset() comment; then test_package.py: the removed-name test and the
initializing test (the two new cases), the frame-walk probes at the top of the
file and the extended getattribute test, the empty-slot test's cache pin, 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).

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
stub-translator resolution after the pop); an entry still executing its body is
handed to import_module whether or not the name has been resolved before
(test_import_alias_of_an_initializing_module_waits_on_its_import, by
mutation: with the gate removed the spy is never asked); the resolution reads
no attribute off the module it resolves or off its spec, 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, four 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 a writer's same-named module in the slot
is replaced for a name gone or blocked, which no test reaches (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 the two ways live resolution alone would break it).

Test Plan:

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

Two cases join the commit below's nineteen, and seven of those are extended:
twenty-one test_import_alias tests. 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. It 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. 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 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), 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
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 on a stub translator over fn's globals -- the one resolution
in the family a compile does not make, 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 -- and asserts the alias
binds the second module. 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 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. Every test_import_alias test whose
scratch name gets cached pops it from _import_source_cache in finally,
alongside the alias and the entry -- fourteen 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.
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.

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: three of the twenty-one 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 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 eighteen pass there: the removed-name test, whose
memo serves the name, the initializing test, whose cold memo calls
import_module for every first resolution, and the assertNotIns on an empty
stub among them. Those are pinned at this tree by mutation of
symbolic_convert.py, each mutant run against the twenty-one and restored
afterwards: with the _initializing test removed, the initializing test alone
fails, on assertIn(name, asked) ('torch_test_package_import_alias_initializing' not found in []); 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
test's stub resolution errors too; with the torch_package arm's cacheable
flipped to True, the torch_package test alone fails
('<torch_package_0>.torch_test_package_import_alias_packaged' unexpectedly found in {...}); with the isinstance(value, types.ModuleType) conjunct
dropped from the write, the non-module-value test alone fails
('torch_test_package_import_alias_non_module_value' unexpectedly found in {...}); and with the cache write moved above the alias check, five failures:
'torch_test_package_import_alias_taken' unexpectedly found in {...} on
assertNotIn in each of the three taken_by_a_non_module cases,
'torch_test_package_import_alias_cached' in cached_until_reset, and
'torch_test_package_import_alias_refused' in the install test. 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-one pass and the
whole file is 99 tests, OK (skipped=40, expected failures=1);
test_aot_compile.py whole: 207 tests, OK (skipped=6);
test_misc.py -k test_torch_package_working_with_trace: OK.

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_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
python test/dynamo/test_misc.py -k test_torch_package_working_with_trace
python test/dynamo/test_aot_compile.py
lintrunner --take RUFF,PYFMT torch/_dynamo/symbolic_convert.py torch/_dynamo/__init__.py test/dynamo/test_package.py

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 memo'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 commit below (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 one resolution in the family a compile does not make; the non-module-value test drives it on the live translator from a comptime callback -- and asserts the alias binds new. The setdefault mutant is the one failure among the twenty-one on the first assertion, and with that assertion removed on the second.

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:2523-2532) 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 -- fourteen 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. Four 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 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 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). 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 below this commit 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 with the cold memo, 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 memo skips the wait in exactly one situation: M was fully imported before, removed from sys.modules and imported again, so the memo holds the previous incarnation. 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 below this commit. _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: 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: 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.

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-poisoned]
@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 16, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ 4 Pending, 2 Unrelated Failures

As of commit 4c7dd4d 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 commented Sep 16, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

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

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

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

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

This was referenced Sep 16, 2026
[ghstack-poisoned]
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
[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: 765a66c
Pull-Request: #197303
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head f6da608f725f; both blockers are resolved in code -- the _initializing branch is gone with the lock-order note kept at the read, and the unconditional alias write now has a mutation-verified test -- and the only thing left is the PR description, which is still a pre-round-65 revision and describes the branch that was dropped.

1. > torch/_dynamo/symbolic_convert.py:2459-2463 — the _initializing → importlib.import_module(module_name) branch cannot change value on the one caller that can reach it with a genuinely-initializing entry from traced bytecode, and its one effectful path is the one that can hang. [...]

Already addressed at f6da608f725f: the branch is gone. The sys.modules arm is now the plain read, the cache fallback, and importlib.import_module only for a name the cache has never seen (symbolic_convert.py:2450-2454), so an entry still executing its body is served as is -- which, as the finding says, is what the same-thread re-entrancy case already got. The lock-order hazard the finding asked to record is stated at the read (:2446-2449): importing there would block on the module lock under compile_lock, an order importlib's deadlock check cannot see, so the next reader does not put the wait back.

1b. > the PR description frames the wait as the branch's justification [...]

Open, in the body only: the live description is an earlier revision and still says the commit "hands an entry still executing its body to importlib.import_module so the trace waits on it as an import statement would", still enumerates three import-machinery cases, and still cites test_import_alias_of_an_initializing_module_waits_on_its_import, which was deleted with the branch (its Test Plan line now collects nothing). The commit message at f6da608f725f is accurate and already carries the replacement text and the reason the branch went; refreshing the description from it, keeping the FAQ block, is queued for the author.

2. > torch/_dynamo/symbolic_convert.py:2532 — dropping the if not conflict or live: gate for an unconditional f_globals[alias] = value has a reachable behaviour change that no test covers, and the PR body acknowledges this ("No test reaches that case"). [...]

Already addressed at f6da608f725f: test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache (test_package.py:2213-2280) builds exactly the state the finding enumerates -- a trace binds and caches one module, install() in the same globals binds a second of the same name, then the entry is popped and, in a second subTest, set to None -- and asserts the cached module replaces the installed one in both arms. It is a pin, not a paragraph: restoring the old conflict/live gate fails that test in both arms and nothing else, and the description's enumeration also now names the freshly-imported elif value is None path the finding pointed out was missing.

3. > test/dynamo/test_package.py:1726-1731 — the empty-slot test hand-rolls a fake translator out of types.SimpleNamespace ... and calls the unbound InstructionTranslatorBase.import_source(tx, name). [...]

Already addressed at f6da608f725f: the fake translator is gone and both non-bytecode resolutions use the shape you pointed at. The empty-slot test now drives import_source from a comptime callback on the live translator via a probe whose own bytecode never imports the name (test_package.py:1751-1770), and the new gone-name test uses the same mechanism (:2236-2243), so the real OutputGraph and CompilePackage are in the path in both.

4. > torch/_dynamo/__init__.py:171-174 — this comment restates the declaration comment at symbolic_convert.py:261-264 ... Drop it — the declaration is the right single home for the invariant. [...]

Already addressed at f6da608f725f: dropped. torch/_dynamo/__init__.py is no longer touched by this PR at all -- the diff is symbolic_convert.py and test_package.py -- and the "never cleared, not by torch._dynamo.reset() either" invariant lives only at the declaration (symbolic_convert.py:260-263).

5. > torch/_dynamo/symbolic_convert.py:2443-2458 and :2523-2531 — 16 lines of comment for a 5-line dict read, and 9 for a one-line assignment, largely restating CPython internals. [...]

Already addressed at f6da608f725f: the read arm carries 9 comment lines for 7 lines of code (:2441-2449) and the write 3 (:2529-2531). The CPython restatements you named -- _load_unlocked writing _initializing, _find_spec accepting any finder return, ModuleSpec having no __slots__ -- went out with the branch, leaving the two load-bearing facts (the read takes no lock where import_module does on 3.10, and importing here would cross the lock order) and the derivation in the commit message.

6. > test/dynamo/test_package.py:1622,1644 — "nn_modules_globals_vt builds its value from the memo" ... now describe a helper that no longer exists ... Since this PR deletes the memo, retire the term with it. [...]

Already addressed at f6da608f725f: the term is retired. No import-alias comment in the file says "memo" any more (the two remaining hits are pre-existing pickle comments), the nn-hook comment reads "the commit directly above this one changes", and the scratch name is now torch_test_package_import_alias_handed_over.

7. > test/dynamo/test_package.py:1945 — test_import_alias_of_an_initializing_module_waits_on_its_import does not test a wait. [...]

Already addressed at f6da608f725f: the test is deleted, since the dispatch it pinned no longer happens -- the branch it covered is gone, so there is nothing left to mis-name as concurrency coverage.

8. > Request Changes — The unconditional alias write is a deliberate, reachable behaviour change with no test; that alone blocks approval. [...]

Already addressed at f6da608f725f on both counts: the write is pinned by a new test that fails under the old gate, and the _initializing branch was removed rather than annotated, with the lock-order note kept at the read so the hazard stays on record. test/dynamo/test_package.py -k import_alias is 24 tests, all passing at this head. The one item still outstanding is the description refresh in 1b, which is prose and is queued for the author.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

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


Re-reviewed after the latest push: the previous round's blocking finding (unconditional alias write with no test) is now pinned by a new test, and the __spec__._initializing branch has been dropped entirely — but the PR description still describes that branch, a test that does not exist, and a file the diff does not touch, so the commit message no longer matches the commit.

Full review

PR Review: #197303

Summary

Replaces the process-wide functools.cached _import_module with _import_source_cache (what import_source last bound per name) and reads sys.modules directly. Both findings from the previous round are addressed in the code; the remaining problems are a PR description that describes a different revision of the change, and two small cleanups.


Backward Compatibility

  • The PR description does not describe this diff. For a ghstack PR the description is the commit message, and this one documents a revision that no longer exists. Concretely, none of the following are in the tree:

    • The __spec__._initializing gate. grep -n "_initializing\|__spec__" torch/_dynamo/symbolic_convert.py finds only the unrelated resolve_name reads at :2557-2571. The description devotes ~1500 words to it ("hands an entry still executing its body to importlib.import_module so the trace waits on it as an import statement would", the object.__getattribute__ spec read, the isinstance(spec, ModuleSpec) gate, the 3.10-vs-3.12 lock measurements, two FAQ answers). The code now does the opposite, and says so at symbolic_convert.py:2447-2450: "An entry still executing its body is served as is."
    • test_import_alias_of_an_initializing_module_waits_on_its_import. grep -n initializing test/dynamo/test_package.py returns nothing, so the Test Plan line python test/dynamo/test_package.py -k test_import_alias_of_an_initializing_module_waits_on_its_import selects zero tests.
    • Any change to torch/_dynamo/__init__.py. git diff --name-only origin/gh/bobrenjc93/1253/base...HEAD is two files; the "Order to review" list's second entry ("torch/_dynamo/__init__.py, the reset() comment") and the paragraph justifying that comment describe a hunk that was removed.
    • The test counts. The description says "Two cases join the commit below's nineteen ... twenty-one test_import_alias tests"; base has 22 and HEAD has 23, so one case was added. The per-mutant failure tables ("three of the twenty-one fail there", "with the _initializing test removed, the initializing test alone fails") are measurements of a tree that no longer exists.

    Also note the behaviour change the description now gets backwards. Dropping the _initializing branch is the right call — for get_globals_source_and_value the initializing module is the one whose body triggered the compile, so waiting on its import lock under compile_lock is the deadlock, not the fix — but it is a change against the base commit, whose cold _import_module entered _find_and_load and waited (unconditionally on 3.10, under the :1355 gate on 3.11+). The description asserts the wait is preserved and pinned by a test. Please rewrite the body against the actual diff before landing, and keep the deadlock rationale, which is the load-bearing part. Fix this →

Thread Safety

  • torch/_dynamo/symbolic_convert.py:2455 — the comment above (:2447-2450) names the lock-order hazard and explains that a present entry is served without entering the import machinery, but the elif value is None: value = importlib.import_module(module_name) line directly below still enters it, executing a module body inside the trace with compile_lock held, for the first resolution of any name absent from sys.modules. That is pre-existing, not a regression. The problem is that the hazard is now documented only in the branch that avoids it, so the one line that still takes it reads as safe. Name it at that line — first resolution of an absent name runs the module body under compile_lock, which is why the cache exists — so a future change does not widen the path on the assumption that import_module is unreachable from here. Fix this →

Code Quality

  • torch/_dynamo/symbolic_convert.py:2451-2455 — the resolution tests value is None twice and looks the cache up twice (module_name in _import_source_cache then _import_source_cache[module_name]). One if with a single .get says the same thing, and the cache can never hold None (the write at :2528 is guarded by isinstance(value, types.ModuleType)):

    value = sys.modules.get(module_name)
    if value is None:
        cached = _import_source_cache.get(module_name)
        value = cached if cached is not None else importlib.import_module(module_name)

    Fix this →

  • test/dynamo/test_package.py:2237 — in the new test, def resolve(ctx) shadows the ctx = DiskDynamoStore() bound at :2224 and used at :2252-2253. The parameter is a ComptimeContext, an unrelated type, and the two live in the same function body. Rename the callback parameter (the sibling at :2122 has the same shadow but no outer ctx to collide with). Fix this →

Recommendation

Request Changes

The code is in good shape: test_import_alias_of_a_name_gone_rebinds_the_installed_module_to_the_cache (test_package.py:2213-2276) pins the unconditional write for both the deleted and the None-blocked arm, the empty-slot test now drives import_source through a comptime callback on the live translator rather than a SimpleNamespace fake, the cacheable local plus the isinstance conjunct keep the dict[str, types.ModuleType] annotation honest, and the stale "memo" wording is gone from the test comments. What blocks landing is the description: it is the commit message, and it currently documents a _initializing branch, a test, and a file hunk that are not in the diff, while stating the reverse of the change it actually makes to initializing entries.

· branch [`gh/bobrenjc93/1253/head`](https://github.com/pytorch/pytorch/tree/gh/bobrenjc93/1253/head)

[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: 9988b6b
Pull-Request: #197303
@bobrenjc93 bobrenjc93 changed the title [dynamo] Serve a removed or blocked import name from what the alias last bound [no-ci] [dynamo] Serve a removed or blocked import name from what the alias last bound Sep 19, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head 808f70990a75; the three code items are folded and the description is queued for the author.

1. > The PR description does not describe this diff. [...]

Queued for the author, and narrowed: the commit message at 808f70990a75 already describes this diff -- it says the _initializing branch is gone and why, lists no torch/_dynamo/__init__.py hunk, counts twenty-three instances, and records the initializing behaviour change as untested -- so the stale text is the published body only, which lags the message because ghstack does not move a hand-maintained body. The replacement is that message, FAQ block kept.

2. > torch/_dynamo/symbolic_convert.py:2455 -- the comment above names the lock-order hazard [...] but the elif value is None: value = importlib.import_module(module_name) line directly below still enters it [...]

Fixed in 808f70990a75: the import_module line carries its own comment -- the one path left that enters the import machinery, the first resolution of a name absent from sys.modules, runs the module body inside the trace with compile_lock held.

3. > torch/_dynamo/symbolic_convert.py:2451-2455 -- the resolution tests value is None twice and looks the cache up twice [...]

Fixed in 808f70990a75: one value is None test and one .get on the cache, as an explicit if cached is not None / else so the import_module line keeps a place for item 2's comment (the one-line ternary would be wrapped by the formatter).

4. > test/dynamo/test_package.py:2237 -- in the new test, def resolve(ctx) shadows the ctx = DiskDynamoStore() [...]

Fixed in 808f70990a75: the callback parameter is comptime_ctx; the sibling without an outer ctx is unchanged.

[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: a4176f6
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: 5573690
Pull-Request: #197303
@bobrenjc93 bobrenjc93 changed the title [no-ci] [dynamo] Serve a removed or blocked import name from what the alias last bound [dynamo] Serve a removed or blocked import name from what the alias last bound Sep 19, 2026
[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: 084fb62
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: 155efcd
Pull-Request: #197303
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 20, 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: 155efcd
Pull-Request: #197303
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 20, 2026 •

Copy link
Copy Markdown

Re-reviewing PR #197303

  • Gather context (diff vs origin/gh/bobrenjc93/1253/base, commit log)
  • Verify the three folded items from the last round
  • Deep review of symbolic_convert.py and test_package.py
  • Fact-check findings
  • Post review

View job run · branch gh/bobrenjc93/1253/head

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant