Skip to content

[dynamo] Rebind a stale module alias instead of failing the trace - #196896

Closed
bobrenjc93 wants to merge 74 commits into
gh/bobrenjc93/1184/basefrom
gh/bobrenjc93/1184/head
Closed

bobrenjc93 wants to merge 74 commits into
gh/bobrenjc93/1184/basefrom
gh/bobrenjc93/1184/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

import_source mints __import_<mangled>, resolves the module it names and
writes it into self.output.global_scope, which is the traced frame's real
globals, a live module __dict__. Nothing removes that binding, so it outlives
the compile that minted it, and any later compile of any function in the same
module re-enters with the alias already bound. A writer other than this method
can have bound it, too: CompilePackage.install binds each recorded alias to
importlib.import_module(module_name) in the traced module's globals, and
AOTCompiledFunction._seed_guard_scope does the same into a scope its own
comment describes as possibly a user module's live namespace.

The write's collision check was an identity test against a memoized object:

# parent
value = _import_module(module_name)           # functools.cache'd: first resolution, for the life of the process
if not (alias not in f_globals or f_globals[alias] is value):
    raise AssertionError("expected alias not in f_globals or f_globals[alias] is value to be true")
f_globals[alias] = value

So after a sys.modules handover, the module install() bound into the slot
and the memoized object the next trace compares it against are two module
objects of the same name, and tracing died on a hard AssertionError that
restated the condition and named nothing:

import mypkg.helper                                        # traced once: alias memoized to module object A
sys.modules["mypkg.helper"] = fresh_copy                   # a lazy-import shim handing over, a mock.patch.dict, a fixture
package.install(backends)                                  # binds vars(mypkg.model)["__import_mypkg_dot_helper"] = importlib.import_module(...) -> B

torch.compile(other_fn_in_mypkg_model)(x)                  # a second trace in the same globals reaches import_source
# parent: AssertionError: expected alias not in f_globals or f_globals[alias] is value to be true
#         -- A is not B, the check fires, and AssertionError is in _compile's pass-through tuple: no eager fallback

Accept a same-name module and rebind; graph-break only on a real collision

A stale module object of the right name is not the collision the check exists
to catch, so accept it and rebind. The check is now if alias in f_globals,
and it graph-breaks only when the bound value is neither the object just
resolved nor a module whose own __name__ is this module name or the resolved
module's own __name__:

if alias in f_globals:
    bound = f_globals[alias]
    bound_name = object.__getattribute__(bound, "__dict__").get("__name__") if isinstance(bound, types.ModuleType) else None
    value_name = object.__getattribute__(value, "__dict__").get("__name__") if isinstance(value, types.ModuleType) else None
    accepted = (module_name, value_name) if value_name else (module_name,)
    if bound is not value and bound_name not in accepted:
        offender = type(bound).__name__ + (f" named {bound_name}" if bound_name is not None else "")
        unimplemented(gb_type="Import alias already bound",
                      context=f"{alias} for {module_name}: {offender}", ...)
f_globals[alias] = value

That still catches a non-module in the alias name and two module names
mangling onto one alias:

vars(mypkg.model)["__import_mypkg_dot_helper"] = "oops"          # a str in the slot
# Unsupported: Import alias already bound: __import_mypkg_dot_helper for mypkg.helper: str

vars(mypkg.model)["__import_a_dot_b"] = sys.modules["a_dot_b"]   # a.b and a_dot_b mangle onto one alias
# Unsupported: ... __import_a_dot_b for a.b: module named a_dot_b

The resolved module's name counts because a sys.modules key need not be the
module's own __name__: os.path is named posixpath, and torch's own BC
shim entries are all of that shape, so under such a key a stale object never
answers to the key itself:

sys.modules["mypkg.shim"] = target            # a module whose __name__ is "mypkg.target"
# a stale copy of target left in __import_mypkg_dot_shim is accepted: its __name__ matches the
# resolved module's; a module named "mypkg.third" in the same slot still graph-breaks

Both __name__ reads go through object.__getattribute__(x, "__dict__"): a
module's PEP 562 __getattr__ and a class-level __getattribute__
(importlib.util._LazyModule's imports the module on any attribute read,
__dict__ included) are user code that must not run inside a trace on the way
to a verdict. The offender is named by type, plus its __name__ when it has
one so the message names the offending module, and never repr'd, for the same
reason. The residual case is a graph break rather than an AssertionError
because the condition is the user's globals, and IMPORT_NAME already reports
a non-module import result with unimplemented.

Which object the alias is rebound to here

This commit leaves import_source resolving through the memoized
_import_module, so the object it compares the bound alias against, and
rebinds the alias to, is still the one first resolved in the process. The check
does not depend on which (a same-name module in the slot is accepted either
way, and each test here plants a fresh name, so first resolution and live entry
coincide), but the rebind's direction does: where a writer has bound the live
module and the memo is older, this commit's rebind takes the slot back to the
memoized module, and the graph, specialized on the object IMPORT_NAME pushed,
is then guarded through a module the program no longer holds. That divergence
is the parent's whenever the memo and the live entry differ, with or without
anything in the slot, and the next commit in the stack (#197046) closes it by
resolving the live sys.modules entry; what it costs in the meantime is
measured in the FAQ below, and the answer is not the one the naive reading
gives.

Two smaller moves that go with the check

The module-type check runs before the alias is written. IMPORT_NAME ran
it on __import__'s result at push time, after import_source had already
bound the alias. It now runs before the import_source call, so on that path,
the one caller resolving a name the traced bytecode chose, a non-module
sys.modules entry is never written into the traced globals:

sys.modules["mypkg.weird"] = object()          # sys.modules accepts anything; __import__ hands it back verbatim
def fn(x):
    import mypkg.weird
    return x
torch.compile(fn)(x)
# parent: bound vars(mypkg.model)["__import_mypkg_dot_weird"] = <object>, THEN graph-broke on "Bad import result";
#         a second trace after the entry is swapped for another non-module then tripped the alias check
#         on two nameless objects
# now:    graph-breaks on "Bad import result" first; the alias is never written

The other eight callers (nn_modules_globals_vt, codegen.py's three sites,
torch_function.py, ctx_manager.py, misc.py, functions.py) reach
import_source with no module-type test, so a non-module entry under one of
their names, torch's own and stdlib names or a class's __module__, is still
bound verbatim there, unchanged by this commit; get_globals_source_and_value
already has one, since _registered_module_for_globals returns a name only for
a types.ModuleType whose __dict__ is the frame's globals. The hoisted check
is isinstance(value, types.ModuleType) alone: DummyModule only ever arrives
on the replay arm, where add_local_mod rejected non-modules when the record
was written, so that import goes.

The alias is recorded only once the binding is made. The check can now
fail recoverably, and the package entry is entered outside the trace that fails
(code_context wraps the whole compile, and a frame that skips or restarts
leaves its entry in _codes), so a record written before the check shipped in
the saved entry, and install() then bound the alias over the very global the
check refused to touch:

vars(mypkg.model)["__import_mypkg_dot_helper"] = "oops"
package = CompilePackage(fn); torch.compile(fn, options={"package": package})(x)   # two ops, then `import mypkg.helper`
# trace graph-breaks at the import and compiles up to the checkpoint; the package entry survives
store.save_package(package, path); pkg, backends = store.load_package(fn, path)
pkg.install(backends)
# recorded above the check:  install() binds importlib.import_module("mypkg.helper") over the "oops" the trace refused
# recorded after the check:  no entry names the alias, and the str is still there

_install_global writes unconditionally; record_only_if_new gates only the
uninstall bookkeeping. With the old AssertionError this was unreachable,
since the compile died before anything was serialized.

Behaviour changes against the parent

Each is pinned by a test below.

  • (a) An alias slot holding something other than the module it names, a
    non-module or a module of another name, is an Unsupported graph break where
    it was an AssertionError. Because IMPORT_NAME has no
    break_graph_if_unsupported, the Unsupported lands in step(): the frame
    is skipped outright unless an empty-stack checkpoint (two or more ops)
    precedes the import, and compiled up to that checkpoint otherwise, with
    either outcome cached on the code object and nothing guarding the alias, so
    fixing the global afterwards does not retrace the frame until
    torch._dynamo.reset()
    (test_import_alias_taken_by_a_non_module_graph_breaks,
    test_import_alias_the_trace_refused_is_not_recorded_for_install).
  • (b) A module object of the right name in the slot is accepted and the
    alias rebound where the parent raised
    (test_import_alias_accepts_a_stale_module_under_an_aliased_key,
    test_import_alias_check_does_not_run_a_module_getattribute).
  • (c) IMPORT_NAME of a non-module sys.modules entry no longer writes
    the alias before breaking
    (test_import_alias_is_not_bound_to_a_non_module_import).
  • (d) No package record is made for an alias the trace refused to bind
    (test_import_alias_the_trace_refused_is_not_recorded_for_install).

graph_break_registry.json gains the Import alias already bound entry, with
one hint per case: the global of that name for a non-module or nameless module
in the slot, renaming a module for two names mangling onto one alias, and
calling torch._dynamo.reset() after fixing the global, for the caching in (a).

Test Plan:

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

Five cases, all of which fail on the parent -- four on the old
AssertionError, test_import_alias_is_not_bound_to_a_non_module_import on
the alias the parent wrote. One plants a str, a module named other.name and
a nameless module (with a PEP 562 __getattr__ that raises) in the alias slot
in turn and pins the graph break's wording for each, then, with a
CompileCounter and no fullgraph, that frame_count stays 0 across the
refused call and a second call after the global is removed, and goes to 1 with
the alias bound only after torch._dynamo.reset(). One traces with a
CompilePackage while a str holds the alias -- two ops before the import, so
the trace restarts and compiles up to that checkpoint rather than skipping --
saves, loads and installs, and pins that no entry recorded the alias and the
str is still there. One plants a module whose class raises on a __dict__
read in both slots and traces through it. One plants two successive non-module
sys.modules entries and pins that neither is bound. One pins that a stale
module left under a key that is not its own __name__ is accepted rather than
raising, and that a module of some third name still graph-breaks.

python test/dynamo/test_package.py -k test_import_alias_taken_by_a_non_module_graph_breaks
python test/dynamo/test_package.py -k test_import_alias_the_trace_refused_is_not_recorded_for_install
python test/dynamo/test_package.py -k test_import_alias_check_does_not_run_a_module_getattribute
python test/dynamo/test_package.py -k test_import_alias_is_not_bound_to_a_non_module_import
python test/dynamo/test_package.py -k test_import_alias_accepts_a_stale_module_under_an_aliased_key

The four cases that plant a module under a fixed name and trace through it
call _import_module.cache_clear() in finally, next to the sys.modules
pop: the memo outlives the entry, so on a same-process re-execution -- the
default --reruns=2 of run_test.py -- the second run's import_source
would resolve the first run's module object and the assertIs against the
freshly planted one would fail. Measured by running each of the five tests
twice in one unittest process: without the calls, 5 failures, every one an
assertIs on a module of the right name that is not the one just planted;
with them, 10 tests OK. test_import_alias_is_not_bound_to_a_non_module_import
needs none, since the hoisted check graph-breaks before import_source runs
and the memo never sees its name -- it passed both runs without one.

Each is load-bearing, measured on this tree by mutation. Restoring the
identity-only test errors
test_import_alias_accepts_a_stale_module_under_an_aliased_key and
test_import_alias_check_does_not_run_a_module_getattribute with
Unsupported: Import alias already bound; narrowing the accepted names back to
the sys.modules key alone errors the first of those the same way. Reading the
bound module's name with getattr(bound, "__name__", None) errors the
nameless-module subtest of test_import_alias_taken_by_a_non_module_graph_breaks
with RuntimeError: module __getattr__ ran inside a trace for __name__, the
PEP 562 hook the fixture installs; reading either module's __dict__ as an
attribute errors test_import_alias_check_does_not_run_a_module_getattribute
with module __getattribute__ ran inside a trace. Dropping the named {bound_name} half of the message fails the other.name subtest and the
aliased-key case on their assertRaisesRegex. Raising AssertionError in
place of unimplemented fails five cases -- the three subtests, the aliased-key
case, the refused case -- on the exception type. Recording the alias above the
check fails the refused case on assertNotIn(alias, entry.import_sources).
Un-hoisting the module check fails
test_import_alias_is_not_bound_to_a_non_module_import on the alias it wrote.
On the test side, one op instead of two before the refused import fails its
len(guarded_codes) == 1 pin with 0, the frame having been skipped for want
of a checkpoint; two ops before the import in the skipped-frame case fail its
frame_count == 0 pin with 1, and dropping its torch._dynamo.reset() fails
the frame_count == 1 pin with 0. The whole file: 79 tests, OK (skipped=40,
expected failures=1).

They live in test_package.py rather than test_misc.py because the writer
that empirically reaches the collision path is CompilePackage.install, and
that file already owns the DiskDynamoStore save/load/install idiom and the
rest of the import_sources coverage.

lintrunner --take RUFF,PYFMT,GB_REGISTRY torch/_dynamo/symbolic_convert.py test/dynamo/test_package.py

FAQ: the most recent push reverted the first half of this PR -- the live sys.modules resolution, _import_source_cache, and four of the nine tests are gone from HEAD, while the description, Test Plan and FAQ still describe them. Restore them, or rewrite the description, title reasoning, Test Plan and all seven FAQ answers.

It is a split, not a revert, and the description now matches it. The resolution half -- _import_source_cache, the importlib.import_module resolution, the nn_modules_globals_vt value, the deletion of _import_module and the four tests test_import_alias_binds_the_live_module, test_import_alias_survives_a_sys_modules_rebind, test_import_alias_rebind_makes_a_stale_artifact_visible and test_import_alias_of_a_name_removed_from_sys_modules_keeps_its_module -- is the next commit in this stack, #197046, whose message carries the five FAQ answers that argued that half (the nn_modules_globals_vt divergence, "costs at most a recompile", the eleven callers, the dropped functools.cache, package.uninstall()). This commit is the collision check alone, on the memoized resolution the parent has, and this message describes only that: the third paragraph says which object the alias is rebound to here and what that leaves for the next commit, the Test Plan names the five tests that exist at this tree, and the three FAQ entries below are the ones about this half. The observation that test_import_alias_accepts_a_stale_module_under_an_aliased_key passes because its key is unique per test, so the memoized first resolution is the live object, is right and is what the third paragraph says: the check's verdict is the same under either resolution, so these tests plant fresh names and pin the verdict, and the four tests that pin which object gets resolved live with the resolution.

FAQ: with the resolution reverted, the relaxation actively converts install's correct binding into a stale one, and the direction is the harmful one: install() binds the alias to the live module, the next trace finds the memoized object under value, accepts the same-named live one in the slot and overwrites it with the memo; the installed artifact's serialized guards then read the alias out of that same dict, MODULE_MATCH is unserializable so no identity guard catches it, and the artifact keeps serving a graph built against a module the program no longer holds. Pre-PR that sequence raised the AssertionError, which is loud and safe. The relaxation should not land on its own.

The binding direction is as described -- at this commit the rebind lands on the memoized object, and the third paragraph now says so -- but the sequence's ending was read off the code rather than run, and run it ends the other way round. Measured on three trees with the same script (a module M resolved and saved against at VALUE=2, then sys.modules[M] handed to a second object with VALUE=7, the CompilePackage loaded and install()ed so the alias binds that second object, a second function in the same globals traced through import M, then the installed artifact called): on this tree the trace rebinds the alias to the memoized module, and the artifact then reports its staleness -- RuntimeError: Detected recompile under fail_on_recompile, and under the default stance a recompile that returns 8.0, equal to eager, on that call and the four after it. On the parent the trace dies on the AssertionError, and the artifact, with the alias left on the live module, serves 3.0 where eager returns 8.0, under both stances. On the next commit's tree the alias stays on the live module, as intended, and the artifact serves the same stale 3.0 under both stances. So the relaxation on its own does not convert a detectable staleness into a silent one; the one tree of the three on which that artifact's staleness is detected is this one, and that is an accident of the direction rather than a merit: what makes the artifact silent on the other two is that a loaded EQUALS_MATCH guard's expected value is re-read through the guard scope when the artifact is installed (TORCH_LOGS=guards shows the saved G['__import_M'].VALUE == 2 rebuilt at install() as ... == 7), so against whichever module the alias holds at install time the guard is trivially true, and only a later change to what the alias reads can fail it. That is a property of how loaded guards are built, present on the parent and untouched by either commit; the object the alias should hold is the live one, which is the next commit's change, and the two land adjacent. The AssertionError this commit removes was neither safe nor a guard on that artifact: it killed the trace of a different function, with no eager fallback, and left the artifact serving its stale 3.0.

FAQ: the surviving tests leak into _import_module's memo, and the cache_clear() that guarded it was deleted with the resolution tests: each plants a throwaway module in sys.modules under a fixed name, traces through import_source, then pops the entry in finally, leaving the memo holding that object under a name no longer in sys.modules. On any same-process re-execution the second run resolves run 1's object and the assertIs fails.

Fixed, as measured above: running each of the five tests twice in one process failed 5 of the 10 runs before the fix, all on an assertIs against a same-named module from the first run, and passes all 10 with _import_module.cache_clear() in the four finally blocks that plant a module and trace through it. On the next commit's tree, where _import_module is deleted and the alias resolves the live entry, the same four tests run twice pass without any clearing (measured with that commit's files: 8 runs, OK), so the calls are needed here and only here; that commit drops them with the helper.

FAQ: the torch_package branch also flows through the new predicate, and a torch.package module's __name__ does not equal the <torch_package_N>.foo string used as module_name, so the relaxation never applies there.

It does apply: that registry is keyed by the module's own __name__. package_importer.py:380 sets module.__name__ = self._mangler.mangle(name) and :394 stores _package_imported_modules[module.__name__] = module, with :390-393 asserting the key is unique. Measured on a real package: registry key ['<torch_package_0>.pkgprobe_mod'], module.__name__ == '<torch_package_0>.pkgprobe_mod', key == module.__name__: True. So on that branch module_name is value.__name__, and a stale torch.package module of the same mangled name is accepted exactly as on the normal branch.

FAQ: the raise case list still does not include an actual mangling collision; plant a genuine a.b / a_dot_b pair, since only that proves the surviving purpose of the check end to end.

Measured on the real pair rather than planted: with sys.modules carrying a synthetic package aprobe (__path__ = []), aprobe.b and aprobe_dot_b, tracing from aprobe.b import VALUE binds __import_aprobe_dot_b to the module named aprobe.b (non-empty fromlist, so IMPORT_NAME passes aprobe.b verbatim), and tracing import aprobe_dot_b in those same globals then graph-breaks (Unsupported, gb_type Import alias already bound) with module alias __import_aprobe_dot_b for aprobe_dot_b is already bound to a module named aprobe.b in the globals of the frame being traced as its explanation -- the check's surviving purpose, end to end, under the relaxed predicate, because the resolved module is self-named and so both accepted names are aprobe_dot_b. Moving that into the case list would add three sys.modules entries and a fake package with a __path__ for __import__ to walk, and no branch: the reject arm is bound_name not in accepted, a graph break rather than a raise, and the other.name case of test_import_alias_taken_by_a_non_module_graph_breaks plus test_import_alias_accepts_a_stale_module_under_an_aliased_key already reach it -- the latter with the key, the resolved module's name and the bound module's name all three distinct, one more distinct name than a collision has.

FAQ: the hoisted Bad import result check guards one of the ten import_source call sites, but the description states its consequence for all of them.

Narrowed: the message scopes that sentence to IMPORT_NAME, the one caller resolving a name the traced bytecode chose, and says outright that the other eight bind a non-module entry under their names verbatim, as before this commit, while get_globals_source_and_value brings its own module-type test. Those names are torch's own and stdlib ones (codegen.py's three sites, functions.py, torch_function.py, nn_modules_globals_vt) or a class's __module__ (ctx_manager.py, misc.py); a non-module under one of those is a broken process, not a trace to save.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 [email protected]
Co-Authored-By: Claude Fable 5.1 [email protected]

🤖 Generated with Claude Code

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (2 Unrelated Failures)

As of commit 124f988 with merge base 51d4378 (image):

🟡 GREEN LIGHT - PR requires human review:

  • Pinned divergence from eager
    • test_import_alias_puts_the_memo_back_over_the_installed_live_module asserts compiled_fn2(*args) equals args[0] * 7 and assertNotEqual(fn2(*args), compiled_fn2(*args)) after new.VALUE = 8 (test_package.py:1191-1193).
    • It pins frame_count == 1 across that change (test_package.py:1194), so a fullgraph=True compile keeps serving a stale result with no recompile.
    • The test's own comment states "a change to the live module goes unseen. Pinned as the divergence it is" (test_package.py:1147-1151).
  • Accepted slot bypasses the deliberate hard error
    • if bound_name not in accepted: (symbolic_convert.py:2474) wraps the if not graph_break_ok: raise AssertionError arm at :2492, so a same-named slot is accepted for callers that pass no flag.
    • nn_modules_globals_vt (symbolic_convert.py:2384) and get_globals_source_and_value (:6539) call import_source with no graph_break_ok, the callers the comment at :2489-2491 says keep the hard error.
    • The alias is then overwritten with _import_module's functools.cached value (:2441, :2513), whose only cache_clear() callers in the tree are test_package.py teardowns.
  • Open design question and a description that does not match the diff
    • A maintainer comment dated 2026-09-19 lists item 1 as "Open, for the author to decide" — whether this commit should stop writing the memo back over an accepted same-named binding.
    • The body's change (b) cites test_import_alias_accepts_a_stale_module_under_an_aliased_key, a name absent from the diff, which adds test_import_alias_accepts_a_stale_module_of_either_accepted_name instead.

reason: possible_regression
Reviewed commit: 124f988

Inference job

🐛 Report a wrong verdict

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 13, 2026
This was referenced Sep 13, 2026
@bobrenjc93 bobrenjc93 added ciflow/trunk Trigger trunk jobs on your pull request topic: not user facing topic category labels Sep 13, 2026
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 39m 28s —— View job


Reviewed — the relaxation looks unsound to me: the object it rebinds the alias to is the process-memoized (possibly stale) module, while the trace specializes on the live one, so guards end up watching a different object than the graph was built from; details below.

Full review

PR Review: #196896

Summary

Relaxes import_source's alias-collision assert so a stale-but-same-named module in the alias slot is rebound instead of crashing the trace. The relaxation as written can convert the old hard crash into a silently stale specialization, because the value it rebinds to is not the object the trace built variables from; two smaller issues in the new predicate and several gaps in the tests.

Infrastructure

torch/_dynamo/symbolic_convert.py:2450 — the rebind desynchronizes the guard scope from the traced value. The safety argument in the PR description is "which module object a compiled artifact was built against is pinned by its guards, not by this write." That does not hold on this path, because value here is not the object the trace is tracing against:

  • IMPORT_NAME pushes the module returned by live __import__ (symbolic_convert.py:2510), and PythonModuleVariable.tp_getattro_impl reads attributes off that object (variables/misc.py:2030-2039).
  • import_source independently resolves the module through _import_module, @functools.cache with no invalidation anywhere in the tree (symbolic_convert.py:260-267), and writes that object into f_globals[alias] (:2450).

So in exactly the scenario the PR targets — first compile memoizes A, sys.modules swaps in B — the new code rebinds the alias to the stale A while the graph is specialized on B's attribute values. Guards do not pin B: GuardBuilder.get re-derives the expected value by evaluating G['__import_...'].VALUE against global_scope (guards.py:2882, :1357), and at check time G is runtime_global_scope, which defaults to the same dict (guards.py:1362-1364, :1710-1716). Expected value and runtime read both come from A, so the guard passes; nothing installs a MODULE_MATCH/ID guard on the alias in this path, since symbolic_convert.py:2546 constructs PythonModuleVariable directly and bypasses variables/builder.py:1933. Any subsequent change to B is invisible.

Worse for the precompile path the change is written for: CompilePackage.install binds the alias to live B (package.py:1306-1310), and the installed artifact's deserialized EQUALS_MATCH guards read the alias out of that same live module dict. A later cache-miss trace of any function in those globals now overwrites the alias with A, so the installed artifact's guard reads A's attribute, matches the value it was built from, and keeps serving a graph specialized on a module the program no longer uses. EQUALS_MATCH is serializable (it is absent from UNSUPPORTED_SERIALIZATION_GUARD_TYPES, guards.py:5096-5105), and under caching_precompile the ID-derived guards that would have caught this are filtered out (guards.py:4921-4948), so there is no backstop. The direction is the harmful one: install writes the live object, the trace overwrites it with the cached one.

The test masks this by construction: placeholder.VALUE = 2 and real.VALUE = 2 (test/dynamo/test_package.py:979, :999). Set real.VALUE = 3 and call the installed compiled_fn(*args) after fn2's trace has rebound the alias — I expect x + 2 against an eager x + 3. I could not run this (no built torch in this checkout), so please confirm before acting on it.

If it reproduces, the minimal fix is to keep one object for both the write and the trace, e.g. resolve value from live sys.modules in import_source (falling back to _import_module when absent) so the alias, the pushed PythonModuleVariable, and every writer agree. Preserving the existing bound when it is a same-named module is the other direction, but on its own it still leaves the pushed value and the guard scope disagreeing. Fix this →

Code Quality

symbolic_convert.py:2444 — bound.__name__ is not free of user code, contradicting the comment two lines above. The comment justifies avoiding repr because "this raises out of tracing, where __repr__ is user code," but the predicate itself does a plain attribute read on an arbitrary object from user globals. isinstance(bound, types.ModuleType) admits subclasses, and module-level __getattr__ (PEP 562) and ModuleType.__getattribute__ overrides are common — torch/backends/__init__.py and torch/_VF.py both ship them, and importlib.util.LazyLoader's module class intercepts attribute access to run the deferred import under the import lock. That is precisely the "lazy-import shim" this PR is about, so the check can trigger a full module execution, or raise AttributeError/ValueError out of Dynamo internals, from inside the guard for an error path. Read it out of the dict instead: bound.__dict__.get("__name__"), which cannot dispatch to user code and is what the module system itself uses.

symbolic_convert.py:2446-2449 — the message drops the only field that distinguishes the two failure modes it now guards. The check still catches distinct module names mangling to one alias (a.b.c and a.b_dot_c both mangle to __import_a_dot_b_dot_c at :2429), but for that case type(bound).__name__ is "module", so the reader gets "already bound to a module" with no way to tell a mangling collision from a stale rebind. Once __name__ is read from __dict__ it is a plain module name, not a repr, so including it is free and is the one datum that diagnoses the collision.

symbolic_convert.py:2442 — bound = f_globals.get(alias, value). The name asserts something the value does not mean when the key is absent; the sentinel trick then makes the "is already bound to" wording in the message reachable only because of branch ordering. if alias in f_globals: around the check reads as what it is.

Testing

test/dynamo/test_package.py:1003 — torch._dynamo.optimize(package=package)(fn) discards its result. Every other load-then-install site in this file binds the wrapper and then calls it, usually under fail_on_recompile, to prove the artifact serves (:386-389, :433-436, :488-492, :540-542, :614-616). Here nothing uses it, and with no backend= argument _optimize defaults to "inductor" and eagerly resolves it via get_compiler_fn (torch/_dynamo/eval_frame.py:1804, :1889), pulling in Inductor for a test that otherwise runs on eager. Either delete it or make it load-bearing — and making it load-bearing is what closes the gap above: calling the installed artifact after fn2's trace rebinds the alias is the assertion that actually tests the PR's safety claim, and no test currently does.

test/dynamo/test_package.py:1012-1014 — assertions are weaker than the invariant they mean to pin. Because _import_module is memoized and primed while sys.modules[name] is placeholder, the rebound object is exactly placeholder, so assertIs(bound, placeholder) is the precise assertion; assertIsInstance + __name__ + assertIsNot(bound, real) also passes if the alias holds some third module. It cannot be tightened as-is, which is the next point.

test/dynamo/test_package.py:1015-1017, :1037-1039 — the tests leak into a process-wide cache that nothing clears. finally unwinds sys.modules and fn.__globals__, but _import_module (symbolic_convert.py:260-267) keeps the throwaway ModuleType forever under a name no longer in sys.modules, leaving the two permanently disagreeing for the rest of the process. On a rerun in the same process (--repeat, flaky-test reruns) the first test's first compile silently resolves run 1's placeholder, so it no longer exercises the sequence it documents. Add _import_module.cache_clear() to both finally blocks, then tighten :1012-1014 to assertIs.

test/dynamo/test_package.py:1004 — install() with no matching uninstall() and no trailing torch._dynamo.reset(). The precompile entries and installed globals survive to the next setUp; the comparable test at :833-857 resets explicitly.

Recommendation

Needs Discussion — the design question in Infrastructure needs to be settled first. If the stale/live divergence reproduces as described, this trades a loud crash for a silent wrong answer on the precompile path, and the fix belongs in which object gets bound rather than in how the collision is classified. The __name__ read and the test issues are straightforward either way.

Note: I reviewed statically and did not run test/dynamo/test_package.py — no built torch was importable in this checkout.

| Branch: `gh/bobrenjc93/1184/head`

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

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


Re-reviewed: the earlier stale-vs-live finding is fixed for IMPORT_NAME, but the identical divergence survives two methods above the fix (nn_modules_globals_vt), and the "at most a recompile" safety argument for the rebind does not hold for AOT-loaded artifacts, which have no recompile path at all.

Full review

PR Review: #196896

Summary

Two changes to import_source: resolve the aliased module from live sys.modules instead of the process-memoized _import_module, and downgrade the alias-collision assert so a same-named module in the slot is rebound rather than fatal. The first change fixes the divergence I flagged last round on the IMPORT_NAME path, but leaves the same defect in the sibling call site; the second rests on a safety claim that is false on the AOT path, and the tests are built so that neither gap can fire.

Infrastructure

symbolic_convert.py:2381-2386 — nn_modules_globals_vt still has exactly the divergence the fix at :2434 exists to remove. The fix's own premise is that the object bound under the alias must be the object the trace builds VariableTrackers from. Two methods above it, that premise is violated by construction:

module_source = self.import_source(module_name)      # binds sys.modules[...] (live, after this PR)
fglobals_value = _import_module(module_name)         # memoized -- possibly a different object
return VariableTracker.build(self, fglobals_value, module_source)

VariableTracker.build routes to VariableBuilder (variables/builder.py:1927-1940), producing PythonModuleVariable(fglobals_value, source=module_source), and tp_getattro_impl (variables/misc.py:2030-2039) reads attributes off fglobals_value while tagging them AttrSource(module_source, name). GuardBuilder.get re-derives every expected value by evaluating the source against the scope, i.e. getattr(G[alias], name) on the live module — so the graph is specialized on the memoized object and the guards validate the live one. This is not academic: the sole consumer (variables/nn_module.py:1373-1402) uses it to read the lengths of _global_backward_pre_hooks, _global_backward_hooks, _global_forward_hooks, _global_forward_pre_hooks, and if all are empty Dynamo bypasses _call_impl and traces forward directly. That path installs no SEQUENCE_LENGTH on those dicts (unlike the instance-hook path at nn_module.py:1611), so a stale module's global-hook dicts silently decide graph shape. The one-line fix is to drop _import_module here and take the value import_source resolved. Fix this →

symbolic_convert.py:2448-2465 — "costs at most a recompile where it used to be a crash" is false for a loaded AOT artifact; there it converts a trace-time crash into a call-time crash in a different function. The rebind's whole justification is that guards pin which module a compiled artifact was built against. On this path they do not:

  • IMPORT_NAME constructs PythonModuleVariable(value, source=source) directly (:2562) and installs no guard on the module object — only VariableBuilder does install_guards(GuardBuilder.MODULE_MATCH) (variables/builder.py:1931-1934). So no identity guard exists to pin it.
  • MODULE_MATCH is unserializable anyway (guards.py:5096-5105; serialize_guards raises PackageError on it at :5122-5127), and aot_compile_fullgraph's default guard_filter_fn (aot_compile.py:1019-1040) additionally drops every is_global guard.

What remains rooted at the alias are attribute guards, and the scope they read is held by reference: _seed_guard_scope writes guard_scope[alias] = importlib.import_module(module_name) (aot_compile.py:712-714) into what its own comment at :699-701 describes as possibly a user module's live namespace. A later trace of any function in those globals now overwrites that alias where it previously raised. AOTCompiledFunction.__call__ (aot_compile.py:824-845) has no recompile and no eager fallback — guard failure is raise RuntimeError(f"GuardManager check failed, reason: {debug_info}"), and torch/compiler/__init__.py:1013-1015 documents exactly that ("rather than recompiling"). AOTCompiledModel.__call__ (:1342-1451) likewise terminates in raise RuntimeError(report). Same for torch.compiler.set_stance("fail_on_recompile"), where fail_callback (eval_frame.py:300-348) raises on any cache miss.

So the alias is a single slot with two consumers that want different objects — the running trace wants live, a previously-loaded artifact wants the one its guards were seeded against — and this PR resolves that in favor of the trace without saying so. I think favoring the trace is the right call (the alternative reintroduces the first bug), but the comment and PR description should state the actual cost, and the AOT-artifact-breaks-at-call-time case deserves either a test or an explicit note that it is accepted.

symbolic_convert.py:2434-2436 — the resolution change lands on all eleven import_source callers, but only IMPORT_NAME is reasoned about. Several derive module_name from an object's __module__ and then build AttrSource(import_source(...), attrname), asserting that the module still holds that exact object under that name — variables/misc.py:1311 (self.fn_cls.__module__ for autograd functions), variables/torch_function.py:220 (ty.__module__), variables/ctx_manager.py:118. Under the very sys.modules handover this PR targets, the live module may not carry the attribute the memoized one did, so GuardBuilder.get raises AttributeError out of Dynamo internals where it previously succeeded. That is arguably the correct semantics — a guard should read what the program reads — but it is a distinct behavior change from the one described, and nothing covers it.

Minor, same line: the torch_package branch at :2420-2426 also flows through the new predicate, and a torch.package module's __name__ does not generally equal the <torch_package_N>.foo string used as module_name, so the relaxation never applies there and those traces keep raising. Worth a word in the comment so the next reader does not assume it does.

Testing

test/dynamo/test_package.py:1044-1062 — all three module objects are given VALUE = 2, which excludes the only case where the rebind has a consequence. The comment at :1014-1016 states this is deliberate ("All three objects agree on VALUE, so the installed artifact stays valid across the rebind"), but that is precisely the case that cannot distinguish a safe rebind from a harmful one. Give newer a different VALUE and the fail_on_recompile assertion at :1061-1062 becomes the test of the PR's actual safety claim — and per the AOT/stance analysis above, I expect it to raise rather than recompile. Either way the result belongs in the test suite: if it recompiles cleanly the claim is proven, and if it raises the tradeoff is documented rather than assumed.

test/dynamo/test_package.py:1088 — the third subtest's comment overclaims. It says the case list covers "a second module name that mangles onto the same alias", but types.ModuleType("other.name") is a wrong module planted directly in the slot, not a mangling collision. The real collision the check exists to catch is two distinct module names mangling to one alias via . -> _dot_ at :2437 (a.b.c and a.b_dot_c). Nothing constructs that, so the surviving purpose of the check is untested — reword the comment or add the actual pair.

test/dynamo/test_package.py:1063-1066 — no package.uninstall(). install() at :1050 writes the alias plus every backend_id into this test module's live globals via _install_global (package.py:1256-1276), and the finally block pops only the alias. The comparable test at :736 calls uninstall() explicitly; the one at :628 resets before installing. The backend-id bindings survive into the next test in the file.

Recommendation

Request Changes — nn_modules_globals_vt should be fixed in this PR (it is the same defect, three lines away, and it silently decides graph shape), and the rebind's cost should be stated correctly and covered by a test where the swapped module actually differs. The bound.__dict__.get("__name__") read, the if alias in f_globals restructure, and the by-type error message all address the previous round's points.

Note: reviewed statically; no built torch was importable in this checkout, so I did not run test/dynamo/test_package.py. The divergent-VALUE prediction above in particular is unverified.

| Branch: `gh/bobrenjc93/1184/head`

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@bobrenjc93 bobrenjc93 changed the title [no-ci] [dynamo] Rebind a stale module alias instead of failing the trace [dynamo] Rebind a stale module alias instead of failing the trace Sep 18, 2026
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
pytorchmergebot pushed a commit that referenced this pull request Sep 19, 2026
…ard for and which share a line (#197001)

**Problem.** The no-match report decides, entry by entry, whether its missing-global hint names "this `Module` instance's forward" or stays neutral ("the live scope this artifact was loaded against"), by comparing the dict `forward` resolves to against the dict each entry's guards hold. Nothing pinned that a caller-supplied `guard_globals=` dict stays neutral, or that in a report with two entries holding different dicts only the entry holding the resolved one is told which forward.

**Fix.** Two tests pin exactly that: one where no entry holds the resolved dict (and defining the name in the supplied dict then serves the call), and one where exactly one of two does, checked in both orders with a single resolve asserted. No source change.

**Summary.** Tests only, for the no-match report the report commit (#196823) raises, split out of it so that its review fits in one pass -- the pattern of #196824 and #196825, which pin the dispatch's last resort and a guarded global the loading process does not have from test-only commits. Split twice more for review budget: the five-test revision of this commit died at the review bot's 60-minute ceiling, so the two tests that pin WHEN the report resolves `forward` -- only for a SUPPLIED scope, and once -- moved up into `[aot_compile] Pin when the no-match report resolves forward` (#197301), and the three-entry test that pins which entries share a hint line moved up into `[aot_compile] Pin that the no-match report shares one hint line across entries worded alike`. What stays here is the pair that pins WHICH entry the hint names a `forward` for: one where no entry is, and one where exactly one of two is. Both pass at the parent, whose report they pin, fail below the report commit (#196896) where no report exists, and each fails under a targeted edit of `_no_match_report` that no other test in the file catches, measured by editing the report and running the whole file. Two tests of the previous revision are gone, one because the footer gate it fenced is already fenced by two other tests and one because it is folded into the three-entry test's entry `[1]` in the commit above.

## What the report does at this tree

The report decides its hint per entry. An entry whose verbose parts name a whole missing global gets `_missing_global_hint(forward=...)`, with `forward` set when `resolved is not None and resolved is result._guard_globals`; `resolved` is what one `_resolve_guard_scope(self.model)` returned, run at most once, at the first hinted entry whose scope is SUPPLIED, and reused for every entry after it (when it runs, and that it runs once, is #197301's).

```
# the two wordings the tests tell apart
For [i]: a guarded global is missing from the live scope this artifact was loaded against; define it there ...   # neutral
For [i]: ... this GlobalConfigModule instance's forward resolves to ...                                          # named
```

## Both fail below the report commit

Both tests pass at the parent, whose report they pin, and fail below the report commit (at #196896, the commit under it), where the no-match fall-through `results[0](self.model, *args, **kwargs)` raises the function path's `GuardManager check failed` message. That message quotes the guard's `KeyError on G[...]` part and, for a whole missing global, appends the function path's hint sentence, so the `loaded against; define it there` substring the tests also look for is present there; what it lacks is the `[i]` entry prefix, the `For [i]:` hint line and the `Tried N` header, and with no report there is no resolve. Measured with that tree's `aot_compile.py` under this tree's test file:

| test | failure below the report commit |
| --- | --- |
| `..._hint_stays_neutral_for_a_supplied_scope` | `"[0] KeyError on G['AOT_HERMETIC_WEIGHT']" not found` |
| `..._names_forward_only_for_the_dict_it_resolves_to` | `Expected '_resolve_guard_scope' to be called once. Called 0 times` |

The one that compiles in its own body calls `_hide_leaked_dynamo_globals()` on entry, as the capture-only `test_aot_compile_fn_missing_global_hint_names_the_tracing_scope` does; the other shares `_two_input_global_guard_artifact` with `test_no_match_message_hints_each_scope_a_mixed_model_failed_in` and the landed `test_aot_compile_module_missing_global_hint_names_the_resolved_module` and, like them, does not, its kept guards being rooted at `GLOBAL_POOLING_CONFIG` alone.

## `test_no_match_message_hint_stays_neutral_for_a_supplied_scope`

```python
scope: dict[str, object] = {"__builtins__": builtins}          # never had AOT_HERMETIC_WEIGHT
compiled = AOTCompiledModel.deserialize(HermeticModule(), data, guard_globals=scope)
with self.assertRaises(RuntimeError) as ctx:
    compiled(x)
message = str(ctx.exception)
self.assertIn("[0] KeyError on G['AOT_HERMETIC_WEIGHT']", message)
self.assertIn("For [0]: a guarded global is missing from the live scope this artifact was loaded against; define it there", message)
self.assertNotIn("instance's forward", message)
# the advice, followed: the guards hold the supplied dict, and defining the name there serves the call
self.assertIs(compiled.compiled_results[0]._guard_globals, scope)
scope["AOT_HERMETIC_WEIGHT"] = AOT_HERMETIC_WEIGHT
self.assertEqual(compiled(x), x @ AOT_HERMETIC_WEIGHT)
```

It loads through `AOTCompiledModel.deserialize(..., guard_globals=...)` with a dict that never had the guarded name, so the guards hold a dict no `forward` resolves to, asserts the scope-neutral wording under its `For [0]:` prefix, and then the advice it gives: `compiled_results[0]._guard_globals is scope`, and defining the name in that dict serves the call -- with `AOT_HERMETIC_WEIGHT` defined in this module's dict, where the class's `forward` lives, the whole time.

Reducing the compare to `resolved is not None` fails it with a report that names `this HermeticModule instance's forward`, and fails exactly two others: the landed #196818's `..._names_the_resolved_module`, whose second half loads with `guard_globals=dict(globals())` -- a copy of the module dict, taken while the module itself lacked the name, that is not the dict `forward` resolves to -- and asserts `loaded against; define it there`, and this commit's `names_forward_only_for_the_dict_it_resolves_to`, whose caller-supplied entry is then told which forward as well. #197048's `test_no_match_report_survives_a_forward_resolve_that_raises` reaches the neutral wording through `resolved is None`, and its `test_no_match_message_hint_covers_a_rebound_forward` through a resolve that IS the dict the guards hold, so both pass under that edit.

What this test adds over `..._names_the_resolved_module` is the other way to the wording, a supplied dict that never had the name rather than a stale copy carrying the module's `__name__`, and the recovery: no other `AOTCompiledModel.deserialize(..., guard_globals=)` test defines a missing name in the supplied dict and asserts the call is served (`..._deserialize_takes_a_guard_globals_scope` supplies a copy that already carries its names, and `covers_a_rebound_forward` defines the name in the dict the load RESOLVED, not one the caller passed).

## `test_no_match_message_names_forward_only_for_the_dict_it_resolves_to`

```python
by_forward = AOTCompiledModel.deserialize(GlobalConfigModule(), data)                    # resolves scope from model.forward: this module's dict
by_caller = AOTCompiledModel.deserialize(GlobalConfigModule(), data, guard_globals=scope)  # a dict that never had the name
self.assertIs(by_forward.compiled_results[0]._guard_globals, globals())
self.assertIs(by_caller.compiled_results[0]._guard_globals, scope)
del GLOBAL_POOLING_CONFIG
pair = by_forward.compiled_results[:1] + by_caller.compiled_results[:1]
cases = ((pair, [named, neutral]), (pair[::-1], [neutral, named]))                        # both orders
for results, wording in cases:
    mixed = AOTCompiledModel(GlobalConfigModule(), results)
    with patch(target, wraps=_resolve_guard_scope) as resolves, self.assertRaises(RuntimeError) as ctx:
        mixed(x)
    resolves.assert_called_once_with(mixed.model)          # one resolve, asked about the model the report is for
    hints = [line for line in message.splitlines() if line.startswith("For [")]
    self.assertEqual([line[:9] for line in hints], ["For [0]: ", "For [1]: "], message)
    for hint, want in zip(hints, wording):
        self.assertIn(want, hint)
```

This is the shape that tells a per-entry `forward` from one shared across the report. Two SUPPLIED results whose guards hold different dicts -- one from `deserialize(GlobalConfigModule(), data)`, which resolves the scope from `model.forward` and so holds this module's dict, the one `_resolve_guard_scope` returns; one from `deserialize(..., guard_globals=scope)` with a dict that never had the name -- go into one `AOTCompiledModel` by hand, as `hints_each_scope_a_mixed_model_failed_in` builds its CAPTURED + SUPPLIED pair, and are dispatched with `GLOBAL_POOLING_CONFIG` deleted, in both orders. Each order enters a fresh `patch(..., wraps=_resolve_guard_scope)`, so its count is that order's alone, and asserts `assert_called_once_with(mixed.model)` -- one resolve, asked about the model the report is for -- two `For [i]:` lines, and that the entry holding the resolved dict is the one told `this GlobalConfigModule instance's forward` while the other gets the live-scope wording.

| edit to `_no_match_report` | fails |
| --- | --- |
| decide `forward` once, at the first hinted entry, and apply it to every entry | this test alone, on the second entry's wording (`'the live scope this artifact was loaded against; define it there' not found in "For [1]: ... this GlobalConfigModule instance's forward resolves to ..."`) |
| resolve `_resolve_guard_scope(type(self.model)())` instead of `self.model` | this test on `expected call not found`, plus #197048's `covers_a_rebound_forward` and `survives_a_forward_resolve_that_raises` on wording |

Nothing else in the file catches the first edit: `..._names_the_resolved_module`'s two entries share one dict in each half, and `hints_each_scope`'s SUPPLIED entry is its only one. The line count does not catch that edit, because the resolved dict carries a `__name__` and the supplied one does not, so the two hints stay two sentences either way; the wording does. The `_with(mixed.model)` is what pins which module is resolved: asking about a fresh instance resolves to the same dict here, so the wording cannot tell, and a fresh instance does not carry the `forward` the two #197048 tests rebind.

## Two tests of the previous revision are gone

`test_no_match_message_advises_an_input_for_a_missing_global` and its `SelfModeBranchGlobalModule` fixture pinned the footer under a report whose every entry was hinted; the footer is unconditional, and returning before it when `sum(map(len, hinted.values())) == len(results)` fails two tests at this tree without it (both on `'Add a ModelInput' not found`): #196825's `test_aot_compile_module_absent_global_fails_guard` and #197048's `survives_a_forward_resolve_that_raises` (and, one commit up, #197301's `resolves_forward_only_for_a_supplied_scope`). Its other assertions -- that the `L['self'].mode` mismatch is absent from the first report and named by the second -- pinned the guard tree's install order and fail-count re-sort in guards.cpp, not the report.

`test_missing_key_inside_a_present_global_is_not_a_missing_global` is folded into the three-entry test's entry `[1]`, which fences the same substring edit, and rides with it in the commit above.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_hint_stays_neutral_for_a_supplied_scope
python test/dynamo/test_aot_compile.py -k test_no_match_message_names_forward_only_for_the_dict_it_resolves_to
python test/dynamo/test_aot_compile.py
```

The whole file is green here and on the parent commit.

## FAQ

> **FAQ: The review found that
> `test_aot_compile_module_missing_global_hint_names_the_resolved_module`, in
> the landed #196818, already fails under the edit that this commit's
> `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` was once
> described as the one test to catch. Why keep the test?**
>
> Because the coverage claim was wrong, and the test's other half is not pinned
> anywhere else. Re-measured on the whole file with the compare reduced to
> `resolved is not None`: the failures are `..._names_the_resolved_module`
> (`'loaded against; define it there' not found`), this test, and this commit's
> `names_forward_only_for_the_dict_it_resolves_to`; every other test passes. So
> the identity compare is fenced at #196818 as well, and the message says so
> instead of crediting this test alone. What this test alone covers is a
> `guard_globals=` dict that never had the name --
> `..._names_the_resolved_module` reaches the same wording through
> `dict(globals())`, a copy taken while the module itself lacked the name --
> and the recovery, defining the name in that dict and asserting the call is
> served, which no other `AOTCompiledModel.deserialize(..., guard_globals=)`
> test does.

> **FAQ: The review found two of an earlier revision's five tests largely
> redundant with the base, and two report branches -- where `tried_forward` is
> set, and hint dedup keyed by text -- unpinned. What changed?**
>
> Both redundancies were measured and both tests are gone; both branches are
> now pinned, one in the commit above and one in #197301. Gating the footer on
> every entry being hinted, the edit
> `test_no_match_message_advises_an_input_for_a_missing_global` fenced, fails
> two tests at this tree without it -- #196825's `absent_global_fails_guard`
> and #197048's `survives_a_forward_resolve_that_raises` -- so that test and
> its fixture add no fence on the report, and its `L['self'].mode` assertions
> pin guards.cpp's accessor order, not this function. Replacing the report's
> whole-part predicate with a substring test, the edit
> `test_missing_key_inside_a_present_global_is_not_a_missing_global` fenced
> alone, and keying `hinted` by dict identity are both fenced by the
> three-entry `shares_a_hint_line_across_entries_worded_alike` in the commit
> above, so the fold loses no coverage and the module path still has its own
> pin of the predicate. The `tried_forward` mark is pinned by #197301's
> `resolves_forward_once_past_a_resolve_that_raises`.

> **FAQ: Every new test passes at the parent commit. Where is the red-on-parent
> evidence?**
>
> There is none by construction: this is a tests-only commit pinning the
> report the parent already ships, so every test passes on the parent's tree.
> The two measurements that stand in for it are above: each test fails under
> the tree below the report commit (#196896), where no report exists, and each
> fails under a targeted edit of `_no_match_report` that no other test in the
> file catches -- the mutation table is what shows the pins are not vacuous.

> **FAQ: The review listed `"; ".join(parts)` with more than one verbose code
> part per entry as uncovered. Why is there no test for it here?**
>
> Because that join is #197134's (`Keep a no-match report entry to one line
> that says what its guards answered`), whose
> `test_no_match_report_keeps_an_entry_on_one_line_past_odd_separators` owns
> the entry format; how many parts an entry quotes has no bearing on the hint,
> which is what this commit pins. A multi-part entry test belongs next to that
> one, in that PR.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

Pull Request resolved: #197001
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220
pytorchmergebot pushed a commit that referenced this pull request Sep 19, 2026
…s entries worded alike (#197569)

**Problem.** The no-match report from #196823 groups its missing-global hint by sentence, so two entries loaded against different caller dicts but worded alike share one `For [0, 2]:` line, and a nested-key `KeyError` stays off the hint; nothing in the file exercised a three-entry report, so none of that was pinned.

**Fix.** Add `test_no_match_message_shares_a_hint_line_across_entries_worded_alike`, the report's only three-entry test, which pins the shared non-contiguous hint line, the nested-key exclusion, the single resolve of the model's own forward and the footer's placement. No source change.

**Summary.** Tests only, for the no-match report the report commit (#196823) raises, split off the top of `[aot_compile] Pin which entries the no-match report's hint names forward for` (#197001) because that commit's five-test revision died at the review bot's 60-minute ceiling; the two tests that pin WHICH entry the hint names a `forward` for stay there, the two that pin WHEN the report resolves `forward` moved into #197301, and this one -- the report's only three-entry test, which reads the hint LINES rather than any one entry's wording -- comes here. It loads three SUPPLIED results from three `deserialize(GlobalConfigModule(), data, guard_globals=...)` calls, each holding a caller dict of its own, where `[0]` and `[2]` lack `GLOBAL_POOLING_CONFIG` and `[1]` has it bound to `{}` so its guard fails on the KEY. It pins four things at once: the hint lines are keyed by sentence and not by dict, so `[0]` and `[2]` share one non-contiguous `For [0, 2]:` line; `[1]`'s nested-key `KeyError on G['GLOBAL_POOLING_CONFIG']['pooling']` is the ordinary mismatch the whole-part match keeps off the hint; the report's one resolve is `assert_called_once_with(mixed.model)` on an `_unresolvable_forward_module()`, whose forward is a partial `get_traced_fn` refuses, so it returns `(None, reason)` without raising and no entry is told which forward; and the footer follows a report whose hinted list is non-contiguous. It passes at the parent, whose report it pins, and fails below the report commit (at #196896), where the no-match fall-through raises the function path's `GuardManager check failed` message with no `[i]` entry prefix, no `For [i]:` line and no `Tried N` header, on `Expected '_resolve_guard_scope' to be called once. Called 0 times`. Two targeted edits of `_no_match_report` that no other test in the file catches -- keying `hinted` by `(id(result._guard_globals), hint)`, and replacing `_names_a_missing_global` with a `"KeyError on G[" in part` substring test -- each fail this test alone, which is what shows the pin is not vacuous.

## Where this sits in the stack

Tests only, for the no-match report the report commit (#196823) raises, split off the top of `[aot_compile] Pin which entries the no-match report's hint names forward for` (#197001) because that commit's five-test revision died at the review bot's 60-minute ceiling. The two tests that pin WHICH entry the hint names a `forward` for stay there, the two that pin WHEN the report resolves `forward` moved into #197301, and this one -- the report's only three-entry test, which reads the hint LINES rather than any one entry's wording -- comes here.

## The fixture and the report it pins

```python
x = torch.randn(4, 8)
data = self._two_input_global_guard_artifact(x)
absent = {"__builtins__": builtins}                                   # no GLOBAL_POOLING_CONFIG
keyless = {**absent, "GLOBAL_POOLING_CONFIG": {}}                     # the global, without the key its guard reads
loads = [AOTCompiledModel.deserialize(GlobalConfigModule(), data, guard_globals=s)
         for s in (absent, keyless, dict(absent))]                    # three SUPPLIED results, three distinct dicts
results = [loaded.compiled_results[0] for loaded in loads]
assert [r._guard_scope for r in results] == [_GuardScope.SUPPLIED] * 3
assert len({id(r._guard_globals) for r in results}) == 3

mixed = AOTCompiledModel(self._unresolvable_forward_module(), results)
with patch("torch._dynamo.aot_compile._resolve_guard_scope", wraps=_resolve_guard_scope) as resolves:
    with self.assertRaises(RuntimeError) as ctx:
        mixed(x)
resolves.assert_called_once_with(mixed.model)
```

The report the test asserts, line by line:

```
No AOT compiled graph matched this call. Tried 3 compiled input(s):
  [0] KeyError on G['GLOBAL_POOLING_CONFIG']
  [1] KeyError on G['GLOBAL_POOLING_CONFIG']['pooling']
  [2] KeyError on G['GLOBAL_POOLING_CONFIG']
For [0, 2]: a guarded global is missing from the live scope this artifact was loaded against; define it there ...
Add a ModelInput ...
```

`test_no_match_message_shares_a_hint_line_across_entries_worded_alike` is the report's first three-entry test (`Tried 3` appears nowhere else in the file). The three entry lines are asserted exactly, `len(hints) == 1`, the one hint starts with `For [0, 2]:` and does not contain `instance's forward`, and `Add a ModelInput` is the last line. It shares `_two_input_global_guard_artifact` with `test_no_match_message_hints_each_scope_a_mixed_model_failed_in` and the landed `test_aot_compile_module_missing_global_hint_names_the_resolved_module` and, like them, does not call `_hide_leaked_dynamo_globals()`, its kept guards being rooted at `GLOBAL_POOLING_CONFIG` alone.

## The four things it pins

**First, hint lines are keyed by sentence, not by dict.** `[0]` and `[2]` carry no `__name__`, so their neutral sentences are identical and they share one non-contiguous `For [0, 2]:` line. Keying `hinted` by `(id(result._guard_globals), hint)` instead fails it on the line count (`Expected 1 but got 2`) and nothing else in the file: `..._names_the_resolved_module`'s `For [0, 1]` entries share one dict object. The merge is the intended reading: a per-dict line would print the same sentence twice, and the sentence names no dict, so the reader could not tell the two lines apart; two entries that give one instruction get one line.

**Second, the nested-key mismatch stays off the hint.** `[1]` is the nested-key mismatch the whole-part match keeps off the hint: replacing the report's `_names_a_missing_global` with a `"KeyError on G[" in part` substring test fails it on `For [0, 1, 2]:` and nothing else in the file, the fence the dropped `test_missing_key_inside_a_present_global_is_not_a_missing_global` carried (see the FAQ); the predicate itself is pinned on the function path by `test_aot_compile_fn_missing_nested_key_gets_no_missing_global_hint`.

**Third, the report resolves the model's own forward, once.** The model is `_unresolvable_forward_module()`, whose forward is a partial `get_traced_fn` refuses, so the report's one resolve -- `assert_called_once_with(mixed.model)` -- returns `(None, reason)` without raising and no entry is told which forward; the fixture's three other uses pass no `guard_globals=`, so their results are RECONSTRUCTED and never reach the resolve. The `_with(mixed.model)` is what pins which model the report asks about: resolving `type(self.model)()` instead fails this test on `expected call not found`, along with #197048's `covers_a_rebound_forward` and `survives_a_forward_resolve_that_raises` and #197001's `names_forward_only_for_the_dict_it_resolves_to`.

**Fourth, the footer follows a report whose hinted list is non-contiguous.**

## Where it is red

It passes at the parent, whose report it pins, and fails below the report commit (at #196896, the commit under it), where the no-match fall-through `results[0](self.model, *args, **kwargs)` raises the function path's `GuardManager check failed` message: that message carries the missing-global hint sentence the test also looks for, but no `[i]` entry prefix, no `For [i]:` line and no `Tried N` header, and with no report there is no resolve. Measured with that tree's `aot_compile.py` under this tree's test file, it fails on `Expected '_resolve_guard_scope' to be called once. Called 0 times`.

| mutation of `_no_match_report` | fails on | other tests in the file affected |
| --- | --- | --- |
| key `hinted` by `(id(result._guard_globals), hint)` | `Expected 1 but got 2` hint lines | none |
| `_names_a_missing_global` -> `"KeyError on G[" in part` | `For [0, 1, 2]:` | none |
| resolve `type(self.model)()` instead of `self.model` | `expected call not found` | #197048's `covers_a_rebound_forward` and `survives_a_forward_resolve_that_raises`, #197001's `names_forward_only_for_the_dict_it_resolves_to` |
| tree below the report commit (#196896) | `Expected '_resolve_guard_scope' to be called once. Called 0 times` | -- |

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_shares_a_hint_line_across_entries_worded_alike
python test/dynamo/test_aot_compile.py
```

The whole file is green here and on the parent commit.

## FAQ

> **FAQ: The report's comment on `hinted` says entries that share a scope
> share a sentence, but the dict is keyed by hint text, so two entries holding
> different dicts with identical wording collapse into one `For [0, 2]:` line.
> Is that intended, and why pin it rather than change it?**
>
> It is intended, and this commit changes no code. The hint sentence is the
> whole of what the reader gets: it names a scope only when the dict carries a
> `__name__` (`here vars(mod)`), and two caller-supplied dicts without one
> yield the identical sentence, so a per-dict line would print that sentence
> twice with nothing to tell the two lines apart. Two entries whose advice
> reads the same get one line; two entries whose advice differs -- a resolved
> module dict next to a supplied one, a CAPTURED entry next to a SUPPLIED one
> -- keep their own, which #197001's
> `names_forward_only_for_the_dict_it_resolves_to` and
> `hints_each_scope_a_mixed_model_failed_in` pin. The comment's "share a
> scope" is the common case of sharing a sentence, and belongs to #197149.

> **FAQ: An earlier revision had a separate
> `test_missing_key_inside_a_present_global_is_not_a_missing_global`. Where did
> it go?**
>
> Into this test's entry `[1]`, which fences the same edit: replacing the
> whole-part predicate with a substring test fails this test alone in the whole
> file, so the fold loses no coverage, and it buys the nested-key mismatch a
> place next to two whole-global ones in one report, where the point is that
> the hint skips it while the entry line still quotes it. The module path also
> keeps its own pin of the predicate on the function side.

> **FAQ: The test passes at the parent commit. Where is the red-on-parent
> evidence?**
>
> There is none by construction: this is a tests-only commit pinning the report
> the parent already ships, so it passes on the parent's tree. The two
> measurements that stand in for it are above: it fails under the tree below the
> report commit (#196896), where no report exists, and it fails under two
> targeted edits of `_no_match_report` that no other test in the file catches --
> the mutations are what show the pin is not vacuous.

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

Pull Request resolved: #197569
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220, #197001
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head 2dec23b5568d; the round-23 review predates two
re-slices, and of its findings one is now the next commit in the stack, three are
fixed in the tree, one needs no action, and the rest is description prose.

1. > I wrote that "the base already accepts a stale module whose __name__ equals the sys.modules key," making behaviour change (b) "narrower than stated." That is wrong. [...]

Already addressed at 2dec23b5568d: the correction holds and needs no change. The base
still calls unimplemented(...) unconditionally once the slot holds any different
object, so it accepts nothing, and both arms of the acceptance -- the module_name
arm and the value_name arm -- are introduced by this commit's predicate. The
description's behaviour change (b) is stated at full width and stays that way.

2. > symbolic_convert.py:2482 -- the accept path is followed by an unconditional write of the memo, so accepting install()'s live binding is immediately followed by overwriting it. [...]

Owned by #197256: that commit is exactly the conditional write you offered as the
alternative fix -- it computes live as module_name in sys.modules and sys.modules[module_name] is value
on the normal branch and True on the torch_package branch, and skips the write
when there is a same-named conflict and the resolved module is not live; #197046
above it then stops resolving through the memo at all. Keeping the write
unconditional here is what makes this commit the predicate alone, and the
divergence is now pinned by a test rather than argued (finding 4). The FAQ answer
you flag as measured against a parent that raised is genuine and is on the
description-edit list below.

3. > The description attributes to this commit five things that are in its base, and its Test Plan names no test that this commit adds except one. [...]

Open: still true at 2dec23b5568d, and prose-only. The graph break with its three
hints, the graph_break_registry.json entry, the hoisted Bad import result
check, the record-after-check ordering and behaviour changes (a), (c),
(d) are all 83dd71eb778's, and I confirmed the fifth -k
(..._accepts_a_stale_module_under_an_aliased_key) selects zero tests while the
whole file now runs 92, not 79. The fix is deletion: drop the "Two smaller moves"
section, (a)/(c)/(d) and the "Five cases" paragraph, and replace the -k list
with the six methods this commit adds.

4. > No test has the memo and the live entry differ, so the arm the first finding is about is uncovered. [...]

Already addressed at 2dec23b5568d: test_import_alias_puts_the_memo_back_over_the_installed_live_module
is the shape you described -- compile once to prime the memo, hand
sys.modules[name] to a second object, save_package/load_package/install(),
assert the alias holds the live module, then trace a second function in those
globals. It asserts the alias comes back to the memoized module, and that the
compiled function keeps returning x * 7 after the live module's VALUE moves to
8 with frame_count still 1, so the unseen divergence is pinned rather than
implied. -k import_alias is 14 tests, OK.

5. > The torch_package case is load-bearing on acceptance but not on the value_name term. [...]

Already addressed at 2dec23b5568d: that test's comment now says outright that the
registry is keyed by the module's own mangled __name__, and asserts
assertNotIn(mangled, sys.modules), so it no longer implies the widening is what
makes it pass. The two arms are pinned where you said they are, by
@parametrize("stale_named_for", ("target", "key")) on
test_import_alias_accepts_a_stale_module_of_either_accepted_name: one arm has
bound_name == value_name != module_name, the other bound_name == module_name != value_name.

6. > symbolic_convert.py:2452-2454 -- "Two module names mangling onto one alias still graph break: their resolved names differ" is stated as a guarantee and is an assumption. [...]

Already addressed at 2dec23b5568d: the comment reads "still graph break in practice:
their resolved names differ." Two distinct objects both answering to one
__name__ under a.b and a_dot_b are accepted, and nothing but their
improbability prevents it, so the sentence no longer reads as an invariant.

7. > Needs Discussion -- ... Two things need settling. [...]

Owned by #197256 and open on the description: the first item, the accept path's
unconditional write, is #197256 verbatim, with #197046 removing the memo
resolution above it; the second is the description, which is queued for the author to cut back to this commit's own content, with the stale FAQ measurement against an AssertionError-raising parent rewritten. No code change is owed at this
head.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 18m 57s —— View job


Twenty-fourth pass: round twenty-three's finding is now pinned as intended behaviour — the new test_import_alias_puts_the_memo_back_over_the_installed_live_module asserts that under fullgraph=True the compiled function returns a stale answer that differs from eager, where the base raises. That makes the design question unavoidable rather than latent, and the FAQ defending it still measures against a parent that raised AssertionError rather than the graph break the base actually has.

Full review

PR Review: #196896

Summary

git diff origin/gh/bobrenjc93/1184/base...HEAD is 57 changed lines in symbolic_convert.py — only the value_name widening of the acceptance predicate plus comments — and 291 in test_package.py (five new methods, six instantiated). The graph break, the hoisted Bad import result check, the record-after-check ordering, the graph_break_ok split and the registry entry are all at base. One design question that now needs settling, one stale docstring, two smaller test items.

Infrastructure

symbolic_convert.py:2509 — the accept path is followed by an unconditional write of the memo, and test_import_alias_puts_the_memo_back_over_the_installed_live_module (test_package.py:1142) now pins the consequence as correct: a fullgraph=True compile that silently returns the wrong answer, where the base raises. I walked the test's state machine against the two trees:

base HEAD
fn2's trace, memo=old, slot=new (install's live binding) f_globals[alias] is not value → straight to unimplemented (base :2444-2480; the name read only builds the message) → Unsupported, and under fullgraph=True that is an error bound_name == value_name == module_name → in accepted (:2472) → write f_globals[alias] = value (:2509)
slot after the trace new — install's binding intact old — pinned at :1189
new.VALUE = 8 n/a frame_count stays 1 (:1194), compiled serves x * 7 (:1192), assertNotEqual(fn2(*args), compiled_fn2(*args)) (:1193)

So on this exact arm the delta is not "loud AssertionError → visible recompile", which is what the second FAQ answer measures; it is fullgraph=True error → silent divergence from eager, with no recompile and no guard able to fire. I re-verified why nothing catches it: IMPORT_NAME constructs PythonModuleVariable(value, source=source) directly rather than through VariableBuilder, so no MODULE_MATCH is installed on the alias; MODULE_MATCH is unserializable regardless; and an attribute guard's expected value is re-derived through the same alias, so expected read and runtime read both come from the memo and agree while the graph holds the live module's constant.

The description's third paragraph discloses the direction and says #197046 closes it, and the test comment says the same — so this is not hidden. The problem is that the argument for shipping it is measured against a tree that no longer exists: the FAQ's "Pre-PR that sequence raised the AssertionError, which is loud and safe" and its three-tree measurement predate the base absorbing unimplemented. On the current base the sequence graph-breaks and leaves install's live binding in place, so the base outcome is neither a crash nor a stale artifact — under fullgraph=True it is a hard error the user sees, and without fullgraph it is an eager fallback. Baking the opposite into a test as an expected value, for one commit, is the call I would want stated explicitly rather than inherited from a stale measurement. Fix this →

The description attributes to this commit five things that are in its base. At origin/gh/bobrenjc93/1184/base: the unimplemented graph break with all three hints (:2470-2480), the graph_break_ok parameter and the hard-error arm for the codegen/tracing callers (:2465-2469), the hoisted module-type check (:2562-2568, comment "Before import_source, which binds the result…"), the record-after-check ordering (:2481-2485), and the graph_break_registry.json entry (grep -c → 1, and the file is unchanged in this diff). Behaviour changes (a), (c), (d) are all the base's. So are three of the five tests the Test Plan's -k invocations name (taken_by_a_non_module_graph_breaks, the_trace_refused_is_not_recorded_for_install, is_not_bound_to_a_non_module_import at base :1081, :1280, :1327), and one invocation — ..._accepts_a_stale_module_under_an_aliased_key — selects zero tests, that method having been renamed to ..._of_either_accepted_name. The five methods this commit adds appear nowhere in the Test Plan.

Code Quality

symbolic_convert.py:2424-2428 — the docstring now states the opposite of what the method does. "A slot already holding something other than the resolved module is a hard error unless graph_break_ok says the caller can graph break there." After this commit a slot holding a same-named module is neither: it is accepted and overwritten, which is the entire change. The docstring is byte-identical to base's, so it was simply not touched; a reader who trusts it will conclude the relaxation is not there. It is the one place a caller of import_source looks, and the two callers that pass no graph_break_ok (:2384, :6539) depend on knowing which slots still raise.

Testing

test_package.py:1250 — test_import_alias_accepts_a_stale_torch_package_module is not load-bearing on the term this commit adds, and its comment implies it is. _package_imported_modules is keyed by the module's own mangled __name__ (package_importer.py:390-394 stores under module.__name__, asserting uniqueness; _mangling.py:27-30 builds that name), so on that branch module_name == value_name and accepted collapses to a single distinct name — the module_name arm is what accepts, not value_name. The test does fail on base (which accepts nothing), so it is not vacuous, but it pins the acceptance rather than the widening. Worth one clause in the comment, since the two arms are properly separated by the @parametrize at :1093.

Same test, cleanup asymmetry: its sibling test_import_alias_taken_in_a_torch_package_slot_is_a_hard_error pops the registry entry in finally (:1443, added in this PR's most recent commit) and this one does not, though both import a package and leave an entry behind. The entry is weakly held so it cannot collide with a later mangled name, but the inconsistency between two adjacent tests doing the same setup is the kind of thing that reads as an oversight rather than a decision.

test_package.py:1596 — the comment references cache_method, which import_source no longer uses. "A refused call stores nothing in cache_method's cache, which fills on the return path only." The method is memoized by the explicit _import_source_memo dict, and the comment at symbolic_convert.py:2415-2420 exists specifically to say why it is not @cache_method (graph_break_ok would be part of the key). The assertion itself is right (assertNotIn(key, tx._import_source_memo) at :1625); only the prose points at the wrong mechanism.

Recommendation

Needs Discussion — the value_name widening is correct in itself and both of its arms plus the value_name is None fallback are pinned by mutations I could name, and I verified the torch_package registry-keying premise and the object.__getattribute__ reads independently. What needs settling is that the commit now ships, and asserts as correct, a fullgraph=True compile whose output differs from eager on an arm where the base raises — defended by a FAQ measurement taken against a parent that raised AssertionError rather than the graph break the base has. The stale docstring is a line; the two test items are a clause each.

Note: reviewed statically. No built torch extension in this checkout (torch/_C*.so absent, no .venv), so test/dynamo/test_package.py was not run; every claim above is read off the cited lines in this tree or in git show origin/gh/bobrenjc93/1184/base.

| Branch: `gh/bobrenjc93/1184/head`

[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head 32a5d50767bd; the docstring and the two test items are folded, the description is queued for the author, and the write-back question is the author's call and is left open here.

1. > symbolic_convert.py:2509 -- the accept path is followed by an unconditional write of the memo, and test_import_alias_puts_the_memo_back_over_the_installed_live_module now pins the consequence as correct: a fullgraph=True compile that silently returns the wrong answer, where the base raises. [...]

Open, for the author to decide: whether this commit should stop writing the memo back over an accepted same-named binding (which is what #197256 directly above does conditionally, and #197046 removes by resolving the live entry), or keep the two-step shape with the FAQ re-measured against the current base, where the sequence graph-breaks rather than raising AssertionError. No code changed on this arm at 32a5d50767bd; the stale FAQ measurement is on the author's description-edit list.

2. > The description attributes to this commit five things that are in its base. [...]

Queued for the author: the description edits are listed (drop the base-owned sections and behaviour changes, replace the -k list with the methods this commit adds, fix the whole-file count); the body is hand-maintained, so it is not rewritten by script.

3. > symbolic_convert.py:2424-2428 -- the docstring now states the opposite of what the method does. [...]

Fixed in 32a5d50767bd: the docstring adds the third outcome, "except a module of the same name, which is accepted and replaced by the resolved module".

4. > test_package.py:1250 -- test_import_alias_accepts_a_stale_torch_package_module is not load-bearing on the term this commit adds, and its comment implies it is. [...] Same test, cleanup asymmetry [...]

Fixed in 32a5d50767bd: the comment says the registry is keyed by the module's own mangled __name__, so module_name == value_name there and the test pins the acceptance rather than the widening, and its finally pops the registry entry like its sibling.

5. > test_package.py:1596 -- the comment references cache_method, which import_source no longer uses. [...]

Fixed in 32a5d50767bd: the comment and the two places in the commit message that quoted it name _import_source_memo.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 27m 2s —— View job


Twenty-fifth pass: the round-24 items are folded and I re-verified each. The new finding is that the acceptance arm sits above the graph_break_ok split, so it silently exempts the same-named case from the deliberate hard error on the seven callers the comment two lines below says must keep it — and the one test that reaches acceptance through such a caller takes the torch_package branch, where staleness is structurally impossible, so it cannot stand in for the __import_ arm.

Full review

PR Review: #196896

Summary

git diff origin/gh/bobrenjc93/1184/base...HEAD is 60 changed lines in symbolic_convert.py — the acceptance predicate in import_source plus comments and the docstring — and 295 in test_package.py (six new methods, seven instantiated). graph_break_registry.json is unchanged versus base. One infrastructure/coverage finding, one small code-quality point, and the description.

Infrastructure

symbolic_convert.py:2476 — the acceptance arm is nested above the graph_break_ok split, so it applies to the seven callers whose refusal the comment at :2484-2490 deliberately keeps as a hard error, and nothing in the method says so. I verified the control flow: if bound_name not in accepted: at :2476 wraps both refusal paths, and if not graph_break_ok: raise AssertionError at :2491 is nested one level inside it. So when bound_name in accepted, neither raise nor unimplemented is reachable and graph_break_ok is never consulted — control falls straight to f_globals[alias] = value at :2512. At base (:2445-2470) there is no accepted comparison at all: once f_globals[alias] is not value, control reaches if not graph_break_ok: raise AssertionError unconditionally.

That is a defensible call, but it is the exact case the comment at :2484-2490 argues against, in that comment's own words — "the tracing-phase callers keep it too, for now: whether they should break instead is deferred" — and the same-named case is now silently exempt from the deferral. Where it bites is get_globals_source_and_value's __import_ arm (:6542, no graph_break_ok), and each step checks out:

  • _registered_module_for_globals returns a module only when module.__dict__ is f_globals (:283), so fglobals_value is provably the object currently in sys.modules under that key.
  • value = _import_module(module_name) (:2443) is functools.cached (:260-267) with no invalidation anywhere in torch/ — the only cache_clear() calls in the tree are test_package.py teardowns — so after a handover it can be an older object.
  • With the alias slot holding the live module (which is what CompilePackage.install binds, package.py:1334-1340 → the unconditional module.__dict__[name] = value at :1289), bound_name == value_name == module_name, the slot is accepted, and the memo is written over it.
  • VariableBuilder(self, module_source)(fglobals_value) at :6546 then builds the VT from the live object while module_source is GlobalSource(alias). VariableBuilder installs MODULE_MATCH for a plain module (variables/builder.py:1933), and MODULE_MATCH (guards.py:3122) → id_match_unchecked (:2664) takes val = self.get(guard) (:2675), i.e. it evaluates G['__import_...'] against scope["G"] = global_scope (:1369, torch/_guards.py:1448) — so the expected id comes from the alias slot (the memo), not from the VT's value. Same for the replayed write: InliningInstructionTranslator.STORE_GLOBAL (:6612) → side_effects.store_attr, replayed at side_effects.py:2079-2083 as cg(value); cg(var); STORE_ATTR, and cg(var) routes through codegen.py:300-327 to GlobalSource.reconstruct (source.py:251-252) emitting LOAD_GLOBAL <alias>.

One correction to a claim earlier rounds have made about this path, since it changes the severity: the alias lives in self.output.global_scope (:2446), the root frame's globals — not the inlined callee's module dict. The comment at :2481-2482 says exactly that. So the divergence is between the root frame's alias slot and the callee module the VT wraps, which is narrower than "writes into the live module's own dict."

Reachability needs a handover plus a writer having pre-bound the live module plus the inlined-callee shape, so I am not asking for the acceptance to be narrowed. What I would want is one clause in the :2484-2490 comment acknowledging that the same-named case no longer reaches the split it describes, and coverage (below). Fix this →

Testing

No test covers same-named acceptance on the __import_ arm of a caller that does not pass graph_break_ok, and the one test that reaches acceptance through such a caller cannot stand in for it. The three hard-error tests all plant a str (:1389, :1441, :1471), so they still refuse and none of them exercises the new arm. test_import_alias_accepts_a_stale_torch_package_module (:1250) does plant a same-named module (types.ModuleType(mangled) at :1276) and does reach get_globals_source_and_value with no graph_break_ok — but on the torch_package branch, and I verified that branch cannot have the divergence the finding above is about: _package_imported_modules is keyed by the module's own mangled __name__ with a hard uniqueness assert at package_importer.py:389-394, its only writer is :394, and _mangling.py:9-25 increments a process-global index so no two manglers ever produce the same <torch_package_N> prefix. A key is therefore never rebound, value is never older than a later read, and the only same-named module that can occupy that slot is one never registered — which is what the test constructs. The __import_ arm's three acceptance tests (:1093, :1142, :1201) all go through IMPORT_NAME, i.e. graph_break_ok=True.

That gap matters more than a missing case usually would, because it is the arm where the base's behaviour was a deliberate AssertionError rather than a graph break, and because the write it performs is the one MODULE_MATCH and the replayed STORE_GLOBAL both read. test_import_alias_taken_for_an_inlined_callees_module_is_a_hard_error (:1451) is the fixture — same shape, same-named module in the slot instead of a str.

Code Quality

test_package.py:1613 — tx.import_source(key, True) passes graph_break_ok as a positional bool. Both production call sites spell it out (:2615, :2617 both use graph_break_ok=True), and the parameter is keyword-defaulted precisely because a bare True at a call site says nothing. The comment above the test names the flag, so the call should too.

What I verified as fixed since round twenty-four

  • The docstring is accurate. :2426-2430 now names the third outcome ("except a module of the same name, which is accepted and replaced by the resolved module").
  • test_import_alias_accepts_a_stale_torch_package_module's comment no longer implies the widening is what makes it pass (:1255-1258, "the registry is keyed by the module's own mangled __name__, so module_name == value_name here"), and its finally pops the registry entry (:1281) like its sibling at :1448.
  • The cache_method reference is gone (:1601-1602 names _import_source_memo, matching :5586 and the read/write at :2432/:2515).
  • The memo comment at :2415-2421 is now correct on the mechanism it claims: the memo is written only past the check (:2515, after :2476), so a refusal memoizes nothing and a memo hit implies f_globals[alias] is value for the rest of that translator's life — graph_break_ok genuinely cannot matter on a hit.
  • The accepted arms and the value_name is None fallback are each load-bearing. Dropping value_name fails the target parametrization of :1093; dropping module_name fails the key one; dropping the if value_name guard fails the nameless-module leg of :1589, which now also has assertEqual(len(seen), …) before each unpack (:1626, :1637), closing round twenty-one's item.
  • Both __name__ reads go through object.__getattribute__ (:2460, :2471), and test_import_alias_check_does_not_run_a_module_getattribute (:1532) plants _ImportAliasHookedModule in both slots, so it fails if either read becomes a plain attribute access.

Infrastructure (description)

The description still attributes to this commit five things present at base — the unimplemented graph break with all three hints (base :2471-2481), the graph_break_ok split (base :2466), the hoisted Bad import result check, the record-after-check ordering (base :2482-2486), and the graph_break_registry.json entry (unchanged in this diff) — so behaviour changes (a), (c), (d) are the base's, three of the five -k invocations select base tests, and -k …accepts_a_stale_module_under_an_aliased_key selects zero. You have this queued; noting it only because it is still the thing that makes the diff and the prose describe different changes.

Recommendation

Approve with comments — the predicate is correct, both of its arms plus the value_name is None fallback are pinned by mutations I could name, and I independently confirmed the torch_package registry-keying premise and the object.__getattribute__ reads. Before landing I would want the :2484-2490 comment to acknowledge that the same-named case no longer reaches the graph_break_ok split, and one test covering that acceptance on the __import_ arm of a non-graph_break_ok caller — the arm where the base's behaviour was a hard error and where the memo/live divergence is reachable. The positional bool is one line.

Note: reviewed statically. No built torch extension in this checkout (torch/_C*.so absent, no .venv), so test/dynamo/test_package.py was not run; every claim above is read off the cited lines in this tree or in git show origin/gh/bobrenjc93/1184/base.

| Branch: `gh/bobrenjc93/1184/head`

[ghstack-poisoned]
@bobrenjc93
bobrenjc93 marked this pull request as ready for review September 19, 2026 21:52
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93 bobrenjc93 closed this Sep 20, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1184/head branch November 24, 2026 01:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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