Skip to content

[dynamo] Memoize import_source per translator with an explicit dict - #197746

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

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

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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]

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 added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 19, 2026
@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/197746

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

⏳ 2 Pending, 2 Unrelated Failures

As of commit 2d8f708 with merge base 51d4378 (image):

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

  • Behavior neutrality
    • _import_source_memo keys on module_name, matching cache_method's single-element args tuple at torch/utils/_functools.py:96, so lookups are identical
    • The is not None test is safe because both returns in import_source yield a GlobalSource (symbolic_convert.py:2444), never None
    • Write at symbolic_convert.py:2445 sits past the alias assertion, so a raising call memoizes nothing — same as the decorator caching only on success
  • Preservation
    • The f_globals[alias] is value assertion at symbolic_convert.py:2438-2441 and the torch_package branch are untouched; no defensive logic dropped
    • Nothing in the tree reads or clears the old _cache_method_import_source attribute, and no translator class defines __slots__
  • Lifetime and callers
    • The dict is initialized in InstructionTranslatorBase.__init__ (symbolic_convert.py:5511), matching the decorator's per-instance cache; InliningInstructionTranslator gets a fresh memo as it did before
    • All 11 call sites pass module_name positionally, so no keyword path changes
  • Scope
    • Confined to import_source and one __init__ line in torch/_dynamo/symbolic_convert.py; no public API, CI, or build surface touched

reason: clean
Reviewed commit: 2d8f708

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


The code change is correct and behavior-neutral, but the 7-line comment that is the substance of this PR states a justification that is incomplete — the "slot already taken" branch it claims a memo hit rules out is in fact reachable within a single compile by an inlined frame whose own memo is empty.

Full review

PR Review: #197746

Summary

Replaces @cache_method on InstructionTranslatorBase.import_source with an explicit per-translator _import_source_memo dict so a follow-up commit can add a graph_break_ok argument without it becoming part of the cache key. The mechanical change is sound and preserves the decorator's lifetime and first-caller-wins semantics; the problems are all in the explanatory comment, which is the load-bearing artifact of a pure refactor.

Code Quality

1. torch/_dynamo/symbolic_convert.py:2418-2421 — the stated reason is incomplete, in a way that matters for the follow-up commit.

The comment says graph_break_ok "is read only when the alias slot is taken, which a memo hit rules out because the memo is written only past that check." A memo hit rules the branch out for that translator. But the memo is per-translator while the slot it guards is per-compile: InliningInstructionTranslator.__init__ passes output=parent.output (line 6383), so f_globals = self.output.global_scope (line 2441) is shared, while every inlined frame starts with an empty _import_source_memo (line 5519).

So for a module name the root translator already resolved, an inlined frame misses its memo, runs the body, and does reach the slot-taken check at line 2442. What makes that benign is the f_globals[alias] is value disjunct (_import_module returns the sys.modules entry, so identity holds), not the memo. The comment's argument only covers repeat calls within one translator, which is the case the memo actually eliminates.

This is worth fixing rather than nitpicking, because the next commit hangs a real decision on it: if graph_break_ok=False at a call site reached from an inlined frame, the flag-sensitive branch is live even though a "hit would have" suppressed it. The behavior is still fine (the is value disjunct short-circuits before the flag is consulted), but the comment as written tells a future reader the branch is unreachable, which is the wrong mental model to leave behind.

Suggested framing: the flag is safe to omit from the key because every path that reaches the slot-taken check for an already-resolved name satisfies f_globals[alias] is value, so the flag is never consulted for a name any translator in this compile has already resolved.

Fix this →

2. torch/_dynamo/symbolic_convert.py:2416 — the comment forward-references a parameter that does not exist.

graph_break_ok appears nowhere in the tree at this commit (grep -rn graph_break_ok torch/ matches only this comment). Anyone reading this file at this SHA, or bisecting through it, sees a justification for an argument they cannot find. Either defer the graph_break_ok paragraph to the commit that introduces it and keep only "the key is module_name alone, not the signature" here, or phrase it so it stands alone (e.g. "so that a later argument cannot silently join the key").

3. torch/_dynamo/symbolic_convert.py:2415-2421 — comment density.

Seven lines of nested subordinate clauses to justify a one-key dict, against CLAUDE.md's "minimize comments; be concise." Three lines carrying the invariant (key is the module name; the memo dies with the translator; a later flag must not join the key) would land better than the full derivation. The derivation belongs in the commit message, where it already is.

Performance

Not a blocker, but noting the tradeoff since it is the one measurable difference from cache_method: the memo is now allocated eagerly in __init__ rather than lazily on first call (torch/utils/_functools.py:93-95), so every InliningInstructionTranslator — one per inlined call during tracing — pays an empty-dict allocation whether or not it ever imports. This matches the adjacent _pycode_last_varname / _pycode_varname_counter allocations at lines 5513-5517, so it is consistent with existing practice and almost certainly noise; flagging only so the choice is deliberate.

Separately, and out of scope for a no-behavior-change refactor: because the namespace being memoized (output.global_scope, output.import_sources) is per-compile, a memo on self.output would be both safe and strictly more effective than a per-translator one — it would also elide the re-resolution described in finding 1. If the per-translator lifetime is being kept deliberately (matching the decorator exactly, so this commit stays provably neutral), that is a reasonable call and worth one clause in the comment; right now the comment asserts the lifetime is safe without saying why per-translator was preferred over per-compile.

Recommendation

Needs Discussion

The code is correct and I found no behavioral defect: the memo read (line 2424), the write placement past the assertion (line 2449), and the is not None test (safe — import_source cannot return None) all preserve the decorator's semantics, and import_source is unreachable before __init__ completes, so dropping cache_method's lazy getattr/setattr cannot raise AttributeError. But for a refactor whose entire deliverable is "make room for the next commit, and explain why the key is narrower than the signature," the explanation needs to be right. Fix the comment's reasoning (finding 1) and the forward reference (finding 2) and this is good to land.


  • Gather context (read diff vs base, read import_source, cache_method, all call sites, __init__ ordering)
  • Verify claims with sub-agents (init-ordering safety, inlined-frame memo reachability, is value identity via sys.modules)
  • Post review

Note: I reviewed statically and did not run the test plan — no built PyTorch is available in this checkout, so python test/dynamo/test_package.py was not executed.
| Branch: gh/bobrenjc93/1288/head

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Re-reviewed against the current head 50bed3cb499e; all three items are folded in the comment, which is now three lines.

1. > torch/_dynamo/symbolic_convert.py:2418-2421 -- the stated reason is incomplete, in a way that matters for the follow-up commit. [...] Suggested framing: the flag is safe to omit from the key because every path that reaches the slot-taken check for an already-resolved name satisfies f_globals[alias] is value [...]

Fixed, in the commit that owns the flag: the comment here no longer argues about graph_break_ok at all, and #197255 directly above adds the reasoning you give -- a memo hit means this translator bound the alias, an inlined translator's miss finds f_globals[alias] is value, and a taken slot is decided by each caller's own flag.

2. > torch/_dynamo/symbolic_convert.py:2416 -- the comment forward-references a parameter that does not exist. [...]

Fixed in 50bed3cb499e: the comment says only that the key is module_name alone, not the whole argument tuple, "so a later argument cannot silently split the memo"; graph_break_ok is not named until the commit that adds it.

3. > torch/_dynamo/symbolic_convert.py:2415-2421 -- comment density. [...]

Fixed in 50bed3cb499e: three lines -- the key, the per-translator lifetime as the decorator had it, and the write past the alias check. The derivation stays in the commit message. On the per-translator versus per-compile lifetime: kept per-translator deliberately so this commit is provably neutral against @cache_method; the message says so.

@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 17m 40s —— View job


The refactor is correct and I found no behavioral difference from @cache_method; both comment issues from my earlier review were addressed, and what remains are three smaller problems in the replacement comment, which is the load-bearing artifact of a pure refactor.

Full review

PR Review: #197746

Summary

Replaces @cache_method on InstructionTranslatorBase.import_source with an explicit per-translator _import_source_memo dict, so a follow-up commit can add a graph_break_ok argument without it joining the cache key. I found no observable difference from the decorator; the remaining problems are all in the three-line comment that justifies the swap.

Code Quality

1. torch/_dynamo/symbolic_convert.py:2417 — the comment dropped the one fact a reader cannot derive locally.

The comment it replaces said the cache "only exists for the duration of this InstructionTranslator - so it should be safe to do." The new comment keeps the fact ("Per translator, as the decorator was") but drops the safety argument: the alias it hands back names a key in self.output.global_scope (line 2437), i.e. the globals of the compile that minted it, so a memo that outlived the compile would hand back a source pointing at a global that no longer exists. "As the decorator was" is an appeal to what the code used to do, not a reason — and it stops being checkable the moment someone reads this file without the diff in hand. The lifetime constraint is exactly the kind of non-local invariant CLAUDE.md says comments are for; the "per translator" mechanic is visible from __init__.

2. torch/_dynamo/symbolic_convert.py:2415-2416 — still a forward reference, just an anonymous one.

import_source takes exactly one argument at this SHA, so "keyed by module_name alone, not the whole argument tuple" describes a distinction with no current difference, and "a later argument cannot silently split the memo" names no argument a reader can go look at. This is better than the previous draft's dangling graph_break_ok (which appeared nowhere in the tree), but anyone reading or bisecting through this commit still sees a rule motivated entirely by code that does not exist yet. Either fold this justification into the commit that introduces the second argument, or make it self-standing here by stating the property rather than the future: the key is the module name because the module name is what determines the alias.

3. torch/_dynamo/symbolic_convert.py:2417 — "written only past the alias check" is now a bare fact with no stated consequence.

In the previous draft this clause was load-bearing: it supported the (incorrect) argument that a memo hit rules out the slot-taken branch. With that argument removed, the clause states a placement without saying why the placement matters. The consequence worth recording is that a refusal memoizes nothing — an import_source call that raises past line 2438 leaves the memo empty, so the next call re-resolves rather than returning a source for an alias that was never bound. That is what makes the placement deliberate rather than incidental. State it or drop the clause.

Fix this →

Performance

Two differences from the decorator, neither a blocker, flagged so the choices are deliberate:

  • The memo is now allocated eagerly in __init__ (line 5511) rather than lazily on first call (torch/utils/_functools.py:93-95), so every InliningInstructionTranslator — one per inlined call during tracing — pays an empty-dict allocation whether or not it ever imports. This matches the adjacent _pycode_last_varname / _pycode_varname_counter allocations at lines 5504-5509, so it is consistent with the file and almost certainly noise.
  • The memo is per-translator while everything it guards (output.global_scope, output.import_sources) is per-compile, because InliningInstructionTranslator passes output=parent.output (line 6375) but gets a fresh _import_source_memo. So a module the root translator already resolved is re-resolved once per inlined frame that imports it — the assertion at line 2438 passes via the f_globals[alias] is value disjunct. A memo on self.output would be both safe and strictly more effective. Out of scope for a no-behavior-change refactor, and keeping the decorator's exact lifetime is what makes this commit provably neutral, but that reasoning is the thing the comment should be recording (see finding 1) rather than "as the decorator was".

Recommendation

Approve (after the comment fixes)

I verified the mechanics and found no defect: the memo read (line 2420), the is not None test (safe — import_source cannot return None, so it is equivalent to cache_method's sentinel), and the write placement past the assertion (line 2445) all reproduce the decorator's semantics; nothing in the repo introspects or clears _cache_method_import_source; no translator is deep-copied, pickled, or __dict__-snapshotted; no class in the hierarchy defines __slots__; all 11 call sites pass module_name positionally; and import_source is unreachable before __init__ line 5511 completes, so dropping the decorator's lazy getattr cannot raise AttributeError. Since the deliverable of this commit is the explanation, finding 1 in particular should land before merge.


  • Load /pr-review guidelines
  • Read diff vs origin/gh/bobrenjc93/1288/base, import_source, cache_method, __init__, all call sites
  • Verify with sub-agents (init-ordering safety, cache-attribute introspection, deepcopy/pickle, __slots__, positional call sites)
  • Post review

Note: reviewed statically. No built PyTorch is available in this checkout, so the test plan (python test/dynamo/test_package.py) was not executed.
| Branch: gh/bobrenjc93/1288/head

[ghstack-poisoned]
@bobrenjc93
bobrenjc93 marked this pull request as ready for review September 19, 2026 22:18
@bobrenjc93 bobrenjc93 added ciflow/trunk Trigger trunk jobs on your pull request topic: not user facing topic category labels Sep 20, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@github-actions
github-actions Bot deleted the gh/bobrenjc93/1288/head branch November 24, 2026 01:47
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