Repository navigation
[dynamo] Serve a removed or blocked import name from what the alias last bound - #197303
bobrenjc93 wants to merge 33 commits into
Conversation
[ghstack-poisoned]
🔗 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 FailuresAs of commit 4c7dd4d with merge base 51d4378 ( UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This PR needs a
|
[ghstack-poisoned]
…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]
…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]
…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
|
Re-reviewed against the current head 1. > Already addressed at 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 2. > Already addressed at 3. > Already addressed at 4. > Already addressed at 5. > Already addressed at 6. > Already addressed at 7. > Already addressed at 8. > Request Changes — The unconditional alias write is a deliberate, reachable behaviour change with no test; that alone blocks approval. [...] Already addressed at |
|
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 Full reviewPR Review: #197303SummaryReplaces the process-wide Backward Compatibility
Thread Safety
Code Quality
RecommendationRequest Changes The code is in good shape: |
[ghstack-poisoned]
…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
|
Re-reviewed against the current head 1. > The PR description does not describe this diff. [...] Queued for the author, and narrowed: the commit message at 2. > Fixed in 3. > Fixed in 4. > Fixed in |
[ghstack-poisoned]
…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]
…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
[ghstack-poisoned]
…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]
…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]
…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
Re-reviewing PR #197303
|

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 makesimport_sourcebind the livesys.modulesentry whenever there is one andkeeps the memoized
_import_modulein front of that read, for a name sinceremoved from
sys.modulesor blocked there withNone; this one replaces thememo with a cache of what
import_sourcelast bound, written only once thealias check has passed, reads
sys.moduleswith nothing in front of it, andhands an entry still executing its body to
importlib.import_moduleso thetrace waits on it as an import statement would.
_import_moduleisfunctools.cached for the life of the process: it holdsthe 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[...], amock.patch.dict(sys.modules)scope -- or beenset to
None, the import system's blocked-module sentinel that makes anyimport of the name raise
ModuleNotFoundError, because importing such a nameagain would execute the module body inside the trace and bind a second copy of
a module the program still holds, or for
Noneraise out of guardconstruction (
ModuleNotFoundErroris not in_compile's pass-through tuple,so that raise surfaces as
InternalTorchDynamoErrorwith 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_cachereplaces it,keyed by name, holding what
import_sourcelast bound: each acceptedresolution overwrites the entry, so a name that then leaves
sys.modulesbinds 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 poppedand the alias deleted
import_sourcebinds 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 boundremembered the name allthe 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 writebefore 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_sourcebranches on it and carried to the write in a local,cacheable:Falsein thetorch_packagearm, whose names resolve through_package_imported_modules, aWeakValueDictionary(
package_importer.py:731) that holds a packaged module only while itsimporter or the user does, so an entry would pin a
torch.packagemodule theuser 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;
Trueinthe
sys.modulesarm. A second"torch_package" in module_nametest at thewrite, 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.modulesaccepts any object, and anon-module entry, which the callers without a module check bind verbatim, is
never remembered, so the cache's
dict[str, types.ModuleType]annotation holdsby construction.
The live entry is read from
sys.modulesitself, and the memo no longer runsin 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 withouttouching a lock unless the entry is missing or its
__spec__._initializingisset, but 3.10's (
:1022-1034) has no such gate -- it enters_ModuleLockManagerand calls_lock_unlock_modulefor every name, eachthrough
_get_module_lock, which brackets its body with the global importlock (
:185,:211), all of it undercompile_lock. Measured with spies on_get_module_lockand_imp.acquire_lock, resolving a present, initializedname through
import_module: 3.10.20, two module-lock and fourglobal-import-lock acquisitions and 5.5 us per call; 3.12.14, none and 388 ns.
The
sys.modulesread 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_sourceis@cache_method). The import machinery is entered in threecases only: a name absent from
sys.modulesthat no trace has resolved before(a first import, as before); a name blocked with
Nonethat no trace hasresolved before (which raises
ModuleNotFoundError, as before); and an entrywhose
__spec__._initializingis set --_load_unlocked(:911-950) sets itaround a first-time execution of the module body -- where
import_modulewaits 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.modulesand imported again while a trace resolved it, orthe 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)) andthen 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
_initializingtest removed it finished 2921 ms beforethe body ended and bound a module whose spec was still
_initializing. Thewait 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 plantsan entry whose instance-dict
__spec__has_initializingset and, under aspy on
importlib.import_module, pins that the name is asked for and that thealias binds what the call returned (with the lock free, the entry itself).
The entry's
__spec__is read out of its instance dict throughobject.__getattribute__, the way the alias check below reads__name__, andonly for a
types.ModuleType(a non-module entry has no spec and is served asis). An attribute read would run a PEP 562
__getattr__or a class-level__getattribute__inside the trace, andimportlib.util._LazyModule.__getattribute__(importlib/util.py:172-221on3.12) executes the module body on any read,
__spec__included._init_module_attrswrites__spec__into the dict (_bootstrap.py:778)before
_load_unlockedmarks it_initializingand publishes the module, sothe 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_unlockedwrites_initializingas aplain instance attribute (
spec._initializing = Trueat:926,= Falseat:950) on the spec_find_specreturned, andModuleSpecdeclares no__slots__, no class-level default and no descriptor for it, so for every realspec the dict read answers what
getattrdid --Nonefor one that never wentthrough
_load_unlocked(measured: a freshModuleSpec's dict has no suchkey), else the flag.
specis whatever the module body assigned to__spec__,so a plain
getattrwould run a descriptor or a__getattr__on an objectoutside Dynamo's control inside guard construction, and a
MagicMockin thatslot answers it with a truthy child and sends a fully-loaded module through
import_module(measured:getattr(mock, "_initializing", False)isTrue;the dict read is
None). Theisinstancegate rather than anis not Noneone is a choice, not a guarantee the import system gives:
_find_spec(
_bootstrap.py:1240-1280) returns whatever asys.meta_pathfinder handedback, checking only
is not None(:1263), and_load_unlockedsetsspec._initializingon that object unqualified, so a duck-typed spec can carrythe flag. Every finder in the stdlib and in this repo returns a
ModuleSpec--torch.package's importer builds one atpackage_importer.py:372, and thefind_specs undertest/delegate toimportlib.util.find_specor go throughspec_from_loader-- and an object of another type need not have a__dict__to read: measured,
object.__getattribute__(5, "__dict__")raisesAttributeError, which the gate turns into "not initializing", asgetattr(5, "_initializing", False)was. The pair is deliberately narrowerthan the gate
_find_and_loadapplies,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 aModuleTypesubclass serving__spec__from aclass-level
__getattribute__or a PEP 562__getattr__, or a spec servingthe flag from a property, reads as not initializing here; so does a module
whose finder returned a spec of another type that
_load_unlockedthenflagged. 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 aLazyLoader-installedmodule on both 3.10 and 3.12 (measured:
__import__(name),import nameand,on 3.12,
import_module(name)all leave the body run and the class swappedback to
module; only the dict read leaves it lazy), so a tracedimportnever hands
import_sourcean unexecuted lazy module, and the memo'simport_modulemade the samegetattr(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_getattributepins theresolution as well as the check: its module class raises on any read made with
import_sourceon the stack, its spec's_initializingis a property thatraises the same way, and on the commit below, on 3.12, the test errors with
the module's raise reached from
_find_and_loadunder_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] = valueruns unconditionally:valueis the live entrywhenever
sys.modulesholds a module under the name, or the one a first importhas 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 thecached 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 awriter's module was replaced, and
Nonefor 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_moduleis deleted; its last caller is this read. The cache is nevercleared, not by
torch._dynamo.reset()either, so a module the process hasdropped 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 otherprocess-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 andblocked compiles follow a
reset()(measured on the original commit: thedeleted case fails on the spy,
'torch.autograd.profiler' unexpectedly found in [...], the blocked case errors withInternalTorchDynamoError: ModuleNotFoundError: import of torch.autograd.profiler halted; None in sys.modules). Only names the traced bytecode never imported can arrive absentor blocked:
IMPORT_NAME's own__import__has just put its name back orraised,
get_globals_source_and_valueresolves only a module it has justfound live under the frame's
__name__, and the other callers pass torch'sown or stdlib names for codegen.
torch.autograd.profileris such a name:codegen.pyresolves it on every compile underconfig.record_runtime_overhead(on by default) for the runtime-overheadrecord 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 tracewith the entry deleted has no other reason to re-import it. The removed-name
test uses it for that reason: an earlier
functoolsfixture asserted thatnothing in the process first-imports a
functoolsuser during the compile,which held on Linux and failed on macOS trunk CI, where the re-executed
functools.pyalso left the alias on a copy.Order to review:
symbolic_convert.py, the_import_source_cachedeclarationreplacing
_import_module, then thesys.modulesarm ofimport_source(thecache read, the
import_modulefallbacks, the__spec__gate and itscomment), the
cacheablelocal in both arms, and the write block (record,cache write, unconditional alias write);
torch/_dynamo/__init__.py, thereset()comment; thentest_package.py: the removed-name test and theinitializing 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_packagetest and thenon-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.modulesor blocked there withNonebinds whatimport_sourcelastbound under it rather than the first object the process resolved
(
test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache, itsstub-translator resolution after the pop); an entry still executing its body is
handed to
import_modulewhether or not the name has been resolved before(
test_import_alias_of_an_initializing_module_waits_on_its_import, bymutation: 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_moduledid on 3.11+ for the first resolution of a name(
test_import_alias_check_does_not_run_a_module_getattribute); a refused traceremembers 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_packagenameand 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, eachby 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.modulesbetween two tracesstill 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:
Two cases join the commit below's nineteen, and seven of those are extended:
twenty-one
test_import_aliastests. One deletestorch.autograd.profilerfrom
sys.modulesbetween two traces and then blocks it withNone, and pinsunder a spy on
importlib.import_modulethat neither trace asks for the name,the entry stays absent (
assertNotIn) orNone(assertIsNone, the two armschecked separately so a trace that re-added the name bound to
Nonecannotpass 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=Trueso its premise --that codegen resolves the name on every compile -- is pinned rather than
inherited from the default. It mutates the one
sys.moduleskey it is aboutand puts the module back in
finally, rather than snapshottingsys.moduleswith
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.modulesfor the rest of the process while live references to it survive,the duplicate-module failure the
functoolsfixture hit on macOS; measuredafter the test,
sys.modules["torch.autograd.profiler"]andtorch.autograd.profilerare both the module the test started with. Oneplants a module whose instance-dict
__spec__is aModuleSpecwith_initializing = True, compiles a function importing it under a spy onimportlib.import_module, and pins that the spy was asked for the name andthat 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
_ImportAliasHookedModuleused to raise on a__dict__read anywhere, and nowraises on any read made with
InstructionTranslatorBase.import_sourceon thePython stack, matched by function name and by the frame's module (
__import__and
PythonModuleVariableread__spec__and__name__off a module bydesign, 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 aModuleSpecsubclass whose_initializingis a property thatraises under the same frame walk and otherwise answers out of the instance
dict, where the test writes
Falsethe way_load_unlockedwould (a propertyhas no setter, so through
vars(spec));__import__reads the flag off apresent module's spec by design (measured: the property runs once under
IMPORT_NAME's__import__, from the importing frame, and answersFalse),so a resolution that reads it with
getattrraises out of guard constructionand 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_methodwrapper keeps the function under__wrapped__) has theco_nameand__module__the walk matches, so a renamed or inlinedimport_sourcefails there rather than letting every read through. Theempty-slot test, after its handover, asserts
_import_source_cache[name]isthe second module and then, with the entry popped and the alias deleted, drives
import_sourceon a stub translator overfn's globals -- the one resolutionin the family a compile does not make, because
fn's own import statementcannot run once the entry is gone (measured: eager raises
ModuleNotFoundError, and the compile graph-breaks withUnsupported: Import failureand binds nothing); only a name the traced bytecode never importsreaches 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_breakspins, per case, thatneither the
fullgraphrefusal nor the skipped frame leaves the name in_import_source_cacheand that the compile which finally binds the alias does,and
test_import_alias_the_trace_refused_is_not_recorded_for_installpins thename 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 itsguards refuses each gain one
assertNotInon the cache:test_import_alias_accepts_a_stale_torch_package_moduleasserts the mangledname absent after its compile, and
test_import_alias_check_with_a_non_module_value_accepts_the_key_aloneassertsthe key absent after its accepted call. Every
test_import_aliastest whosescratch name gets cached pops it from
_import_source_cacheinfinally,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 onlymatters 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 entryIMPORT_NAMErejects beforeimport_sourceruns, and a non-module is nevercached in any case;
test_import_alias_accepts_a_stale_torch_package_module,whose name takes the
torch_packagearm, which never writes the cache, andwhich asserts that instead; and the removed-name test, whose name is
torch.autograd.profilerand 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 underthis test file with a stub
_import_source_cache = {}added so the fileimports: 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 withKeyErroron_import_source_cache[name], nothing having written the cache;and
test_import_alias_graph_break_is_cached_until_reseterrors the same wayon its
assertIs(_import_source_cache[name], module)after the compile thatbinds the alias. The other eighteen pass there: the removed-name test, whose
memo serves the name, the initializing test, whose cold memo calls
import_modulefor every first resolution, and theassertNotIns on an emptystub among them. Those are pinned at this tree by mutation of
symbolic_convert.py, each mutant run against the twenty-one and restoredafterwards: with the
_initializingtest removed, the initializing test alonefails, 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-resolutionmemo one indirection further in -- the empty-slot test alone fails, on
assertIs(_import_source_cache[name], new)after the handover; with thecache 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 blockedcase with
InternalTorchDynamoError: ModuleNotFoundError: import of torch.autograd.profiler halted; None in sys.modules, and the empty-slottest's stub resolution errors too; with the
torch_packagearm'scacheableflipped to
True, thetorch_packagetest alone fails(
'<torch_package_0>.torch_test_package_import_alias_packaged' unexpectedly found in {...}); with theisinstance(value, types.ModuleType)conjunctdropped 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 {...}onassertNotInin each of the threetaken_by_a_non_modulecases,'torch_test_package_import_alias_cached'incached_until_reset, and'torch_test_package_import_alias_refused'in the install test. Neither ofthe two guard mutants changes what a compile binds today -- one pins a dropped
torch.packagemodule for the process, the other opens a pathIMPORT_NAMEblocks -- 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.pywhole: 207 tests, OK (skipped=6);test_misc.py -k test_torch_package_working_with_trace: OK.Authored with the assistance of Claude Code.
Co-Authored-By: Claude Opus 5 [email protected]
Co-Authored-By: Claude Fable 5.1 [email protected]