Repository navigation
[dynamo] Bind the import alias to the live sys.modules entry - #197046
bobrenjc93 wants to merge 51 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/197046
Note: Links to docs will display an error until the docs builds have been completed. ⏳ 6 Pending, 2 Unrelated FailuresAs of commit 370c1d1 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. |
|
Claude finished @bobrenjc93's task in 28m 23s —— View job Reviewed — the core change (bind the alias to the live Full reviewPR Review: #197046Summary
Thread Safety
Code Quality
Testing
RecommendationNeeds Discussion The alias/graph-identity argument is sound and the tests pin the behavior change on both sides. What needs a decision before merge is the thread-safety item: removing the memo moves the module-lock wait from once-per-name-per-process to once-per-compile, and its failure mode there is Note on verification: PyTorch is not built in this checkout (no |
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[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: 9b49eed 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: 834e470 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: ecad603 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: 3e19efa 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: 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
|
Re-reviewed against the current head 1. > The description and the tree have diverged. [...] Open, for the body and not the commit message: the message at 2. > Owned by #197303, and the order here is deliberate: the parent resolves through 3. > Related, same lines: the comment at Already addressed at 4. > Owned by #197135, which roots the source at the defining module whenever the alias binds another; as you note, keeping it a separate commit is a human decision that is on the record, and the intermediate state is measured rather than assumed. The two sub-points are addressed here: the hand-seeded 5. > Already addressed at 6. > Deleting the fallback entirely ( Already addressed at 7. > Deleting Already addressed at 8. > Making the memo call lazy (option C above, the fix) fails nothing -- so the suite cannot tell the safe ordering from the unsafe one. [...] Already addressed at 9. > The Declined: still accurate -- dropping the gate for an unconditional 10. > Declined as non-blocking, though confirmed: 11. > Already addressed at 12. > Two things block. [...] The first stands against the body and is queued for the author to replace with the commit message at |
|
Claude finished @bobrenjc93's task in 27m 17s —— View job Re-reviewed at Full reviewPR Review: #197046SummaryAfter the re-slice, the production change is 22 lines in one file: Three things I checked and found clean, since two of them were raised as suspicions in earlier rounds and one was raised by a sub-agent this round:
Also verified the value side of the Code Quality
Backward Compatibility
RecommendationNeeds Discussion No blocking code finding: the re-sliced hunks hold up under an independent re-derivation, the three suspicions I carried in (the Note on verification: PyTorch is not built in this checkout (no |
[ghstack-poisoned]
[ghstack-poisoned]
|
Re-reviewed against the current head 1. > Fixed in 2. > Fixed in 3. > Recorded as you state it; the repair is #197135 and the ordering is the author's decision, raised with them together with the same question on #197256. 4. > Recommendation [...] the published PR body is still the pre-reslice text [...] Queued for the author: the replacement body is the commit message at |
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
Re-reviewing PR #197046
|
[ghstack-poisoned]
|
Claude finished @bobrenjc93's task in 24m 5s —— View job Re-reviewed at Full reviewPR Review: #197046SummaryThe production change against The delta since round 12's I re-derived the resolution rather than carrying round 12's conclusions forward, and found three things clean that were worth re-checking:
Also re-verified the Code Quality
Testing
Backward Compatibility
RecommendationNeeds Discussion No correctness finding in the production hunk, which has not changed since round 12; the three suspicions I carried in (the Note on verification: PyTorch is not built in this checkout (no |
[ghstack-poisoned]
|
Re-reviewed against the current head 1. > Fixed in 2. > Fixed in |
|
Claude finished @bobrenjc93's task in 43m 6s —— View job Re-reviewed at Full reviewPR Review: #197046SummaryThe production change against Round 13's two items are fixed: the I re-derived the change from scratch rather than carrying prior rounds forward, and confirmed three things clean:
And the Code Quality
Backward Compatibility
RecommendationNeeds Discussion No correctness finding in the production hunk — third consecutive round, and this time the hunks are unchanged apart from a rename, with the resolution ladder, the write gate's reachable delta, and the Note on verification: PyTorch is not built in this checkout (no |

Stack from ghstack (oldest at bottom):
Split for review budget from
[dynamo] Root the global nn.Module hook guards at the defining module when the alias binds another(#197135), the commitdirectly above: this one changes what
import_sourcebinds; that one changeswhere
nn_modules_globals_vtroots its guards once the alias can bind a moduleother than the one whose dicts it reads.
import_sourcemints__import_<mangled>, resolves the module it names andwrites it into
self.output.global_scope, the traced frame's real globals.That alias roots the guards for every attribute the trace reads off the module,
while the graph is specialized on the object
IMPORT_NAMEpushed, which iswhatever
__import__returned: livesys.modules. The value written was_import_module(module_name), and_import_modulewasfunctools.cached forthe life of the process with nothing clearing it, so once a name had been
resolved anywhere in the process the helper kept handing back that first
object. After a
sys.modulesrebind -- a lazy-import shim handing over, amock.patch.dict(sys.modules, ...), a test fixture -- the two disagree: thegraph is built against the module the program actually uses and the guard
watches one nobody holds any more, so it is blind to every later change to the
live one and the compiled function keeps returning a value computed from the
abandoned module. The previous commit's collision check has no part in this: it
reproduces just as well with the alias absent from
f_globals, where no checkruns at all. Its write condition -- a writer's same-named module replaced only
when the module resolved here was the live entry -- is dropped: the value bound
is that entry whenever
sys.modulesholds a module under the name, which isthe case the condition let through, and for a name gone from
sys.modulesorblocked there with
Noneit is what this process's traces last bound. Therethe condition treated the two alike in one direction only:
.get(module_name, value)returned the default for an absent name, so a writer's module wasreplaced, and
Nonefor a blocked one, so it was kept. Now both replace it;neither the writer's module nor the cached one is live, and the cached one is
the object the guards this alias roots were built against.
The previous commit's three-way test flips here and is renamed for what it
now asserts,
test_import_alias_rebinds_the_installed_module_to_the_live_entry:the alias binds the live entry, a change to the live module recompiles, and a
change to the installed one no longer does. Its empty-slot test flips the same
way and is renamed too,
test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache: an emptyslot binds the live entry rather than the module the process's earlier trace of
the name bound, a change to the live module recompiles, and a change to that
earlier module, which nothing guards, does not.
Read the live
sys.modulesentry, which is what__import__handedIMPORT_NAME, so the alias binds the same object the graph was specialized on.It is read from
sys.modulesdirectly rather than throughimportlib.import_module, because what that call costs for a present namedepends on the interpreter: on 3.12
_find_and_load(
importlib/_bootstrap.py:1349-1356) returns without touching a lock unlessthe entry is missing or its
__spec__._initializingis set, but 3.10's(
:1022-1034) has no such gate -- it enters_ModuleLockManagerand calls_lock_unlock_modulefor every name, each through_get_module_lock, whichbrackets its body with the global import lock (
:185,:211), all of it undercompile_lock. Measured with spies on_get_module_lockand_imp.acquire_lock, resolving a present, initialized name throughimport_module: 3.10.20, two module-lock and four global-import-lockacquisitions 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 three cases only: a nameabsent from
sys.modulesthat no trace has resolved before (a first import, asbefore); a name blocked with
Nonethat no trace has resolved before (whichraises
ModuleNotFoundError, as before); and an entry whose__spec__._initializingis set --_load_unlocked(:911-950) sets it arounda first-time execution of the module body -- where
import_modulewaits on themodule lock the way an import statement would, two lock acquisitions on both
versions. Measured with a scratch module whose body starts a thread that
compiles a
__main__function inlining one of its functions (the inliningtranslator's
_load_global->get_globals_source_and_value->import_source(M)) and then sleeps 3 s, after a warm-up compile: the compilefinished 31 ms after the body ended here and 33 ms after on the parent, both
binding the module; with the
_initializingtest removed it finished 2921 msbefore the body ended and bound a module whose spec was still
_initializing.The wait itself is a two-thread timing scenario, so that measurement stands in
for it; the dispatch is pinned single-threaded by
test_import_alias_of_an_initializing_module_waits_on_its_import, which 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(sys.modulesaccepts any object; a non-moduleentry has no spec and is served as is). An attribute read would run a PEP 562
__getattr__or a class-level__getattribute__inside the trace, 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, so the dict read sees thesame 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 a plain instance attribute (spec._initializing = Trueat:926,= Falseat:950) on the spec_find_specreturned, andModuleSpecdeclares no__slots__, no class-level default and no descriptorfor it, so for every real spec the dict read answers what
getattrdid --Nonefor one that never went through_load_unlocked(measured: a freshModuleSpec's dict has no such key), else the flag.specis whatever themodule body assigned to
__spec__, so a plaingetattrwould run adescriptor or a
__getattr__on an object outside Dynamo's control inside guardconstruction, and a
MagicMockin that slot answers it with a truthy child andsends a fully-loaded module through
import_module(measured:getattr(mock, "_initializing", False)isTrue; the dict read isNone). Theisinstancegate rather than an
is not Noneone is a choice, not a guarantee the importsystem gives:
_find_spec(_bootstrap.py:1240-1280) returns whatever asys.meta_pathfinder handed back, checking onlyis not None(:1263), and_load_unlockedsetsspec._initializingon that object unqualified, so aduck-typed spec can carry the 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 ofanother type need not have a
__dict__to read: measured,object.__getattribute__(5, "__dict__")raisesAttributeError, which thegate turns into "not initializing", as
getattr(5, "_initializing", False)was. The pair is deliberately narrower than 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-installed module on both 3.10and 3.12 (measured:
__import__(name),import nameand, on 3.12,import_module(name)all leave the body run and the class swapped back tomodule; only the dict read leaves it lazy), so a tracedimportnever handsimport_sourcean unexecuted lazy module, and the parent'simport_modulemade the same
getattr(module, "__spec__", None)on 3.11+ (_find_and_load,:1356) on the first resolution of each name per process, none on 3.10. Hereno 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 parent, on 3.12, the test errors with the
module's raise reached from
_find_and_load.The resolved object is remembered per name in
_import_source_cachewhen itis a module --
sys.modulesaccepts any object, and a non-module entry, whichthe callers without a module check bind verbatim, is never written to the
cache, so its
dict[str, types.ModuleType]annotation holds by construction --and only once the alias check below has passed, alongside the package record
and
output.import_sources, so a trace the check refuses withImport alias already boundremembers nothing: the cache is never cleared, and a write madebefore the check would pin a module the process may later drop on behalf of a
trace that bound nothing. Each resolution overwrites the entry, so the cache
holds what
import_sourcelast bound under the name, not what the processfirst resolved as the memo did;
test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cachepins thatafter its handover with the entry popped, and a
setdefaultwrite in place ofthe assignment fails it there. Whether the name is one the cache can serve is
decided where
import_sourcebranches on it and carried to the write in alocal,
cacheable:Falsein thetorch_packagearm,Truein thesys.modulesarm. Thetorch_packagearm's names resolve through_package_imported_modules, aWeakValueDictionary(
package_importer.py:731) that holds a packaged module only while itsimporter or the user does, and the cache is never cleared, so a cache entry
would pin a
torch.packagemodule the user has dropped for the rest of theprocess; that is the hazard the arm's comment names, and the arm's names are
never read back from the cache in any case, the read being in the other arm. A
second
"torch_package" in module_nametest at the write, a hundred lines below thefirst, would have to be kept in step with it by hand; the local cannot drift.
test_import_alias_accepts_a_stale_torch_package_module, whose functioninlines a helper from a
torch.package-imported module, pins it: the mangledname is absent from the cache after the compile, and with the arm's flag
flipped the test fails there, the name found. A name whose
sys.modulesentry has since gone --del sys.modules[...], amock.patch.dict(sys.modules)scope -- or been set toNone, the importsystem's blocked-module sentinel that makes any import of the name raise
ModuleNotFoundError, is served from the cache instead of going back throughthe import machinery, which would execute the module body again inside the
trace and bind a second copy of a module the program still holds, or for
Noneraise out of guard construction.ModuleNotFoundErroris not in_compile's pass-through tuple, so that raise would surface asInternalTorchDynamoErrorwith no eager fallback; measured, testing livenessby key presence, which holds for a
Noneentry, does exactly that. The cache isnever cleared, not by
torch._dynamo.reset()either, so a module the processhas dropped stays alive in it; the memoized
_import_moduleretained modulesthe same way, so this is not new retention.
reset()promises a fresh processand clears its other process-globals in one place, so a comment closing the
clear group there, set off by a blank line from the unrelated statement below
it, names this one and why it stays, rather than leaving the exception to the
declaration alone; a
reset()that did clear it fails the removed-name test,whose deleted and blocked compiles follow a
reset()(measured: the deletedcase 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 bytecodenever imported can arrive absent or blocked:
IMPORT_NAME's own__import__has just put its name back or raised,
get_globals_source_and_valueresolvesonly a module it has just found live under the frame's
__name__, and theother callers pass torch's own or stdlib names for codegen.
torch.autograd.profileris such a name:codegen.pyresolves it on everycompile under
config.record_runtime_overhead(on by default) for theruntime-overhead record in the compiled frame's prologue, and the only
function-scope import of it in torch/ (
torch/profiler/_utils.py) is off thecompile path, so a trace with the entry deleted has no other reason to
re-import it. The removed-name test uses it for that reason: an earlier
functoolsfixture asserted that nothing in the process first-imports afunctoolsuser during the compile, which held on Linux and failed on macOStrunk CI, where the re-executed
functools.pyalso left the alias on a copy._import_moduleis deleted. Its one remaining caller,nn_modules_globals_vt,reads the four global hook dicts to decide whether a module call may bypass
_call_impl, and it has to read the dicts_call_implitself reads throughits own
__globals__: the defining module's, which nosys.modulesrebindmoves. The plain attribute chain
torch.nn.modules.moduleis that module forthe same reason a memo would be:
_find_and_load_unlockeddoessetattr(parent_module, child, module)once (_bootstrap.py:1339) and neverrevisits it, and
import torchbinds the submodule unconditionally(
torch/nn/__init__.py:8->torch/nn/modules/__init__.py:1);convert_frame.py:1372-1375already reads the same four dicts through it. Thesource stays the alias, as before. That leaves one case this commit does not
finish: with
sys.modules["torch.nn.modules.module"]rebound to anothermodule, the alias now binds that module while the value is the defining one,
and a hook registered on the defining module installs a
CLOSURE_MATCHonG['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[0],which resolves on the other module and raises
KeyError: 0out of guardconstruction as an
InternalTorchDynamoError. Measured with a shim carryingempty hook dicts and forwarding every other read to the defining module, in
both orders -- shim installed after a first compile in the process, and before
any: this commit raises in both. The parent is right in one order only: with
the name resolved before the rebind its memo holds the defining module and the
hook runs, but with the shim installed before the process's first compile the
memo holds the shim, the hook dicts read empty, the call bypasses
_call_impland the compiled function skips the hook and returns a tensor eager does not,
with nothing raised. The commit above roots the source at the defining module
whenever the alias binds another, which makes both orders right, and pins it
with
test_import_alias_rebind_keeps_the_global_nn_hooks_visible; in aprocess that has not rebound
sys.modulesfor torch's own module nothingchanges on this path, so the guard shape and the recorded
import_sourcesareas before (
test_aot_compile.pypins{"__import_torch_dot_nn_dot_modules_dot_module"}as that set in two places;both pass here).
Which module object a compiled artifact was built against is pinned by its
guards, not by this write: no identity guard on the alias survives
serialization (
MODULE_MATCHis inUNSUPPORTED_SERIALIZATION_GUARD_TYPES),so a rebind that hands the slot a different object of the same name leaves a
loaded artifact passing its guards. A rebind therefore costs a recompile only
when the live module answers differently, i.e. when the artifact is stale --
and on a path that never recompiles, a loaded AOT artifact or
fail_on_recompile, that staleness is reported instead of served: with thealias left on the abandoned module the same guards pass and the artifact
answers out of a module nobody holds.
Behaviour change against the parent, pinned below: the alias binds the live
sys.modulesentry rather than the first object the process resolved, so aprogram that rebinds a module between compiles recompiles where its guards used
to watch the abandoned object silently
(
test_import_alias_binds_the_live_module,test_import_alias_survives_a_sys_modules_rebind,test_import_alias_rebind_makes_a_stale_artifact_visible), and so does onewhose alias slot is empty while
_import_source_cacheholds the module anearlier trace bound, where the parent put that module into the slot
(
test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache, whichthen pops the entry and pins that the cache serves that live module, the last
one bound, and not the earlier one). Not a
change: a name removed from or blocked in
sys.modulesbetween two tracesstill binds the module the program holds, as the memo did
(
test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module, whichpasses on the parent and pins this commit against the two ways live resolution
alone would break it); and an alias
install()bound to the live entry, whichthe trace then resolves too, is recorded for the package exactly as when the
parent's trace found its memo older and left the slot alone
(
test_import_alias_the_trace_left_alone_is_recorded_for_install, which passeson the parent). Also pinned: the resolution reads no attribute off the
module it resolves or off its spec, which the parent did on 3.11+ for the first
resolution of a name (
test_import_alias_check_does_not_run_a_module_getattribute).Test Plan:
Five cases join the previous commit's twelve (thirteen tests, its accepted-names
fixture being parametrized over two); five of the twelve are extended, one is
renamed, and its empty-slot case and its recorded-skip case are rewritten for
what this commit binds. One compiles a function importing a scratch module,
resets, hands the
sys.modulesentry to a second module object and compilesagain, pinning that the alias
follows the handover and that the guard then sees a mutation of the live
module. One saves a
CompilePackage, loads and installs it --install()binds the alias to the live module -- then hands the module over once more
before tracing a fresh function in those same globals, and pins that the alias
follows and the installed artifact still serves under
fail_on_recompile. Onehands the module over to one answering differently and pins that the rebound
alias makes a loaded artifact's staleness visible -- a guard miss under
fail_on_recompile, and the live answer once the default stance recompiles.One deletes
torch.autograd.profilerfromsys.modulesbetween two traces andthen blocks it with
None, and pins under a spy onimportlib.import_modulethat neither trace asks for the name, the entry stays absent (
assertNotIn)or
None(assertIsNone, the two arms checked separately so a trace thatre-added the name bound to
Nonecannot pass the absent arm), and the aliasstill 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 nameon every compile -- is pinned rather than inherited from the default. One
plants 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 one is the alias
check's
_ImportAliasHookedModuletest: its module class used to raise on a__dict__read anywhere, and now raises on any read made withInstructionTranslatorBase.import_sourceon the Python stack, matched byfunction name and by the frame's module (
__import__andPythonModuleVariableread__spec__and__name__off a module by design,so the stack is the discriminator), which covers the resolution's
__spec__read as well as the check's
__name__reads. The live module's__spec__is aModuleSpecsubclass whose_initializingis a property that raises under thesame frame walk and otherwise answers out of the instance dict, where the test
writes
Falsethe way_load_unlockedwould (a property has no setter, sothrough
vars(spec));__import__reads the flag off a present module's specby design (measured: the property runs once under
IMPORT_NAME's__import__, from the importing frame, and answersFalse), so a resolutionthat reads it with
getattrraises out of guard construction and one thatreads the dict serves the entry without reaching
import_module. With no readleft for a hook to observe, the frame walk's positive control is static: the
test asserts that
InstructionTranslatorBase.import_source.__wrapped__(thecache_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. The othertwo extended ones are 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 aliasdoes, and
test_import_alias_the_trace_refused_is_not_recorded_for_installpins the name absent from the cache after the checkpointed refusal and again
after
install(). The last two extended are the two tests that reach the cachewrite with a value one of its guards refuses, each gaining one
assertNotInon the cache, described with their mutants below. The previous commit's
empty-slot case, renamed
test_import_alias_of_an_empty_slot_is_the_live_entry_not_the_cache, compileswith one module live, pops the alias, resets, hands the name over to a second
module and compiles again under a
CompileCounter: the alias binds the secondmodule, a change to it recompiles (equal to eager,
frame_count2), and achange to the first, which
_import_source_cachestill holds, does nothing(equal to eager,
frame_countstill 2); the previous commit pinned theopposite there -- the first module bound, the change to the live one unseen and
the change to the first one recompiling. It then pins the cache's contents:
_import_source_cache[name]is the second module, and with the entry poppedand the alias deleted,
import_sourcebinds the second module, not the first.That resolution is driven on a stub translator over
fn's globals, the waytest_import_alias_check_with_a_non_module_value_accepts_the_key_alonedrivesit, because
fn's own import statement cannot run once the entry is gone(measured: eager raises
ModuleNotFoundError, and the compile graph-breakswith
Unsupported: Import failureand binds nothing); only a name the tracedbytecode never imports reaches the cache read from a compile, which is the
removed-name test's path, and that test sees one module object for its name.
Its recorded case,
test_import_alias_the_trace_left_alone_is_recorded_for_install, keeps itsbody:
install()bound the live module after a handover, a second functionunder its own
CompilePackagetraces the name and finds the alias holding thevery entry it resolved, the record is made all the same, and a fresh process's
install()binds a third module and the loaded function serves underfail_on_recompile; its header no longer says the memo is older, since there isno memo, and both tests'
finallypop the name from_import_source_cacheasthe other eleven do (the previous commit's
_import_module.cache_clear()namesthe helper this commit deletes). The removed-name test mutates the one
sys.moduleskey it is about and puts themodule back in
finally, rather than snapshottingsys.moduleswithmock.patch.dict, whose exit clears the dict and restores the snapshot, so amodule 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; measured afterthe test,
sys.modules["torch.autograd.profiler"]andtorch.autograd.profilerare both the module the test started with. Everytest_import_aliastest whose scratch name gets cached pops it from_import_source_cacheinfinally, alongside the alias and the entry --thirteen at this commit: the pop only matters where a later compile runs with the
name absent or blocked, but one teardown shape keeps a test-minted module from
outliving its test either way. Four have nothing to pop:
test_import_alias_the_trace_refused_is_not_recorded_for_install, whose onetrace 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.
The first three fail on the parent (measured with the parent's
symbolic_convert.pychecked out under this test file, plus a stub_import_source_cache = {}on it so the file imports; the parent'simport_sourcenever reads it) onassertIs(fn.__globals__[alias], ...), thealias holding the module of the earlier compile; the third also fails with that
assertion removed, on
RuntimeError not raised, the stale artifact having beenserved. So does the second variant of the previous commit's accepted-names
fixture,
..._stale_named_for_target, on the parent's source under this file:the memo hands it the first variant's module, the first-resolution staleness
this commit removes, in an inherited test. The renamed test fails on the parent
on
assertIs(fn.__globals__[alias], new), the alias holdinginstall()'smodule, which is what its old name
promised. The empty-slot test fails on the parent the same way, on
assertIs(fn.__globals__[alias], new)after its second compile, the aliasholding the module the first compile bound, which is what its old name
promised; at this tree, with an empty slot made to take the cached module when
the cache has the name -- the parent's empty-slot write, as a mutant -- it is
the one failure among the eighteen
test_import_aliastests, on that sameassertion. With the cache write made
_import_source_cache.setdefault(module_name, value)-- a first-resolution memo one indirection further in -- it is again theone failure among the eighteen, on
assertIs(_import_source_cache[name], new)after the handover, and with that assertion removed on
assertIs(scope[alias], new)after the stub-translator resolution; every other test but the removed-nameone keeps its name live across its compiles, so the cache is write-only there,
and that one sees a single module object for its name. The recorded test passes
on the parent, whose skip arm made the record too, and is load-bearing here by
mutation: with the package record made
only when the write changes the binding (
f_globals.get(alias) is not value),it is the one failure, erroring with
KeyError: '__import_torch_test_package_import_alias_recorded'onpkg2._codes[fn2.__code__].import_sources[alias]. The extended test errors on the parent on 3.12 withInternalTorchDynamoError: RuntimeError: module __getattribute__ read __spec__ inside a trace, the read made by_find_and_load(_bootstrap.py:1356)under
_import_module; with this commit's resolution written as a plaingetattr(value, "__spec__", None)it errors the same way fromimport_sourceitself; with the flag read as
getattr(spec, "_initializing", False)it errorswith
InternalTorchDynamoError: RuntimeError: spec _initializing property ran inside a trace, raised fromimport_source(the initializing test, whose specis a plain
ModuleSpec, passes under that mutant, so the probe is what pinsthe read); and with
import_sourcerenamed toimport_source_impland theold name kept as a class attribute it fails on
'import_source_impl' != 'import_source', where the same rename with that assertion removed passes itwith every read let through. The removed-name test passes on the
parent and is load-bearing here by mutation, measured at this tree: dropping
the cache and importing whenever the entry is absent fails its deleted case on
the spy (
'torch.autograd.profiler' unexpectedly found in [...], the tracehaving re-imported it) and errors its blocked case with
InternalTorchDynamoError: ModuleNotFoundError: import of torch.autograd.profiler halted; None in sys.modules; testing liveness by keypresence instead of by value binds the blocked case's
Noneand the compiledframe's runtime-overhead prologue errors on
AttributeError: 'NoneType' object has no attribute '_is_profiler_enabled'; and with thereset()before each ofits compiles removed, so that no compile runs, its deleted case errors with
NameError: name '__import_torch_dot_autograd_dot_profiler' is not definedfrom the compiled frame's prologue and its blocked case with
KeyErroron thedelete, where the same test without the delete passes, every assertion in its
block holding with no compile. The
initializing test passes on the parent too, whose cold memo calls
import_modulefor every first resolution, and pins this commit's dispatch:with the
_initializingtest removed it fails onassertIn(name, asked), theentry having been served without asking. The refused-alias tests' cache
assertions fail with the cache write moved back above the check, the previous
push's order, measured at this tree:
'torch_test_package_import_alias_taken' unexpectedly found in {...}onassertNotInin each of the three cases, and'torch_test_package_import_alias_refused' unexpectedly found in {...}in theinstall test, four failures. The cache write's two guards are each pinned by
the one test that reaches the write with a value that guard refuses.
test_import_alias_is_not_bound_to_a_non_module_importcannot:IMPORT_NAMEis the one caller that hands
import_sourcea name the traced code chose, andit rejects a non-module first, and the callers without that check carry
torch's own names or a class's
__module__at reconstruction, where anon-module in the slot fails on
G[alias].<Name>regardless. Sotest_import_alias_check_with_a_non_module_value_accepts_the_key_alone, whichdrives
import_sourceon a stub translator with aSimpleNamespaceunder thekey, asserts the key absent from
_import_source_cacheafter the acceptedcall: with the
isinstance(value, types.ModuleType)conjunct dropped from thewrite it fails there (
'torch_test_package_import_alias_non_module_value' unexpectedly found in {...: namespace(VALUE=1)}), and without that assertionthe mutant passed all eighteen. The
torch_packagearm is covered bytest_import_alias_accepts_a_stale_torch_package_modulehere andtest_torch_package_working_with_traceintest_misc.py, both green at thistree; the first asserts the mangled name absent from the cache after its
compile, and with the arm's
cacheableflipped toTrueit fails there(
'<torch_package_0>.torch_test_package_import_alias_packaged' unexpectedly found in {...}), where without that assertion the mutant passed all eighteen.Neither mutant changes what a compile binds today -- one pins a dropped
torch.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. The whole file:
96 tests, OK (skipped=40, expected failures=1);
test_aot_compile.pywhole:294 tests, OK (skipped=6).
PYREFLY reports nothing in the files this commit touches; its findings are in
torch/_dynamo/guards.pyandtorch/_native/cutedsl/hw_caps.py, neither ofwhich this commit changes.
Authored with the assistance of Claude Code.
Co-Authored-By: Claude Opus 5 [email protected]
Co-Authored-By: Claude Fable 5.1 [email protected]
🤖 Generated with Claude Code