Repository navigation
[dynamo] Root the global nn.Module hook guards at the defining module when the alias binds another - #197135
[dynamo] Root the global nn.Module hook guards at the defining module when the alias binds another#197135bobrenjc93 wants to merge 28 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/197135
Note: Links to docs will display an error until the docs builds have been completed. ❌ 11 New Failures, 1 Unclassified FailureAs of commit 469c441 with merge base 51d4378 ( 🟢 GREEN LIGHT - PR approved to be merged without human review:
reason: NEW FAILURES - The following jobs have failed:
UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
… when the alias binds another Split for review budget from `[dynamo] Bind the import alias to the live sys.modules entry` (#197046), the commit directly below: that one makes the `__import_*` alias bind the live `sys.modules` entry; this one makes `nn_modules_globals_vt` stop rooting its guards at that alias once it binds a module other than the one whose dicts the VT reads. `nn_modules_globals_vt` reads the four global hook dicts to decide whether a module call may bypass `_call_impl`, and it has to read the dicts `_call_impl` itself reads through its own `__globals__`: the defining module's, `torch.nn.modules.module`, which no `sys.modules` rebind moves (`convert_frame.py:1371-1376` reads the same four dicts through the same attribute chain). Its source was the `__import_torch_dot_nn_dot_modules_dot_module` alias unconditionally. Below this commit that alias binds the live `sys.modules` entry, so a program that rebinds `sys.modules["torch.nn.modules.module"]` -- a test fixture, a `mock.patch.dict(sys.modules, ...)` -- leaves the VT's value and its source naming different objects. That is unobservable while the defining module has no hooks, because empty dicts guard as one `TYPE_MATCH` each; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[0]`, which resolves on the other module and raises `KeyError: 0` out of guard construction as an `InternalTorchDynamoError`. The parent's parent, whose memoized `_import_module` happened to hold the defining module, ran the hook. The source now follows the value: the alias while `self.output.global_scope[alias]` is the defining module, otherwise the module itself installed by id, the fallback `get_globals_source_and_value` (`symbolic_convert.py:6539-6549`) already takes for an inlined function whose globals `sys.modules` does not account for. Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right: taking the live entry as the value, the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched, measured at this tree); keeping the alias as the source unconditionally is the parent, `KeyError: 0`. The premise that drives the `IMPORT_NAME` fix below -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. In a process that has not rebound `sys.modules` for torch's own module the source is the alias as before, so the guard shape and the recorded `import_sources` are unchanged (`test_aot_compile.py` pins `{"__import_torch_dot_nn_dot_modules_dot_module"}` as that set in two places; both pass here). Order to review: `nn_modules_globals_vt` in `torch/_dynamo/symbolic_convert.py` (the whole change is the `is not module` branch), then `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` in `test/dynamo/test_package.py`. Behaviour change against the parent, pinned below: with `sys.modules["torch.nn.modules.module"]` rebound to a shim carrying empty hook dicts and a forward hook registered on the defining module, compiling a function that calls an `nn.Module` matches eager and runs the hook, where the parent raised `InternalTorchDynamoError: KeyError: 0` out of guard construction (`test_import_alias_rebind_keeps_the_global_nn_hooks_visible`). Test Plan: ``` python test/dynamo/test_package.py -k test_import_alias_rebind_keeps_the_global_nn_hooks_visible python test/dynamo/test_package.py python test/dynamo/test_aot_compile.py -k test_aot_compile_module_deserialize_unwraps_optimized_module -k test_aot_compile_module_deserialize_takes_a_guard_globals_scope ``` One test joins the previous commit's ten `test_import_alias` cases. It compiles a function calling an `nn.Module` once so the process has resolved the name, resets, rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts, registers a forward hook on the defining module and compiles again, pinning that the hook runs under compile as in eager (`fired == [mod, mod]`), that `compiled == eager`, that `torch.nn.modules.module` is still the defining module and that the alias holds the shim. It restores `sys.modules`, the alias, the hook and `_import_source_cache` in `finally`. The hook is what makes the test load-bearing: without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only. It errors on the parent with `InternalTorchDynamoError: KeyError: 0` (measured by running this file's test against the parent's `symbolic_convert.py`), and on the parent's parent, the last commit with the memoized `_import_module`, fails on `assertIs(fn.__globals__[alias], shim)`, the memo holding the defining module. The other alternative, the live entry as the value, fails it at this tree on `Tensor-likes are not close!` (6/6 mismatched, the hook skipped). The whole file: 85 tests, OK (skipped=40, expected failures=1). ``` lintrunner --take RUFF,PYFMT,GB_REGISTRY torch/_dynamo/symbolic_convert.py test/dynamo/test_package.py lintrunner --take PYREFLY torch/_dynamo/symbolic_convert.py ``` > **FAQ: `nn_modules_globals_vt` still takes its value from a fixed module object while its source comes from `import_source`, which now binds live `sys.modules`. Fix that too -- the divergence silently decides graph shape.** > > Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right. The value has to be the defining module: the dicts the runtime consults are read by `nn.Module._call_impl` through its own `__globals__`, the defining module's `__dict__`, never through the alias, so that is what the bypass decision must read; `convert_frame.py:1371-1376` reads the same dicts through the same attribute chain. Taking the live entry instead, measured with the alias on a shim carrying empty dicts and a forward hook registered on the defining module: the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched). Keeping the defining module as the value with the alias as the source, the shape of the commit below, is what the earlier answer measured as unobservable -- and it is, while the defining module has no hooks, because the guards are one `TYPE_MATCH` per dict; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[0]`, which resolves on the shim and raises `KeyError: 0` out of guard construction as an `InternalTorchDynamoError`. So the source now follows the value: the alias while `self.output.global_scope[alias]` is the defining module, otherwise the module installed by id, the fallback `get_globals_source_and_value` (`symbolic_convert.py:6539-6549`) already takes for an inlined function whose globals `sys.modules` does not account for. The premise that drives the `IMPORT_NAME` fix -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. > **FAQ: the `nn_modules_globals_vt` value/source divergence is documented and hand-measured but not pinned by any test; a test that rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts and asserts a compiled `nn.Module` forward still matches eager would convert the comment into a check.** > > Added as `test_import_alias_rebind_keeps_the_global_nn_hooks_visible`, with one addition to the suggested shape that turned out to matter: a forward hook registered on the defining module. Without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only; with it, the hand measurement's conclusion fell over (previous FAQ), and the test now kills both alternatives -- the live value on a numeric mismatch, the unconditional alias source on `KeyError: 0`, which is what the commit below alone produces -- and fails on the last commit with the memoized `_import_module` on `assertIs(fn.__globals__[alias], shim)`, the memo holding the defining module. It asserts the hook ran once under eager and once more under compile, `compiled == eager`, `torch.nn.modules.module is real` and that the alias holds the shim, and restores `sys.modules`, the alias, the hook and `_import_source_cache` in `finally`. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: eb61593 Pull-Request: #197135
|
Claude finished @bobrenjc93's task in 9m 5s —— View job Reviewed: the source-side fix and its test look right, but the new PR Review: #197135 — detailsPR Review: #197135Summary
Infrastructure
_UNNAMED_SCOPE_PREFIX = "___unnamed_scope"
_MINTED_GLOBAL_PREFIXES = ("__import_", "__builtins_dict__", _UNNAMED_SCOPE_PREFIX)The comment above it (
The new name fails that test. Three concrete consequences, all reachable with a
Note the Reachability is narrow (requires the TestingNo coverage for the serialization/load path the change affects. The new test exercises in-process compile only. The three Code Quality
Reading RecommendationNeeds Discussion The core fix is correct and the test kills both alternatives. What blocks approval is the |
[ghstack-poisoned]
… when the alias binds another Split for review budget from `[dynamo] Bind the import alias to the live sys.modules entry` (#197046), the commit directly below: that one makes the `__import_*` alias bind the live `sys.modules` entry; this one makes `nn_modules_globals_vt` stop rooting its guards at that alias once it binds a module other than the one whose dicts the VT reads. `nn_modules_globals_vt` reads the four global hook dicts to decide whether a module call may bypass `_call_impl`, and it has to read the dicts `_call_impl` itself reads through its own `__globals__`: the defining module's, `torch.nn.modules.module`, which no `sys.modules` rebind moves (`convert_frame.py:1371-1376` reads the same four dicts through the same attribute chain). Its source was the `__import_torch_dot_nn_dot_modules_dot_module` alias unconditionally. Below this commit that alias binds the live `sys.modules` entry, so a program that rebinds `sys.modules["torch.nn.modules.module"]` -- a test fixture, a `mock.patch.dict(sys.modules, ...)` -- leaves the VT's value and its source naming different objects. That is unobservable while the defining module has no hooks, because empty dicts guard as one `TYPE_MATCH` each; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[0]`, which resolves on the other module and raises `KeyError: 0` out of guard construction as an `InternalTorchDynamoError`. The parent's parent, whose memoized `_import_module` happened to hold the defining module, ran the hook. The source now follows the value. It stays the alias while `self.output.global_scope[alias]` is the defining module, read back after `import_source` because that binding is what a guard rooted at the alias reads. Otherwise it is the `torch` package's own alias walking `.nn.modules.module` -- the attributes the value itself is read through, which the rebind does not move -- so the guards become `G['__import_torch'].nn.modules.module._global_forward_hooks` and so on. Not a name minted by id, which an earlier revision of this commit installed through `install_global_by_id("___nn_modules_module", module)`: `aot_compile.py` enumerates the global names Dynamo mints by prefix and argues the list complete (`_MINTED_GLOBAL_PREFIXES`, `aot_compile.py:74-89`), and a fourth family fails all three places that read it. Measured with an artifact captured under the rebind through `torch.compile(...).aot_compile` with a `guard_filter_fn` that keeps global guards, then loaded with a fresh `guard_globals=` scope: `_seed_guard_scope` (`aot_compile.py:854-872`) seeds `import_sources` aliases and `___unnamed_scope` names and so seeded nothing; `_has_global_guards` (`aot_compile.py:724`) subtracts only `import_sources` aliases and so was `True` for an artifact with no user global; the load then failed `KeyError on G['___nn_modules_module_<id>_c0']` and `_names_a_missing_global` (`aot_compile.py:106-112`) classed it as a user global, so `_missing_global_hint` told the caller to define a name embedding `id()` of an object in the tracing process. Rooted at `__import_torch`, the same artifact's guarded globals are `{__import_torch, __builtins_dict___N}`, `_has_global_guards` is `False`, the load seeds exactly `__import_torch`, and the call matches eager. No new family, so the completeness argument in `aot_compile.py` stands as written. Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right: taking the live entry as the value, the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched, measured at this tree); keeping the alias as the source unconditionally is the parent, `KeyError: 0`. The premise that drives the `IMPORT_NAME` fix below -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. In a process that has not rebound `sys.modules` for torch's own module the source is the alias as before, so the guard shape and the recorded `import_sources` are unchanged (`test_aot_compile.py` pins `{"__import_torch_dot_nn_dot_modules_dot_module"}` as that set in two places; both pass here). Order to review: `nn_modules_globals_vt` in `torch/_dynamo/symbolic_convert.py` (the whole change is the `is not module` branch), then `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` in `test/dynamo/test_package.py` for the in-process case, then `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` in `test/dynamo/test_aot_compile.py` for the artifact. Behaviour change against the parent, pinned below. In process: with `sys.modules["torch.nn.modules.module"]` rebound to a shim carrying empty hook dicts and a forward hook registered on the defining module, compiling a function that calls an `nn.Module` matches eager and runs the hook, where the parent raised `InternalTorchDynamoError: KeyError: 0` out of guard construction. Through an artifact: one captured under the rebind with a `guard_filter_fn` that keeps global guards roots its hook-dict guards at `__import_torch`, and a load seeds that name; the parent's roots at the module's own alias, which a load seeds through `importlib.import_module`, so in a loading process under the same rebind its guards read the shim's dicts. Test Plan: ``` python test/dynamo/test_package.py -k test_import_alias_rebind_keeps_the_global_nn_hooks_visible python test/dynamo/test_aot_compile.py -k test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package python test/dynamo/test_package.py python test/dynamo/test_aot_compile.py ``` `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` joins the previous commit's ten `test_import_alias` cases. It compiles a function calling an `nn.Module` once so the process has resolved the name, resets, rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts, registers a forward hook on the defining module and compiles again, pinning that the hook runs under compile as in eager (`fired == [mod, mod]`), that `compiled == eager`, that `torch.nn.modules.module` is still the defining module and that the alias holds the shim. It restores `sys.modules`, the alias, the hook and `_import_source_cache` in `finally`. The hook is what makes the test load-bearing: without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only. It errors on the parent with `InternalTorchDynamoError: KeyError: 0` (measured by running this file's test against the parent's `symbolic_convert.py`), and on the parent's parent, the last commit with the memoized `_import_module`, fails on `assertIs(fn.__globals__[alias], shim)`. Two mutations of this tree fail it: the live entry as the value on `Tensor-likes are not close!` (6/6 mismatched, the hook skipped); the alias as the source unconditionally on `KeyError: 0`. `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` captures `fn(m, x)`, `m` a `ParentWithChildModule` passed as an argument so the artifact has no user global, under `patch.dict(sys.modules, {name: shim})` with `keep_global_guards`, serializes it, and pins on the guards state that `_names_a_missing_global` returns `False` for every recorded global (none would be reported as a name to define), then loads it with a fresh `guard_globals=` scope, still under the rebind, and pins `_has_global_guards` `False`, the seeded names exactly `{"__import_torch"}`, and the call equal to eager. It fails on the earlier revision of this commit at the first pin (`True is not false : ___nn_modules_module_<id>_c0`) and on the parent at the seeded set (`__import_torch_dot_nn_dot_modules_dot_module`, not `__import_torch`). It registers no hook: see the FAQ below on why. Whole files at this tree: `test_package.py` 89 tests, OK (skipped=40, expected failures=1); `test_aot_compile.py` 287 tests, OK (skipped=6). ``` lintrunner --take RUFF,PYFMT,GB_REGISTRY torch/_dynamo/symbolic_convert.py test/dynamo/test_package.py test/dynamo/test_aot_compile.py lintrunner --take PYREFLY torch/_dynamo/symbolic_convert.py ``` > **FAQ: `nn_modules_globals_vt` still takes its value from a fixed module object while its source comes from `import_source`, which now binds live `sys.modules`. Fix that too -- the divergence silently decides graph shape.** > > Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right. The value has to be the defining module: the dicts the runtime consults are read by `nn.Module._call_impl` through its own `__globals__`, the defining module's `__dict__`, never through the alias, so that is what the bypass decision must read; `convert_frame.py:1371-1376` reads the same dicts through the same attribute chain. Taking the live entry instead, measured with the alias on a shim carrying empty dicts and a forward hook registered on the defining module: the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched). Keeping the defining module as the value with the alias as the source, the shape of the commit below, is what the earlier answer measured as unobservable -- and it is, while the defining module has no hooks, because the guards are one `TYPE_MATCH` per dict; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[0]`, which resolves on the shim and raises `KeyError: 0` out of guard construction as an `InternalTorchDynamoError`. So the source now follows the value: the alias while `self.output.global_scope[alias]` is the defining module, otherwise the `torch` package's alias walking `.nn.modules.module`, the attributes the value is read through. The premise that drives the `IMPORT_NAME` fix -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. > **FAQ: the `nn_modules_globals_vt` value/source divergence is documented and hand-measured but not pinned by any test; a test that rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts and asserts a compiled `nn.Module` forward still matches eager would convert the comment into a check.** > > Added as `test_import_alias_rebind_keeps_the_global_nn_hooks_visible`, with one addition to the suggested shape that turned out to matter: a forward hook registered on the defining module. Without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only; with it, the hand measurement's conclusion fell over (previous FAQ), and the test now kills both alternatives -- the live value on a numeric mismatch, the unconditional alias source on `KeyError: 0`, which is what the commit below alone produces -- and fails on the last commit with the memoized `_import_module` on `assertIs(fn.__globals__[alias], shim)`, the memo holding the defining module. It asserts the hook ran once under eager and once more under compile, `compiled == eager`, `torch.nn.modules.module is real` and that the alias holds the shim, and restores `sys.modules`, the alias, the hook and `_import_source_cache` in `finally`. > **FAQ: `___nn_modules_module_*` is a fourth Dynamo-minted global family that `aot_compile.py` enumerates nowhere: add the prefix to `_MINTED_GLOBAL_PREFIXES`, seed it in `_seed_guard_scope` with a `CleanupHook.disown`, subtract it in `_has_global_guards`, and update the completeness comment.** > > The family is gone instead. The fallback root is now the `torch` package's `__import_torch` alias with `.nn.modules.module` walked as `AttrSource`s, so every name a guard here can be rooted at is an `__import_*` alias, the first family in that tuple: `_seed_guard_scope` seeds it from `import_sources`, `_has_global_guards` subtracts it, `_names_a_missing_global` recognizes the prefix, and `import_source` binds it by plain assignment, so there is no `CleanupHook` to disown. All three consequences the review derived were reproduced first with the id-minted name (nothing seeded, `_has_global_guards` `True` with no user global, `KeyError on G['___nn_modules_module_<id>_c0']` reported as a global to define) and are absent with this root, which `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` pins. The `torch` package rather than `torch.nn.modules`: the chain then mirrors `torch.nn.modules.module`, the expression the value is read through, and a fixture that rebinds `sys.modules["torch"]` itself leaves nothing in Dynamo working. The comment at `aot_compile.py:74-87` needs no amendment: it says a family belongs in the tuple once a serializable guard roots at a `GlobalSource` on one of its names, and no guard roots at a name outside the three. > **FAQ: why does the artifact test register no hook, and why does it not pin that a hook registered after the load fails the loaded guards?** > > Two measured reasons, neither this commit's to change. First, with a hook on the defining module under the rebind, the capture never reaches the guard-scope sites: the hook makes the trace inline `_call_impl`, whose `__globals__` is the defining module's dict, and `_registered_module_for_globals` (`symbolic_convert.py:266-278`) resolves `sys.modules[__name__]` to the shim, whose dict is a different object, so `get_globals_source_and_value` falls to the `___unnamed_scope` branch and records the defining module's whole `__dict__` under it; the guards pickler then writes that dict by value and pickles its `T = TypeVar("T")` by qualified name through `sys.modules`, which is the shim, and `aot_compile` raises `PackageError: PicklingError: Can't pickle ~T: attribute lookup T on torch.nn.modules.module failed` (the parent raises `KeyError: 0` earlier on the same input). Second, a hook registered after a compile is not guarded at all, in process and without any rebind: the global hook dicts guard as `TYPE_MATCH` only, under both values of `skip_nnmodule_hook_guards` -- `EMPTY_NN_MODULE_HOOKS_DICT` is installed for the instance's own hook attributes (`nn_module.py:1563-1591`), not for the module globals read here -- so a global forward hook registered after a `torch.compile` call is skipped by the compiled function with no recompile (measured on this tree: `frame_count` 1, hook fired 0, result differs from eager), which `config.py:458-461` documents as the accepted unsafety. A loaded artifact inherits exactly that, so a hook-after-load phase would pin the same `TYPE_MATCH` pass on every tree. > **FAQ: `import_source(module.__name__)` is called for its side effects even when its `GlobalSource` is discarded: the alias is recorded in `import_sources`, bound in `f_globals`, and `CompilePackage.install` binds it in every loading process. Check `sys.modules` first and skip the call.** > > The read-back of `global_scope[alias]` after the call is the check, and the comment now says so: it is the binding a guard rooted at the alias reads, and `import_source` is what decides it -- the live entry, or `_import_source_cache` for a name since removed from `sys.modules` or blocked with `None`. Reading `sys.modules` here would duplicate that decision in a second place with its own corner cases. The recorded-but-unread alias is the ordinary state of an `import_sources` entry, not a new one: `test_load_seeds_exactly_the_recorded_globals` asserts `len(guarded) < len(import_sources)` on an artifact whose only guarded alias is this same `__import_torch_dot_nn_dot_modules_dot_module`, and the capture in the new artifact test records six aliases for one guarded root. `install` binding it to the shim in a still-rebound loading process binds a name nothing reads. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: 014a2a7 Pull-Request: #197135
… when the alias binds another Split for review budget from `[dynamo] Bind the import alias to the live sys.modules entry` (#197046), the commit directly below: that one makes the `__import_*` alias bind the live `sys.modules` entry; this one makes `nn_modules_globals_vt` stop rooting its guards at that alias once it binds a module other than the one whose dicts the VT reads. `nn_modules_globals_vt` reads the four global hook dicts to decide whether a module call may bypass `_call_impl`, and it has to read the dicts `_call_impl` itself reads through its own `__globals__`: the defining module's, `torch.nn.modules.module`, which no `sys.modules` rebind moves (`convert_frame.py:1371-1376` reads the same four dicts through the same attribute chain). Its source was the `__import_torch_dot_nn_dot_modules_dot_module` alias unconditionally. Below this commit that alias binds the live `sys.modules` entry, so a program that rebinds `sys.modules["torch.nn.modules.module"]` -- a test fixture, a `mock.patch.dict(sys.modules, ...)` -- leaves the VT's value and its source naming different objects. That is unobservable while the defining module has no hooks, because empty dicts guard as one `TYPE_MATCH` each; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[0]`, which resolves on the other module and raises `KeyError: 0` out of guard construction as an `InternalTorchDynamoError`. The parent's parent, whose memoized `_import_module` happened to hold the defining module, ran the hook. The source now follows the value. It stays the alias while `self.output.global_scope[alias]` is the defining module, read back after `import_source` because that binding is what a guard rooted at the alias reads. Otherwise it is the `torch` package's own alias walking `.nn.modules.module` -- the attributes the value itself is read through, which the rebind does not move -- so the guards become `G['__import_torch'].nn.modules.module._global_forward_hooks` and so on. Not a name minted by id, which an earlier revision of this commit installed through `install_global_by_id("___nn_modules_module", module)`: `aot_compile.py` enumerates the global names Dynamo mints by prefix and argues the list complete (`_MINTED_GLOBAL_PREFIXES`, `aot_compile.py:74-89`), and a fourth family fails all three places that read it. Measured with an artifact captured under the rebind through `torch.compile(...).aot_compile` with a `guard_filter_fn` that keeps global guards, then loaded with a fresh `guard_globals=` scope: `_seed_guard_scope` (`aot_compile.py:854-872`) seeds `import_sources` aliases and `___unnamed_scope` names and so seeded nothing; `_has_global_guards` (`aot_compile.py:724`) subtracts only `import_sources` aliases and so was `True` for an artifact with no user global; the load then failed `KeyError on G['___nn_modules_module_<id>_c0']` and `_names_a_missing_global` (`aot_compile.py:106-112`) classed it as a user global, so `_missing_global_hint` told the caller to define a name embedding `id()` of an object in the tracing process. Rooted at `__import_torch`, the same artifact's guarded globals are `{__import_torch, __builtins_dict___N}`, `_has_global_guards` is `False`, the load seeds exactly `__import_torch`, and the call matches eager. No new family, so the completeness argument in `aot_compile.py` stands as written. Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right: taking the live entry as the value, the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched, measured at this tree); keeping the alias as the source unconditionally is the parent, `KeyError: 0`. The premise that drives the `IMPORT_NAME` fix below -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. In a process that has not rebound `sys.modules` for torch's own module the source is the alias as before, so the guard shape and the recorded `import_sources` are unchanged (`test_aot_compile.py` pins `{"__import_torch_dot_nn_dot_modules_dot_module"}` as that set in two places; both pass here). Order to review: `nn_modules_globals_vt` in `torch/_dynamo/symbolic_convert.py` (the whole change is the `is not module` branch), then `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` in `test/dynamo/test_package.py` for the in-process case, then `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` in `test/dynamo/test_aot_compile.py` for the artifact. Behaviour change against the parent, pinned below. In process: with `sys.modules["torch.nn.modules.module"]` rebound to a shim carrying empty hook dicts and a forward hook registered on the defining module, compiling a function that calls an `nn.Module` matches eager and runs the hook, where the parent raised `InternalTorchDynamoError: KeyError: 0` out of guard construction. Through an artifact: one captured under the rebind with a `guard_filter_fn` that keeps global guards roots its hook-dict guards at `__import_torch`, and a load seeds that name; the parent's roots at the module's own alias, which a load seeds through `importlib.import_module`, so in a loading process under the same rebind its guards read the shim's dicts. Test Plan: ``` python test/dynamo/test_package.py -k test_import_alias_rebind_keeps_the_global_nn_hooks_visible python test/dynamo/test_aot_compile.py -k test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package python test/dynamo/test_package.py python test/dynamo/test_aot_compile.py ``` `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` joins the previous commit's ten `test_import_alias` cases. It compiles a function calling an `nn.Module` once so the process has resolved the name, resets, rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts, registers a forward hook on the defining module and compiles again, pinning that the hook runs under compile as in eager (`fired == [mod, mod]`), that `compiled == eager`, that `torch.nn.modules.module` is still the defining module and that the alias holds the shim. It restores `sys.modules`, the alias, the hook and `_import_source_cache` in `finally`. The hook is what makes the test load-bearing: without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only. It errors on the parent with `InternalTorchDynamoError: KeyError: 0` (measured by running this file's test against the parent's `symbolic_convert.py`), and on the parent's parent, the last commit with the memoized `_import_module`, fails on `assertIs(fn.__globals__[alias], shim)`. Two mutations of this tree fail it: the live entry as the value on `Tensor-likes are not close!` (6/6 mismatched, the hook skipped); the alias as the source unconditionally on `KeyError: 0`. `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` captures `fn(m, x)`, `m` a `ParentWithChildModule` passed as an argument so the artifact has no user global, under `patch.dict(sys.modules, {name: shim})` with `keep_global_guards`, serializes it, and pins on the guards state that `_names_a_missing_global` returns `False` for every recorded global (none would be reported as a name to define), then loads it with a fresh `guard_globals=` scope, still under the rebind, and pins `_has_global_guards` `False`, the seeded names exactly `{"__import_torch"}`, and the call equal to eager. It fails on the earlier revision of this commit at the first pin (`True is not false : ___nn_modules_module_<id>_c0`) and on the parent at the seeded set (`__import_torch_dot_nn_dot_modules_dot_module`, not `__import_torch`). It registers no hook: see the FAQ below on why. Whole files at this tree: `test_package.py` 89 tests, OK (skipped=40, expected failures=1); `test_aot_compile.py` 287 tests, OK (skipped=6). ``` lintrunner --take RUFF,PYFMT,GB_REGISTRY torch/_dynamo/symbolic_convert.py test/dynamo/test_package.py test/dynamo/test_aot_compile.py lintrunner --take PYREFLY torch/_dynamo/symbolic_convert.py ``` > **FAQ: `nn_modules_globals_vt` still takes its value from a fixed module object while its source comes from `import_source`, which now binds live `sys.modules`. Fix that too -- the divergence silently decides graph shape.** > > Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right. The value has to be the defining module: the dicts the runtime consults are read by `nn.Module._call_impl` through its own `__globals__`, the defining module's `__dict__`, never through the alias, so that is what the bypass decision must read; `convert_frame.py:1371-1376` reads the same dicts through the same attribute chain. Taking the live entry instead, measured with the alias on a shim carrying empty dicts and a forward hook registered on the defining module: the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched). Keeping the defining module as the value with the alias as the source, the shape of the commit below, is what the earlier answer measured as unobservable -- and it is, while the defining module has no hooks, because the guards are one `TYPE_MATCH` per dict; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[0]`, which resolves on the shim and raises `KeyError: 0` out of guard construction as an `InternalTorchDynamoError`. So the source now follows the value: the alias while `self.output.global_scope[alias]` is the defining module, otherwise the `torch` package's alias walking `.nn.modules.module`, the attributes the value is read through. The premise that drives the `IMPORT_NAME` fix -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. > **FAQ: the `nn_modules_globals_vt` value/source divergence is documented and hand-measured but not pinned by any test; a test that rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts and asserts a compiled `nn.Module` forward still matches eager would convert the comment into a check.** > > Added as `test_import_alias_rebind_keeps_the_global_nn_hooks_visible`, with one addition to the suggested shape that turned out to matter: a forward hook registered on the defining module. Without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only; with it, the hand measurement's conclusion fell over (previous FAQ), and the test now kills both alternatives -- the live value on a numeric mismatch, the unconditional alias source on `KeyError: 0`, which is what the commit below alone produces -- and fails on the last commit with the memoized `_import_module` on `assertIs(fn.__globals__[alias], shim)`, the memo holding the defining module. It asserts the hook ran once under eager and once more under compile, `compiled == eager`, `torch.nn.modules.module is real` and that the alias holds the shim, and restores `sys.modules`, the alias, the hook and `_import_source_cache` in `finally`. > **FAQ: `___nn_modules_module_*` is a fourth Dynamo-minted global family that `aot_compile.py` enumerates nowhere: add the prefix to `_MINTED_GLOBAL_PREFIXES`, seed it in `_seed_guard_scope` with a `CleanupHook.disown`, subtract it in `_has_global_guards`, and update the completeness comment.** > > The family is gone instead. The fallback root is now the `torch` package's `__import_torch` alias with `.nn.modules.module` walked as `AttrSource`s, so every name a guard here can be rooted at is an `__import_*` alias, the first family in that tuple: `_seed_guard_scope` seeds it from `import_sources`, `_has_global_guards` subtracts it, `_names_a_missing_global` recognizes the prefix, and `import_source` binds it by plain assignment, so there is no `CleanupHook` to disown. All three consequences the review derived were reproduced first with the id-minted name (nothing seeded, `_has_global_guards` `True` with no user global, `KeyError on G['___nn_modules_module_<id>_c0']` reported as a global to define) and are absent with this root, which `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` pins. The `torch` package rather than `torch.nn.modules`: the chain then mirrors `torch.nn.modules.module`, the expression the value is read through, and a fixture that rebinds `sys.modules["torch"]` itself leaves nothing in Dynamo working. The comment at `aot_compile.py:74-87` needs no amendment: it says a family belongs in the tuple once a serializable guard roots at a `GlobalSource` on one of its names, and no guard roots at a name outside the three. > **FAQ: why does the artifact test register no hook, and why does it not pin that a hook registered after the load fails the loaded guards?** > > Two measured reasons, neither this commit's to change. First, with a hook on the defining module under the rebind, the capture never reaches the guard-scope sites: the hook makes the trace inline `_call_impl`, whose `__globals__` is the defining module's dict, and `_registered_module_for_globals` (`symbolic_convert.py:266-278`) resolves `sys.modules[__name__]` to the shim, whose dict is a different object, so `get_globals_source_and_value` falls to the `___unnamed_scope` branch and records the defining module's whole `__dict__` under it; the guards pickler then writes that dict by value and pickles its `T = TypeVar("T")` by qualified name through `sys.modules`, which is the shim, and `aot_compile` raises `PackageError: PicklingError: Can't pickle ~T: attribute lookup T on torch.nn.modules.module failed` (the parent raises `KeyError: 0` earlier on the same input). Second, a hook registered after a compile is not guarded at all, in process and without any rebind: the global hook dicts guard as `TYPE_MATCH` only, under both values of `skip_nnmodule_hook_guards` -- `EMPTY_NN_MODULE_HOOKS_DICT` is installed for the instance's own hook attributes (`nn_module.py:1563-1591`), not for the module globals read here -- so a global forward hook registered after a `torch.compile` call is skipped by the compiled function with no recompile (measured on this tree: `frame_count` 1, hook fired 0, result differs from eager), which `config.py:458-461` documents as the accepted unsafety. A loaded artifact inherits exactly that, so a hook-after-load phase would pin the same `TYPE_MATCH` pass on every tree. > **FAQ: `import_source(module.__name__)` is called for its side effects even when its `GlobalSource` is discarded: the alias is recorded in `import_sources`, bound in `f_globals`, and `CompilePackage.install` binds it in every loading process. Check `sys.modules` first and skip the call.** > > The read-back of `global_scope[alias]` after the call is the check, and the comment now says so: it is the binding a guard rooted at the alias reads, and `import_source` is what decides it -- the live entry, or `_import_source_cache` for a name since removed from `sys.modules` or blocked with `None`. Reading `sys.modules` here would duplicate that decision in a second place with its own corner cases. The recorded-but-unread alias is the ordinary state of an `import_sources` entry, not a new one: `test_load_seeds_exactly_the_recorded_globals` asserts `len(guarded) < len(import_sources)` on an artifact whose only guarded alias is this same `__import_torch_dot_nn_dot_modules_dot_module`, and the capture in the new artifact test records six aliases for one guarded root. `install` binding it to the shim in a still-rebound loading process binds a name nothing reads. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: 014a2a7 Pull-Request: #197135
… when the alias binds another Split for review budget from `[dynamo] Bind the import alias to the live sys.modules entry` (#197046), two commits below (`[dynamo] Serve a removed or blocked import name from what the alias last bound`, split from the same commit, sits between): that one makes the `__import_*` alias bind the live `sys.modules` entry; this one makes `nn_modules_globals_vt` stop rooting its guards at that alias once it binds a module other than the one whose dicts the VT reads. `nn_modules_globals_vt` reads the four global hook dicts to decide whether a module call may bypass `_call_impl`, and it has to read the dicts `_call_impl` itself reads through its own `__globals__`: the defining module's, `torch.nn.modules.module`, which no `sys.modules` rebind moves (`convert_frame.py:1371-1376` reads the same four dicts through the same attribute chain). Its source was the `__import_torch_dot_nn_dot_modules_dot_module` alias unconditionally. Below this commit that alias binds the live `sys.modules` entry, so a program that rebinds `sys.modules["torch.nn.modules.module"]` -- a test fixture, a `mock.patch.dict(sys.modules, ...)` -- leaves the VT's value and its source naming different objects. That is unobservable while the defining module has no hooks, because empty dicts guard as one `TYPE_MATCH` each; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]` -- `<id>` the handle's `RemovableHandle.next_id` at registration, a process-global counter (`torch/utils/hooks.py:22-27`), so `0` only in a process that has registered no earlier hook -- which resolves on the other module and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. The two commits below both have it; #197256, whose memoized `_import_module` still decided the alias, ran the hook when the name had been resolved before the rebind and skipped it otherwise. The source now follows the value. It stays the alias while `self.output.global_scope[alias]` is the defining module, read back after `import_source` because that binding is what a guard rooted at the alias reads. Otherwise it is the `torch` package's own alias walking `.nn.modules.module` -- the attributes the value itself is read through, which the rebind does not move -- so the guards become `G['__import_torch'].nn.modules.module._global_forward_hooks` and so on. Not a name minted by id, which an earlier revision of this commit installed through `install_global_by_id("___nn_modules_module", module)`: `aot_compile.py` enumerates the global names Dynamo mints by prefix and argues the list complete (`_MINTED_GLOBAL_PREFIXES`, `aot_compile.py:75-93`), and a fourth family fails all three places that read it. Measured with an artifact captured under the rebind through `torch.compile(...).aot_compile` with a `guard_filter_fn` that keeps global guards, then loaded with a fresh `guard_globals=` scope: `_seed_guard_scope` (`aot_compile.py:854-872`) seeds `import_sources` aliases and `___unnamed_scope` names and so seeded nothing; `_has_global_guards` (`aot_compile.py:724`) subtracts only `import_sources` aliases and so was `True` for an artifact with no user global; the load then failed `KeyError on G['___nn_modules_module_<id>_c0']` and `_names_a_missing_global` (`aot_compile.py:106-112`) classed it as a user global, so `_missing_global_hint` told the caller to define a name embedding `id()` of an object in the tracing process. Rooted at `__import_torch`, the same artifact's guarded globals are `{__import_torch, __builtins_dict___N}`, `_has_global_guards` is `False`, the load seeds exactly `__import_torch`, and the call matches eager. No new family, so the list in `aot_compile.py` stands; its criterion is reworded here, because these are the first guards on a minted name whose `originating_source` is a chain rather than the `GlobalSource` itself, and the repo has one helper for each reading of "rooted at". `_guard_source_globals` (`aot_compile.py:595`) keeps a guard whose source IS a `GlobalSource`, and returns nothing for `__import_torch` on this artifact (measured: `set()`); `get_global_source_name` (`source.py:1329`) walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) records `global_scope` through, so the name is in `_recorded_guard_globals` (`aot_compile.py:621`), which is what `_has_global_guards` subtracts from and `_seed_guard_scope` seeds. The comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as `get_global_source_name` decides it, with these guards as the example, so a future family with a chained root and its own prefix is not read as exempt. Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right: taking the live entry as the value, the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched, measured on an earlier revision of this tree); keeping the alias as the source unconditionally is the parent, `KeyError: <id>`. The premise that drives the `IMPORT_NAME` fix below -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. In a process that has not rebound `sys.modules` for torch's own module the source is the alias as before, so the guard shape and the recorded `import_sources` are unchanged (`test_aot_compile.py` pins `{"__import_torch_dot_nn_dot_modules_dot_module"}` as that set in two places; both pass here). Order to review: `nn_modules_globals_vt` in `torch/_dynamo/symbolic_convert.py` (the whole change is the `is not module` branch), then `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` in `test/dynamo/test_package.py` for the in-process case, then `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` in `test/dynamo/test_aot_compile.py` for the artifact, then the reworded completeness comment above `_MINTED_GLOBAL_PREFIXES` in `torch/_dynamo/aot_compile.py` (comment only; no code in that file changes). Behaviour change against the parent, pinned below. In process: with `sys.modules["torch.nn.modules.module"]` rebound to a shim carrying empty hook dicts and a forward hook registered on the defining module, compiling a function that calls an `nn.Module` matches eager and runs the hook, where the parent raised `InternalTorchDynamoError: KeyError: <id>` out of guard construction, `<id>` the hook handle's id (`0` in a fresh process, as above). Through an artifact: one captured under the rebind with a `guard_filter_fn` that keeps global guards roots its hook-dict guards at `__import_torch`, and a load seeds that name; the parent's roots at the module's own alias, which a load seeds through `importlib.import_module`, so in a loading process under the same rebind its guards read the shim's dicts. Out of scope here, and the same on the parent and at this commit: the mirror ordering. A capture in a process where the alias binds the defining module takes the alias branch -- the predicate compares `global_scope[alias]` with the module, and they are one object -- so the artifact roots its hook-dict guards at `__import_torch_dot_nn_dot_modules_dot_module`; loaded into a process that has rebound `sys.modules["torch.nn.modules.module"]`, `_seed_guard_scope` (`aot_compile.py:854-859`) binds that alias with `importlib.import_module`, the shim, and builds the guards from the shim's dicts (measured on an earlier revision of this tree: the seeded set is the alias, `scope[alias] is shim`, and the loaded `TYPE_MATCH` reads `type=<class 'dict'>`, the shim's, where the capture's read `OrderedDict`). No trace-time predicate can see that ordering: the rebind exists only in the loading process, and the artifact carries no identity guard on the root for a load to compare the seeded module against, since `MODULE_MATCH` reduces to `ID_MATCH` and both are in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`). The check would have to run at load, in `_seed_guard_scope` -- another file and another PR. What it decides today is bounded, and measured, in the FAQ below. Test Plan: ``` python test/dynamo/test_package.py -k test_import_alias_rebind_keeps_the_global_nn_hooks_visible python test/dynamo/test_aot_compile.py -k test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package python test/dynamo/test_package.py python test/dynamo/test_aot_compile.py ``` `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` joins the `test_import_alias` tests below it and replaces one of them: #197046's `test_import_alias_nn_hook_guards_read_the_live_entry_the_alias_binds`, which pinned, as the state this commit changes, that a forward hook on the defining module under the rebind raises `InternalTorchDynamoError` out of guard construction, is deleted here, because at this tree the raise it asserts no longer happens (measured: run against this tree's `symbolic_convert.py`, it fails with `InternalTorchDynamoError not raised`) and the new test is that pin's flip; the `InternalTorchDynamoError` import in `test_package.py`, which only it used, goes with it. It compiles a function calling an `nn.Module` once so the process has resolved the name, resets, rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts, registers a forward hook on the defining module and compiles again, pinning that the hook runs under compile as in eager (`fired == [mod, mod]`), that `compiled == eager`, that `torch.nn.modules.module` is still the defining module and that the alias holds the shim. In `finally` it removes the hook, restores `sys.modules`, pops both aliases from `fn.__globals__` -- the module's own and `__import_torch`, the fallback root, which the first, clean compile already binds through `IMPORT_NAME` and the fallback rebinds -- and both `_import_source_cache` entries. The hook is what makes the test load-bearing: without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only. It errors on the parent with `InternalTorchDynamoError: KeyError: 0` (measured by running this file's test against the parent's `symbolic_convert.py`; `0` is the handle id in a process that has registered no earlier hook). Two mutations of this tree fail it, measured on an earlier revision whose `nn_modules_globals_vt` is this one: the live entry as the value on `Tensor-likes are not close!` (6/6 mismatched, the hook skipped); the alias as the source unconditionally on `KeyError: 0`. The test's comment names the mechanism the parent's failure has, not the value-side mutation's: the bypass decision reads the VT's value (`_hooks_dict_len`, `nn_module.py:1375`, through `PythonModuleVariable.tp_getattro_impl`, which does `getattr(self.value, name)` on its `is_torch` branch, `misc.py:2030`), the defining module under either source, so it sees the hook either way; it is the `CLOSURE_MATCH` on the hook that reads through the source, `self.get(guard)` (`guards.py:3138`) evaluating `G[alias]._global_forward_hooks[<id>]` against the live scope as the guard is built, which is where the parent's traceback raises `KeyError: 0` (measured: `build_guards -> CLOSURE_MATCH -> get -> get_value -> eval`). `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` captures `fn(m, x)`, `m` a `ParentWithChildModule` passed as an argument so the artifact has no user global, under `patch.dict(sys.modules, {name: shim})` with `keep_global_guards`, serializes it, and pins on the guards state the shape of the guards `get_global_source_name` resolves to `__import_torch`: exactly the four `G['__import_torch'].nn.modules.module._global_*` names, the walk and not only the root, so a change that kept the root and dropped the walk, or walked from another base, fails it. It then pins that `_names_a_missing_global` returns `False` for every recorded global; at this tree that holds by construction, every root being a prefixed alias, and the comment says it stays as the regression guard against a root minted by id. It loads the artifact with a fresh `guard_globals=` scope, still under the rebind, and pins `_has_global_guards` `False`, the seeded names exactly `{"__import_torch"}`, and the call equal to eager. It fails with the id-minted root of this commit's earlier revision (`install_global_by_id("___nn_modules_module", module)`, re-applied to that tree as a mutant) at the `_names_a_missing_global` pin (`True is not false : ___nn_modules_module_<id>_c0`), and on the parent at the guard-shape pin (measured against the parent's `symbolic_convert.py`: the set of guards resolving to `__import_torch` is empty there, the four missing). It registers no hook: see the FAQ below on why. It pops the alias's and `__import_torch`'s `_import_source_cache` entries through `addCleanup`, so an assertion failing inside the `patch.dict` block cannot leave the shim cached; the `__import_torch` binding the capture writes into this module's dict is stripped by `_hide_leaked_dynamo_globals`' cleanup. Whole files at this tree: `test_package.py` 101 tests, OK (skipped=40, expected failures=1); `test_aot_compile.py` 208 tests, OK (skipped=6). ``` lintrunner --take RUFF,PYFMT,GB_REGISTRY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py test/dynamo/test_package.py test/dynamo/test_aot_compile.py lintrunner --take PYREFLY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py ``` PYREFLY reports nothing in the four files this commit touches; its seven findings are in `torch/_dynamo/guards.py` and `torch/_native/cutedsl/hw_caps.py`, neither of which this commit changes. > **FAQ: `nn_modules_globals_vt` still takes its value from a fixed module object while its source comes from `import_source`, which now binds live `sys.modules`. Fix that too -- the divergence silently decides graph shape.** > > Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right. The value has to be the defining module: the dicts the runtime consults are read by `nn.Module._call_impl` through its own `__globals__`, the defining module's `__dict__`, never through the alias, so that is what the bypass decision must read; `convert_frame.py:1371-1376` reads the same dicts through the same attribute chain. Taking the live entry instead, measured with the alias on a shim carrying empty dicts and a forward hook registered on the defining module: the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched). Keeping the defining module as the value with the alias as the source, the shape of the two commits below, is what the earlier answer measured as unobservable -- and it is, while the defining module has no hooks, because the guards are one `TYPE_MATCH` per dict; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]`, `<id>` being `RemovableHandle.next_id` at registration (`0` in a process that has registered no earlier hook), which resolves on the shim and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. So the source now follows the value: the alias while `self.output.global_scope[alias]` is the defining module, otherwise the `torch` package's alias walking `.nn.modules.module`, the attributes the value is read through. The premise that drives the `IMPORT_NAME` fix -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. > **FAQ: the `nn_modules_globals_vt` value/source divergence is documented and hand-measured but not pinned by any test; a test that rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts and asserts a compiled `nn.Module` forward still matches eager would convert the comment into a check.** > > Added as `test_import_alias_rebind_keeps_the_global_nn_hooks_visible`, with one addition to the suggested shape that turned out to matter: a forward hook registered on the defining module. Without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only; with it, the hand measurement's conclusion fell over (previous FAQ), and the test now kills both alternatives -- the live value on a numeric mismatch, the unconditional alias source on `KeyError: 0`, which is what the two commits below produce. It asserts the hook ran once under eager and once more under compile, `compiled == eager`, `torch.nn.modules.module is real` and that the alias holds the shim, and in `finally` removes the hook, restores `sys.modules`, and pops both aliases (`__import_torch` is the fallback root) from `fn.__globals__` and both entries from `_import_source_cache`. > **FAQ: `___nn_modules_module_*` is a fourth Dynamo-minted global family that `aot_compile.py` enumerates nowhere: add the prefix to `_MINTED_GLOBAL_PREFIXES`, seed it in `_seed_guard_scope` with a `CleanupHook.disown`, subtract it in `_has_global_guards`, and update the completeness comment.** > > The family is gone instead. The fallback root is now the `torch` package's `__import_torch` alias with `.nn.modules.module` walked as `AttrSource`s, so every name a guard here can be rooted at is an `__import_*` alias, the first family in that tuple: `_seed_guard_scope` seeds it from `import_sources`, `_has_global_guards` subtracts it, `_names_a_missing_global` recognizes the prefix, and `import_source` binds it by plain assignment, so there is no `CleanupHook` to disown. All three consequences the review derived were reproduced first with the id-minted name (nothing seeded, `_has_global_guards` `True` with no user global, `KeyError on G['___nn_modules_module_<id>_c0']` reported as a global to define) and are absent with this root, which `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` pins. The `torch` package rather than `torch.nn.modules`: the chain then mirrors `torch.nn.modules.module`, the expression the value is read through, and a fixture that rebinds `sys.modules["torch"]` itself leaves nothing in Dynamo working. The completeness comment above the tuple (`aot_compile.py:75-93`) is reworded rather than extended: it said a family belongs in the tuple once a serializable guard is rooted at a `GlobalSource` on one of its names, and `_guard_source_globals` (`aot_compile.py:595`) reads "rooted at" as the `originating_source` IS a `GlobalSource`, which no hook-dict guard here satisfies (their sources are the `AttrSource` chain; that helper returns `set()` for this artifact, measured), so by that reading the family would be out of scope while all three sites act on the name. The reading the three sites share is `get_global_source_name` (`source.py:1329`), which walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) fills `global_scope` with; the comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as that helper decides it, and names these guards as the example. No name outside the three families resolves that way. > **FAQ: why does the artifact test register no hook, and why does it not pin that a hook registered after the load fails the loaded guards?** > > Two measured reasons, neither this commit's to change. First, with a hook on the defining module under the rebind, the capture never reaches the guard-scope sites: the hook makes the trace inline `_call_impl`, whose `__globals__` is the defining module's dict, and `_registered_module_for_globals` resolves `sys.modules[__name__]` to the shim, whose dict is a different object, so `get_globals_source_and_value` falls to the `___unnamed_scope` branch and records the defining module's whole `__dict__` under it; the guards pickler then writes that dict by value and pickles its `T = TypeVar("T")` by qualified name through `sys.modules`, which is the shim, and `aot_compile` raises `PackageError: PicklingError: Can't pickle ~T: attribute lookup T on torch.nn.modules.module failed` (the parent raises `KeyError: 0` earlier on the same input). Second, a hook registered after a compile is not guarded at all, in process and without any rebind: the global hook dicts guard as `TYPE_MATCH` only, under both values of `skip_nnmodule_hook_guards` -- `EMPTY_NN_MODULE_HOOKS_DICT` is installed for the instance's own hook attributes (`nn_module.py:1563-1591`), not for the module globals read here -- so a global forward hook registered after a `torch.compile` call is skipped by the compiled function with no recompile (measured on an earlier revision of this tree: `frame_count` 1, hook fired 0, result differs from eager), which `config.py:458-461` documents as the accepted unsafety. A loaded artifact inherits exactly that, so a hook-after-load phase would pin the same `TYPE_MATCH` pass on every tree. > **FAQ: the fix is conditioned on trace-time state, so the mirror ordering stays silently wrong: a capture in a clean process roots at `__import_torch_dot_nn_dot_modules_dot_module`, and a load into a process that has rebound `sys.modules["torch.nn.modules.module"]` has `_seed_guard_scope` seed that alias with `importlib.import_module`, the shim, whose four empty hook dicts pass the `TYPE_MATCH`es, so the loaded function bypasses `_call_impl` and skips a global hook registered on the real module. Handle it, or state that the ordering is out of scope.** > > Out of scope, stated in the message. The handling would be a load-time change in `aot_compile._seed_guard_scope` -- another file and another PR -- because no predicate in `nn_modules_globals_vt` runs where the rebind is: it runs in the capturing process, where the alias and the defining module are one object, and the artifact has no identity guard on the root for a load to check, `MODULE_MATCH`/`ID_MATCH` being unserializable. Measured on an earlier revision of this tree to size what is left. The seeding half is as the finding says: a hookless `fn(m, x)` capture with `keep_global_guards`, deserialized with a fresh `guard_globals=` under `patch.dict(sys.modules, {name: shim})`, seeds `{"__import_torch_dot_nn_dot_modules_dot_module"}` bound to the shim, and its hook-dict guards are built from the shim's dicts (`type=<class 'dict'>` in the loaded tree, `OrderedDict` in the capture's). The consequence half is narrower: a global forward hook registered on the defining module in the loading process is skipped by that load -- and equally by the clean load of the same artifact, whose alias is seeded with the defining module (`loaded fired=[]`, output equal to the hookless eager, in both). Empty dicts guard as `TYPE_MATCH` only, so the rebind changes which module's dicts the guards read, not what they decide; a hook the capture did not see is the accepted unsafety of the previous FAQ, rebind or not. The shape where the root would decide the outcome needs a capture-time hook, and there the four-dict shim does not pass silently: that capture carries `DICT_LENGTH`/`DICT_CONTAINS`/`EQUALS_MATCH` guards on the alias's hook dicts, `_global_forward_hooks_with_kwargs` among them, and its rebound load fails inside `deserialize` with `AttributeError: module 'torch.nn.modules.module' has no attribute '_global_forward_hooks_with_kwargs'` out of `TYPE_MATCH` creation (`guards.py:2425`), where the clean load of the same artifact runs the hook registered in the loading process. A shim carrying every dict `_call_impl` reads was not measured. > **FAQ: `assertEqual(set(scope) - before, {"__import_torch"})` is the only assertion in the artifact test that discriminates against the parent, and it couples to `keep_global_guards` dropping `MODULE_MATCH`; `assertIn("__import_torch", ...)` plus `assertNotIn(nn_alias, ...)` would state the intent without that coupling.** > > Kept exact, and no longer the only discriminating pin: the guard-shape assertion added above it fails first on the parent (measured: the set of guards resolving to `__import_torch` is empty there). The exact set is the claim this message makes -- the load seeds exactly the one name the kept guards resolve through -- and the coupling is to serialization, not to the filter's choice: `MODULE_MATCH` is in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`), so any filter that lets an artifact serialize drops it, and a second seeded alias would mean a second root some serializable guard resolves through, which is what the pin should catch rather than admit. > **FAQ: `import_source(module.__name__)` is called for its side effects even when its `GlobalSource` is discarded: the alias is recorded in `import_sources`, bound in `f_globals`, and `CompilePackage.install` binds it in every loading process. Check `sys.modules` first and skip the call.** > > The read-back of `global_scope[alias]` after the call is the check, and the comment now says so: it is the binding a guard rooted at the alias reads, and `import_source` is what decides it -- the live entry, or `_import_source_cache` for a name since removed from `sys.modules` or blocked with `None`. Reading `sys.modules` here would duplicate that decision in a second place with its own corner cases. The recorded-but-unread alias is the ordinary state of an `import_sources` entry, not a new one: `test_load_seeds_exactly_the_recorded_globals` asserts `len(guarded) < len(import_sources)` on an artifact whose only guarded alias is this same `__import_torch_dot_nn_dot_modules_dot_module`, and the capture in the new artifact test records six aliases for one guarded root. `install` binding it to the shim in a still-rebound loading process binds a name nothing reads. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: 4452cd8 Pull-Request: #197135
[ghstack-poisoned]
… when the alias binds another Split for review budget from `[dynamo] Bind the import alias to the live sys.modules entry` (#197046), two commits below (`[dynamo] Serve a removed or blocked import name from what the alias last bound`, split from the same commit, sits between): that one makes the `__import_*` alias bind the live `sys.modules` entry; this one makes `nn_modules_globals_vt` stop rooting its guards at that alias once it binds a module other than the one whose dicts the VT reads. `nn_modules_globals_vt` reads the four global hook dicts to decide whether a module call may bypass `_call_impl`, and it has to read the dicts `_call_impl` itself reads through its own `__globals__`: the defining module's, `torch.nn.modules.module`, which no `sys.modules` rebind moves (`convert_frame.py:1371-1376` reads the same four dicts through the same attribute chain). Its source was the `__import_torch_dot_nn_dot_modules_dot_module` alias unconditionally. Below this commit that alias binds the live `sys.modules` entry, so a program that rebinds `sys.modules["torch.nn.modules.module"]` -- a test fixture, a `mock.patch.dict(sys.modules, ...)` -- leaves the VT's value and its source naming different objects. That is unobservable while the defining module has no hooks, because empty dicts guard as one `TYPE_MATCH` each; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]` -- `<id>` the handle's `RemovableHandle.next_id` at registration, a process-global counter (`torch/utils/hooks.py:22-27`), so `0` only in a process that has registered no earlier hook -- which resolves on the other module and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. The two commits below both have it; #197256, whose memoized `_import_module` still decided the alias, ran the hook when the name had been resolved before the rebind and skipped it otherwise. The source now follows the value. It stays the alias while `self.output.global_scope[alias]` is the defining module, read back after `import_source` because that binding is what a guard rooted at the alias reads. Otherwise it is the `torch` package's own alias walking `.nn.modules.module` -- the attributes the value itself is read through, which the rebind does not move -- so the guards become `G['__import_torch'].nn.modules.module._global_forward_hooks` and so on. Not a name minted by id, which an earlier revision of this commit installed through `install_global_by_id("___nn_modules_module", module)`: `aot_compile.py` enumerates the global names Dynamo mints by prefix and argues the list complete (`_MINTED_GLOBAL_PREFIXES`, `aot_compile.py:75-93`), and a fourth family fails all three places that read it. Measured with an artifact captured under the rebind through `torch.compile(...).aot_compile` with a `guard_filter_fn` that keeps global guards, then loaded with a fresh `guard_globals=` scope: `_seed_guard_scope` (`aot_compile.py:854-872`) seeds `import_sources` aliases and `___unnamed_scope` names and so seeded nothing; `_has_global_guards` (`aot_compile.py:724`) subtracts only `import_sources` aliases and so was `True` for an artifact with no user global; the load then failed `KeyError on G['___nn_modules_module_<id>_c0']` and `_names_a_missing_global` (`aot_compile.py:106-112`) classed it as a user global, so `_missing_global_hint` told the caller to define a name embedding `id()` of an object in the tracing process. Rooted at `__import_torch`, the same artifact's guarded globals are `{__import_torch, __builtins_dict___N}`, `_has_global_guards` is `False`, the load seeds exactly `__import_torch`, and the call matches eager. No new family, so the list in `aot_compile.py` stands; its criterion is reworded here, because these are the first guards on a minted name whose `originating_source` is a chain rather than the `GlobalSource` itself, and the repo has one helper for each reading of "rooted at". `_guard_source_globals` (`aot_compile.py:595`) keeps a guard whose source IS a `GlobalSource`, and returns nothing for `__import_torch` on this artifact (measured: `set()`); `get_global_source_name` (`source.py:1329`) walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) records `global_scope` through, so the name is in `_recorded_guard_globals` (`aot_compile.py:621`), which is what `_has_global_guards` subtracts from and `_seed_guard_scope` seeds. The comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as `get_global_source_name` decides it, with these guards as the example, so a future family with a chained root and its own prefix is not read as exempt. Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right: taking the live entry as the value, the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched, measured on an earlier revision of this tree); keeping the alias as the source unconditionally is the parent, `KeyError: <id>`. The premise that drives the `IMPORT_NAME` fix below -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. In a process that has not rebound `sys.modules` for torch's own module the source is the alias as before, so the guard shape and the recorded `import_sources` are unchanged (`test_aot_compile.py` pins `{"__import_torch_dot_nn_dot_modules_dot_module"}` as that set in two places; both pass here). Order to review: `nn_modules_globals_vt` in `torch/_dynamo/symbolic_convert.py` (the whole change is the `is not module` branch), then `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` in `test/dynamo/test_package.py` for the in-process case, then `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` in `test/dynamo/test_aot_compile.py` for the artifact, then the reworded completeness comment above `_MINTED_GLOBAL_PREFIXES` in `torch/_dynamo/aot_compile.py` (comment only; no code in that file changes). Behaviour change against the parent, pinned below. In process: with `sys.modules["torch.nn.modules.module"]` rebound to a shim carrying empty hook dicts and a forward hook registered on the defining module, compiling a function that calls an `nn.Module` matches eager and runs the hook, where the parent raised `InternalTorchDynamoError: KeyError: <id>` out of guard construction, `<id>` the hook handle's id (`0` in a fresh process, as above). Through an artifact: one captured under the rebind with a `guard_filter_fn` that keeps global guards roots its hook-dict guards at `__import_torch`, and a load seeds that name; the parent's roots at the module's own alias, which a load seeds through `importlib.import_module`, so in a loading process under the same rebind its guards read the shim's dicts. Out of scope here, and the same on the parent and at this commit: the mirror ordering. A capture in a process where the alias binds the defining module takes the alias branch -- the predicate compares `global_scope[alias]` with the module, and they are one object -- so the artifact roots its hook-dict guards at `__import_torch_dot_nn_dot_modules_dot_module`; loaded into a process that has rebound `sys.modules["torch.nn.modules.module"]`, `_seed_guard_scope` (`aot_compile.py:854-859`) binds that alias with `importlib.import_module`, the shim, and builds the guards from the shim's dicts (measured on an earlier revision of this tree: the seeded set is the alias, `scope[alias] is shim`, and the loaded `TYPE_MATCH` reads `type=<class 'dict'>`, the shim's, where the capture's read `OrderedDict`). No trace-time predicate can see that ordering: the rebind exists only in the loading process, and the artifact carries no identity guard on the root for a load to compare the seeded module against, since `MODULE_MATCH` reduces to `ID_MATCH` and both are in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`). The check would have to run at load, in `_seed_guard_scope` -- another file and another PR. What it decides today is bounded, and measured, in the FAQ below. Test Plan: ``` python test/dynamo/test_package.py -k test_import_alias_rebind_keeps_the_global_nn_hooks_visible python test/dynamo/test_aot_compile.py -k test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package python test/dynamo/test_package.py python test/dynamo/test_aot_compile.py ``` `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` joins the `test_import_alias` tests below it and replaces one of them: #197046's `test_import_alias_nn_hook_guards_read_the_live_entry_the_alias_binds`, which pinned, as the state this commit changes, that a forward hook on the defining module under the rebind raises `InternalTorchDynamoError` out of guard construction, is deleted here, because at this tree the raise it asserts no longer happens (measured: run against this tree's `symbolic_convert.py`, it fails with `InternalTorchDynamoError not raised`) and the new test is that pin's flip; the `InternalTorchDynamoError` import in `test_package.py`, which only it used, goes with it. It compiles a function calling an `nn.Module` once so the process has resolved the name, resets, rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts, registers a forward hook on the defining module and compiles again, pinning that the hook runs under compile as in eager (`fired == [mod, mod]`), that `compiled == eager`, that `torch.nn.modules.module` is still the defining module and that the alias holds the shim. In `finally` it removes the hook, restores `sys.modules`, pops both aliases from `fn.__globals__` -- the module's own and `__import_torch`, the fallback root, which the first, clean compile already binds through `IMPORT_NAME` and the fallback rebinds -- and both `_import_source_cache` entries. The hook is what makes the test load-bearing: without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only. It errors on the parent with `InternalTorchDynamoError: KeyError: 0` (measured by running this file's test against the parent's `symbolic_convert.py`; `0` is the handle id in a process that has registered no earlier hook). Two mutations of this tree fail it, measured on an earlier revision whose `nn_modules_globals_vt` is this one: the live entry as the value on `Tensor-likes are not close!` (6/6 mismatched, the hook skipped); the alias as the source unconditionally on `KeyError: 0`. The test's comment names the mechanism the parent's failure has, not the value-side mutation's: the bypass decision reads the VT's value (`_hooks_dict_len`, `nn_module.py:1375`, through `PythonModuleVariable.tp_getattro_impl`, which does `getattr(self.value, name)` on its `is_torch` branch, `misc.py:2030`), the defining module under either source, so it sees the hook either way; it is the `CLOSURE_MATCH` on the hook that reads through the source, `self.get(guard)` (`guards.py:3138`) evaluating `G[alias]._global_forward_hooks[<id>]` against the live scope as the guard is built, which is where the parent's traceback raises `KeyError: 0` (measured: `build_guards -> CLOSURE_MATCH -> get -> get_value -> eval`). `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` captures `fn(m, x)`, `m` a `ParentWithChildModule` passed as an argument so the artifact has no user global, under `patch.dict(sys.modules, {name: shim})` with `keep_global_guards`, serializes it, and pins on the guards state the shape of the guards `get_global_source_name` resolves to `__import_torch`: exactly the four `G['__import_torch'].nn.modules.module._global_*` names, the walk and not only the root, so a change that kept the root and dropped the walk, or walked from another base, fails it. It then pins that `_names_a_missing_global` returns `False` for every recorded global; at this tree that holds by construction, every root being a prefixed alias, and the comment says it stays as the regression guard against a root minted by id. It loads the artifact with a fresh `guard_globals=` scope, still under the rebind, and pins `_has_global_guards` `False`, the seeded names exactly `{"__import_torch"}`, and the call equal to eager. It fails with the id-minted root of this commit's earlier revision (`install_global_by_id("___nn_modules_module", module)`, re-applied to that tree as a mutant) at the `_names_a_missing_global` pin (`True is not false : ___nn_modules_module_<id>_c0`), and on the parent at the guard-shape pin (measured against the parent's `symbolic_convert.py`: the set of guards resolving to `__import_torch` is empty there, the four missing). It registers no hook: see the FAQ below on why. It pops the alias's and `__import_torch`'s `_import_source_cache` entries through `addCleanup`, so an assertion failing inside the `patch.dict` block cannot leave the shim cached; the `__import_torch` binding the capture writes into this module's dict is stripped by `_hide_leaked_dynamo_globals`' cleanup. Whole files at this tree: `test_package.py` 101 tests, OK (skipped=40, expected failures=1); `test_aot_compile.py` 208 tests, OK (skipped=6). ``` lintrunner --take RUFF,PYFMT,GB_REGISTRY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py test/dynamo/test_package.py test/dynamo/test_aot_compile.py lintrunner --take PYREFLY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py ``` PYREFLY reports nothing in the four files this commit touches; its seven findings are in `torch/_dynamo/guards.py` and `torch/_native/cutedsl/hw_caps.py`, neither of which this commit changes. > **FAQ: `nn_modules_globals_vt` still takes its value from a fixed module object while its source comes from `import_source`, which now binds live `sys.modules`. Fix that too -- the divergence silently decides graph shape.** > > Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right. The value has to be the defining module: the dicts the runtime consults are read by `nn.Module._call_impl` through its own `__globals__`, the defining module's `__dict__`, never through the alias, so that is what the bypass decision must read; `convert_frame.py:1371-1376` reads the same dicts through the same attribute chain. Taking the live entry instead, measured with the alias on a shim carrying empty dicts and a forward hook registered on the defining module: the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched). Keeping the defining module as the value with the alias as the source, the shape of the two commits below, is what the earlier answer measured as unobservable -- and it is, while the defining module has no hooks, because the guards are one `TYPE_MATCH` per dict; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]`, `<id>` being `RemovableHandle.next_id` at registration (`0` in a process that has registered no earlier hook), which resolves on the shim and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. So the source now follows the value: the alias while `self.output.global_scope[alias]` is the defining module, otherwise the `torch` package's alias walking `.nn.modules.module`, the attributes the value is read through. The premise that drives the `IMPORT_NAME` fix -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. > **FAQ: the `nn_modules_globals_vt` value/source divergence is documented and hand-measured but not pinned by any test; a test that rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts and asserts a compiled `nn.Module` forward still matches eager would convert the comment into a check.** > > Added as `test_import_alias_rebind_keeps_the_global_nn_hooks_visible`, with one addition to the suggested shape that turned out to matter: a forward hook registered on the defining module. Without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only; with it, the hand measurement's conclusion fell over (previous FAQ), and the test now kills both alternatives -- the live value on a numeric mismatch, the unconditional alias source on `KeyError: 0`, which is what the two commits below produce. It asserts the hook ran once under eager and once more under compile, `compiled == eager`, `torch.nn.modules.module is real` and that the alias holds the shim, and in `finally` removes the hook, restores `sys.modules`, and pops both aliases (`__import_torch` is the fallback root) from `fn.__globals__` and both entries from `_import_source_cache`. > **FAQ: `___nn_modules_module_*` is a fourth Dynamo-minted global family that `aot_compile.py` enumerates nowhere: add the prefix to `_MINTED_GLOBAL_PREFIXES`, seed it in `_seed_guard_scope` with a `CleanupHook.disown`, subtract it in `_has_global_guards`, and update the completeness comment.** > > The family is gone instead. The fallback root is now the `torch` package's `__import_torch` alias with `.nn.modules.module` walked as `AttrSource`s, so every name a guard here can be rooted at is an `__import_*` alias, the first family in that tuple: `_seed_guard_scope` seeds it from `import_sources`, `_has_global_guards` subtracts it, `_names_a_missing_global` recognizes the prefix, and `import_source` binds it by plain assignment, so there is no `CleanupHook` to disown. All three consequences the review derived were reproduced first with the id-minted name (nothing seeded, `_has_global_guards` `True` with no user global, `KeyError on G['___nn_modules_module_<id>_c0']` reported as a global to define) and are absent with this root, which `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` pins. The `torch` package rather than `torch.nn.modules`: the chain then mirrors `torch.nn.modules.module`, the expression the value is read through, and a fixture that rebinds `sys.modules["torch"]` itself leaves nothing in Dynamo working. The completeness comment above the tuple (`aot_compile.py:75-93`) is reworded rather than extended: it said a family belongs in the tuple once a serializable guard is rooted at a `GlobalSource` on one of its names, and `_guard_source_globals` (`aot_compile.py:595`) reads "rooted at" as the `originating_source` IS a `GlobalSource`, which no hook-dict guard here satisfies (their sources are the `AttrSource` chain; that helper returns `set()` for this artifact, measured), so by that reading the family would be out of scope while all three sites act on the name. The reading the three sites share is `get_global_source_name` (`source.py:1329`), which walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) fills `global_scope` with; the comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as that helper decides it, and names these guards as the example. No name outside the three families resolves that way. > **FAQ: why does the artifact test register no hook, and why does it not pin that a hook registered after the load fails the loaded guards?** > > Two measured reasons, neither this commit's to change. First, with a hook on the defining module under the rebind, the capture never reaches the guard-scope sites: the hook makes the trace inline `_call_impl`, whose `__globals__` is the defining module's dict, and `_registered_module_for_globals` resolves `sys.modules[__name__]` to the shim, whose dict is a different object, so `get_globals_source_and_value` falls to the `___unnamed_scope` branch and records the defining module's whole `__dict__` under it; the guards pickler then writes that dict by value and pickles its `T = TypeVar("T")` by qualified name through `sys.modules`, which is the shim, and `aot_compile` raises `PackageError: PicklingError: Can't pickle ~T: attribute lookup T on torch.nn.modules.module failed` (the parent raises `KeyError: 0` earlier on the same input). Second, a hook registered after a compile is not guarded at all, in process and without any rebind: the global hook dicts guard as `TYPE_MATCH` only, under both values of `skip_nnmodule_hook_guards` -- `EMPTY_NN_MODULE_HOOKS_DICT` is installed for the instance's own hook attributes (`nn_module.py:1563-1591`), not for the module globals read here -- so a global forward hook registered after a `torch.compile` call is skipped by the compiled function with no recompile (measured on an earlier revision of this tree: `frame_count` 1, hook fired 0, result differs from eager), which `config.py:458-461` documents as the accepted unsafety. A loaded artifact inherits exactly that, so a hook-after-load phase would pin the same `TYPE_MATCH` pass on every tree. > **FAQ: the fix is conditioned on trace-time state, so the mirror ordering stays silently wrong: a capture in a clean process roots at `__import_torch_dot_nn_dot_modules_dot_module`, and a load into a process that has rebound `sys.modules["torch.nn.modules.module"]` has `_seed_guard_scope` seed that alias with `importlib.import_module`, the shim, whose four empty hook dicts pass the `TYPE_MATCH`es, so the loaded function bypasses `_call_impl` and skips a global hook registered on the real module. Handle it, or state that the ordering is out of scope.** > > Out of scope, stated in the message. The handling would be a load-time change in `aot_compile._seed_guard_scope` -- another file and another PR -- because no predicate in `nn_modules_globals_vt` runs where the rebind is: it runs in the capturing process, where the alias and the defining module are one object, and the artifact has no identity guard on the root for a load to check, `MODULE_MATCH`/`ID_MATCH` being unserializable. Measured on an earlier revision of this tree to size what is left. The seeding half is as the finding says: a hookless `fn(m, x)` capture with `keep_global_guards`, deserialized with a fresh `guard_globals=` under `patch.dict(sys.modules, {name: shim})`, seeds `{"__import_torch_dot_nn_dot_modules_dot_module"}` bound to the shim, and its hook-dict guards are built from the shim's dicts (`type=<class 'dict'>` in the loaded tree, `OrderedDict` in the capture's). The consequence half is narrower: a global forward hook registered on the defining module in the loading process is skipped by that load -- and equally by the clean load of the same artifact, whose alias is seeded with the defining module (`loaded fired=[]`, output equal to the hookless eager, in both). Empty dicts guard as `TYPE_MATCH` only, so the rebind changes which module's dicts the guards read, not what they decide; a hook the capture did not see is the accepted unsafety of the previous FAQ, rebind or not. The shape where the root would decide the outcome needs a capture-time hook, and there the four-dict shim does not pass silently: that capture carries `DICT_LENGTH`/`DICT_CONTAINS`/`EQUALS_MATCH` guards on the alias's hook dicts, `_global_forward_hooks_with_kwargs` among them, and its rebound load fails inside `deserialize` with `AttributeError: module 'torch.nn.modules.module' has no attribute '_global_forward_hooks_with_kwargs'` out of `TYPE_MATCH` creation (`guards.py:2425`), where the clean load of the same artifact runs the hook registered in the loading process. A shim carrying every dict `_call_impl` reads was not measured. > **FAQ: `assertEqual(set(scope) - before, {"__import_torch"})` is the only assertion in the artifact test that discriminates against the parent, and it couples to `keep_global_guards` dropping `MODULE_MATCH`; `assertIn("__import_torch", ...)` plus `assertNotIn(nn_alias, ...)` would state the intent without that coupling.** > > Kept exact, and no longer the only discriminating pin: the guard-shape assertion added above it fails first on the parent (measured: the set of guards resolving to `__import_torch` is empty there). The exact set is the claim this message makes -- the load seeds exactly the one name the kept guards resolve through -- and the coupling is to serialization, not to the filter's choice: `MODULE_MATCH` is in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`), so any filter that lets an artifact serialize drops it, and a second seeded alias would mean a second root some serializable guard resolves through, which is what the pin should catch rather than admit. > **FAQ: `import_source(module.__name__)` is called for its side effects even when its `GlobalSource` is discarded: the alias is recorded in `import_sources`, bound in `f_globals`, and `CompilePackage.install` binds it in every loading process. Check `sys.modules` first and skip the call.** > > The read-back of `global_scope[alias]` after the call is the check, and the comment now says so: it is the binding a guard rooted at the alias reads, and `import_source` is what decides it -- the live entry, or `_import_source_cache` for a name since removed from `sys.modules` or blocked with `None`. Reading `sys.modules` here would duplicate that decision in a second place with its own corner cases. The recorded-but-unread alias is the ordinary state of an `import_sources` entry, not a new one: `test_load_seeds_exactly_the_recorded_globals` asserts `len(guarded) < len(import_sources)` on an artifact whose only guarded alias is this same `__import_torch_dot_nn_dot_modules_dot_module`, and the capture in the new artifact test records six aliases for one guarded root. `install` binding it to the shim in a still-rebound loading process binds a name nothing reads. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: acf4980 Pull-Request: #197135
[ghstack-poisoned]
… when the alias binds another Split for review budget from `[dynamo] Bind the import alias to the live sys.modules entry` (#197046), two commits below (`[dynamo] Serve a removed or blocked import name from what the alias last bound`, split from the same commit, sits between): that one makes the `__import_*` alias bind the live `sys.modules` entry; this one makes `nn_modules_globals_vt` stop rooting its guards at that alias once it binds a module other than the one whose dicts the VT reads. `nn_modules_globals_vt` reads the four global hook dicts to decide whether a module call may bypass `_call_impl`, and it has to read the dicts `_call_impl` itself reads through its own `__globals__`: the defining module's, `torch.nn.modules.module`, which no `sys.modules` rebind moves (`convert_frame.py:1371-1376` reads the same four dicts through the same attribute chain). Its source was the `__import_torch_dot_nn_dot_modules_dot_module` alias unconditionally. Below this commit that alias binds the live `sys.modules` entry, so a program that rebinds `sys.modules["torch.nn.modules.module"]` -- a test fixture, a `mock.patch.dict(sys.modules, ...)` -- leaves the VT's value and its source naming different objects. That is unobservable while the defining module has no hooks, because empty dicts guard as one `TYPE_MATCH` each; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]` -- `<id>` the handle's `RemovableHandle.next_id` at registration, a process-global counter (`torch/utils/hooks.py:22-27`), so `0` only in a process that has registered no earlier hook -- which resolves on the other module and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. The two commits below both have it; #197256, whose memoized `_import_module` still decided the alias, ran the hook when the name had been resolved before the rebind and skipped it otherwise. The source now follows the value. It stays the alias while `self.output.global_scope[alias]` is the defining module, read back after `import_source` because that binding is what a guard rooted at the alias reads. Otherwise it is the `torch` package's own alias walking `.nn.modules.module` -- the attributes the value itself is read through, which the rebind does not move -- so the guards become `G['__import_torch'].nn.modules.module._global_forward_hooks` and so on. Not a name minted by id, which an earlier revision of this commit installed through `install_global_by_id("___nn_modules_module", module)`: `aot_compile.py` enumerates the global names Dynamo mints by prefix and argues the list complete (`_MINTED_GLOBAL_PREFIXES`, `aot_compile.py:75-93`), and a fourth family fails all three places that read it. Measured with an artifact captured under the rebind through `torch.compile(...).aot_compile` with a `guard_filter_fn` that keeps global guards, then loaded with a fresh `guard_globals=` scope: `_seed_guard_scope` (`aot_compile.py:854-872`) seeds `import_sources` aliases and `___unnamed_scope` names and so seeded nothing; `_has_global_guards` (`aot_compile.py:724`) subtracts only `import_sources` aliases and so was `True` for an artifact with no user global; the load then failed `KeyError on G['___nn_modules_module_<id>_c0']` and `_names_a_missing_global` (`aot_compile.py:106-112`) classed it as a user global, so `_missing_global_hint` told the caller to define a name embedding `id()` of an object in the tracing process. Rooted at `__import_torch`, the same artifact's guarded globals are `{__import_torch, __builtins_dict___N}`, `_has_global_guards` is `False`, the load seeds exactly `__import_torch`, and the call matches eager. No new family, so the list in `aot_compile.py` stands; its criterion is reworded here, because these are the first guards on a minted name whose `originating_source` is a chain rather than the `GlobalSource` itself, and the repo has one helper for each reading of "rooted at". `_guard_source_globals` (`aot_compile.py:595`) keeps a guard whose source IS a `GlobalSource`, and returns nothing for `__import_torch` on this artifact (measured: `set()`); `get_global_source_name` (`source.py:1329`) walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) records `global_scope` through, so the name is in `_recorded_guard_globals` (`aot_compile.py:621`), which is what `_has_global_guards` subtracts from and `_seed_guard_scope` seeds. The comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as `get_global_source_name` decides it, with these guards as the example, so a future family with a chained root and its own prefix is not read as exempt. Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right: taking the live entry as the value, the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched, measured on an earlier revision of this tree); keeping the alias as the source unconditionally is the parent, `KeyError: <id>`. The premise that drives the `IMPORT_NAME` fix below -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. In a process that has not rebound `sys.modules` for torch's own module the source is the alias as before, so the guard shape and the recorded `import_sources` are unchanged (`test_aot_compile.py` pins `{"__import_torch_dot_nn_dot_modules_dot_module"}` as that set in two places; both pass here). Order to review: `nn_modules_globals_vt` in `torch/_dynamo/symbolic_convert.py` (the whole change is the `is not module` branch), then `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` in `test/dynamo/test_package.py` for the in-process case, then `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` in `test/dynamo/test_aot_compile.py` for the artifact, then the reworded completeness comment above `_MINTED_GLOBAL_PREFIXES` in `torch/_dynamo/aot_compile.py` (comment only; no code in that file changes). Behaviour change against the parent, pinned below. In process: with `sys.modules["torch.nn.modules.module"]` rebound to a shim carrying empty hook dicts and a forward hook registered on the defining module, compiling a function that calls an `nn.Module` matches eager and runs the hook, where the parent raised `InternalTorchDynamoError: KeyError: <id>` out of guard construction, `<id>` the hook handle's id (`0` in a fresh process, as above). Through an artifact: one captured under the rebind with a `guard_filter_fn` that keeps global guards roots its hook-dict guards at `__import_torch`, and a load seeds that name; the parent's roots at the module's own alias, which a load seeds through `importlib.import_module`, so in a loading process under the same rebind its guards read the shim's dicts. Out of scope here, and the same on the parent and at this commit: the mirror ordering. A capture in a process where the alias binds the defining module takes the alias branch -- the predicate compares `global_scope[alias]` with the module, and they are one object -- so the artifact roots its hook-dict guards at `__import_torch_dot_nn_dot_modules_dot_module`; loaded into a process that has rebound `sys.modules["torch.nn.modules.module"]`, `_seed_guard_scope` (`aot_compile.py:854-859`) binds that alias with `importlib.import_module`, the shim, and builds the guards from the shim's dicts (measured on an earlier revision of this tree: the seeded set is the alias, `scope[alias] is shim`, and the loaded `TYPE_MATCH` reads `type=<class 'dict'>`, the shim's, where the capture's read `OrderedDict`). No trace-time predicate can see that ordering: the rebind exists only in the loading process, and the artifact carries no identity guard on the root for a load to compare the seeded module against, since `MODULE_MATCH` reduces to `ID_MATCH` and both are in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`). The check would have to run at load, in `_seed_guard_scope` -- another file and another PR. What it decides today is bounded, and measured, in the FAQ below. Test Plan: ``` python test/dynamo/test_package.py -k test_import_alias_rebind_keeps_the_global_nn_hooks_visible python test/dynamo/test_aot_compile.py -k test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package python test/dynamo/test_package.py python test/dynamo/test_aot_compile.py ``` `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` joins the `test_import_alias` tests below it and replaces one of them: #197046's `test_import_alias_nn_hook_guards_read_the_live_entry_the_alias_binds`, which pinned, as the state this commit changes, that a forward hook on the defining module under the rebind raises `InternalTorchDynamoError` out of guard construction, is deleted here, because at this tree the raise it asserts no longer happens (measured: run against this tree's `symbolic_convert.py`, it fails with `InternalTorchDynamoError not raised`) and the new test is that pin's flip; the `InternalTorchDynamoError` import in `test_package.py`, which only it used, goes with it. It compiles a function calling an `nn.Module` once so the process has resolved the name, resets, rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts, registers a forward hook on the defining module and compiles again, pinning that the hook runs under compile as in eager (`fired == [mod, mod]`), that `compiled == eager`, that `torch.nn.modules.module` is still the defining module and that the alias holds the shim. In `finally` it removes the hook, restores `sys.modules`, pops both aliases from `fn.__globals__` -- the module's own and `__import_torch`, the fallback root, which the first, clean compile already binds through `IMPORT_NAME` and the fallback rebinds -- and both `_import_source_cache` entries. The hook is what makes the test load-bearing: without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only. It errors on the parent with `InternalTorchDynamoError: KeyError: 0` (measured by running this file's test against the parent's `symbolic_convert.py`; `0` is the handle id in a process that has registered no earlier hook). Two mutations of this tree fail it, measured on an earlier revision whose `nn_modules_globals_vt` is this one: the live entry as the value on `Tensor-likes are not close!` (6/6 mismatched, the hook skipped); the alias as the source unconditionally on `KeyError: 0`. The test's comment names the mechanism the parent's failure has, not the value-side mutation's: the bypass decision reads the VT's value (`_hooks_dict_len`, `nn_module.py:1375`, through `PythonModuleVariable.tp_getattro_impl`, which does `getattr(self.value, name)` on its `is_torch` branch, `misc.py:2030`), the defining module under either source, so it sees the hook either way; it is the `CLOSURE_MATCH` on the hook that reads through the source, `self.get(guard)` (`guards.py:3138`) evaluating `G[alias]._global_forward_hooks[<id>]` against the live scope as the guard is built, which is where the parent's traceback raises `KeyError: 0` (measured: `build_guards -> CLOSURE_MATCH -> get -> get_value -> eval`). `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` captures `fn(m, x)`, `m` a `ParentWithChildModule` passed as an argument so the artifact has no user global, under `patch.dict(sys.modules, {name: shim})` with `keep_global_guards`, serializes it, and pins on the guards state the shape of the guards `get_global_source_name` resolves to `__import_torch`: exactly the four `G['__import_torch'].nn.modules.module._global_*` names, the walk and not only the root, so a change that kept the root and dropped the walk, or walked from another base, fails it. It then pins that `_names_a_missing_global` returns `False` for every recorded global; at this tree that holds by construction, every root being a prefixed alias, and the comment says it stays as the regression guard against a root minted by id. It loads the artifact with a fresh `guard_globals=` scope, still under the rebind, and pins `_has_global_guards` `False`, the seeded names exactly `{"__import_torch"}`, and the call equal to eager. It fails with the id-minted root of this commit's earlier revision (`install_global_by_id("___nn_modules_module", module)`, re-applied to that tree as a mutant) at the `_names_a_missing_global` pin (`True is not false : ___nn_modules_module_<id>_c0`), and on the parent at the guard-shape pin (measured against the parent's `symbolic_convert.py`: the set of guards resolving to `__import_torch` is empty there, the four missing). It registers no hook: see the FAQ below on why. It pops the alias's and `__import_torch`'s `_import_source_cache` entries through `addCleanup`, so an assertion failing inside the `patch.dict` block cannot leave the shim cached; the `__import_torch` binding the capture writes into this module's dict is stripped by `_hide_leaked_dynamo_globals`' cleanup. Whole files at this tree: `test_package.py` 101 tests, OK (skipped=40, expected failures=1); `test_aot_compile.py` 208 tests, OK (skipped=6). ``` lintrunner --take RUFF,PYFMT,GB_REGISTRY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py test/dynamo/test_package.py test/dynamo/test_aot_compile.py lintrunner --take PYREFLY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py ``` PYREFLY reports nothing in the four files this commit touches; its seven findings are in `torch/_dynamo/guards.py` and `torch/_native/cutedsl/hw_caps.py`, neither of which this commit changes. > **FAQ: `nn_modules_globals_vt` still takes its value from a fixed module object while its source comes from `import_source`, which now binds live `sys.modules`. Fix that too -- the divergence silently decides graph shape.** > > Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right. The value has to be the defining module: the dicts the runtime consults are read by `nn.Module._call_impl` through its own `__globals__`, the defining module's `__dict__`, never through the alias, so that is what the bypass decision must read; `convert_frame.py:1371-1376` reads the same dicts through the same attribute chain. Taking the live entry instead, measured with the alias on a shim carrying empty dicts and a forward hook registered on the defining module: the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched). Keeping the defining module as the value with the alias as the source, the shape of the two commits below, is what the earlier answer measured as unobservable -- and it is, while the defining module has no hooks, because the guards are one `TYPE_MATCH` per dict; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]`, `<id>` being `RemovableHandle.next_id` at registration (`0` in a process that has registered no earlier hook), which resolves on the shim and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. So the source now follows the value: the alias while `self.output.global_scope[alias]` is the defining module, otherwise the `torch` package's alias walking `.nn.modules.module`, the attributes the value is read through. The premise that drives the `IMPORT_NAME` fix -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. > **FAQ: the `nn_modules_globals_vt` value/source divergence is documented and hand-measured but not pinned by any test; a test that rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts and asserts a compiled `nn.Module` forward still matches eager would convert the comment into a check.** > > Added as `test_import_alias_rebind_keeps_the_global_nn_hooks_visible`, with one addition to the suggested shape that turned out to matter: a forward hook registered on the defining module. Without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only; with it, the hand measurement's conclusion fell over (previous FAQ), and the test now kills both alternatives -- the live value on a numeric mismatch, the unconditional alias source on `KeyError: 0`, which is what the two commits below produce. It asserts the hook ran once under eager and once more under compile, `compiled == eager`, `torch.nn.modules.module is real` and that the alias holds the shim, and in `finally` removes the hook, restores `sys.modules`, and pops both aliases (`__import_torch` is the fallback root) from `fn.__globals__` and both entries from `_import_source_cache`. > **FAQ: `___nn_modules_module_*` is a fourth Dynamo-minted global family that `aot_compile.py` enumerates nowhere: add the prefix to `_MINTED_GLOBAL_PREFIXES`, seed it in `_seed_guard_scope` with a `CleanupHook.disown`, subtract it in `_has_global_guards`, and update the completeness comment.** > > The family is gone instead. The fallback root is now the `torch` package's `__import_torch` alias with `.nn.modules.module` walked as `AttrSource`s, so every name a guard here can be rooted at is an `__import_*` alias, the first family in that tuple: `_seed_guard_scope` seeds it from `import_sources`, `_has_global_guards` subtracts it, `_names_a_missing_global` recognizes the prefix, and `import_source` binds it by plain assignment, so there is no `CleanupHook` to disown. All three consequences the review derived were reproduced first with the id-minted name (nothing seeded, `_has_global_guards` `True` with no user global, `KeyError on G['___nn_modules_module_<id>_c0']` reported as a global to define) and are absent with this root, which `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` pins. The `torch` package rather than `torch.nn.modules`: the chain then mirrors `torch.nn.modules.module`, the expression the value is read through, and a fixture that rebinds `sys.modules["torch"]` itself leaves nothing in Dynamo working. The completeness comment above the tuple (`aot_compile.py:75-93`) is reworded rather than extended: it said a family belongs in the tuple once a serializable guard is rooted at a `GlobalSource` on one of its names, and `_guard_source_globals` (`aot_compile.py:595`) reads "rooted at" as the `originating_source` IS a `GlobalSource`, which no hook-dict guard here satisfies (their sources are the `AttrSource` chain; that helper returns `set()` for this artifact, measured), so by that reading the family would be out of scope while all three sites act on the name. The reading the three sites share is `get_global_source_name` (`source.py:1329`), which walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) fills `global_scope` with; the comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as that helper decides it, and names these guards as the example. No name outside the three families resolves that way. > **FAQ: why does the artifact test register no hook, and why does it not pin that a hook registered after the load fails the loaded guards?** > > Two measured reasons, neither this commit's to change. First, with a hook on the defining module under the rebind, the capture never reaches the guard-scope sites: the hook makes the trace inline `_call_impl`, whose `__globals__` is the defining module's dict, and `_registered_module_for_globals` resolves `sys.modules[__name__]` to the shim, whose dict is a different object, so `get_globals_source_and_value` falls to the `___unnamed_scope` branch and records the defining module's whole `__dict__` under it; the guards pickler then writes that dict by value and pickles its `T = TypeVar("T")` by qualified name through `sys.modules`, which is the shim, and `aot_compile` raises `PackageError: PicklingError: Can't pickle ~T: attribute lookup T on torch.nn.modules.module failed` (the parent raises `KeyError: 0` earlier on the same input). Second, a hook registered after a compile is not guarded at all, in process and without any rebind: the global hook dicts guard as `TYPE_MATCH` only, under both values of `skip_nnmodule_hook_guards` -- `EMPTY_NN_MODULE_HOOKS_DICT` is installed for the instance's own hook attributes (`nn_module.py:1563-1591`), not for the module globals read here -- so a global forward hook registered after a `torch.compile` call is skipped by the compiled function with no recompile (measured on an earlier revision of this tree: `frame_count` 1, hook fired 0, result differs from eager), which `config.py:458-461` documents as the accepted unsafety. A loaded artifact inherits exactly that, so a hook-after-load phase would pin the same `TYPE_MATCH` pass on every tree. > **FAQ: the fix is conditioned on trace-time state, so the mirror ordering stays silently wrong: a capture in a clean process roots at `__import_torch_dot_nn_dot_modules_dot_module`, and a load into a process that has rebound `sys.modules["torch.nn.modules.module"]` has `_seed_guard_scope` seed that alias with `importlib.import_module`, the shim, whose four empty hook dicts pass the `TYPE_MATCH`es, so the loaded function bypasses `_call_impl` and skips a global hook registered on the real module. Handle it, or state that the ordering is out of scope.** > > Out of scope, stated in the message. The handling would be a load-time change in `aot_compile._seed_guard_scope` -- another file and another PR -- because no predicate in `nn_modules_globals_vt` runs where the rebind is: it runs in the capturing process, where the alias and the defining module are one object, and the artifact has no identity guard on the root for a load to check, `MODULE_MATCH`/`ID_MATCH` being unserializable. Measured on an earlier revision of this tree to size what is left. The seeding half is as the finding says: a hookless `fn(m, x)` capture with `keep_global_guards`, deserialized with a fresh `guard_globals=` under `patch.dict(sys.modules, {name: shim})`, seeds `{"__import_torch_dot_nn_dot_modules_dot_module"}` bound to the shim, and its hook-dict guards are built from the shim's dicts (`type=<class 'dict'>` in the loaded tree, `OrderedDict` in the capture's). The consequence half is narrower: a global forward hook registered on the defining module in the loading process is skipped by that load -- and equally by the clean load of the same artifact, whose alias is seeded with the defining module (`loaded fired=[]`, output equal to the hookless eager, in both). Empty dicts guard as `TYPE_MATCH` only, so the rebind changes which module's dicts the guards read, not what they decide; a hook the capture did not see is the accepted unsafety of the previous FAQ, rebind or not. The shape where the root would decide the outcome needs a capture-time hook, and there the four-dict shim does not pass silently: that capture carries `DICT_LENGTH`/`DICT_CONTAINS`/`EQUALS_MATCH` guards on the alias's hook dicts, `_global_forward_hooks_with_kwargs` among them, and its rebound load fails inside `deserialize` with `AttributeError: module 'torch.nn.modules.module' has no attribute '_global_forward_hooks_with_kwargs'` out of `TYPE_MATCH` creation (`guards.py:2425`), where the clean load of the same artifact runs the hook registered in the loading process. A shim carrying every dict `_call_impl` reads was not measured. > **FAQ: `assertEqual(set(scope) - before, {"__import_torch"})` is the only assertion in the artifact test that discriminates against the parent, and it couples to `keep_global_guards` dropping `MODULE_MATCH`; `assertIn("__import_torch", ...)` plus `assertNotIn(nn_alias, ...)` would state the intent without that coupling.** > > Kept exact, and no longer the only discriminating pin: the guard-shape assertion added above it fails first on the parent (measured: the set of guards resolving to `__import_torch` is empty there). The exact set is the claim this message makes -- the load seeds exactly the one name the kept guards resolve through -- and the coupling is to serialization, not to the filter's choice: `MODULE_MATCH` is in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`), so any filter that lets an artifact serialize drops it, and a second seeded alias would mean a second root some serializable guard resolves through, which is what the pin should catch rather than admit. > **FAQ: `import_source(module.__name__)` is called for its side effects even when its `GlobalSource` is discarded: the alias is recorded in `import_sources`, bound in `f_globals`, and `CompilePackage.install` binds it in every loading process. Check `sys.modules` first and skip the call.** > > The read-back of `global_scope[alias]` after the call is the check, and the comment now says so: it is the binding a guard rooted at the alias reads, and `import_source` is what decides it -- the live entry, or `_import_source_cache` for a name since removed from `sys.modules` or blocked with `None`. Reading `sys.modules` here would duplicate that decision in a second place with its own corner cases. The recorded-but-unread alias is the ordinary state of an `import_sources` entry, not a new one: `test_load_seeds_exactly_the_recorded_globals` asserts `len(guarded) < len(import_sources)` on an artifact whose only guarded alias is this same `__import_torch_dot_nn_dot_modules_dot_module`, and the capture in the new artifact test records six aliases for one guarded root. `install` binding it to the shim in a still-rebound loading process binds a name nothing reads. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: dc0f127 Pull-Request: #197135
[ghstack-poisoned]
… when the alias binds another Split for review budget from `[dynamo] Bind the import alias to the live sys.modules entry` (#197046), two commits below (`[dynamo] Serve a removed or blocked import name from what the alias last bound`, split from the same commit, sits between): that one makes the `__import_*` alias bind the live `sys.modules` entry; this one makes `nn_modules_globals_vt` stop rooting its guards at that alias once it binds a module other than the one whose dicts the VT reads. `nn_modules_globals_vt` reads the four global hook dicts to decide whether a module call may bypass `_call_impl`, and it has to read the dicts `_call_impl` itself reads through its own `__globals__`: the defining module's, `torch.nn.modules.module`, which no `sys.modules` rebind moves (`convert_frame.py:1371-1376` reads the same four dicts through the same attribute chain). Its source was the `__import_torch_dot_nn_dot_modules_dot_module` alias unconditionally. Below this commit that alias binds the live `sys.modules` entry, so a program that rebinds `sys.modules["torch.nn.modules.module"]` -- a test fixture, a `mock.patch.dict(sys.modules, ...)` -- leaves the VT's value and its source naming different objects. That is unobservable while the defining module has no hooks, because empty dicts guard as one `TYPE_MATCH` each; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]` -- `<id>` the handle's `RemovableHandle.next_id` at registration, a process-global counter (`torch/utils/hooks.py:22-27`), so `0` only in a process that has registered no earlier hook -- which resolves on the other module and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. The two commits below both have it; #197256, whose memoized `_import_module` still decided the alias, ran the hook when the name had been resolved before the rebind and skipped it otherwise. The source now follows the value. It stays the alias while `self.output.global_scope[alias]` is the defining module, read back after `import_source` because that binding is what a guard rooted at the alias reads. Otherwise it is the `torch` package's own alias walking `.nn.modules.module` -- the attributes the value itself is read through, which the rebind does not move -- so the guards become `G['__import_torch'].nn.modules.module._global_forward_hooks` and so on. Not a name minted by id, which an earlier revision of this commit installed through `install_global_by_id("___nn_modules_module", module)`: `aot_compile.py` enumerates the global names Dynamo mints by prefix and argues the list complete (`_MINTED_GLOBAL_PREFIXES`, `aot_compile.py:75-93`), and a fourth family fails all three places that read it. Measured with an artifact captured under the rebind through `torch.compile(...).aot_compile` with a `guard_filter_fn` that keeps global guards, then loaded with a fresh `guard_globals=` scope: `_seed_guard_scope` (`aot_compile.py:854-872`) seeds `import_sources` aliases and `___unnamed_scope` names and so seeded nothing; `_has_global_guards` (`aot_compile.py:724`) subtracts only `import_sources` aliases and so was `True` for an artifact with no user global; the load then failed `KeyError on G['___nn_modules_module_<id>_c0']` and `_names_a_missing_global` (`aot_compile.py:106-112`) classed it as a user global, so `_missing_global_hint` told the caller to define a name embedding `id()` of an object in the tracing process. Rooted at `__import_torch`, the same artifact's guarded globals are `{__import_torch, __builtins_dict___N}`, `_has_global_guards` is `False`, the load seeds exactly `__import_torch`, and the call matches eager. No new family, so the list in `aot_compile.py` stands; its criterion is reworded here, because these are the first guards on a minted name whose `originating_source` is a chain rather than the `GlobalSource` itself, and the repo has one helper for each reading of "rooted at". `_guard_source_globals` (`aot_compile.py:595`) keeps a guard whose source IS a `GlobalSource`, and returns nothing for `__import_torch` on this artifact (measured: `set()`); `get_global_source_name` (`source.py:1329`) walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) records `global_scope` through, so the name is in `_recorded_guard_globals` (`aot_compile.py:621`), which is what `_has_global_guards` subtracts from and `_seed_guard_scope` seeds. The comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as `get_global_source_name` decides it, with these guards as the example, so a future family with a chained root and its own prefix is not read as exempt. Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right: taking the live entry as the value, the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched, measured on an earlier revision of this tree); keeping the alias as the source unconditionally is the parent, `KeyError: <id>`. The premise that drives the `IMPORT_NAME` fix below -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. In a process that has not rebound `sys.modules` for torch's own module the source is the alias as before, so the guard shape and the recorded `import_sources` are unchanged (`test_aot_compile.py` pins `{"__import_torch_dot_nn_dot_modules_dot_module"}` as that set in two places; both pass here). Order to review: `nn_modules_globals_vt` in `torch/_dynamo/symbolic_convert.py` (the whole change is the `is not module` branch), then `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` in `test/dynamo/test_package.py` for the in-process case, then `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` in `test/dynamo/test_aot_compile.py` for the artifact, then the reworded completeness comment above `_MINTED_GLOBAL_PREFIXES` in `torch/_dynamo/aot_compile.py` (comment only; no code in that file changes). Behaviour change against the parent, pinned below. In process: with `sys.modules["torch.nn.modules.module"]` rebound to a shim carrying empty hook dicts and a forward hook registered on the defining module, compiling a function that calls an `nn.Module` matches eager and runs the hook, where the parent raised `InternalTorchDynamoError: KeyError: <id>` out of guard construction, `<id>` the hook handle's id (`0` in a fresh process, as above). Through an artifact: one captured under the rebind with a `guard_filter_fn` that keeps global guards roots its hook-dict guards at `__import_torch`, and a load seeds that name; the parent's roots at the module's own alias, which a load seeds through `importlib.import_module`, so in a loading process under the same rebind its guards read the shim's dicts. Out of scope here, and the same on the parent and at this commit: the mirror ordering. A capture in a process where the alias binds the defining module takes the alias branch -- the predicate compares `global_scope[alias]` with the module, and they are one object -- so the artifact roots its hook-dict guards at `__import_torch_dot_nn_dot_modules_dot_module`; loaded into a process that has rebound `sys.modules["torch.nn.modules.module"]`, `_seed_guard_scope` (`aot_compile.py:854-859`) binds that alias with `importlib.import_module`, the shim, and builds the guards from the shim's dicts (measured on an earlier revision of this tree: the seeded set is the alias, `scope[alias] is shim`, and the loaded `TYPE_MATCH` reads `type=<class 'dict'>`, the shim's, where the capture's read `OrderedDict`). No trace-time predicate can see that ordering: the rebind exists only in the loading process, and the artifact carries no identity guard on the root for a load to compare the seeded module against, since `MODULE_MATCH` reduces to `ID_MATCH` and both are in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`). The check would have to run at load, in `_seed_guard_scope` -- another file and another PR. What it decides today is bounded, and measured, in the FAQ below. Test Plan: ``` python test/dynamo/test_package.py -k test_import_alias_rebind_keeps_the_global_nn_hooks_visible python test/dynamo/test_aot_compile.py -k test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package python test/dynamo/test_package.py python test/dynamo/test_aot_compile.py ``` `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` joins the `test_import_alias` tests below it and replaces one of them: #197046's `test_import_alias_nn_hook_guards_read_the_live_entry_the_alias_binds`, which pinned, as the state this commit changes, that a forward hook on the defining module under the rebind raises `InternalTorchDynamoError` out of guard construction, is deleted here, because at this tree the raise it asserts no longer happens (measured: run against this tree's `symbolic_convert.py`, it fails with `InternalTorchDynamoError not raised`) and the new test is that pin's flip; the `InternalTorchDynamoError` import in `test_package.py`, which only it used, goes with it. It compiles a function calling an `nn.Module` once so the process has resolved the name, resets, rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts, registers a forward hook on the defining module and compiles again, pinning that the hook runs under compile as in eager (`fired == [mod, mod]`), that `compiled == eager`, that `torch.nn.modules.module` is still the defining module and that the alias holds the shim. In `finally` it removes the hook, restores `sys.modules`, pops both aliases from `fn.__globals__` -- the module's own and `__import_torch`, the fallback root, which the first, clean compile already binds through `IMPORT_NAME` and the fallback rebinds -- and both `_import_source_cache` entries. The hook is what makes the test load-bearing: without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only. It errors on the parent with `InternalTorchDynamoError: KeyError: 0` (measured by running this file's test against the parent's `symbolic_convert.py`; `0` is the handle id in a process that has registered no earlier hook). Two mutations of this tree fail it, measured on an earlier revision whose `nn_modules_globals_vt` is this one: the live entry as the value on `Tensor-likes are not close!` (6/6 mismatched, the hook skipped); the alias as the source unconditionally on `KeyError: 0`. The test's comment names the mechanism the parent's failure has, not the value-side mutation's: the bypass decision reads the VT's value (`_hooks_dict_len`, `nn_module.py:1375`, through `PythonModuleVariable.tp_getattro_impl`, which does `getattr(self.value, name)` on its `is_torch` branch, `misc.py:2030`), the defining module under either source, so it sees the hook either way; it is the `CLOSURE_MATCH` on the hook that reads through the source, `self.get(guard)` (`guards.py:3138`) evaluating `G[alias]._global_forward_hooks[<id>]` against the live scope as the guard is built, which is where the parent's traceback raises `KeyError: 0` (measured: `build_guards -> CLOSURE_MATCH -> get -> get_value -> eval`). `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` captures `fn(m, x)`, `m` a `ParentWithChildModule` passed as an argument so the artifact has no user global, under `patch.dict(sys.modules, {name: shim})` with `keep_global_guards`, serializes it, and pins on the guards state the shape of the guards `get_global_source_name` resolves to `__import_torch`: exactly the four `G['__import_torch'].nn.modules.module._global_*` names, the walk and not only the root, so a change that kept the root and dropped the walk, or walked from another base, fails it. It then pins that `_names_a_missing_global` returns `False` for every recorded global; at this tree that holds by construction, every root being a prefixed alias, and the comment says it stays as the regression guard against a root minted by id. It loads the artifact with a fresh `guard_globals=` scope, still under the rebind, and pins `_has_global_guards` `False`, the seeded names exactly `{"__import_torch"}`, and the call equal to eager. It fails with the id-minted root of this commit's earlier revision (`install_global_by_id("___nn_modules_module", module)`, re-applied to that tree as a mutant) at the `_names_a_missing_global` pin (`True is not false : ___nn_modules_module_<id>_c0`), and on the parent at the guard-shape pin (measured against the parent's `symbolic_convert.py`: the set of guards resolving to `__import_torch` is empty there, the four missing). It registers no hook: see the FAQ below on why. It pops the alias's and `__import_torch`'s `_import_source_cache` entries through `addCleanup`, so an assertion failing inside the `patch.dict` block cannot leave the shim cached; the `__import_torch` binding the capture writes into this module's dict is stripped by `_hide_leaked_dynamo_globals`' cleanup. Whole files at this tree: `test_package.py` 101 tests, OK (skipped=40, expected failures=1); `test_aot_compile.py` 208 tests, OK (skipped=6). ``` lintrunner --take RUFF,PYFMT,GB_REGISTRY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py test/dynamo/test_package.py test/dynamo/test_aot_compile.py lintrunner --take PYREFLY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py ``` PYREFLY reports nothing in the four files this commit touches; its seven findings are in `torch/_dynamo/guards.py` and `torch/_native/cutedsl/hw_caps.py`, neither of which this commit changes. > **FAQ: `nn_modules_globals_vt` still takes its value from a fixed module object while its source comes from `import_source`, which now binds live `sys.modules`. Fix that too -- the divergence silently decides graph shape.** > > Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right. The value has to be the defining module: the dicts the runtime consults are read by `nn.Module._call_impl` through its own `__globals__`, the defining module's `__dict__`, never through the alias, so that is what the bypass decision must read; `convert_frame.py:1371-1376` reads the same dicts through the same attribute chain. Taking the live entry instead, measured with the alias on a shim carrying empty dicts and a forward hook registered on the defining module: the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched). Keeping the defining module as the value with the alias as the source, the shape of the two commits below, is what the earlier answer measured as unobservable -- and it is, while the defining module has no hooks, because the guards are one `TYPE_MATCH` per dict; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]`, `<id>` being `RemovableHandle.next_id` at registration (`0` in a process that has registered no earlier hook), which resolves on the shim and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. So the source now follows the value: the alias while `self.output.global_scope[alias]` is the defining module, otherwise the `torch` package's alias walking `.nn.modules.module`, the attributes the value is read through. The premise that drives the `IMPORT_NAME` fix -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. > **FAQ: the `nn_modules_globals_vt` value/source divergence is documented and hand-measured but not pinned by any test; a test that rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts and asserts a compiled `nn.Module` forward still matches eager would convert the comment into a check.** > > Added as `test_import_alias_rebind_keeps_the_global_nn_hooks_visible`, with one addition to the suggested shape that turned out to matter: a forward hook registered on the defining module. Without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only; with it, the hand measurement's conclusion fell over (previous FAQ), and the test now kills both alternatives -- the live value on a numeric mismatch, the unconditional alias source on `KeyError: 0`, which is what the two commits below produce. It asserts the hook ran once under eager and once more under compile, `compiled == eager`, `torch.nn.modules.module is real` and that the alias holds the shim, and in `finally` removes the hook, restores `sys.modules`, and pops both aliases (`__import_torch` is the fallback root) from `fn.__globals__` and both entries from `_import_source_cache`. > **FAQ: `___nn_modules_module_*` is a fourth Dynamo-minted global family that `aot_compile.py` enumerates nowhere: add the prefix to `_MINTED_GLOBAL_PREFIXES`, seed it in `_seed_guard_scope` with a `CleanupHook.disown`, subtract it in `_has_global_guards`, and update the completeness comment.** > > The family is gone instead. The fallback root is now the `torch` package's `__import_torch` alias with `.nn.modules.module` walked as `AttrSource`s, so every name a guard here can be rooted at is an `__import_*` alias, the first family in that tuple: `_seed_guard_scope` seeds it from `import_sources`, `_has_global_guards` subtracts it, `_names_a_missing_global` recognizes the prefix, and `import_source` binds it by plain assignment, so there is no `CleanupHook` to disown. All three consequences the review derived were reproduced first with the id-minted name (nothing seeded, `_has_global_guards` `True` with no user global, `KeyError on G['___nn_modules_module_<id>_c0']` reported as a global to define) and are absent with this root, which `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` pins. The `torch` package rather than `torch.nn.modules`: the chain then mirrors `torch.nn.modules.module`, the expression the value is read through, and a fixture that rebinds `sys.modules["torch"]` itself leaves nothing in Dynamo working. The completeness comment above the tuple (`aot_compile.py:75-93`) is reworded rather than extended: it said a family belongs in the tuple once a serializable guard is rooted at a `GlobalSource` on one of its names, and `_guard_source_globals` (`aot_compile.py:595`) reads "rooted at" as the `originating_source` IS a `GlobalSource`, which no hook-dict guard here satisfies (their sources are the `AttrSource` chain; that helper returns `set()` for this artifact, measured), so by that reading the family would be out of scope while all three sites act on the name. The reading the three sites share is `get_global_source_name` (`source.py:1329`), which walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) fills `global_scope` with; the comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as that helper decides it, and names these guards as the example. No name outside the three families resolves that way. > **FAQ: why does the artifact test register no hook, and why does it not pin that a hook registered after the load fails the loaded guards?** > > Two measured reasons, neither this commit's to change. First, with a hook on the defining module under the rebind, the capture never reaches the guard-scope sites: the hook makes the trace inline `_call_impl`, whose `__globals__` is the defining module's dict, and `_registered_module_for_globals` resolves `sys.modules[__name__]` to the shim, whose dict is a different object, so `get_globals_source_and_value` falls to the `___unnamed_scope` branch and records the defining module's whole `__dict__` under it; the guards pickler then writes that dict by value and pickles its `T = TypeVar("T")` by qualified name through `sys.modules`, which is the shim, and `aot_compile` raises `PackageError: PicklingError: Can't pickle ~T: attribute lookup T on torch.nn.modules.module failed` (the parent raises `KeyError: 0` earlier on the same input). Second, a hook registered after a compile is not guarded at all, in process and without any rebind: the global hook dicts guard as `TYPE_MATCH` only, under both values of `skip_nnmodule_hook_guards` -- `EMPTY_NN_MODULE_HOOKS_DICT` is installed for the instance's own hook attributes (`nn_module.py:1563-1591`), not for the module globals read here -- so a global forward hook registered after a `torch.compile` call is skipped by the compiled function with no recompile (measured on an earlier revision of this tree: `frame_count` 1, hook fired 0, result differs from eager), which `config.py:458-461` documents as the accepted unsafety. A loaded artifact inherits exactly that, so a hook-after-load phase would pin the same `TYPE_MATCH` pass on every tree. > **FAQ: the fix is conditioned on trace-time state, so the mirror ordering stays silently wrong: a capture in a clean process roots at `__import_torch_dot_nn_dot_modules_dot_module`, and a load into a process that has rebound `sys.modules["torch.nn.modules.module"]` has `_seed_guard_scope` seed that alias with `importlib.import_module`, the shim, whose four empty hook dicts pass the `TYPE_MATCH`es, so the loaded function bypasses `_call_impl` and skips a global hook registered on the real module. Handle it, or state that the ordering is out of scope.** > > Out of scope, stated in the message. The handling would be a load-time change in `aot_compile._seed_guard_scope` -- another file and another PR -- because no predicate in `nn_modules_globals_vt` runs where the rebind is: it runs in the capturing process, where the alias and the defining module are one object, and the artifact has no identity guard on the root for a load to check, `MODULE_MATCH`/`ID_MATCH` being unserializable. Measured on an earlier revision of this tree to size what is left. The seeding half is as the finding says: a hookless `fn(m, x)` capture with `keep_global_guards`, deserialized with a fresh `guard_globals=` under `patch.dict(sys.modules, {name: shim})`, seeds `{"__import_torch_dot_nn_dot_modules_dot_module"}` bound to the shim, and its hook-dict guards are built from the shim's dicts (`type=<class 'dict'>` in the loaded tree, `OrderedDict` in the capture's). The consequence half is narrower: a global forward hook registered on the defining module in the loading process is skipped by that load -- and equally by the clean load of the same artifact, whose alias is seeded with the defining module (`loaded fired=[]`, output equal to the hookless eager, in both). Empty dicts guard as `TYPE_MATCH` only, so the rebind changes which module's dicts the guards read, not what they decide; a hook the capture did not see is the accepted unsafety of the previous FAQ, rebind or not. The shape where the root would decide the outcome needs a capture-time hook, and there the four-dict shim does not pass silently: that capture carries `DICT_LENGTH`/`DICT_CONTAINS`/`EQUALS_MATCH` guards on the alias's hook dicts, `_global_forward_hooks_with_kwargs` among them, and its rebound load fails inside `deserialize` with `AttributeError: module 'torch.nn.modules.module' has no attribute '_global_forward_hooks_with_kwargs'` out of `TYPE_MATCH` creation (`guards.py:2425`), where the clean load of the same artifact runs the hook registered in the loading process. A shim carrying every dict `_call_impl` reads was not measured. > **FAQ: `assertEqual(set(scope) - before, {"__import_torch"})` is the only assertion in the artifact test that discriminates against the parent, and it couples to `keep_global_guards` dropping `MODULE_MATCH`; `assertIn("__import_torch", ...)` plus `assertNotIn(nn_alias, ...)` would state the intent without that coupling.** > > Kept exact, and no longer the only discriminating pin: the guard-shape assertion added above it fails first on the parent (measured: the set of guards resolving to `__import_torch` is empty there). The exact set is the claim this message makes -- the load seeds exactly the one name the kept guards resolve through -- and the coupling is to serialization, not to the filter's choice: `MODULE_MATCH` is in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`), so any filter that lets an artifact serialize drops it, and a second seeded alias would mean a second root some serializable guard resolves through, which is what the pin should catch rather than admit. > **FAQ: `import_source(module.__name__)` is called for its side effects even when its `GlobalSource` is discarded: the alias is recorded in `import_sources`, bound in `f_globals`, and `CompilePackage.install` binds it in every loading process. Check `sys.modules` first and skip the call.** > > The read-back of `global_scope[alias]` after the call is the check, and the comment now says so: it is the binding a guard rooted at the alias reads, and `import_source` is what decides it -- the live entry, or `_import_source_cache` for a name since removed from `sys.modules` or blocked with `None`. Reading `sys.modules` here would duplicate that decision in a second place with its own corner cases. The recorded-but-unread alias is the ordinary state of an `import_sources` entry, not a new one: `test_load_seeds_exactly_the_recorded_globals` asserts `len(guarded) < len(import_sources)` on an artifact whose only guarded alias is this same `__import_torch_dot_nn_dot_modules_dot_module`, and the capture in the new artifact test records six aliases for one guarded root. `install` binding it to the shim in a still-rebound loading process binds a name nothing reads. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: 5f8fffb Pull-Request: #197135
[ghstack-poisoned]
… when the alias binds another Split for review budget from `[dynamo] Bind the import alias to the live sys.modules entry` (#197046), two commits below (`[dynamo] Serve a removed or blocked import name from what the alias last bound`, split from the same commit, sits between): that one makes the `__import_*` alias bind the live `sys.modules` entry; this one makes `nn_modules_globals_vt` stop rooting its guards at that alias once it binds a module other than the one whose dicts the VT reads. `nn_modules_globals_vt` reads the four global hook dicts to decide whether a module call may bypass `_call_impl`, and it has to read the dicts `_call_impl` itself reads through its own `__globals__`: the defining module's, `torch.nn.modules.module`, which no `sys.modules` rebind moves (`convert_frame.py:1371-1376` reads the same four dicts through the same attribute chain). Its source was the `__import_torch_dot_nn_dot_modules_dot_module` alias unconditionally. Below this commit that alias binds the live `sys.modules` entry, so a program that rebinds `sys.modules["torch.nn.modules.module"]` -- a test fixture, a `mock.patch.dict(sys.modules, ...)` -- leaves the VT's value and its source naming different objects. That is unobservable while the defining module has no hooks, because empty dicts guard as one `TYPE_MATCH` each; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]` -- `<id>` the handle's `RemovableHandle.next_id` at registration, a process-global counter (`torch/utils/hooks.py:22-27`), so `0` only in a process that has registered no earlier hook -- which resolves on the other module and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. The two commits below both have it; #197256, whose memoized `_import_module` still decided the alias, ran the hook when the name had been resolved before the rebind and skipped it otherwise. The source now follows the value. It stays the alias while `self.output.global_scope[alias]` is the defining module, read back after `import_source` because that binding is what a guard rooted at the alias reads. Otherwise it is the `torch` package's own alias walking `.nn.modules.module` -- the attributes the value itself is read through, which the rebind does not move -- so the guards become `G['__import_torch'].nn.modules.module._global_forward_hooks` and so on. Not a name minted by id, which an earlier revision of this commit installed through `install_global_by_id("___nn_modules_module", module)`: `aot_compile.py` enumerates the global names Dynamo mints by prefix and argues the list complete (`_MINTED_GLOBAL_PREFIXES`, `aot_compile.py:75-93`), and a fourth family fails all three places that read it. Measured with an artifact captured under the rebind through `torch.compile(...).aot_compile` with a `guard_filter_fn` that keeps global guards, then loaded with a fresh `guard_globals=` scope: `_seed_guard_scope` (`aot_compile.py:854-872`) seeds `import_sources` aliases and `___unnamed_scope` names and so seeded nothing; `_has_global_guards` (`aot_compile.py:724`) subtracts only `import_sources` aliases and so was `True` for an artifact with no user global; the load then failed `KeyError on G['___nn_modules_module_<id>_c0']` and `_names_a_missing_global` (`aot_compile.py:106-112`) classed it as a user global, so `_missing_global_hint` told the caller to define a name embedding `id()` of an object in the tracing process. Rooted at `__import_torch`, the same artifact's guarded globals are `{__import_torch, __builtins_dict___N}`, `_has_global_guards` is `False`, the load seeds exactly `__import_torch`, and the call matches eager. No new family, so the list in `aot_compile.py` stands; its criterion is reworded here, because these are the first guards on a minted name whose `originating_source` is a chain rather than the `GlobalSource` itself, and the repo has one helper for each reading of "rooted at". `_guard_source_globals` (`aot_compile.py:595`) keeps a guard whose source IS a `GlobalSource`, and returns nothing for `__import_torch` on this artifact (measured: `set()`); `get_global_source_name` (`source.py:1329`) walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) records `global_scope` through, so the name is in `_recorded_guard_globals` (`aot_compile.py:621`), which is what `_has_global_guards` subtracts from and `_seed_guard_scope` seeds. The comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as `get_global_source_name` decides it, with these guards as the example, so a future family with a chained root and its own prefix is not read as exempt. Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right: taking the live entry as the value, the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched, measured on an earlier revision of this tree); keeping the alias as the source unconditionally is the parent, `KeyError: <id>`. The premise that drives the `IMPORT_NAME` fix below -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. In a process that has not rebound `sys.modules` for torch's own module the source is the alias as before, so the guard shape and the recorded `import_sources` are unchanged (`test_aot_compile.py` pins `{"__import_torch_dot_nn_dot_modules_dot_module"}` as that set in two places; both pass here). Order to review: `nn_modules_globals_vt` in `torch/_dynamo/symbolic_convert.py` (the whole change is the `is not module` branch), then `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` in `test/dynamo/test_package.py` for the in-process case, then `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` in `test/dynamo/test_aot_compile.py` for the artifact, then the reworded completeness comment above `_MINTED_GLOBAL_PREFIXES` in `torch/_dynamo/aot_compile.py` (comment only; no code in that file changes). Behaviour change against the parent, pinned below. In process: with `sys.modules["torch.nn.modules.module"]` rebound to a shim carrying empty hook dicts and a forward hook registered on the defining module, compiling a function that calls an `nn.Module` matches eager and runs the hook, where the parent raised `InternalTorchDynamoError: KeyError: <id>` out of guard construction, `<id>` the hook handle's id (`0` in a fresh process, as above). Through an artifact: one captured under the rebind with a `guard_filter_fn` that keeps global guards roots its hook-dict guards at `__import_torch`, and a load seeds that name; the parent's roots at the module's own alias, which a load seeds through `importlib.import_module`, so in a loading process under the same rebind its guards read the shim's dicts. Out of scope here, and the same on the parent and at this commit: the mirror ordering. A capture in a process where the alias binds the defining module takes the alias branch -- the predicate compares `global_scope[alias]` with the module, and they are one object -- so the artifact roots its hook-dict guards at `__import_torch_dot_nn_dot_modules_dot_module`; loaded into a process that has rebound `sys.modules["torch.nn.modules.module"]`, `_seed_guard_scope` (`aot_compile.py:854-859`) binds that alias with `importlib.import_module`, the shim, and builds the guards from the shim's dicts (measured on an earlier revision of this tree: the seeded set is the alias, `scope[alias] is shim`, and the loaded `TYPE_MATCH` reads `type=<class 'dict'>`, the shim's, where the capture's read `OrderedDict`). No trace-time predicate can see that ordering: the rebind exists only in the loading process, and the artifact carries no identity guard on the root for a load to compare the seeded module against, since `MODULE_MATCH` reduces to `ID_MATCH` and both are in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`). The check would have to run at load, in `_seed_guard_scope` -- another file and another PR. What it decides today is bounded, and measured, in the FAQ below. Test Plan: ``` python test/dynamo/test_package.py -k test_import_alias_rebind_keeps_the_global_nn_hooks_visible python test/dynamo/test_aot_compile.py -k test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package python test/dynamo/test_package.py python test/dynamo/test_aot_compile.py ``` `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` joins the `test_import_alias` tests below it and replaces one of them: #197046's `test_import_alias_nn_hook_guards_read_the_live_entry_the_alias_binds`, which pinned, as the state this commit changes, that a forward hook on the defining module under the rebind raises `InternalTorchDynamoError` out of guard construction, is deleted here, because at this tree the raise it asserts no longer happens (measured: run against this tree's `symbolic_convert.py`, it fails with `InternalTorchDynamoError not raised`) and the new test is that pin's flip; the `InternalTorchDynamoError` import in `test_package.py`, which only it used, goes with it. It compiles a function calling an `nn.Module` once so the process has resolved the name, resets, rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts, registers a forward hook on the defining module and compiles again, pinning that the hook runs under compile as in eager (`fired == [mod, mod]`), that `compiled == eager`, that `torch.nn.modules.module` is still the defining module and that the alias holds the shim. In `finally` it removes the hook, restores `sys.modules`, pops both aliases from `fn.__globals__` -- the module's own and `__import_torch`, the fallback root, which the first, clean compile already binds through `IMPORT_NAME` and the fallback rebinds -- and both `_import_source_cache` entries. The hook is what makes the test load-bearing: without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only. It errors on the parent with `InternalTorchDynamoError: KeyError: 0` (measured by running this file's test against the parent's `symbolic_convert.py`; `0` is the handle id in a process that has registered no earlier hook). Two mutations of this tree fail it, measured on an earlier revision whose `nn_modules_globals_vt` is this one: the live entry as the value on `Tensor-likes are not close!` (6/6 mismatched, the hook skipped); the alias as the source unconditionally on `KeyError: 0`. The test's comment names the mechanism the parent's failure has, not the value-side mutation's: the bypass decision reads the VT's value (`_hooks_dict_len`, `nn_module.py:1375`, through `PythonModuleVariable.tp_getattro_impl`, which does `getattr(self.value, name)` on its `is_torch` branch, `misc.py:2030`), the defining module under either source, so it sees the hook either way; it is the `CLOSURE_MATCH` on the hook that reads through the source, `self.get(guard)` (`guards.py:3138`) evaluating `G[alias]._global_forward_hooks[<id>]` against the live scope as the guard is built, which is where the parent's traceback raises `KeyError: 0` (measured: `build_guards -> CLOSURE_MATCH -> get -> get_value -> eval`). `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` captures `fn(m, x)`, `m` a `ParentWithChildModule` passed as an argument so the artifact has no user global, under `patch.dict(sys.modules, {name: shim})` with `keep_global_guards`, serializes it, and pins on the guards state the shape of the guards `get_global_source_name` resolves to `__import_torch`: exactly the four `G['__import_torch'].nn.modules.module._global_*` names, the walk and not only the root, so a change that kept the root and dropped the walk, or walked from another base, fails it. It then pins that `_names_a_missing_global` returns `False` for every recorded global; at this tree that holds by construction, every root being a prefixed alias, and the comment says it stays as the regression guard against a root minted by id. It loads the artifact with a fresh `guard_globals=` scope, still under the rebind, and pins `_has_global_guards` `False`, the seeded names exactly `{"__import_torch"}`, and the call equal to eager. It fails with the id-minted root of this commit's earlier revision (`install_global_by_id("___nn_modules_module", module)`, re-applied to that tree as a mutant) at the `_names_a_missing_global` pin (`True is not false : ___nn_modules_module_<id>_c0`), and on the parent at the guard-shape pin (measured against the parent's `symbolic_convert.py`: the set of guards resolving to `__import_torch` is empty there, the four missing). It registers no hook: see the FAQ below on why. It pops the alias's and `__import_torch`'s `_import_source_cache` entries through `addCleanup`, so an assertion failing inside the `patch.dict` block cannot leave the shim cached; the `__import_torch` binding the capture writes into this module's dict is stripped by `_hide_leaked_dynamo_globals`' cleanup. Whole files at this tree: `test_package.py` 101 tests, OK (skipped=40, expected failures=1); `test_aot_compile.py` 208 tests, OK (skipped=6). ``` lintrunner --take RUFF,PYFMT,GB_REGISTRY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py test/dynamo/test_package.py test/dynamo/test_aot_compile.py lintrunner --take PYREFLY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py ``` PYREFLY reports nothing in the four files this commit touches; its seven findings are in `torch/_dynamo/guards.py` and `torch/_native/cutedsl/hw_caps.py`, neither of which this commit changes. > **FAQ: `nn_modules_globals_vt` still takes its value from a fixed module object while its source comes from `import_source`, which now binds live `sys.modules`. Fix that too -- the divergence silently decides graph shape.** > > Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right. The value has to be the defining module: the dicts the runtime consults are read by `nn.Module._call_impl` through its own `__globals__`, the defining module's `__dict__`, never through the alias, so that is what the bypass decision must read; `convert_frame.py:1371-1376` reads the same dicts through the same attribute chain. Taking the live entry instead, measured with the alias on a shim carrying empty dicts and a forward hook registered on the defining module: the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched). Keeping the defining module as the value with the alias as the source, the shape of the two commits below, is what the earlier answer measured as unobservable -- and it is, while the defining module has no hooks, because the guards are one `TYPE_MATCH` per dict; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]`, `<id>` being `RemovableHandle.next_id` at registration (`0` in a process that has registered no earlier hook), which resolves on the shim and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. So the source now follows the value: the alias while `self.output.global_scope[alias]` is the defining module, otherwise the `torch` package's alias walking `.nn.modules.module`, the attributes the value is read through. The premise that drives the `IMPORT_NAME` fix -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. > **FAQ: the `nn_modules_globals_vt` value/source divergence is documented and hand-measured but not pinned by any test; a test that rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts and asserts a compiled `nn.Module` forward still matches eager would convert the comment into a check.** > > Added as `test_import_alias_rebind_keeps_the_global_nn_hooks_visible`, with one addition to the suggested shape that turned out to matter: a forward hook registered on the defining module. Without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only; with it, the hand measurement's conclusion fell over (previous FAQ), and the test now kills both alternatives -- the live value on a numeric mismatch, the unconditional alias source on `KeyError: 0`, which is what the two commits below produce. It asserts the hook ran once under eager and once more under compile, `compiled == eager`, `torch.nn.modules.module is real` and that the alias holds the shim, and in `finally` removes the hook, restores `sys.modules`, and pops both aliases (`__import_torch` is the fallback root) from `fn.__globals__` and both entries from `_import_source_cache`. > **FAQ: `___nn_modules_module_*` is a fourth Dynamo-minted global family that `aot_compile.py` enumerates nowhere: add the prefix to `_MINTED_GLOBAL_PREFIXES`, seed it in `_seed_guard_scope` with a `CleanupHook.disown`, subtract it in `_has_global_guards`, and update the completeness comment.** > > The family is gone instead. The fallback root is now the `torch` package's `__import_torch` alias with `.nn.modules.module` walked as `AttrSource`s, so every name a guard here can be rooted at is an `__import_*` alias, the first family in that tuple: `_seed_guard_scope` seeds it from `import_sources`, `_has_global_guards` subtracts it, `_names_a_missing_global` recognizes the prefix, and `import_source` binds it by plain assignment, so there is no `CleanupHook` to disown. All three consequences the review derived were reproduced first with the id-minted name (nothing seeded, `_has_global_guards` `True` with no user global, `KeyError on G['___nn_modules_module_<id>_c0']` reported as a global to define) and are absent with this root, which `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` pins. The `torch` package rather than `torch.nn.modules`: the chain then mirrors `torch.nn.modules.module`, the expression the value is read through, and a fixture that rebinds `sys.modules["torch"]` itself leaves nothing in Dynamo working. The completeness comment above the tuple (`aot_compile.py:75-93`) is reworded rather than extended: it said a family belongs in the tuple once a serializable guard is rooted at a `GlobalSource` on one of its names, and `_guard_source_globals` (`aot_compile.py:595`) reads "rooted at" as the `originating_source` IS a `GlobalSource`, which no hook-dict guard here satisfies (their sources are the `AttrSource` chain; that helper returns `set()` for this artifact, measured), so by that reading the family would be out of scope while all three sites act on the name. The reading the three sites share is `get_global_source_name` (`source.py:1329`), which walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) fills `global_scope` with; the comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as that helper decides it, and names these guards as the example. No name outside the three families resolves that way. > **FAQ: why does the artifact test register no hook, and why does it not pin that a hook registered after the load fails the loaded guards?** > > Two measured reasons, neither this commit's to change. First, with a hook on the defining module under the rebind, the capture never reaches the guard-scope sites: the hook makes the trace inline `_call_impl`, whose `__globals__` is the defining module's dict, and `_registered_module_for_globals` resolves `sys.modules[__name__]` to the shim, whose dict is a different object, so `get_globals_source_and_value` falls to the `___unnamed_scope` branch and records the defining module's whole `__dict__` under it; the guards pickler then writes that dict by value and pickles its `T = TypeVar("T")` by qualified name through `sys.modules`, which is the shim, and `aot_compile` raises `PackageError: PicklingError: Can't pickle ~T: attribute lookup T on torch.nn.modules.module failed` (the parent raises `KeyError: 0` earlier on the same input). Second, a hook registered after a compile is not guarded at all, in process and without any rebind: the global hook dicts guard as `TYPE_MATCH` only, under both values of `skip_nnmodule_hook_guards` -- `EMPTY_NN_MODULE_HOOKS_DICT` is installed for the instance's own hook attributes (`nn_module.py:1563-1591`), not for the module globals read here -- so a global forward hook registered after a `torch.compile` call is skipped by the compiled function with no recompile (measured on an earlier revision of this tree: `frame_count` 1, hook fired 0, result differs from eager), which `config.py:458-461` documents as the accepted unsafety. A loaded artifact inherits exactly that, so a hook-after-load phase would pin the same `TYPE_MATCH` pass on every tree. > **FAQ: the fix is conditioned on trace-time state, so the mirror ordering stays silently wrong: a capture in a clean process roots at `__import_torch_dot_nn_dot_modules_dot_module`, and a load into a process that has rebound `sys.modules["torch.nn.modules.module"]` has `_seed_guard_scope` seed that alias with `importlib.import_module`, the shim, whose four empty hook dicts pass the `TYPE_MATCH`es, so the loaded function bypasses `_call_impl` and skips a global hook registered on the real module. Handle it, or state that the ordering is out of scope.** > > Out of scope, stated in the message. The handling would be a load-time change in `aot_compile._seed_guard_scope` -- another file and another PR -- because no predicate in `nn_modules_globals_vt` runs where the rebind is: it runs in the capturing process, where the alias and the defining module are one object, and the artifact has no identity guard on the root for a load to check, `MODULE_MATCH`/`ID_MATCH` being unserializable. Measured on an earlier revision of this tree to size what is left. The seeding half is as the finding says: a hookless `fn(m, x)` capture with `keep_global_guards`, deserialized with a fresh `guard_globals=` under `patch.dict(sys.modules, {name: shim})`, seeds `{"__import_torch_dot_nn_dot_modules_dot_module"}` bound to the shim, and its hook-dict guards are built from the shim's dicts (`type=<class 'dict'>` in the loaded tree, `OrderedDict` in the capture's). The consequence half is narrower: a global forward hook registered on the defining module in the loading process is skipped by that load -- and equally by the clean load of the same artifact, whose alias is seeded with the defining module (`loaded fired=[]`, output equal to the hookless eager, in both). Empty dicts guard as `TYPE_MATCH` only, so the rebind changes which module's dicts the guards read, not what they decide; a hook the capture did not see is the accepted unsafety of the previous FAQ, rebind or not. The shape where the root would decide the outcome needs a capture-time hook, and there the four-dict shim does not pass silently: that capture carries `DICT_LENGTH`/`DICT_CONTAINS`/`EQUALS_MATCH` guards on the alias's hook dicts, `_global_forward_hooks_with_kwargs` among them, and its rebound load fails inside `deserialize` with `AttributeError: module 'torch.nn.modules.module' has no attribute '_global_forward_hooks_with_kwargs'` out of `TYPE_MATCH` creation (`guards.py:2425`), where the clean load of the same artifact runs the hook registered in the loading process. A shim carrying every dict `_call_impl` reads was not measured. > **FAQ: `assertEqual(set(scope) - before, {"__import_torch"})` is the only assertion in the artifact test that discriminates against the parent, and it couples to `keep_global_guards` dropping `MODULE_MATCH`; `assertIn("__import_torch", ...)` plus `assertNotIn(nn_alias, ...)` would state the intent without that coupling.** > > Kept exact, and no longer the only discriminating pin: the guard-shape assertion added above it fails first on the parent (measured: the set of guards resolving to `__import_torch` is empty there). The exact set is the claim this message makes -- the load seeds exactly the one name the kept guards resolve through -- and the coupling is to serialization, not to the filter's choice: `MODULE_MATCH` is in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`), so any filter that lets an artifact serialize drops it, and a second seeded alias would mean a second root some serializable guard resolves through, which is what the pin should catch rather than admit. > **FAQ: `import_source(module.__name__)` is called for its side effects even when its `GlobalSource` is discarded: the alias is recorded in `import_sources`, bound in `f_globals`, and `CompilePackage.install` binds it in every loading process. Check `sys.modules` first and skip the call.** > > The read-back of `global_scope[alias]` after the call is the check, and the comment now says so: it is the binding a guard rooted at the alias reads, and `import_source` is what decides it -- the live entry, or `_import_source_cache` for a name since removed from `sys.modules` or blocked with `None`. Reading `sys.modules` here would duplicate that decision in a second place with its own corner cases. The recorded-but-unread alias is the ordinary state of an `import_sources` entry, not a new one: `test_load_seeds_exactly_the_recorded_globals` asserts `len(guarded) < len(import_sources)` on an artifact whose only guarded alias is this same `__import_torch_dot_nn_dot_modules_dot_module`, and the capture in the new artifact test records six aliases for one guarded root. `install` binding it to the shim in a still-rebound loading process binds a name nothing reads. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: e666c36 Pull-Request: #197135
[ghstack-poisoned]
… when the alias binds another Split for review budget from `[dynamo] Bind the import alias to the live sys.modules entry` (#197046), two commits below (`[dynamo] Serve a removed or blocked import name from what the alias last bound`, split from the same commit, sits between): that one makes the `__import_*` alias bind the live `sys.modules` entry; this one makes `nn_modules_globals_vt` stop rooting its guards at that alias once it binds a module other than the one whose dicts the VT reads. `nn_modules_globals_vt` reads the four global hook dicts to decide whether a module call may bypass `_call_impl`, and it has to read the dicts `_call_impl` itself reads through its own `__globals__`: the defining module's, `torch.nn.modules.module`, which no `sys.modules` rebind moves (`convert_frame.py:1371-1376` reads the same four dicts through the same attribute chain). Its source was the `__import_torch_dot_nn_dot_modules_dot_module` alias unconditionally. Below this commit that alias binds the live `sys.modules` entry, so a program that rebinds `sys.modules["torch.nn.modules.module"]` -- a test fixture, a `mock.patch.dict(sys.modules, ...)` -- leaves the VT's value and its source naming different objects. That is unobservable while the defining module has no hooks, because empty dicts guard as one `TYPE_MATCH` each; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]` -- `<id>` the handle's `RemovableHandle.next_id` at registration, a process-global counter (`torch/utils/hooks.py:22-27`), so `0` only in a process that has registered no earlier hook -- which resolves on the other module and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. The two commits below both have it; #197256, whose memoized `_import_module` still decided the alias, ran the hook when the name had been resolved before the rebind and skipped it otherwise. The source now follows the value. It stays the alias while `self.output.global_scope[alias]` is the defining module, read back after `import_source` because that binding is what a guard rooted at the alias reads. Otherwise it is the `torch` package's own alias walking `.nn.modules.module` -- the attributes the value itself is read through, which the rebind does not move -- so the guards become `G['__import_torch'].nn.modules.module._global_forward_hooks` and so on. Not a name minted by id, which an earlier revision of this commit installed through `install_global_by_id("___nn_modules_module", module)`: `aot_compile.py` enumerates the global names Dynamo mints by prefix and argues the list complete (`_MINTED_GLOBAL_PREFIXES`, `aot_compile.py:75-93`), and a fourth family fails all three places that read it. Measured with an artifact captured under the rebind through `torch.compile(...).aot_compile` with a `guard_filter_fn` that keeps global guards, then loaded with a fresh `guard_globals=` scope: `_seed_guard_scope` (`aot_compile.py:854-872`) seeds `import_sources` aliases and `___unnamed_scope` names and so seeded nothing; `_has_global_guards` (`aot_compile.py:724`) subtracts only `import_sources` aliases and so was `True` for an artifact with no user global; the load then failed `KeyError on G['___nn_modules_module_<id>_c0']` and `_names_a_missing_global` (`aot_compile.py:106-112`) classed it as a user global, so `_missing_global_hint` told the caller to define a name embedding `id()` of an object in the tracing process. Rooted at `__import_torch`, the same artifact's guarded globals are `{__import_torch, __builtins_dict___N}`, `_has_global_guards` is `False`, the load seeds exactly `__import_torch`, and the call matches eager. No new family, so the list in `aot_compile.py` stands; its criterion is reworded here, because these are the first guards on a minted name whose `originating_source` is a chain rather than the `GlobalSource` itself, and the repo has one helper for each reading of "rooted at". `_guard_source_globals` (`aot_compile.py:595`) keeps a guard whose source IS a `GlobalSource`, and returns nothing for `__import_torch` on this artifact (measured: `set()`); `get_global_source_name` (`source.py:1329`) walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) records `global_scope` through, so the name is in `_recorded_guard_globals` (`aot_compile.py:621`), which is what `_has_global_guards` subtracts from and `_seed_guard_scope` seeds. The comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as `get_global_source_name` decides it, with these guards as the example, so a future family with a chained root and its own prefix is not read as exempt. Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right: taking the live entry as the value, the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched, measured on an earlier revision of this tree); keeping the alias as the source unconditionally is the parent, `KeyError: <id>`. The premise that drives the `IMPORT_NAME` fix below -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. In a process that has not rebound `sys.modules` for torch's own module the source is the alias as before, so the guard shape and the recorded `import_sources` are unchanged (`test_aot_compile.py` pins `{"__import_torch_dot_nn_dot_modules_dot_module"}` as that set in two places; both pass here). Order to review: `nn_modules_globals_vt` in `torch/_dynamo/symbolic_convert.py` (the whole change is the `is not module` branch), then `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` in `test/dynamo/test_package.py` for the in-process case, then `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` in `test/dynamo/test_aot_compile.py` for the artifact, then the reworded completeness comment above `_MINTED_GLOBAL_PREFIXES` in `torch/_dynamo/aot_compile.py` (comment only; no code in that file changes). Behaviour change against the parent, pinned below. In process: with `sys.modules["torch.nn.modules.module"]` rebound to a shim carrying empty hook dicts and a forward hook registered on the defining module, compiling a function that calls an `nn.Module` matches eager and runs the hook, where the parent raised `InternalTorchDynamoError: KeyError: <id>` out of guard construction, `<id>` the hook handle's id (`0` in a fresh process, as above). Through an artifact: one captured under the rebind with a `guard_filter_fn` that keeps global guards roots its hook-dict guards at `__import_torch`, and a load seeds that name; the parent's roots at the module's own alias, which a load seeds through `importlib.import_module`, so in a loading process under the same rebind its guards read the shim's dicts. Out of scope here, and the same on the parent and at this commit: the mirror ordering. A capture in a process where the alias binds the defining module takes the alias branch -- the predicate compares `global_scope[alias]` with the module, and they are one object -- so the artifact roots its hook-dict guards at `__import_torch_dot_nn_dot_modules_dot_module`; loaded into a process that has rebound `sys.modules["torch.nn.modules.module"]`, `_seed_guard_scope` (`aot_compile.py:854-859`) binds that alias with `importlib.import_module`, the shim, and builds the guards from the shim's dicts (measured on an earlier revision of this tree: the seeded set is the alias, `scope[alias] is shim`, and the loaded `TYPE_MATCH` reads `type=<class 'dict'>`, the shim's, where the capture's read `OrderedDict`). No trace-time predicate can see that ordering: the rebind exists only in the loading process, and the artifact carries no identity guard on the root for a load to compare the seeded module against, since `MODULE_MATCH` reduces to `ID_MATCH` and both are in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`). The check would have to run at load, in `_seed_guard_scope` -- another file and another PR. What it decides today is bounded, and measured, in the FAQ below. Test Plan: ``` python test/dynamo/test_package.py -k test_import_alias_rebind_keeps_the_global_nn_hooks_visible python test/dynamo/test_aot_compile.py -k test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package python test/dynamo/test_package.py python test/dynamo/test_aot_compile.py ``` `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` joins the `test_import_alias` tests below it and replaces one of them: #197046's `test_import_alias_nn_hook_guards_read_the_live_entry_the_alias_binds`, which pinned, as the state this commit changes, that a forward hook on the defining module under the rebind raises `InternalTorchDynamoError` out of guard construction, is deleted here, because at this tree the raise it asserts no longer happens (measured: run against this tree's `symbolic_convert.py`, it fails with `InternalTorchDynamoError not raised`) and the new test is that pin's flip; the `InternalTorchDynamoError` import in `test_package.py`, which only it used, goes with it. It compiles a function calling an `nn.Module` once so the process has resolved the name, resets, rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts, registers a forward hook on the defining module and compiles again, pinning that the hook runs under compile as in eager (`fired == [mod, mod]`), that `compiled == eager`, that `torch.nn.modules.module` is still the defining module and that the alias holds the shim. In `finally` it removes the hook, restores `sys.modules`, pops both aliases from `fn.__globals__` -- the module's own and `__import_torch`, the fallback root, which the first, clean compile already binds through `IMPORT_NAME` and the fallback rebinds -- and both `_import_source_cache` entries. The hook is what makes the test load-bearing: without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only. It errors on the parent with `InternalTorchDynamoError: KeyError: 0` (measured by running this file's test against the parent's `symbolic_convert.py`; `0` is the handle id in a process that has registered no earlier hook). Two mutations of this tree fail it, measured on an earlier revision whose `nn_modules_globals_vt` is this one: the live entry as the value on `Tensor-likes are not close!` (6/6 mismatched, the hook skipped); the alias as the source unconditionally on `KeyError: 0`. The test's comment names the mechanism the parent's failure has, not the value-side mutation's: the bypass decision reads the VT's value (`_hooks_dict_len`, `nn_module.py:1375`, through `PythonModuleVariable.tp_getattro_impl`, which does `getattr(self.value, name)` on its `is_torch` branch, `misc.py:2030`), the defining module under either source, so it sees the hook either way; it is the `CLOSURE_MATCH` on the hook that reads through the source, `self.get(guard)` (`guards.py:3138`) evaluating `G[alias]._global_forward_hooks[<id>]` against the live scope as the guard is built, which is where the parent's traceback raises `KeyError: 0` (measured: `build_guards -> CLOSURE_MATCH -> get -> get_value -> eval`). `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` captures `fn(m, x)`, `m` a `ParentWithChildModule` passed as an argument so the artifact has no user global, under `patch.dict(sys.modules, {name: shim})` with `keep_global_guards`, serializes it, and pins on the guards state the shape of the guards `get_global_source_name` resolves to `__import_torch`: exactly the four `G['__import_torch'].nn.modules.module._global_*` names, the walk and not only the root, so a change that kept the root and dropped the walk, or walked from another base, fails it. It then pins that `_names_a_missing_global` returns `False` for every recorded global; at this tree that holds by construction, every root being a prefixed alias, and the comment says it stays as the regression guard against a root minted by id. It loads the artifact with a fresh `guard_globals=` scope, still under the rebind, and pins `_has_global_guards` `False`, the seeded names exactly `{"__import_torch"}`, and the call equal to eager. It fails with the id-minted root of this commit's earlier revision (`install_global_by_id("___nn_modules_module", module)`, re-applied to that tree as a mutant) at the `_names_a_missing_global` pin (`True is not false : ___nn_modules_module_<id>_c0`), and on the parent at the guard-shape pin (measured against the parent's `symbolic_convert.py`: the set of guards resolving to `__import_torch` is empty there, the four missing). It registers no hook: see the FAQ below on why. It pops the alias's and `__import_torch`'s `_import_source_cache` entries through `addCleanup`, so an assertion failing inside the `patch.dict` block cannot leave the shim cached; the `__import_torch` binding the capture writes into this module's dict is stripped by `_hide_leaked_dynamo_globals`' cleanup. Whole files at this tree: `test_package.py` 101 tests, OK (skipped=40, expected failures=1); `test_aot_compile.py` 208 tests, OK (skipped=6). ``` lintrunner --take RUFF,PYFMT,GB_REGISTRY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py test/dynamo/test_package.py test/dynamo/test_aot_compile.py lintrunner --take PYREFLY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py ``` PYREFLY reports nothing in the four files this commit touches; its seven findings are in `torch/_dynamo/guards.py` and `torch/_native/cutedsl/hw_caps.py`, neither of which this commit changes. > **FAQ: `nn_modules_globals_vt` still takes its value from a fixed module object while its source comes from `import_source`, which now binds live `sys.modules`. Fix that too -- the divergence silently decides graph shape.** > > Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right. The value has to be the defining module: the dicts the runtime consults are read by `nn.Module._call_impl` through its own `__globals__`, the defining module's `__dict__`, never through the alias, so that is what the bypass decision must read; `convert_frame.py:1371-1376` reads the same dicts through the same attribute chain. Taking the live entry instead, measured with the alias on a shim carrying empty dicts and a forward hook registered on the defining module: the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched). Keeping the defining module as the value with the alias as the source, the shape of the two commits below, is what the earlier answer measured as unobservable -- and it is, while the defining module has no hooks, because the guards are one `TYPE_MATCH` per dict; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]`, `<id>` being `RemovableHandle.next_id` at registration (`0` in a process that has registered no earlier hook), which resolves on the shim and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. So the source now follows the value: the alias while `self.output.global_scope[alias]` is the defining module, otherwise the `torch` package's alias walking `.nn.modules.module`, the attributes the value is read through. The premise that drives the `IMPORT_NAME` fix -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. > **FAQ: the `nn_modules_globals_vt` value/source divergence is documented and hand-measured but not pinned by any test; a test that rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts and asserts a compiled `nn.Module` forward still matches eager would convert the comment into a check.** > > Added as `test_import_alias_rebind_keeps_the_global_nn_hooks_visible`, with one addition to the suggested shape that turned out to matter: a forward hook registered on the defining module. Without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only; with it, the hand measurement's conclusion fell over (previous FAQ), and the test now kills both alternatives -- the live value on a numeric mismatch, the unconditional alias source on `KeyError: 0`, which is what the two commits below produce. It asserts the hook ran once under eager and once more under compile, `compiled == eager`, `torch.nn.modules.module is real` and that the alias holds the shim, and in `finally` removes the hook, restores `sys.modules`, and pops both aliases (`__import_torch` is the fallback root) from `fn.__globals__` and both entries from `_import_source_cache`. > **FAQ: `___nn_modules_module_*` is a fourth Dynamo-minted global family that `aot_compile.py` enumerates nowhere: add the prefix to `_MINTED_GLOBAL_PREFIXES`, seed it in `_seed_guard_scope` with a `CleanupHook.disown`, subtract it in `_has_global_guards`, and update the completeness comment.** > > The family is gone instead. The fallback root is now the `torch` package's `__import_torch` alias with `.nn.modules.module` walked as `AttrSource`s, so every name a guard here can be rooted at is an `__import_*` alias, the first family in that tuple: `_seed_guard_scope` seeds it from `import_sources`, `_has_global_guards` subtracts it, `_names_a_missing_global` recognizes the prefix, and `import_source` binds it by plain assignment, so there is no `CleanupHook` to disown. All three consequences the review derived were reproduced first with the id-minted name (nothing seeded, `_has_global_guards` `True` with no user global, `KeyError on G['___nn_modules_module_<id>_c0']` reported as a global to define) and are absent with this root, which `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` pins. The `torch` package rather than `torch.nn.modules`: the chain then mirrors `torch.nn.modules.module`, the expression the value is read through, and a fixture that rebinds `sys.modules["torch"]` itself leaves nothing in Dynamo working. The completeness comment above the tuple (`aot_compile.py:75-93`) is reworded rather than extended: it said a family belongs in the tuple once a serializable guard is rooted at a `GlobalSource` on one of its names, and `_guard_source_globals` (`aot_compile.py:595`) reads "rooted at" as the `originating_source` IS a `GlobalSource`, which no hook-dict guard here satisfies (their sources are the `AttrSource` chain; that helper returns `set()` for this artifact, measured), so by that reading the family would be out of scope while all three sites act on the name. The reading the three sites share is `get_global_source_name` (`source.py:1329`), which walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) fills `global_scope` with; the comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as that helper decides it, and names these guards as the example. No name outside the three families resolves that way. > **FAQ: why does the artifact test register no hook, and why does it not pin that a hook registered after the load fails the loaded guards?** > > Two measured reasons, neither this commit's to change. First, with a hook on the defining module under the rebind, the capture never reaches the guard-scope sites: the hook makes the trace inline `_call_impl`, whose `__globals__` is the defining module's dict, and `_registered_module_for_globals` resolves `sys.modules[__name__]` to the shim, whose dict is a different object, so `get_globals_source_and_value` falls to the `___unnamed_scope` branch and records the defining module's whole `__dict__` under it; the guards pickler then writes that dict by value and pickles its `T = TypeVar("T")` by qualified name through `sys.modules`, which is the shim, and `aot_compile` raises `PackageError: PicklingError: Can't pickle ~T: attribute lookup T on torch.nn.modules.module failed` (the parent raises `KeyError: 0` earlier on the same input). Second, a hook registered after a compile is not guarded at all, in process and without any rebind: the global hook dicts guard as `TYPE_MATCH` only, under both values of `skip_nnmodule_hook_guards` -- `EMPTY_NN_MODULE_HOOKS_DICT` is installed for the instance's own hook attributes (`nn_module.py:1563-1591`), not for the module globals read here -- so a global forward hook registered after a `torch.compile` call is skipped by the compiled function with no recompile (measured on an earlier revision of this tree: `frame_count` 1, hook fired 0, result differs from eager), which `config.py:458-461` documents as the accepted unsafety. A loaded artifact inherits exactly that, so a hook-after-load phase would pin the same `TYPE_MATCH` pass on every tree. > **FAQ: the fix is conditioned on trace-time state, so the mirror ordering stays silently wrong: a capture in a clean process roots at `__import_torch_dot_nn_dot_modules_dot_module`, and a load into a process that has rebound `sys.modules["torch.nn.modules.module"]` has `_seed_guard_scope` seed that alias with `importlib.import_module`, the shim, whose four empty hook dicts pass the `TYPE_MATCH`es, so the loaded function bypasses `_call_impl` and skips a global hook registered on the real module. Handle it, or state that the ordering is out of scope.** > > Out of scope, stated in the message. The handling would be a load-time change in `aot_compile._seed_guard_scope` -- another file and another PR -- because no predicate in `nn_modules_globals_vt` runs where the rebind is: it runs in the capturing process, where the alias and the defining module are one object, and the artifact has no identity guard on the root for a load to check, `MODULE_MATCH`/`ID_MATCH` being unserializable. Measured on an earlier revision of this tree to size what is left. The seeding half is as the finding says: a hookless `fn(m, x)` capture with `keep_global_guards`, deserialized with a fresh `guard_globals=` under `patch.dict(sys.modules, {name: shim})`, seeds `{"__import_torch_dot_nn_dot_modules_dot_module"}` bound to the shim, and its hook-dict guards are built from the shim's dicts (`type=<class 'dict'>` in the loaded tree, `OrderedDict` in the capture's). The consequence half is narrower: a global forward hook registered on the defining module in the loading process is skipped by that load -- and equally by the clean load of the same artifact, whose alias is seeded with the defining module (`loaded fired=[]`, output equal to the hookless eager, in both). Empty dicts guard as `TYPE_MATCH` only, so the rebind changes which module's dicts the guards read, not what they decide; a hook the capture did not see is the accepted unsafety of the previous FAQ, rebind or not. The shape where the root would decide the outcome needs a capture-time hook, and there the four-dict shim does not pass silently: that capture carries `DICT_LENGTH`/`DICT_CONTAINS`/`EQUALS_MATCH` guards on the alias's hook dicts, `_global_forward_hooks_with_kwargs` among them, and its rebound load fails inside `deserialize` with `AttributeError: module 'torch.nn.modules.module' has no attribute '_global_forward_hooks_with_kwargs'` out of `TYPE_MATCH` creation (`guards.py:2425`), where the clean load of the same artifact runs the hook registered in the loading process. A shim carrying every dict `_call_impl` reads was not measured. > **FAQ: `assertEqual(set(scope) - before, {"__import_torch"})` is the only assertion in the artifact test that discriminates against the parent, and it couples to `keep_global_guards` dropping `MODULE_MATCH`; `assertIn("__import_torch", ...)` plus `assertNotIn(nn_alias, ...)` would state the intent without that coupling.** > > Kept exact, and no longer the only discriminating pin: the guard-shape assertion added above it fails first on the parent (measured: the set of guards resolving to `__import_torch` is empty there). The exact set is the claim this message makes -- the load seeds exactly the one name the kept guards resolve through -- and the coupling is to serialization, not to the filter's choice: `MODULE_MATCH` is in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`), so any filter that lets an artifact serialize drops it, and a second seeded alias would mean a second root some serializable guard resolves through, which is what the pin should catch rather than admit. > **FAQ: `import_source(module.__name__)` is called for its side effects even when its `GlobalSource` is discarded: the alias is recorded in `import_sources`, bound in `f_globals`, and `CompilePackage.install` binds it in every loading process. Check `sys.modules` first and skip the call.** > > The read-back of `global_scope[alias]` after the call is the check, and the comment now says so: it is the binding a guard rooted at the alias reads, and `import_source` is what decides it -- the live entry, or `_import_source_cache` for a name since removed from `sys.modules` or blocked with `None`. Reading `sys.modules` here would duplicate that decision in a second place with its own corner cases. The recorded-but-unread alias is the ordinary state of an `import_sources` entry, not a new one: `test_load_seeds_exactly_the_recorded_globals` asserts `len(guarded) < len(import_sources)` on an artifact whose only guarded alias is this same `__import_torch_dot_nn_dot_modules_dot_module`, and the capture in the new artifact test records six aliases for one guarded root. `install` binding it to the shim in a still-rebound loading process binds a name nothing reads. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: e8a2126 Pull-Request: #197135
[ghstack-poisoned]
… when the alias binds another Split for review budget from `[dynamo] Bind the import alias to the live sys.modules entry` (#197046), two commits below (`[dynamo] Serve a removed or blocked import name from what the alias last bound`, split from the same commit, sits between): that one makes the `__import_*` alias bind the live `sys.modules` entry; this one makes `nn_modules_globals_vt` stop rooting its guards at that alias once it binds a module other than the one whose dicts the VT reads. `nn_modules_globals_vt` reads the four global hook dicts to decide whether a module call may bypass `_call_impl`, and it has to read the dicts `_call_impl` itself reads through its own `__globals__`: the defining module's, `torch.nn.modules.module`, which no `sys.modules` rebind moves (`convert_frame.py:1371-1376` reads the same four dicts through the same attribute chain). Its source was the `__import_torch_dot_nn_dot_modules_dot_module` alias unconditionally. Below this commit that alias binds the live `sys.modules` entry, so a program that rebinds `sys.modules["torch.nn.modules.module"]` -- a test fixture, a `mock.patch.dict(sys.modules, ...)` -- leaves the VT's value and its source naming different objects. That is unobservable while the defining module has no hooks, because empty dicts guard as one `TYPE_MATCH` each; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]` -- `<id>` the handle's `RemovableHandle.next_id` at registration, a process-global counter (`torch/utils/hooks.py:22-27`), so `0` only in a process that has registered no earlier hook -- which resolves on the other module and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. The two commits below both have it; #197256, whose memoized `_import_module` still decided the alias, ran the hook when the name had been resolved before the rebind and skipped it otherwise. The source now follows the value. It stays the alias while `self.output.global_scope[alias]` is the defining module, read back after `import_source` because that binding is what a guard rooted at the alias reads. Otherwise it is the `torch` package's own alias walking `.nn.modules.module` -- the attributes the value itself is read through, which the rebind does not move -- so the guards become `G['__import_torch'].nn.modules.module._global_forward_hooks` and so on. Not a name minted by id, which an earlier revision of this commit installed through `install_global_by_id("___nn_modules_module", module)`: `aot_compile.py` enumerates the global names Dynamo mints by prefix and argues the list complete (`_MINTED_GLOBAL_PREFIXES`, `aot_compile.py:75-93`), and a fourth family fails all three places that read it. Measured with an artifact captured under the rebind through `torch.compile(...).aot_compile` with a `guard_filter_fn` that keeps global guards, then loaded with a fresh `guard_globals=` scope: `_seed_guard_scope` (`aot_compile.py:854-872`) seeds `import_sources` aliases and `___unnamed_scope` names and so seeded nothing; `_has_global_guards` (`aot_compile.py:724`) subtracts only `import_sources` aliases and so was `True` for an artifact with no user global; the load then failed `KeyError on G['___nn_modules_module_<id>_c0']` and `_names_a_missing_global` (`aot_compile.py:106-112`) classed it as a user global, so `_missing_global_hint` told the caller to define a name embedding `id()` of an object in the tracing process. Rooted at `__import_torch`, the same artifact's guarded globals are `{__import_torch, __builtins_dict___N}`, `_has_global_guards` is `False`, the load seeds exactly `__import_torch`, and the call matches eager. No new family, so the list in `aot_compile.py` stands; its criterion is reworded here, because these are the first guards on a minted name whose `originating_source` is a chain rather than the `GlobalSource` itself, and the repo has one helper for each reading of "rooted at". `_guard_source_globals` (`aot_compile.py:595`) keeps a guard whose source IS a `GlobalSource`, and returns nothing for `__import_torch` on this artifact (measured: `set()`); `get_global_source_name` (`source.py:1329`) walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) records `global_scope` through, so the name is in `_recorded_guard_globals` (`aot_compile.py:621`), which is what `_has_global_guards` subtracts from and `_seed_guard_scope` seeds. The comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as `get_global_source_name` decides it, with these guards as the example, so a future family with a chained root and its own prefix is not read as exempt. Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right: taking the live entry as the value, the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched, measured on an earlier revision of this tree); keeping the alias as the source unconditionally is the parent, `KeyError: <id>`. The premise that drives the `IMPORT_NAME` fix below -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. In a process that has not rebound `sys.modules` for torch's own module the source is the alias as before, so the guard shape and the recorded `import_sources` are unchanged (`test_aot_compile.py` pins `{"__import_torch_dot_nn_dot_modules_dot_module"}` as that set in two places; both pass here). Order to review: `nn_modules_globals_vt` in `torch/_dynamo/symbolic_convert.py` (the whole change is the `is not module` branch), then `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` in `test/dynamo/test_package.py` for the in-process case, then `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` in `test/dynamo/test_aot_compile.py` for the artifact, then the reworded completeness comment above `_MINTED_GLOBAL_PREFIXES` in `torch/_dynamo/aot_compile.py` (comment only; no code in that file changes). Behaviour change against the parent, pinned below. In process: with `sys.modules["torch.nn.modules.module"]` rebound to a shim carrying empty hook dicts and a forward hook registered on the defining module, compiling a function that calls an `nn.Module` matches eager and runs the hook, where the parent raised `InternalTorchDynamoError: KeyError: <id>` out of guard construction, `<id>` the hook handle's id (`0` in a fresh process, as above). Through an artifact: one captured under the rebind with a `guard_filter_fn` that keeps global guards roots its hook-dict guards at `__import_torch`, and a load seeds that name; the parent's roots at the module's own alias, which a load seeds through `importlib.import_module`, so in a loading process under the same rebind its guards read the shim's dicts. Out of scope here, and the same on the parent and at this commit: the mirror ordering. A capture in a process where the alias binds the defining module takes the alias branch -- the predicate compares `global_scope[alias]` with the module, and they are one object -- so the artifact roots its hook-dict guards at `__import_torch_dot_nn_dot_modules_dot_module`; loaded into a process that has rebound `sys.modules["torch.nn.modules.module"]`, `_seed_guard_scope` (`aot_compile.py:854-859`) binds that alias with `importlib.import_module`, the shim, and builds the guards from the shim's dicts (measured on an earlier revision of this tree: the seeded set is the alias, `scope[alias] is shim`, and the loaded `TYPE_MATCH` reads `type=<class 'dict'>`, the shim's, where the capture's read `OrderedDict`). No trace-time predicate can see that ordering: the rebind exists only in the loading process, and the artifact carries no identity guard on the root for a load to compare the seeded module against, since `MODULE_MATCH` reduces to `ID_MATCH` and both are in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`). The check would have to run at load, in `_seed_guard_scope` -- another file and another PR. What it decides today is bounded, and measured, in the FAQ below. Test Plan: ``` python test/dynamo/test_package.py -k test_import_alias_rebind_keeps_the_global_nn_hooks_visible python test/dynamo/test_aot_compile.py -k test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package python test/dynamo/test_package.py python test/dynamo/test_aot_compile.py ``` `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` joins the `test_import_alias` tests below it and replaces one of them: #197046's `test_import_alias_nn_hook_guards_read_the_live_entry_the_alias_binds`, which pinned, as the state this commit changes, that a forward hook on the defining module under the rebind raises `InternalTorchDynamoError` out of guard construction, is deleted here, because at this tree the raise it asserts no longer happens (measured: run against this tree's `symbolic_convert.py`, it fails with `InternalTorchDynamoError not raised`) and the new test is that pin's flip; the `InternalTorchDynamoError` import in `test_package.py`, which only it used, goes with it. It compiles a function calling an `nn.Module` once so the process has resolved the name, resets, rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts, registers a forward hook on the defining module and compiles again, pinning that the hook runs under compile as in eager (`fired == [mod, mod]`), that `compiled == eager`, that `torch.nn.modules.module` is still the defining module and that the alias holds the shim. In `finally` it removes the hook, restores `sys.modules`, pops both aliases from `fn.__globals__` -- the module's own and `__import_torch`, the fallback root, which the first, clean compile already binds through `IMPORT_NAME` and the fallback rebinds -- and both `_import_source_cache` entries. The hook is what makes the test load-bearing: without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only. It errors on the parent with `InternalTorchDynamoError: KeyError: 0` (measured by running this file's test against the parent's `symbolic_convert.py`; `0` is the handle id in a process that has registered no earlier hook). Two mutations of this tree fail it, measured on an earlier revision whose `nn_modules_globals_vt` is this one: the live entry as the value on `Tensor-likes are not close!` (6/6 mismatched, the hook skipped); the alias as the source unconditionally on `KeyError: 0`. The test's comment names the mechanism the parent's failure has, not the value-side mutation's: the bypass decision reads the VT's value (`_hooks_dict_len`, `nn_module.py:1375`, through `PythonModuleVariable.tp_getattro_impl`, which does `getattr(self.value, name)` on its `is_torch` branch, `misc.py:2030`), the defining module under either source, so it sees the hook either way; it is the `CLOSURE_MATCH` on the hook that reads through the source, `self.get(guard)` (`guards.py:3138`) evaluating `G[alias]._global_forward_hooks[<id>]` against the live scope as the guard is built, which is where the parent's traceback raises `KeyError: 0` (measured: `build_guards -> CLOSURE_MATCH -> get -> get_value -> eval`). `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` captures `fn(m, x)`, `m` a `ParentWithChildModule` passed as an argument so the artifact has no user global, under `patch.dict(sys.modules, {name: shim})` with `keep_global_guards`, serializes it, and pins on the guards state the shape of the guards `get_global_source_name` resolves to `__import_torch`: exactly the four `G['__import_torch'].nn.modules.module._global_*` names, the walk and not only the root, so a change that kept the root and dropped the walk, or walked from another base, fails it. It then pins that `_names_a_missing_global` returns `False` for every recorded global; at this tree that holds by construction, every root being a prefixed alias, and the comment says it stays as the regression guard against a root minted by id. It loads the artifact with a fresh `guard_globals=` scope, still under the rebind, and pins `_has_global_guards` `False`, the seeded names exactly `{"__import_torch"}`, and the call equal to eager. It fails with the id-minted root of this commit's earlier revision (`install_global_by_id("___nn_modules_module", module)`, re-applied to that tree as a mutant) at the `_names_a_missing_global` pin (`True is not false : ___nn_modules_module_<id>_c0`), and on the parent at the guard-shape pin (measured against the parent's `symbolic_convert.py`: the set of guards resolving to `__import_torch` is empty there, the four missing). It registers no hook: see the FAQ below on why. It pops the alias's and `__import_torch`'s `_import_source_cache` entries through `addCleanup`, so an assertion failing inside the `patch.dict` block cannot leave the shim cached; the `__import_torch` binding the capture writes into this module's dict is stripped by `_hide_leaked_dynamo_globals`' cleanup. Whole files at this tree: `test_package.py` 101 tests, OK (skipped=40, expected failures=1); `test_aot_compile.py` 208 tests, OK (skipped=6). ``` lintrunner --take RUFF,PYFMT,GB_REGISTRY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py test/dynamo/test_package.py test/dynamo/test_aot_compile.py lintrunner --take PYREFLY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py ``` PYREFLY reports nothing in the four files this commit touches; its seven findings are in `torch/_dynamo/guards.py` and `torch/_native/cutedsl/hw_caps.py`, neither of which this commit changes. > **FAQ: `nn_modules_globals_vt` still takes its value from a fixed module object while its source comes from `import_source`, which now binds live `sys.modules`. Fix that too -- the divergence silently decides graph shape.** > > Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right. The value has to be the defining module: the dicts the runtime consults are read by `nn.Module._call_impl` through its own `__globals__`, the defining module's `__dict__`, never through the alias, so that is what the bypass decision must read; `convert_frame.py:1371-1376` reads the same dicts through the same attribute chain. Taking the live entry instead, measured with the alias on a shim carrying empty dicts and a forward hook registered on the defining module: the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched). Keeping the defining module as the value with the alias as the source, the shape of the two commits below, is what the earlier answer measured as unobservable -- and it is, while the defining module has no hooks, because the guards are one `TYPE_MATCH` per dict; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]`, `<id>` being `RemovableHandle.next_id` at registration (`0` in a process that has registered no earlier hook), which resolves on the shim and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. So the source now follows the value: the alias while `self.output.global_scope[alias]` is the defining module, otherwise the `torch` package's alias walking `.nn.modules.module`, the attributes the value is read through. The premise that drives the `IMPORT_NAME` fix -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. > **FAQ: the `nn_modules_globals_vt` value/source divergence is documented and hand-measured but not pinned by any test; a test that rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts and asserts a compiled `nn.Module` forward still matches eager would convert the comment into a check.** > > Added as `test_import_alias_rebind_keeps_the_global_nn_hooks_visible`, with one addition to the suggested shape that turned out to matter: a forward hook registered on the defining module. Without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only; with it, the hand measurement's conclusion fell over (previous FAQ), and the test now kills both alternatives -- the live value on a numeric mismatch, the unconditional alias source on `KeyError: 0`, which is what the two commits below produce. It asserts the hook ran once under eager and once more under compile, `compiled == eager`, `torch.nn.modules.module is real` and that the alias holds the shim, and in `finally` removes the hook, restores `sys.modules`, and pops both aliases (`__import_torch` is the fallback root) from `fn.__globals__` and both entries from `_import_source_cache`. > **FAQ: `___nn_modules_module_*` is a fourth Dynamo-minted global family that `aot_compile.py` enumerates nowhere: add the prefix to `_MINTED_GLOBAL_PREFIXES`, seed it in `_seed_guard_scope` with a `CleanupHook.disown`, subtract it in `_has_global_guards`, and update the completeness comment.** > > The family is gone instead. The fallback root is now the `torch` package's `__import_torch` alias with `.nn.modules.module` walked as `AttrSource`s, so every name a guard here can be rooted at is an `__import_*` alias, the first family in that tuple: `_seed_guard_scope` seeds it from `import_sources`, `_has_global_guards` subtracts it, `_names_a_missing_global` recognizes the prefix, and `import_source` binds it by plain assignment, so there is no `CleanupHook` to disown. All three consequences the review derived were reproduced first with the id-minted name (nothing seeded, `_has_global_guards` `True` with no user global, `KeyError on G['___nn_modules_module_<id>_c0']` reported as a global to define) and are absent with this root, which `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` pins. The `torch` package rather than `torch.nn.modules`: the chain then mirrors `torch.nn.modules.module`, the expression the value is read through, and a fixture that rebinds `sys.modules["torch"]` itself leaves nothing in Dynamo working. The completeness comment above the tuple (`aot_compile.py:75-93`) is reworded rather than extended: it said a family belongs in the tuple once a serializable guard is rooted at a `GlobalSource` on one of its names, and `_guard_source_globals` (`aot_compile.py:595`) reads "rooted at" as the `originating_source` IS a `GlobalSource`, which no hook-dict guard here satisfies (their sources are the `AttrSource` chain; that helper returns `set()` for this artifact, measured), so by that reading the family would be out of scope while all three sites act on the name. The reading the three sites share is `get_global_source_name` (`source.py:1329`), which walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) fills `global_scope` with; the comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as that helper decides it, and names these guards as the example. No name outside the three families resolves that way. > **FAQ: why does the artifact test register no hook, and why does it not pin that a hook registered after the load fails the loaded guards?** > > Two measured reasons, neither this commit's to change. First, with a hook on the defining module under the rebind, the capture never reaches the guard-scope sites: the hook makes the trace inline `_call_impl`, whose `__globals__` is the defining module's dict, and `_registered_module_for_globals` resolves `sys.modules[__name__]` to the shim, whose dict is a different object, so `get_globals_source_and_value` falls to the `___unnamed_scope` branch and records the defining module's whole `__dict__` under it; the guards pickler then writes that dict by value and pickles its `T = TypeVar("T")` by qualified name through `sys.modules`, which is the shim, and `aot_compile` raises `PackageError: PicklingError: Can't pickle ~T: attribute lookup T on torch.nn.modules.module failed` (the parent raises `KeyError: 0` earlier on the same input). Second, a hook registered after a compile is not guarded at all, in process and without any rebind: the global hook dicts guard as `TYPE_MATCH` only, under both values of `skip_nnmodule_hook_guards` -- `EMPTY_NN_MODULE_HOOKS_DICT` is installed for the instance's own hook attributes (`nn_module.py:1563-1591`), not for the module globals read here -- so a global forward hook registered after a `torch.compile` call is skipped by the compiled function with no recompile (measured on an earlier revision of this tree: `frame_count` 1, hook fired 0, result differs from eager), which `config.py:458-461` documents as the accepted unsafety. A loaded artifact inherits exactly that, so a hook-after-load phase would pin the same `TYPE_MATCH` pass on every tree. > **FAQ: the fix is conditioned on trace-time state, so the mirror ordering stays silently wrong: a capture in a clean process roots at `__import_torch_dot_nn_dot_modules_dot_module`, and a load into a process that has rebound `sys.modules["torch.nn.modules.module"]` has `_seed_guard_scope` seed that alias with `importlib.import_module`, the shim, whose four empty hook dicts pass the `TYPE_MATCH`es, so the loaded function bypasses `_call_impl` and skips a global hook registered on the real module. Handle it, or state that the ordering is out of scope.** > > Out of scope, stated in the message. The handling would be a load-time change in `aot_compile._seed_guard_scope` -- another file and another PR -- because no predicate in `nn_modules_globals_vt` runs where the rebind is: it runs in the capturing process, where the alias and the defining module are one object, and the artifact has no identity guard on the root for a load to check, `MODULE_MATCH`/`ID_MATCH` being unserializable. Measured on an earlier revision of this tree to size what is left. The seeding half is as the finding says: a hookless `fn(m, x)` capture with `keep_global_guards`, deserialized with a fresh `guard_globals=` under `patch.dict(sys.modules, {name: shim})`, seeds `{"__import_torch_dot_nn_dot_modules_dot_module"}` bound to the shim, and its hook-dict guards are built from the shim's dicts (`type=<class 'dict'>` in the loaded tree, `OrderedDict` in the capture's). The consequence half is narrower: a global forward hook registered on the defining module in the loading process is skipped by that load -- and equally by the clean load of the same artifact, whose alias is seeded with the defining module (`loaded fired=[]`, output equal to the hookless eager, in both). Empty dicts guard as `TYPE_MATCH` only, so the rebind changes which module's dicts the guards read, not what they decide; a hook the capture did not see is the accepted unsafety of the previous FAQ, rebind or not. The shape where the root would decide the outcome needs a capture-time hook, and there the four-dict shim does not pass silently: that capture carries `DICT_LENGTH`/`DICT_CONTAINS`/`EQUALS_MATCH` guards on the alias's hook dicts, `_global_forward_hooks_with_kwargs` among them, and its rebound load fails inside `deserialize` with `AttributeError: module 'torch.nn.modules.module' has no attribute '_global_forward_hooks_with_kwargs'` out of `TYPE_MATCH` creation (`guards.py:2425`), where the clean load of the same artifact runs the hook registered in the loading process. A shim carrying every dict `_call_impl` reads was not measured. > **FAQ: `assertEqual(set(scope) - before, {"__import_torch"})` is the only assertion in the artifact test that discriminates against the parent, and it couples to `keep_global_guards` dropping `MODULE_MATCH`; `assertIn("__import_torch", ...)` plus `assertNotIn(nn_alias, ...)` would state the intent without that coupling.** > > Kept exact, and no longer the only discriminating pin: the guard-shape assertion added above it fails first on the parent (measured: the set of guards resolving to `__import_torch` is empty there). The exact set is the claim this message makes -- the load seeds exactly the one name the kept guards resolve through -- and the coupling is to serialization, not to the filter's choice: `MODULE_MATCH` is in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`), so any filter that lets an artifact serialize drops it, and a second seeded alias would mean a second root some serializable guard resolves through, which is what the pin should catch rather than admit. > **FAQ: `import_source(module.__name__)` is called for its side effects even when its `GlobalSource` is discarded: the alias is recorded in `import_sources`, bound in `f_globals`, and `CompilePackage.install` binds it in every loading process. Check `sys.modules` first and skip the call.** > > The read-back of `global_scope[alias]` after the call is the check, and the comment now says so: it is the binding a guard rooted at the alias reads, and `import_source` is what decides it -- the live entry, or `_import_source_cache` for a name since removed from `sys.modules` or blocked with `None`. Reading `sys.modules` here would duplicate that decision in a second place with its own corner cases. The recorded-but-unread alias is the ordinary state of an `import_sources` entry, not a new one: `test_load_seeds_exactly_the_recorded_globals` asserts `len(guarded) < len(import_sources)` on an artifact whose only guarded alias is this same `__import_torch_dot_nn_dot_modules_dot_module`, and the capture in the new artifact test records six aliases for one guarded root. `install` binding it to the shim in a still-rebound loading process binds a name nothing reads. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: 1caa170 Pull-Request: #197135
[ghstack-poisoned]
… when the alias binds another Split for review budget from `[dynamo] Bind the import alias to the live sys.modules entry` (#197046), two commits below (`[dynamo] Serve a removed or blocked import name from what the alias last bound`, split from the same commit, sits between): that one makes the `__import_*` alias bind the live `sys.modules` entry; this one makes `nn_modules_globals_vt` stop rooting its guards at that alias once it binds a module other than the one whose dicts the VT reads. `nn_modules_globals_vt` reads the four global hook dicts to decide whether a module call may bypass `_call_impl`, and it has to read the dicts `_call_impl` itself reads through its own `__globals__`: the defining module's, `torch.nn.modules.module`, which no `sys.modules` rebind moves (`convert_frame.py:1371-1376` reads the same four dicts through the same attribute chain). Its source was the `__import_torch_dot_nn_dot_modules_dot_module` alias unconditionally. Below this commit that alias binds the live `sys.modules` entry, so a program that rebinds `sys.modules["torch.nn.modules.module"]` -- a test fixture, a `mock.patch.dict(sys.modules, ...)` -- leaves the VT's value and its source naming different objects. That is unobservable while the defining module has no hooks, because empty dicts guard as one `TYPE_MATCH` each; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]` -- `<id>` the handle's `RemovableHandle.next_id` at registration, a process-global counter (`torch/utils/hooks.py:22-27`), so `0` only in a process that has registered no earlier hook -- which resolves on the other module and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. The two commits below both have it; #197256, whose memoized `_import_module` still decided the alias, ran the hook when the name had been resolved before the rebind and skipped it otherwise. The source now follows the value. It stays the alias while `self.output.global_scope[alias]` is the defining module, read back after `import_source` because that binding is what a guard rooted at the alias reads. Otherwise it is the `torch` package's own alias walking `.nn.modules.module` -- the attributes the value itself is read through, which the rebind does not move -- so the guards become `G['__import_torch'].nn.modules.module._global_forward_hooks` and so on. Not a name minted by id, which an earlier revision of this commit installed through `install_global_by_id("___nn_modules_module", module)`: `aot_compile.py` enumerates the global names Dynamo mints by prefix and argues the list complete (`_MINTED_GLOBAL_PREFIXES`, `aot_compile.py:75-93`), and a fourth family fails all three places that read it. Measured with an artifact captured under the rebind through `torch.compile(...).aot_compile` with a `guard_filter_fn` that keeps global guards, then loaded with a fresh `guard_globals=` scope: `_seed_guard_scope` (`aot_compile.py:854-872`) seeds `import_sources` aliases and `___unnamed_scope` names and so seeded nothing; `_has_global_guards` (`aot_compile.py:724`) subtracts only `import_sources` aliases and so was `True` for an artifact with no user global; the load then failed `KeyError on G['___nn_modules_module_<id>_c0']` and `_names_a_missing_global` (`aot_compile.py:106-112`) classed it as a user global, so `_missing_global_hint` told the caller to define a name embedding `id()` of an object in the tracing process. Rooted at `__import_torch`, the same artifact's guarded globals are `{__import_torch, __builtins_dict___N}`, `_has_global_guards` is `False`, the load seeds exactly `__import_torch`, and the call matches eager. No new family, so the list in `aot_compile.py` stands; its criterion is reworded here, because these are the first guards on a minted name whose `originating_source` is a chain rather than the `GlobalSource` itself, and the repo has one helper for each reading of "rooted at". `_guard_source_globals` (`aot_compile.py:595`) keeps a guard whose source IS a `GlobalSource`, and returns nothing for `__import_torch` on this artifact (measured: `set()`); `get_global_source_name` (`source.py:1329`) walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) records `global_scope` through, so the name is in `_recorded_guard_globals` (`aot_compile.py:621`), which is what `_has_global_guards` subtracts from and `_seed_guard_scope` seeds. The comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as `get_global_source_name` decides it, with these guards as the example, so a future family with a chained root and its own prefix is not read as exempt. Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right: taking the live entry as the value, the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched, measured on an earlier revision of this tree); keeping the alias as the source unconditionally is the parent, `KeyError: <id>`. The premise that drives the `IMPORT_NAME` fix below -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. In a process that has not rebound `sys.modules` for torch's own module the source is the alias as before, so the guard shape and the recorded `import_sources` are unchanged (`test_aot_compile.py` pins `{"__import_torch_dot_nn_dot_modules_dot_module"}` as that set in two places; both pass here). Order to review: `nn_modules_globals_vt` in `torch/_dynamo/symbolic_convert.py` (the whole change is the `is not module` branch), then `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` in `test/dynamo/test_package.py` for the in-process case, then `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` in `test/dynamo/test_aot_compile.py` for the artifact, then the reworded completeness comment above `_MINTED_GLOBAL_PREFIXES` in `torch/_dynamo/aot_compile.py` (comment only; no code in that file changes). Behaviour change against the parent, pinned below. In process: with `sys.modules["torch.nn.modules.module"]` rebound to a shim carrying empty hook dicts and a forward hook registered on the defining module, compiling a function that calls an `nn.Module` matches eager and runs the hook, where the parent raised `InternalTorchDynamoError: KeyError: <id>` out of guard construction, `<id>` the hook handle's id (`0` in a fresh process, as above). Through an artifact: one captured under the rebind with a `guard_filter_fn` that keeps global guards roots its hook-dict guards at `__import_torch`, and a load seeds that name; the parent's roots at the module's own alias, which a load seeds through `importlib.import_module`, so in a loading process under the same rebind its guards read the shim's dicts. Out of scope here, and the same on the parent and at this commit: the mirror ordering. A capture in a process where the alias binds the defining module takes the alias branch -- the predicate compares `global_scope[alias]` with the module, and they are one object -- so the artifact roots its hook-dict guards at `__import_torch_dot_nn_dot_modules_dot_module`; loaded into a process that has rebound `sys.modules["torch.nn.modules.module"]`, `_seed_guard_scope` (`aot_compile.py:854-859`) binds that alias with `importlib.import_module`, the shim, and builds the guards from the shim's dicts (measured on an earlier revision of this tree: the seeded set is the alias, `scope[alias] is shim`, and the loaded `TYPE_MATCH` reads `type=<class 'dict'>`, the shim's, where the capture's read `OrderedDict`). No trace-time predicate can see that ordering: the rebind exists only in the loading process, and the artifact carries no identity guard on the root for a load to compare the seeded module against, since `MODULE_MATCH` reduces to `ID_MATCH` and both are in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`). The check would have to run at load, in `_seed_guard_scope` -- another file and another PR. What it decides today is bounded, and measured, in the FAQ below. Test Plan: ``` python test/dynamo/test_package.py -k test_import_alias_rebind_keeps_the_global_nn_hooks_visible python test/dynamo/test_aot_compile.py -k test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package python test/dynamo/test_package.py python test/dynamo/test_aot_compile.py ``` `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` joins the `test_import_alias` tests below it and replaces one of them: #197046's `test_import_alias_nn_hook_guards_read_the_live_entry_the_alias_binds`, which pinned, as the state this commit changes, that a forward hook on the defining module under the rebind raises `InternalTorchDynamoError` out of guard construction, is deleted here, because at this tree the raise it asserts no longer happens (measured: run against this tree's `symbolic_convert.py`, it fails with `InternalTorchDynamoError not raised`) and the new test is that pin's flip; the `InternalTorchDynamoError` import in `test_package.py`, which only it used, goes with it. It compiles a function calling an `nn.Module` once so the process has resolved the name, resets, rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts, registers a forward hook on the defining module and compiles again, pinning that the hook runs under compile as in eager (`fired == [mod, mod]`), that `compiled == eager`, that `torch.nn.modules.module` is still the defining module and that the alias holds the shim. In `finally` it removes the hook, restores `sys.modules`, pops both aliases from `fn.__globals__` -- the module's own and `__import_torch`, the fallback root, which the first, clean compile already binds through `IMPORT_NAME` and the fallback rebinds -- and both `_import_source_cache` entries. The hook is what makes the test load-bearing: without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only. It errors on the parent with `InternalTorchDynamoError: KeyError: 0` (measured by running this file's test against the parent's `symbolic_convert.py`; `0` is the handle id in a process that has registered no earlier hook). Two mutations of this tree fail it, measured on an earlier revision whose `nn_modules_globals_vt` is this one: the live entry as the value on `Tensor-likes are not close!` (6/6 mismatched, the hook skipped); the alias as the source unconditionally on `KeyError: 0`. The test's comment names the mechanism the parent's failure has, not the value-side mutation's: the bypass decision reads the VT's value (`_hooks_dict_len`, `nn_module.py:1375`, through `PythonModuleVariable.tp_getattro_impl`, which does `getattr(self.value, name)` on its `is_torch` branch, `misc.py:2030`), the defining module under either source, so it sees the hook either way; it is the `CLOSURE_MATCH` on the hook that reads through the source, `self.get(guard)` (`guards.py:3138`) evaluating `G[alias]._global_forward_hooks[<id>]` against the live scope as the guard is built, which is where the parent's traceback raises `KeyError: 0` (measured: `build_guards -> CLOSURE_MATCH -> get -> get_value -> eval`). `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` captures `fn(m, x)`, `m` a `ParentWithChildModule` passed as an argument so the artifact has no user global, under `patch.dict(sys.modules, {name: shim})` with `keep_global_guards`, serializes it, and pins on the guards state the shape of the guards `get_global_source_name` resolves to `__import_torch`: exactly the four `G['__import_torch'].nn.modules.module._global_*` names, the walk and not only the root, so a change that kept the root and dropped the walk, or walked from another base, fails it. It then pins that `_names_a_missing_global` returns `False` for every recorded global; at this tree that holds by construction, every root being a prefixed alias, and the comment says it stays as the regression guard against a root minted by id. It loads the artifact with a fresh `guard_globals=` scope, still under the rebind, and pins `_has_global_guards` `False`, the seeded names exactly `{"__import_torch"}`, and the call equal to eager. It fails with the id-minted root of this commit's earlier revision (`install_global_by_id("___nn_modules_module", module)`, re-applied to that tree as a mutant) at the `_names_a_missing_global` pin (`True is not false : ___nn_modules_module_<id>_c0`), and on the parent at the guard-shape pin (measured against the parent's `symbolic_convert.py`: the set of guards resolving to `__import_torch` is empty there, the four missing). It registers no hook: see the FAQ below on why. It pops the alias's and `__import_torch`'s `_import_source_cache` entries through `addCleanup`, so an assertion failing inside the `patch.dict` block cannot leave the shim cached; the `__import_torch` binding the capture writes into this module's dict is stripped by `_hide_leaked_dynamo_globals`' cleanup. Whole files at this tree: `test_package.py` 101 tests, OK (skipped=40, expected failures=1); `test_aot_compile.py` 208 tests, OK (skipped=6). ``` lintrunner --take RUFF,PYFMT,GB_REGISTRY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py test/dynamo/test_package.py test/dynamo/test_aot_compile.py lintrunner --take PYREFLY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py ``` PYREFLY reports nothing in the four files this commit touches; its seven findings are in `torch/_dynamo/guards.py` and `torch/_native/cutedsl/hw_caps.py`, neither of which this commit changes. > **FAQ: `nn_modules_globals_vt` still takes its value from a fixed module object while its source comes from `import_source`, which now binds live `sys.modules`. Fix that too -- the divergence silently decides graph shape.** > > Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right. The value has to be the defining module: the dicts the runtime consults are read by `nn.Module._call_impl` through its own `__globals__`, the defining module's `__dict__`, never through the alias, so that is what the bypass decision must read; `convert_frame.py:1371-1376` reads the same dicts through the same attribute chain. Taking the live entry instead, measured with the alias on a shim carrying empty dicts and a forward hook registered on the defining module: the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched). Keeping the defining module as the value with the alias as the source, the shape of the two commits below, is what the earlier answer measured as unobservable -- and it is, while the defining module has no hooks, because the guards are one `TYPE_MATCH` per dict; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]`, `<id>` being `RemovableHandle.next_id` at registration (`0` in a process that has registered no earlier hook), which resolves on the shim and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. So the source now follows the value: the alias while `self.output.global_scope[alias]` is the defining module, otherwise the `torch` package's alias walking `.nn.modules.module`, the attributes the value is read through. The premise that drives the `IMPORT_NAME` fix -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. > **FAQ: the `nn_modules_globals_vt` value/source divergence is documented and hand-measured but not pinned by any test; a test that rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts and asserts a compiled `nn.Module` forward still matches eager would convert the comment into a check.** > > Added as `test_import_alias_rebind_keeps_the_global_nn_hooks_visible`, with one addition to the suggested shape that turned out to matter: a forward hook registered on the defining module. Without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only; with it, the hand measurement's conclusion fell over (previous FAQ), and the test now kills both alternatives -- the live value on a numeric mismatch, the unconditional alias source on `KeyError: 0`, which is what the two commits below produce. It asserts the hook ran once under eager and once more under compile, `compiled == eager`, `torch.nn.modules.module is real` and that the alias holds the shim, and in `finally` removes the hook, restores `sys.modules`, and pops both aliases (`__import_torch` is the fallback root) from `fn.__globals__` and both entries from `_import_source_cache`. > **FAQ: `___nn_modules_module_*` is a fourth Dynamo-minted global family that `aot_compile.py` enumerates nowhere: add the prefix to `_MINTED_GLOBAL_PREFIXES`, seed it in `_seed_guard_scope` with a `CleanupHook.disown`, subtract it in `_has_global_guards`, and update the completeness comment.** > > The family is gone instead. The fallback root is now the `torch` package's `__import_torch` alias with `.nn.modules.module` walked as `AttrSource`s, so every name a guard here can be rooted at is an `__import_*` alias, the first family in that tuple: `_seed_guard_scope` seeds it from `import_sources`, `_has_global_guards` subtracts it, `_names_a_missing_global` recognizes the prefix, and `import_source` binds it by plain assignment, so there is no `CleanupHook` to disown. All three consequences the review derived were reproduced first with the id-minted name (nothing seeded, `_has_global_guards` `True` with no user global, `KeyError on G['___nn_modules_module_<id>_c0']` reported as a global to define) and are absent with this root, which `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` pins. The `torch` package rather than `torch.nn.modules`: the chain then mirrors `torch.nn.modules.module`, the expression the value is read through, and a fixture that rebinds `sys.modules["torch"]` itself leaves nothing in Dynamo working. The completeness comment above the tuple (`aot_compile.py:75-93`) is reworded rather than extended: it said a family belongs in the tuple once a serializable guard is rooted at a `GlobalSource` on one of its names, and `_guard_source_globals` (`aot_compile.py:595`) reads "rooted at" as the `originating_source` IS a `GlobalSource`, which no hook-dict guard here satisfies (their sources are the `AttrSource` chain; that helper returns `set()` for this artifact, measured), so by that reading the family would be out of scope while all three sites act on the name. The reading the three sites share is `get_global_source_name` (`source.py:1329`), which walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) fills `global_scope` with; the comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as that helper decides it, and names these guards as the example. No name outside the three families resolves that way. > **FAQ: why does the artifact test register no hook, and why does it not pin that a hook registered after the load fails the loaded guards?** > > Two measured reasons, neither this commit's to change. First, with a hook on the defining module under the rebind, the capture never reaches the guard-scope sites: the hook makes the trace inline `_call_impl`, whose `__globals__` is the defining module's dict, and `_registered_module_for_globals` resolves `sys.modules[__name__]` to the shim, whose dict is a different object, so `get_globals_source_and_value` falls to the `___unnamed_scope` branch and records the defining module's whole `__dict__` under it; the guards pickler then writes that dict by value and pickles its `T = TypeVar("T")` by qualified name through `sys.modules`, which is the shim, and `aot_compile` raises `PackageError: PicklingError: Can't pickle ~T: attribute lookup T on torch.nn.modules.module failed` (the parent raises `KeyError: 0` earlier on the same input). Second, a hook registered after a compile is not guarded at all, in process and without any rebind: the global hook dicts guard as `TYPE_MATCH` only, under both values of `skip_nnmodule_hook_guards` -- `EMPTY_NN_MODULE_HOOKS_DICT` is installed for the instance's own hook attributes (`nn_module.py:1563-1591`), not for the module globals read here -- so a global forward hook registered after a `torch.compile` call is skipped by the compiled function with no recompile (measured on an earlier revision of this tree: `frame_count` 1, hook fired 0, result differs from eager), which `config.py:458-461` documents as the accepted unsafety. A loaded artifact inherits exactly that, so a hook-after-load phase would pin the same `TYPE_MATCH` pass on every tree. > **FAQ: the fix is conditioned on trace-time state, so the mirror ordering stays silently wrong: a capture in a clean process roots at `__import_torch_dot_nn_dot_modules_dot_module`, and a load into a process that has rebound `sys.modules["torch.nn.modules.module"]` has `_seed_guard_scope` seed that alias with `importlib.import_module`, the shim, whose four empty hook dicts pass the `TYPE_MATCH`es, so the loaded function bypasses `_call_impl` and skips a global hook registered on the real module. Handle it, or state that the ordering is out of scope.** > > Out of scope, stated in the message. The handling would be a load-time change in `aot_compile._seed_guard_scope` -- another file and another PR -- because no predicate in `nn_modules_globals_vt` runs where the rebind is: it runs in the capturing process, where the alias and the defining module are one object, and the artifact has no identity guard on the root for a load to check, `MODULE_MATCH`/`ID_MATCH` being unserializable. Measured on an earlier revision of this tree to size what is left. The seeding half is as the finding says: a hookless `fn(m, x)` capture with `keep_global_guards`, deserialized with a fresh `guard_globals=` under `patch.dict(sys.modules, {name: shim})`, seeds `{"__import_torch_dot_nn_dot_modules_dot_module"}` bound to the shim, and its hook-dict guards are built from the shim's dicts (`type=<class 'dict'>` in the loaded tree, `OrderedDict` in the capture's). The consequence half is narrower: a global forward hook registered on the defining module in the loading process is skipped by that load -- and equally by the clean load of the same artifact, whose alias is seeded with the defining module (`loaded fired=[]`, output equal to the hookless eager, in both). Empty dicts guard as `TYPE_MATCH` only, so the rebind changes which module's dicts the guards read, not what they decide; a hook the capture did not see is the accepted unsafety of the previous FAQ, rebind or not. The shape where the root would decide the outcome needs a capture-time hook, and there the four-dict shim does not pass silently: that capture carries `DICT_LENGTH`/`DICT_CONTAINS`/`EQUALS_MATCH` guards on the alias's hook dicts, `_global_forward_hooks_with_kwargs` among them, and its rebound load fails inside `deserialize` with `AttributeError: module 'torch.nn.modules.module' has no attribute '_global_forward_hooks_with_kwargs'` out of `TYPE_MATCH` creation (`guards.py:2425`), where the clean load of the same artifact runs the hook registered in the loading process. A shim carrying every dict `_call_impl` reads was not measured. > **FAQ: `assertEqual(set(scope) - before, {"__import_torch"})` is the only assertion in the artifact test that discriminates against the parent, and it couples to `keep_global_guards` dropping `MODULE_MATCH`; `assertIn("__import_torch", ...)` plus `assertNotIn(nn_alias, ...)` would state the intent without that coupling.** > > Kept exact, and no longer the only discriminating pin: the guard-shape assertion added above it fails first on the parent (measured: the set of guards resolving to `__import_torch` is empty there). The exact set is the claim this message makes -- the load seeds exactly the one name the kept guards resolve through -- and the coupling is to serialization, not to the filter's choice: `MODULE_MATCH` is in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`), so any filter that lets an artifact serialize drops it, and a second seeded alias would mean a second root some serializable guard resolves through, which is what the pin should catch rather than admit. > **FAQ: `import_source(module.__name__)` is called for its side effects even when its `GlobalSource` is discarded: the alias is recorded in `import_sources`, bound in `f_globals`, and `CompilePackage.install` binds it in every loading process. Check `sys.modules` first and skip the call.** > > The read-back of `global_scope[alias]` after the call is the check, and the comment now says so: it is the binding a guard rooted at the alias reads, and `import_source` is what decides it -- the live entry, or `_import_source_cache` for a name since removed from `sys.modules` or blocked with `None`. Reading `sys.modules` here would duplicate that decision in a second place with its own corner cases. The recorded-but-unread alias is the ordinary state of an `import_sources` entry, not a new one: `test_load_seeds_exactly_the_recorded_globals` asserts `len(guarded) < len(import_sources)` on an artifact whose only guarded alias is this same `__import_torch_dot_nn_dot_modules_dot_module`, and the capture in the new artifact test records six aliases for one guarded root. `install` binding it to the shim in a still-rebound loading process binds a name nothing reads. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: 4c2fee2 Pull-Request: #197135
[ghstack-poisoned]
… when the alias binds another Split for review budget from `[dynamo] Bind the import alias to the live sys.modules entry` (#197046), two commits below (`[dynamo] Serve a removed or blocked import name from what the alias last bound`, split from the same commit, sits between): that one makes the `__import_*` alias bind the live `sys.modules` entry; this one makes `nn_modules_globals_vt` stop rooting its guards at that alias once it binds a module other than the one whose dicts the VT reads. `nn_modules_globals_vt` reads the four global hook dicts to decide whether a module call may bypass `_call_impl`, and it has to read the dicts `_call_impl` itself reads through its own `__globals__`: the defining module's, `torch.nn.modules.module`, which no `sys.modules` rebind moves (`convert_frame.py:1371-1376` reads the same four dicts through the same attribute chain). Its source was the `__import_torch_dot_nn_dot_modules_dot_module` alias unconditionally. Below this commit that alias binds the live `sys.modules` entry, so a program that rebinds `sys.modules["torch.nn.modules.module"]` -- a test fixture, a `mock.patch.dict(sys.modules, ...)` -- leaves the VT's value and its source naming different objects. That is unobservable while the defining module has no hooks, because empty dicts guard as one `TYPE_MATCH` each; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]` -- `<id>` the handle's `RemovableHandle.next_id` at registration, a process-global counter (`torch/utils/hooks.py:22-27`), so `0` only in a process that has registered no earlier hook -- which resolves on the other module and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. The two commits below both have it; #197256, whose memoized `_import_module` still decided the alias, ran the hook when the name had been resolved before the rebind and skipped it otherwise. The source now follows the value. It stays the alias while `self.output.global_scope[alias]` is the defining module, read back after `import_source` because that binding is what a guard rooted at the alias reads. Otherwise it is the `torch` package's own alias walking `.nn.modules.module` -- the attributes the value itself is read through, which the rebind does not move -- so the guards become `G['__import_torch'].nn.modules.module._global_forward_hooks` and so on. Not a name minted by id, which an earlier revision of this commit installed through `install_global_by_id("___nn_modules_module", module)`: `aot_compile.py` enumerates the global names Dynamo mints by prefix and argues the list complete (`_MINTED_GLOBAL_PREFIXES`, `aot_compile.py:75-93`), and a fourth family fails all three places that read it. Measured with an artifact captured under the rebind through `torch.compile(...).aot_compile` with a `guard_filter_fn` that keeps global guards, then loaded with a fresh `guard_globals=` scope: `_seed_guard_scope` (`aot_compile.py:854-872`) seeds `import_sources` aliases and `___unnamed_scope` names and so seeded nothing; `_has_global_guards` (`aot_compile.py:724`) subtracts only `import_sources` aliases and so was `True` for an artifact with no user global; the load then failed `KeyError on G['___nn_modules_module_<id>_c0']` and `_names_a_missing_global` (`aot_compile.py:106-112`) classed it as a user global, so `_missing_global_hint` told the caller to define a name embedding `id()` of an object in the tracing process. Rooted at `__import_torch`, the same artifact's guarded globals are `{__import_torch, __builtins_dict___N}`, `_has_global_guards` is `False`, the load seeds exactly `__import_torch`, and the call matches eager. No new family, so the list in `aot_compile.py` stands; its criterion is reworded here, because these are the first guards on a minted name whose `originating_source` is a chain rather than the `GlobalSource` itself, and the repo has one helper for each reading of "rooted at". `_guard_source_globals` (`aot_compile.py:595`) keeps a guard whose source IS a `GlobalSource`, and returns nothing for `__import_torch` on this artifact (measured: `set()`); `get_global_source_name` (`source.py:1329`) walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) records `global_scope` through, so the name is in `_recorded_guard_globals` (`aot_compile.py:621`), which is what `_has_global_guards` subtracts from and `_seed_guard_scope` seeds. The comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as `get_global_source_name` decides it, with these guards as the example, so a future family with a chained root and its own prefix is not read as exempt. Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right: taking the live entry as the value, the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched, measured on an earlier revision of this tree); keeping the alias as the source unconditionally is the parent, `KeyError: <id>`. The premise that drives the `IMPORT_NAME` fix below -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. In a process that has not rebound `sys.modules` for torch's own module the source is the alias as before, so the guard shape and the recorded `import_sources` are unchanged (`test_aot_compile.py` pins `{"__import_torch_dot_nn_dot_modules_dot_module"}` as that set in two places; both pass here). Order to review: `nn_modules_globals_vt` in `torch/_dynamo/symbolic_convert.py` (the whole change is the `is not module` branch), then `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` in `test/dynamo/test_package.py` for the in-process case, then `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` in `test/dynamo/test_aot_compile.py` for the artifact, then the reworded completeness comment above `_MINTED_GLOBAL_PREFIXES` in `torch/_dynamo/aot_compile.py` (comment only; no code in that file changes). Behaviour change against the parent, pinned below. In process: with `sys.modules["torch.nn.modules.module"]` rebound to a shim carrying empty hook dicts and a forward hook registered on the defining module, compiling a function that calls an `nn.Module` matches eager and runs the hook, where the parent raised `InternalTorchDynamoError: KeyError: <id>` out of guard construction, `<id>` the hook handle's id (`0` in a fresh process, as above). Through an artifact: one captured under the rebind with a `guard_filter_fn` that keeps global guards roots its hook-dict guards at `__import_torch`, and a load seeds that name; the parent's roots at the module's own alias, which a load seeds through `importlib.import_module`, so in a loading process under the same rebind its guards read the shim's dicts. Out of scope here, and the same on the parent and at this commit: the mirror ordering. A capture in a process where the alias binds the defining module takes the alias branch -- the predicate compares `global_scope[alias]` with the module, and they are one object -- so the artifact roots its hook-dict guards at `__import_torch_dot_nn_dot_modules_dot_module`; loaded into a process that has rebound `sys.modules["torch.nn.modules.module"]`, `_seed_guard_scope` (`aot_compile.py:854-859`) binds that alias with `importlib.import_module`, the shim, and builds the guards from the shim's dicts (measured on an earlier revision of this tree: the seeded set is the alias, `scope[alias] is shim`, and the loaded `TYPE_MATCH` reads `type=<class 'dict'>`, the shim's, where the capture's read `OrderedDict`). No trace-time predicate can see that ordering: the rebind exists only in the loading process, and the artifact carries no identity guard on the root for a load to compare the seeded module against, since `MODULE_MATCH` reduces to `ID_MATCH` and both are in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`). The check would have to run at load, in `_seed_guard_scope` -- another file and another PR. What it decides today is bounded, and measured, in the FAQ below. Test Plan: ``` python test/dynamo/test_package.py -k test_import_alias_rebind_keeps_the_global_nn_hooks_visible python test/dynamo/test_aot_compile.py -k test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package python test/dynamo/test_package.py python test/dynamo/test_aot_compile.py ``` `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` joins the `test_import_alias` tests below it and replaces one of them: #197046's `test_import_alias_nn_hook_guards_read_the_live_entry_the_alias_binds`, which pinned, as the state this commit changes, that a forward hook on the defining module under the rebind raises `InternalTorchDynamoError` out of guard construction, is deleted here, because at this tree the raise it asserts no longer happens (measured: run against this tree's `symbolic_convert.py`, it fails with `InternalTorchDynamoError not raised`) and the new test is that pin's flip; the `InternalTorchDynamoError` import in `test_package.py`, which only it used, goes with it. It compiles a function calling an `nn.Module` once so the process has resolved the name, resets, rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts, registers a forward hook on the defining module and compiles again, pinning that the hook runs under compile as in eager (`fired == [mod, mod]`), that `compiled == eager`, that `torch.nn.modules.module` is still the defining module and that the alias holds the shim. In `finally` it removes the hook, restores `sys.modules`, pops both aliases from `fn.__globals__` -- the module's own and `__import_torch`, the fallback root, which the first, clean compile already binds through `IMPORT_NAME` and the fallback rebinds -- and both `_import_source_cache` entries. The hook is what makes the test load-bearing: without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only. It errors on the parent with `InternalTorchDynamoError: KeyError: 0` (measured by running this file's test against the parent's `symbolic_convert.py`; `0` is the handle id in a process that has registered no earlier hook). Two mutations of this tree fail it, measured on an earlier revision whose `nn_modules_globals_vt` is this one: the live entry as the value on `Tensor-likes are not close!` (6/6 mismatched, the hook skipped); the alias as the source unconditionally on `KeyError: 0`. The test's comment names the mechanism the parent's failure has, not the value-side mutation's: the bypass decision reads the VT's value (`_hooks_dict_len`, `nn_module.py:1375`, through `PythonModuleVariable.tp_getattro_impl`, which does `getattr(self.value, name)` on its `is_torch` branch, `misc.py:2030`), the defining module under either source, so it sees the hook either way; it is the `CLOSURE_MATCH` on the hook that reads through the source, `self.get(guard)` (`guards.py:3138`) evaluating `G[alias]._global_forward_hooks[<id>]` against the live scope as the guard is built, which is where the parent's traceback raises `KeyError: 0` (measured: `build_guards -> CLOSURE_MATCH -> get -> get_value -> eval`). `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` captures `fn(m, x)`, `m` a `ParentWithChildModule` passed as an argument so the artifact has no user global, under `patch.dict(sys.modules, {name: shim})` with `keep_global_guards`, serializes it, and pins on the guards state the shape of the guards `get_global_source_name` resolves to `__import_torch`: exactly the four `G['__import_torch'].nn.modules.module._global_*` names, the walk and not only the root, so a change that kept the root and dropped the walk, or walked from another base, fails it. It then pins that `_names_a_missing_global` returns `False` for every recorded global; at this tree that holds by construction, every root being a prefixed alias, and the comment says it stays as the regression guard against a root minted by id. It loads the artifact with a fresh `guard_globals=` scope, still under the rebind, and pins `_has_global_guards` `False`, the seeded names exactly `{"__import_torch"}`, and the call equal to eager. It fails with the id-minted root of this commit's earlier revision (`install_global_by_id("___nn_modules_module", module)`, re-applied to that tree as a mutant) at the `_names_a_missing_global` pin (`True is not false : ___nn_modules_module_<id>_c0`), and on the parent at the guard-shape pin (measured against the parent's `symbolic_convert.py`: the set of guards resolving to `__import_torch` is empty there, the four missing). It registers no hook: see the FAQ below on why. It pops the alias's and `__import_torch`'s `_import_source_cache` entries through `addCleanup`, so an assertion failing inside the `patch.dict` block cannot leave the shim cached; the `__import_torch` binding the capture writes into this module's dict is stripped by `_hide_leaked_dynamo_globals`' cleanup. Whole files at this tree: `test_package.py` 101 tests, OK (skipped=40, expected failures=1); `test_aot_compile.py` 208 tests, OK (skipped=6). ``` lintrunner --take RUFF,PYFMT,GB_REGISTRY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py test/dynamo/test_package.py test/dynamo/test_aot_compile.py lintrunner --take PYREFLY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py ``` PYREFLY reports nothing in the four files this commit touches; its seven findings are in `torch/_dynamo/guards.py` and `torch/_native/cutedsl/hw_caps.py`, neither of which this commit changes. > **FAQ: `nn_modules_globals_vt` still takes its value from a fixed module object while its source comes from `import_source`, which now binds live `sys.modules`. Fix that too -- the divergence silently decides graph shape.** > > Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right. The value has to be the defining module: the dicts the runtime consults are read by `nn.Module._call_impl` through its own `__globals__`, the defining module's `__dict__`, never through the alias, so that is what the bypass decision must read; `convert_frame.py:1371-1376` reads the same dicts through the same attribute chain. Taking the live entry instead, measured with the alias on a shim carrying empty dicts and a forward hook registered on the defining module: the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched). Keeping the defining module as the value with the alias as the source, the shape of the two commits below, is what the earlier answer measured as unobservable -- and it is, while the defining module has no hooks, because the guards are one `TYPE_MATCH` per dict; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]`, `<id>` being `RemovableHandle.next_id` at registration (`0` in a process that has registered no earlier hook), which resolves on the shim and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. So the source now follows the value: the alias while `self.output.global_scope[alias]` is the defining module, otherwise the `torch` package's alias walking `.nn.modules.module`, the attributes the value is read through. The premise that drives the `IMPORT_NAME` fix -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. > **FAQ: the `nn_modules_globals_vt` value/source divergence is documented and hand-measured but not pinned by any test; a test that rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts and asserts a compiled `nn.Module` forward still matches eager would convert the comment into a check.** > > Added as `test_import_alias_rebind_keeps_the_global_nn_hooks_visible`, with one addition to the suggested shape that turned out to matter: a forward hook registered on the defining module. Without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only; with it, the hand measurement's conclusion fell over (previous FAQ), and the test now kills both alternatives -- the live value on a numeric mismatch, the unconditional alias source on `KeyError: 0`, which is what the two commits below produce. It asserts the hook ran once under eager and once more under compile, `compiled == eager`, `torch.nn.modules.module is real` and that the alias holds the shim, and in `finally` removes the hook, restores `sys.modules`, and pops both aliases (`__import_torch` is the fallback root) from `fn.__globals__` and both entries from `_import_source_cache`. > **FAQ: `___nn_modules_module_*` is a fourth Dynamo-minted global family that `aot_compile.py` enumerates nowhere: add the prefix to `_MINTED_GLOBAL_PREFIXES`, seed it in `_seed_guard_scope` with a `CleanupHook.disown`, subtract it in `_has_global_guards`, and update the completeness comment.** > > The family is gone instead. The fallback root is now the `torch` package's `__import_torch` alias with `.nn.modules.module` walked as `AttrSource`s, so every name a guard here can be rooted at is an `__import_*` alias, the first family in that tuple: `_seed_guard_scope` seeds it from `import_sources`, `_has_global_guards` subtracts it, `_names_a_missing_global` recognizes the prefix, and `import_source` binds it by plain assignment, so there is no `CleanupHook` to disown. All three consequences the review derived were reproduced first with the id-minted name (nothing seeded, `_has_global_guards` `True` with no user global, `KeyError on G['___nn_modules_module_<id>_c0']` reported as a global to define) and are absent with this root, which `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` pins. The `torch` package rather than `torch.nn.modules`: the chain then mirrors `torch.nn.modules.module`, the expression the value is read through, and a fixture that rebinds `sys.modules["torch"]` itself leaves nothing in Dynamo working. The completeness comment above the tuple (`aot_compile.py:75-93`) is reworded rather than extended: it said a family belongs in the tuple once a serializable guard is rooted at a `GlobalSource` on one of its names, and `_guard_source_globals` (`aot_compile.py:595`) reads "rooted at" as the `originating_source` IS a `GlobalSource`, which no hook-dict guard here satisfies (their sources are the `AttrSource` chain; that helper returns `set()` for this artifact, measured), so by that reading the family would be out of scope while all three sites act on the name. The reading the three sites share is `get_global_source_name` (`source.py:1329`), which walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) fills `global_scope` with; the comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as that helper decides it, and names these guards as the example. No name outside the three families resolves that way. > **FAQ: why does the artifact test register no hook, and why does it not pin that a hook registered after the load fails the loaded guards?** > > Two measured reasons, neither this commit's to change. First, with a hook on the defining module under the rebind, the capture never reaches the guard-scope sites: the hook makes the trace inline `_call_impl`, whose `__globals__` is the defining module's dict, and `_registered_module_for_globals` resolves `sys.modules[__name__]` to the shim, whose dict is a different object, so `get_globals_source_and_value` falls to the `___unnamed_scope` branch and records the defining module's whole `__dict__` under it; the guards pickler then writes that dict by value and pickles its `T = TypeVar("T")` by qualified name through `sys.modules`, which is the shim, and `aot_compile` raises `PackageError: PicklingError: Can't pickle ~T: attribute lookup T on torch.nn.modules.module failed` (the parent raises `KeyError: 0` earlier on the same input). Second, a hook registered after a compile is not guarded at all, in process and without any rebind: the global hook dicts guard as `TYPE_MATCH` only, under both values of `skip_nnmodule_hook_guards` -- `EMPTY_NN_MODULE_HOOKS_DICT` is installed for the instance's own hook attributes (`nn_module.py:1563-1591`), not for the module globals read here -- so a global forward hook registered after a `torch.compile` call is skipped by the compiled function with no recompile (measured on an earlier revision of this tree: `frame_count` 1, hook fired 0, result differs from eager), which `config.py:458-461` documents as the accepted unsafety. A loaded artifact inherits exactly that, so a hook-after-load phase would pin the same `TYPE_MATCH` pass on every tree. > **FAQ: the fix is conditioned on trace-time state, so the mirror ordering stays silently wrong: a capture in a clean process roots at `__import_torch_dot_nn_dot_modules_dot_module`, and a load into a process that has rebound `sys.modules["torch.nn.modules.module"]` has `_seed_guard_scope` seed that alias with `importlib.import_module`, the shim, whose four empty hook dicts pass the `TYPE_MATCH`es, so the loaded function bypasses `_call_impl` and skips a global hook registered on the real module. Handle it, or state that the ordering is out of scope.** > > Out of scope, stated in the message. The handling would be a load-time change in `aot_compile._seed_guard_scope` -- another file and another PR -- because no predicate in `nn_modules_globals_vt` runs where the rebind is: it runs in the capturing process, where the alias and the defining module are one object, and the artifact has no identity guard on the root for a load to check, `MODULE_MATCH`/`ID_MATCH` being unserializable. Measured on an earlier revision of this tree to size what is left. The seeding half is as the finding says: a hookless `fn(m, x)` capture with `keep_global_guards`, deserialized with a fresh `guard_globals=` under `patch.dict(sys.modules, {name: shim})`, seeds `{"__import_torch_dot_nn_dot_modules_dot_module"}` bound to the shim, and its hook-dict guards are built from the shim's dicts (`type=<class 'dict'>` in the loaded tree, `OrderedDict` in the capture's). The consequence half is narrower: a global forward hook registered on the defining module in the loading process is skipped by that load -- and equally by the clean load of the same artifact, whose alias is seeded with the defining module (`loaded fired=[]`, output equal to the hookless eager, in both). Empty dicts guard as `TYPE_MATCH` only, so the rebind changes which module's dicts the guards read, not what they decide; a hook the capture did not see is the accepted unsafety of the previous FAQ, rebind or not. The shape where the root would decide the outcome needs a capture-time hook, and there the four-dict shim does not pass silently: that capture carries `DICT_LENGTH`/`DICT_CONTAINS`/`EQUALS_MATCH` guards on the alias's hook dicts, `_global_forward_hooks_with_kwargs` among them, and its rebound load fails inside `deserialize` with `AttributeError: module 'torch.nn.modules.module' has no attribute '_global_forward_hooks_with_kwargs'` out of `TYPE_MATCH` creation (`guards.py:2425`), where the clean load of the same artifact runs the hook registered in the loading process. A shim carrying every dict `_call_impl` reads was not measured. > **FAQ: `assertEqual(set(scope) - before, {"__import_torch"})` is the only assertion in the artifact test that discriminates against the parent, and it couples to `keep_global_guards` dropping `MODULE_MATCH`; `assertIn("__import_torch", ...)` plus `assertNotIn(nn_alias, ...)` would state the intent without that coupling.** > > Kept exact, and no longer the only discriminating pin: the guard-shape assertion added above it fails first on the parent (measured: the set of guards resolving to `__import_torch` is empty there). The exact set is the claim this message makes -- the load seeds exactly the one name the kept guards resolve through -- and the coupling is to serialization, not to the filter's choice: `MODULE_MATCH` is in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`), so any filter that lets an artifact serialize drops it, and a second seeded alias would mean a second root some serializable guard resolves through, which is what the pin should catch rather than admit. > **FAQ: `import_source(module.__name__)` is called for its side effects even when its `GlobalSource` is discarded: the alias is recorded in `import_sources`, bound in `f_globals`, and `CompilePackage.install` binds it in every loading process. Check `sys.modules` first and skip the call.** > > The read-back of `global_scope[alias]` after the call is the check, and the comment now says so: it is the binding a guard rooted at the alias reads, and `import_source` is what decides it -- the live entry, or `_import_source_cache` for a name since removed from `sys.modules` or blocked with `None`. Reading `sys.modules` here would duplicate that decision in a second place with its own corner cases. The recorded-but-unread alias is the ordinary state of an `import_sources` entry, not a new one: `test_load_seeds_exactly_the_recorded_globals` asserts `len(guarded) < len(import_sources)` on an artifact whose only guarded alias is this same `__import_torch_dot_nn_dot_modules_dot_module`, and the capture in the new artifact test records six aliases for one guarded root. `install` binding it to the shim in a still-rebound loading process binds a name nothing reads. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: 97f344d Pull-Request: #197135
[ghstack-poisoned]
… when the alias binds another Split for review budget from `[dynamo] Bind the import alias to the live sys.modules entry` (#197046), two commits below (`[dynamo] Serve a removed or blocked import name from what the alias last bound`, split from the same commit, sits between): that one makes the `__import_*` alias bind the live `sys.modules` entry; this one makes `nn_modules_globals_vt` stop rooting its guards at that alias once it binds a module other than the one whose dicts the VT reads. `nn_modules_globals_vt` reads the four global hook dicts to decide whether a module call may bypass `_call_impl`, and it has to read the dicts `_call_impl` itself reads through its own `__globals__`: the defining module's, `torch.nn.modules.module`, which no `sys.modules` rebind moves (`convert_frame.py:1371-1376` reads the same four dicts through the same attribute chain). Its source was the `__import_torch_dot_nn_dot_modules_dot_module` alias unconditionally. Below this commit that alias binds the live `sys.modules` entry, so a program that rebinds `sys.modules["torch.nn.modules.module"]` -- a test fixture, a `mock.patch.dict(sys.modules, ...)` -- leaves the VT's value and its source naming different objects. That is unobservable while the defining module has no hooks, because empty dicts guard as one `TYPE_MATCH` each; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]` -- `<id>` the handle's `RemovableHandle.next_id` at registration, a process-global counter (`torch/utils/hooks.py:22-27`), so `0` only in a process that has registered no earlier hook -- which resolves on the other module and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. The two commits below both have it; #197256, whose memoized `_import_module` still decided the alias, ran the hook when the name had been resolved before the rebind and skipped it otherwise. The source now follows the value. It stays the alias while `self.output.global_scope[alias]` is the defining module, read back after `import_source` because that binding is what a guard rooted at the alias reads. Otherwise it is the `torch` package's own alias walking `.nn.modules.module` -- the attributes the value itself is read through, which the rebind does not move -- so the guards become `G['__import_torch'].nn.modules.module._global_forward_hooks` and so on. Not a name minted by id, which an earlier revision of this commit installed through `install_global_by_id("___nn_modules_module", module)`: `aot_compile.py` enumerates the global names Dynamo mints by prefix and argues the list complete (`_MINTED_GLOBAL_PREFIXES`, `aot_compile.py:75-93`), and a fourth family fails all three places that read it. Measured with an artifact captured under the rebind through `torch.compile(...).aot_compile` with a `guard_filter_fn` that keeps global guards, then loaded with a fresh `guard_globals=` scope: `_seed_guard_scope` (`aot_compile.py:854-872`) seeds `import_sources` aliases and `___unnamed_scope` names and so seeded nothing; `_has_global_guards` (`aot_compile.py:724`) subtracts only `import_sources` aliases and so was `True` for an artifact with no user global; the load then failed `KeyError on G['___nn_modules_module_<id>_c0']` and `_names_a_missing_global` (`aot_compile.py:106-112`) classed it as a user global, so `_missing_global_hint` told the caller to define a name embedding `id()` of an object in the tracing process. Rooted at `__import_torch`, the same artifact's guarded globals are `{__import_torch, __builtins_dict___N}`, `_has_global_guards` is `False`, the load seeds exactly `__import_torch`, and the call matches eager. No new family, so the list in `aot_compile.py` stands; its criterion is reworded here, because these are the first guards on a minted name whose `originating_source` is a chain rather than the `GlobalSource` itself, and the repo has one helper for each reading of "rooted at". `_guard_source_globals` (`aot_compile.py:595`) keeps a guard whose source IS a `GlobalSource`, and returns nothing for `__import_torch` on this artifact (measured: `set()`); `get_global_source_name` (`source.py:1329`) walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) records `global_scope` through, so the name is in `_recorded_guard_globals` (`aot_compile.py:621`), which is what `_has_global_guards` subtracts from and `_seed_guard_scope` seeds. The comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as `get_global_source_name` decides it, with these guards as the example, so a future family with a chained root and its own prefix is not read as exempt. Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right: taking the live entry as the value, the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched, measured on an earlier revision of this tree); keeping the alias as the source unconditionally is the parent, `KeyError: <id>`. The premise that drives the `IMPORT_NAME` fix below -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. In a process that has not rebound `sys.modules` for torch's own module the source is the alias as before, so the guard shape and the recorded `import_sources` are unchanged (`test_aot_compile.py` pins `{"__import_torch_dot_nn_dot_modules_dot_module"}` as that set in two places; both pass here). Order to review: `nn_modules_globals_vt` in `torch/_dynamo/symbolic_convert.py` (the whole change is the `is not module` branch), then `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` in `test/dynamo/test_package.py` for the in-process case, then `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` in `test/dynamo/test_aot_compile.py` for the artifact, then the reworded completeness comment above `_MINTED_GLOBAL_PREFIXES` in `torch/_dynamo/aot_compile.py` (comment only; no code in that file changes). Behaviour change against the parent, pinned below. In process: with `sys.modules["torch.nn.modules.module"]` rebound to a shim carrying empty hook dicts and a forward hook registered on the defining module, compiling a function that calls an `nn.Module` matches eager and runs the hook, where the parent raised `InternalTorchDynamoError: KeyError: <id>` out of guard construction, `<id>` the hook handle's id (`0` in a fresh process, as above). Through an artifact: one captured under the rebind with a `guard_filter_fn` that keeps global guards roots its hook-dict guards at `__import_torch`, and a load seeds that name; the parent's roots at the module's own alias, which a load seeds through `importlib.import_module`, so in a loading process under the same rebind its guards read the shim's dicts. Out of scope here, and the same on the parent and at this commit: the mirror ordering. A capture in a process where the alias binds the defining module takes the alias branch -- the predicate compares `global_scope[alias]` with the module, and they are one object -- so the artifact roots its hook-dict guards at `__import_torch_dot_nn_dot_modules_dot_module`; loaded into a process that has rebound `sys.modules["torch.nn.modules.module"]`, `_seed_guard_scope` (`aot_compile.py:854-859`) binds that alias with `importlib.import_module`, the shim, and builds the guards from the shim's dicts (measured on an earlier revision of this tree: the seeded set is the alias, `scope[alias] is shim`, and the loaded `TYPE_MATCH` reads `type=<class 'dict'>`, the shim's, where the capture's read `OrderedDict`). No trace-time predicate can see that ordering: the rebind exists only in the loading process, and the artifact carries no identity guard on the root for a load to compare the seeded module against, since `MODULE_MATCH` reduces to `ID_MATCH` and both are in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`). The check would have to run at load, in `_seed_guard_scope` -- another file and another PR. What it decides today is bounded, and measured, in the FAQ below. Test Plan: ``` python test/dynamo/test_package.py -k test_import_alias_rebind_keeps_the_global_nn_hooks_visible python test/dynamo/test_aot_compile.py -k test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package python test/dynamo/test_package.py python test/dynamo/test_aot_compile.py ``` `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` joins the `test_import_alias` tests below it and replaces one of them: #197046's `test_import_alias_nn_hook_guards_read_the_live_entry_the_alias_binds`, which pinned, as the state this commit changes, that a forward hook on the defining module under the rebind raises `InternalTorchDynamoError` out of guard construction, is deleted here, because at this tree the raise it asserts no longer happens (measured: run against this tree's `symbolic_convert.py`, it fails with `InternalTorchDynamoError not raised`) and the new test is that pin's flip; the `InternalTorchDynamoError` import in `test_package.py`, which only it used, goes with it. It compiles a function calling an `nn.Module` once so the process has resolved the name, resets, rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts, registers a forward hook on the defining module and compiles again, pinning that the hook runs under compile as in eager (`fired == [mod, mod]`), that `compiled == eager`, that `torch.nn.modules.module` is still the defining module and that the alias holds the shim. In `finally` it removes the hook, restores `sys.modules`, pops both aliases from `fn.__globals__` -- the module's own and `__import_torch`, the fallback root, which the first, clean compile already binds through `IMPORT_NAME` and the fallback rebinds -- and both `_import_source_cache` entries. The hook is what makes the test load-bearing: without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only. It errors on the parent with `InternalTorchDynamoError: KeyError: 0` (measured by running this file's test against the parent's `symbolic_convert.py`; `0` is the handle id in a process that has registered no earlier hook). Two mutations of this tree fail it, measured on an earlier revision whose `nn_modules_globals_vt` is this one: the live entry as the value on `Tensor-likes are not close!` (6/6 mismatched, the hook skipped); the alias as the source unconditionally on `KeyError: 0`. The test's comment names the mechanism the parent's failure has, not the value-side mutation's: the bypass decision reads the VT's value (`_hooks_dict_len`, `nn_module.py:1375`, through `PythonModuleVariable.tp_getattro_impl`, which does `getattr(self.value, name)` on its `is_torch` branch, `misc.py:2030`), the defining module under either source, so it sees the hook either way; it is the `CLOSURE_MATCH` on the hook that reads through the source, `self.get(guard)` (`guards.py:3138`) evaluating `G[alias]._global_forward_hooks[<id>]` against the live scope as the guard is built, which is where the parent's traceback raises `KeyError: 0` (measured: `build_guards -> CLOSURE_MATCH -> get -> get_value -> eval`). `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` captures `fn(m, x)`, `m` a `ParentWithChildModule` passed as an argument so the artifact has no user global, under `patch.dict(sys.modules, {name: shim})` with `keep_global_guards`, serializes it, and pins on the guards state the shape of the guards `get_global_source_name` resolves to `__import_torch`: exactly the four `G['__import_torch'].nn.modules.module._global_*` names, the walk and not only the root, so a change that kept the root and dropped the walk, or walked from another base, fails it. It then pins that `_names_a_missing_global` returns `False` for every recorded global; at this tree that holds by construction, every root being a prefixed alias, and the comment says it stays as the regression guard against a root minted by id. It loads the artifact with a fresh `guard_globals=` scope, still under the rebind, and pins `_has_global_guards` `False`, the seeded names exactly `{"__import_torch"}`, and the call equal to eager. It fails with the id-minted root of this commit's earlier revision (`install_global_by_id("___nn_modules_module", module)`, re-applied to that tree as a mutant) at the `_names_a_missing_global` pin (`True is not false : ___nn_modules_module_<id>_c0`), and on the parent at the guard-shape pin (measured against the parent's `symbolic_convert.py`: the set of guards resolving to `__import_torch` is empty there, the four missing). It registers no hook: see the FAQ below on why. It pops the alias's and `__import_torch`'s `_import_source_cache` entries through `addCleanup`, so an assertion failing inside the `patch.dict` block cannot leave the shim cached; the `__import_torch` binding the capture writes into this module's dict is stripped by `_hide_leaked_dynamo_globals`' cleanup. Whole files at this tree: `test_package.py` 101 tests, OK (skipped=40, expected failures=1); `test_aot_compile.py` 208 tests, OK (skipped=6). ``` lintrunner --take RUFF,PYFMT,GB_REGISTRY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py test/dynamo/test_package.py test/dynamo/test_aot_compile.py lintrunner --take PYREFLY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py ``` PYREFLY reports nothing in the four files this commit touches; its seven findings are in `torch/_dynamo/guards.py` and `torch/_native/cutedsl/hw_caps.py`, neither of which this commit changes. > **FAQ: `nn_modules_globals_vt` still takes its value from a fixed module object while its source comes from `import_source`, which now binds live `sys.modules`. Fix that too -- the divergence silently decides graph shape.** > > Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right. The value has to be the defining module: the dicts the runtime consults are read by `nn.Module._call_impl` through its own `__globals__`, the defining module's `__dict__`, never through the alias, so that is what the bypass decision must read; `convert_frame.py:1371-1376` reads the same dicts through the same attribute chain. Taking the live entry instead, measured with the alias on a shim carrying empty dicts and a forward hook registered on the defining module: the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched). Keeping the defining module as the value with the alias as the source, the shape of the two commits below, is what the earlier answer measured as unobservable -- and it is, while the defining module has no hooks, because the guards are one `TYPE_MATCH` per dict; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]`, `<id>` being `RemovableHandle.next_id` at registration (`0` in a process that has registered no earlier hook), which resolves on the shim and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. So the source now follows the value: the alias while `self.output.global_scope[alias]` is the defining module, otherwise the `torch` package's alias walking `.nn.modules.module`, the attributes the value is read through. The premise that drives the `IMPORT_NAME` fix -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. > **FAQ: the `nn_modules_globals_vt` value/source divergence is documented and hand-measured but not pinned by any test; a test that rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts and asserts a compiled `nn.Module` forward still matches eager would convert the comment into a check.** > > Added as `test_import_alias_rebind_keeps_the_global_nn_hooks_visible`, with one addition to the suggested shape that turned out to matter: a forward hook registered on the defining module. Without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only; with it, the hand measurement's conclusion fell over (previous FAQ), and the test now kills both alternatives -- the live value on a numeric mismatch, the unconditional alias source on `KeyError: 0`, which is what the two commits below produce. It asserts the hook ran once under eager and once more under compile, `compiled == eager`, `torch.nn.modules.module is real` and that the alias holds the shim, and in `finally` removes the hook, restores `sys.modules`, and pops both aliases (`__import_torch` is the fallback root) from `fn.__globals__` and both entries from `_import_source_cache`. > **FAQ: `___nn_modules_module_*` is a fourth Dynamo-minted global family that `aot_compile.py` enumerates nowhere: add the prefix to `_MINTED_GLOBAL_PREFIXES`, seed it in `_seed_guard_scope` with a `CleanupHook.disown`, subtract it in `_has_global_guards`, and update the completeness comment.** > > The family is gone instead. The fallback root is now the `torch` package's `__import_torch` alias with `.nn.modules.module` walked as `AttrSource`s, so every name a guard here can be rooted at is an `__import_*` alias, the first family in that tuple: `_seed_guard_scope` seeds it from `import_sources`, `_has_global_guards` subtracts it, `_names_a_missing_global` recognizes the prefix, and `import_source` binds it by plain assignment, so there is no `CleanupHook` to disown. All three consequences the review derived were reproduced first with the id-minted name (nothing seeded, `_has_global_guards` `True` with no user global, `KeyError on G['___nn_modules_module_<id>_c0']` reported as a global to define) and are absent with this root, which `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` pins. The `torch` package rather than `torch.nn.modules`: the chain then mirrors `torch.nn.modules.module`, the expression the value is read through, and a fixture that rebinds `sys.modules["torch"]` itself leaves nothing in Dynamo working. The completeness comment above the tuple (`aot_compile.py:75-93`) is reworded rather than extended: it said a family belongs in the tuple once a serializable guard is rooted at a `GlobalSource` on one of its names, and `_guard_source_globals` (`aot_compile.py:595`) reads "rooted at" as the `originating_source` IS a `GlobalSource`, which no hook-dict guard here satisfies (their sources are the `AttrSource` chain; that helper returns `set()` for this artifact, measured), so by that reading the family would be out of scope while all three sites act on the name. The reading the three sites share is `get_global_source_name` (`source.py:1329`), which walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) fills `global_scope` with; the comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as that helper decides it, and names these guards as the example. No name outside the three families resolves that way. > **FAQ: why does the artifact test register no hook, and why does it not pin that a hook registered after the load fails the loaded guards?** > > Two measured reasons, neither this commit's to change. First, with a hook on the defining module under the rebind, the capture never reaches the guard-scope sites: the hook makes the trace inline `_call_impl`, whose `__globals__` is the defining module's dict, and `_registered_module_for_globals` resolves `sys.modules[__name__]` to the shim, whose dict is a different object, so `get_globals_source_and_value` falls to the `___unnamed_scope` branch and records the defining module's whole `__dict__` under it; the guards pickler then writes that dict by value and pickles its `T = TypeVar("T")` by qualified name through `sys.modules`, which is the shim, and `aot_compile` raises `PackageError: PicklingError: Can't pickle ~T: attribute lookup T on torch.nn.modules.module failed` (the parent raises `KeyError: 0` earlier on the same input). Second, a hook registered after a compile is not guarded at all, in process and without any rebind: the global hook dicts guard as `TYPE_MATCH` only, under both values of `skip_nnmodule_hook_guards` -- `EMPTY_NN_MODULE_HOOKS_DICT` is installed for the instance's own hook attributes (`nn_module.py:1563-1591`), not for the module globals read here -- so a global forward hook registered after a `torch.compile` call is skipped by the compiled function with no recompile (measured on an earlier revision of this tree: `frame_count` 1, hook fired 0, result differs from eager), which `config.py:458-461` documents as the accepted unsafety. A loaded artifact inherits exactly that, so a hook-after-load phase would pin the same `TYPE_MATCH` pass on every tree. > **FAQ: the fix is conditioned on trace-time state, so the mirror ordering stays silently wrong: a capture in a clean process roots at `__import_torch_dot_nn_dot_modules_dot_module`, and a load into a process that has rebound `sys.modules["torch.nn.modules.module"]` has `_seed_guard_scope` seed that alias with `importlib.import_module`, the shim, whose four empty hook dicts pass the `TYPE_MATCH`es, so the loaded function bypasses `_call_impl` and skips a global hook registered on the real module. Handle it, or state that the ordering is out of scope.** > > Out of scope, stated in the message. The handling would be a load-time change in `aot_compile._seed_guard_scope` -- another file and another PR -- because no predicate in `nn_modules_globals_vt` runs where the rebind is: it runs in the capturing process, where the alias and the defining module are one object, and the artifact has no identity guard on the root for a load to check, `MODULE_MATCH`/`ID_MATCH` being unserializable. Measured on an earlier revision of this tree to size what is left. The seeding half is as the finding says: a hookless `fn(m, x)` capture with `keep_global_guards`, deserialized with a fresh `guard_globals=` under `patch.dict(sys.modules, {name: shim})`, seeds `{"__import_torch_dot_nn_dot_modules_dot_module"}` bound to the shim, and its hook-dict guards are built from the shim's dicts (`type=<class 'dict'>` in the loaded tree, `OrderedDict` in the capture's). The consequence half is narrower: a global forward hook registered on the defining module in the loading process is skipped by that load -- and equally by the clean load of the same artifact, whose alias is seeded with the defining module (`loaded fired=[]`, output equal to the hookless eager, in both). Empty dicts guard as `TYPE_MATCH` only, so the rebind changes which module's dicts the guards read, not what they decide; a hook the capture did not see is the accepted unsafety of the previous FAQ, rebind or not. The shape where the root would decide the outcome needs a capture-time hook, and there the four-dict shim does not pass silently: that capture carries `DICT_LENGTH`/`DICT_CONTAINS`/`EQUALS_MATCH` guards on the alias's hook dicts, `_global_forward_hooks_with_kwargs` among them, and its rebound load fails inside `deserialize` with `AttributeError: module 'torch.nn.modules.module' has no attribute '_global_forward_hooks_with_kwargs'` out of `TYPE_MATCH` creation (`guards.py:2425`), where the clean load of the same artifact runs the hook registered in the loading process. A shim carrying every dict `_call_impl` reads was not measured. > **FAQ: `assertEqual(set(scope) - before, {"__import_torch"})` is the only assertion in the artifact test that discriminates against the parent, and it couples to `keep_global_guards` dropping `MODULE_MATCH`; `assertIn("__import_torch", ...)` plus `assertNotIn(nn_alias, ...)` would state the intent without that coupling.** > > Kept exact, and no longer the only discriminating pin: the guard-shape assertion added above it fails first on the parent (measured: the set of guards resolving to `__import_torch` is empty there). The exact set is the claim this message makes -- the load seeds exactly the one name the kept guards resolve through -- and the coupling is to serialization, not to the filter's choice: `MODULE_MATCH` is in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`), so any filter that lets an artifact serialize drops it, and a second seeded alias would mean a second root some serializable guard resolves through, which is what the pin should catch rather than admit. > **FAQ: `import_source(module.__name__)` is called for its side effects even when its `GlobalSource` is discarded: the alias is recorded in `import_sources`, bound in `f_globals`, and `CompilePackage.install` binds it in every loading process. Check `sys.modules` first and skip the call.** > > The read-back of `global_scope[alias]` after the call is the check, and the comment now says so: it is the binding a guard rooted at the alias reads, and `import_source` is what decides it -- the live entry, or `_import_source_cache` for a name since removed from `sys.modules` or blocked with `None`. Reading `sys.modules` here would duplicate that decision in a second place with its own corner cases. The recorded-but-unread alias is the ordinary state of an `import_sources` entry, not a new one: `test_load_seeds_exactly_the_recorded_globals` asserts `len(guarded) < len(import_sources)` on an artifact whose only guarded alias is this same `__import_torch_dot_nn_dot_modules_dot_module`, and the capture in the new artifact test records six aliases for one guarded root. `install` binding it to the shim in a still-rebound loading process binds a name nothing reads. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: 1ce23b6 Pull-Request: #197135
[ghstack-poisoned]
… when the alias binds another Split for review budget from `[dynamo] Bind the import alias to the live sys.modules entry` (#197046), two commits below (`[dynamo] Serve a removed or blocked import name from what the alias last bound`, split from the same commit, sits between): that one makes the `__import_*` alias bind the live `sys.modules` entry; this one makes `nn_modules_globals_vt` stop rooting its guards at that alias once it binds a module other than the one whose dicts the VT reads. `nn_modules_globals_vt` reads the four global hook dicts to decide whether a module call may bypass `_call_impl`, and it has to read the dicts `_call_impl` itself reads through its own `__globals__`: the defining module's, `torch.nn.modules.module`, which no `sys.modules` rebind moves (`convert_frame.py:1371-1376` reads the same four dicts through the same attribute chain). Its source was the `__import_torch_dot_nn_dot_modules_dot_module` alias unconditionally. Below this commit that alias binds the live `sys.modules` entry, so a program that rebinds `sys.modules["torch.nn.modules.module"]` -- a test fixture, a `mock.patch.dict(sys.modules, ...)` -- leaves the VT's value and its source naming different objects. That is unobservable while the defining module has no hooks, because empty dicts guard as one `TYPE_MATCH` each; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]` -- `<id>` the handle's `RemovableHandle.next_id` at registration, a process-global counter (`torch/utils/hooks.py:22-27`), so `0` only in a process that has registered no earlier hook -- which resolves on the other module and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. The two commits below both have it; #197256, whose memoized `_import_module` still decided the alias, ran the hook when the name had been resolved before the rebind and skipped it otherwise. The source now follows the value. It stays the alias while `self.output.global_scope[alias]` is the defining module, read back after `import_source` because that binding is what a guard rooted at the alias reads. Otherwise it is the `torch` package's own alias walking `.nn.modules.module` -- the attributes the value itself is read through, which the rebind does not move -- so the guards become `G['__import_torch'].nn.modules.module._global_forward_hooks` and so on. Not a name minted by id, which an earlier revision of this commit installed through `install_global_by_id("___nn_modules_module", module)`: `aot_compile.py` enumerates the global names Dynamo mints by prefix and argues the list complete (`_MINTED_GLOBAL_PREFIXES`, `aot_compile.py:75-93`), and a fourth family fails all three places that read it. Measured with an artifact captured under the rebind through `torch.compile(...).aot_compile` with a `guard_filter_fn` that keeps global guards, then loaded with a fresh `guard_globals=` scope: `_seed_guard_scope` (`aot_compile.py:854-872`) seeds `import_sources` aliases and `___unnamed_scope` names and so seeded nothing; `_has_global_guards` (`aot_compile.py:724`) subtracts only `import_sources` aliases and so was `True` for an artifact with no user global; the load then failed `KeyError on G['___nn_modules_module_<id>_c0']` and `_names_a_missing_global` (`aot_compile.py:106-112`) classed it as a user global, so `_missing_global_hint` told the caller to define a name embedding `id()` of an object in the tracing process. Rooted at `__import_torch`, the same artifact's guarded globals are `{__import_torch, __builtins_dict___N}`, `_has_global_guards` is `False`, the load seeds exactly `__import_torch`, and the call matches eager. No new family, so the list in `aot_compile.py` stands; its criterion is reworded here, because these are the first guards on a minted name whose `originating_source` is a chain rather than the `GlobalSource` itself, and the repo has one helper for each reading of "rooted at". `_guard_source_globals` (`aot_compile.py:595`) keeps a guard whose source IS a `GlobalSource`, and returns nothing for `__import_torch` on this artifact (measured: `set()`); `get_global_source_name` (`source.py:1329`) walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) records `global_scope` through, so the name is in `_recorded_guard_globals` (`aot_compile.py:621`), which is what `_has_global_guards` subtracts from and `_seed_guard_scope` seeds. The comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as `get_global_source_name` decides it, with these guards as the example, so a future family with a chained root and its own prefix is not read as exempt. Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right: taking the live entry as the value, the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched, measured on an earlier revision of this tree); keeping the alias as the source unconditionally is the parent, `KeyError: <id>`. The premise that drives the `IMPORT_NAME` fix below -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. In a process that has not rebound `sys.modules` for torch's own module the source is the alias as before, so the guard shape and the recorded `import_sources` are unchanged (`test_aot_compile.py` pins `{"__import_torch_dot_nn_dot_modules_dot_module"}` as that set in two places; both pass here). Order to review: `nn_modules_globals_vt` in `torch/_dynamo/symbolic_convert.py` (the whole change is the `is not module` branch), then `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` in `test/dynamo/test_package.py` for the in-process case, then `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` in `test/dynamo/test_aot_compile.py` for the artifact, then the reworded completeness comment above `_MINTED_GLOBAL_PREFIXES` in `torch/_dynamo/aot_compile.py` (comment only; no code in that file changes). Behaviour change against the parent, pinned below. In process: with `sys.modules["torch.nn.modules.module"]` rebound to a shim carrying empty hook dicts and a forward hook registered on the defining module, compiling a function that calls an `nn.Module` matches eager and runs the hook, where the parent raised `InternalTorchDynamoError: KeyError: <id>` out of guard construction, `<id>` the hook handle's id (`0` in a fresh process, as above). Through an artifact: one captured under the rebind with a `guard_filter_fn` that keeps global guards roots its hook-dict guards at `__import_torch`, and a load seeds that name; the parent's roots at the module's own alias, which a load seeds through `importlib.import_module`, so in a loading process under the same rebind its guards read the shim's dicts. Out of scope here, and the same on the parent and at this commit: the mirror ordering. A capture in a process where the alias binds the defining module takes the alias branch -- the predicate compares `global_scope[alias]` with the module, and they are one object -- so the artifact roots its hook-dict guards at `__import_torch_dot_nn_dot_modules_dot_module`; loaded into a process that has rebound `sys.modules["torch.nn.modules.module"]`, `_seed_guard_scope` (`aot_compile.py:854-859`) binds that alias with `importlib.import_module`, the shim, and builds the guards from the shim's dicts (measured on an earlier revision of this tree: the seeded set is the alias, `scope[alias] is shim`, and the loaded `TYPE_MATCH` reads `type=<class 'dict'>`, the shim's, where the capture's read `OrderedDict`). No trace-time predicate can see that ordering: the rebind exists only in the loading process, and the artifact carries no identity guard on the root for a load to compare the seeded module against, since `MODULE_MATCH` reduces to `ID_MATCH` and both are in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`). The check would have to run at load, in `_seed_guard_scope` -- another file and another PR. What it decides today is bounded, and measured, in the FAQ below. Test Plan: ``` python test/dynamo/test_package.py -k test_import_alias_rebind_keeps_the_global_nn_hooks_visible python test/dynamo/test_aot_compile.py -k test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package python test/dynamo/test_package.py python test/dynamo/test_aot_compile.py ``` `test_import_alias_rebind_keeps_the_global_nn_hooks_visible` joins the `test_import_alias` tests below it and replaces one of them: #197046's `test_import_alias_nn_hook_guards_read_the_live_entry_the_alias_binds`, which pinned, as the state this commit changes, that a forward hook on the defining module under the rebind raises `InternalTorchDynamoError` out of guard construction, is deleted here, because at this tree the raise it asserts no longer happens (measured: run against this tree's `symbolic_convert.py`, it fails with `InternalTorchDynamoError not raised`) and the new test is that pin's flip; the `InternalTorchDynamoError` import in `test_package.py`, which only it used, goes with it. It compiles a function calling an `nn.Module` once so the process has resolved the name, resets, rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts, registers a forward hook on the defining module and compiles again, pinning that the hook runs under compile as in eager (`fired == [mod, mod]`), that `compiled == eager`, that `torch.nn.modules.module` is still the defining module and that the alias holds the shim. In `finally` it removes the hook, restores `sys.modules`, pops both aliases from `fn.__globals__` -- the module's own and `__import_torch`, the fallback root, which the first, clean compile already binds through `IMPORT_NAME` and the fallback rebinds -- and both `_import_source_cache` entries. The hook is what makes the test load-bearing: without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only. It errors on the parent with `InternalTorchDynamoError: KeyError: 0` (measured by running this file's test against the parent's `symbolic_convert.py`; `0` is the handle id in a process that has registered no earlier hook). Two mutations of this tree fail it, measured on an earlier revision whose `nn_modules_globals_vt` is this one: the live entry as the value on `Tensor-likes are not close!` (6/6 mismatched, the hook skipped); the alias as the source unconditionally on `KeyError: 0`. The test's comment names the mechanism the parent's failure has, not the value-side mutation's: the bypass decision reads the VT's value (`_hooks_dict_len`, `nn_module.py:1375`, through `PythonModuleVariable.tp_getattro_impl`, which does `getattr(self.value, name)` on its `is_torch` branch, `misc.py:2030`), the defining module under either source, so it sees the hook either way; it is the `CLOSURE_MATCH` on the hook that reads through the source, `self.get(guard)` (`guards.py:3138`) evaluating `G[alias]._global_forward_hooks[<id>]` against the live scope as the guard is built, which is where the parent's traceback raises `KeyError: 0` (measured: `build_guards -> CLOSURE_MATCH -> get -> get_value -> eval`). `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` captures `fn(m, x)`, `m` a `ParentWithChildModule` passed as an argument so the artifact has no user global, under `patch.dict(sys.modules, {name: shim})` with `keep_global_guards`, serializes it, and pins on the guards state the shape of the guards `get_global_source_name` resolves to `__import_torch`: exactly the four `G['__import_torch'].nn.modules.module._global_*` names, the walk and not only the root, so a change that kept the root and dropped the walk, or walked from another base, fails it. It then pins that `_names_a_missing_global` returns `False` for every recorded global; at this tree that holds by construction, every root being a prefixed alias, and the comment says it stays as the regression guard against a root minted by id. It loads the artifact with a fresh `guard_globals=` scope, still under the rebind, and pins `_has_global_guards` `False`, the seeded names exactly `{"__import_torch"}`, and the call equal to eager. It fails with the id-minted root of this commit's earlier revision (`install_global_by_id("___nn_modules_module", module)`, re-applied to that tree as a mutant) at the `_names_a_missing_global` pin (`True is not false : ___nn_modules_module_<id>_c0`), and on the parent at the guard-shape pin (measured against the parent's `symbolic_convert.py`: the set of guards resolving to `__import_torch` is empty there, the four missing). It registers no hook: see the FAQ below on why. It pops the alias's and `__import_torch`'s `_import_source_cache` entries through `addCleanup`, so an assertion failing inside the `patch.dict` block cannot leave the shim cached; the `__import_torch` binding the capture writes into this module's dict is stripped by `_hide_leaked_dynamo_globals`' cleanup. Whole files at this tree: `test_package.py` 101 tests, OK (skipped=40, expected failures=1); `test_aot_compile.py` 208 tests, OK (skipped=6). ``` lintrunner --take RUFF,PYFMT,GB_REGISTRY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py test/dynamo/test_package.py test/dynamo/test_aot_compile.py lintrunner --take PYREFLY torch/_dynamo/symbolic_convert.py torch/_dynamo/aot_compile.py ``` PYREFLY reports nothing in the four files this commit touches; its seven findings are in `torch/_dynamo/guards.py` and `torch/_native/cutedsl/hw_caps.py`, neither of which this commit changes. > **FAQ: `nn_modules_globals_vt` still takes its value from a fixed module object while its source comes from `import_source`, which now binds live `sys.modules`. Fix that too -- the divergence silently decides graph shape.** > > Fixed on the source side, not the value side, because the two alternatives fail in opposite directions and only one of them is right. The value has to be the defining module: the dicts the runtime consults are read by `nn.Module._call_impl` through its own `__globals__`, the defining module's `__dict__`, never through the alias, so that is what the bypass decision must read; `convert_frame.py:1371-1376` reads the same dicts through the same attribute chain. Taking the live entry instead, measured with the alias on a shim carrying empty dicts and a forward hook registered on the defining module: the trace sees no hooks, bypasses `_call_impl`, and the compiled function skips the hook eager runs (`Tensor-likes are not close!`, 6/6 mismatched). Keeping the defining module as the value with the alias as the source, the shape of the two commits below, is what the earlier answer measured as unobservable -- and it is, while the defining module has no hooks, because the guards are one `TYPE_MATCH` per dict; register one and the dict VT installs a `CLOSURE_MATCH` on `G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]`, `<id>` being `RemovableHandle.next_id` at registration (`0` in a process that has registered no earlier hook), which resolves on the shim and raises `KeyError: <id>` out of guard construction as an `InternalTorchDynamoError`. So the source now follows the value: the alias while `self.output.global_scope[alias]` is the defining module, otherwise the `torch` package's alias walking `.nn.modules.module`, the attributes the value is read through. The premise that drives the `IMPORT_NAME` fix -- guard what the bytecode pushed -- has nothing to attach to here, because no bytecode pushes a module on this path. > **FAQ: the `nn_modules_globals_vt` value/source divergence is documented and hand-measured but not pinned by any test; a test that rebinds `sys.modules["torch.nn.modules.module"]` to a shim with empty hook dicts and asserts a compiled `nn.Module` forward still matches eager would convert the comment into a check.** > > Added as `test_import_alias_rebind_keeps_the_global_nn_hooks_visible`, with one addition to the suggested shape that turned out to matter: a forward hook registered on the defining module. Without it the test passes under either value and either source, because empty dicts guard as `TYPE_MATCH` only; with it, the hand measurement's conclusion fell over (previous FAQ), and the test now kills both alternatives -- the live value on a numeric mismatch, the unconditional alias source on `KeyError: 0`, which is what the two commits below produce. It asserts the hook ran once under eager and once more under compile, `compiled == eager`, `torch.nn.modules.module is real` and that the alias holds the shim, and in `finally` removes the hook, restores `sys.modules`, and pops both aliases (`__import_torch` is the fallback root) from `fn.__globals__` and both entries from `_import_source_cache`. > **FAQ: `___nn_modules_module_*` is a fourth Dynamo-minted global family that `aot_compile.py` enumerates nowhere: add the prefix to `_MINTED_GLOBAL_PREFIXES`, seed it in `_seed_guard_scope` with a `CleanupHook.disown`, subtract it in `_has_global_guards`, and update the completeness comment.** > > The family is gone instead. The fallback root is now the `torch` package's `__import_torch` alias with `.nn.modules.module` walked as `AttrSource`s, so every name a guard here can be rooted at is an `__import_*` alias, the first family in that tuple: `_seed_guard_scope` seeds it from `import_sources`, `_has_global_guards` subtracts it, `_names_a_missing_global` recognizes the prefix, and `import_source` binds it by plain assignment, so there is no `CleanupHook` to disown. All three consequences the review derived were reproduced first with the id-minted name (nothing seeded, `_has_global_guards` `True` with no user global, `KeyError on G['___nn_modules_module_<id>_c0']` reported as a global to define) and are absent with this root, which `test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package` pins. The `torch` package rather than `torch.nn.modules`: the chain then mirrors `torch.nn.modules.module`, the expression the value is read through, and a fixture that rebinds `sys.modules["torch"]` itself leaves nothing in Dynamo working. The completeness comment above the tuple (`aot_compile.py:75-93`) is reworded rather than extended: it said a family belongs in the tuple once a serializable guard is rooted at a `GlobalSource` on one of its names, and `_guard_source_globals` (`aot_compile.py:595`) reads "rooted at" as the `originating_source` IS a `GlobalSource`, which no hook-dict guard here satisfies (their sources are the `AttrSource` chain; that helper returns `set()` for this artifact, measured), so by that reading the family would be out of scope while all three sites act on the name. The reading the three sites share is `get_global_source_name` (`source.py:1329`), which walks a `ChainedSource` to its base and is what `prune_variable` (`guards.py:5159`) fills `global_scope` with; the comment now says a family belongs in the tuple once a serializable guard resolves through a `GlobalSource` on the name, as that helper decides it, and names these guards as the example. No name outside the three families resolves that way. > **FAQ: why does the artifact test register no hook, and why does it not pin that a hook registered after the load fails the loaded guards?** > > Two measured reasons, neither this commit's to change. First, with a hook on the defining module under the rebind, the capture never reaches the guard-scope sites: the hook makes the trace inline `_call_impl`, whose `__globals__` is the defining module's dict, and `_registered_module_for_globals` resolves `sys.modules[__name__]` to the shim, whose dict is a different object, so `get_globals_source_and_value` falls to the `___unnamed_scope` branch and records the defining module's whole `__dict__` under it; the guards pickler then writes that dict by value and pickles its `T = TypeVar("T")` by qualified name through `sys.modules`, which is the shim, and `aot_compile` raises `PackageError: PicklingError: Can't pickle ~T: attribute lookup T on torch.nn.modules.module failed` (the parent raises `KeyError: 0` earlier on the same input). Second, a hook registered after a compile is not guarded at all, in process and without any rebind: the global hook dicts guard as `TYPE_MATCH` only, under both values of `skip_nnmodule_hook_guards` -- `EMPTY_NN_MODULE_HOOKS_DICT` is installed for the instance's own hook attributes (`nn_module.py:1563-1591`), not for the module globals read here -- so a global forward hook registered after a `torch.compile` call is skipped by the compiled function with no recompile (measured on an earlier revision of this tree: `frame_count` 1, hook fired 0, result differs from eager), which `config.py:458-461` documents as the accepted unsafety. A loaded artifact inherits exactly that, so a hook-after-load phase would pin the same `TYPE_MATCH` pass on every tree. > **FAQ: the fix is conditioned on trace-time state, so the mirror ordering stays silently wrong: a capture in a clean process roots at `__import_torch_dot_nn_dot_modules_dot_module`, and a load into a process that has rebound `sys.modules["torch.nn.modules.module"]` has `_seed_guard_scope` seed that alias with `importlib.import_module`, the shim, whose four empty hook dicts pass the `TYPE_MATCH`es, so the loaded function bypasses `_call_impl` and skips a global hook registered on the real module. Handle it, or state that the ordering is out of scope.** > > Out of scope, stated in the message. The handling would be a load-time change in `aot_compile._seed_guard_scope` -- another file and another PR -- because no predicate in `nn_modules_globals_vt` runs where the rebind is: it runs in the capturing process, where the alias and the defining module are one object, and the artifact has no identity guard on the root for a load to check, `MODULE_MATCH`/`ID_MATCH` being unserializable. Measured on an earlier revision of this tree to size what is left. The seeding half is as the finding says: a hookless `fn(m, x)` capture with `keep_global_guards`, deserialized with a fresh `guard_globals=` under `patch.dict(sys.modules, {name: shim})`, seeds `{"__import_torch_dot_nn_dot_modules_dot_module"}` bound to the shim, and its hook-dict guards are built from the shim's dicts (`type=<class 'dict'>` in the loaded tree, `OrderedDict` in the capture's). The consequence half is narrower: a global forward hook registered on the defining module in the loading process is skipped by that load -- and equally by the clean load of the same artifact, whose alias is seeded with the defining module (`loaded fired=[]`, output equal to the hookless eager, in both). Empty dicts guard as `TYPE_MATCH` only, so the rebind changes which module's dicts the guards read, not what they decide; a hook the capture did not see is the accepted unsafety of the previous FAQ, rebind or not. The shape where the root would decide the outcome needs a capture-time hook, and there the four-dict shim does not pass silently: that capture carries `DICT_LENGTH`/`DICT_CONTAINS`/`EQUALS_MATCH` guards on the alias's hook dicts, `_global_forward_hooks_with_kwargs` among them, and its rebound load fails inside `deserialize` with `AttributeError: module 'torch.nn.modules.module' has no attribute '_global_forward_hooks_with_kwargs'` out of `TYPE_MATCH` creation (`guards.py:2425`), where the clean load of the same artifact runs the hook registered in the loading process. A shim carrying every dict `_call_impl` reads was not measured. > **FAQ: `assertEqual(set(scope) - before, {"__import_torch"})` is the only assertion in the artifact test that discriminates against the parent, and it couples to `keep_global_guards` dropping `MODULE_MATCH`; `assertIn("__import_torch", ...)` plus `assertNotIn(nn_alias, ...)` would state the intent without that coupling.** > > Kept exact, and no longer the only discriminating pin: the guard-shape assertion added above it fails first on the parent (measured: the set of guards resolving to `__import_torch` is empty there). The exact set is the claim this message makes -- the load seeds exactly the one name the kept guards resolve through -- and the coupling is to serialization, not to the filter's choice: `MODULE_MATCH` is in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES` (`guards.py:5110-5119`), so any filter that lets an artifact serialize drops it, and a second seeded alias would mean a second root some serializable guard resolves through, which is what the pin should catch rather than admit. > **FAQ: `import_source(module.__name__)` is called for its side effects even when its `GlobalSource` is discarded: the alias is recorded in `import_sources`, bound in `f_globals`, and `CompilePackage.install` binds it in every loading process. Check `sys.modules` first and skip the call.** > > The read-back of `global_scope[alias]` after the call is the check, and the comment now says so: it is the binding a guard rooted at the alias reads, and `import_source` is what decides it -- the live entry, or `_import_source_cache` for a name since removed from `sys.modules` or blocked with `None`. Reading `sys.modules` here would duplicate that decision in a second place with its own corner cases. The recorded-but-unread alias is the ordinary state of an `import_sources` entry, not a new one: `test_load_seeds_exactly_the_recorded_globals` asserts `len(guarded) < len(import_sources)` on an artifact whose only guarded alias is this same `__import_torch_dot_nn_dot_modules_dot_module`, and the capture in the new artifact test records six aliases for one guarded root. `install` binding it to the shim in a still-rebound loading process binds a name nothing reads. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> ghstack-source-id: c29cfbc Pull-Request: #197135
Stack from ghstack (oldest at bottom):
Split for review budget from
[dynamo] Bind the import alias to the live sys.modules entry(#197046), the commit directly below: that one makes the__import_*alias bind the livesys.modulesentry; this one makesnn_modules_globals_vtstop rooting its guards at that alias once it binds amodule other than the one whose dicts the VT reads.
nn_modules_globals_vtreads the four global hook dicts to decide whether amodule call may bypass
_call_impl, and it has to read the dicts_call_implitself reads through its own
__globals__: the defining module's,torch.nn.modules.module, which nosys.modulesrebind moves(
convert_frame.py:1371-1376reads the same four dicts through the sameattribute chain). Its source was the
__import_torch_dot_nn_dot_modules_dot_modulealias unconditionally. Below this commit that alias binds the live
sys.modulesentry, so a program that rebinds
sys.modules["torch.nn.modules.module"]-- atest fixture, a
mock.patch.dict(sys.modules, ...)-- leaves the VT's valueand its source naming different objects. That is unobservable while the
defining module has no hooks, because empty dicts guard as one
TYPE_MATCHeach; register one and the dict VT installs a
CLOSURE_MATCHonG['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks[<id>]--
<id>the handle'sRemovableHandle.next_idat registration, aprocess-global counter (
torch/utils/hooks.py:22-27), so0only in a processthat has registered no earlier hook -- which resolves on the other module and
raises
KeyError: <id>out of guard construction as anInternalTorchDynamoError. The parent's parent, whosememoized
_import_modulehappened to hold the defining module, ran the hook.The source now follows the value. It stays the alias while
self.output.global_scope[alias]is the defining module, read back afterimport_sourcebecause that binding is what a guard rooted at the aliasreads. Otherwise it is the
torchpackage's own alias walking.nn.modules.module-- the attributes the value itself is read through, whichthe rebind does not move -- so the guards become
G['__import_torch'].nn.modules.module._global_forward_hooksand so on. Not aname minted by id, which an earlier revision of this commit installed through
install_global_by_id("___nn_modules_module", module):aot_compile.pyenumerates the global names Dynamo mints by prefix and argues the list
complete (
_MINTED_GLOBAL_PREFIXES,aot_compile.py:74-89), and a fourthfamily fails all three places that read it. Measured with an artifact captured
under the rebind through
torch.compile(...).aot_compilewith aguard_filter_fnthat keeps global guards, then loaded with a freshguard_globals=scope:_seed_guard_scope(aot_compile.py:854-872) seedsimport_sourcesaliases and___unnamed_scopenames and so seeded nothing;_has_global_guards(aot_compile.py:724) subtracts onlyimport_sourcesaliases and so was
Truefor an artifact with no user global; the load thenfailed
KeyError on G['___nn_modules_module_<id>_c0']and_names_a_missing_global(aot_compile.py:106-112) classed it as a userglobal, so
_missing_global_hinttold the caller to define a name embeddingid()of an object in the tracing process. Rooted at__import_torch, thesame artifact's guarded globals are
{__import_torch, __builtins_dict___N},_has_global_guardsisFalse, the load seeds exactly__import_torch, andthe call matches eager. No new family, so the completeness argument in
aot_compile.pystands as written.Fixed on the source side, not the value side, because the two alternatives
fail in opposite directions and only one of them is right: taking the live
entry as the value, the trace sees no hooks, bypasses
_call_impl, and thecompiled function skips the hook eager runs (
Tensor-likes are not close!,6/6 mismatched, measured at this tree); keeping the alias as the source
unconditionally is the parent,
KeyError: <id>. The premise that drives theIMPORT_NAMEfix below -- guard what the bytecode pushed -- has nothing toattach to here, because no bytecode pushes a module on this path. In a process
that has not rebound
sys.modulesfor torch's own module the source is thealias as before, so the guard shape and the recorded
import_sourcesareunchanged (
test_aot_compile.pypins{"__import_torch_dot_nn_dot_modules_dot_module"}as that set in two places;both pass here).
Order to review:
nn_modules_globals_vtintorch/_dynamo/symbolic_convert.py(the whole change is the
is not modulebranch), thentest_import_alias_rebind_keeps_the_global_nn_hooks_visibleintest/dynamo/test_package.pyfor the in-process case, thentest_load_seeds_a_rebound_nn_module_alias_through_the_torch_packageintest/dynamo/test_aot_compile.pyfor the artifact.Behaviour change against the parent, pinned below. In process: with
sys.modules["torch.nn.modules.module"]rebound to a shim carrying empty hookdicts and a forward hook registered on the defining module, compiling a
function that calls an
nn.Modulematches eager and runs the hook, where theparent raised
InternalTorchDynamoError: KeyError: 0out of guardconstruction. Through an artifact: one captured under the rebind with a
guard_filter_fnthat keeps global guards roots its hook-dict guards at__import_torch, and a load seeds that name; the parent's roots at themodule's own alias, which a load seeds through
importlib.import_module, soin a loading process under the same rebind its guards read the shim's dicts.
Out of scope here, and the same on the parent and at this commit: the mirror
ordering. A capture in a process where the alias binds the defining module
takes the alias branch -- the predicate compares
global_scope[alias]with themodule, and they are one object -- so the artifact roots its hook-dict guards
at
__import_torch_dot_nn_dot_modules_dot_module; loaded into a process thathas rebound
sys.modules["torch.nn.modules.module"],_seed_guard_scope(
aot_compile.py:854-859) binds that alias withimportlib.import_module,the shim, and builds the guards from the shim's dicts (measured on this tree:
the seeded set is the alias,
scope[alias] is shim, and the loadedTYPE_MATCHreadstype=<class 'dict'>, the shim's, where the capture's readOrderedDict). No trace-time predicate can see that ordering: the rebindexists only in the loading process, and the artifact carries no identity guard
on the root for a load to compare the seeded module against, since
MODULE_MATCHreduces toID_MATCHand both are inUNSUPPORTED_SERIALIZATION_GUARD_TYPES(guards.py:5110-5119). The checkwould have to run at load, in
_seed_guard_scope-- another file and anotherPR. What it decides today is bounded, and measured, in the FAQ below.
Test Plan:
test_import_alias_rebind_keeps_the_global_nn_hooks_visiblejoins theprevious commit's ten
test_import_aliascases. It compiles a functioncalling an
nn.Moduleonce so the process has resolved the name, resets,rebinds
sys.modules["torch.nn.modules.module"]to a shim with empty hookdicts, registers a forward hook on the defining module and compiles again,
pinning that the hook runs under compile as in eager (
fired == [mod, mod]),that
compiled == eager, thattorch.nn.modules.moduleis still the definingmodule and that the alias holds the shim. In
finallyit removes the hook,restores
sys.modules, pops both aliases fromfn.__globals__-- themodule's own and
__import_torch, the fallback root, which the first, cleancompile already binds through
IMPORT_NAME(symbolic_convert.py:2617-2619)and the fallback rebinds -- and both
_import_source_cacheentries. Measuredby running the test in-process and reading the module dict and the cache after
it: before this revision it left
__import_torchbound and"torch"cached,now it leaves neither. The hook is what
makes the test load-bearing: without it the test passes under either value
and either source, because empty dicts guard as
TYPE_MATCHonly. It errorson the parent with
InternalTorchDynamoError: KeyError: 0(measured byrunning this file's test against the parent's
symbolic_convert.py;0isthe handle id in a process that has registered no earlier hook), and on the
parent's parent, the last commit with the memoized
_import_module, fails onassertIs(fn.__globals__[alias], shim)(that tree lacks_import_source_cache, so its import was guarded for that run). Two mutationsof this tree fail it: the live entry as the value on
Tensor-likes are not close!(6/6 mismatched, the hook skipped); the alias as the sourceunconditionally on
KeyError: 0.test_load_seeds_a_rebound_nn_module_alias_through_the_torch_packagecapturesfn(m, x),maParentWithChildModulepassed as an argument so the artifacthas no user global, under
patch.dict(sys.modules, {name: shim})withkeep_global_guards, serializes it, and pins on the guards state that_names_a_missing_globalreturnsFalsefor every recorded global (nonewould be reported as a name to define), then loads it with a fresh
guard_globals=scope, still under the rebind, and pins_has_global_guardsFalse, the seeded names exactly{"__import_torch"}, and the call equal toeager. It fails with the id-minted root of this commit's earlier revision
(
install_global_by_id("___nn_modules_module", module), re-applied to thistree as a mutant) at the first pin (
True is not false : ___nn_modules_module_<id>_c0) and on the parent at the seeded set(
__import_torch_dot_nn_dot_modules_dot_module, not__import_torch). Itregisters no hook: see the FAQ below on why. It pops the alias's and
__import_torch's_import_source_cacheentries throughaddCleanup, so anassertion failing inside the
patch.dictblock cannot leave the shim cached(the previous revision popped one entry after the block, outside any cleanup);
the
__import_torchbinding the capture writes into this module's dict isstripped by
_hide_leaked_dynamo_globals' cleanup. Measured in-process asabove: the previous revision left
_import_source_cache["torch"]; now neithername is in the module dict or the cache after the test.
Whole files at this tree:
test_package.py92 tests, OK (skipped=40, expectedfailures=1);
test_aot_compile.py288 tests, OK (skipped=6).PYREFLY reports nothing in the three files this commit touches; its findings
are in
torch/_dynamo/guards.pyandtorch/_native/cutedsl/hw_caps.py,neither of which this commit changes.
Authored with the assistance of Claude Code.
Co-Authored-By: Claude Fable 5.1 [email protected]
🤖 Generated with Claude Code