Repository navigation
[dynamo] Skip an already-bound name when installing a global - #196822
bobrenjc93 wants to merge 5 commits into
Conversation
[ghstack-poisoned]
🔗 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 ( GREEN LIGHT - PR approved to be merged without human review:
reason: 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. |
View job run | Branch: |
|
Claude finished @bobrenjc93's task in 18m 30s —— View job The
|
|
Claude finished @bobrenjc93's task in 23m 45s —— View job The
|
|
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
|
|
Claude finished @bobrenjc93's task in 13m 8s —— View job Nothing has been pushed since my sixth pass — HEAD is still
|
|
Claude finished @bobrenjc93's task in 5m 13s —— View job Nothing has been pushed since my seventh pass — HEAD is still
|
|
@pytorchbot merge -i |
Merge startedYour 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 |
…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

Stack from ghstack (oldest at bottom):
install_globaltrustsunique_idto hand out a free name, and within oneprocess 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___Nkey into the live module globals and re-installs a loadedentry's
__resume_at_*globals as well. A compile that happens after such a loadstarts its counter from zero, regenerates one of those names, and
CleanupHook.createraises on the collision. A load path added above thiscommit 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 tounique_idin
bytecode_transformationand skips forward while the generated name isalready bound in the scope it is handed.
unique_idis cheap and the loop runsat 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 resumefunction's name, which is skipped at its own site in
symbolic_convertratherthan inside
install_global_unsafe; and the__comprehension_*name incomprehension_graph_break, which installs through the same hook. That thirdone cannot collide today -- nothing records a
__comprehension_*name on apackage, 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.createraises 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_namemints__compiled_fn_N_<uuid4>andinstall_global_unsafebinds it directly(
output_graph.py:3133and:3136), and a load really does re-seed those --they are the artifact's backend ids, and
CompilePackage.install()writes eachone back into the module dict -- but the uuid is what puts them out of reach:
is_compiled_fn_namematches only a name carrying one, and no other process'scounter reproduces a uuid.
variables/builtin.py:1667, the constant fold inBuiltinVariable._handle_insert_op_in_graph, mintsunique_id(fn.__name__)but never binds it verbatim:
invoke_and_store_as_constanteither installsthrough
install_global_by_id, whose_{id(value)}_c{compile_id}suffixnothing records on a package for a load to re-seed, or hands the name to
register_attr_or_module, which re-uniquifies it againstglobal_scopethrough
get_unique_name_wrtbefore binding. Andresume_execution.py:169's___context_manager_Ngoes intoco_varnames, so it is a local of the resumefunction and reaches no module dict at all.
The resume name's placement is not about timing: at every
install_global_unsafecall site the install still precedes the codegen thatloads 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 asubstitute chosen inside the install would be ignored by the second use.
One test, parametrized over all three mint sites, rewinds
bytecode_transformation._unique_id_counterand pre-binds the names the nextmints 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
CleanupHookownership over withdisownfirst:reset()leaves the hookthat installed a name still owning it in
_cleanup_owners, and a hook fireswhenever 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_functionandcomprehensionit is that the function reached under the substituted name isthe right one, and for
install_globalthe skipped name holds the builtinsdict, so it is that the builtin guards still resolve through the substituted
key. A second call under
error_on_recompilepins that a later call is SERVEDrather than recompiled: for
install_globalthe builtin guards the compileinstalled 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:
Authored with the assistance of Claude Code.
Co-Authored-By: Claude Opus 5 [email protected]
FAQ
🤖 Generated with Claude Code