Repository navigation
Conversation
Serialize BUILTIN_MATCH since they are all stored in __builtin__ dict. Also fixed an issue that the wrong global scope is passed to CheckFunctionManager while loading guards. Previously we can always reuse the compile-time global scope for evaluating guards because the compile-time and runtime global scope are always the same. For precompile, we need to serialize the compile-time global scope for loading only. We need to point the CheckFunctionManager to the new global scope after loading is finished for evaluating guards. Differential Revision: [D77159313](https://our.internmc.facebook.com/intern/diff/D77159313/) [ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/157016
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit cd88d15 with merge base 4c8eb65 ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
Serialize BUILTIN_MATCH since they are all stored in __builtin__ dict. Also fixed an issue that the wrong global scope is passed to CheckFunctionManager while loading guards. Previously we can always reuse the compile-time global scope for evaluating guards because the compile-time and runtime global scope are always the same. For precompile, we need to serialize the compile-time global scope for loading only. We need to point the CheckFunctionManager to the new global scope after loading is finished for evaluating guards. Differential Revision: [D77159313](https://our.internmc.facebook.com/intern/diff/D77159313/) ghstack-source-id: 292943746 Pull Request resolved: #157016
|
This pull request was exported from Phabricator. Differential Revision: D77159313 |
Serialize BUILTIN_MATCH since they are all stored in __builtin__ dict. Also fixed an issue that the wrong global scope is passed to CheckFunctionManager while loading guards. Previously we can always reuse the compile-time global scope for evaluating guards because the compile-time and runtime global scope are always the same. For precompile, we need to serialize the compile-time global scope for loading only. We need to point the CheckFunctionManager to the new global scope after loading is finished for evaluating guards. Differential Revision: [D77159313](https://our.internmc.facebook.com/intern/diff/D77159313/) cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx chenyang78 kadeng chauhang amjames [ghstack-poisoned]
|
This pull request was exported from Phabricator. Differential Revision: D77159313 |
Serialize BUILTIN_MATCH since they are all stored in __builtin__ dict. Also fixed an issue that the wrong global scope is passed to CheckFunctionManager while loading guards. Previously we can always reuse the compile-time global scope for evaluating guards because the compile-time and runtime global scope are always the same. For precompile, we need to serialize the compile-time global scope for loading only. We need to point the CheckFunctionManager to the new global scope after loading is finished for evaluating guards. Differential Revision: [D77159313](https://our.internmc.facebook.com/intern/diff/D77159313/) cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx chenyang78 kadeng chauhang amjames [ghstack-poisoned]
|
This pull request was exported from Phabricator. Differential Revision: D77159313 |
Serialize BUILTIN_MATCH since they are all stored in __builtin__ dict. Also fixed an issue that the wrong global scope is passed to CheckFunctionManager while loading guards. Previously we can always reuse the compile-time global scope for evaluating guards because the compile-time and runtime global scope are always the same. For precompile, we need to serialize the compile-time global scope for loading only. We need to point the CheckFunctionManager to the new global scope after loading is finished for evaluating guards. Differential Revision: [D77159313](https://our.internmc.facebook.com/intern/diff/D77159313/) cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx chenyang78 kadeng chauhang amjames [ghstack-poisoned]
Pull Request resolved: #157016 Serialize BUILTIN_MATCH since they are all stored in __builtin__ dict. Also fixed an issue that the wrong global scope is passed to CheckFunctionManager while loading guards. Previously we can always reuse the compile-time global scope for evaluating guards because the compile-time and runtime global scope are always the same. For precompile, we need to serialize the compile-time global scope for loading only. We need to point the CheckFunctionManager to the new global scope after loading is finished for evaluating guards. ghstack-source-id: 293504156 @exported-using-ghexport Differential Revision: [D77159313](https://our.internmc.facebook.com/intern/diff/D77159313/)
|
This pull request was exported from Phabricator. Differential Revision: D77159313 |
Serialize BUILTIN_MATCH since they are all stored in __builtin__ dict. Also fixed an issue that the wrong global scope is passed to CheckFunctionManager while loading guards. Previously we can always reuse the compile-time global scope for evaluating guards because the compile-time and runtime global scope are always the same. For precompile, we need to serialize the compile-time global scope for loading only. We need to point the CheckFunctionManager to the new global scope after loading is finished for evaluating guards. Differential Revision: [D77159313](https://our.internmc.facebook.com/intern/diff/D77159313/) cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx chenyang78 kadeng chauhang amjames [ghstack-poisoned]
Pull Request resolved: #157016 Serialize BUILTIN_MATCH since they are all stored in __builtin__ dict. Also fixed an issue that the wrong global scope is passed to CheckFunctionManager while loading guards. Previously we can always reuse the compile-time global scope for evaluating guards because the compile-time and runtime global scope are always the same. For precompile, we need to serialize the compile-time global scope for loading only. We need to point the CheckFunctionManager to the new global scope after loading is finished for evaluating guards. ghstack-source-id: 293653150 @exported-using-ghexport Differential Revision: [D77159313](https://our.internmc.facebook.com/intern/diff/D77159313/)
|
This pull request was exported from Phabricator. Differential Revision: D77159313 |
Serialize BUILTIN_MATCH since they are all stored in __builtin__ dict. Also fixed an issue that the wrong global scope is passed to CheckFunctionManager while loading guards. Previously we can always reuse the compile-time global scope for evaluating guards because the compile-time and runtime global scope are always the same. For precompile, we need to serialize the compile-time global scope for loading only. We need to point the CheckFunctionManager to the new global scope after loading is finished for evaluating guards. Differential Revision: [D77159313](https://our.internmc.facebook.com/intern/diff/D77159313/) cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx chenyang78 kadeng chauhang amjames [ghstack-poisoned]
Pull Request resolved: #157016 Serialize BUILTIN_MATCH since they are all stored in __builtin__ dict. Also fixed an issue that the wrong global scope is passed to CheckFunctionManager while loading guards. Previously we can always reuse the compile-time global scope for evaluating guards because the compile-time and runtime global scope are always the same. For precompile, we need to serialize the compile-time global scope for loading only. We need to point the CheckFunctionManager to the new global scope after loading is finished for evaluating guards. ghstack-source-id: 293883339 @exported-using-ghexport Differential Revision: [D77159313](https://our.internmc.facebook.com/intern/diff/D77159313/)
|
This pull request was exported from Phabricator. Differential Revision: D77159313 |
|
@pytorchbot merge |
Merge startedYour change will be merged once all checks pass (ETA 0-4 Hours). Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
`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_GLOBAL`s `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](https://claude.com/claude-code)
Pull Request resolved: #196822
Approved by: https://github.com/pytorchgreenlight
Stack from ghstack (oldest at bottom):
Serialize BUILTIN_MATCH since they are all stored in builtin dict.
Also fixed an issue that the wrong global scope is passed to CheckFunctionManager while loading guards. Previously we can always reuse the compile-time global scope for evaluating guards because the compile-time and runtime global scope are always the same.
For precompile, we need to serialize the compile-time global scope for loading only. We need to point the CheckFunctionManager to the new global scope after loading is finished for evaluating guards.
Differential Revision: D77159313
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @chenyang78 @kadeng @chauhang @amjames