Skip to content

[dynamo] Check IMPORT_NAME's result is a module before binding an alias - #197745

Closed
bobrenjc93 wants to merge 3 commits into
gh/bobrenjc93/1287/basefrom
gh/bobrenjc93/1287/head
Closed

bobrenjc93 wants to merge 3 commits into
gh/bobrenjc93/1287/basefrom
gh/bobrenjc93/1287/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Problem. IMPORT_NAME checked that __import__'s result was a module only after import_source had already bound the result into the traced globals and a process-wide cache, so a non-module sys.modules entry was left behind in both, and a later trace with a real module in the entry crashed with an InternalTorchDynamoError instead of compiling.

Fix. Move the module-type check ahead of the import_source call, so a non-module never reaches the traced globals or the cache and the graph break happens first; the replay arm needs no check and pushes as-is.

Summary. IMPORT_NAME tested __import__'s result with isinstance(value, (types.ModuleType, DummyModule)) at push time, after import_source had already minted __import_<mangled> for the name and written that result into self.output.global_scope -- the root frame's real globals, a live module __dict__ that nothing unwinds -- and into _import_module's process-wide cache. sys.modules accepts any object and __import__ hands it back verbatim, so a non-module entry was bound under the alias and only then graph-broken on (Bad import result), and a later trace, after a real module had replaced the entry, passed the push-time check on the module __import__ returned while import_source served the cached non-module: the alias kept the non-module, the pushed variable held the module, and the guards built on the alias read VALUE off an object(), an InternalTorchDynamoError on a trace that should have compiled. Hoisting the check ahead of the import_source call keeps the non-module out of the traced globals and out of the cache, since the call that filled it no longer runs, so a later trace with a real module in the entry binds the alias to that module and compiles. The hoisted test is isinstance(value, types.ModuleType) alone and sits on the import arm only, because a replayed value is a DummyModule, a plain dataclass that is not a ModuleType, which add_local_mod already rejected non-modules for when the record was written, so the replay arm pushes with no type test and the DummyModule import goes away. Two behaviours change against the parent, both pinned or explained below: IMPORT_NAME of a non-module entry no longer writes the alias before breaking, and with replay_record_enabled on such an entry reaches the graph break instead of add_local_mod's AssertionError.

The bug: bind first, check second

# parent, IMPORT_NAME
value = __import__(module_name, ...)                    # sys.modules[name] handed back verbatim
source = self.import_source(module_name)                # mints __import_<mangled>, writes value into
                                                        # self.output.global_scope AND _import_module's cache
if isinstance(value, (types.ModuleType, DummyModule)):  # checked only now
    self.push(PythonModuleVariable(value, source=source))
else:
    unimplemented(gb_type="Bad import result", ...)     # too late: the alias is already bound

self.output.global_scope is the root frame's real globals, a live module __dict__ that nothing unwinds, so the non-module stayed bound under the alias for good. The second failure follows from the cache:

sys.modules[name] = object()
torch.compile(fn)(x)        # parent: Unsupported: Bad import result -- but fn.__globals__["__import_..."] is the object()
torch._dynamo.reset()
sys.modules[name] = module  # a real module now
torch.compile(fn)(x)        # parent: InternalTorchDynamoError -- the guards read VALUE off the cached object()
                            # now:    compiles, agrees with eager, alias bound to `module`

On the parent's second trace, __import__ returned the module, so the push-time check passed, but import_source served the cached non-module: the alias kept the non-module, the pushed variable held the module, and the guards built on the alias read VALUE off an object().

The fix: check before import_source

# now, IMPORT_NAME, import arm
value = __import__(module_name, ...)
if not isinstance(value, types.ModuleType):
    unimplemented(gb_type="Bad import result", context=typestr(value),
                  explanation="Import result is not a Python module.", hints=[])
...
source = self.import_source(module_name)                # never reached with a non-module
...
self.push(PythonModuleVariable(value, source=source))   # no type test on either arm

Hoisting the check ahead of the import_source call keeps the non-module out of the traced globals and out of the cache, since the call that filled it no longer runs: a later trace with a real module in the entry binds the alias to that module and compiles.

Why ModuleType alone, on the import arm only. A replayed value is a DummyModule, a plain dataclass that is not a ModuleType, so a check on that arm would refuse every replay -- and needs none, add_local_mod having rejected non-modules when the record was written. That is why the replay arm now pushes with no type test at all, and why the DummyModule half of the old condition, which existed only for it, goes away with the import from replay_record.

The other nine import_source callers

The check guards this one call site. The other nine import_source callers reach it with no module-type test, and a non-module entry under one of their names is still bound verbatim there, unchanged here -- though get_globals_source_and_value already brings its own test, since _registered_module_for_globals returns a name only for a types.ModuleType whose __dict__ is the frame's globals. Those names are torch's own and stdlib ones, or a class's __module__; a non-module under one of them is a broken process, not a trace to save. IMPORT_NAME is the one caller resolving a name the traced bytecode chose, which is what makes its result worth checking.

Behaviour changes against the parent

  • 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 pins it by planting a non-module, requiring the Bad import result graph break and an unbound alias, and then, with a real module in the entry, a compile that agrees with eager and an alias bound to that module.
  • With replay_record_enabled on (off by default), such an entry now reaches that graph break instead of the AssertionError add_local_mod raised first when it ran ahead of the check. That one is untested, since the path is the parent's add_local_mod and the config is off by default.

The test

name = "torch_test_package_import_alias_non_module"
alias = f"__import_{name}"

def fn(x):
    import torch_test_package_import_alias_non_module as taken
    return x + taken.VALUE

sys.modules[name] = object()
with self.assertRaisesRegex(Unsupported, "Bad import result"):
    torch.compile(fn, backend="eager", fullgraph=True)(*args)
self.assertNotIn(alias, fn.__globals__)              # parent: the alias is bound to the object()
torch._dynamo.reset()
sys.modules[name] = module                           # types.ModuleType(name) with VALUE = 1
compiled = torch.compile(fn, backend="eager", fullgraph=True)
self.assertEqual(fn(*args), compiled(*args))         # parent: InternalTorchDynamoError from the guard build
self.assertIs(fn.__globals__[alias], module)

The cleanup clears _import_module's cache as well as sys.modules and the alias, since the memo outlives the sys.modules entry and a same-process rerun would otherwise resolve this run's module from it.

The test lives in test_package.py rather than test_misc.py because the alias binding this is about is the one CompilePackage records and install() rebinds, and that file already owns the rest of the import_sources coverage.

Test Plan:

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

The new test is red on the parent's torch/_dynamo/symbolic_convert.py, on the
alias the parent wrote before breaking, and its second half fails there too,
with the guard-build AttributeError on the cached object(); restoring the
push-time isinstance in place of the hoisted one reproduces the first failure. The whole file is green at
this commit.

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

The Bad import result registry entry is unchanged: the call moves, its
strings do not.

Authored with the assistance of Claude Code.

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

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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 d239de4 with merge base 51d4378 (image):

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

  • Correctness
    • Hoisting the isinstance(value, types.ModuleType) test to symbolic_convert.py:2516 keeps a non-module out of the alias import_source writes into output.global_scope at :2439.
    • The graph break is unchanged in kind and strings, so registry entry GB0022 in graph_break_registry.json:313 still matches.
    • test_misc.py:18334's types.ModuleType subclass still passes isinstance, so that regression test is unaffected.
  • Replay arm
    • Dropping the type test there is backed by add_local_mod rejecting non-modules at replay_record.py:101-104 and _resolve_modules minting the DummyModules at :130-143.
    • Nothing puts a DummyModule into sys.modules, so the import arm's stricter test cannot reject a legitimate replay value.
    • Removing the DummyModule import is safe: the only other user is variables/builder.py:1927, which imports it from replay_record directly.
  • Testing
    • test_package.py:1073 pins both halves: the Bad import result break with assertNotIn(alias, fn.__globals__), then a real module in the entry with assertIs(fn.__globals__[alias], module).
    • The finally block restores sys.modules, the alias, and _import_module.cache_clear(), so the planted state does not leak to other tests.
  • Scope
    • Two files, one opcode handler plus one test; no public API, docs, or CI workflow change in the diff.

reason: clean
Reviewed commit: d239de4

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.

@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 23m 35s —— View job


Reviewed: the code change is a real improvement, but the PR description's central motivation (a second trace dying on import_source's alias assertion) is unreachable because _import_module is @functools.cache'd, which makes the test's second loop iteration redundant.

Full review

PR Review: #197745

Summary

Hoists IMPORT_NAME's module-type check ahead of import_source so a non-module sys.modules entry never gets bound under __import_<name> in the traced frame's globals. The hoist itself is correct and fixes a real latent inconsistency, but the stated failure mode that motivates it does not exist, one defensive check was dropped without a replacement, and two pyrefly suppressions look stale.

Testing

  • test/dynamo/test_package.py:1089 — the loop over (object(), object()) does not test what the description says it tests. import_source resolves the module through _import_module (torch/_dynamo/symbolic_convert.py:260-267), which is @functools.cached, and nothing clears that cache — torch._dynamo.reset() clears only the trace_rules caches (torch/_dynamo/trace_rules.py:4302-4307). So on the parent commit the second trace still resolves the first object() inside import_source, f_globals[alias] is value holds, the alias assertion passes, and the trace graph-breaks on Bad import result exactly like the first. The alias-collision AssertionError the PR body describes ("A second trace, after the entry had been swapped for another non-module, then found the alias holding neither the module it names nor the object being resolved, and died on import_source's alias assertion") cannot be reached in a single process for a non-torch_package name.

    What is actually red on the parent is the assertNotIn(alias, fn.__globals__) on the first iteration — the leaked alias. That is the behaviour worth pinning, and it needs one entry, not two. Either drop the loop and test a single planted non-module, or keep two iterations for a scenario that genuinely differs. The commit message must be corrected either way: per CLAUDE.md it has to explain the real root cause, and right now it explains a failure mode that the functools.cache prevents.

    There is a related scenario the change does fix which the description misses and which would be worth pinning instead: plant a non-module, compile (parent binds alias → non-module and caches nothing, since import_source is what calls _import_module), then replace the entry with a real module and compile again. On the parent, __import__ returns the real module, passes the push-time check, and gets pushed with source=GlobalSource(alias) while f_globals[alias] still holds the stale non-module — a source/value mismatch that guards are then built against. On this commit the alias was never written, so the second trace binds it correctly.

    Fix this →

Code Quality

  • torch/_dynamo/symbolic_convert.py:2547-2548 — the push is now unconditional, so the replay arm has no type check at all. The invariant the comment leans on (add_local_mod rejects non-modules, replay_record.py:101-104) only covers records this process wrote; the arm is entered on recorded_name in self.f_globals (line 2494), which any global literally named ___local_mod_<level>_<fromlist>_<name> satisfies, as does a hand-edited/unpickled record. In that case PythonModuleVariable.__init__ reads self.value.__name__ (torch/_dynamo/variables/misc.py:2009) and an AttributeError escapes as an internal error instead of the clean Bad import result graph break the parent produced. Since the check has to be a graph break on the import arm, keep a cheap assertion on the replay arm — isinstance(value, (types.ModuleType, DummyModule)) — so the invariant is enforced where it is assumed rather than only documented.
  • torch/_dynamo/symbolic_convert.py:2518 and :2522 — # pyrefly: ignore [unbound-name] looks stale in its new position. In the old location the suppressions were needed because value was assigned in two branches; inside the else arm value is assigned at line 2499 and the only other exit is unimplemented, which is -> NoReturn. permissive-ignores = true in pyrefly.toml:138 means an unneeded ignore won't fail lint, so this won't show up in CI — please confirm by removing them and re-running pyrefly locally, and drop them if they aren't required. (Low confidence: I could not run pyrefly in this environment.)
  • torch/_dynamo/symbolic_convert.py:2513-2517 — the five-line comment is about the PR's own history ("Only this arm can take the check ... it would refuse every replay") rather than the invariant a future reader needs. Two lines stating the invariant — non-module must not reach import_source, and the replay arm's values are DummyModules guaranteed by add_local_mod — carry the same information. Same for test/dynamo/test_package.py:1074-1078, whose second and third sentences describe the unreachable scenario above and will be wrong once the description is corrected.

Recommendation

Request Changes

The code change is right and worth landing. What blocks it is the commit message, which attributes the fix to a failure mode _import_module's cache makes impossible, and the test's second iteration, which exercises nothing the first does not. Restoring a type assertion on the replay arm is a small addition that keeps the invariant enforced where the new code assumes it.

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

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head 66d16785c600; items 1, 3 and 4 are folded, item 2 is declined.

1. > test/dynamo/test_package.py:1089 -- the loop over (object(), object()) does not test what the description says it tests. [...] What is actually red on the parent is the assertNotIn(alias, fn.__globals__) on the first iteration [...] There is a related scenario the change does fix which the description misses and which would be worth pinning instead [...]

Fixed in 66d16785c600, both halves. The test plants one non-module, requires the Bad import result break and an unbound alias, then puts a real module in the entry and requires a compile that agrees with eager with the alias bound to that module. Measured on the parent's symbolic_convert.py: the first half fails on the bound alias and the second dies in guard construction with AttributeError: 'object' object has no attribute 'VALUE' on the cached non-module, exactly the source/value mismatch you describe; on this commit both pass. The commit message now states that as the defect, with the _import_module cache named as what made the parent's later trace wrong, and drops the unreachable alias-assertion story.

2. > torch/_dynamo/symbolic_convert.py:2547-2548 -- the push is now unconditional, so the replay arm has no type check at all. [...] keep a cheap assertion on the replay arm [...]

Declined: the replay arm's values come from records this process wrote through add_local_mod, which rejects non-modules, and a hand-edited record or a user global literally named ___local_mod_<...> is a broken record rather than a trace to save; the assertion would trade one internal error for another on that path while re-importing DummyModule here for no traced-code case. The comment says what the arm relies on.

3. > torch/_dynamo/symbolic_convert.py:2518 and :2522 -- # pyrefly: ignore [unbound-name] looks stale in its new position. [...]

Fixed in 66d16785c600: both suppressions are removed; lintrunner --take PYREFLY on the file reports no error with or without them, so they were dead in the new position.

4. > torch/_dynamo/symbolic_convert.py:2513-2517 -- the five-line comment is about the PR's own history [...] Same for test/dynamo/test_package.py:1074-1078 [...]

Fixed in 66d16785c600: three lines stating the invariant (a non-module must not reach import_source; the replay arm needs no check, its values being the DummyModules add_local_mod admitted), and the test comment describes the two scenarios the rewritten test pins.

@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 14m 41s —— View job


Re-reviewed: the code change is correct and the test was reworked into the right shape, but the PR description still describes the old two-non-module test and a root cause that _import_module's cache makes unreachable, so it needs rewriting before landing.

Full review

PR Review: #197745

Summary

Hoists IMPORT_NAME's module-type check ahead of import_source so a non-module sys.modules entry never gets bound under __import_<name> in the traced frame's globals. Since my last pass the test was reworked to the plant-non-module-then-real-module scenario and the stale pyrefly suppressions are gone, so the remaining problems are the PR description, which no longer matches either the test or a reachable failure mode, and two smaller issues in the test.

Testing

  • The PR description contradicts the test it cites. The body says the fix is pinned "by planting two successive non-module entries and requiring that neither is bound and that both graph-break as Bad import result." test/dynamo/test_package.py:1091-1100 plants one non-module, then replaces it with a real module and asserts fn.__globals__[alias] is module. The description describes a test that is not in the diff.

  • The stated root cause is unreachable. The third paragraph attributes the fix to a second trace that "found the alias holding neither the module it names nor the object being resolved, and died on import_source's alias assertion." That AssertionError (torch/_dynamo/symbolic_convert.py:2435-2439) cannot fire here. import_source resolves the module through _import_module (torch/_dynamo/symbolic_convert.py:260), which is @functools.cache'd and is cleared nowhere in non-test code — torch._dynamo.reset() clears FakeTensorMode and the trace_rules caches, not this one. So on the parent, the second trace gets the same cached object back, f_globals[alias] is value holds, and the assertion passes.

    What is actually broken on the parent — and what the reworked test now correctly pins — is the stale binding: import_source computes value = _import_module(name), which returns the cached first non-module, so f_globals[alias] stays bound to the non-module while __import__ hands back the real module, and PythonModuleVariable is pushed with source=GlobalSource(alias) pointing at a slot holding something else. Guards then get built against that mismatch. That is the failure mode; the description should say so. Per CLAUDE.md the commit message has to explain the real root cause, and for a ghstack commit the body is the PR description, so this needs a message edit plus ghstack -u.

    Fix this →

  • test/dynamo/test_package.py:1074 — the test does not belong in TestPackage. The class carries @functorch_config.patch("bundled_autograd_cache", True) and @torch._dynamo.config.patch({"strict_precompile": True}) (test/dynamo/test_package.py:132-135), neither of which this test wants, and the only assertions are about fn.__globals__ and a graph break — nothing about CompilePackage or install(). Its sibling for the adjacent case already lives in test_misc.py:18334 (test_import_user_defined_module, the types.ModuleType subclass that motivated the same Bad import result path). Put the new test next to it so both halves of the type check are covered in one place and neither inherits precompile config it does not use.

  • test/dynamo/test_package.py:1104 — _import_module.cache_clear() is load-bearing but unexplained, so it reads as defensive cleanup and will be deleted. Without it, a repeat run in the same process resolves the name from a cache entry whose module is no longer in sys.modules. One line saying that is enough. The same line is also why the test reaches into torch._dynamo.symbolic_convert for a private symbol, which is worth making obvious.

Recommendation

Request Changes

The code change at torch/_dynamo/symbolic_convert.py:2513-2522 is right, and hoisting the check also happens to move it ahead of calc_package()/resolve_name(), so a relative import of a non-module no longer risks an uncaught ImportError from resolve_name before the graph break. What blocks it is the description: it cites a test that is not in the diff and a root cause the functools.cache prevents. The test's home and the unexplained cache_clear() should be fixed in the same pass.

I could not run python test/dynamo/test_package.py -k test_import_alias_is_not_bound_to_a_non_module_import or pyrefly in this environment (no built torch), so the red-on-parent / green-on-this-commit claims in the Test Plan are unverified here.

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

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head d239de4c3783; the description is refreshed, the cache_clear() line is explained, and the test stays where it is.

1. > The PR description contradicts the test it cites. [...] > The stated root cause is unreachable. [...]

Fixed: the commit message was corrected in the previous push (it names the _import_module cache as what made the parent's later trace wrong, and describes the non-module-then-real-module test), but ghstack leaves an existing PR body alone, so the description you read was the first publish's text. The body is now the current message at d239de4c3783.

2. > test/dynamo/test_package.py:1074 -- the test does not belong in TestPackage. [...]

Declined: the class-level bundled_autograd_cache and strict_precompile patches do not bear on this test's assertions, and the rest of the test_import_alias family, which the two commits above add to and which this test is the base case of, lives in this file next to the import_sources coverage; splitting the family across two files would cost more than it buys.

3. > test/dynamo/test_package.py:1104 -- _import_module.cache_clear() is load-bearing but unexplained [...]

Fixed in d239de4c3783: a two-line comment says the memo outlives the sys.modules entry and a same-process rerun would otherwise resolve this run's module from it.

@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 44m 54s —— View job


Re-reviewed at d239de4: the three folded items check out and the two declines are reasonable, so this is approvable — one inaccurate comment reference is all that's left.

Full review

PR Review: #197745

Summary

Hoists IMPORT_NAME's module-type check ahead of import_source so a non-module sys.modules entry never gets bound under __import_<name> in the traced frame's globals. Everything flagged in the previous two rounds is now either folded or declined with reasoning I accept; one comment points a reader at the wrong function for the invariant it states.

Code Quality

  • torch/_dynamo/symbolic_convert.py:2515 — "its values are the DummyModules add_local_mod admitted" names the wrong function. add_local_mod (torch/_dynamo/replay_record.py:101-104) admits ModuleType and rejects everything else; the DummyModule substitution happens later, in ExecutionRecorder._resolve_modules (torch/_dynamo/replay_record.py:130-143), when the record is dumped. A reader following the comment to add_local_mod finds a ModuleType check and no DummyModule, and has to rediscover the missing hop. Naming _resolve_modules as what produces the values, and add_local_mod as what constrains them, closes that gap in the same three lines.

    Fix this →

Prior rounds

Verified rather than restated:

  • Test rewrite and description (round 1 item 1, round 2). test/dynamo/test_package.py:1074-1108 now plants one non-module, requires the Bad import result break and assertNotIn(alias, fn.__globals__), then puts a real module in the entry and requires agreement with eager plus assertIs(fn.__globals__[alias], module). I traced the second half against the parent and it does fail there: the first compile's import_source calls _import_module(name), which memoizes the object(); the second compile's __import__ returns the real module and passes the old push-time check, while import_source re-binds the memoized object() under the alias and hands back GlobalSource(alias), so guards read VALUE off the object(). The commit message at HEAD now describes that, and the unreachable alias-AssertionError story is gone.
  • pyrefly suppressions (round 1 item 3). Both removed from the hoisted check. The two that remain, at :2540 and :2543, are the parent's and cover value/source across the two arms.
  • _import_module.cache_clear() (round 2). Explained at test/dynamo/test_package.py:1105-1106. It clears the memo process-wide rather than for one name, but _import_module wraps importlib.import_module, which re-resolves through sys.modules, so the cost is a re-resolve and not a behavior change.

Both declines are fine. On the replay-arm check: PythonModuleVariable reading __name__ off a non-DummyModule requires a record that add_local_mod could not have written, and an assertion there would trade one internal error for another on a path no traced code reaches. On the test's home: strict_precompile is inert without caching_precompile (torch/_dynamo/output_graph.py:2588 early-returns on a falsy self.package), so the class decorators do not affect these assertions, and keeping the test_import_alias family together is worth more than the file boundary.

Recommendation

Approve

The hoist is correct, and it also moves the check ahead of calc_package()/resolve_name(), so a relative import of a non-module can no longer raise an uncaught ImportError from resolve_name before the graph break. The comment reference is worth correcting but does not need another round.

I could not run python test/dynamo/test_package.py -k test_import_alias_is_not_bound_to_a_non_module_import or pyrefly here (no built torch), so the red-on-parent / green-at-HEAD claims in the Test Plan are reasoned about statically rather than executed.

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

@bobrenjc93
bobrenjc93 marked this pull request as ready for review September 19, 2026 23:04
@bobrenjc93 bobrenjc93 added topic: not user facing topic category ciflow/trunk Trigger trunk jobs on your pull request labels Sep 20, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #197746

pytorchmergebot pushed a commit that referenced this pull request Sep 20, 2026
…197746)

A refactor with no behaviour change, to make room for the commit directly
above, which gives `import_source` a second argument: `graph_break_ok`, the
flag that decides whether an alias slot already holding something else is a
graph break or a hard error.

`cache_method` keys on the whole argument tuple, so that flag would silently
become part of the key, and a module name that two callers on one translator
both resolve would run the body once per distinct flag value instead of once.
Nothing about the second run would be wrong -- `f_globals[alias] is value`
holds by then, so the check is skipped, and the package record and
`update_co_names` are idempotent -- but the memo exists to make resolution
happen once, and the flag cannot change the answer a memo hit returns: it is
read only when the slot is taken, which a hit rules out, because the memo is
written only past that check. First-caller-wins is therefore the same source
any caller would have got. Keying on `module_name` alone also lets the new
argument be passed by keyword at the call sites, which the decorator forbade.

So the decorator gives way to an explicit `_import_source_memo` dict declared
in `InstructionTranslatorBase.__init__`, read at the top of the method and
written just before the return. Its lifetime is the decorator's: it lives on
the translator and dies with it, which is what made the cache safe in the first
place -- the alias it hands back names a global in the globals of the compile
that minted it. The comment above the method now says why the key is one
argument rather than the signature.

Test Plan:

```
python test/dynamo/test_package.py -k import_alias
python test/dynamo/test_package.py
```

Behaviour-neutrality was also measured directly on this tree, on a frame doing
`from torch.autograd.profiler import profile` with `config.record_runtime_overhead`
on, so that `IMPORT_NAME` and codegen's pregraph marker both resolve
`torch.autograd.profiler`: the sequence of aliases `import_source` resolves
across the compile is identical before and after this commit.

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

Authored with the assistance of Claude Code.

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

Pull Request resolved: #197746
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149, #197048, #196825, #196897, #197218, #196909, #196826, #197390, #197391, #197188, #197179, #197195, #197220, #197001, #197569, #197301, #196908, #197319, #197219, #197580, #197050, #197257, #197745
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1287/head branch November 24, 2026 01:46
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 Merged module: dynamo topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants