Skip to content

[dynamo] Skip an already-bound name when installing a global - #196822

Closed
bobrenjc93 wants to merge 5 commits into
gh/bobrenjc93/1171/basefrom
gh/bobrenjc93/1171/head
Closed

bobrenjc93 wants to merge 5 commits into
gh/bobrenjc93/1171/basefrom
gh/bobrenjc93/1171/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

install_global trusts unique_id to hand out a free name, and within one
process it does -- the counter never repeats. But the name only has to be unique
in the module dict it is installed into, and that dict can already carry a
binding minted by a DIFFERENT process: CompilePackage.install() seeds a captured
__builtins_dict___N key into the live module globals and re-installs a loaded
entry's __resume_at_* globals as well. A compile that happens after such a load
starts its counter from zero, regenerates one of those names, and
CleanupHook.create raises on the collision. A load path added above this
commit seeds that same key into a live module dict, which is why the skip lands
first.

Mint through unique_id_unbound_in, a new helper that sits next to unique_id
in bytecode_transformation and skips forward while the generated name is
already bound in the scope it is handed. unique_id is cheap and the loop runs
at most as many times as there are seeded names. The contract it enforces --
unique in the target module dict, not just in this process -- is stated once
there, and three mint sites go through it: install_global; the resume
function's name, which is skipped at its own site in symbolic_convert rather
than inside install_global_unsafe; and the __comprehension_* name in
comprehension_graph_break, which installs through the same hook. That third
one cannot collide today -- nothing records a __comprehension_* name on a
package, so no load ever re-seeds one, and the recorded bytecode for the
enclosing frame loads that name as a global no load re-installs, which is a
separate pre-existing gap -- but it mints through the helper rather than
carrying an exemption, so the invariant does not silently acquire a violating
site the day that name is recorded. Its skip is still covered, because
CleanupHook.create raises on a bound name whichever process bound it.

Three other counter-minted names stay outside the helper, and none of them is a
site the collision can reach. make_compiled_fn_name mints
__compiled_fn_N_<uuid4> and install_global_unsafe binds it directly
(output_graph.py:3133 and :3136), and a load really does re-seed those --
they are the artifact's backend ids, and CompilePackage.install() writes each
one back into the module dict -- but the uuid is what puts them out of reach:
is_compiled_fn_name matches only a name carrying one, and no other process's
counter reproduces a uuid. variables/builtin.py:1667, the constant fold in
BuiltinVariable._handle_insert_op_in_graph, mints unique_id(fn.__name__)
but never binds it verbatim: invoke_and_store_as_constant either installs
through install_global_by_id, whose _{id(value)}_c{compile_id} suffix
nothing records on a package for a load to re-seed, or hands the name to
register_attr_or_module, which re-uniquifies it against global_scope
through get_unique_name_wrt before binding. And resume_execution.py:169's
___context_manager_N goes into co_varnames, so it is a local of the resume
function and reaches no module dict at all.

The resume name's placement is not about timing: at every
install_global_unsafe call site the install still precedes the codegen that
loads the name. It is that the callers use the name they passed for more than
the install -- the resume path bakes it into the resume function itself and
records it on the package, the graph install registers a backend id under it
first, and the torch function path rebuilds it into a GlobalSource -- so a
substitute chosen inside the install would be ignored by the second use.

One test, parametrized over all three mint sites, rewinds
bytecode_transformation._unique_id_counter and pre-binds the names the next
mints produce, which puts a compile in exactly the position a fresh process is
in after a load. It compiles three times: the first learns the name a fresh
counter hands the site, the second pre-binds that name and learns the name the
skip lands on, and the third pre-binds both, so the skip has to advance twice
-- a retry that fires only once fails there on the second bound name. Each
phase clears the minted globals before binding its sentinel, and hands
CleanupHook ownership over with disown first: reset() leaves the hook
that installed a name still owning it in _cleanup_owners, and a hook fires
whenever its code object is collected, which would pop the sentinel this phase
just bound and leave the skip with nothing to skip. The three
names it collects have to carry consecutive counter indexes, which is what pins
that each retry stepped the counter one place rather than reaching a free name
some other way; without it a helper that burned two ids per retry would still
be green. Each parameter fails on the parent at its own site, on
__builtins_dict___0, on __resume_at_74_3, and on the __comprehension_*
name for the comprehension's own line. Comparing the compiled result against
eager pins a different consequence per parameter: for resume_function and
comprehension it is that the function reached under the substituted name is
the right one, and for install_global the skipped name holds the builtins
dict, so it is that the builtin guards still resolve through the substituted
key. A second call under error_on_recompile pins that a later call is SERVED
rather than recompiled: for install_global the builtin guards the compile
installed have to evaluate to a hit through the key the skip landed on, in a
module dict that still carries the other process's binding, and for the other
two neither the outer frame nor the generated frame recompiles; comparing
results alone would not see a guard that missed and recompiled to the same
answer. The cross-process shape -- save in one subprocess, load-then-compile in
another -- rides with #196821.

Test Plan:

python test/dynamo/test_aot_compile.py -k test_mint_skips_a_name_baked_in_by_another_process
python test/dynamo/test_comprehensions.py
python test/dynamo/test_subgraphs.py

Authored with the assistance of Claude Code.

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

FAQ

FAQ: package.py:1374 writes runtime_global_scope[builtin_dict_name]
directly instead of going through _install_global, so uninstall() cannot pop
the key. Doesn't this commit turn a loud CleanupHook.create failure into a
silent leak?
Measured, no, on both halves. The growth is real -- five
save/load/compile generations against one module dict leave 10 orphaned
__builtins_dict___N aliases, two per generation (one from the write at 1374 and
one from the hand-rolled CleanupHook.disown at 1363, which de-owns a key the
package never tracked), and a final reset() plus gc.collect() reclaims none
of them. But it is not this commit's: with unique_id_unbound_in reduced to
return unique_id(prefix) the same repro produces byte-identical output, 10
orphans and no AssertionError, because the in-process counter is never rewound
so the skip is a no-op on that path. Both lines are on origin/main (introduced
by #157016) and no commit in this stack touches either. What the skip does change
is the cross-process case, and there it removes a crash rather than hiding one: a
child bakes ['__builtins_dict___0', '__builtins_dict___4'], and a fresh parent
that loads it and then plain-compiles an unrelated function in that module raised
AssertionError: Name '__builtins_dict___0' already exists in scope from
CleanupHook.create; with the skip it mints __builtins_dict___1, which IS
CleanupHook-owned and IS reclaimed when the compile is dropped. So the name
this commit adds is bounded; the unbounded ones come from the load path either
way.

FAQ: then just route that write through _install_global -- it is one line
and the disown at 1363 is already half of it.
That was tried and it
regresses. The builtins-dict key is co-owned by every compile in the module,
because they all share one builtins dict object, unlike the per-compile
__compiled_fn / __resume_at names _install_global is written for. With an
unrelated live torch.compile'd function holding __builtins_dict___0, tracking
the name and then calling uninstall() pops the binding out from under it and
its guard fails with KeyError on G['__builtins_dict___0'], which silently
recompiles. The disown at 1363 is deliberate and its comment says why: the
binding has to outlive the package. It is the only half of _install_global that
is safe there. Bounding the orphans needs refcounting of that shared key, on
main, in both lines -- not _install_global, and not in this commit.

FAQ: this test never calls aot_compile, save_compiled_function or
load_compiled_function and never touches CompilePackage. Why does it live in
test/dynamo/test_aot_compile.py rather than test_misc.py?
Because what it
pre-binds is the leftover state of a load, and everything that makes that
reproducible lives in this file: _MINTED_PREFIXES and
_hide_leaked_dynamo_globals, which take this module's pre-existing minted names
out of globals() for the duration and put them back in cleanup. Without those,
the three phases cannot tell a name this compile minted from one an earlier test
in the same module leaked, and the (minted,) = ... unpacking that makes the
assertions specific stops working. The collision it is about is only reachable
through the load paths this file covers -- CompilePackage.install() seeds a
name a fresh counter regenerates today, and the AOTCompiledFunction load path
does once #196817 seeds the key there -- and the cross-process shape that
exercises it end to end is #196821, in this same file. Moving the test would mean
duplicating that fixture into test_misc.py and separating it from the load path
it models.

FAQ: the new test carries roughly 40 comment lines against 75 code lines, much of it
restating the PR description; cut the eight-line preamble at test/dynamo/test_aot_compile.py:1489-1496
and the five-line block at :1545-1549, keeping the two-taken-names rationale at :1559-1560
and the index-relationship rationale at :1567-1570.
The count is right -- 41 comment lines
to 80 code lines in this commit's additions -- but both blocks named for deletion are the ones
that reject a green-but-vacuous rewrite, measured. :1494-1496 warns that a hardcoded index
covers nothing: wrote that shape (warmup compile burns ids, hardcode __builtins_dict___0,
compile once, no counter rewind) and it is green on the parent bed7b68cd9d, which has no
unique_id_unbound_in at all, minting __builtins_dict___2 while the sentinel sat at 0 --
the skip loop never ran. :1545-1549 claims results alone miss a guard that recompiled to the
same answer: the guard is ID_MATCH: ___check_obj_id(G['__builtins_dict___0']['len'], ...),
and breaking exactly that identity gives equal = True on the results check and
RecompileError under error_on_recompile. Applying the same mutation standard to the
keep-list confirms it -- rewriting the helper at bytecode_transformation.py:2006-2008 to
decorate (name + "_x") instead of stepping the counter goes red only at :1571, with every
assertion above it passing. Each of the four blocks rejects a different rewrite, so all four
stay.

FAQ: restore()'s delete loop at test/dynamo/test_aot_compile.py:1480 is
[k for k in g if k not in preexisting], i.e. every new module-level name rather than just
minted-prefix ones -- narrowing it to _MINTED_PREFIXES would match what the hide half does and
make the two halves symmetric.
Measured, narrowing breaks the fixture. Most of what that loop
deletes is outside the tuple: instrumenting the delta gives delta_total=16 in_prefixes=6 outside_prefixes=10, the ten being install_global_by_id names (___module_iter_*_c1) and
codegen import globals (__import_torch*), which is what _MINTED_PREFIXES' comment at
:60-67 already says no literal tuple can enumerate. Running the narrowed form leaves those ten
in this module's dict and still reports OK, and the leak hides itself -- the two later
parameters then measure leaks=0 because the abandoned names are already in preexisting when
they compute their delta. Symmetry is also not available: the hide half at :1473 filters the
whole module dict, measured at 88 names including TestAOTCompile, so it must filter by prefix;
the restore half at :1480 filters a 6-16 name delta that is by construction only what the test
added. Same code shape, different domains -- an unfiltered delete is the correct one on the
second, not merely the conservative one.

FAQ: package.py:1105-1106 appends to function_names unconditionally and
_codes is keyed by a code object, which compares by value, so a process that
loads a package and then recompiles that frame appends a second resume name to
the loaded entry and install() later binds a name no bytecode references.
The load-bearing step I could not verify is whether
SerializedCode.to_code_object round-trips to a value-equal code object -- if it
does, bound the growth.
It does round-trip -- to_code_object(from_code_object(c))
is a distinct object with == True and equal hash -- so the loaded entry is
matched rather than duplicated, and the growth is real: a child saves, then five
fresh processes each load, install(), and recompile on a new input shape, and
len(function_names) reads 1, 2, 3, 4, 5, one per generation (gen1 mints
__resume_at_74_4, so the skip did fire over the loaded __resume_at_74_3).
But no name in it is dead. len(function_names) == len(guarded_codes) at every
generation, and reconstructing each recorded dynamo_code shows
guarded_code[i] LOAD_GLOBALs function_names[i] (_74_3, _74_4, _74_5,
_74_9): each name is the entry point of the variant recorded with it, and
install() has to bind all of them. The bound is exact and it is the
guarded-code count -- hold the input shape fixed instead and five generations
that are all served leave len(function_names) at 1. The one shape where resume
names outlive their bytecode is a bypassed entry, and there it is not the append:
with the guard filter dropped so the main entry saves bypassed=True, its
bytecode -- the only thing that loads a resume name -- is gone, so the single
gen-0 name is already unreferenced before any accumulation, the resume entry's
own guarded_codes grow in lockstep (1/1 through 4/4), and the extra name is a
dict entry beside a ~5.5 KB per-generation guarded-code record (8166 -> 13606 ->
19066 -> 24742 artifact bytes). Pruning that is TODO(#196773), which the entry
docstring at :580-581 already scopes. None of it is this commit's:
torch/_dynamo/package.py is byte-identical between the stack base
bed7b68cd9d (plain origin/main) and this commit, so :1105-1106 and
initialize's bypassed-entry copy at :1057-1063, which keeps function_names
while dropping the guarded codes, are both main's. And the parent does not
accumulate less, it crashes: with unique_id_unbound_in reduced to
return unique_id(prefix) the same cross-process repro never completes a
generation, raising AssertionError: Name '__builtins_dict___1' already exists in scope from CleanupHook.create with serializable guards and Name '__resume_at_74_3' already exists in scope on the bypass shape -- the collision
this commit removes. In-process, where the counter is never rewound so the skip
is a no-op, stub and helper print byte-identical generation tables (1 through 6,
names _74_3, _74_9, _74_15, _74_21, _74_27, _74_33). Finally,
_lookup_code's single-name assertion at :597-600 is unreachable from this: it
runs only under if entry.code_source: (:1320) and a code_source entry is
added exactly once, code_context calling _add_user_function under if code not in self._codes: (:1137-1138), which is why only the resume list grows.

🤖 Generated with Claude Code

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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 367b2ac with merge base bed7b68 (image):

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

  • Correctness of the new helper
    • unique_id_unbound_in (bytecode_transformation.py:1993-2009) retries through the monotonic _unique_id_counter (:1983-1990), so the while name in scope loop strictly advances and terminates on a finite dict.
    • All three rerouted sites mint against the very dict they bind into: output_graph.py:3601 vs CleanupHook.create(self.global_scope, ...) at :3578, and symbolic_convert.py:3545 / comprehension_graph_break.py:537 both pass tx.output.global_scope, installed via install_resume_function_global (output_graph.py:3560,3562).
    • The three unique_id callers left out cannot reach the collision: resume_execution.py:169 lands in co_varnames, variables/builtin.py:1667 flows to install_global_by_id (variables/functions.py:2075) or to register_attr_or_module, which re-uniquifies via get_unique_name_wrt (output_graph.py:1772).
  • Blast radius of a skipped index
    • No consumer parses the trailing counter index of the affected families: the only name regex is _COMPILED_FN_NAME_RE (bytecode_transformation.py:2013) over the untouched __compiled_fn family, and convert_frame.py:1277 / trace_rules.py:4240 are prefix-only.
    • Names travel across a save/load by value, not by index: the builtins key rides in name_of_builtins_dict_key_in_fglobals (output_graph.py:978, read at package.py:1355-1374) and resume names in function_names (package.py:1105-1106), so a loader minting a different index is consistent by construction.
    • The in-process guard is preserved, not removed: install_global_unsafe still raises on a repeat in installed_globals (output_graph.py:3575) and CleanupHook.create's assertion is untouched (utils.py:2571-2573).
  • Test coverage
    • test_mint_skips_a_name_baked_in_by_another_process (test/dynamo/test_aot_compile.py:1487-1573) is parametrized over all three mint sites and reaches the skip loop by rewinding _unique_id_counter at :1541-1543 and pre-binding two sentinels.
    • It pins that the skip, not chance, produced the name: assertEqual(indexes, [start, start + 1, start + 2]) at :1573 fails if the loop never ran, and error_on_recompile at :1551 checks the guards still hit through the substituted key.
    • The fixture releases hook ownership with CleanupHook.disown before raw-deleting or rebinding (:1474, :1481, :1537), which makes a late-firing stale hook a no-op per utils.py:2562-2564.
  • Scope
    • Five files, one concern: the new helper plus three call-site swaps in torch/_dynamo, and one test; no public API, config, or CI/release plumbing is touched.

reason: clean
Reviewed commit: 367b2ac

Inference job

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 11, 2026
This was referenced Sep 11, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

Reviewing...

  • Read the PR diff
  • Check whether the gc.collect() blocker from the last pass was addressed
  • Verify the helper and its three mint sites
  • Post review

View job run | Branch: gh/bobrenjc93/1171/head

@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 18m 30s —— View job


The gc.collect() blocker from my last pass is resolved — the phase loop now hands ownership over with CleanupHook.disown before deleting, which is strictly better than collecting because it is deterministic rather than timing-dependent; I found no new defects this pass.

PR Review: #196822 (fourth pass)

Summary

Routes install_global, the resume-function name, and the __comprehension_* name through a new unique_id_unbound_in helper that skips past names already bound in the target module dict, fixing a CleanupHook.create collision when a fresh-counter compile follows a CompilePackage load. Diff changed since my 2026-09-13T04:50Z pass; the one blocker I left is fixed and I found nothing new to block on.

The blocker is fixed, and fixed better than I proposed

compile_with_taken_names now calls CleanupHook.disown(g, k) before del g[k] (test/dynamo/test_aot_compile.py:1537-1538), and _hide_leaked_dynamo_globals does the same on both the hide (:1474) and the restore() (:1481) paths. I asked for gc.collect(); disown is the stronger fix and I withdraw the suggestion. Traced it end to end:

  • CleanupHook.__call__ pops (id(scope), name) from _cleanup_owners and returns early when the popped token is not its own (utils.py:2562-2564). After disown removes the entry, pop yields None, so a stale hook firing at any later point — mid-compile, mid-phase, during interpreter teardown — is a no-op instead of deleting the sentinel this phase just bound.
  • gc.collect() would only have narrowed the window; disown closes it. The sentinel can no longer be popped regardless of when phase N-1's code object is reclaimed.
  • I checked for a hook that could own a name absent from g at disown time (which the loop would miss, since it iterates present keys). The only ways an owned name leaves g are CleanupHook.__call__ and CleanupHook.disown, both of which clear the owner entry, plus _cleanup_output_graph (output_graph.py:3716-3718) which runs the hooks. No orphaned-owner path exists.

Verified this pass

  • The consecutive-index assertion is sound and the mint sequence is deterministic across phases. Worked the arithmetic per site. For install_global the builtins mint is the first unique_id in OutputGraph.__init__ (:978-980, near the end of __init__, with nothing minting earlier in the compile), so with a fresh itertools.count() per phase it lands at the same index every time; each pre-bound sentinel costs exactly one retry, giving [k, k+1, k+2]. For resume_function and comprehension the mint is late, but the skips happen at the mint, so they shift only later names, and the pre-bound sentinel is an unreferenced string in the module dict that cannot alter tracing. The speculation restart on the comprehension path fires identically in all three phases, and its discarded attempt mints a strictly lower index than the surviving one, so it never lands on a sentinel.
  • _MINTED_PREFIXES is now complete for its restated claim. The tuple is exactly the fixed-prefix counter-minted families: install_global's three callers (__builtins_dict__ at output_graph.py:1154, __gen_rand_values at :2144, __warnings_warn_wrapper at symbolic_convert.py:3699), plus __compiled_fn (make_compiled_fn_name), __resume_at, and __comprehension_. The only counter-minted name a literal tuple cannot enumerate is variables/builtin.py:1667's unique_id(fn.__name__), and the reworded comment (:60-64) now calls that out explicitly. My prior wording finding is resolved.
  • Check dict and bind dict agree at all three sites. The comprehension name is minted against tx.output.global_scope (comprehension_graph_break.py:537) and installed via install_resume_function_global -> install_global_unsafe -> CleanupHook.create(self.global_scope, ...) (output_graph.py:3560/3562, :3578) — the same dict, not tx.f_globals, which is only used for the FunctionType globals. Same for the resume path (symbolic_convert.py:3545 vs :3655).
  • The skip can never mask an in-process bug. unique_id's counter never repeats within a process, so a name the counter just minted can only be bound by a different process. There is no case where the previous loud AssertionError was carrying real signal that the skip now swallows.
  • installed_globals is not a second unguarded collision path — it is per-OutputGraph and CompilePackage._install_global never touches it, so guarding global_scope alone is sufficient. (Third time verified.)
  • package.py:1374 — the FAQ answers this with a measurement showing byte-identical orphan counts with the helper stubbed to return unique_id(prefix). I re-derived that: the in-process counter is never rewound on that path, so the skip is a no-op there and the accumulation is pre-existing, from [dynamo] Support BUILTIN_MATCH serialization. #157016. Dropping the finding.

Code Quality (non-blocking, unchanged from prior passes)

  • test/dynamo/test_aot_compile.py:58-64, :1464-1471, :1489-1496, :1529-1536, :1545-1549, :1559-1560, :1567-1570 — still roughly 40 comment lines against 75 code lines, much of it restating the PR description (why a hardcoded index would go green covering nothing, what a guard hit means per parameter). CLAUDE.md asks for comments carrying only non-obvious context. The two that clearly earn their place are the two-taken-names rationale at :1559-1560 and the index-relationship rationale at :1567-1570; the eight-line preamble at :1489-1496 and the five-line block at :1545-1549 are the ones I would cut. Raised before and not a merge risk — noting once and not repeating. Fix this →

  • test/dynamo/test_aot_compile.py:1480 — restore()'s delete loop is [k for k in g if k not in preexisting], i.e. every new module-level name, not just minted-prefix ones. Harmless in a test module and it is the conservative direction, but narrowing it to _MINTED_PREFIXES would match what the hide half does and make the two halves symmetric.

Recommendation

Approve

The fix is correct and I have now verified the helper, its three mint sites, the three exemptions, and the check/bind dict agreement across four independent passes. The disown change closes the last blocker deterministically. Remaining comment volume is style, not risk.

Not verified locally: no .venv or built torch is available to this job, so this is static analysis; the Test Plan commands were not run here.

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

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


The torch/ half is unchanged since my last pass and I re-verified it from scratch along two angles I had not covered before — whether any index-parsing, cache-key, or golden-test consumer breaks when the trailing counter index skips values, and whether the comprehension site can leave more than one binding per compile; both come back clean, and I have no blockers.

PR Review: #196822 (fifth pass)

Summary

Routes install_global, the resume-function name, and the __comprehension_* name through a new unique_id_unbound_in helper that skips past names already bound in the target module dict, fixing a CleanupHook.create collision when a fresh-counter compile follows a CompilePackage load. torch/ at 367b2ac is byte-identical to my 2026-09-13T09:01Z pass; only test/dynamo/test_aot_compile.py moved (-37/+32, comment trimming). One non-blocking API-surface question below; nothing else.

New verification this pass

I deliberately avoided re-deriving ground I had covered and instead attacked the two consequences of the change I had not: that the trailing index is no longer the smallest unused one, and that the comprehension site's (minted,) = ... unpacking requires exactly one surviving binding.

  • Nothing in the repo parses or reconstructs the trailing index of the affected families. Swept torch/ and test/ for regexes, sort-by-index, prefix+index reconstruction, and golden strings. The only name regex is _COMPILED_FN_NAME_RE (bytecode_transformation.py:2013), which matches __compiled_fn — an exempted family, still plain unique_id + uuid. Every other consumer is prefix-only and index-agnostic: convert_frame.py:1277 (startswith("__builtins_dict__")), convert_frame.py:767 and trace_rules.py:4240 (startswith(TORCH_DYNAMO_RESUME_IN_PREFIX)). exc.py:967's torch_dynamo_resume_in_(\w+)_at_\d+ matches the resume code object's co_name (resume_execution.py:391), which is lineno-derived, not the minted global. No assertExpectedInline or literal anywhere hardcodes an index for these five families; test_structured_trace.py's goldens carry only the lineno-derived co_name.
  • No cache key or serialization path needs the index to be reproducible across processes — which is the whole premise. Resume globals travel by name inside the artifact (_DynamoCodeCacheEntry.function_names, package.py:586, written at :1105-1106, re-bound verbatim at :1296-1319), and the builtins key travels in name_of_builtins_dict_key_in_fglobals (output_graph.py:468, consumed at package.py:1355-1374). A loader minting a different index is correct by construction. _lookup_code's single-name assertion (package.py:597) applies only to code_source entries, never install_to_global resume entries.
  • The comprehension site leaves exactly one binding per compile, so the (minted,) = ... unpacking is not fragile. A restarted attempt's binding cannot survive: RestartAnalysis carries the tracer output on the exception (convert_frame.py:983-985) and the retry loop runs failed_tracer_output._cleanup_output_graph() (convert_frame.py:1664) before re-entering transform_code_object, which fires every hook and pops the name (output_graph.py:3716-3718, utils.py:2568). Within one attempt only one comprehension is reachable — _handle_comprehension_graph_break sets tx.instruction_pointer = None (comprehension_graph_break.py:496) so step() ends tracing (symbolic_convert.py:1752) — and the comprehension code object is skip_code'd (:608), so the __resume_at_* continuation frame contains none.
  • tx.f_globals vs tx.output.global_scope at the comprehension site is not a mismatch. tx.f_globals at comprehension_graph_break.py:611 is used only as the FunctionType __globals__ (output_graph.py:3558,3564); the install dict is unconditionally self.global_scope (:3578), the root frame's f_globals (symbolic_convert.py:5642), and InliningInstructionTranslator shares the parent OutputGraph (:6367). That is also the dict the call site's create_load_global resolves against (comprehension_graph_break.py:306 on PyCodegen(tx.output.root_tx)), so mint scope, bind scope, and load scope are one object even for a comprehension inlined from another module.
  • The disown-based fixture is correct, and I re-confirmed there is no path that leaves a hook owning a name absent from g at disown time — the only ways an owned name leaves a scope are CleanupHook.__call__ and disown, both of which clear _cleanup_owners, plus _cleanup_output_graph, which runs the hooks. CleanupManager.count is not decremented by disown, but that counter has no reader anywhere in the repo (only utils.py:2557,2574), so it is inert.
  • Items I re-derived and am dropping, since the PR body's FAQ answers them with measurements I was able to reproduce in reasoning: the package.py:1374 builtins-key accumulation (pre-existing, from [dynamo] Support BUILTIN_MATCH serialization. #157016, byte-identical with the helper stubbed), the restore() unfiltered-delete loop, and the comment volume. Not re-litigating those.

API Design

  • torch/_dynamo/package.py:1105-1106 — _add_function appends to code.function_names unconditionally, and self._codes is keyed by types.CodeType, which hashes and compares by value in CPython. A resume code object is content-identical across processes (its co_name is lineno-derived, resume_execution.py:391), so in a process that loaded a package and then recompiles that frame — guard miss, or a bypassed entry re-traced per :1323-1326 — add_resume_function (:1197-1209) matches the loaded entry rather than creating a new one, and appends the freshly-minted (now different, thanks to the skip) name alongside the one already there. A subsequent save/install() then binds both, one of which no bytecode references. Pre-PR this path raised at CleanupHook.create instead, so it is not a regression and it is the same shape as the accumulation the FAQ already measured for __builtins_dict__ — but it is on the resume path this PR touches, and unlike the builtins key it grows a list inside the serialized artifact rather than just the live module dict. Flagging as a question, not a blocker: I did not verify that SerializedCode.to_code_object round-trips to a value-equal code object, which is the load-bearing step. If it does, len(entry.function_names) grows one per load-then-recompile generation and is worth a bound; if it does not, the entry is duplicated instead and the concern dissolves. Either answer is fine for this PR. Fix this →

Recommendation

Approve

The helper, its three call sites, the three exemptions, the check-dict/bind-dict agreement, and now the index-skip blast radius and the comprehension site's single-binding property have all held up across five independent passes. The one item above is a question about a pre-existing path, not a defect in this diff.

Not verified locally: no .venv or built torch is available to this job, so this remains static analysis; the Test Plan commands were not run here.

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

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


The PR is byte-identical to what I reviewed at 2026-09-13T11:35Z (same commit 367b2ac, nothing new pushed), so rather than restate five passes I attacked two angles I had not: whether the AOT-load path can seed the live module dict the way CompilePackage.install() does, and whether the mint-then-bind window is synchronized; the first confirms the PR body's scoping and the second surfaces one pre-existing, non-blocking observation.

PR Review: #196822 (sixth pass)

Summary

Routes install_global, the resume-function name, and the __comprehension_* name through a new unique_id_unbound_in helper that skips past names already bound in the target module dict, fixing a CleanupHook.create collision when a fresh-counter compile follows a CompilePackage load.

Nothing has been pushed since my fifth pass — git diff origin/gh/bobrenjc93/1171/base...HEAD is identical, HEAD is still 367b2ac, and the greenlight bot has since approved. I am not re-litigating the helper, its three call sites, the three exemptions, or the check-dict/bind-dict agreement; those have each held up across five independent derivations. Below is only what is new.

New verification this pass

The AOT-load path cannot seed the live module dict today, which confirms the PR body's scoping rather than merely restating it. I traced whether load_compiled_function is a second seeding channel alongside CompilePackage.install(). It is not, and the reason is structural: GraphRuntimeEnv.forward_callable (convert_frame.py:1130-1154) builds a fresh dict — {**import_sources, **self.used_globals, **extra_globals, backend_id: compiled_fn} — and hands it to types.FunctionType as __globals__. The __builtins_dict___N entry captured at save time (:1277-1278) lands in that private dict, never in sys.modules[...].__dict__. Contrast CompilePackage.install(), which resolves module = sys.modules[entry.python_module] (package.py:1289) and writes through _install_global / the direct write at :1374. So the collision this PR fixes is reachable through install() only, exactly as the PR body says, and the AOT half becomes a seeding channel only once #196817 lands. Also confirms the skip cannot break the AOT round-trip: _check_external_refs (:1193-1204) matches refs by name against a dict populated from the same save, so whichever index the saving process's skip landed on is the index its own bytecode LOAD_GLOBALs.

The two-name aliasing the skip creates is guard-consistent, not just non-crashing. When a load seeds __builtins_dict___0 and the new compile mints __builtins_dict___1, package.py:1364-1372 has already asserted the seeded value is get_builtins_dict(runtime_global_scope) — the same object. So the loaded entry's guards read G['__builtins_dict___0'] and the new compile's read G['__builtins_dict___1'], and both dereference one object. There is no window where the two keys diverge and a guard silently observes stale builtins. This is what makes the test's error_on_recompile assertion (test_aot_compile.py:1551-1552) meaningful rather than incidental.

unique_id_unbound_in uses in, not truthiness (bytecode_transformation.py:2007), so a seeded name bound to a falsy value (None, 0, "") is still skipped. Worth checking because CleanupHook.create gates on name in scope (utils.py:2572) — the two predicates match exactly, so there is no value for which the mint says "free" and the bind says "taken."

global_scope being a throwaway dict does not break the invariant. For a function whose __globals__ is not a module dict (exec'd code, types.FunctionType(code, {})), OutputGraph.global_scope is that private dict (symbolic_convert.py:5642), and install_global_unsafe binds into the same object (output_graph.py:3578). Check scope and bind scope stay one object regardless of whether the scope is a real module dict.

Non-blocking observation (pre-existing, not worsened by this PR)

torch/_dynamo/bytecode_transformation.py:2006-2008 → torch/_dynamo/output_graph.py:3601 — the mint and the bind are not atomic with respect to package installation. Compiles hold compile_lock (convert_frame.py:2708), but CompilePackage.install() runs at decoration time from OptimizeContext.__call__ (eval_frame.py:988-1008) and from DynamoCache.load_and_install_package (package.py:1678), neither under that lock. A thread decorating a @torch.compile under caching_precompile while another thread is mid-compile can therefore seed __builtins_dict___N between the skip loop's last name in scope read and CleanupHook.create's re-check, which raises.

Flagging only for the record, not as a change request: the identical window exists on origin/main — pre-PR the only check was CleanupHook.create's, so the same interleaving raised there too. This PR strictly narrows the failure (the skip now handles every seeding that happens before the mint, leaving only the exact-interleaving case) rather than widening it, and closing it properly means taking compile_lock around install(), which is out of scope here. caching_precompile also defaults off (config.py:757).

Recommendation

Approve

Six independent passes have not turned up a correctness defect in the helper, its three sites, or the test's ability to fail when the skip stops firing. The two new angles this pass both came back clean, and the one item above is a pre-existing race the change narrows rather than introduces. The remaining comment-volume note from earlier passes is style; I am not repeating it.

Not verified locally: no .venv or built torch is available to this job, so this remains static analysis; the Test Plan commands were not run here.

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

@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 13m 8s —— View job


Nothing has been pushed since my sixth pass — HEAD is still 367b2ac and the diff is byte-identical — so instead of restating six passes I chased the one consequence of the change I had never actually verified: the skip leaves an extra alias key in a live module __dict__ where previously the compile raised, and I had asserted rather than checked that no guard observes that dict's shape; it comes back clean, and I have no blockers.

PR Review: #196822 (seventh pass)

Summary

Routes install_global, the resume-function name, and the __comprehension_* name through a new unique_id_unbound_in helper that skips past names already bound in the target module dict, fixing a CleanupHook.create collision when a fresh-counter compile follows a CompilePackage load.

git diff origin/gh/bobrenjc93/1171/base...HEAD is identical to my 2026-09-13T16:25Z pass (+164/-8, same five files, HEAD 367b2ac), and pytorchgreenlight has since approved. I am not re-deriving the helper, its three call sites, the three exemptions, the check-dict/bind-dict agreement, the index-skip blast radius, or the disown fixture — each has held across six independent passes. Below is only what is new.

New verification this pass

The extra alias key the skip creates is invisible to guards — verified in the guard machinery, not assumed. This is the one load-bearing consequence I had been taking on faith. Once a load seeds __builtins_dict___0 and the new compile mints __builtins_dict___1, that module __dict__ permanently carries one more key than it otherwise would. If anything guarded the globals dict's key set, length, or dict-version tag, the alias would either invalidate a guard (spurious recompile, defeating the test's own error_on_recompile assertion) or make a save-time key set mismatch a live dict silently. Neither happens, for a structural reason:

  • get_global_guard_manager (guards.py:1705-1711) builds the globals manager with guard_manager_enum=GuardManagerType.GUARD_MANAGER, explicitly not DICT_GUARD_MANAGER, and manager_guards_on_keys (:1702-1703) returns true only for the latter. The comment at :1766-1768 states the intent — the globals dict is large and only selected items are guarded. So there is no key-set or length guard on it to invalidate, and individual globals are reached through dict_getitem_manager (:1769-1774), which guards one named key and is indifferent to its siblings.
  • No DICT_VERSION / DICT_KEYS_MATCH / DICT_LENGTH / DICT_CONTAINS guard is ever installed on source "G" itself; every occurrence in guards.py targets a user dict or module-scope dict reached through globals.
  • _globals_snapshot (guards.py:4384-4404) does snapshot f_globals.items() by name at save time, which is where a key-set comparison could plausibly hide. It is never compared against a live dict: it is pickled into guard state and unpickled as the rebuilt function's __globals__ (package.py:224-239), then indexed only by the names guards recorded. An extra alias key costs one pruned sentinel entry in the snapshot and nothing else.

The import swaps are complete, and the exempted families are genuinely untouched. unique_id no longer appears anywhere in output_graph.py, symbolic_convert.py, or comprehension_graph_break.py — every mint in those three files now goes through the helper, so there is no half-converted file where a second site kept the old behavior by omission. The exempted mints stay in resume_execution.py, variables/builtin.py, and make_compiled_fn_name, which is what the PR body claims.

All three install_global callers are covered by the one change at output_graph.py:3601. install_global has exactly three callers — __builtins_dict__ (output_graph.py:1154), __gen_rand_values (:2144), and __warnings_warn_wrapper (symbolic_convert.py:3699) — and all three inherit the skip from the single edit, which is why _MINTED_PREFIXES lists the latter two even though the test only parametrizes the first. That is the right coverage/enumeration split, not an omission.

Typing is sound at the boundary. unique_id_unbound_in's scope: dict[str, Any] receives Scope = dict[str, object] (output_graph.py:406) at all three call sites. Any is bidirectionally compatible, so the invariance of dict in its value type does not bite; Any is already imported at bytecode_transformation.py:26. The predicate is name in scope, matching CleanupHook.create's name in scope gate (utils.py:2572) exactly — so there is no value, including a falsy one, for which the mint reports "free" and the bind reports "taken."

Code Quality (raised in earlier passes, not repeating in detail)

test/dynamo/test_aot_compile.py still carries roughly 40 comment lines against 75 code lines in the added test, and the PR body answers that with a measurement showing each of the four blocks rejects a distinct green-but-vacuous rewrite. I disagree only on volume, not on substance, and it is not a merge risk. Noting once for the record and dropping it.

Recommendation

Approve

Seven passes have not produced a correctness defect. The remaining question I was carrying — whether tolerating a duplicate alias key in a live module dict has a guard-visible consequence — is now checked in guards.py rather than assumed, and it does not. This review has reached diminishing returns against an unchanged diff; further passes are unlikely to add signal unless the code changes.

Not verified locally: no .venv or built torch is available to this job, so this remains static analysis; the Test Plan commands were not run here.

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

@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 5m 13s —— View job


Nothing has been pushed since my seventh pass — HEAD is still 367b2ac, git diff origin/gh/bobrenjc93/1171/base...HEAD is byte-identical (+164/-8, same five files), and pytorchgreenlight has approved — so rather than restate seven passes I checked the two things about the test fixture I had never verified: whether patch.object on _unique_id_counter actually reaches the mint, and whether _hide_leaked_dynamo_globals popping keys out of a live module dict can damage a compiled artifact from an earlier test; both come back sound, and I have no blockers.

PR Review: #196822 (eighth pass)

Summary

Routes install_global, the resume-function name, and the __comprehension_* name through a new unique_id_unbound_in helper that skips past names already bound in the target module dict, fixing a CleanupHook.create collision when a fresh-counter compile follows a CompilePackage load.

I am not re-deriving the helper, its three call sites, the three exemptions, the check-dict/bind-dict agreement, the index-skip blast radius, the guard-invisibility of the extra alias key, or the disown fixture — each has held across seven independent derivations. Below is only what is new. Prior passes concentrated on the torch/ half; this one is aimed at the fixture, since that is where an unnoticed defect would show up as CI flake rather than a wrong answer.

New verification this pass

The counter patch reaches the mint, which is not obvious and is load-bearing for every assertion in the test. patch.object(bytecode_transformation, "_unique_id_counter", itertools.count()) (test_aot_compile.py:1542) rebinds a module attribute, so it only takes effect if the consumer resolves that name at call time through the module global rather than closing over the object. It does: unique_id reads next(_unique_id_counter) as a module-global lookup on every call (bytecode_transformation.py:1987), and unique_id_unbound_in calls unique_id rather than the counter (:2006, :2008), so the patch is seen through both hops. I also confirmed _unique_id_counter is referenced in exactly three places repo-wide — its definition, that one read, and the test's patch — so there is no second module that imported the counter object by value (from ... import _unique_id_counter) and would keep using the unpatched one. Had any site done that, the rewind would silently no-op and all three phases would mint from the real counter, well past the sentinels, making the test green and vacuous — the exact failure the PR body's :1494-1496 comment is defending against, reached through a mechanism that comment does not cover.

The not isinstance(g[k], str) filter is a sound discriminator, not a coincidence. compile_with_taken_names returns [k for k in g if k.startswith(minted_prefix) and not isinstance(g[k], str)], i.e. it separates the phase's sentinels (the string "taken by another process") from the real mint by value type. That holds for all three parameters because the installed value is never a str: install_builtins_dict_in_fglobals binds get_builtins_dict(self.global_scope), a dict (output_graph.py:1153-1154), and both the resume and comprehension paths bind either a types.FunctionType or the _make_fn closure (output_graph.py:3558-3565). So the (minted,) = ... unpacking cannot be broken by a sentinel leaking into the result, and cannot be broken by the mint being mistaken for one.

The fixture's pop can degrade a live compiled artifact from an earlier test, but the damage is bounded to a recompile and is undone in cleanup. _hide_leaked_dynamo_globals pops every _MINTED_PREFIXES key out of globals() for the test's duration (:1471-1474). If an earlier test in this module left a live torch.compile'd function whose guards read G['__builtins_dict___0'], that key is now absent while this test runs. I checked the consequence: a missing global is a graceful guard miss, not an error — the same KeyError on G[...] → silent-recompile behavior the PR body's own FAQ measured for the _install_global experiment — so the worst case is one extra recompile in an unrelated test, and restore() (:1476-1482) puts the originals back. Nothing in the file calls a previously-compiled function after a later test's setUp, and TestCase resets between tests. Worth knowing the exposure exists; it is not worth changing.

install_global's other two callers are genuinely covered by the one edit, and _MINTED_PREFIXES listing them is correct rather than defensive. install_global has exactly three callers — __builtins_dict__ (output_graph.py:1154), __gen_rand_values (:2144), __warnings_warn_wrapper (symbolic_convert.py:3699) — and all three inherit the skip from the single line at :3601. The test parametrizes only the first, but the other two must still appear in _MINTED_PREFIXES because a leftover from either one would sit in this module's dict at an index a rewound counter regenerates, which is what the hide half exists to prevent. Coverage and enumeration are correctly scoped differently here.

No export-surface change. bytecode_transformation.py has no __all__, so adding unique_id_unbound_in neither extends nor needs to extend a public list, and unique_id remains for the three exempted sites — the module is not left half-converted (unique_id no longer appears at all in output_graph.py, symbolic_convert.py, or comprehension_graph_break.py).

Recommendation

Approve

Eight passes, now including the fixture's own mechanics, have not produced a correctness defect. The counter patch propagates correctly, the sentinel/mint discriminator is type-sound, and the one new exposure I found (hiding globals out from under a live artifact) degrades to a recompile and is reverted in cleanup. The comment-volume note from earlier passes is style and the PR body answers it with measurements; I am not repeating it. This review has reached diminishing returns against an unchanged diff — further passes are unlikely to add signal unless the code changes.

Not verified locally: no .venv or built torch is available to this job (import torch is not runnable here), so this remains static analysis; the Test Plan commands were not run.

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

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 2 checks: inductor / unit-test / inductor-cpu-test / test (inductor_aoti_fallback, 1, 2, mt-l-x86iamx-8-64, unstable), inductor / unit-test / inductor-cpu-test / test (inductor_aoti_fallback, 2, 2, mt-l-x86iamx-8-64, unstable)

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

pytorchmergebot pushed a commit that referenced this pull request Sep 14, 2026
…on, across processes (#196821)

Tests only. One covers the alias seeding in #196817, reached through the
guard-scope resolution in #196818 and exercised through an `nn.Module` artifact
where that scope is resolved rather than passed. The other covers #196822's
`install_global` retry across processes; the last paragraph explains why it rides
here rather than with the fix.

The first is the real deployment shape: the artifact is captured in a subprocess
that never runs in this interpreter, so the load itself has to seed the aliases
its kept guards are rooted at. It asserts against the namespace delta -- which
`__import_*` names this module's globals gained across the load -- rather than
against the artifact re-filtered by the gate under test, which passes with the
gate deleted: the artifact records several aliases and only the one a kept guard
reads may be written into a live user namespace. Which alias that is comes off
the serialized `global_scope`, pruned to exactly the guarded names, rather than
off a literal. The recorded `__builtins_dict___N` key is the other half of the
same rule under its own gate: the serializer writes that key into the pruned
scope whether or not a guard reads it, so the load scans the kept guards'
sources for that key instead, and this capture's filter drops BUILTIN_MATCH, so
no kept guard names it and the load leaves it unbound. No state dict is copied
from the capturing process, so the closing `assertEqual(model(x), mod(x))` is a
real numeric assertion that dispatch reads this process's live parameters
rather than tensors baked into the artifact.

It restores the globals it disturbed through the helper added lower in the
stack, which by #196818 pops the `__import_*` aliases along with the other name
families in the test file's `_MINTED_PREFIXES`. A test that loads needs that
alias half popped, since its guards are rooted at those aliases: a sibling's
in-process capture leaves them bound, and a load that finds them already there
seeds nothing, so a pin on what the load wrote would be vacuous. The test
asserts the namespace starts with none of them; cleanup still strips whatever
the load added before putting the originals back, so the names the load seeded
do not outlive it.

The second test is the cross-process half of #196822's `install_global` retry:
a fresh process loads a module artifact captured with its BUILTIN_MATCH guard
kept -- a load seeds that key only for an artifact whose kept guards read it --
so the load seeds a `__builtins_dict___N` key, and then a compile in that same
process mints that name and has to be handed another. The mint is put there by
rewinding the counter to the index read off the name the load seeded, rather
than by betting that the capturing and the loading process both stopped their
counters at the same index: either side burning an id leaves the two names in
no conflict at all, the retry never runs, and the test goes red for a reason
unrelated to it. What the in-process sibling cannot do is make the taken name a
real one -- it pre-binds a sentinel string -- and that, not the counter
arithmetic, is what this test adds. It rides here rather than with the fix
because the shape it needs -- a module load whose guard scope is the loading
module's live namespace, so the captured builtins-dict key is seeded there
rather than into a scope rebuilt from the artifact -- arrives with #196818,
above the fix. It could have been written against the function path at #196817
instead, since a caller-supplied `f_globals` is normally the defining module's
live namespace and reaches the same collision; the module shape was kept
because there the load resolves the scope itself, so nothing in the test can be
read as the caller choosing a namespace to collide in. The reloading wrapper
takes no `guard_filter_fn`: `_load_aot_compiled_module` reads only the
artifact, so the loading process's filter has no say in what a loaded artifact
checks, and naming one that drops BUILTIN_MATCH would have contradicted the
capture this test loads. #196822 keeps the in-process tests, and cites the
precompile package path that reaches the same collision at the base of this
stack.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_import_alias_guard_loads_across_processes
python test/dynamo/test_aot_compile.py -k test_load_then_compile_survives_baked_in_global_collision
```

Authored with the assistance of Claude Code.

Co-Authored-By: Claude Opus 5 <[email protected]>

## FAQ

> **FAQ: If `install_global` were changed to overwrite the taken name instead of
> retrying past it, would the load's seeded `__builtins_dict___0` be clobbered
> with this test still green, so a `model(x)` vs `mod(x)` comparison is needed
> after the colliding compile?** No. Built with that exact mutation -- the
> `while name in scope` loop deleted from `unique_id_unbound_in` AND the
> `if name in scope: raise AssertionError` deleted from `CleanupHook.create`, so
> the install really does overwrite -- the test as written FAILS:
> `AssertionError: no collision on __builtins_dict___0: [...] -> {...}`, because
> the post-compile key set is unchanged. The suggested replacement is the one
> that does not work: with the same mutation in place and the numeric comparison
> substituted for the key-set assertion, the run prints
> `EXPERIMENT: post-collision numerics OK` and passes. It cannot detect a
> clobber, because both bindings hold the SAME object -- `get_builtins_dict`
> returns `global_scope["__builtins__"]` and `_seed_guard_scope` falls back to
> `builtins.__dict__`, so within one process the seeded value and the value a
> later compile installs are identical and overwriting one with the other is
> numerically invisible. Load-path numerics are separately pinned by
> `test_aot_compile_module_import_alias_guard_loads_across_processes` in this
> same commit, whose closing `assertEqual(model(x), mod(x))` covers exactly the
> "dispatch reads live parameters" property; duplicating it here is the
> one-fact-two-places the same review asks to remove.

> **FAQ: Isn't `assertEqual({k for k in g if k.startswith("__import_")}, set())`
> tautological one line after `_hide_leaked_dynamo_globals()`, whose whole job is
> popping every `_MINTED_PREFIXES` name?** It is the only assertion in the test
> that is not vacuous if that helper stops popping the `__import_` family.
> Measured: with `__import_torch_dot_nn_dot_modules_dot_module` bound in the
> module dict after the helper runs -- exactly what a helper that no longer pops
> that prefix leaves behind -- the load seeds nothing
> (`EXPERIMENT seeded by load: set()`) and the main assertion below still passes,
> `Ran 1 test ... OK`, covering nothing. Put the line back in and the same run
> goes red: `AssertionError: Set comparison failed: Items in the first set but
> not the second`. That is the vacuity the commit message calls out ("a load that
> finds them already there seeds nothing, so a pin on what the load wrote would
> be vacuous"), and this line is what rules it out.

> **FAQ: `torch.compile(later, ...)` discards its wrapper, so shouldn't a comment
> record the hidden invariant that a `CleanupHook` cannot fire and empty `after`?**
> There is nothing hidden left to document once it is measured: two forced full
> collections inserted immediately before the read leave the name in place
> (`EXPERIMENT after gc: installed = {'__builtins_dict___1'}`, test OK), for the
> reason the review itself gives -- the hook is keyed on the output code object
> held by `later.__code__`'s `ExtraState`, and `later` is a live local through the
> assertion. Adding an explanation of why an unreachable failure is unreachable, in
> the same review that asks for roughly 40 comment lines to come down, would trade
> a real cut for a speculative one; the block instead lost nine comment lines. If
> the hook ever could fire the assertion is loud, not silent: it names the key set
> it read.

> **FAQ: Isn't the 101-column f-string at `:864` over B950's ~96-column ceiling
> at `line-length = 88`?** B950 is enforced by nothing in this repo:
> `.flake8:25` lists `B950` under "Codes where ruff is the source of truth", and
> ruff does not implement B950 (its `select` takes `B` and `E`, with `E501`
> explicitly ignored at `pyproject.toml:484`). `lintrunner --take RUFF,PYFMT` and
> `lintrunner --take FLAKE8` both report `ok No lint issues` on the file at HEAD,
> and 18 lines in this same file already exceed 96 columns before this commit
> touches it. The rewrite of the assertion shortened the message anyway, to 81
> columns.

> **FAQ: Should the colliding compile be wrapped in
> `patch.object(bytecode_transformation, "_unique_id_counter", itertools.count())`
> so the mint lands at index 0 regardless of how many ids the load burned?**
> The determinism problem is real and is fixed, but not with a counter that
> starts at 0 -- that fixes only the loading side. Measured: with the suggested
> `itertools.count()` in place and one `unique_id` burned in the LOAD path, the
> test passes; with the same fix and two ids burned in the CAPTURE path, it fails
> again, `expected a name collision: seeded={'__builtins_dict___1'},
> minted=['__builtins_dict___0', ...]`, because the artifact's baked-in index
> moved and the fresh counter still starts at 0. The counter is therefore rewound
> to the index read off the name the load actually seeded
> (`itertools.count(int(taken.rpartition("_")[2]))`), which is green under a burn
> on either side and still red under the mutation it targets.

> **FAQ: The three-line alias derivation (`guarded = set(import_sources) &
> set(...global_scope)`, `assertLess`, `(alias,) = guarded`) is duplicated
> verbatim across the two tests, with its rationale comment restated too --
> shouldn't it be one helper on the test class returning `(import_sources,
> guards_state, alias)`?** The idiom appears exactly twice in the file, and
> only one of the two is this commit's:
> `test_aot_compile_module_import_alias_guard_loads_across_processes`
> (`:3531-3536`, added here) and
> `test_load_seeds_exactly_the_recorded_globals` (`:4189-4194`), which is
> already present at this commit -- `git log -S` puts it in #196817, six
> commits down. The shared helper therefore cannot live here at all: it would
> be a new `TestAOTCompile` method added in #196817 and called once from each
> of two PRs, to save three lines. Those three are not character-for-character
> identical either -- the first two are, the third binds a different name
> (`(alias,)` vs `(kept_alias,)`), because #196817's test keeps that name live
> for another thirty lines, where "kept" is what distinguishes the guarded
> alias from the sentinel the test deliberately writes over it (`:4221`,
> `:4223-4229`). The requested return tuple also absorbs two lines that are
> not shared behaviour: #196817's test reads `builtins_key` off `guards_state`
> BEFORE the derivation (`:4186`) and checks a caller-supplied `scope`, while
> this one reads it after and checks live `globals()`. And the middle line is
> an assertion; moving `assertLess` into a shared helper reports the failure
> from the helper instead of from the test whose premise -- the artifact
> records more aliases than any kept guard reads -- it exists to pin. The
> rationale is not duplicated one-for-one either: only the "pruned to exactly
> the guarded names, rather than off `import_sources`' order" clause is
> common. This test's comment is four lines because it carries a reason the
> other has no room for (assert on what the load wrote into this live
> namespace, "not against the artifact re-filtered by the gate under test",
> and not off a literal, an alternative that only exists when the target is
> `globals()`); #196817's is two. Weighed against the repo's style rule -- do
> not add trivial one-or-two-line helpers used once unless they significantly
> improve readability, and when uncertain choose the simpler, more concise
> implementation -- a cross-PR helper wrapping five lines with two call sites
> and two different downstream shapes is the more expensive of the two options
> to read, so the derivation stays inline and identical, which was the
> substance of the earlier request.

> **FAQ: `model(torch.randn(4, 4))` in `_subprocess_load_then_compile` discards its
> result, and the seeding it looks like it triggers already ran in `__post_init__`,
> so `seeded` is populated with or without it -- either drop the line or give it
> the one-line reason?** The reason is now on it, at `:812-813`: `# The only serve
> of the loaded artifact: a guard rooted at a name the load failed to seed raises
> HERE, not at any assertion below.` Dropping it is the half the measurement rules
> out. It is the test's only call on the loaded artifact, and
> `AOTCompiledModel.__call__` raising on a guard miss (`aot_compile.py:1421-1426`)
> is the assertion. One mutation at a time in a scratch copy, each run with the
> line deleted and then restored: pop the two `__import_*` aliases the kept guards
> are rooted at back out at the end of `_seed_guard_scope`, and without the line
> the test is green, `Ran 1 test ... OK`, while with it it is red -- `RuntimeError:
> GuardManager check failed, reason: GuardDebugInfo(verbose_code_parts=["KeyError
> on G['__import_torch_dot_nn_dot_modules_dot_linear']"], ...)` (the per-input
> report that spells this `[0] KeyError on G[...]` arrives with #196823). Seed the
> builtins key to the wrong dict and the split repeats: green without the line,
> `KeyError on G['__builtins_dict___0']['isinstance']` with it. Nothing else here
> reaches either class -- `:896-902` checks only that the key is BOUND, not that
> anything resolves through it, and `:936-942` reads the mint `later`'s own compile
> made, whose guards are rooted at nothing the artifact seeded -- and no sibling
> does either: `:3509` captures under `keep_global_guards`, which drops
> BUILTIN_MATCH.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: #196821
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196767, #196817, #196815, #196816, #196818, #196819, #196820
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1171/head branch November 19, 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