Skip to content

[dynamo] Root the global nn.Module hook guards at the defining module when the alias binds another - #197135

Closed
bobrenjc93 wants to merge 28 commits into
gh/bobrenjc93/1202/basefrom
gh/bobrenjc93/1202/head
Closed

bobrenjc93 wants to merge 28 commits into
gh/bobrenjc93/1202/basefrom
gh/bobrenjc93/1202/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Split for review budget from [dynamo] 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[<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 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: <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.

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.

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 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
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. 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 (symbolic_convert.py:2617-2619)
and the fallback rebinds -- and both _import_source_cache entries. Measured
by running the test in-process and reading the module dict and the cache after
it: before this revision it left __import_torch bound 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_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), and on the
parent's parent, the last commit with the memoized _import_module, fails on
assertIs(fn.__globals__[alias], shim) (that tree lacks
_import_source_cache, so its import was guarded for that run). 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 with the id-minted root of this commit's earlier revision
(install_global_by_id("___nn_modules_module", module), re-applied to this
tree 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). 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 previous revision popped one entry after the block, outside any cleanup);
the __import_torch binding the capture writes into this module's dict is
stripped by _hide_leaked_dynamo_globals' cleanup. Measured in-process as
above: the previous revision left _import_source_cache["torch"]; now neither
name is in the module dict or the cache after the test.

Whole files at this tree: test_package.py 92 tests, OK (skipped=40, expected
failures=1); test_aot_compile.py 288 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

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

FAQ: 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[<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 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 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 AttrSources, 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: 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_MATCHes, 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 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: 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]

🤖 Generated with Claude Code

[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 15, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 11 New Failures, 1 Unclassified Failure

As of commit 469c441 with merge base 51d4378 (image):

🟢 GREEN LIGHT - PR approved to be merged without human review:

  • Correctness
    • nn_modules_globals_vt still takes the defining module as the VT value, so the bypass decision at nn_module.py:1373-1398, which reads self.value, is unchanged
    • The new predicate cannot KeyError: import_source assigns global_scope[alias] on every returning path (symbolic_convert.py:2534)
    • The non-rebound path is byte-identical, since the predicate is false whenever the live sys.modules entry is the defining module
  • Guard-root plumbing
    • The fallback root __import_torch is an import_sources alias, so _seed_guard_scope seeds it and _has_global_guards subtracts it (aot_compile.py:771, :908)
    • get_global_source_name does walk ChainedSource.base (source.py:1329-1334), so the amended completeness comment at aot_compile.py:90-97 reads accurately
  • Testing
    • test_import_alias_rebind_keeps_the_global_nn_hooks_visible covers the in-process compile with a forward hook on the defining module
    • test_load_seeds_a_rebound_nn_module_alias_through_the_torch_package pins the guard walk and the seeded root across an artifact round-trip
    • The deleted test_import_alias_nn_hook_guards_read_the_live_entry_the_alias_binds pinned the parent's pre-fix KeyError, so removing it is required here
  • Scope
    • The logic change is the four-line is not module branch in torch/_dynamo/symbolic_convert.py; no public API, workflow, or CI-gate edits

reason: clean
Reviewed commit: 469c441

Inference job

🐛 Report a wrong verdict

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.

@bobrenjc93 bobrenjc93 changed the title [dynamo] Root the global nn.Module hook guards at the defining module when the alias binds another [no-ci] [dynamo] Root the global nn.Module hook guards at the defining module when the alias binds another Sep 15, 2026
bobrenjc93 added a commit that referenced this pull request Sep 15, 2026
… 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
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

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


Reviewed: the source-side fix and its test look right, but the new ___nn_modules_module_* global is a fourth Dynamo-minted global family that aot_compile.py is not taught about, and the comment there explicitly claims its list is complete.

PR Review: #197135 — details

PR Review: #197135

Summary

nn_modules_globals_vt stops rooting its hook-dict guards at the __import_torch_dot_nn_dot_modules_dot_module alias once that alias binds a module other than torch.nn.modules.module, falling back to an id-installed global. The value/source reasoning is sound and the new test is load-bearing, but the change mints a new global-name family that three places in torch/_dynamo/aot_compile.py enumerate by prefix and were not updated.

Infrastructure

___nn_modules_module_* is a fourth Dynamo-minted global family, and aot_compile.py enumerates exactly three. aot_compile.py:88-89:

_UNNAMED_SCOPE_PREFIX = "___unnamed_scope"
_MINTED_GLOBAL_PREFIXES = ("__import_", "__builtins_dict__", _UNNAMED_SCOPE_PREFIX)

The comment above it (aot_compile.py:74-87) does not merely list these — it argues the list is complete, and states the condition under which the argument has to be redone:

"The list is complete because a report here needs a serializable guard rooted at a GlobalSource on the name: every other minted family builds no Source (the codegen-only installs) or a guard type in UNSUPPORTED_SERIALIZATION_GUARD_TYPES, which ___unnamed_scope's was not -- so moving a type off that list means re-checking this one."

The new name fails that test. MODULE_MATCH, installed on the root by builder.py:1927-1940, is in UNSUPPORTED_SERIALIZATION_GUARD_TYPES (guards.py:5110-5119), so the root guard alone would not qualify. But the four AttrSource children — nn_module.py:1391-1397 reading _global_backward_pre_hooks, _global_backward_hooks, _global_forward_hooks, _global_forward_pre_hooks through misc.py:2023-2039 — build plain dict VTs whose guards (TYPE_MATCH / SEQUENCE_LENGTH) are not on that list. So a serializable guard rooted at a GlobalSource on the new name is exactly the shape the comment says makes a family belong in the tuple.

Three concrete consequences, all reachable with a guard_filter_fn that keeps global guards (the default aot_compile filter at aot_compile.py:1216-1225 drops g.is_global, but keep_global_guards — used at test_aot_compile.py:2200-2204 — does not):

  1. Misleading user advice. _names_a_missing_global (aot_compile.py:106-112) does not match["name"].strip("\"'").startswith(_MINTED_GLOBAL_PREFIXES). ___nn_modules_module_... matches no prefix, so a KeyError on G['___nn_modules_module_<id>_c<n>'] is classified as a missing user global and the load emits _missing_global_hint (aot_compile.py:908-960) telling the caller to define that name in their scope. It embeds id() of an object in the tracing process — no caller can define it. This is precisely the failure mode the ___unnamed_scope entry exists to prevent.

  2. Not seeded at load. _seed_guard_scope (aot_compile.py:777-906) seeds three families: import_sources aliases (854-856), ___unnamed_scope* names (868-872), and the builtins key. Nothing seeds ___nn_modules_module_*, so in a loading process the guard KeyErrors instead of resolving.

  3. _has_global_guards spuriously true. aot_compile.py:718-724 computes recorded_globals - aliases where aliases = set(runtime_env.import_sources), deliberately subtracting Dynamo's own aliases as "not user globals". The id-name is not an import_sources alias, so it survives the subtraction and the artifact reports itself as having user global guards.

Note the ___unnamed_scope seeding at aot_compile.py:868-872 also calls CleanupHook.disown — because install_global_by_id binds through install_global_unsafe, which installs a CleanupHook (output_graph.py:3578). The new site has the same property and would need the same treatment.

Reachability is narrow (requires the sys.modules rebind and a global-guard-keeping filter), but the codebase left an explicit instruction to re-check on exactly this change. Either add the prefix to _MINTED_GLOBAL_PREFIXES and seed/subtract it alongside ___unnamed_scope, or state in the commit why the family cannot reach serialization and amend the completeness argument in aot_compile.py:74-87 so the next reader does not have to re-derive it.

Fix this →

Testing

No coverage for the serialization/load path the change affects. The new test exercises in-process compile only. The three aot_compile.py sites above are precisely where the new name is unhandled, and the PR's own Test Plan runs test_aot_compile.py only for the two cases that pin import_sources == {"__import_torch_dot_nn_dot_modules_dot_module"} — i.e. the cases where the branch is not taken, so they cannot detect the gap. A test that rebinds sys.modules["torch.nn.modules.module"] and then round-trips through torch._dynamo.aot_compile with guard_filter_fn=keep_global_guards (the pattern at test_aot_compile.py:2200-2204) would pin whichever resolution is chosen above.

Code Quality

import_source is called for its side effects even when its return value is discarded. At symbolic_convert.py:2384-2387, import_source(module.__name__) is invoked unconditionally, then the resulting GlobalSource is thrown away in the rebind branch. Its side effects are not thrown away: it records output.import_sources[alias] and package.add_import_source(alias, module_name) (symbolic_convert.py:2500-2502) and writes f_globals[alias] = value (2508). So a precompile artifact records an alias no guard reads, and CompilePackage.install (package.py:1334-1340) then binds it in every loading process via importlib.import_module — in a still-rebound process, to the shim.

Reading global_scope[alias] after the call is deliberate and is the accurate check (it is what a guard rooted at the alias would read, which a bare sys.modules lookup would not capture once a previous compile or install has bound the alias). But that rationale is not in the comment, and the comment's "the module itself is installed otherwise" does not say the alias is still minted and recorded on the discarded path. Worth one line, since the alternative — checking sys.modules first and skipping import_source entirely — is the obvious reading and is subtly wrong.

Recommendation

Needs Discussion

The core fix is correct and the test kills both alternatives. What blocks approval is the aot_compile.py gap: the change adds a minted-global family to a codebase that enumerates them by prefix in three places and left a comment asking to be re-checked on exactly this event. Either wire the new prefix through those three sites (plus a round-trip test), or record in the commit message why the family provably cannot reach a serializable guard and update the completeness argument at aot_compile.py:74-87.

• branch `gh/bobrenjc93/1202/head`

@bobrenjc93 bobrenjc93 added ciflow/trunk Trigger trunk jobs on your pull request topic: not user facing topic category labels Sep 15, 2026
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 15, 2026
… 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
bobrenjc93 added a commit that referenced this pull request Sep 15, 2026
… 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
bobrenjc93 added a commit that referenced this pull request Sep 17, 2026
… 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]
bobrenjc93 added a commit that referenced this pull request Sep 17, 2026
… 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]
bobrenjc93 added a commit that referenced this pull request Sep 17, 2026
… 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]
bobrenjc93 added a commit that referenced this pull request Sep 18, 2026
… 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]
bobrenjc93 added a commit that referenced this pull request Sep 18, 2026
… 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]
bobrenjc93 added a commit that referenced this pull request Sep 18, 2026
… 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]
bobrenjc93 added a commit that referenced this pull request Sep 18, 2026
… 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]
bobrenjc93 added a commit that referenced this pull request Sep 18, 2026
… 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]
bobrenjc93 added a commit that referenced this pull request Sep 18, 2026
… 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]
bobrenjc93 added a commit that referenced this pull request Sep 18, 2026
… 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]
bobrenjc93 added a commit that referenced this pull request Sep 18, 2026
… 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
@bobrenjc93
bobrenjc93 marked this pull request as ready for review September 18, 2026 20:39
@bobrenjc93 bobrenjc93 changed the title [no-ci] [dynamo] Root the global nn.Module hook guards at the defining module when the alias binds another [dynamo] Root the global nn.Module hook guards at the defining module when the alias binds another Sep 19, 2026
@bobrenjc93 bobrenjc93 closed this Sep 20, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1202/head branch November 22, 2026 01:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant