Repository navigation
[dynamo] Decide the verbatim tuple on its recording, keep builtins out of snapshots, guard the 3.14 annotation read - #196767
bobrenjc93 wants to merge 16 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/196767
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 f1cb16f with merge base b8bd7cf ( 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. |
|
Claude finished @bobrenjc93's task in 28m 9s —— View job Reviewed: the Full reviewPR Review: #196767SummaryThree cleanups to the guard-state pickler: decide verbatim plain tuples from Code Quality
Testing
RecommendationRequest Changes The annotation swallow is the blocker: it can turn a correct bypass into a guard that misses forever, and the new test pins that behaviour. The |
… longer overflows on a deep list) [ghstack-poisoned]
…t of snapshots, guard the 3.14 annotation read Follow-up to the reviews of #196476, #196478 and #196479. `_keep_container_verbatim` decided a plain tuple in two steps: is it in `guard_tree_values`, and is it in `value_guarded_containers`. The second alone is the rule; the first held because `EQUALS_MATCH` registers the value it reads, a separate invariant whose failure would be the silent forever-miss the rule exists to prevent. The tuple case now reads the recording alone: ```python if type(container) is tuple: return id(container) in self.value_guarded_containers if type(container) is dict: return False return self._keep(container) ``` A globals snapshot kept `__builtins__` "as read" when some guard had registered it and replaced it with the `builtins` module only when pruned. For an imported module `f_globals["__builtins__"]` IS `builtins.__dict__`, the dict every compile that guards a builtin registers, so the kept branch was the common one and each snapshot carried all of builtins (about 6 KB, 155 keys) next to the filtered copy `G` already holds; the two are distinct objects, so pickle does not share them. The entry is now always the module, pickled by reference. `FunctionType` accepts either. `_read_raw_annotations` asked `annotationlib` for FORWARDREF annotations on 3.14 unguarded. FORWARDREF reruns the annotate function with every NAME lookup proxied, so it absorbs a missing name, a raising attribute or a raising call, but a sub-expression with no name in it still raises out of it: ```python def f(x: f"{Missing}"): # TypeError: Cannot stringify annotation containing string formatting def f(x: ()[0]): # IndexError ``` That would fail the dump for a slot the prune exists to make optional; the read now returns an empty set instead. The 3.14 path had no test at all, since every annotation in the suite either was an assigned dict or resolved; a 3.14-gated test now pins that a TYPE_CHECKING-only name comes back as a pruned proxy and the f-string case drops the set (CI runs this file on 3.14; there is no local 3.14 build). `_missing` uses `torch.utils._functools.cache_method`, the in-tree per-method cache that does not pin `self`, in place of a hand-rolled dict. Test and comment cleanups: the guarded-defaults test names the full-compile round trip that can tell a whole-container guard from a per-element one instead of forward-referencing it; the two snapshot tests capture the module dict's key set BEFORE the dump, since a `CleanupHook` for a traced code object can drop a `__builtins_dict___N` key out of the live dict during the load; the `name_beside_unpicklable_default` subtest says it prunes only because the harness drops the `bind_args` guard; the pickler `__init__` comment no longer claims omitting the recording prunes every container. One #196476 comment is not a change here: the AOT pickler's own by-value reducer carried only `__defaults__` at that commit, so an AOT-rebuilt helper lost `__kwdefaults__` and `__dict__` and its `__name__` was the qualname. #196685 and the commits above it move that pickler onto the shared base, which is where those are fixed in this stack. Test Plan: ``` python test/dynamo/test_guard_serialization.py python test/dynamo/test_guard_serialization.py -k snapshot -k verbatim -k type_checking_only python test/dynamo/test_aot_compile.py -k Pickler python test/dynamo/test_package.py ``` The two snapshot tests, the verbatim-rule tests and the `__builtins__` change pass on the previous commit as well (the rule and the module are behaviourally the same for every recorded tuple and every imported module); the TYPE_CHECKING test is 3.14-only and runs in CI. Authored with an AI assistant. ghstack-source-id: a071f27 Pull-Request: #196767
[ghstack-poisoned]
…t of snapshots, guard the 3.14 annotation read Follow-up to the reviews of #196476, #196478 and #196479. `_keep_container_verbatim` decided a plain tuple in two steps: is it in `guard_tree_values`, and is it in `value_guarded_containers`. The second alone is the rule; the first held because `EQUALS_MATCH` registers the value it reads, a separate invariant whose failure would be the silent forever-miss the rule exists to prevent. The tuple case now reads the recording alone: ```python if type(container) is tuple: return id(container) in self.value_guarded_containers if type(container) is dict: return False return self._keep(container) ``` A globals snapshot kept `__builtins__` "as read" when some guard had registered it and replaced it with the `builtins` module only when pruned. For an imported module `f_globals["__builtins__"]` IS `builtins.__dict__`, the dict every compile that guards a builtin registers, so the kept branch was the common one and each snapshot carried all of builtins (about 6 KB, 155 keys) next to the filtered copy `G` already holds; the two are distinct objects, so pickle does not share them. The entry is now always the module, pickled by reference. `FunctionType` accepts either. `_read_raw_annotations` asked `annotationlib` for FORWARDREF annotations on 3.14 unguarded. FORWARDREF reruns the annotate function with every NAME lookup proxied, so it absorbs a missing name, a raising attribute or a raising call, but a sub-expression with no name in it still raises out of it: ```python def f(x: f"{Missing}"): # TypeError: Cannot stringify annotation containing string formatting def f(x: ()[0]): # IndexError ``` That would fail the dump for a slot the prune exists to make optional; the read now returns an empty set instead. The 3.14 path had no test at all, since every annotation in the suite either was an assigned dict or resolved; a 3.14-gated test now pins that a TYPE_CHECKING-only name comes back as a pruned proxy and the f-string case drops the set (CI runs this file on 3.14; there is no local 3.14 build). `_missing` uses `torch.utils._functools.cache_method`, the in-tree per-method cache that does not pin `self`, in place of a hand-rolled dict. Test and comment cleanups: the guarded-defaults test names the full-compile round trip that can tell a whole-container guard from a per-element one instead of forward-referencing it; the two snapshot tests capture the module dict's key set BEFORE the dump, since a `CleanupHook` for a traced code object can drop a `__builtins_dict___N` key out of the live dict during the load; the `name_beside_unpicklable_default` subtest says it prunes only because the harness drops the `bind_args` guard; the pickler `__init__` comment no longer claims omitting the recording prunes every container. One #196476 comment is not a change here: the AOT pickler's own by-value reducer carried only `__defaults__` at that commit, so an AOT-rebuilt helper lost `__kwdefaults__` and `__dict__` and its `__name__` was the qualname. #196685 and the commits above it move that pickler onto the shared base, which is where those are fixed in this stack. Test Plan: ``` python test/dynamo/test_guard_serialization.py python test/dynamo/test_guard_serialization.py -k snapshot -k verbatim -k type_checking_only python test/dynamo/test_aot_compile.py -k Pickler python test/dynamo/test_package.py ``` The two snapshot tests, the verbatim-rule tests and the `__builtins__` change pass on the previous commit as well (the rule and the module are behaviourally the same for every recorded tuple and every imported module); the TYPE_CHECKING test is 3.14-only and runs in CI. Authored with an AI assistant. ghstack-source-id: 3992d8d Pull-Request: #196767
|
Claude finished @bobrenjc93's task in 19m 33s —— View job Reviewed: nothing in the three PR files has moved since the last round, so this round I went after the one half of the annotation argument that had only ever been checked at the save side — whether an empty Full reviewPR Review: #196767SummaryThree cleanups to the guard-state pickler: decide a verbatim plain tuple from What moved: nothing in this PR's files. Verified this round, so not findingsThe annotation drop is inert on the load side too, which is the half of the argument the comment does not make.
No new test passes vacuously, and each exercises the reducer it claims to. All five snapshot/tuple tests build their function with The The seven-line log block really is duplicated rather than shared, for the reason the PR gives. CI: Dr. CI reports GREEN at RecommendationApprove No findings. The three behaviour changes are each pinned by a test that fails on the parent; the tuple rewrite is total against its only producer ( Note: there is no built torch in this checkout ( |
|
Claude finished @bobrenjc93's task in 24m 3s —— View job Reviewed: nothing in the three PR files has moved since the last round, so this round I fanned out over three areas no prior round had touched — whether the new snapshot exemption can now disagree with the other builtins-dict path in the same file ( Full reviewPR Review: #196767SummaryThree cleanups to the guard-state pickler: decide a verbatim plain tuple from What moved: nothing in this PR's files. Verified this round, so not findingsThe exemption cannot disagree with the other builtins-dict path in the same file — and it narrows a pre-existing gap rather than widening one. This is the angle I most expected to yield something, because
No concurrency exposure from the new module-level singleton. Dynamo compiles concurrently in several regimes, and no prior round had checked what a process-wide The two mock-based tests and the real CI: the only failing workflow is RecommendationApprove No findings. The three behaviour changes are each pinned by a test that fails on the parent; the tuple rewrite is total against its only producer ( Note: there is no built torch in this checkout ( |
|
@pytorchbot merge -i |
|
Claude finished @bobrenjc93's task in 32m 21s —— View job Reviewed: nothing in the three PR files has moved since the last round, so this round I went after an angle no prior round had taken — verifying the factual claims in the comments this PR newly writes, rather than the behaviour they describe — and four of the five check out exactly. What is left is two nits about the new annotation handler, both grounded in an asymmetry with the sibling handler the PR explicitly discusses as its pair. No blockers. Full reviewPR Review: #196767SummaryThree cleanups to the guard-state pickler: decide a verbatim plain tuple from What moved: nothing in this PR's files. The comments this PR writes: four claims verified exactly, one loosePrior rounds all audited the behaviour. Nobody had checked whether the mechanisms the new comments assert are true — which matters, because a comment asserting a false mechanism is what a future reader acts on. Four hold precisely:
The fifth is loose rather than wrong:
Code Quality
Verified this round, so not findings
CI: the only failing workflow is RecommendationApprove No blockers. The three behaviour changes are each pinned by a test that fails on the parent; four of the five factual claims the new comments make are exactly right against the code, with the fifth over-reaching only in scope; and the two remaining items are a missing memo and a missing exception type on a DEBUG line, both mitigated by the deliberate symmetry with the sibling handler. Note: there is no built torch in this checkout ( |
Merge startedYour change will be merged while ignoring the following 2 checks: inductor / unit-test / inductor-cpu-test / test (inductor_aoti_fallback, 2, 2, mt-l-x86iamx-8-64, unstable), inductor / unit-test / inductor-cpu-test / test (inductor_aoti_fallback, 1, 2, mt-l-x86iamx-8-64, unstable) Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
|
Claude finished @bobrenjc93's task in 28m 25s —— View job Reviewed: nothing in the three PR files has moved, and the PR has since been merged ( Full reviewPR Review: #196767SummaryThree cleanups to the guard-state pickler: decide a verbatim plain tuple from State. The checkout's blobs for all three files match the PR's changed-file SHAs ( Verified this round, so not findingsThe 3.14 test really is exercised in CI — the one claim every prior round relayed from the description without checking. The Test Plan rests the FORWARDREF coverage on "CI runs this file on 3.14; there is no local 3.14 build", and prior rounds (mine included) repeated it. Traced end to end: On 3.14 the FORWARDREF read cannot drop a guard-registered annotation value, and the keep branch really is dead there. The Testing
RecommendationApprove (post-merge; the item above is follow-up material) The three behaviour changes are each pinned by a test that fails on the parent; the tuple rewrite is total against its only producer ( Note: there is no built torch in this checkout ( |
|
Claude finished @bobrenjc93's task in 22m 24s —— View job Reviewed: nothing in the three PR files has moved since the last round (the PR is merged), so this round I went after an angle no prior round had taken — reading the newly written comments against each other rather than against the code — and found one internal inconsistency: two comments ten lines apart in the same function describe the 3.14 FORWARDREF read in contradictory terms, and the contradiction sits on the argument that makes a branch dead. Follow-up material, not a blocker. Full reviewPR Review: #196767SummaryThree cleanups to the guard-state pickler: decide a verbatim plain tuple from State. All three blobs match the PR's changed-file SHAs ( Code Quality
Verified this round, so not findings
CI: 9 passed, 1 failed ( RecommendationApprove (post-merge; the item above is follow-up material) The three behaviour changes are each pinned by a test that fails on the parent; the tuple rewrite is total against its only producer and its five call sites; the builtins exemption's one-directional cost is disclosed in the comment and its marker is now immune to the mid-dump growth of Note: there is no built torch in this checkout ( |
…into the guard scope on load (#196817) When Dynamo traces a function it mints synthetic names into the TRACING process's `fn.__globals__` and roots guards at them. Two kinds matter here: ```python class M(torch.nn.Module): def __init__(self): super().__init__(); self.lin = torch.nn.Linear(4, 4) def forward(self, x): if not isinstance(x, torch.Tensor): # a builtin reference raise TypeError(type(x)) return self.lin(x) # a child-module call torch.compile(M(), backend="eager")(torch.randn(2, 4)) g = M.forward.__globals__ [k for k in g if k.startswith("__import_")] # ['__import_torch_dot_nn_dot_modules_dot_module', ...] [k for k in g if k.startswith("__builtins_dict__")] # ['__builtins_dict___0'] g["__builtins_dict___0"] is builtins.__dict__ # True: the LIVE builtins dict ``` The guards read those names through `G[...]`: ``` G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks # DICT_LENGTH == 0 ___check_obj_id(G['__builtins_dict___0']['isinstance'], 140012...) # BUILTIN_MATCH, an ID_MATCH into the dict ``` A process that only LOADS an `aot_compile` artifact never traced, so its scope has none of those names. The default `guard_filter_fn` drops global guards wholesale, which is why this stayed hidden; keep them and the load dies: ```python compiled = torch.compile(m, fullgraph=True, backend="eager", options={"guard_filter_fn": keep_global_guards}).aot_compile(((x,), {})) compiled.save_compiled_function("m.pt") # ---- a fresh process ---- loaded = AOTCompiledFunction.deserialize(open("m.pt", "rb").read()) loaded(x) # RuntimeError: ... KeyError on G['__import_torch_dot_nn_dot_modules_dot_module'] ``` In-process tests could not see this: the capture had already leaked the aliases into the module dict, so the load found them there. ## Who needs a global guard on a loaded artifact A model that reads module-level state in `forward` is specialized on that state at trace time, and the global guards are the only record of it: ```python EPS = 1e-5 # baked into the graph as a constant USE_FUSED = True # picks a branch at trace time FREQS = torch.randn(4096, 64) # lifted as a graph input; dtype/shape/device guarded def forward(x): if USE_FUSED: ... return (x / (x.norm() + EPS)) * FREQS[:x.shape[1]] ``` Under the default filter a loading process that sets `EPS = 1e-3`, flips `USE_FUSED`, or binds a bf16 `FREQS` is served the traced graph anyway, with no error. That is the right default for an artifact shipped to a different codebase, and this commit leaves it alone. It is the wrong trade for the other common deployment, precompile as a warm cache across processes running the SAME code, where the module layout matches and there is no reason to give up the safety eager `torch.compile` has; `CompilePackage` already lives there and keeps every guard. `torch.compile` exposes the choice through `guard_filter_fn` and ships helpers for it (`keep_global_context_and_tensor_guards_unsafe`, `keep_tensor_guards`, `skip_guard_on_globals`). Before this commit the choice did not work: keep a global guard and the load crashed on the alias, or the guard resolved against the snapshot the tracing process serialized, which agrees with itself and so can never fail. An offered option has to either work or refuse. Some `G[...]` readers survive even the default filter, because `is_global` looks only at `originating_source`: a `SHAPE_ENV` guard on a dynamic-dim module-level tensor, and a `DUPLICATE_INPUT` whose `source_b` is a global. The shape-guard case raised `KeyError` on every default load before this commit, so the fix below reaches artifacts that never touched the filter. ## Seed the guard scope at load, gated per name `AOTCompiledFunction.__post_init__` now calls `_seed_guard_scope` before `load_guard_manager`, writing into whichever dict the guards will resolve against. In outline: ```python def _seed_guard_scope(guard_scope, output_graph): # aliases: the artifact recorded {alias: module_name} in runtime_env.import_sources for alias, module_name in runtime_env.import_sources.items(): if alias in output_graph.global_scope and alias not in guard_scope: guard_scope[alias] = importlib.import_module(module_name) # builtins key: only when a deserialized guard is rooted at exactly that name roots = {get_global_source_name(g.originating_source) for g in output_graph.guards} if builtins_key in roots: CleanupHook.disown(guard_scope, builtins_key) ... # the re-derive below guard_scope.setdefault("__builtins__", builtins.__dict__) guard_scope[builtins_key] = get_builtins_dict(guard_scope) ``` Each name is gated on a kept guard being rooted at THAT name, not on the artifact having some global-rooted guard, because this writes into a dict that may be a user module's live namespace and installs no `CleanupHook`. A gate that coarse pays exactly the cost it exists to avoid in the case it admits: an artifact whose only global guard is on a user global would still write the builtins key into the caller's namespace, and would `disown` a name a live compile in that module owns. The two gates differ because the serializer records the two names differently: - **Aliases** are gated on the serialized `global_scope`, which the serializer already pruned to the names the kept guards resolve at check time. That set is wider than the guards' `originating_source`s: a `DUPLICATE_INPUT` reads its `source_b` and a `SHAPE_ENV` guard reads the shape-env sources, and a scope lacking either fails with the same `KeyError on G[...]` (measured). That is exactly the set an alias must be seeded for. An alias can only be missing from a caller-supplied scope, since `GraphRuntimeEnv.forward_callable` builds `fn.__globals__` with every recorded alias already imported. - **The builtins key** cannot use that gate: the serializer writes it into the pruned scope whether or not a guard reads it. So it is matched against the roots of the deserialized guards. The two wider channels never root at the builtins key: `load_builtin_from_argval` is the only place a source under that key is minted, and `guard_on_key_order` cannot name it, since every site that fills it adds the source of a dict or set variable. That is a structural property, so `test_builtins_key_gate_covers_the_other_serializer_channels` pins it: one artifact that really populates both channels (a non-empty `shape_env_sources`, and a `DUPLICATE_INPUT` whose `source_b` is a `GlobalSource`) and neither yields the builtins key. It never loads, so it passes unchanged on the parent; it guards the serializer property the gate relies on. A binding this process already had is left alone: a wrong binding FAILS a guard rather than passing it, and a caller-supplied scope may legitimately carry these names. That deliberately differs from `install()`'s builtins branch in package.py, which raises on a mismatch. `CleanupHook.disown` still runs on the builtins key even when its value is kept: a pre-reset compile may own the name and would delete the binding when its hook is collected. `test_load_disowns_only_a_builtins_key_a_guard_reads` pins both directions against a live compile that minted the artifact's exact key name. The aliases need no `disown`: `import_source` and `CompilePackage._install_global` bind one by plain dict assignment, and `install_global_unsafe`, the only site that creates a `CleanupHook`, never installs an alias. ## The builtins key must point at LIVE builtins, not a snapshot On the DEFAULT load path the key is often already present, and that is the second bug. When the generated bytecode itself reads a builtin (one that survived into the output instead of being constant-folded away), the reconstruction goes through `DictGetItemSource(GlobalSource(key))`, so `get_runtime_env` records the key in `used_globals` holding a pickle-FILTERED COPY of the tracing builtins. `forward_callable` spreads `used_globals` into `fn.__globals__`, which on the default path IS the guard scope. The old `builtins_key not in guard_scope` gate bailed, and the guard compared identities inside a frozen snapshot: ```python def fn(x): if isinstance(x, torch.Tensor): # constant-folded; its BUILTIN_MATCH is kept via keep_builtin_guards return len # `len` survives, so the bytecode reads G['__builtins_dict___0']['len'] loaded = AOTCompiledFunction.deserialize(data) # default path real = builtins.isinstance builtins.isinstance = lambda o, t: real(o, t) # behaviorally identical wrapper loaded.guard_check(x) # parent: True (ID_MATCH against the frozen copy, which still holds the old object) # now: False (the scope holds builtins.__dict__ itself, so the rebind is seen) ``` A kept guard that cannot fail is the whole bug: the artifact stops noticing the one change it was kept to detect, on the ORDINARY load. So the key is re-derived when, and only when, the value bound there `is` the artifact's own recording (`runtime_env.used_globals.get(builtins_key)`, compared by identity). Any other binding, a caller's copy of the real builtins included, is a value this process chose and stays: ```python scope = {builtins_key: dict(builtins.__dict__)} loaded = AOTCompiledFunction.deserialize(data, guard_globals=scope) scope[builtins_key] is builtins.__dict__ # False: the caller's dict is kept "__builtins__" in scope # False: nothing extra was written ``` `test_load_rederives_a_builtins_key_bound_to_its_own_snapshot` pins both arms on an artifact whose bytecode really reads the key (it asserts the key is in `bytecode.co_names` and in `used_globals` before it goes near a load). Two consequences of the re-derive, both deliberate. First, `__builtins__` is seeded with the live `builtins.__dict__` rather than a copy, for the same identity reason: seeding `builtins.__dict__.copy()` leaves `guard_check` True after the `isinstance` rebind (measured). That branch fires only when the scope has no `__builtins__` at all, which a real module namespace always has (CPython binds it to `builtins.__dict__` itself); the scope that lacks it is `fn.__globals__`, a plain dict literal from `forward_callable`. The `builtins.__dict__.copy()` in `GuardBuilder.__init__` is not a precedent: it copies so the torch.package loop below it can write demangled module names without touching real builtins. Second, the recording was filtered for picklability alone, never narrowed to what this process has, so a builtin the tracing process had and the loading one lacks stops being readable: with a kept guard on that name the load says so, ``KeyError on G['__builtins_dict___0']['aot_probe']`` out of `guard_check`, and with that guard filtered out the read raises `KeyError` from the generated bytecode. `test_load_rederives_over_a_builtin_the_loading_process_lacks` pins both arms. Binding a dict that merges the recording over live builtins would satisfy both readers on paper and is the frozen-snapshot bug again for every shared name (measured: it takes `guard_check` after the rebind back to True). The seeding runs AFTER `forward_callable` on purpose: `PyFunction_New` caches `__builtins__` at creation, so writing `__builtins__` afterwards cannot rewire what the compiled bytecode resolves against (measured on 3.12: rebinding after creation is inert, binding before creation decides the lookup). The builtins KEY is the exception, and deliberately so: it is an ordinary global that `LOAD_GLOBAL` resolves live on every call, so the re-derive also decides what the generated bytecode subscripts, and it can only fire when that bytecode reads the key, since that read is what makes `get_runtime_env` record the copy. ## `guard_globals=`: a caller-controlled guard scope `deserialize` grows a keyword-only parameter whose semantics differ from `f_globals`: ```python # f_globals is MERGED over the scope rebuilt from the artifact: a name it omits # still resolves to the baked-in value. AOTCompiledFunction.deserialize(data, f_globals={"EPS": 1e-3}) # guard_globals REPLACES the guard scope, no fallback. A missing name fails the # guard, and an EMPTY dict is an empty scope rather than "no scope". loaded = AOTCompiledFunction.deserialize(data, guard_globals={}) loaded(x) # RuntimeError: KeyError on G['EPS'] (for an artifact whose kept guard reads EPS) # The load WRITES its seeds into the dict passed, so pass the one they should land in. scope = {"__name__": "fresh_module"} loaded = AOTCompiledFunction.deserialize(data, guard_globals=scope) builtins_key in scope, "__builtins__" in scope # (True, True) when a kept guard reads them ``` In practice the caller hands over the live namespace that defines those globals, not a hand-built dict: ```python # deployment process, in the module that binds EPS / USE_FUSED / FREQS loaded = AOTCompiledFunction.deserialize(data, guard_globals=sys.modules[__name__].__dict__) loaded(x) # refuses: the kept guard on EPS reads 1e-3 here, the graph was built for 1e-5 ``` The guards check what that module binds NOW, on every call, so a later rebind of `USE_FUSED` is caught too. The load seeds the synthetic `__import_*` and `__builtins_dict___N` names into that module dict on the caller's behalf, which is the case the per-name gating and `CleanupHook.disown` below exist for: a real namespace is being written to. A hand-built dict works as well, and an omission is loud rather than silent: ```python scope = {"EPS": EPS, "USE_FUSED": USE_FUSED} # forgot FREQS loaded = AOTCompiledFunction.deserialize(data, guard_globals=scope) loaded(x) # RuntimeError: ... KeyError on G['FREQS'] ``` There is no fallback to the baked-in value, so the failure names the missing global and the fix is adding the key; the synthetic names are never the caller's to add. Passing nothing leaves a kept global guard vacuous: the default guard scope is the reconstructed `fn.__globals__`, which holds the values recorded at trace time, so the guard compares the recording to itself. A failed guard is a refusal, since `aot_compile` has no recompile path, and that is the correct outcome: `EPS` is a constant inside the graph, so no scope can make the loaded artifact compute with `1e-3`; the artifact was built for a different configuration and says so. `f_globals` is not the tool for this: it changes what the bytecode reads and is merged into the default guard scope, so it can fail a guard but cannot change a baked constant. `torch.compiler.load_compiled_function` does not forward `guard_globals` yet, so today it is reachable only through `AOTCompiledFunction.deserialize`; the public plumbing is left for a follow-up (see the FAQ). It is held by reference and never merged into `fn.__globals__`, so a caller-supplied scope cannot rewire what the compiled bytecode reads. The load refuses a `guard_globals`/`f_globals` whose `__builtins__` is neither a dict nor a module, naming the parameter it arrived by and the offending TYPE: ```python AOTCompiledFunction.deserialize(data, guard_globals={"__builtins__": None}) # TypeError: guard_globals['__builtins__'] must be a dict or a module, got NoneType ``` The parameter name is conditional because `f_globals` is merged into `fn.__globals__` before the function is built, so the default scope can carry a bad binding too; the value is not printed because a repr on a load failure path runs user code. The check needs only `guard_scope.get("__builtins__")`, so it is hoisted above the alias writes and above `disown`, and runs whenever a kept guard roots at the key rather than only when the key is about to be derived. Otherwise a refused load has already bound every guarded alias into the caller's dict and stripped a live compile's ownership of the key, and a caller who pre-binds the key alongside a bad `__builtins__` loads successfully. The last arm of `test_load_refuses_a_non_dict_builtins_binding` pins both against a scope where a `CleanupHook` owns the key. ## Three places still resolved `G` against the serialized snapshot Re-rooting the guards at a caller's dict exposed three sinks that were not reading the runtime scope. **A falsy scope was "no scope".** `GuardBuilder.__init__` took `runtime_global_scope or global_scope`, so `guard_globals={}` was silently replaced by the globals serialized with the artifact, the baked-in resolution this path exists to forbid, and whether that happened depended on whether the seeding above had made the dict truthy. It now tests `is None`, which is what "no scope supplied" always meant: the eager path passes `None` and is unchanged, and `CompilePackage.install()` passes `sys.modules[...].__dict__`, which is never empty. `load_guard_manager` says so at its own signature, since it is the sink that receives the choice. `test_load_into_an_empty_scope_refuses_a_lifted_global` pins it: an artifact whose kept guard reads a global the graph LIFTED, loaded with `guard_globals={}`, has to refuse on `KeyError on G['EPS']`. The old fallback holds a FakeTensor for that global, so its `TENSOR_MATCH` fails on the type instead, which the regex also rejects; the fallback answers on a baked-in value only for a specialized global the serializer kept a real value for, which is the `AOT_POOL_MODE` arm of `test_load_seeds_no_name_no_guard_is_rooted_at`. **Python lambda shape guards.** A `SHAPE_ENV` guard roots at a `ShapeEnvSource`, which is not global, so the default filter KEEPS it, and with `enable_cpp_symbolic_shape_guards` off (the default) it installs as one Python lambda over its code parts, which carry a literal `G['NAME']` for a global with a dynamic dim. `add_python_lambda_leaf_guard_to_root` exec'd that lambda over the SERIALIZED `global_scope`, so it never saw `runtime_global_scope`: ```python # default filter: the global is pruned from the serialized scope, so nothing names it loaded(x) # KeyError on 'AOT_DYN_ROWS' on EVERY load, the default one included # kept global guard: the serialized scope holds a FakeTensor with the TRACED sizes loaded.guard_check(torch.randn(4, 5)) # passed against a traced (4, 3), whatever the caller's dict held ``` The lambda now closes over `runtime_global_scope`, the dict the C++ tree is rooted at; on the eager path that is `global_scope` itself, so nothing there changes. `CompilePackage.install()` gets the same fix through the same line, and there it is the silent arm: a package keeps every guard, so a shape constraint on a dynamic-dim module-level global was checked against the pickled FakeTensor and passed whatever the module bound. A one-row global was served the graph built for `2 <= rows` (measured under `fail_on_recompile`); the fix turns that stale hit into a recompile. `test_installed_shape_guard_on_a_global_reads_the_live_module_dict` pins that half through `DiskDynamoStore` save/load and `install()`, anchored on `verbose_code_parts=["2 <= G['PKG_DYN_ROWS']` because the stance message prints the whole guard tree before the parts that failed. Both arms rebind the global to a fresh tensor because the loaded `TENSOR_MATCH` rejects the marked original: the pickled FakeTensor carries no `_dynamo_dynamic_indices`, so the load guards `hasattr(G['PKG_DYN_ROWS'], '_dynamo_dynamic_indices') == False`. `test_load_resolves_a_python_shape_guard_against_the_guard_scope` pins the default-filter case and `test_load_python_shape_guard_cannot_pass_on_the_serialized_scope` the silent arm; on the parent the first fails its default load with `GuardManager check failed ... ["'AOT_DYN_ROWS'"]` and the second with `RuntimeError not raised`. **Fail reasons.** `guard_manager.global_scope` is the dict `get_guard_fail_reason_helper`, `recompilation_reason_for_no_tensor_aliasing_guard` and `guard_error_hook` evaluate failed code parts against. None is reachable from a loaded artifact today (the first two run over eager `cache_entries` and the `skip_guards_check=True` sanity check a deserialized state disables; the hook fires from `lookup_in_list` while precompile entries go through `run_root_guard_manager`), so leaving it on the serialized dict was a latent split rather than a live bug. But it was the one `G` that disagreed with both the lambda and the accessor tree, and wiring recompile reasons to precompile entries would have reintroduced what this commit closes. It is re-pointed the same way; on the eager path `guard_manager.global_scope["G"] is fn.__globals__` before and after (measured). ## Interaction with a later compile in the same module Seeding a captured `__builtins_dict___N` into a live module dict puts a name in the way of a later compile in that module, whose `unique_id` counter is still behind and will regenerate it. The mint sites below this commit already skip forward past a name that is taken (`unique_id_unbound_in`), so that load-then-compile does not trip `CleanupHook.create`'s "already exists in scope" assertion. That sequence is pinned here rather than where the skip lands, since only this commit has a load that does the seeding: the `guard_reads_builtins` arm of `test_load_disowns_only_a_builtins_key_a_guard_reads` compiles again, under a rewound counter, in a module dict where the key is already bound by the earlier live compile and the load only disowned it. ## Review order Read the guard scope `__post_init__` chooses first, then `_seed_guard_scope`, then the `is None` test in `GuardBuilder.__init__` that lets an empty scope survive the trip, then the `G` a Python lambda guard closes over in `add_python_lambda_leaf_guard_to_root` and the one `guard_manager.global_scope` keeps for fail reasons, then the tests. `test_builtins_key_gate_covers_the_other_serializer_channels` runs with `assume_static_by_default=False` so the shape-env channel carries a GLOBAL-rooted source (`AOT_DUPE_A`), asserted alongside the dupe half; without the flag it fails `'AOT_DUPE_A' not found in set()`. The no-overwrite arms of `test_load_keeps_a_prebound_builtins_scope` and `test_load_rederives_a_builtins_key_bound_to_its_own_snapshot` pre-bind through a `CleanupHook` and fire it after the load, so a `_seed_guard_scope` that never runs on a caller scope fails them with `never disowned` / `the load replaced, or never disowned, the builtins dict it was handed` (checked by mutation). Test Plan: ``` python test/dynamo/test_aot_compile.py python test/dynamo/test_package.py python test/dynamo/test_guard_serialization.py python test/dynamo/test_aot_compile.py -k test_load_resolves_a_python_shape_guard_against_the_guard_scope python test/dynamo/test_aot_compile.py -k test_load_python_shape_guard_cannot_pass_on_the_serialized_scope python test/dynamo/test_package.py -k test_installed_shape_guard_on_a_global_reads_the_live_module_dict python test/dynamo/test_misc.py -k recompil ``` The seeding-specific cases, individually: ``` python test/dynamo/test_aot_compile.py -k test_load_seeds_exactly_the_recorded_globals python test/dynamo/test_aot_compile.py -k test_kept_builtin_match_guard_reads_the_seeded_builtins_dict python test/dynamo/test_aot_compile.py -k test_load_seeds_no_name_no_guard_is_rooted_at python test/dynamo/test_aot_compile.py -k test_load_into_an_empty_scope_refuses_a_lifted_global python test/dynamo/test_aot_compile.py -k test_load_keeps_a_prebound_builtins_scope python test/dynamo/test_aot_compile.py -k test_load_rederives_a_builtins_key_bound_to_its_own_snapshot python test/dynamo/test_aot_compile.py -k test_load_rederives_over_a_builtin_the_loading_process_lacks python test/dynamo/test_aot_compile.py -k test_load_disowns_only_a_builtins_key_a_guard_reads python test/dynamo/test_aot_compile.py -k test_load_refuses_a_non_dict_builtins_binding python test/dynamo/test_aot_compile.py -k test_builtins_key_gate_covers_the_other_serializer_channels ``` The live-builtins requirement was checked by mutation: replacing `builtins.__dict__` with `builtins.__dict__.copy()` in `_seed_guard_scope` fails `test_kept_builtin_match_guard_reads_the_seeded_builtins_dict` with `AssertionError: False is not true : seeded a snapshot instead of the live builtins dict` on the identity assertion, before the post-rebind `guard_check` is reached. The re-derive gate was checked the same way, in both directions, against `test_load_rederives_a_builtins_key_bound_to_its_own_snapshot`. Restoring the old `if builtins_key not in guard_scope` bail fails its first arm with `AssertionError: False is not true : the load left its own pickled builtins snapshot in the guard scope`, the scope having kept the recorded copy. Dropping the snapshot-identity half of the gate, so that the key is re-derived whenever a guard reads it, fails its second arm with `AssertionError: False is not true : the derive replaced a builtins dict the loading process chose`, and takes `test_load_keeps_a_prebound_builtins_scope` down with it. The new case was checked the same way: restoring the old `if builtins_key in guard_scope` bail, and re-deriving to a dict that merges the recording over live builtins, both fail it with `AssertionError: False is not true : the load left its own recording under the builtins key`. ``` lintrunner --take RUFF,PYFMT torch/_dynamo/aot_compile.py torch/_dynamo/guards.py test/dynamo/test_aot_compile.py test/dynamo/test_package.py lintrunner --take PYREFLY torch/_dynamo/aot_compile.py torch/_dynamo/guards.py ``` Authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]> ## FAQ > FAQ: a load seeds `__import_*` aliases into a module dict, but > `CompilePackage.uninstall()` pops every alias `install()` recorded -- can a > package cycle in that module delete an alias this load seeded? It can, and the > loaded artifact's alias-rooted guard then fails loudly with `KeyError on > G['__import_...']`. The deletion itself is pre-existing behaviour of > install/uninstall rather than something this commit introduces: an alias a > plain in-process trace writes into that module dict (`symbolic_convert.py`, no > `CleanupHook`) is popped by the same cycle; there the next call recompiles and > rewrites the alias, so the failure does not surface. > FAQ: `import_sources` can record a `<torch_package_0>.mod` module name whose > alias carries no `__import_` prefix, and `_seed_guard_scope` hands it to > `importlib.import_module`. Is that new? No. > `GraphRuntimeEnv.forward_callable` and `CompilePackage.install()` already > `importlib.import_module` every recorded `import_sources` entry on every load, > so the seeding adds no reachable failure the base does not already have. > **FAQ: `guard_globals` has no public plumbing -- `torch.compiler.load_compiled_function` forwards only `f_globals` and `external_data`, so `_guard_globals` is always `None` in-tree and the alias-seeding loop is dead code. Plumb it through in this PR or split the alias half out.** Correct about this commit and answered by the next one. At this commit `torch/compiler/__init__.py:1014` reads `return AOTCompiledFunction.deserialize(data, f_globals, external_data)`; at the very next commit in the stack (#196815, "Re-root a loaded function's global guards at the live scope") the same call site reads `AOTCompiledFunction.deserialize(data, f_globals, external_data, guard_globals=f_globals)`. Splitting the sink from the caller that fills it is deliberate: this commit is the one that has to argue what gets seeded and why each name is gated, and #196815 is the one that has to argue that `f_globals` is the right dict to re-root at. Reviewing them as one diff would mix those two arguments. Note also that the alias loop being a no-op on the DEFAULT path is not the same as it being dead: `forward_callable` does import every recorded alias into `fn.__globals__`, which is exactly why the loop is gated on `alias not in guard_scope` rather than unconditional, and the builtins half of the method is live on the default path today. > **FAQ: no subprocess coverage for the scenario the PR is about -- all six new tests are in-process, and `_run_in_subprocess` already exists in this file. Add at least one save-in-parent / load-in-child test.** Agreed, and it is the commit two positions further up: #196821, "Cover import-alias seeding and a post-load mint collision, across processes", whose diff adds three `_run_in_subprocess` call sites to `test/dynamo/test_aot_compile.py`. The cross-process test needs the `guard_globals=f_globals` plumbing from #196815 to have a public loader worth spawning a child around, so it sits above that commit rather than here. The in-process tests here are not a substitute for it and are not claimed to be: they pin the gating decisions (which names are written, which are left alone, empty scope vs no scope, and the `CleanupHook` ownership handoff), which is what this commit is responsible for. > **FAQ: `guard_scope["__builtins__"] = builtins.__dict__` installs the live builtins dict where `GuardBuilder.__init__` uses `builtins.__dict__.copy()`; a copy would be strictly safer and matches the neighbouring code.** A copy is not safer here, it is silently wrong, and it now has a test. The kept guard rooted at the seeded key is an ID_MATCH on a builtin -- measured code list `___check_obj_id(G['__builtins_dict___0']['isinstance'], 139967305648704)` -- and `get_builtins_dict` hands back whatever object `__builtins__` holds without copying, so a snapshot freezes the identities the guard compares against. Measured both ways on the same artifact: with the live dict, `guard_check(x)` is `True` before rebinding `builtins.isinstance` and `False` after; with `builtins.__dict__.copy()` it is `True` before and still `True` after. A guard that should have missed keeps passing. `test_kept_builtin_match_guard_reads_the_seeded_builtins_dict` now pins this, and the copy makes it fail on its identity assertion with `AssertionError: False is not true : seeded a snapshot instead of the live builtins dict`. A caller who pre-binds `__builtins__` to a copy is choosing the other side of that trade, knowingly: measured, the key then derives from the copy, `guard_check` stays True after `builtins.isinstance` is rebound, and flips to False when `isinstance` is rebound inside the copy -- the guard watches the dict the caller said it should. > > The safety concern also does not apply to the case it describes. The branch only fires when the scope has no `__builtins__` at all, and CPython already binds a module namespace's `__builtins__` to `builtins.__dict__` itself -- measured `is builtins.__dict__ == True` for both `sys.modules["torch"].__dict__` and `sys.modules["torch.nn"].__dict__` -- so a user module namespace never reaches this line, and if it did there would be nothing new to write. The scope that does reach it is `fn.__globals__`, which `forward_callable` builds as a plain dict literal (`f_globals = {**import_sources, **self.used_globals, ..., backend_id: compiled_fn}`) and which consequently has no `__builtins__`. Finally, `GuardBuilder.__init__:1365` is not a precedent in the other direction: it copies precisely so that the `torch.package` loop on the next lines can write demangled module names into `self.scope["__builtins__"]` without mutating real builtins. That dict is mutated; this one is only read through by a guard. > **FAQ: the load-time gate at `aot_compile.py:549-575` is a second, narrower copy of the serializer's source enumeration (`guards.py:5161-5173` plus `additional_used_global_vars` from `DUPLICATE_INPUT` at `guards.py:3271-3272`), with nothing to catch drift. Serialize `used_builtin_vars` onto `OutputGraphGuardsState` instead, or factor out a shared helper.** The narrower walk is correct today and I verified the two extra channels cannot reach the builtins key: `shape_env_sources` is substituted only for a `ShapeEnvSource` originating source, whose own `get_global_source_name` is `None`, and `additional_used_global_vars` is fed from `get_global_source_name(source_b)`, and `source_b` CAN be a global -- the pinning test's own `DUPLICATE_INPUT` has `source_b = GlobalSource('AOT_DUPE_A')` -- but never the builtins key: `load_builtin_from_argval` in `symbolic_convert.py` is the only place a source rooted at that key is minted at all. The drift risk you describe is nonetheless real -- nothing fails if a future guard type adds a third channel -- and I am declining the fix here rather than disputing it. Serializing `used_builtin_vars` changes what `OutputGraphGuardsState` carries, which is capture-side serialization shared by `CompilePackage` and every existing artifact, so it is a schema change with a compatibility story of its own; landing it inside a commit whose subject is load-time seeding would bury it. The natural place is a follow-up that adds the field on the capture side and then simplifies this gate to read it, at which point the shared-helper option disappears because there is no second walk left to share. > **FAQ: seeded names have no cleanup path -- `CompilePackage._install_global` records each name in `_installed_globals` and `uninstall()` pops them, but names seeded here outlive the loaded artifact permanently. Record them so a caller can undo them.** Declined because there is no undo to hook them to. `AOTCompiledFunction`'s entire method surface is `prepare_f_locals`, `guard_check`, `__post_init__`, `_seed_guard_scope`, `__call__`, `source_info`, `save_compiled_function`, `serialize`, `deserialize`, `disable_guard_check` -- there is no `uninstall`, no teardown, and no lifetime object for a seeded-name list to belong to, so recording the names would add a field with no reader and no test that could pin anything beyond the list's own contents. The asymmetry with `CompilePackage` is that it owns an install/uninstall pair; this load does not. On the default path there is also nothing to leak: the seeded names go into `fn.__globals__`, a dict `forward_callable` constructs for that one artifact, not into any pre-existing namespace. The caller-supplied path writes into a dict the caller built and holds -- measured at 2 names for a `keep_builtin_guards` artifact, `['__builtins__', '__builtins_dict___0']` -- and the per-name gate exists so that number stays at what a kept guard actually reads. If `AOTCompiledFunction` grows an uninstall, the list should be added with it. > **FAQ: `guards_state: Any` at `aot_compile.py:515` silences checking on the four fields this method's correctness depends on; since only `guards_state.output_graph` is used, take `OutputGraphGuardsState` directly.** The `Any` is already gone -- the parameter itself is gone (`aot_compile.py:519-521`) -- but the second half of the suggestion was worth taking, so `_seed_guard_scope` now takes `output_graph: "OutputGraphGuardsState"` and `__post_init__` passes `guards_state.output_graph`, which also drops the local rebind inside the method. Confirmed the annotation is load-bearing rather than decorative: renaming `output_graph.global_scope` to a nonexistent attribute makes PYREFLY report ``Object of class `OutputGraphGuardsState` has no attribute `no_such_field_xyz` ``, and `lintrunner --take PYREFLY torch/_dynamo/aot_compile.py` is clean as written. > **FAQ: the `_guard_globals` field comment describes a separation the default path does not have -- on that path `guard_scope` IS `self.fn.__globals__`, so `_seed_guard_scope` writes into the dict the compiled bytecode executes against.** Confirmed and reworded. `__post_init__` does `guard_scope = self._guard_globals; if guard_scope is None: guard_scope = self.fn.__globals__`, so with no caller-supplied scope the seeding writes straight into the function's runtime globals. The comment now states that what a caller supplies is never merged into `fn.__globals__` -- which is the part that is true unconditionally -- and says explicitly that left `None` the guards resolve against `fn.__globals__` itself and are seeded into it. > **FAQ: `_seed_guard_scope` is roughly 33 comment lines for 20 lines of code, plus a 19-line `deserialize` docstring; keep the load-bearing invariants and move the rest to the commit message.** Trimmed against the revision reviewed, though later rounds folded more in: at this commit the method carries 39 comment lines over 33 of code (`:519-603`) and the `deserialize` docstring is 12 lines. Kept: why seeding is needed at all, why each name is gated individually, why an existing binding is left alone, why the pruned `global_scope` gates the aliases but cannot gate the builtins key, why `disown` runs even when the value is left alone, and why `__builtins__` can be absent. Dropped from the code and already present in the commit message: the enumeration of the serializer's two extra source channels, the `install()`-divergence contrast, and the `f_globals`-versus-`guard_globals` restatement in the docstring. One thing went the other way -- the reason the builtins dict must be the live one and not a snapshot is now a comment as well as a message paragraph, because it is the invariant a future reader is most likely to "fix". > **FAQ: `AOTCompiledModel.deserialize` has no `guard_globals` plumbing, and > it is the loader most likely to hit the `KeyError` this PR fixes -- the > failure in the description is `nn.Module`-shaped, `aot_compile.py:937` calls > `AOTCompiledFunction.deserialize(result)` with no kwargs, #196815 does not > touch that call, and the module-level test routes around the gap by calling > the function loader directly. Confirm the module path is tracked in this > stack, and say in the test why it bypasses the module loader.** Tracked, and > it is #196818, "Resolve a loaded module's guard scope from `model.forward`", > three commits above this one. That commit adds the keyword-only > `guard_globals` to `AOTCompiledModel.deserialize` and forwards it into every > `AOTCompiledFunction.deserialize` call in the `compiled_results` loop, > together with `bytecode_reads_guard_scope=True` and > `forward_not_resolved_reason=`; the supporting symbols are > `_resolve_guard_scope`, `_unwrap_optimized_module`, and the > `_has_global_guards` / `_bytecode_reads_guard_scope` fields on > `AOTCompiledFunction` that arm the live-value pick. > > It deliberately does more than the keyword you propose, because the keyword > alone would leave the public path unfixed: `_load_aot_compiled_module` > (`eval_frame.py:614`) passes no kwargs and #196818 leaves it untouched. > Instead `deserialize` resolves the scope itself, from the `__globals__` of > the function `model.forward` resolves to -- `model.forward` rather than > `get_traced_fn(model)`, which returns `Module._wrapped_call_impl` and so > `nn.Module`'s namespace as soon as a hook is registered -- so the only > public way in is fixed with no caller change at all. Its fifteen new tests, > `test_aot_compile_module_dispatches_on_global_guard` through > `test_aot_compile_module_deserialize_takes_a_guard_globals_scope`, drive > `AOTCompiledModel.deserialize` itself rather than around it. > > Splitting it that way is deliberate. This commit has to argue what gets > seeded and why each name is gated one at a time; #196818 has to argue which > dict a module artifact's guards should resolve against, that a passing guard > is the only thing that licenses serving the graph a live value, and the > `OptimizedModule` unwrap -- and it needs #196815's function-side > `guard_globals` in place before there is a scope for it to forward. As one > diff those arguments would be read as one. > > The comment you ask for is already in the test: > `test_load_seeds_exactly_the_recorded_globals` says "Deliberately around > `AOTCompiledModel.deserialize`: it takes no guard scope at this commit, so > the function loader is the only place a caller-supplied one can be pinned", > and names resolving a module artifact's scope from `model.forward` as where > that changes. > **FAQ: the builtins-key re-derive rewires what the compiled BYTECODE resolves, not > just what the guards resolve, and it fires only in the case where the generated > bytecode reads that key -- so a builtin the loading process lacks becomes a bare > `KeyError` from inside the bytecode after `guard_check` already passed, while two > comments in the method say the seeding cannot decide bytecode resolution. Correct > the comments, or validate that live builtins covers every name the bytecode reads > before swapping.** The mechanism is right and the comments now say so; the > validation is declined. Neither cited comment actually claimed inertness -- the > `_guard_globals` field comment scopes its claim to "a caller-supplied one", and > the ordering comment to "the `__builtins__` written below", which is the only name > `PyFunction_New` caches -- but nothing said the builtins KEY is different, so the > ordering comment now adds "The builtins-dict key below is an ordinary global and > does; see there", and the re-derive comment states that it decides what the > bytecode subscripts and what that costs. Measured, on an artifact whose bytecode > really reads the key (`LOAD_GLOBAL __builtins_dict___0; LOAD_CONST 'aot_probe'; > BINARY_SUBSCR`) with the probe builtin deleted before the load: with the guard on > that name kept, `guard_check` is False and the failure names it -- `KeyError on > G['__builtins_dict___0']['aot_probe']`; with only the `isinstance` guard kept, > `guard_check` is True and the call raises `KeyError: 'aot_probe'`. Both arms are > now pinned by `test_load_rederives_over_a_builtin_the_loading_process_lacks`, and > both succeed at the parent commit, which is where that test fails. > > The validation is declined because nothing records the names the bytecode > subscripts out of the key: `external_refs` records the key alone, and > `used_globals[key]` is the entire picklable-filtered builtins dict (measured 157 > entries, none of them missing from live builtins), so a check would either re-scan > generated bytecode for a `LOAD_GLOBAL`/`LOAD_CONST`/`BINARY_SUBSCR` triple -- > codegen- and opcode-version-coupled -- or refuse loads over names nothing reads. > The tempting alternative of binding a dict that merges the recording over live > builtins is worse than either: measured, it takes `guard_check` after a > `builtins.isinstance` rebind from False back to True, i.e. it restores for every > shared name exactly the frozen-snapshot bug the re-derive was added to kill. And > the silent arm needs an artifact whose author kept a guard rooted at the builtins > key while filtering away the guard on a name the bytecode reads out of it: under > the DEFAULT filter the re-derive never runs at all (measured, the scope keeps the > recording), and with that guard kept the load already fails loudly and names the > missing entry. If it is worth converting into a load-time refusal, it belongs > where the read-name set is produced -- codegen / `get_runtime_env` -- not in > guard-scope seeding. > **FAQ: `test_load_seeds_exactly_the_recorded_globals` rebuilds the prefix filter inline over `("__import_", "__builtins_dict__")` (`test_aot_compile.py:2311-2315`) rather than `_MINTED_PREFIXES` (`test_aot_compile.py:77-84`); the two sets diverge both ways, so leaked `__compiled_fn` / `__resume_at` / `__comprehension_` / `__gen_rand_values` / `__warnings_warn_wrapper` names land in `base` and then in the `set(scope) - before` assertion at `test_aot_compile.py:2319`. Use `_MINTED_PREFIXES`.** Both halves are wrong, measured. `_MINTED_PREFIXES` has no `__import_` entry, so substituting it is not a tightening but a break: the leaked alias survives into `base`, the load then finds it already bound and seeds nothing, and the test fails with `AssertionError: Set comparison failed: Items in the second set but not the first: '__import_torch_dot_nn_dot_modules_dot_module'`. That is the reason the filter is inline rather than shared -- this test needs the aliases stripped, which is exactly what the shared tuple does not do, and widening `_MINTED_PREFIXES` to include `__import_` would change what every other user of it hides. The stated consequence is also unreachable: `base` is copied into `scope` before `before = set(scope)` is taken (`test_aot_compile.py:2316-2317`), so any name the inline tuple keeps and `_MINTED_PREFIXES` would have stripped is present on both sides of `set(scope) - before` and cancels out. Injecting three such leaks -- `__compiled_fn_999`, `__resume_at_999`, `__warnings_warn_wrapper_999` -- into this module's globals ahead of the filter leaves the test green (`Ran 1 test in 0.353s / OK`). The prefixes that matter to this assertion are the ones a load can seed, and those are the two the tuple lists. > **FAQ: the re-derive points the runtime key at FULL live builtins while any guard baked over that slot was baked from the `used_builtin_vars`-pruned sub-dict (`guards.py:5194-5201`); a whole-dict guard rooted at `G[builtins_key]` -- `DICT_KEYS_MATCH` / `SEQUENCE_LENGTH` -- would compare a pruned key set against the live dict and fail deterministically.** Measured, and the contrast is not between the pruned dict and something the re-derive introduced -- it is between the pruned dict and what the load already had before this commit. On the `keep_builtin_guards` artifact: the serialized `global_scope[builtins_key]` pruned to `used_builtin_vars` is 2 keys (`['isinstance', 'len']`), the recording `forward_callable` spreads into `fn.__globals__` is 157, and live `builtins.__dict__` is 157, with `recorded == live` True and `serialized == recorded` False. So a `DICT_KEYS_MATCH`/`SEQUENCE_LENGTH` baked over the 2-key serialized dict fails against the 157-key recording exactly as it fails against the 157-key live dict; as key sets those two are indistinguishable, and swapping one for the other cannot be what breaks such a guard. The guards this artifact actually keeps are `['ID_MATCH'] | DictGetItemSource(base=GlobalSource(global_name='__builtins_dict___0'), index='len')` and the same for `'isinstance'`, both by-reference identity, and `output_graph.guard_on_key_order` is empty -- and cannot name the key at all, since every site that fills it adds the source of a dict or set variable, which is why the gate no longer scans it. If a future guard type does bake a whole-dict comparison over a pruned slot, the bug is the pruning, and it is on the serializer side of the line, not here. > **FAQ: the re-derive is scoped to `guard_scope` alone while the snapshot it targets lives in `fn.__globals__`; on a caller-supplied scope the two are different dicts and the frozen snapshot survives in the bytecode's.** Correct, and fixed by #196904 at the top of this stack rather than here: the re-derive there iterates both dicts, deriving each from its own `__builtins__`, and flips the arm of `test_load_rederives_over_a_builtin_the_loading_process_lacks` that #196815 added to pin the split. It is a separate commit so this re-slice stays reviewable as the re-slice it is; the split is reachable here only through `deserialize(..., guard_globals=)` (no public caller supplies that dict until #196815), and only under a `guard_filter_fn` that keeps a builtins-rooted guard. > **FAQ: `runtime_global_scope` re-roots only the C++ `GlobalsGuardAccessor` tree; `add_python_lambda_leaf_guard_to_root` execs its guard over the serialized `G`, and the default filter keeps `SHAPE_ENV`, whose default form is that lambda -- so `guard_globals={}` silently passes a shape guard on a dynamic-dim global.** Right about the mechanism, and fixed: the lambda now closes over `runtime_global_scope`. The measured consequence was in two parts, neither quite the one described. Under the default filter the global is not in the serialized scope at all (`shape_env_sources` is filled from the cpp code parts alone, so the pruning drops it), and the lambda raised `KeyError` on EVERY load, the default one included -- `verbose_code_parts=["'AOT_DYN'"]` -- so that artifact was unusable rather than permissive. The silent pass needs a kept global guard, which is what puts the FakeTensor with the traced sizes into the scope; then a live `(4, 5)` tensor against a traced `(4, 3)` did pass `guard_check`, measured with `keep_global_guards` and `assume_static_by_default=False`. Both arms are pinned by `test_load_resolves_a_python_shape_guard_against_the_guard_scope` and `test_load_python_shape_guard_cannot_pass_on_the_serialized_scope`. `CompilePackage.install()` loads through the same `GuardBuilder`, so the one line closes its copy too, and `test_installed_shape_guard_on_a_global_reads_the_live_module_dict` pins that half in `test_package.py`. The third `G`, `guard_manager.global_scope`, is re-pointed at the runtime scope as well rather than left on the serialized dict: its readers are unreachable from a loaded artifact, but leaving it made the invariant two-of-three. > **FAQ: `_seed_guard_scope` runs before `load_guard_manager`, so a failure inside guard-manager construction leaves the caller's dict seeded and the `_cleanup_owners` token popped.** Accepted as the residual it is. Everything that can fail on the CALLER's input runs before the first write: `load_guards_state` (unpickling) runs first, and the `__builtins__` type refusal is hoisted above every write. What runs after is `load_guard_manager`, which reads only the deserialized guards and the serialized scope (`example_value=self.scope["G"]`) and holds the caller's dict by reference for check-time lookups (`globals_dict_manager(f_globals=...)`, and now the lambda's `G`), so a raise there is a malformed artifact, not a property of the dict handed in. > **FAQ: the refusal reads `guard_scope.get("__builtins__")`, while `f_globals` reaches `fn.__globals__` independently, so `deserialize(data, f_globals={"__builtins__": None}, guard_globals=good)` loads clean.** It does, measured -- and it also CALLS clean, because the generated bytecode reads builtins through the `__builtins_dict___N` global, not through `__builtins__`, so the bad binding is inert there. The refusal exists for the dict the GUARDS derive the builtins dict from, which is why it inspects that one; with no `guard_globals` the two dicts coincide and the same call refuses with `TypeError: f_globals['__builtins__'] must be a dict or a module, got NoneType`. #196815 forwards `f_globals` as `guard_globals` on the public path, so there the two cannot diverge. > **FAQ: `CompilePackage.install()` gets this behavior change through the same line and has no test for it -- `test_dynamic_shape` marks a LOCAL argument dynamic, so its shape sources root at `L['x']`, never at `G[...]`.** Added, and the package path is the silent arm rather than the KeyError one: a package keeps every guard, so the dynamic-dim global is in the serialized scope as a FakeTensor with the traced sizes, and measured through `DiskDynamoStore` save/load and `install()` under `fail_on_recompile`, a module global rebound to one row was SERVED the graph built for `2 <= rows` on the parent's lambda scope, and is refused with the fix. `test_installed_shape_guard_on_a_global_reads_the_live_module_dict` pins both arms -- a fresh seven-row global is served, a one-row one raises -- and fails on the parent with `RuntimeError not raised`. Its regex anchors on `verbose_code_parts=["2 <= G['PKG_DYN_ROWS']` because the stance message prints the whole guard tree first, LAMBDA_GUARD line included, so matching the lambda text alone would pass on a TENSOR_MATCH failure. Both arms rebind to fresh tensors rather than reusing the marked original because the loaded TENSOR_MATCH rejects it: `_dynamo_dynamic_indices` does not survive the pickled FakeTensor, so the load guards `hasattr(G['PKG_DYN_ROWS'], '_dynamo_dynamic_indices') == False` (measured: calling with the original after install is itself refused, by the C++ tree, on the fix and on the parent alike). > **FAQ: the two shape-guard regexes match the lambda's whole verbose list, not the failing constraint -- `LAMBDA_GUARD::check_verbose_nopybind` returns the entire list and `__call__` stringifies it -- so the comment "the failure has to name that guard" claims more than the assertion checks; and the `guard_globals={}` arm cannot distinguish the fix from the parent.** Both comments corrected; the assertion is kept. Asserting on `guard_manager.check_verbose(...)` parts directly would hand back the same whole list, so it buys no precision the regex lacks; what the regex does establish is the honest claim the comment now makes -- it tells a lambda that resolved the name and failed on the caller's tensor from one whose only part is the KeyError name, which is what the serialized scope produced on the parent (`["'AOT_DYN_ROWS'"]`). The empty-scope arm is now labelled what it is: a specification arm, since the name is absent from the serialized scope too and a lambda over either dict raises `KeyError` there; the default-load and one-row arms are the ones that separate the fix from the parent. > **FAQ: `guard_manager.global_scope` is still built from `builder.scope["G"]`, a third `G` channel that disagrees with the lambda and the accessor tree on a loaded artifact.** Re-pointed at `builder.runtime_global_scope`, since that removes the trap where a comment would only describe it. Its readers (`get_guard_fail_reason_helper`, `recompilation_reason_for_no_tensor_aliasing_guard`, `guard_error_hook`) are unreachable from a loaded artifact, so the change is inert there today, and on the eager path it is a no-op by identity: `builder.runtime_global_scope` IS `global_scope` when no runtime scope is passed, measured `guard_manager.global_scope["G"] is fn.__globals__` True before and after on an eager compile, and on a loaded artifact False before (the serialized dict) and True after. `test_aot_compile.py`, `test_package.py`, `test_guard_serialization.py` and `test_misc.py -k recompil` (18 tests) stay green. > **FAQ: [carried] the "LIVE builtins" comment in `_seed_guard_scope` is unconditional while the code uses `setdefault`.** The comment now carries the clause: the live dict is what this load binds when the scope has no `__builtins__`, and a caller who pre-binds one chooses the dict the guard watches -- the arm `test_load_keeps_a_prebound_builtins_scope` pins. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: https://github.com/pytorch/pytorch/pull/196817 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #196767
…cope (#196815) The parent commit (#196817) taught `AOTCompiledFunction.deserialize` to take a `guard_globals=` dict, hold it by reference, and resolve global guards against it instead of the scope rebuilt from the artifact. This commit wires the public loader to use it, by forwarding the one dict it already takes for both roles: ```python # torch/compiler/__init__.py, before return AOTCompiledFunction.deserialize(data, f_globals, external_data) # after return AOTCompiledFunction.deserialize(data, f_globals, external_data, guard_globals=f_globals) ``` Documenting the one dict was preferred to giving `load_compiled_function` a separate public `guard_globals=` parameter: a second scope argument is new public API for a distinction callers have no reason to draw, and the review asked only that the semantics be discoverable. ## What it fixes: a rebind after load was invisible `AOTCompiledFunction` built its guard manager against `self.fn.__globals__`, the scope reconstructed at load: the globals serialized at capture with any caller-supplied `f_globals` merged over them, once. So a value rebound BEFORE the load could fail its guard, but a rebind AFTER was seen by nothing, however the global was guarded: ```python # --- capture process, module mypkg.model --- POOL = "sum" def fn(x): return x.sum(1) if POOL == "sum" else x.mean(1) torch.compile(fn, fullgraph=True, backend="eager", options={"guard_filter_fn": keep_global_guards}).aot_compile(((x,), {})).save_compiled_function("fn.pt") # --- loading process --- import mypkg.model as m loaded = torch.compiler.load_compiled_function(open("fn.pt", "rb"), f_globals=vars(m)) loaded(x) # serves the "sum" graph m.POOL = "mean" loaded(x) # parent: still serves "sum" -- the guard checked a snapshot taken at load # now: RuntimeError: GuardManager check failed ... on the POOL guard ``` `test_aot_compile_fn_guards_track_rebound_global` pins it. ## `f_globals` is MERGED for the bytecode and REPLACES for the guards Supplying the same dict for both roles makes `f_globals` a complete live scope rather than a patch on top of the capture, and the two contracts are easy to conflate, so the docstring now spells both out: - **Bytecode: merged.** The compiled code does not read this dict at all. It reads `fn.__globals__`, a snapshot `GraphRuntimeEnv.forward_callable` builds at load out of the globals serialized with the artifact with `f_globals` merged over them by value. A name the dict omits still resolves there, and a name it binds is what the graph computes with whether or not a kept guard checks it. `test_load_compiled_function_f_globals_merges_for_the_bytecode` pins both halves; it needs no guard to be observable, since the default filter keeps none that would check the bound name, and says so, so it is not read as a regression test for the re-rooting it does not exercise. - **Guards: replaced.** A name the dict lacks fails the guard until that name is bound in the dict, with no fallback to the value serialized with the artifact. ## The behaviour change: a dict of a few extra names is no longer enough That narrows what an accepted `f_globals` may be. The old guide asked for it "when the original function references user-defined types or other non-standard globals", so callers passed a handful of names: ```python loaded = torch.compiler.load_compiled_function(f, f_globals={"MyConfig": MyConfig}) ``` Under the default filter nothing changes: it keeps no global guard, so a load cannot notice which dict they would have resolved against. For an artifact compiled with a `guard_filter_fn` that keeps a global guard, the dict was previously merged over the rebuilt scope and the guards still resolved against the serialized globals; the same call now resolves them against that small dict alone: ```python loaded(x) # RuntimeError: GuardManager check failed ... KeyError on G['POOL'] ``` Resolving guards against the live scope is the point of the change and the API is experimental, so the break stands rather than being papered over with a fallback that would defeat it. What a caller passes instead is the defining module's namespace, `vars(mod)`, which the guide's own example already used. The docstring and the guide now state that requirement, bind every global the kept guards read with values that satisfy them, and scope the `vars(mod)` advice to an artifact whose kept guards read a global. Under the default filter the dict does nothing for the guards and only widens what the bytecode merges over, unchecked, so they say to pass only the names the load cannot otherwise resolve. Both keep only what a caller can act on and stay off guard internals: that the load may insert names of its own is stated in each, while the literal minted name patterns and the per-name gating stay in the comment on `_seed_guard_scope`, and the merge/replace split stays in `deserialize`'s own docstring. That insertion is newly visible to public-API callers, because the dict being written into is now theirs rather than the one `forward_callable` built, so `test_load_compiled_function_f_globals_is_seeded_in_place` loads through `load_compiled_function` and pins the exact key set a load adds to a dict the caller owns. ## Guards and bytecode now read different dicts This is new for `load_compiled_function`, whose guard scope used to be `fn.__globals__` itself so the two could not disagree, and it is the one place a passing guard stops certifying the value the graph uses. The guards read `f_globals` live; the bytecode reads the load-time snapshot. A global rebound after the load is therefore seen by the guards and not by the graph: ```python FREQS = torch.randn(4, 8) # lifted as a graph input; TENSOR_MATCH guards metadata, not values loaded = torch.compiler.load_compiled_function(f, f_globals=vars(m)) m.FREQS = torch.randn(4, 8) # same metadata, different values loaded(x) # guard PASSES; computes with the FREQS the snapshot holds m.FREQS = torch.nn.Parameter(torch.randn(4, 8)) # same metadata, different type loaded(x) # RuntimeError: GuardManager check failed ... naming Tensor vs Parameter ``` Both ends are pinned: `test_load_compiled_function_f_globals_guard_checks_the_tensor_type` and `test_load_compiled_function_f_globals_accepted_rebind_is_not_used`. The docstring and the guide mark the second a known limitation rather than a contract to rely on. Two designs close the gap: root the guards for the names the bytecode reads (`runtime_env.used_globals`) at the snapshot, so a guard can never certify a value the graph will not use, or refresh those snapshot entries from the live dict after a check passes, so the rebind is honoured. Both change what a call dispatches to rather than only which dict the guards resolve against: the first re-introduces, for every global the graph lifted, exactly the baked-in resolution this commit removes, and the second makes a passing guard mutate the running graph's globals. The choice is left to a follow-up, which the accepted-rebind test will have to update either way. ## `{}` is an empty scope, not "no scope" Two spellings that were indistinguishable before now differ: ```python torch.compiler.load_compiled_function(f) # guards resolve against the artifact-rebuilt scope torch.compiler.load_compiled_function(f, f_globals={}) # guards resolve against an EMPTY live scope ``` The second fails every kept guard rooted at a global the load does not seed itself with `KeyError on G['NAME']`. The empty dict is left meaning an empty scope rather than normalized to "no scope" (`guard_globals=f_globals or None`) because the caller can recover from the failure and cannot from the alternative: ```python scope = {} loaded = torch.compiler.load_compiled_function(f, f_globals=scope) loaded(x) # KeyError on G['POOL'] scope["POOL"] = "sum" # the dict is held by reference loaded(x) # serves ``` That is what the scope hint the next commit adds tells them to do, while the rebuilt scope is not a dict any caller can reach. Normalizing would also make a dict live by reference only while it is non-empty, so a caller who loads first and populates after would keep getting the rebuilt scope with nothing raising to say so. The only in-tree caller passing an empty dict is the merge test above, which means "merge nothing" by it and answers the same either way. `test_load_compiled_function_empty_f_globals_is_an_empty_guard_scope` pins both spellings and the recovery. ## Two effects of forwarding one dict for both roles **The builtins re-derive lands in the caller's dict.** One of the names a load inserts is the Dynamo builtins dict. `_seed_guard_scope` writes the live builtins under that key into the guard scope, now the caller's dict, while `fn.__globals__` keeps the pickle-filtered copy `get_runtime_env` recorded at capture, because `forward_callable` copies the merged globals into it by value before the seeding runs. The guards read this process's builtins and the bytecode reads the capture's, so for one artifact the two load spellings answer differently: with no scope the re-derive lands in `fn.__globals__` and a builtin the capture had and this process lacks stops being readable, while through `load_compiled_function(f, f_globals=scope)` the same artifact serves off the recorded copy. Either spelling needs a `guard_filter_fn` that keeps a builtins-rooted guard to notice, and the divergence is reachable on the parent by calling `deserialize` with `guard_globals=` alone; what this commit changes is that the public spelling now takes that path. An arm on the parent's `test_load_rederives_over_a_builtin_the_loading_process_lacks` loads through `load_compiled_function` the artifact whose no-scope load raises `KeyError: 'aot_probe'` and pins it serving, with the live builtins in the caller's dict and the capture's recording still in `fn.__globals__`. **The `__builtins__` refusal named a parameter the caller could not reach.** `deserialize` refuses a `__builtins__` binding that is neither a dict nor a module and names the parameter the bad dict arrived by. On the parent, whether `guard_globals` had been supplied settled that, because nothing there set both. This commit sets both on every public call, so a caller of `load_compiled_function` passing `f_globals={"__builtins__": None}` was told to fix `guard_globals`, a parameter not in the signature they called: ```python arrived_as_f_globals = self._guard_globals is None or self._guard_globals is self._extra_globals param = "f_globals" if arrived_as_f_globals else "guard_globals" ``` The review's suggested predicate, the identity test alone, would have regressed the `f_globals`-only `deserialize` arm: there `_extra_globals` holds the dict and `_guard_globals` is `None`, so the two are not identical and that caller would start being pointed at `guard_globals`. The `is None` disjunct keeps that arm right, the identity disjunct fixes the public one, and a direct `deserialize` caller supplying only `guard_globals` is still told `guard_globals`. A third arm on `test_load_refuses_a_non_dict_builtins_binding` loads through `torch.compiler.load_compiled_function`, the only way to reach a dict that arrived by both routes. ## Symbolic-shape guards resolve their global operands in the same dict Both texts say what a `SHAPE_ENV` guard's global operands resolve against, and the answer is the same dict as every other guard's, in both forms the guard can take. The parent re-roots the Python lambda a `SHAPE_ENV` guard installs by default at `runtime_global_scope`, and an artifact captured under `enable_cpp_symbolic_shape_guards` builds its operand managers out of the C++ globals tree, which was rooted there already. Neither text promises which form to expect, because neither the config nor the C++ compile decides it on its own: an operand that is neither an int nor a float falls back to the lambda with the config on (`torch/_dynamo/guards.py:3622`), while a load whose compile raises `InvalidCxxCompiler` (`:3690`) installs no C++ guard and still resolves the operands out of the live scope, since the operand managers are built at `:3642-3645` before `CppCodeCache.load` at `:3686`. What a load reads is what the capture recorded (`:3457-3463`), and the config's only read in library code is `:3535`, in an else-branch a load never enters, so which form a guard takes is a property of the artifact and not of the load. The one thing the default filter changes is that a `SHAPE_ENV` guard is KEPT by it, `ShapeEnvSource` not being a global source, so a dynamic-dim global is the one case where the default filter leaves a guard reading a global, and both texts now say so where they said no kept guard does. `test_load_compiled_function_f_globals_governs_a_cpp_shape_guard` captures under that config, patched around the capture alone since the load never reads it, and pins the C++ end: with the name omitted from `f_globals` the call raises `KeyError on G['AOT_CPP_SHAPE_GLOBAL']`, and binding it in the dict the caller still holds makes the same call serve. It needs no compiler skip gate, because the operand managers are built before the C++ compile is attempted; replacing the load with the parent's `AOTCompiledFunction.deserialize(data, scope, None)` fails it with `AssertionError: RuntimeError not raised`. Because the tensor it marks dynamic is a module global, the test drops `mark_dynamic`'s marking off it in cleanup, so a later test on that global cannot inherit it. The Python-lambda end is pinned at the parent. ## Scope of the fix The fix is scoped to the supplied-scope path. A load that passes no `f_globals` still resolves global guards against the artifact-rebuilt scope, where a global the graph lifted is checked against the value serialized with it and one it did not lift is simply absent and fails the guard; the next commit makes that state explicit and says so when a guard fails. The NB added to the default `guard_filter_fn` records only what is not derivable at that call site: that dropping every global guard is deliberate rather than a gap, because narrowing it would need every load to supply a scope binding every global a kept guard reads. It does not call that filter `torch.compiler.skip_guard_on_globals_unsafe`'s behaviour, which it is not: that one is `[not entry.is_global for entry in guard_entries]`, while this one also drops a non-global guard whose type the serializer refuses, so a `CLOSURE_MATCH` on a local callable argument is dropped here and kept there. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_aot_compile_fn_guards_track_rebound_global python test/dynamo/test_aot_compile.py -k test_load_compiled_function_f_globals_guard_checks_the_tensor_type python test/dynamo/test_aot_compile.py -k test_load_compiled_function_f_globals_merges_for_the_bytecode python test/dynamo/test_aot_compile.py -k test_load_compiled_function_f_globals_is_seeded_in_place python test/dynamo/test_aot_compile.py -k test_load_compiled_function_f_globals_accepted_rebind_is_not_used python test/dynamo/test_aot_compile.py -k test_load_compiled_function_empty_f_globals_is_an_empty_guard_scope python test/dynamo/test_aot_compile.py -k test_load_compiled_function_f_globals_governs_a_cpp_shape_guard python test/dynamo/test_aot_compile.py -k test_load_refuses_a_non_dict_builtins_binding python test/dynamo/test_aot_compile.py ``` Each new test was checked against a mutation. Dropping the `guard_globals=` argument this commit adds (i.e. the parent's behaviour) fails `test_aot_compile_fn_guards_track_rebound_global`, `test_load_compiled_function_f_globals_guard_checks_the_tensor_type` and `test_load_compiled_function_f_globals_is_seeded_in_place`, and leaves `test_load_compiled_function_f_globals_merges_for_the_bytecode` and `test_load_compiled_function_f_globals_accepted_rebind_is_not_used` passing, as their comments say. Adding the second design above -- refreshing `self.fn.__globals__` from the guard scope after a passing check -- fails `test_load_compiled_function_f_globals_accepted_rebind_is_not_used`. Its kept-guard assertion was checked by prepending `TENSOR_MATCH` to `CheckFunctionManager.UNSUPPORTED_SERIALIZATION_GUARD_TYPES`, which fails it with `AssertionError: False is not true`. Both ways of collapsing the two spellings fail `test_load_compiled_function_empty_f_globals_is_an_empty_guard_scope`: passing `guard_globals=f_globals or None`, and dropping `guard_globals=` altogether. The third arm added to `test_load_refuses_a_non_dict_builtins_binding` was checked the same way. Restoring the parent's predicate, ``` param = "f_globals" if self._guard_globals is None else "guard_globals" ``` fails it with `"f_globals\['__builtins__'\] must be a dict or a module, got NoneType" does not match "guard_globals['__builtins__'] must be a dict or a module, got NoneType"`, which is the public-API caller being pointed at a parameter it never passed. The second arm, which calls `deserialize` with `f_globals=` alone, is the one the identity-only predicate would have flipped the same way. Authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]> ## FAQ > **FAQ: Why not root the guards at the load-time snapshot, or refresh the > snapshot after a guard passes?** Both change what a call dispatches to, not just > which dict the guards read, and this PR is a re-slice of an existing change > rather than a redesign of it. The divergence is real and is now stated in the > docstring, the guide and the commit message: the guards read the caller's > `f_globals` live, while the compiled bytecode reads the snapshot > `GraphRuntimeEnv.forward_callable` builds at load time (the globals serialized > with the artifact, with `f_globals` merged over them), so a global rebound after > the load is seen by the guards and not by the graph -- the call raises > `GuardManager check failed` if the new value fails its guard, and serves the > load-time value if it passes. A kept `TENSOR_MATCH` checks metadata, not values, > so rebinding a guarded tensor global to one whose metadata matches -- its exact > Python type, which it compares first, plus dtype, shape, strides, device index, > `requires_grad` and its whole dispatch key set, which carries more than the > device: the layout, and bits such as conjugation -- keeps computing with the > tensor the load snapshotted, while any difference it records fails the guard > instead, naming the property that differed (an `nn.Parameter` substituted for a > plain tensor of identical metadata fails on the type comparison, which a test > pins; a CPU tensor rebound to `value.to('meta')` fails on the dispatch key set > while its device index, `None` on both, matches). Rooting the guards for > `runtime_env.used_globals` at that snapshot would re-introduce, for every global > the graph lifted, exactly the baked-in resolution this PR removes; refreshing > those snapshot entries after a passing check would make a guard evaluation > mutate the running graph's globals. Either is a dispatch-semantics change that > deserves its own PR and its own tests, so this one documents the divergence and > leaves the choice to a follow-up. That follow-up is #196897, higher in this > stack: it re-reads the guarded names into `fn.__globals__` before every call. > **FAQ: Why do the public docs still describe a merge over the whole `f_globals` > dict when #196818 narrows the substitution to the guarded names?** Because they > document a different path. `load_compiled_function` passes `f_globals` as > `_extra_globals` with `_bytecode_reads_guard_scope=False`, so the FUNCTION path > merges the whole dict both before and after #196818; the per-name narrowing > applies to the MODULE path's guard scope. The sentence corrected here describes > the contract that path actually has -- a snapshot of the serialized globals with > `f_globals` merged over them, so an omitted name still resolves and a bound one > overrides unguarded -- rather than a narrowing the function path never gets. > **FAQ: A passing guard no longer certifies the value the graph runs with. Why > is that documented as a known limitation instead of being fixed here?** > > The hazard is real and it is now pinned by a test. Measured through the public > entry point on this commit: compile `x * EPS` with a `guard_filter_fn` that > keeps global guards, save, `load_compiled_function(f, f_globals={"EPS": > tensor(1e-7)})`, then rebind `scope["EPS"] = torch.tensor(5.0)` -- same type, > dtype, shape, strides and `requires_grad`. The kept `TENSOR_MATCH` ACCEPTS the > rebind (no `GuardManager check failed`) and the call still returns `x * 1e-7`, > the value the load snapshotted. That is what > `test_load_compiled_function_f_globals_accepted_rebind_is_not_used` asserts. > > It is not fixed in this commit because both available fixes change what a call > dispatches to, not just which dict the guards read. Re-rooting the guards for > `runtime_env.used_globals` at the snapshot re-introduces, for every global the > graph lifted, exactly the baked-in resolution this commit removes -- the > rebind stops being visible at all, which is the parent's behaviour. Refreshing > those snapshot entries after a passing check makes a guard evaluation mutate > the running graph's globals. Choosing between them is a design decision that > wants its own PR and its own review; folding it into a change that is > otherwise a docstring and one line would hide it. The docstring and the guide > therefore call the divergence a known limitation rather than a contract to > rely on, and the test above is the thing that forces the follow-up to be > explicit: implementing the refresh design makes it fail (verified by applying > that mutation), so whichever fix lands has to update it. #196897, higher in > this stack, is that fix, and it renames and flips the test. > **FAQ: `test_load_compiled_function_f_globals_accepted_rebind_is_not_used` > and `test_load_compiled_function_f_globals_merges_for_the_bytecode` pass on > the parent commit. Are they dead tests?** > > They pass on the parent by design and both say so in their own comments. Their > subject is the half of the `f_globals` contract this commit does NOT change: > the bytecode reads a load-time snapshot of the serialized globals with > `f_globals` merged over them. Verified by dropping the `guard_globals=` > argument this commit adds and re-running the five tests: the three that pin > the re-rooting -- `test_aot_compile_fn_guards_track_rebound_global`, > `test_load_compiled_function_f_globals_guard_checks_the_tensor_type`, > `test_load_compiled_function_f_globals_is_seeded_in_place` -- fail, and these > two pass. Each is still load-bearing against a mutation of the code it > describes: refreshing `self.fn.__globals__` from the guard scope after a > passing check fails the accepted-rebind test, which is exactly the follow-up > design it exists to catch. > **FAQ: Should `f_globals={}` be normalized to "no guard scope", so that it > stays indistinguishable from omitting the argument?** Measured on an artifact > with a kept global guard: omitting the argument serves the graph, and > `f_globals={}` loads fine and then raises `GuardManager check failed, reason: > ... verbose_code_parts=["KeyError on G['EPS']"]` on every call. That > difference is kept and documented rather than normalized away, because the > empty dict is the recoverable spelling of the two. The load holds it by > reference, so binding `EPS` into that same dict after the load makes the next > call serve -- measured -- and at the top of this stack the failure already > says exactly that: "a guarded global is missing from the live scope this > artifact was loaded against; define it there so the guard can resolve it". The > scope the omitted spelling falls back to is `fn.__globals__`, which is not a > dict any caller can reach, so nothing analogous is recoverable there. > `guard_globals=f_globals or None` would also make a dict live by reference > only while it happens to be non-empty, so `d = {}` followed by > `load_compiled_function(f, f_globals=d)` and then `d.update(vars(mod))` would > silently keep resolving guards against the rebuilt scope, with nothing raising > to say so. In tree, the only caller that passes an empty dict is > `test_load_compiled_function_f_globals_merges_for_the_bytecode`, which means > "merge nothing" by it and answers the same either way, and > `benchmarks/dynamo/common.py:1566` passes no `f_globals` at all. > `test_load_compiled_function_empty_f_globals_is_an_empty_guard_scope` now pins > both spellings and the recovery, and it goes red under the normalization. > **FAQ: Does the public docstring's account of the seeding drift from what > `_seed_guard_scope` does, by dropping its per-name gating?** It said "The load > may insert Dynamo-minted names into this dict, and `__builtins__`, never > overwriting a key it already binds", and "may insert" is hedged, so it stated > nothing the gating contradicts: `_seed_guard_scope` writes an `__import_*` alias > only when the serialized `global_scope` carries it, and the builtins-dict key > only when some kept guard's source is rooted at it. The trim is done anyway -- > the parameter's docs are trimmed (the `f_globals` block is 26 lines at this > commit) and lose the minted-name vocabulary entirely -- but the gating is > deliberately not restated there. A caller cannot act on which minted name a kept > guard happened to be rooted at, only on the fact that the load writes into the > dict they passed. The gating stays in `_seed_guard_scope`'s own comment, next to > the code it describes, and the guide keeps the reader-facing form of it. > **FAQ: Which issue tracks closing the guard/bytecode divergence this > docstring calls a temporary limitation?** None is needed: the stack closes it. > #196897 moves the pick of the guarded names from the load to the call, so a > rebind the guards accept is what the graph computes with, and it renames and > flips `test_load_compiled_function_f_globals_accepted_rebind_is_not_used`, > whose comment here says either design has to change it. The narrower split > this commit's message describes for the builtins-dict key -- live builtins in > the caller's dict, the capture's recording still in `fn.__globals__`, pinned > by the arm added to > `test_load_rederives_over_a_builtin_the_loading_process_lacks` -- is closed by > #196904 at the top, which re-derives the key in both dicts and flips that arm. > Both are separate commits so this one stays the re-slice it is, and the > docstring keeps the limitation wording until the commit that removes it. > **FAQ: `_set_pool_mode` reimplements `unittest.mock.patch.object`, which > this file already imports and already uses; why not > `patch.object(sys.modules[__name__], "AOT_POOL_MODE", mode)` at the four > call sites?** The drop-in does work -- checked: `patch.object` on a module > object rebinds the module-dict entry the traced function reads and restores > it on exit -- so this is style, and the helper is not one-use. At the top of > this stack it has eight call sites in five tests across three PRs: four > here, three in #196816's missing-global-hint tests, and one in #196820, > which passes the helper itself as an argument > (`self._check_module_global_guard_dispatch(GlobalRebindModule, > _set_pool_mode)`) whose other actual is `_set_pooling`, a twin of the same > `@contextmanager` shape that #196818 adds with nine `with` blocks of its own > plus two more as-argument uses. That shared helper wants a plain `mode -> > context manager` callable, which the mock spelling only becomes wrapped in a > `functools.partial`, and `_set_pooling` mutates a dict entry in place rather > than rebinding a module global, so it cannot be spelled with `patch.object` > at all -- the pair is what lets the module test say which of the two it is > doing. The three `patch.object` precedents cited all target another module's > attribute (`bytecode_transformation._unique_id_counter`); nothing in the > file reaches its own module dict through `sys.modules[__name__]`. On the two > `_set_pool_mode("sum")` blocks read as no-ops: they are indeed redundant > while the module default stays `"sum"`, and they stay because the test's > subject is that one loaded call answers differently under two values of that > global, so the capture arm and the served arm name the value they run under > instead of sending the reader to check the default -- the three tests > #196816 adds above this one wrap their captures in the same explicit > `_set_pool_mode("sum")`. > **FAQ: Fold the public-wrapper arm and the recovery into the existing > `test_load_into_an_empty_scope_refuses_a_lifted_global` instead of carrying a > third copy of its scaffolding, and factor the three byte-identical 12-line > compile/save/reset preambles into one helper.** The existing test belongs to > #196817 -- `git log -S` puts its introduction in that commit, alongside > `AOTCompiledFunction.deserialize(guard_globals=)` -- and at #196817 > `load_compiled_function` still reads `return > AOTCompiledFunction.deserialize(data, f_globals, external_data)`: it does not > forward the guard scope until this commit. A public-path arm folded into that > test would therefore not raise at the commit that owns the test, so the fold > makes #196817 red rather than tidier, which is a bisect break and not a cleanup. > Its `assertIn("EPS", loaded.fn.__globals__)` is untouched and still sits with the > gate it documents, so nothing is dropped; the new test's subject is the public > wrapper, which is what this commit adds. The preamble is a file-wide shape rather > than a local triplicate: 18 tests in `TestAOTCompile` (five of them this > commit's) close their setup with that same > `compiled_fn.save_compiled_function(self.path())` plus `torch._dynamo.reset()` > block (counted over the class), so a helper covering only the ones added here > would be a second idiom, and one covering all 18 is a whole-file refactor inside > a commit whose production diff is one line plus docs, to be rebased under the 10 > commits above it that also touch this file. Left to a standalone cleanup. > **FAQ: Five of the seven new tests call `_hide_leaked_dynamo_globals()` and two > do not, with no comment saying why; close the divergence or explain it in one > line.** The leak premise is right, and measured: running > `test_load_compiled_function_f_globals_merges_for_the_bytecode` on its own leaves > `__builtins_dict___0`, `__compiled_fn_1_<uuid>` and four `__import_*` names in > this module's dict, and `..._f_globals_is_seeded_in_place` adds two more. The > order-dependence they would create is not reachable, also measured: both named > consumers scrub for themselves -- > `test_mint_skips_a_name_baked_in_by_another_process` deletes every > `_MINTED_PREFIXES` name inline, and > `test_load_seeds_exactly_the_recorded_globals` builds its `base` snapshot with > those prefixes filtered out -- both sort after the two leakers in the > alphabetical order unittest runs the class in, and running the four in exactly > that order in one process is green. Nor is the helper this file's hygiene > contract: of the 63 tests in `TestAOTCompile` that call `torch.compile`, 55 > capture into this module's dict without it, and the 8 that call it are the ones > whose own subject is that dict -- here > `test_aot_compile_fn_guards_track_rebound_global`, which hands `globals()` to the > load as the guard scope and says so in its comment. Even those calls are > insurance rather than load-bearing today: with the method stubbed to a no-op and > a leak already in place, the tests that call it still pass. Two more calls would > change nothing measurable, and a comment explaining an absent helper on 2 of > those 53 tests says as little; the invariant is stated where it is actionable, at > the consumer that needs a clean dict. > **FAQ: For a symbolic-shape guard that reads `G[...]` from the artifact scope, > "binding that name in `f_globals` does not satisfy it -- nor does omitting it > produce the documented `KeyError on G['...']`".** The bullet's main ask is taken: > both public texts now qualify the claim ("Symbolic-shape guards are exempt by > default", with the lambda-form explanation following). The parenthetical holds > only under the default AOT guard filter, and is refuted whenever global guards > are kept. Through `torch.compiler.load_compiled_function(f, f_globals={})`, on > artifacts captured with a `guard_filter_fn` that keeps global guards, `x * EPS` > raises `GuardManager check failed, reason: GuardDebugInfo(result=0, > verbose_code_parts=["KeyError on G['EPS']"], num_guards_executed=0, ...)` -- and > so does the bullet's own scenario -- `dynamic=True` over a shape expression > rooted at a global, `x + SCALE.sum() + x.shape[0]` -- naming `G['SCALE']`. The > lambda is not what reports it, and does not need to be: a global a kept shape > guard reads is a global with its own kept guard, and the C++ tree checks that one > first, so the caller gets the documented message rather than silence. > `CheckFunctionManager.get_global_guard_manager` builds > `globals_dict_manager(f_globals=self.runtime_global_scope, source="G")` > (`torch/_dynamo/guards.py:1710-1716`) and hangs each name off it through > `dict_getitem_manager`, i.e. `DictGetItemGuardAccessor`, whose verbose check > returns `"KeyError on " + get_source()` when the key is absent > (`torch/csrc/dynamo/guards.cpp:5774-5784`); no commit in this stack touches that > file. `test_load_compiled_function_empty_f_globals_is_an_empty_guard_scope` > asserts that exact text and passes, and #196816 above this commit parses it with > `_MISSING_GLOBAL_RE = re.compile(r"KeyError on G\[(?P<name>[^\[\]]*)\]")` to > append its scope hint, which only works because the message is produced. Under > the default filter none of this is reachable: `aot_compile`'s own filter drops > every `is_global` guard, the pruning keyed off `shape_env_sources` then leaves > the name out of the serialized scope entirely, and the only thing left to > complain is the shape lambda, whose own `KeyError` on the bare name is what gets > reported rather than the documented text. There the parenthetical is accurate, > for the reason the next entry measures. > **FAQ: "Then add a test in test/dynamo/test_aot_compile.py that captures > under `torch._dynamo.config.patch(enable_cpp_symbolic_shape_guards=True)` > with a dynamic dim rooted at a global, loads via > `torch.compiler.load_compiled_function` with an `f_globals` that omits that > global, and pins whether the call raises" -- declined last round as needing > a C++-compiler skip gate.** > > The decline was wrong and the test is now here as > `test_load_compiled_function_f_globals_governs_a_cpp_shape_guard`. It needs > no gate, because the thing that fails the call is not the compiled guard. > With the config on, the capture records `python_fallback=False` and > `shape_env_sources=[G['AOT_CPP_SHAPE_GLOBAL'].size()[0]]` > (`torch/_dynamo/guards.py:3569-3580`), and on load `SHAPE_ENV` builds the > operand managers at `guards.py:3642-3644` -- inside the `try`, BEFORE > `CppCodeCache.load` at `:3686` -- so the `DictGetItemGuardAccessor` for > `G['AOT_CPP_SHAPE_GLOBAL']` over `runtime_global_scope` (`:1712`) is in the > tree whether or not the compile succeeds. Measured by raising > `InvalidCxxCompiler` (the `:3690` arm) from `CppCodeCache.load` at capture, > at load, and at both: the test passes in all four configurations, in 3.37s, > 3.63s, 3.61s and 0.29s -- the last being a machine with no usable compiler > at either end, where nothing is compiled at all. > > What it pins: through `load_compiled_function(f, f_globals={})` the call > raises `GuardManager check failed, reason: GuardDebugInfo(result=0, > verbose_code_parts=["KeyError on G['AOT_CPP_SHAPE_GLOBAL']"], > num_guards_executed=4, ...)`, and binding that one name in the dict the > caller still holds makes the same call serve `x + > AOT_CPP_SHAPE_GLOBAL.sum(0)` -- i.e. a C++-compiled shape guard resolves its > global operands through this dict like any other guard, which is what both > public texts now say. It discriminates this commit: replacing the load with > the parent's `AOTCompiledFunction.deserialize(data, scope, None)`, no > `guard_globals=`, fails it with `AssertionError: RuntimeError not raised`. > > What it does not pin is the lambda arm, and no test at this commit can. With > the config off the same capture records `shape_env_sources=[]`, and the > pruning at `guards.py:5162-5169` keys the serialized `global_scope` off that > list, so the name is not in the artifact scope at all: every load spelling > -- argument omitted, `{}`, the name bound, `globals()` -- fails with > `verbose_code_parts=["'AOT_CPP_SHAPE_GLOBAL'"], num_guards_executed=7`, the > `KeyError` the shape lambda itself raises. That pruning is upstream > (#154752, present at the base commit `bed7b68cd9d`), so it is a pre-existing > gap in the lambda path rather than anything this stack changes, and the > carve-out sentence is accurate about it: binding the name in `f_globals` is > not what satisfies such a guard. > > Cost of the addition: 3.44s on its own, and `-k global` over > `test/dynamo/test_aot_compile.py` runs 71 tests in 37.8s with it. The two > tests that already patch the config, > `test_aot_compile_module_shape_only_global_arms_the_guard_scope` and > `test_aot_compile_module_shape_only_global_is_not_read_live`, arrive with > #196818 higher in this stack (`test/dynamo/test_aot_compile.py:1998`, > `:2041` there) and load through > `AOTCompiledModel.deserialize` with no supplied scope, so neither covers the > `f_globals` contract this one does. > **FAQ: "Scope the comment at `torch/_dynamo/aot_compile.py:596-600` to the > default guard-scope path it describes" -- the comment is the parent's, and the > sentence above it already does.** That paragraph is byte-identical at the parent, > #196817: `git show <parent>:torch/_dynamo/aot_compile.py | sed -n '555,600p'` > differs from the same range at this commit only in the parameter-naming comment > and predicate below it, and `git diff <parent> HEAD -- > torch/_dynamo/aot_compile.py` is exactly two hunks, the `arrived_as_f_globals` > predicate at `:565-569` and the NB on the default `guard_filter_fn` at `:778`. > > The restriction is stated one line above the sentence quoted: "... > forward_callable spreads that copy into fn.__globals__, which IS the default > guard scope. Re-derive over that one; a binding from anywhere else is a value > this process chose and stays." The behaviour is the parent's too -- > `AOTCompiledFunction.deserialize(data, guard_globals=scope)` already lands the > re-derive in the caller's dict and leaves the capture's recording in > `fn.__globals__` there, measured on this commit's tree as `scope[key] is > builtins.__dict__` with `'aot_probe' in fn.__globals__[key]`, and the parent > spells that call eleven times across eight of its own tests (at the parent, > `test_aot_compile.py:1683, 1744, 1755, 1792, 1896, 1948, 2017, 2123, 2136, 2184, > 2197`). > > What this commit does change is that the public spelling now takes that path, > and that had no coverage, so an arm on > `test_load_rederives_over_a_builtin_the_loading_process_lacks` now loads the > same artifact through `load_compiled_function` with an `f_globals` dict: the > artifact whose no-scope load raises `KeyError: 'aot_probe'` serves off the > recorded copy there, while the caller's dict holds this process's live > builtins under the minted key. It discriminates the change -- dropping > `guard_globals=f_globals` fails it with that same `KeyError: 'aot_probe'`, > and leaves the unarmed test passing. The commit message now records the split > as well. > **FAQ: "Add `self.assertTrue(loaded.guard_check(x))` after the rebind in > `test_load_compiled_function_f_globals_accepted_rebind_is_not_used`, so the test > pins that a guard was evaluated" -- measured, that line witnesses nothing.** > `guard_check` is a direct `guard_manager.check` > (`torch/_dynamo/aot_compile.py:486-490`) and never consults > `_guard_check_enabled`, which gates `__call__` alone at `:614`. So under the > mutation the suggestion is aimed at -- guard checking stopping at the load -- the > proposed assertion still passes: with `disable_guard_check()` called and the > accepted rebind in place, `guard_check` returns `True`. It also passes with no > guard on the name at all: under the default filter no `G['EPS']` guard survives, > and the load-time value is served with `guard_check` returning `True` after the > same rebind. > > That is what the test's own comment says (`:1825-1827`): "The rebind being > ACCEPTED has to be a guard's answer rather than an absent one: both the served > value and guard_check returning True also hold for an artifact that kept no guard > on G['EPS'] at all" -- which is why the assertion it grew last round reads the > serialized guard set instead. The shape that does discriminate is an > `assertFalse` on a rejected rebind, which is what the cited siblings do: they are > at `:1979`/`:1982` and `:2381`/`:2384` (not `:1964`/`:2366`), and in each pair > the `assertTrue` is the trailing half of an `assertFalse`/`assertTrue` idiom > whose first half is the load-bearing one. `test_..._guard_checks_the_tensor_type` > already pins the rejected end for this artifact. > **FAQ: "Say instead that one that installs as a C++ guard resolves its global > operands here like any other guard" -- the install form is not the criterion > either, so both texts now hedge rather than swap one sufficiency claim for > another.** The premise is right: capture-time > `enable_cpp_symbolic_shape_guards` is not sufficient, since an operand that > is neither an `int` nor a `float` sets `python_fallback = True` at > `torch/_dynamo/guards.py:3622` with the config on, and such an artifact then > serves with the global absent from `f_globals`, measured. > > But keying the sentence on the installed form would be false in the other > direction. The operand managers are built at `guards.py:3642-3645`, inside > the `try` and before `CppCodeCache.load` at `:3686`, so a load whose compile > raises `InvalidCxxCompiler` (the `:3690` arm) installs no C++ guard -- > `install_symbolic_shape_guard` is not called, measured by spying on it -- and > the call still raises `GuardManager check failed ... KeyError on > G['AOT_CPP_SHAPE_GLOBAL']`, with binding that one name in the caller's dict > making the same call serve. > > So the docstring and the guide now say the exemption holds by default, with an > artifact captured under `enable_cpp_symbolic_shape_guards` possibly resolving > those guards' global operands there instead, and promise no form. The requirement > stays a property of the artifact rather than of the load: a load reads what the > capture recorded (`guards.py:3458-3464`) and the config's only read in library > code is `:3535`, in the else-branch a load never enters. The test that pins the > C++ end now patches the config around the capture alone for that reason, and > drops `mark_dynamic`'s marking off the module-level tensor it marks in cleanup so > a later test on that global cannot inherit it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #196815 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #196767, #196817
…in (#196816) This is a diagnostic change only. A guarded global that the scope the guards resolve against does not have is an old failure, not one this commit introduces: the parent already fails the guard check and reports `KeyError on G['NAME']` and nothing else. ```python loaded(x) # RuntimeError: GuardManager check failed, reason: ... KeyError on G['CONFIG'] ``` That report is accurate but tells the user nothing about the fix, and what the fix is depends on which dict the guards were resolved against, which the loaded function did not record. Sending everyone to "pass `f_globals`" is wrong for a caller who already passed one, and wrong for an in-process artifact that never went through `deserialize` at all. ## Record which scope the guards resolve against `AOTCompiledFunction` gets a `_guard_scope` field, settled in `__post_init__`: ```python class _GuardScope(enum.Enum): CAPTURED = "captured" # never serialized; guards hold the tracing process's globals SUPPLIED = "supplied" # a live dict the load re-rooted the guards at RECONSTRUCTED = "reconstructed" # rebuilt for this load out of the artifact ``` The three states are the three ways of getting a callable: ```python # CAPTURED: same process, no round trip; guards were built against mypkg.model's real dict compiled = torch.compile(fn, fullgraph=True, backend="eager", options={"guard_filter_fn": keep_global_guards}).aot_compile(((x,), {})) # SUPPLIED: a live scope was handed over -- guard_globals, which load_compiled_function # fills from its own f_globals, or later a module's live namespace loaded = torch.compiler.load_compiled_function(f, f_globals=vars(mypkg.model)) # RECONSTRUCTED: no scope handed over; guards resolve against fn.__globals__, the dict # forward_callable rebuilt from the globals the graph lifted, the graph's freshly # imported module aliases and the backend id loaded = AOTCompiledFunction.deserialize(data) ``` `__post_init__` settles the state on whether the load SUPPLIED a guard scope rather than on whether that scope has names in it, so a caller who passed an empty one is still told to define the name in the scope they passed, which works because the load holds that dict by reference. ## The advice, worded for the scope that applies When a guard fails and the failure is a missing top-level global, `__call__` appends one of three hints: ``` # RECONSTRUCTED ... KeyError on G['CONFIG'] -- a guarded global is missing from the scope rebuilt from the artifact; load with an f_globals= that is a complete live scope carrying the name -- normally vars(mod) for the module mod that defined the function, which is usually not the module doing the loading -- so the guard can resolve it. # SUPPLIED ... KeyError on G['CONFIG'] -- a guarded global is missing from the live scope this artifact was loaded against; define it there so the guard can resolve it. # CAPTURED ... KeyError on G['CONFIG'] -- a guarded global is missing from the globals of the module the compiled function was traced in, which its guards still resolve against; define it there so the guard can resolve it. ``` The CAPTURED case is real: the guards hold the traced module's dict by reference, so a name deleted after capture can be defined there again. ```python del mypkg.model.CONFIG compiled(x) # KeyError on G['CONFIG'] + the CAPTURED hint mypkg.model.CONFIG = ... # the guards still hold that module dict compiled(x) # resolves again ``` Two wording decisions. The RECONSTRUCTED hint asks for `f_globals=` set to a COMPLETE live scope, normally `vars(mod)` for the module `mod` that DEFINED the function, which is usually not the module doing the loading, rather than a dict of the missing name: on the public loader `f_globals` replaces the dict the guard tree resolves against, so a minimal one trades this failure for the next guarded global's as soon as the kept guards read more than one name the load does not seed. That is the same scope `load_compiled_function`'s own `f_globals` documentation names. And it is spelled with its argument, because a bare `vars()` is the caller's locals. Recording the state is preferred over the shorter alternative of deriving it where the failure is reported: `_guard_globals` is None for CAPTURED and for RECONSTRUCTED alike, so a test on it at that point cannot tell the two apart and would give a caller whose guards still resolve against their own live globals the advice meant for a load that supplied no scope at all. ## A load with only positional `f_globals` stays RECONSTRUCTED ```python loaded = AOTCompiledFunction.deserialize(data, {"CONFIG": CONFIG}) # f_globals, no guard_globals ``` `deserialize`'s positional `f_globals` is `_extra_globals`, which `forward_callable` MERGES over the rebuilt scope by copy. The guards do read the names it carried, but a name bound in that dict after the load is invisible to them, so the SUPPLIED advice, define the name in the scope you passed, would be false for that shape. The state deliberately stays RECONSTRUCTED, and the advice it gets is the one that works, which `test_aot_compile_fn_extra_globals_only_load_is_still_reconstructed` proves by reloading with a complete `f_globals`. A module load is RECONSTRUCTED here too, since `AOTCompiledModel.deserialize` supplies no scope at all; the next commit resolves a live scope for it from `model.forward`, which moves that path to SUPPLIED. ## Only fire for a real missing top-level global The hint is appended only when a guard failure really is a missing top-level global, decided by `fullmatch`ing one verbose code part: ```python _MISSING_GLOBAL_RE = re.compile(r"KeyError on G\[(?P<name>[^\[\]]*)\]") _MINTED_GLOBAL_PREFIXES = ("__import_", "__builtins_dict__", "___unnamed_scope") def _names_a_missing_global(text): match = _MISSING_GLOBAL_RE.fullmatch(text) return match is not None and not match["name"].strip("\"'").startswith(_MINTED_GLOBAL_PREFIXES) ``` - **A nested key gets no hint.** `KeyError on G['CONFIG']['scale']` means the global itself resolved and only a key inside it is absent. The looser alternative of searching the whole `str(GuardDebugInfo)` for `"KeyError on G["` fires there too, and advising the user to define the global would send them the wrong way. `test_aot_compile_fn_missing_nested_key_gets_no_missing_global_hint` pins it. - **A name Dynamo minted gets no hint.** A `KeyError` on an `__import_*` alias or the `__builtins_dict___N` key reports a gap in the seeding a load does for each one a kept guard is rooted at, not a name any caller can define. The `___unnamed_scope_<id>_c<n>` key an inlined frame whose globals belong to no module is guarded through embeds `id()` of a dict in the tracing process, so no module's `vars()` in a loading process holds it and the advice's own recipe cannot be followed for it. The list is complete because a report here needs a serializable guard rooted at a `GlobalSource` on the name: every other minted family builds no `Source` or a guard type in `UNSUPPORTED_SERIALIZATION_GUARD_TYPES`, which `___unnamed_scope`'s was not, so moving a type off that list means re-checking this one. `test_missing_global_hint_skips_a_name_dynamo_minted` and `test_aot_compile_fn_missing_unnamed_scope_gets_no_missing_global_hint` pin the two. `_names_a_missing_global` is a named predicate although only `__call__` consults it here; its second caller arrives with the no-match report in #196823, which runs it over the parts of each entry that report quotes. ## Two mechanical details **`fn` is a declared field.** Both the state and the rebuilt callable are declared dataclass fields rather than attributes `setattr`'d onto the instance. `fn` is `field(init=False, repr=False, compare=False)`, and both flags matter: a field with no default left in the generated `__repr__` or `__eq__` makes both raise `AttributeError` on an instance `__post_init__` abandoned, which is what a traceback rendering frame locals reports instead of the real `check_compatibility` failure. `test_repr_of_an_artifact_whose_post_init_raised` pins it: it passes on the parent, where there is no `fn` field to trip on, and fails when either flag is dropped. **The trailing newline.** `GuardDebugInfo` binds no `__repr__`, so the f-string interpolates its `__str__`, which ends in `)\n`. The hint is appended to the stripped message, since appending the inline continuation straight to it would put the advice on a line of its own, beginning with a stray space. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_aot_compile_fn_missing_global_hint_names_f_globals python test/dynamo/test_aot_compile.py -k test_aot_compile_fn_missing_global_hint_names_the_supplied_scope python test/dynamo/test_aot_compile.py -k test_aot_compile_fn_missing_global_hint_names_the_tracing_scope python test/dynamo/test_aot_compile.py -k test_aot_compile_fn_missing_nested_key_gets_no_missing_global_hint python test/dynamo/test_aot_compile.py -k test_aot_compile_fn_extra_globals_only_load_is_still_reconstructed python test/dynamo/test_aot_compile.py -k test_missing_global_hint_skips_a_name_dynamo_minted python test/dynamo/test_aot_compile.py -k test_aot_compile_fn_missing_unnamed_scope_gets_no_missing_global_hint python test/dynamo/test_aot_compile.py -k test_repr_of_an_artifact_whose_post_init_raised ``` Authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]> ## FAQ > **FAQ: Why is `_names_a_missing_global` a helper when this commit has only one > caller? Shouldn't a one-expression predicate used once be inlined per the repo's > style rule?** Because it is not single-use in the tree that lands: #196823 adds a > second caller when the module dispatch path builds its "no compiled graph > matched" report, running the same predicate over the verbose code parts of each > entry that report quotes, and at the top of the stack there are two call sites. > The one use visible here is an artifact of slicing this feature into atomic > commits, not a property of the final code, so inlining it would mean deleting a > helper in this commit and re-introducing it five commits later -- and in the > interim it would leave #196823's `if missing_global is None and > any(map(_names_a_missing_global, parts)):` referring to a name that no longer > exists. The style rule is aimed at helpers that are genuinely used once; this one > is named precisely so both the function-level failure message and the > module-level report decide "is this a missing top-level global?" the same way, > including the `fullmatch`-not-substring distinction that the nested-key test > pins. > **FAQ: `AOTCompiledFunction.deserialize(data, f_globals=scope)` with no > `guard_globals` records RECONSTRUCTED, yet the guards do read `scope`. > Should that shape be SUPPLIED instead?** > > No -- SUPPLIED would give it advice that is false. `f_globals` there is > `_extra_globals`, and `forward_callable` merges it into a FRESH dict > (`{**import_sources, **used_globals, **(extra_globals or {}), > backend_id: ...}`) which becomes `fn.__globals__` and therefore the guard > scope. The merge copies, so the caller's own dict is not what the guards > read. Measured on that shape: `loaded.fn.__globals__ is scope` is `False`, > `"UNRELATED" in loaded.fn.__globals__` is `True`, and binding the missing > name in `scope` after the load leaves every call still failing -- while > binding it in `fn.__globals__` resolves the guard. SUPPLIED's advice is > "define it there so the guard can resolve it", i.e. exactly the thing that > does not work here; the RECONSTRUCTED advice, load again with an > `f_globals=` that carries the name, is what does, and the test for this > shape proves it by reloading. What was wrong was the sentence's > description of the dict, not the state: the clause "which holds only the > globals the graph lifted" is deleted, since that scope also holds the > graph's freshly imported module aliases, the backend id and whatever an > `f_globals=` merged in. > **FAQ: An `nn.Module` load is RECONSTRUCTED here and cannot pass an > `f_globals=`. Why does it get advice it cannot act on?** > > Because the fix belongs to the next commit in this stack, not to this one. > `AOTCompiledModel.deserialize` supplies no scope, so every function it > builds is RECONSTRUCTED (measured: a module compiled with a > `guard_filter_fn` that keeps global guards, saved with > `_save_aot_compiled_module` and loaded with `_load_aot_compiled_module`, > reports `_guard_scope` RECONSTRUCTED and fails with > `KeyError on G['MOD_POOL']`), and neither `_load_aot_compiled_module` nor > `AOTCompiledModel.deserialize` takes a scope parameter. The next commit > resolves that path's guard scope from `model.forward`, which moves it to > SUPPLIED and gives it the "define it there" advice that is then true of > it, and later commits in the stack cover it with tests. Pinning the > RECONSTRUCTED wording for the module path here would pin behaviour the > very next commit deliberately changes. > **FAQ: The hint throws away the global name it just matched. Have > `_names_a_missing_global` return the name instead of a bool and interpolate > it -- "the global `AOT_POOL_MODE` is missing from ..." -- so the appended > sentence is self-contained rather than making the reader dig the name out of > the `GuardDebugInfo` dump.** > > The name is already in that sentence's own message, two lines above it, and > interpolating it would print it twice. Measured, the whole `RuntimeError` this > hint is appended to is five lines: `GuardManager check failed, reason: > GuardDebugInfo(` / `result=0,` / `verbose_code_parts=["KeyError on > G['AOT_POOL_MODE']"],` / `num_guards_executed=4,` / `user_stack=None) -- a > guarded global is missing from ...`. That shape is structural, not lucky: the > `KeyError on ` report is built by the three-argument `GuardDebugInfo(result, > failed_reason, num_guards_executed)` constructor (`guards.cpp:5569, 5688, 5780, > 6892`), which appends exactly one verbose code part and leaves `user_stack` none, > and `check_accessors_verbose_nopybind` returns at the FIRST failing accessor > while passing those two fields through unchanged -- so this failure can never > carry the many-line `user_stack=` or the second matching name that would bury it. > The pairing is pinned in one message twice over: > `test_aot_compile_fn_extra_globals_only_load_is_still_reconstructed` asserts both > `KeyError on G['AOT_POOL_MODE']` and `missing from the scope rebuilt from the > artifact`, and `test_aot_compile_fn_missing_global_hint_names_the_tracing_scope` > asserts the name and then `) -- a guarded global is missing`. The sentence is > also deliberately name-free because it is not this call site's: #196823 appends > the same one, once, to the `No AOT compiled graph matched this call` report, > after a ` [i] ...` line per compiled input that already quotes that input's own > verbose code parts, choosing the hint from the FIRST entry that named a missing > global. A name interpolated there reads as the one missing global of a report > that just listed every entry. What that commit does thread through is scope facts > -- `forward=` in the signature, and on the instance the reason `get_traced_fn` > could not resolve a forward (the `_forward_not_resolved_reason` field #196818 > adds) -- because the scope, not the name, is what the advice varies on. > **FAQ: Filtering out a Dynamo-minted name replaces misleading advice with no > advice: `KeyError on G['__builtins_dict___0']` gets nothing. Per the > comment, that means `_seed_guard_scope` has a seeding gap, i.e. an internal > Dynamo bug, and saying so -- in `source.py:208`'s wording, "this is an > internal Dynamo bug. Please file an issue on GitHub" -- is strictly more > useful than silence.** > > It is more useful only if it is true, and at this call site it is not > decidable. Measured on the real path: a load whose kept guard is rooted at > `__import_torch_dot_nn_dot_modules_dot_module` starts with that alias > unbound in the module it is handed, comes out SUPPLIED with the alias > seeded, calls fine -- and then deleting that one key from the module's own > namespace reproduces exactly `KeyError on > G['__import_torch_dot_nn_dot_modules_dot_module']`, with the seeding having > worked. That is not a contrived deletion: #196895 higher in this stack fixes > a real instance of it, where a later `CompilePackage.uninstall()` popped the > alias it had merely overwritten and nothing re-seeds, and its > `test_uninstall_keeps_a_global_it_did_not_bind` pins the loaded artifact > still working across that install/uninstall cycle. `_seed_guard_scope` > writes into a live user namespace and deliberately installs no > `CleanupHook`, so from `__call__` "the load never seeded this name" and "the > load seeded it and something later removed it" are indistinguishable, and > only the first is the seeding gap the branch would announce. The convention > cited is a raise at the point the invariant is KNOWN broken -- > `TempLocalSource._name_template` raises `NotImplementedError` because > guarding on it cannot happen -- whereas printing it here would accuse Dynamo > for a name the caller's own dict lost, on a path where the reader's fix is a > version carrying #196895 rather than a new issue. The minted name itself is > not what silence costs them: it is quoted verbatim in that same five-line > message. And the hint takes no name (see above), so the branch also means > the shared predicate stops being a predicate and starts returning a category > that #196823's report reads as a bool -- machinery in the two callers for a > sentence one of the two reachable causes would make false. > **FAQ: `.strip("\"'")` can mangle the name it is prefix-testing -- a global > containing an apostrophe renders as `G["don't"]` and strips down to `don`, so > the prefix test runs against a truncated name. Slice exactly one quote off, or > capture inside the quotes in the regex.** > > `str.strip` removes characters from the two ends only, never from inside, so > that example does not truncate. Measured through the real regex and the real > predicate: the verbose code part is `KeyError on G["don't"]`, the captured name > is `"don't"`, `.strip("\"'")` yields `don't` -- not `don` -- and > `_names_a_missing_global` returns `True`, which is the correct answer for a > name the caller wrote. A mangle would need a global whose own first or last > character is a quote, and the name comes from `GlobalSource._name_template` > (`source.py:262-263`) rendering `repr()` of a `co_names` entry, which is always > an identifier. Exactness here buys nothing over `strip`, and the direction of > any hypothetical truncation is harmless anyway: dropping leading characters can > only make a name start with `_`-prefixed minted text, i.e. suppress a hint, > never invent one. > **FAQ: The two new fields carry too much comment for four lines of code > (`aot_compile.py:518-534`).** > > Measured before deciding: 13 comment lines over 4 code lines, in a field block > that is already 16 comment lines of 61 (26%) -- the pre-existing neighbour > `_guard_globals` runs 3 comment lines for 1 code line, so the density is the > block's, not new. Both comments exist because the code reads as removable > without them: `init=False` on `_guard_scope` is what stops a caller from > asserting a scope the load did not resolve, and `repr=False, compare=False` on > `fn` is what stops `__repr__`/`__eq__` raising `AttributeError` on an instance > `__post_init__` abandoned -- the failure mode > `test_repr_of_an_artifact_whose_post_init_raised` pins, which would otherwise > mask a `check_compatibility` error in any traceback that renders frame locals. > A comment that survives a reviewer proposing the simpler version is the kind > this file keeps. > **FAQ: `_MINTED_GLOBAL_PREFIXES` collides by name with the test module's > differently-populated `_MINTED_PREFIXES` (`test/dynamo/test_aot_compile.py:80`).** > > They are deliberately different sets and never meet: the test module's four > references (`:81, :1587, :1595, :2204`) are all to its own tuple, and the `from > torch._dynamo.aot_compile import (...)` block imports `_GuardScope` and > `_names_a_missing_global` only -- the production tuple is not imported anywhere, > so neither name shadows the other in any namespace. What they enumerate differs > by purpose: the production tuple lists keys a *guard* can be rooted at in the > scope the guards resolve against (`__import_*`, `__builtins_dict__`, > `___unnamed_scope`), while the test tuple lists names a *capture* leaks into the > module dict of the function being compiled (`__compiled_fn`, `__resume_at`, ...), > which is why one contains `___unnamed_scope` and the other `__resume_at`. Naming > them the same thing would be the actual error. > **FAQ: `_GuardScope`'s three string values are never read, so `enum.auto()` > would say so.** > > They are read on every `repr()` of the artifact. `_guard_scope` is a plain > field, so it is the last thing the generated `__repr__` prints: measured, > `repr(compiled_fn)` ends `_guard_scope=<_GuardScope.CAPTURED: 'captured'>)`, > where `enum.auto()` would render `<_GuardScope.CAPTURED: 1>`. That reader is > not hypothetical in this commit: the sibling `fn` field is `repr=False` > precisely because a traceback rendering frame locals is what a > `check_compatibility` failure gets read through, and > `test_repr_of_an_artifact_whose_post_init_raised` pins that path. A state > printed as `'captured'` needs no lookup; one printed as `1` does. > **FAQ: The message ends in `.` when the hint is appended but in `)\n` when it > is not -- make the punctuation consistent.** > > The asymmetry is the point: `rstrip()` is applied only on the branch that appends > a continuation, so every guard failure that is not a missing global keeps the > parent's message byte for byte. Measured at this commit, a plain guard failure > still ends in the same `)\n`, byte-identical to the parent's text for that > failure. Stripping unconditionally would change the text of every unrelated guard > failure -- and the tests that read it -- for a cosmetic gain on a path this > commit does not otherwise touch. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #196816 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #196767, #196817, #196815
…ake (#196819) Mostly tests for the guard-scope resolution the previous commit added, plus the behaviour changes writing them turned up. `aot_compile_module` traces `model.forward` directly, so `nn.Module`'s dispatch in `_call_impl` never runs and every forward or backward hook registered on `model` itself is dropped from the compiled callable. That is a silently different answer rather than an error: ```python class M(torch.nn.Module): def forward(self, x): return x * 2 m = M() m.register_forward_hook(lambda mod, args, out: out + 1) m(x) # eager: x * 2 + 1 aot_compile_module(m, [ModelInput((x,), {}, [])])(x) # x * 2 -- the hook never ran, nothing raised ``` ## Warn about dropped hooks, worded per group `_warn_dropped_module_dispatch(model)` runs at the top of both `aot_compile_module` and `AOTCompiledModel.deserialize`, since a hook present only in the loading process is dropped just as thoroughly, and the tests pin one record per path. It warns whenever any of the four per-instance hook dicts `_call_impl` dispatches on is non-empty, naming the kind of hook ("forward pre-hooks", "backward hooks") rather than the private dict a caller who used `register_forward_pre_hook` never sees: ``` M has forward hooks registered; the AOT compiled forward calls M.forward directly, so those hooks do NOT run and its result may differ from eager -- to keep them, AOT compile torch.compile(model).forward instead, which traces __call__ and runs them; call the artifact it returns with the module as its first argument if you define forward yourself; ... ``` Those four are the per-instance subset of the eight dicts `_call_impl` tests; the four `_global_*` ones are deliberately left out, because an artifact served through `OptimizedModule` still runs them on the wrapper's own `_call_impl`, so warning about them would be a false positive on that path. `test_aot_compile_module_global_hooks_are_not_warned_about` pins that by registering a global forward hook and asserting the load stays silent while the hook still fires through the wrapper. A direct `AOTCompiledModel` really does drop them, and without a warning, which `deserialize`'s docstring now says rather than a fifth warning that would claim the loss for both paths. Only the dicts of `model` itself are polled: a hook or a `__call__` override that a SUBMODULE carries only in the loading process is dropped with no warning at all, because the graph baked in whatever the capture traced through that submodule's `nn.Module.__call__`, so a `model.modules()` walk would be a false positive for the ordinary capture-and-load-with-the-same-hooks case. The docstring states that boundary next to the `_global_*` one. One record per GROUP, not per dict: the forward and backward wordings each name every hook kind in their group, and `test_aot_compile_module_warns_one_record_per_group` registers all four kinds on a module that also overrides `__call__` and pins the three records that come out. The forward dicts and the backward dicts are worded separately, because the redirect is unconditional only for the forward ones. AOT compiling `torch.compile(model).forward` traces `_wrapped_call_impl`, which runs the forward hooks; the same capture refuses a module-level backward hook unless compiled autograd is enabled around it, and the flag the graph break's own hint names does nothing here: ```python m.register_full_backward_hook(hook) torch.compile(m).forward.aot_compile(((x,), {})) # Unsupported: Module-level backwards hooks require compiled autograd torch._dynamo.config.compiled_autograd = True # still refuses: aot_compile never torch.compile(m).forward.aot_compile(((x,), {})) # enters the dynamo context that reads it with torch._dynamo.compiled_autograd._enable(torch.compile): # private; the capture succeeds art = torch.compile(m).forward.aot_compile(((x,), {})) art(m, x).sum().backward() # reproduces eager's hooked gradient exactly art.save_compiled_function(p) # saves load_compiled_function(p) # raises: the artifact cannot round-trip ``` What differs from eager differs too: a dropped backward hook leaves the forward result bit-identical and changes the gradients, so a reader who checked outputs against a "result may differ" warning would conclude it was spurious. The backward message therefore says the hooks do not run, that the gradients may differ while the forward result does not, and that the redirect keeps them only under compiled autograd and only for an artifact that is never reloaded; it calls `_enable` private, because without the word a warning naming an underscored function reads as a supported API. `test_aot_compile_module_dropped_hook_advice` follows the advice rather than only reading it: for the forward dicts it registers a hook with an effect and asserts the redirect's artifact reproduces eager, and for the backward dicts it asserts all three legs above, so the text cannot drift back to denying a redirect that works or promising one that round-trips. The forward-hook warning gets a tail for a `LazyModuleMixin` module: its initializer is registered as a forward pre-hook, so every uninitialized lazy module lands in the warning, and while it does `OptimizedModule._initialize` pins the wrapper's forward to `_call_lazy_check`, which has no `aot_compile`, so the redirect says to call the module once and wrap it again. `test_aot_compile_module_lazy_hook_advice_says_to_wrap_again` pins that pin and its release. ## Warn about an overridden `__call__`, probed the way eager dispatches Hooks are not the only thing tracing `model.forward` skips: a `__call__` the module overrides is dropped the same way, because eager dispatches through `type(model).__call__` while the artifact calls what `forward` compiled to, and since no hook dict records it, that case was silent. It gets a warning of its own, with the redirect, which does work for an override. The probe is the same type lookup eager does: ```python class Logged(torch.nn.Module): def __call__(self, *a, **k): print("called"); return super().__call__(*a, **k) def forward(self, x): return x aot_compile_module(Logged(), ...) # warns: Logged overrides __call__ ... m2 = M(); m2.__call__ = lambda *a: ... # an instance attribute: CPython resolves a special aot_compile_module(m2, ...) # method on the type, eager ignores it, the artifact matches -- silent ``` That lookup is not the whole probe. `fx.GraphModule` installs a wrapper as its per-instance class's `__call__` on every `GraphModule.recompile`, and `recompile` always runs from `__init__`, so the lookup alone calls every GraphModule an override, a plain `symbolic_trace` GraphModule included (an `ExportedProgram.module()` never gets this far: its local-scope `GraphModuleImpl` fails the save with `PackageError`). That wrapper is not an override: with no class `__call__` to wrap it only prettifies `eval_with_key` tracebacks and delegates to `super(cls, obj).__call__`, so eager runs the hooks and the artifact matches. So the probe walks `type(model).__mro__` and skips every class whose own `__call__` is FX's wrapper, taking the next `__call__` the MRO offers, which is the one that delegation reaches: ```python def is_fx_wrapper(c): fn, wrapped = vars(c)["__call__"], vars(c).get("_wrapped_call") return ((fn.__module__, fn.__qualname__) == ("torch.fx.graph_module", "GraphModule.recompile.<locals>.call_wrapped") and isinstance(wrapped, _WrappedCall) and wrapped.cls_call is None) call = next(vars(c)["__call__"] for c in type(model).__mro__ if "__call__" in vars(c) and not is_fx_wrapper(c)) ``` The wrapper is told apart by its def site, since `call_wrapped` is a closure `recompile` mints anew on every run and leaves no one function to compare by identity, with the `_WrappedCall` that `recompile` installs beside it on the same class still carrying a `None` `cls_call`. Identifying it by its function rather than by one class identity matters twice. `recompile` installs it on whatever `type(self)` is at the time, and `parametrize`, `fully_shard` and `replicate` all rebind `module.__class__` to a fresh subclass after the trace, so a recompile after that swap leaves TWO wrapper classes on the MRO (`recompile` reads `vars(cls)`, which does not see the inherited `_wrapped_call`, so the fresh subclass gets one of its own), and the capture itself performs that recompile: serializing the guards pickles the GraphModule, whose `__reduce__` recompiles it onto the swapped class, so every probe after the first capture, a load included, sees both, and a probe keyed on one class identity calls the inner one an override (measured: `ParametrizedLinear overrides __call__`; eager on that module is FX's own version of the same mistake, a `RecursionError` between the two wrappers, so there is no override to report). And a real `__call__` assigned onto the per-instance class afterwards sits on the very class FX wrapped, so skipping that class by identity dropped a genuine override that eager runs. Skipping the class rather than starting the walk past it is what keeps an override sitting AHEAD of it visible; a test traces an `nn.Linear`, parametrizes its weight and pins that the capture stays silent while the artifact still matches eager. A wrapper whose `cls_call` was set is the one shape that does not delegate to `super`; `functional_export` sets it for a hooked root, and a test pins that this stays an override, both on the class that owns it and behind a `__class__` swap that leaves the fresh subclass owning neither attribute. Walking rather than trusting `cls_call` is what makes this safe rather than merely quiet: `cls_call` is `None` for a `GraphModule` subclass that declares `__call__` too, because FX reads the declaration off the per-instance class, where a subclass's does not live, so calling `cls_call is None` not-an-override would have dropped a real one. `test_aot_compile_module_fx_call_wrapper_is_not_warned_about` pins both halves, that a traced GraphModule stays silent on the capture and the load and that such a subclass still warns. `_LazyGraphModule` defers that recompile to the first call or code access, so until then no class on its MRO owns a `__call__` and the probe is silent for want of a wrapper rather than by skipping one; the test pins both states. ## Which arguments the redirect's artifact takes All three redirects say which arguments the artifact they produce takes, because getting it wrong ends on the first call in a guard failure: ```python art = torch.compile(m).forward.aot_compile(((x,), {})) art(m, x) # forward you define yourself: the module first (AOTCompiledModel.__call__ hides this # convention by passing self.model for the user) art(x) # forward defined in a file Dynamo skips, as torch.nn's stock modules are, or under # config.wrap_top_frame: only the forward arguments ``` The branch is the one `OptimizedModule._initialize` took, and the discriminator is `trace_rules.check(mod.forward)`, which resolves on the FILE `forward` is defined in rather than on the class, so a subclass that inherits `forward` unoverridden counts as skipped too. The clause names that predicate, `OptimizedModule._forward_has_skip_rule(model)`, rather than a list, because no list spells the rule: `check_file` consults `LEGACY_MOD_INLINELIST` before `MOD_SKIPLIST`, so a file inside a skipped directory can still be inlined (measured, `QuantStub`'s forward under `torch/ao/` is, so its artifact takes the module first), and a wording that enumerated `MOD_SKIPLIST` would answer wrongly there and rot with the list. Without the clause, following the advice ends in `GuardManager check failed` for the hook wordings, whose trace of `_wrapped_call_impl(self, *args, **kwargs)` absorbs the shifted argument and then fails the recorded `len(L['args']) == 1` guard, and, for the third, in a `TypeError` naming the override's own parameter when the override declares one, or that same guard failure when it takes `*args`. The tests assert the clause on all three wordings: the two hook ones through the parametrization rather than on the forward pair alone, since a module carrying only a backward hook gets the backward warning and no other, and the override wording in the test for that warning. `test_aot_compile_module_redirect_arg_clause_is_conditional` pins the branch rule itself, on a Linear, on a subclass that inherits `forward`, on one that overrides it and on a `QuantStub`, which the inline list rescues from the skipped directory it lives in; it pins that the inheriting subclass's artifact takes only the forward arguments and refuses the module-first call, so the predicate cannot drift from the branch `_initialize` takes, and that the clause names the predicate and no list. ## The capture path unwraps too, and has to REBIND Handed the wrapper `torch.compile` returned, `aot_compile_module` traced `OptimizedModule.forward`, which is eval_frame's `compile_wrapper`: ```python aot_compile_module(torch.compile(m), [ModelInput((x,), {}, [])]) # parent: Unsupported: Attempted to call function marked as skipped ... set_eval_frame ``` So the wrapper-caller path this commit documents and warns for could not reach an artifact at all. Had it traced, `AOTCompiledModel` would have kept the wrapper as `self.model`, which `prepare_f_locals` hands the guards as `L['self']`, so any forward that reads `self` would report no match on every call: measured, `___check_type_id(L['self'], ...) type=<class 'M'>` answers false for the wrapper and true for the module. One rebind, through the `_unwrap_optimized_module` the previous commit added, fixes both halves, and `test_aot_compile_module_capture_warns_about_the_traced_module` now hands in a real `ModelInput` and asserts the artifact answers and holds the module rather than the wrapper. It counts every record rather than filtering for the hook one, since warning about the wrapper emits exactly one record too, and joins them into the assertion's message, which `assertEqual` otherwise drops for not being a string. With `inputs=[]` that test stopped at "Expected at least one compiled result", raised after the warning and before the capture, which is why neither half showed up. ## Both shapes `forward` can take, for scope resolution The hook case is also what discriminates `model` from `model.forward` for the scope resolution #196818 added: a registered forward hook makes `get_traced_fn(model)` return the `Module._wrapped_call_impl` function, whose globals are `torch/nn/modules/module.py`, and the scope must still come out as the module definition's namespace. `test_aot_compile_module_scope_resolves_through_forward_hook` pins that; its hook is deliberately the identity, precisely because hooks are dropped, so it pins scope resolution on a hooked module rather than hook support, and it leaves the warning count to the parametrized test that owns it. A `functools.partial` forward is not such a case (`get_traced_fn` raises the same "Unsupported model code type" for both spellings), so `test_aot_compile_module_fallback_scope_hint_names_the_forward` pins the fallback instead: the artifact loads, the warning names the object and the consequence, and a call reports the missing global and points at the rebuilt scope rather than at a module to define the name in. Asserting that report was chosen over promising the fallback works: nothing on this path puts a user global into the rebuilt scope, whose extra names are the recorded imports and the backend id, so the honest contract is the one that runs, which keeps #196818's choice to warn rather than refuse an unresolvable forward pinned, the one case here with no capture to redirect to. `test_aot_compile_module_fallback_scope_runs_without_global_guards` sits beside it and pins the two things that half silently relied on: that the guards really did fall back to the reconstructed scope, and that with no global guard to satisfy nothing warns. The module dispatch body #196818's test spelled inline becomes a helper parameterized by module factory and mode setter; both the test it came from and the hooked-module test above call it, and the containment #196818 added for the globals a capture leaks into this module's dict moves with the body, to the top of the helper, where one call covers every caller. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_aot_compile_module_dispatches_on_global_guard python test/dynamo/test_aot_compile.py -k test_aot_compile_module_scope_resolves_through_forward_hook python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_on_dropped_hooks python test/dynamo/test_aot_compile.py -k test_aot_compile_module_dropped_hook_advice python test/dynamo/test_aot_compile.py -k test_aot_compile_module_global_hooks_are_not_warned_about python test/dynamo/test_aot_compile.py -k test_aot_compile_module_capture_warns_about_the_traced_module python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_on_custom_call python test/dynamo/test_aot_compile.py -k test_aot_compile_module_warns_one_record_per_group python test/dynamo/test_aot_compile.py -k test_aot_compile_module_instance_call_is_not_warned_about python test/dynamo/test_aot_compile.py -k test_aot_compile_module_fx_call_wrapper_is_not_warned_about python test/dynamo/test_aot_compile.py -k test_aot_compile_module_fallback_scope_hint_names_the_forward python test/dynamo/test_aot_compile.py -k test_aot_compile_module_fallback_scope_runs_without_global_guards python test/dynamo/test_aot_compile.py -k test_aot_compile_fn_missing_global_hint_names_f_globals python test/dynamo/test_aot_compile.py -k test_aot_compile_fn_missing_global_hint_names_the_tracing_scope python test/dynamo/test_aot_compile.py -k test_aot_compile_module_lazy_hook_advice_says_to_wrap_again python test/dynamo/test_aot_compile.py -k test_aot_compile_module_redirect_arg_clause_is_conditional ``` Authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]> ## FAQ > **FAQ: the three warnings fire unconditionally on every capture and every load > with nothing deduping them -- for a module with both a forward and a backward > hook plus a GraphModule-style `__call__` that is three multi-line warnings per > load, so is repeat emission in a serving loop worth a `warn_once`?** Measured: a > load of a module carrying a forward pre-hook, a forward hook and a backward hook > emits 2 records totalling 1600 bytes, and 1000 subsequent calls of the loaded > artifact emit 0 more bytes. The count is 2 rather than 3 because the forward and > backward wordings each name every hook kind in their group in one record, and the > GraphModule `__call__` is no longer one of them after this round's narrowing -- > three records now needs a module that both overrides `__call__` for real and > carries both hook kinds. The emission is per `deserialize`, not per call, so a > serving loop that loads once and serves many times pays it once; `warn_once` > would buy nothing there and would cost the thing the tests pin, that a hook > present only in the loading process is reported in that process too. > **FAQ: the three-leg backward assertion calls `redirected.aot_compile(...)` > three times on the same object relying on the first two raising and the third > succeeding -- wouldn't a `torch._dynamo.reset()` between legs make the third > leg's success attributable to the context manager rather than to accumulated > Dynamo state?** Measured in both directions, and no state is doing any work. > Leg 3 alone in a fresh process, with no preceding legs at all, succeeds and > its artifact reproduces eager's hooked gradient (`LEG3 STANDALONE SUCCEEDS: > True`, `grad matches eager: True`), so the context manager is sufficient on > its own. Reversing the order -- the context-manager leg first, then the two > refusal legs on the same `redirected` -- both refusal legs still raise > `Module-level backwards hooks require compiled autograd`, so a successful > capture leaves nothing behind that lifts the refusal either. A `reset()` > between legs would change no observed outcome. > **FAQ: `test_aot_compile_module_capture_warns_about_the_traced_module` > asserts `len(logs.output) == 1` on the whole logger unlike its siblings which > filter by substring first -- shouldn't it filter the same way so an unrelated > `torch._dynamo.aot_compile` warning added later doesn't fail it with a > confusing diff?** The diff was confusing, and that half is fixed; the filter > is declined. Measured by adding a stray `log.warning` to > `aot_compile_module`: the failure read only `Expected 1 but got 2`, because > PyTorch's `assertEqual` appends the `msg` argument only `if isinstance(msg, > str)` (`common_utils.py:4959`) and `logs.output` is a list, so the records > were dropped. Joining them restores it -- the same mutation now prints > `SOME UNRELATED FUTURE WARNING` and the `ScaleModule has forward hooks` > record verbatim. Filtering instead would give up what the total count is > for: this is the only assertion in the file that the capture path is > otherwise quiet, and it is not redundant with the substring check, since > warning about the wrapper rather than the module it wraps also emits exactly > one record (measured: `OptimizedModule overrides __call__`, with no hook > record, because the wrapper carries 0 forward hooks and 0 pre-hooks). > **FAQ: `ParameterList`/`ParameterDict` override `__call__` to raise > unconditionally, so warning that the result "may differ from eager" for a > module that cannot be called at all is noise -- should the probe skip them > too?** Declined, and unlike the GraphModule case the warning is not wrong > here: eager dispatch really does reach `ParameterList.__call__` > (`container.py:796`), so the type lookup reports a genuine override. What > makes it moot is measurable -- the module cannot be AOT compiled either: > `torch.compile(ParameterList([...]))._aot_compile([...])` raises > `Unsupported: Observed exception` off `Module.forward`, so no artifact ever > exists for the warning's claim to be wrong about. Excluding the two > classes by name would add a special case that only ever fires on a path that > is already an error, whereas the GraphModule narrowing removes a claim that > is false about a module that captures, loads and answers correctly. > **FAQ: `assertIn("takes only the forward arguments", naming[0])` cannot > fail -- that substring is a fixed literal inside the module-level > `_REDIRECT_CALL` which all three warnings emit unconditionally, so it pins > nothing about conditionality, and the two `"with the module as its first > argument"` assertions have the same shape; shouldn't they be replaced with > something branch-dependent?** Measured, all three do fail, under exactly > the drift they exist for. Deleting the clause's qualification tail fails > the first one (`AssertionError: 'takes only the forward arguments' not > found in '...call the artifact it returns with the module as its first > argument'`), and rewording the leading clause to "with the module first" > fails the other two -- all four parametrized hook legs plus the override > test (`FAILED (failures=4)` and `FAILED (failures=1)`). What they pin is > the wording of advice a caller follows verbatim, which is the part that > rots. Conditionality is pinned separately in the same test, by the > `wrap_top_frame` capture whose artifact raises `GuardManager check failed` > when called with the module first, and this round adds the half that > really was missing: that the branch is chosen by the FILE `forward` is > DEFINED in (`OptimizedModule._forward_has_skip_rule`, > `eval_frame.py:492-495`). Measured, that is `True` for `nn.Linear`, `True` > for a user subclass that inherits `forward` and `False` for one that > overrides it, and the artifacts agree: the inheriting subclass's takes > only the forward arguments and refuses the module-first call, the > overriding one's is the other way round. > **FAQ: `issubclass(type(model), getattr(fx_wrapper, "cls", type(None)))` closes > the post-hoc `__class__`-swap hole in the `__call__` probe -- why wasn't that > one-liner taken?** Because measured, it does not close it. With exactly that > substitution, a traced `nn.Linear` whose `weight` is then parametrized -- which > is where `parametrize.py:384-386` rebinds `__class__` to a direct subclass -- > still emits `ParametrizedLinear overrides __call__`, so the new test leg fails > the same way it does unfixed. The entry test was never the whole problem: the > body walked `type(model).__mro__[1:]`, and after the swap the class FX wrapped is > no longer element 0 of that MRO but element 1, so the walk finds `call_wrapped` > on it anyway. The probe now walks the whole MRO and skips every class whose own > `__call__` is the wrapper FX's `graph_module.py` installs (`call_wrapped`, > `:1007-1010`) while its `_WrappedCall.cls_call` (`:453-456`) is `None`, which > survives the swap, survives a `recompile()` after it (which puts a second wrapper > class on the MRO), keeps a `__call__` assigned onto the per-instance class > visible, and also keeps a real override sitting AHEAD of those classes visible -- > the wrapper base that `_fsdp_init.py:426-427` and `replicate.py:247` put there > (`parametrize.py:384-386` subclasses the traced class directly, so its leg is > silent because the FX class survives as MRO element 1, not because a wrapper sits > ahead). Your `issubclass` relation is kept as an assertion in the test, pinning > the shape the swap produces. > **FAQ: `test_aot_compile_module_redirect_arg_clause_is_conditional` captures > without the `_hide_leaked_dynamo_globals()` its siblings call, so it leaks > Dynamo's generated globals into the test module dict -- masked today, but > shouldn't the call be added for consistency?** Declined, and measured rather than > assumed. The test does leak, 6 minted names, but so does nearly every capture in > this file: 68 of the 89 test methods that capture do not hide first (58 of 80 in > the parent), so hiding is not a convention this test departs from. It is what a > test that asserts an exact minted-global set does FOR ITSELF -- the helper pops > the live minted names for the duration of the test and restores them in cleanup > (`test_aot_compile.py:1719`) -- so those tests are correct no matter who ran > before them. Run in one process, the redirect test leaks its 6 names and both > exact-set tests then pass, leaking 4 and 2 of their own. Even the sibling's call > is not load-bearing: deleting it and running the whole file gives `Ran 163 tests > ... OK (skipped=6)`. A line that changes no outcome anywhere, and that cannot > protect a future exact-set test which fails to hide for itself, is not worth > adding. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #196819 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #196767, #196817, #196815, #196816, #196818
…oks (#196820) Tests only. The first pair covers a module artifact loaded with a live guard scope, which splits the artifact's behaviour in two: the snapshot the bytecode reads is taken at load, while the dict the guards resolve against is the loading process's own. Each half is a silent-wrong-answer risk if it regresses, so each is pinned, in the order the tests appear, along with the residual gap the first half leaves -- a global rebound after the load, which the snapshot goes on serving unless a guard on its value refuses the call. The second pair pins two properties of #196819's dropped-hook warning that nothing checks: a hook registered after the load, whose silence its docstring documents, and the once-per-model rather than once-per-ModelInput shape of the warning, which a single-input test cannot tell apart. What they share is the shape of what they cover, a residual gap each of the two commits below chose to document rather than close, which is too little to carry a commit of its own, so the subject names both rather than pretending to one. One half is that the compiled bytecode reads the live scope rather than the globals serialized at capture: the load resolves the scope from `model.forward` and passes it as the guard scope, then merges the guarded names that scope binds -- the recorded builtins-dict key aside, which is excluded by name whether or not a guard reads it -- over the scope rebuilt from the artifact, so an artifact loaded after a global was rebound serves the rebound value. The merge is a snapshot taken when the artifact is rebuilt at load, not at capture, which is why a rebind BEFORE the load is followed while one AFTER it is caught only by a guard on the value -- and a kept `TENSOR_MATCH` checks metadata, not values, so the rebind this test makes after the load, to the same tensor scaled by three, is served from the snapshot; changing the dtype is refused rather than answered wrongly, by the guard on that global, which the assertion names so that an unrelated dtype check cannot stand in for it. That residual gap is the same one an `f_globals` load has; it is a known limitation rather than a goal, and the test documents it as such. It only exists to be documented because the capture passes `keep_global_guards`: under the default filter there is no global guard on the weight at all, so the mechanism the test describes would not be there. The capture-time weight is deliberately not the identity, since with `eye(3)` the assertion cannot tell "read the serialized weight" from "the matmul was dropped", and the test asserts the capture-time and live products differ before it demands that the reload return the live one. The other half is that guards read the loading process's scope dict by reference, so a global rebound after the load redirects dispatch on the next call: a copy taken at load time would go on serving whichever graph matched then, with no error. The global there is a NAME this module rebinds, not a mutated container: a mutation is visible through a copy of the scope just as well, so only a rebind can tell a shared dict from a copied one. Every test here captures and loads in this process, whose module dict is the scope the guards resolve to, so each hides the globals a capture seeds there, as the function-path twin already does. The dropped-hook pair is the same treatment applied to #196819's residual gap: `deserialize` warns about the hooks a module carries when it is loaded, and its docstring says one registered afterwards is dropped without a warning. The docstring documents that silence, but nothing pins it. A test now does, from both sides -- no warning is emitted, and the artifact keeps serving the unhooked answer while the module it holds does not in eager -- so the cost of the silence is on the record rather than resting on the docstring. The warning's other property is that it is once per model, not once per `ModelInput`: `_warn_dropped_module_dispatch` runs ahead of the per-`ModelInput` loop on the capture path and once per `deserialize` on the load path, so a capture of two inputs still emits one paragraph. #196819's parametrized test pins one record per path with a single input, which cannot tell the two apart, so a test with two inputs asserts the compiled-result count next to the warning count, the same way the sibling fallback-scope warning is pinned. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_aot_compile_module_reload_reads_the_live_global python test/dynamo/test_aot_compile.py -k test_aot_compile_module_guards_track_rebound_global python test/dynamo/test_aot_compile.py -k test_aot_compile_module_after_load_hook_is_silently_dropped python test/dynamo/test_aot_compile.py -k test_aot_compile_module_hook_warning_fires_once ``` Authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]> ## FAQ > FAQ: why keep `AOT_HERMETIC_WEIGHT` / `HermeticModule` when nothing about these > tests is hermetic? The criticism of the name is fair -- what the fixture pins is > that a loaded artifact reads the LIVE global as of the load rather than the > sealed capture-time copy, so something like `AOT_LIVE_WEIGHT` would say it > better. The fixture is not local to this commit, though: commits above this one > reuse both names, including assertions on the literal report text > `[0] KeyError on G['AOT_HERMETIC_WEIGHT']`. Renaming in the commit that > introduces them therefore spans more than one commit's test hunks and rewrites > later commits' expected strings, for a naming preference that changes nothing > about what is covered. Nothing in the contract rests on the name: the comment > above the fixture says what it is for (a weight deliberately not the identity, so > "read the serialized weight" and "the matmul was dropped" cannot produce the same > tensor), and the tests that use it spell out which global they rebind and when. > Once the stack lands, the rename is a mechanical follow-up that can touch every > site in one commit. > FAQ: the first leg of `test_aot_compile_module_reload_reads_the_live_global` -- > rebind before the load, then assert the live value -- is already covered by > `test_aot_compile_module_only_the_guarded_global_is_read_live` below; why re-argue > it instead of referring to it? Because what the leg contributes here is not the > detector, it is the baseline the two post-load legs are read against. Measured: > with the live substitution disabled (`extra_globals` rebuilt without `**live`) the > sibling fails, this leg fails, and with the leg's own `assertEqual` deleted the > test still fails one line lower, at the second leg -- so as a detector the leg is > redundant. What is not redundant is its setup: the second leg's expected value IS > `live`, the product of a rebind made before the load, and the third leg's dtype > refusal rebinds that same name; a reference cannot supply a local expectation. The > sibling also establishes the fact under a different filter -- > `keep_tensor_guards_unsafe`, one guarded global and one unguarded Parameter -- > than the `keep_global_guards` this test uses, so pointing at it would ask the > reader to re-derive that the mechanism is the same one. The cost of keeping it is > one assertion line. > FAQ: `_guard_source_globals` no longer asks what a source is ROOTED at -- it > requires the guard's own source to BE a `GlobalSource` -- so isn't "the only kept > global guard is rooted at `AOT_HERMETIC_WEIGHT`" stale vocabulary? No: that > sentence is the justification for the clause before its colon, "the load seeds > nothing into it", and the seeding gate is root-keyed on purpose. > `_seed_guard_scope` computes `roots = {get_global_source_name(source) for source > in sources + guard_on_key_order}` and returns early unless the builtins-dict key > is in it, and the comment above that gate says it "stays wide where > `_guard_source_globals` cannot be"; the alias half gates on a name in the pruned > `global_scope`. Root is in fact the only vocabulary under which the sentence > excludes anything: on a capture that does arm the seeding (`keep_builtin_guards`) > the guard that arms it is > `DictGetItemSource(base=GlobalSource('__builtins_dict___0'), index='len')`, and > no guard's source IS `GlobalSource('__builtins_dict___0')` -- so an "is" reading > would be vacuous there. For this test both readings hold anyway: the kept guard's > source is the bare `GlobalSource('AOT_HERMETIC_WEIGHT')`, the only global name in > `roots` is `AOT_HERMETIC_WEIGHT` (its other members are `None`, from the > `LocalSource`/`GlobalStateSource`/`ShapeEnvSource` guards), and an instrumented > `_seed_guard_scope` adds nothing and rebinds nothing on a scope that is this > module's own `globals()`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #196820 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #196767, #196817, #196815, #196816, #196818, #196819
…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
`CompilePackage._install_global` appended every name it wrote to
`_installed_globals`, and `uninstall()` pops every recorded name. So the
bookkeeping recorded which names the package TOUCHED but never which of them it
CREATED, and uninstall deleted bindings the package had merely overwritten:
```python
def _install_global(self, module, name, value):
CleanupHook.disown(module.__dict__, name)
module.__dict__[name] = value
self._installed_globals.setdefault(module, []).append(name) # recorded whether or not it was already bound
```
That is reachable, and the loss is permanent. `AOTCompiledFunction._seed_guard_scope`
seeds the recorded `__import_*` aliases a kept guard is rooted at into the live
module scope those guards then resolve against BY REFERENCE, and deliberately
leaves an already-bound name alone. A `CompilePackage` that installs the same
alias into the same module afterwards is not the binding's owner, but
`uninstall()` deleted it anyway, and nothing re-seeds:
```python
# mypkg/model.py defines M, whose forward calls a child module, so a kept guard is rooted at
# G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks
loaded = torch.compiler.load_compiled_function(f, f_globals=vars(mypkg.model))
"__import_torch_dot_nn_dot_modules_dot_module" in vars(mypkg.model) # True: the load seeded it
loaded(x) # serves
pkg.install(backends) # a package for another function traced in mypkg.model installs the same
# alias: the identical module object, but the name was RECORDED
pkg.uninstall() # popped it
loaded(x)
# RuntimeError: GuardManager check failed, reason: ...
# KeyError on G['__import_torch_dot_nn_dot_modules_dot_module']
# on every call from now on: the guards read the dict live and nothing puts the alias back
```
## The fix: an ownership token, scoped to the aliases
The fix is in the bookkeeping rather than in `uninstall()`: `_install_global`
grows a `record_only_if_new` flag, and the alias loop in `install()` is its one
caller. For those names it reads the module dict before it writes and records
the name only when it was absent, so uninstall pops exactly the aliases this
package created:
```python
def _install_global(self, module, name, value, *, record_only_if_new=False):
CleanupHook.disown(module.__dict__, name)
record = not (record_only_if_new and name in module.__dict__) # read BEFORE the write
module.__dict__[name] = value
if record:
self._installed_globals.setdefault(module, []).append(name)
# install(): the one caller
for alias, module_name in entry.import_sources.items():
self._install_global(module, alias, importlib.import_module(module_name), record_only_if_new=True)
```
The write itself and the `CleanupHook.disown` call above it are unchanged:
taking over the binding is still right, and for an alias the value being
installed is the identical module object anyway. `disown` only drops a stale
hook's claim on the name, never the binding, so reading the dict after it is
correct.
Gating EVERY install is the obvious reading and it is wrong. A package installs
into the very module its trace ran in, so wherever that trace's own bindings
are still live, the code and backend globals `install()` is about to mint are
already bound:
```python
compiled = torch.compile(fn)(x) # the trace binds __compiled_fn_0, __resume_at_*, ... in vars(mypkg.model)
pkg.save(...); pkg = load(...) # same process, no reset() in between to collect them
pkg.install(backends) # gated everywhere: every name is already bound, NONE is recorded
pkg.uninstall() # removes nothing at all
```
Aliases are the only names anyone else can bind first, and the only names both
`install()` records and `_seed_guard_scope` writes (the builtins-dict key both
also write bypasses `_install_global` and is never recorded), so they are the
only names that need the check. `install()`'s builtins-dict branch writes
`runtime_global_scope[builtin_dict_name]` directly rather than through
`_install_global`, so that key was already never removed by `uninstall()` and
is unaffected.
## What changes in-process, and what is deliberately left alone
First binder owns the alias, which also changes an in-process case: a trace
leaves its own `__import_*` aliases bound in the module, so a package installed
in that same process no longer records them and no longer removes them on
uninstall. The next install overwrites the values, so nothing goes stale.
The reverse direction is deliberately not addressed here. If the PACKAGE binds
an alias first and a later artifact load piggybacks on that binding,
`uninstall()` still removes it and every call into the loaded artifact then
fails with the same `KeyError`:
```python
pkg.install(backends) # the package binds the alias first, and records it
loaded = load_compiled_function(f, f_globals=vars(mypkg.model)) # seeding finds it bound, leaves it, guards hold it
pkg.uninstall() # pops it
loaded(x) # KeyError on G['__import_...'] again
```
Distinguishing that from ordinary package cleanup needs refcounting across
owners, which is a larger change than the bug in front of us.
Never recording an alias at all would cover both orders with no refcounting,
and that is the trade deliberately not taken. `install()` writes into a USER
module's live `__dict__` and `uninstall()` is the only thing that ever takes
those names back out, so a package that records none of its aliases can only
ever add to that namespace (measured, the helper module the new test traces
keeps five permanent `__import_*` names, not one). The leftover is not inert
either, because it is the binding every later owner defers to: a load seeds an
alias only into a scope that does not already bind it, so an alias one package
leaks is the object every later load into that module inherits in place of the
one it would have seeded. Recording a name the package did not create is the
bug being fixed; refusing to record one it did create is the same inaccuracy
pointed the other way.
Test Plan:
```
python test/dynamo/test_package.py
python test/dynamo/test_aot_compile.py
```
The new case, which drives the real path end to end -- a helper module in a
temp file, an artifact saved with a `guard_filter_fn` that keeps global guards,
a fresh import of the helper so the alias starts unbound, a load that seeds it,
then a package install/uninstall cycle -- and then calls the artifact. It pins
both arms of the record: the seeded alias survives uninstall, and a second
cycle in another freshly imported module, where the alias is still unbound
when install() runs, has the package create the alias and uninstall() take it
back out. The backend ids go through the default `record_only_if_new=False`,
so they are recorded and removed either way, which pins the gate's scope
rather than a second arm of it.
```
python test/dynamo/test_package.py -k test_uninstall_keeps_a_global_it_did_not_bind
```
Both arms are proven load-bearing by mutation. Recording unconditionally
(`record = True`) fails at the post-uninstall assertion with
`AssertionError: '__import_torch_dot_nn_dot_modules_dot_module' not found in
{...}`, and calling the loaded artifact under that mutation reproduces the
`KeyError on G['__import_torch_dot_nn_dot_modules_dot_module']` guard failure
above. Never recording (`record = False`), which is what gating every install
degenerates to once the names are already bound, fails at the post-uninstall
`AssertionError: Set comparison failed: Items in the first set but not the
second: '__compiled_fn_3_741f6201_...'` -- the leak the alias-only gate avoids.
Never recording an ALIAS in particular (`record = not record_only_if_new`), an
alias the package itself minted leaking into a user module's namespace forever,
fails the second cycle's post-uninstall `AssertionError:
'__import_torch_dot_nn_dot_modules_dot_module' unexpectedly found in {...}`.
Without that second cycle the mutation passed all 75 tests in the file, which
is why it is there.
A `guard_filter_fn` that keeps global guards is load-bearing in the test rather
than decoration: under the default filter the serialized `global_scope` is
pruned to `__builtins_dict___N` alone, nothing is seeded, and the collision
cannot be constructed at all.
```
lintrunner --take RUFF,PYFMT torch/_dynamo/package.py test/dynamo/test_package.py
lintrunner --take PYREFLY torch/_dynamo/package.py
```
Authored with the assistance of Claude Code.
Co-Authored-By: Claude Opus 5 <[email protected]>
## FAQ
> **FAQ: The `guard_filter_fn` closure in the new test duplicates
> `keep_global_guards` in `test/dynamo/test_aot_compile.py:633-644` line for line
> -- keep one copy, not two.** The predicate is identical and the shared form does
> work: a scratch copy of this file with the closure at `:618-626` deleted and
> `keep_global_guards` imported instead passes, `Ran 1 test in 0.384s ... OK`, and
> it stays mutation-sensitive -- with `record_only_if_new` forced back to `False`
> it fails at the same line, `AssertionError:
> '__import_torch_dot_nn_dot_modules_dot_module' not found in {...}`. So this is
> not a vacuity argument; the cost is the import itself. `test/dynamo/__init__.py`
> exists, so pytest imports this file as `dynamo.test_package` with `test/dynamo`
> off `sys.path`, and the bare `from test_aot_compile import keep_global_guards`
> takes the whole file down at collection: `python -m pytest -q --collect-only` on
> that copy reports `ModuleNotFoundError: No module named 'test_aot_compile'` and
> `no tests collected, 1 error`, against `75 tests collected` for the file as
> written. Surviving both import modes needs the try/except relative guard the
> cross-file importers under `test/dynamo` carry --
> `test_inline_and_install.py:7-10` and `test_dynamic_shapes.py:10-34` re-derive
> test classes that way, and `test_global.py:15-18`,
> `test_nested_graph_breaks.py:11-14`, `test_ctx_manager.py:34-37` and
> `test_modules.py:37-40` import helpers -- so the precedent exists; this file's
> own convention is per-test closures, and the import would also converge nothing:
> `test_package.py` has five local `guard_filter_fn` closures (`:416`, `:654`,
> `:769`, `:1054`, `:1272`), and `:416`/`:1054`/`:1272` are already byte-identical
> to each other and predate this commit -- a per-test closure is this file's
> convention, and the triplicate in it is not what the dedup touches. The one
> module both files already import, `torch/_dynamo/testing.py`, ships in the wheel
> and holds no guard filter today; putting one there also means editing
> `test_aot_compile.py`, which this commit does not touch.
> **FAQ: The deferred reverse order should just be fixed by never recording an
> alias at all -- `record = not record_only_if_new` covers both orders with no
> refcounting and no leak beyond one extra dunder name in a user module's
> `__dict__` -- so what is the argument for keeping the removal?**
>
> Both halves of that measured out, and the argument is the leak, which is
> neither one name nor inert. The reverse order is real: driving it end to end
> (a package installs into a freshly imported helper module,
> `load_compiled_function` piggybacks on the alias it bound, then
> `uninstall()`) the call reports `RuntimeError: GuardManager check failed,
> reason: ... KeyError on G['__import_torch_dot_nn_dot_modules_dot_module']`,
> the same failure this commit fixes in the other order, and the mutation does
> fix it -- the alias survives uninstall and the loaded artifact returns the
> eager result. What it costs is that `install()` writes into a USER module's
> live `__dict__` (`torch/_dynamo/package.py:1303`,
> `sys.modules[entry.python_module]`) and `uninstall()` (`:1275-1277`) is the
> only thing that ever takes those names back out, so a package that records
> none of its aliases can only ever add to that namespace. Measured on the
> helper the new test traces, whose traced function is one `nn.Module` call:
> `aliases install() writes: 5`, and after an install/uninstall cycle under the
> mutation `names left in the user module after uninstall: 6` --
> `__import_torch`, `__import_torch_dot__dynamo_dot_graph_bytecode_inputs`,
> `__import_torch_dot__dynamo_dot_utils`,
> `__import_torch_dot_autograd_dot_profiler`,
> `__import_torch_dot_nn_dot_modules_dot_module`, plus the pre-existing
> `__builtins_dict___0` this commit already accounts for. Unmutated, the same
> script reports `names left in the user module after uninstall: 1`, that
> builtins key alone. The leftover is not inert either, because it is the
> binding every later owner defers to: `_seed_guard_scope` seeds an alias only
> into a scope that does not already bind it
> (`torch/_dynamo/aot_compile.py:758`), deliberately -- "A binding this process
> already had is left alone" (`:702`) -- and measured, a load into a scope
> where the alias is already bound leaves that value in place and reads the
> artifact's guards through it: with a stand-in module of the right `__name__`
> in the slot the load leaves it there and the call fails `getattr failed on
> source
> G['__import_torch_dot_nn_dot_modules_dot_module']._global_forward_hooks`. So
> an alias a package leaks is the object every later load into that module
> inherits in place of the one it would have seeded, and it is the right object
> only for as long as nothing rebinds `sys.modules` under it. Keeping the
> removal is what stops "first binder owns the alias" from degenerating into
> "the first package ever installed here owns it forever", and keeps the
> bookkeeping honest in both directions: recording a name the package did not
> create is the bug being fixed, and refusing to record one it did create is
> the same inaccuracy pointed the other way. The reverse order stays open for a
> change that can tell two owners apart, i.e. refcounting; the deferral in the
> body now carries this argument next to it.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: #196895
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196767, #196817, #196815, #196816, #196818, #196819, #196820, #196821
…ls too (#196904) A load re-derives the serialized `__builtins_dict___N` key over the live builtins whenever the value bound there is the artifact's own recording, because the guard rooted at that key is an ID_MATCH on a builtin and a pickle-filtered snapshot goes on passing after the builtin it read is rebound. But two dicts can be holding that recording, and only on the default path are they one: the guard scope, which the deserialized guard tree reads, and `fn.__globals__`, which is what the generated bytecode subscripts. ```python def fn(x): if isinstance(x, torch.Tensor): # BUILTIN_MATCH guard rooted at G['__builtins_dict___0'] return len # `len` survives into the bytecode: G['__builtins_dict___0']['len'] loaded = AOTCompiledFunction.deserialize(data) # default path loaded.fn.__globals__ is <guard scope> # True: one dict, one re-derive covers both ``` `_seed_guard_scope` visited only the guard scope. So every load whose scope is not `fn.__globals__` left the guards checking the live builtins while the bytecode went on reading the load-time recording: ```python load_compiled_function(f, f_globals=d) # guards read d, bytecode reads fn.__globals__ AOTCompiledFunction.deserialize(data, guard_globals=d) # same split AOTCompiledModel.deserialize(model, data) # the COMMON case: the guard scope is # model.forward.__globals__, and with no f_globals # forward_callable builds fn.__globals__ as a dict of its own scope[builtins_key] is builtins.__dict__ # True: the guards see live builtins loaded.fn.__globals__[builtins_key] is builtins.__dict__ # False: the bytecode still reads the recording ``` An artifact naming a builtin the loading process no longer has could then pass its guard check and serve a value out of the stale recording: the guard certified one dict and the code ran off another. ```python # the tracing process had builtins.aot_probe = os.getcwd; the loading process does not loaded(x) # parent: the bytecode reads G['__builtins_dict___0']['aot_probe'] from the RECORDING and returns os.getcwd # now: KeyError: 'aot_probe' out of the generated bytecode, exactly as on the default-path load ``` ## Iterate the scopes, derive each from its own `__builtins__` ```python scopes = [(guard_scope, where)] if self.fn.__globals__ is not guard_scope and snapshot is not None: scopes.append((self.fn.__globals__, "f_globals")) for scope, where in scopes: # every scope validated BEFORE anything is written bound = scope.get("__builtins__", builtins.__dict__) if not isinstance(bound, (dict, types.ModuleType)): raise TypeError(f"{where}['__builtins__'] must be a dict or a module, got {type(bound).__name__}") ... for scope, _ in scopes: if builtins_key in scope and (snapshot is None or scope[builtins_key] is not snapshot): continue # a binding this process chose stays if "__builtins__" not in scope: scope["__builtins__"] = builtins.__dict__ scope[builtins_key] = get_builtins_dict(scope) # from THIS scope's own __builtins__ ``` The re-derive now iterates the scopes rather than the one, adding `fn.__globals__` when it is a different object and there is a recording there to replace (it needs no `__builtins__` seeding of its own), and derives each scope's key from that scope's OWN `__builtins__`, so a guard-only scope still cannot rewire what the bytecode resolves. The identity test against the snapshot is unchanged: a caller who pre-bound the key in either dict keeps their choice. The `TypeError` naming which parameter a bad `__builtins__` arrived by is computed per scope, keeping the existing answer for the guard scope (where `load_compiled_function` forwards one dict as both and the public name wins, and a module's namespace is named `vars(<module>)`) and naming `f_globals` for the bytecode's, since that is the only parameter that reaches it. That second `TypeError` is a new refusal: ```python AOTCompiledFunction.deserialize(data, f_globals={"__builtins__": None}, guard_globals={}) # parent: loaded, serving off the recording with None still bound # now: TypeError: f_globals['__builtins__'] must be a dict or a module, got NoneType ``` ## Why a separate commit #196815 made this split reachable on its parent through `deserialize(..., guard_globals=)` and, once it forwards the caller's dict as both scopes, through `load_compiled_function` too, and the arm it added to `test_load_rederives_over_a_builtin_the_loading_process_lacks` pinned it as behaviour: live builtins in the caller's dict, the recording still in `fn.__globals__`. (The known limitation its docstring and guide name is a different divergence, a rebind the guards accept, which #196897 closes.) This is a separate commit because closing the split flips that arm, so the re-slice below stays reviewable as the re-slice it is. Test Plan: `test_load_rederives_a_builtins_key_bound_to_its_own_snapshot` gains the bytecode's side of both branches of the "key already bound" check: its caller-supplied-guard-scope arm now asserts `loaded.fn.__globals__[builtins_key] is builtins.__dict__` as well as that the caller's own binding survives in the guard scope, and a new arm loads the same bytes twice into one dict passed as both `f_globals` and `guard_globals` -- `forward_callable` lets `f_globals` override the recording, so the first load takes the derive branch and the second finds the key bound -- requiring the two to agree on what the bytecode reads. The last arm of `test_load_rederives_over_a_builtin_the_loading_process_lacks` asserted the divergence; it now pins the unified behaviour, raising `KeyError('aot_probe')` out of the generated bytecode exactly like the no-scope arm above it, since the builtin is genuinely gone on both sides. `test_aot_compile_module_load_rederives_the_key_the_bytecode_reads` pins the module path: a module whose forward returns `len` is captured under `keep_builtin_guards`, saved and loaded through `_load_aot_compiled_module`, and both the module namespace and `fn.__globals__` must bind the live builtins under the key. `test_load_refuses_a_non_dict_builtins_binding` gains a fourth arm, `deserialize(data, f_globals={"__builtins__": None}, guard_globals={})`, expecting the `f_globals`-named `TypeError`; its `fn` now returns `len` so the bytecode reads the key. The caller-chosen-guard-scope arm of `test_load_rederives_a_builtins_key_bound_to_its_own_snapshot` re-asserts the `fn.__globals__` identity after the call, pinning that `_serve`'s per-call re-read (#196897) leaves the key alone. With the parent's `aot_compile.py` the module test fails with `AssertionError: False is not true : the bytecode kept the recording on the module load path` (its module-dict assertion passes) and the fourth arm with `AssertionError: TypeError not raised`. ``` python test/dynamo/test_aot_compile.py -k test_aot_compile_module_load_rederives_the_key_the_bytecode_reads python test/dynamo/test_aot_compile.py -k test_load_refuses_a_non_dict_builtins_binding python test/dynamo/test_aot_compile.py python test/dynamo/test_package.py python test/dynamo/test_guard_serialization.py ``` `Ran 226 tests ... OK (skipped=6)`, `OK (skipped=40, expected failures=1)` and `Ran 143 tests ... OK (skipped=3)`, unchanged from the parent. The tests discriminate the change. Reverting only `aot_compile.py` and re-running the two: ``` git checkout HEAD~1 -- torch/_dynamo/aot_compile.py python test/dynamo/test_aot_compile.py -k test_load_rederives_a_builtins_key_bound_to_its_own_snapshot python test/dynamo/test_aot_compile.py -k test_load_rederives_over_a_builtin_the_loading_process_lacks git checkout HEAD -- torch/_dynamo/aot_compile.py ``` fails with `AssertionError: False is not true : the bytecode kept the snapshot under a caller-chosen guard scope` and `AssertionError: False is not true : the bytecode kept the recording under a caller-supplied f_globals`. Dropping the first of those assertions as well so the arms below it run, the two-loads arm fails on its first pass with `AssertionError: False is not true : the bytecode is reading a dict this load chose the order of`, and dropping the second leaves the rewritten divergence arm failing with `AssertionError: KeyError not raised` -- the parent serves `os.getcwd` there out of the recording. ``` lintrunner --take RUFF,PYFMT -- torch/_dynamo/aot_compile.py test/dynamo/test_aot_compile.py ``` reports `ok No lint issues.`, and no added line exceeds 88 columns. This change was authored with the assistance of an AI coding assistant. Co-Authored-By: Claude Opus 5 <[email protected]> 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #196904 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #196767, #196817, #196815, #196816, #196818, #196819, #196820, #196821, #196895
…falling through (#197055) `AOTCompiledModel.__call__` fell through to `compiled_results[0]` once every guard failed, so whether the caller saw an error at all turned on the order of the list: `compiled_results[0]` re-raised only because its guard check was still enabled, and had that one result opted out of guard checking it would have run instead. A match was not cheap either: `result()` re-entered `AOTCompiledFunction.__call__`, which bound the call and ran the guards `guard_check` had just passed, so a matching tree was bound and evaluated twice per call. Dispatch now has two explicit stages ahead of the fall-through: scan every result for a guard match, then re-check every result. Only a call neither stage serves reaches the parent's fall-through into `compiled_results[0]`, which is kept as it was: it raises the same `GuardManager check failed` error the parent raised unless `compiled_results[0]` opted out, in which case it runs, as it did at the parent. There is no behaviour change vs the parent on a no-match call. Measured on a two-input `ScaleModule` (float32 and float64) called with float16, each result's `fn` wrapped to record which one served, the parent and this commit give the same four rows: ``` [enabled, enabled] : RuntimeError: GuardManager check failed ... [enabled, opted_out] : RuntimeError: GuardManager check failed ... [opted_out, enabled] : SERVED by [0] [opted_out, opted_out] : SERVED by [0] ``` `test_module_dispatch_no_match_falls_through_to_the_first_result` pins three of those rows without a mock, on a two-input `ModeBranchGlobalModule` whose graphs differ (`x * 2` for `mode == 0`, `x * 3` for `mode == 1`) called with `mode=2`, so the number says which result answered: with nothing opted out the call raises `GuardManager check failed`, with `[0]` opted out it is served `[0]`'s `x * 2`, and with both opted out still `[0]`'s. The fourth row, `[enabled, opted_out]`, is the one the commit that honours an opt-out from any position changes from raise to serve; pinning it here as a raise would make that commit red on a test it has to rewrite, so it is measured above and pinned there, from the other side, as a serve. Honouring an opt-out from any position rather than from `compiled_results[0]` alone is a behaviour change and is that later commit's, with its own test and its own `## Behaviour change` statement; a report that names every compiled input replaces the fall-through later still. The scan cannot skip opted-out results even though they accept anything: guard evaluation happens regardless of the flag, so scanning them first still finds the right graph, and skipping them would reinstate the old fall-through when every result has opted out. On a match, the declared `fn` field is called directly rather than `result()`, which saves re-binding and re-evaluating the guards that just passed: one bind and one evaluation of a matching tree per call, where `result()` made two of each. `test_module_dispatch_evaluates_a_matching_tree_once` counts the `check()` calls dispatch makes on the matching tree and expects one; the parent makes two. Measured on this machine with the parent's dispatch replicated in the same process and the two timed interleaved (best of 15 x 2000 calls), a call matched at `compiled_results[0]` costs 23.3us against the parent's 29.4us, a match at `[1]` of two 28.2us against 34.1us, and a match at the fourth of four inputs 32.9us against 38.9us. Each result is bound on its own, ahead of its guards, and the binding is kept for the re-check. The bind is the first thing the scan does, so a call the signature cannot bind is left alone: it still surfaces as a `TypeError`, as the plain module call would -- the type matches, though the message is `inspect`'s rather than `nn.Module`'s -- instead of a guard error about a call the guards never saw. The test for it sits with the commit that first moves the guard check inside a `try`, where its placement could break it. Because `compiled_results` is a public list the docs teach callers to index into, a call reads it once: `__call__` snapshots `results = tuple(self.compiled_results)` before anything else and both stages iterate the snapshot, so the re-check pairs every result with the binding the scan made for it and never reaches a result the scan did not bind. `test_module_dispatch_judges_only_the_results_a_call_began_with` makes `[0]`'s `check()` splice in a `[1]` that matches the call: with the snapshot that call falls through and raises and the next call serves `[1]`; a scan over the live list serves `[1]` on the same call. The re-check is what keeps the fall-through last, and it exists for exactly one exit of `check()`. In `GuardManager::check_nopybind` (guards.cpp) a tag-safe root whose recorded dict tags and tensor metadata still match runs `check_no_tensor_aliasing_guards_fast`, and when that answers false the node sets `_disable_dict_tag_matching` and returns false before `check_nopybind_template` runs; that is the only path on which a false is not the tree's answer about the call. The fast path's other exits -- a tag or tensor-metadata mismatch, the cap on recorded pointers -- set the same flag and fall out of the `if` into the tree, so their false is genuine. The flag is a per-`GuardManager` member that nothing resets (`= false` at its declaration is the default initializer; every other write sets it true), so a second `check()` runs the tree the fast path skipped, and a sibling tag-safe root the first pass never reached stays armed and can still answer from its own fast path. Tag-safe roots exist only under `use_recursive_dict_tags_for_guards`, which `finalize()` gates `find_tag_safe_roots` on and which defaults to False. That rescue is exactly what the old fall-through got from re-entering `AOTCompiledFunction.__call__` on `compiled_results[0]`, here extended to every result, so nothing that used to be served is refused (`test_module_dispatch_serves_a_call_the_guard_tree_accepts`). Ordering matters more than it looks: an opted-out `compiled_results[0]` runs whatever the fall-through hands it, so without the re-check a call whose `[1]` was falsely rejected once is silently served `[0]`'s graph, compiled for a different call, in exactly the case the parent's fall-through got right because it re-checked `[0]` before it gave up; `test_module_dispatch_rechecks_before_honouring_an_opt_out` pins that. The re-check covers opted-out results too, and for the scan's reason: a scan `check()` that refused from the fast path is no more an answer about an opted-out tree than about an enabled one -- `check()` never reads the flag -- so with `[opted_out, opted_out]` and a false rejection of the second, skipping it falls through to the first one's graph over a tree whose guards genuinely fail; `test_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts` opts both results out and misses `[1]`'s global once. The three re-check tests force the false rejection with a `CountedKey` spliced into this module's globals that misses the guarded global once, and count the `check()` calls dispatch makes on `[1]`'s tree, expecting two: the scan's rejection and the re-check's acceptance. Under the default config no root is tag safe, so a first `check()` can only refuse after running the tree and the re-check re-runs trees that have genuinely failed. Two things follow that the code comment names. Whatever Python those trees run runs again: `LAMBDA_GUARD` closures and the root's `_epilogue_lambda_guards`. And a node that fails an evaluation adds one to its own `_fail_count` (in `check_leaf_guards_nopybind` and `check_accessors_nopybind`), which its parent's fail-fast sort orders accessors by, so a result that fails a no-match call through module dispatch counts that failure twice where a direct `AOTCompiledFunction.__call__` counts it once; both evaluations fail at the same node, so the double count changes how far that node rises, not which node fails. Such a tree still short-circuits at its first failing guard, so the second pass costs 3.2us for two results and 4.6us for four (the no-match call, which then raises, measures 32.6us and 43.7us here against 29.4us and 39.1us with the second pass deleted, and against the parent's 30.2us and 38.5us). Running `check_verbose` as the second pass, so that its answer could double as the failure's explanation, was rejected: an opted-out `compiled_results[0]` makes the guards fail on every call by construction, so dispatch ends at the fall-through serving it and no explanation is ever printed, and `check_verbose` costs about 2.7x a `check()` per tree (2.55us against 0.94us here). `guard_check` and the function path's `__call__` route their own `guard_manager` narrowing through the new `_live_guard_manager()` rather than restating it, and the dispatch reads its manager the same way. That moves one dead state: `__call__` asserted on a null `guard_manager` before it read `_guard_check_enabled`, so an artifact that had opted out raised there and now runs instead. `__post_init__` always populates the field -- only `serialize()` nulls it, and on a copy -- so reaching that state takes assigning the private field by hand, and both paths that do read the manager still raise. The module dispatch's semantics are documented in a docstring on `AOTCompiledModel` itself, where a reader who holds one finds them, as one paragraph later commits extend a sentence at a time. It says what each stage does and what the fall-through does when neither accepts: the call is handed to `compiled_results[0]` as a plain call of that function, which raises unless that one result opted out, in which case its graph runs for a call its guards refused; that is the only thing `disable_guard_check()` changes on this path, since `check()` never reads the flag and an opted-out result is scanned, re-checked and served in index order like any other. It names the one `check()` exit the re-check exists for, and it states that `compiled_results` must hold at least one result: `aot_compile_module` refuses an empty list, but neither the public constructor nor `deserialize` checks, and an empty list reaches the fall-through's `results[0]` as it did at the parent. The user guide is not touched. The three probe tests now start with `_hide_leaked_dynamo_globals()`, as the other compile tests in the class do, so they no longer leave Dynamo's synthetic globals in this module's dict. `_install_global_probe` registers both cleanups before it touches the dict, so an interrupt anywhere leaves the name restored, and its comment says why the probe must be installed after `_hide_leaked_dynamo_globals`, whose sweep calls str methods on every key. `CountedKey.__eq__` answers True for itself before it counts, so the probe's own cleanup pop does not rest on the dict's identity-first lookup. > **FAQ: Why does this commit leave the `disable_guard_check()` bullet of the > user guide alone?** An earlier version extended it to say the compiled > function "runs whatever it is called with, without evaluating its guards". > That is what the function path does, but `disable_guard_check()` is a method > on `AOTCompiledFunction`, which is what `compiled_results` holds, and on the > module path this commit defines an opted-out result's guards are evaluated > for dispatch, so the sentence was false for one of the two paths that share > the method. Scoping it to the function path would have to name module > dispatch, which the page does not document (`_aot_compile` is private and its > docstring says Experimental). The parent's bullet, "Disable runtime guard > validation (advanced use)", holds for both paths and stays; the module > semantics live in the class docstring. > **FAQ: Why is the re-check not gated on whether the tree has an armed > tag-safe root?** Recording the gate is cheap, granted: `find_tag_safe_roots` > materialises `tag_safe_roots` inside `finalize()`, so `bool(tag_safe_roots)` > is one attribute on `GuardManagerWrapper`, decided once. It is declined for > what it would buy and cost. It buys back 3.2us for two results and 4.6us for > four on a call that then raises (or, once a later commit honours an opt-out > from any position, runs a whole graph), and nothing on a match, which is the > call every model is built for. It would make dispatch's correctness rest on a > guards.cpp property read from Python -- "no tag-safe root means `check()` > never refuses without running the tree" -- where the ungated re-check is > correct whatever `check()` does; the gate would have to be re-derived every > time the fast path grows an exit, and the reader of this file cannot see > that. And the three re-check tests force a false rejection with a global > lookup that misses once, which needs no tag-safe root; a gate would skip the > re-check in exactly the configuration those tests run in, and pinning it > would then take a real dict-tag false rejection, which is not deterministic > to force. The code comment states instead that under the default config the > pass re-runs trees that genuinely failed, what that re-runs and double > counts, and that the cost is accepted. > **FAQ: Why does dispatch call `prepare_f_locals`, `_live_guard_manager()` and > `fn` itself rather than a method on `AOTCompiledFunction` for "run, guards > already verified"?** `fn` is that method: it is the declared field the > function path's `__call__` ends in (`return self.fn(*args, **kwargs)`), so a > second name for it would be a one-line wrapper. The bind and the check are > split because dispatch needs the binding after the check -- the re-check > judges the same binding, and the binding-cache commit two above shares one > binding across results -- so a method that hid the split would have to hand > the binding back anyway; `prepare_f_locals` is the class's public method for > it, and `_live_guard_manager()` is the narrowing this commit adds so all > three readers of the field share one. The failure path, where > `_missing_global_hint()` lives, is still `AOTCompiledFunction.__call__`'s > alone and dispatch still reaches it, through the fall-through's > `results[0](...)`; only the success path is open-coded here, and it is one > line in both places. > **FAQ: Where did the shared binding go?** The version reviewed last bound a > call once and reused the binding across every result that binds alike, > behind a cached verdict about `compiled_results`' contents. That is a > performance change with a cross-thread publication protocol of its own, and > the review asked for it to be reviewed against a single question; it is the > binding-cache commit two above this one. Here every result binds on its own: > a bind (`inspect.Signature.bind` plus `apply_defaults`) costs 2.5us against > 0.9us for a `check()` on this machine, so a match at the fourth of four > inputs pays three binds more than it will once the binding-cache commit > lands. > **FAQ: Does `CountedKey` rest on CPython dict internals?** On two documented > behaviours, and on nothing about operand order. `str.__eq__` returns > `NotImplemented` for a non-str, so `CountedKey.__eq__` runs whichever side > the dict puts the stored key on (measured: `"k" == CountedKey("k", 1)` counts > one comparison and answers False, the same as the reverse). The cleanup's > `g.pop(probe, None)` finds the probe by identity, which `__eq__` now also > answers True for, so it no longer rests on the lookup's identity-first > order. And `check.call_count == 2` does not encode how many guards read the > global: a lookup that misses fails the tree wherever it sits, so each > `check()` consumes exactly one miss -- with `misses=2` the same model makes > two `check()` calls on `[1]`, both refused, and the call raises from the > fall-through (measured: `calls=2 compares=2 RAISED`, against `calls=2 > compares=2 SERVED` at `misses=1`). A one-shot in place of the counter is > declined because the commit that replaces the fall-through with a report > uses `misses=2` to pin that the report's `check_verbose` is the third and > last evaluation. > **FAQ: Why does `aot_compile_forward` take a `forward` and rebind it when the > two calls here pass `ScaleModule.forward`?** The parameter compiles one > module for a forward other than its class's, which is how the commits above > assemble models whose results bind differently (a closure cell, a `mode` > default); at this commit both calls pass the class forward, so the rebind is > to itself, and the helper's comment says so. The helper is shared with those > commits, so it is kept in the shape they call it in rather than inlined here > and re-added above. `keep_global_guards` is another module-level helper > without an underscore in this file, so the naming follows that. > **FAQ: Why do the tests count `check()` calls rather than reads of the > guarded global?** An earlier version counted the comparisons a `CountedKey` > spliced into `globals()` saw, and asserted exact counts. Those counts were > right only because CPython's dict lookup compares keys by identity before > `__eq__`, and they encoded how many times the current guard tree happens to > read one global, so a change of tree shape would have broken them without > saying what regressed. The counts now wrap `check` on the result's > `GuardManagerWrapper` (`patch.object(manager, "check", wraps=...)`) and > measure dispatch's calls directly; `CountedKey` remains only where a false > rejection has to be forced, answering False to the first `misses` > comparisons. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_module_dispatch_evaluates_a_matching_tree_once python test/dynamo/test_aot_compile.py -k test_module_dispatch_judges_only_the_results_a_call_began_with python test/dynamo/test_aot_compile.py -k test_module_dispatch_serves_a_call_the_guard_tree_accepts python test/dynamo/test_aot_compile.py -k test_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts python test/dynamo/test_aot_compile.py -k test_module_dispatch_rechecks_before_honouring_an_opt_out python test/dynamo/test_aot_compile.py -k test_module_dispatch_no_match_falls_through_to_the_first_result python test/dynamo/test_aot_compile.py lintrunner --take RUFF,PYFMT test/dynamo/test_aot_compile.py torch/_dynamo/aot_compile.py ``` This commit adds 6 `test_module_dispatch_*` tests, the last parametrized over three opt-out rows; the full file runs 172 tests and passes (6 skipped) where the parent runs 164. The first 5 fail at the parent, i.e. with the parent's `torch/_dynamo/aot_compile.py` under this commit's test file: the counted `check()` test with `Absolute difference: 1` (two calls where one is expected), the mid-call splice test with `RuntimeError not raised` (the live list served the spliced-in result on the same call), the fast-path rescue test with `GuardManager check failed` raised where `[1]` should have been served, and the two re-check ordering tests with `Mismatched elements: 9 / 9` (`[0]`'s `x * 2` served). The three no-match rows pass at the parent, which is what they pin. All 8 also pass with `torch._dynamo.config.use_recursive_dict_tags_for_guards = True` set for the run, so no asserted count depends on the flag being off. Lint is clean. Mutation controls, each run against the 8 tests at this commit and each failing only the tests named: calling `result()` in the scan instead of `result.fn` fails the counted `check()` test with `Absolute difference: 1`; deleting the re-check loop fails the fast-path rescue test (the fall-through raises `GuardManager check failed`) and both re-check ordering tests (`Mismatched elements: 9 / 9`); skipping opted-out results in the re-check fails `test_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts` alone; reading the live list instead of the tuple snapshot fails the mid-call splice test with `RuntimeError not raised`; falling through into `results[-1]` instead of `results[0]` fails the no-match rows with `[0]` opted out (`GuardManager check failed` from the enabled `[1]`) and with both opted out (`Mismatched elements: 9 / 9`, `[1]`'s `x * 3`) while the all-enabled row still raises. The microsecond figures above were measured in one sitting on a shared machine, the parent's dispatch replicated in the same process and timed interleaved with this commit's. Authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #197055 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #196767, #196817, #196815, #196816, #196818, #196819, #196820, #196821, #196895, #196904
…196824) Tests only, for the last-resort stage of the dispatch the previous commit rewrote. `disable_guard_check()` is the escape hatch for an artifact whose guards fail on the serving machine, and where an opted-out result sits in the three-stage ordering decides answers that are wrong-answer bugs with no error raised if the stages slip. Every case below is built so that the wrong stage order returns a different NUMBER and nothing else. ## The fixture: same shapes, same dtypes, different numbers ```python GLOBAL_POOLING_CONFIG = {"pooling": "sum"} class GlobalConfigModule(torch.nn.Module): def forward(self, x): if GLOBAL_POOLING_CONFIG["pooling"] == "sum": return x.sum(1) return x.mean(1) * 10.0 model._aot_compile([ ModelInput(args=(x,), kwargs={}, contexts=[_set_pooling("sum")]), # compiled_results[0] ModelInput(args=(x,), kwargs={}, contexts=[_set_pooling("mean")]), # compiled_results[1] ]) ``` Both graphs accept a `(4, 8)` float tensor and differ only in what they return, so a dispatch that picks the wrong one raises nothing and only `assertEqual` against eager notices. Whether the global is GUARDED depends on the filter: `keep_global_guards` keeps it, so each result matches only under its own mode; the default filter drops it, so both results accept every call. ## Opting out changes what a result accepts, not where it sits `test_aot_compile_module_opted_out_result_keeps_its_place_in_the_scan` uses the default filter, so both trees pass, opts out `[0]`, and calls under the mode `[1]` was traced for: ```python with _set_pooling("mean"): assert results[0].guard_check(mod, x) and results[1].guard_check(mod, x) results[0].disable_guard_check() model(x) == expected["sum"] # [0] served: the first accepting result in INDEX order ``` A dispatch that consults the checked results first, or holds the opted-out ones back for the passes below, serves `[1]` instead, the graph the process global would pick, so nothing but the number says which result answered. Only a mix of one opted-out and one checked result can see that: with none or all opted out, putting the checked results first reorders nothing, and holding the opted-out ones back is what the dispatch commit's `test_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts` already fails on. Every other flag vector's case coincides with one of those two tests, so this is the one case in the file that a mixed vector pins. ## The scan outranks the opt-out, and the last resort serves the first opt-out `test_aot_compile_module_opted_out_result_is_the_last_resort` uses `keep_global_guards`, so each result matches only its own mode: ```python results[0].disable_guard_check() # [0] = sum, opted out with _set_pooling("mean"): model(x) == expected["mean"] # [1]'s guards genuinely pass, so the scan serves [1] results[1].disable_guard_check() # both opted out with _set_pooling("other"): # neither tree passes model(x) == expected["sum"] # the last resort serves the FIRST opted-out result ``` The first arm is the wrong-answer bug if the opt-out is consulted before the real guard checks: `[0]` would serve the first artifact for a call the second was compiled for, same shapes, same dtypes, different numbers. The second arm pins that the last resort is itself ordered: a call no artifact guards gets the graph the earliest opted-out `ModelInput` was traced for. Both cases coincide with the `compiled_results[0]` fall-through the parent replaced, since the result they opt out first IS `compiled_results[0]`, so the test pins the ordering against future reordering rather than regressing the rewrite. A scan that skipped opted-out results is not one of them, for two different reasons: in the first arm the result that must serve is the CHECKED one, which the skip never applies to, so it is served by the scan itself and the second pass is never reached; in the second both trees fail the call anyway and the answer this ordering demands is the first opted-out result, which the last resort serves either way. What tells a skipping scan apart is an opted-out result whose tree the scan would accept: the keeps-its-place test above pins that with honest guards, and the dispatch commit's re-check test covers the false-rejection variant. ## What the escape hatch costs `test_aot_compile_module_disable_guard_check` drives the opt-out through `requires_grad`, which is part of `TENSOR_MATCH`, so the artifact recorded for `requires_grad=False` genuinely cannot match the call: ```python model = torch.compile(ScaleModule(), fullgraph=True, backend="aot_eager") model._aot_compile([ModelInput(args=(torch.randn(3, 3),), kwargs={}, contexts=[])]) x = torch.randn(3, 3, requires_grad=True) model(x) # RuntimeError: ... requires_grad mismatch model.forward.compiled_results[0].disable_guard_check() out = model(x) # served anyway: that is the escape hatch out == x.detach() * 2 and not out.requires_grad # and it is an INFERENCE graph: no grad history ``` It asserts what the opt-out COSTS rather than what it buys: with the guard that would have rejected a `requires_grad=True` call disabled, dispatch serves an inference graph that aot_autograd's runtime wrapper runs with grad disabled, so the caller silently gets a result with no grad history. The expected value is detached for that reason, since `assertEqual` does not compare `requires_grad` and the tensor the call was made with does carry it. That is why this one test compiles with `aot_eager` instead of the `eager` the ordering tests use: an eager backend installs no such wrapper and would still record the grad history. It does not discriminate against the pre-rewrite fall-through, since the result it opts out is again `compiled_results[0]` and `AOTCompiledFunction.__call__` short-circuits on the very same flag and serves the very same graph, so what it is separated for is that its failure mode is loud: lose the opt-out stage and the call reports "No AOT compiled graph matched" instead of answering wrongly, which also keeps either direction of drift visible, a change that starts handing back a differentiable result and a change that starts refusing the call the opt-out was asked to allow. ## What is deliberately not duplicated here Every case above opts out `compiled_results[0]` first, so a last resort that read that one result instead of walking to the first that opted out satisfies all of them. That walk, `[1]` opted out with `[0]` still checked and a call neither artifact guards, served by `[1]` where reading `compiled_results[0]` would refuse it with a no-match report, is pinned by the parent's `test_module_dispatch_serves_an_opted_out_result_from_any_position`, in the commit that introduces the loop. A copy of it here under `keep_global_guards` was the same experiment on the dispatch axis (no edit to the three stages separates the two), and the axis it did add, a rejection from a global guard, is already what `test_aot_compile_module_dispatches_on_global_guard` and `test_module_dispatch_evaluates_a_matching_tree_once` fail on when the pooling guard is dropped, so it was removed rather than kept with a uniqueness claim it could not make. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_aot_compile_module_disable_guard_check python test/dynamo/test_aot_compile.py -k test_aot_compile_module_opted_out_result_keeps_its_place_in_the_scan python test/dynamo/test_aot_compile.py -k test_aot_compile_module_opted_out_result_is_the_last_resort ``` Authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]> ## FAQ > **FAQ: The review asked for the missing last-resort case to be folded into > `test_aot_compile_module_opted_out_result_is_the_last_resort` by reordering its > assertions so the first opt-out is `[1]`. Why is it a separate test?** > > Because the existing test's value is that all of its ordering assertions run > against one capture in one order, and the case that was missing does not belong > to that sequence: it is the only one that discriminates against reading > `compiled_results[0]` instead of walking to the first result that opted out, and > it needs `[0]` to still be checked while `[1]` is not -- the opposite of the > state the ordering cases share. Reordering to make room for it costs the first > ordering assertion its discrimination: with `[1]` opted out first, the call that > assertion makes is one the opted-out result itself guards, so an opt-out > consulted during the scan answers it correctly and the assertion passes anyway; > rewriting it around a call `[0]` guards restores the check. The separate test > states its own premise, keeps the ordering test's sequence intact, and fails > loudly (a no-match report where a graph should have been served) rather than > answering wrongly. > **FAQ: nothing pins the `continue` that made the second `check()` pass skip > opted-out results -- shouldn't there be a test?** There is now, and it is a fix > rather than a pin. This round's audit built the case the earlier answer here said > could not exist: both results opted out, the scan false-rejecting the one whose > guards match (a `CountedKey` with one scripted miss), and dispatch served the > FIRST opted-out result's graph for a call only the second matched -- wrong > numerics, nothing raised -- because the re-check skipped every opted-out result > and the last resort is ordered by index, not by guard. The skip is gone from > #196823, whose re-check now evaluates every result the scan rejected, and that > commit carries the test (asserting the served value and `compares == 2`, red with > the skip restored). The four ordering tests here are unchanged by the fix, > measured over the whole file. > **FAQ: The globals-probe swap in > `test_aot_compile_module_opted_out_result_waits_for_the_full_recheck` uses > `try`/`finally` where the file's three other `CountedKey` swaps use `addCleanup`; > the cleanup order is already correct, so match the sibling and drop the > `try`/`finally` -- a mechanical translation. Why keep it?** Moot: that test is > gone. A later pass showed every edit that reddened it also reddened one of its > two siblings (`test_module_dispatch_serves_a_call_the_guard_tree_accepts`, > neither result opted out, and > `test_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts`, both), > because all three walked the same dispatch path with a flag vector the correct > code ignores; its replacement, > `test_aot_compile_module_opted_out_result_keeps_its_place_in_the_scan`, pins the > one case a mixed vector can see -- an opted-out result whose guards genuinely > pass is served in index order, not after the checked results -- under the default > guard filter, and swaps no probe at all. The `try`/`finally`-versus-`addCleanup` > question therefore has no site left in this commit; the siblings that keep a > `CountedKey` are #196823's, and they use the form their own comments justify. > **FAQ: `test_aot_compile_module_last_resort_iterates_past_a_checked_result` > was the same experiment as the parent's > `test_module_dispatch_serves_an_opted_out_result_from_any_position` -- two > results, `[0]` checked, `[1]` opted out, a call neither guards, `[1]` served. > Fold or drop one?** > > Dropped, after one round of trying to keep it. On the dispatch axis the two > were the same test: no edit to the three stages reddens one and not the other. > The first attempt kept this copy with a comment claiming a guard-filter axis > of its own, and that comment was wrong twice over -- `_guard_source_globals` > cannot drop a guard at all (it only picks live global values for a rebuilt > bytecode's globals, behind a gate this in-process test never reaches), and a > filter regression that dropped the pooling guard already reddens > `test_aot_compile_module_dispatches_on_global_guard` and > `test_module_dispatch_evaluates_a_matching_tree_once`. The walk past a > still-checked result stays pinned where the loop is introduced, in the parent > commit. > **FAQ: The comment on > `test_aot_compile_module_opted_out_result_is_the_last_resort` said a scan that > skipped opted-out results is not pinned because "the second pass re-checks > them and recovers the graph"; neither assertion of that test ever reaches the > second pass.** > > Right, and the comment now names the two actual reasons. With only `[0]` opted > out, the result that must serve is the CHECKED `[1]`, which a skipping scan > never skips, so `[1]` passes on its first evaluation and is served by the scan > itself -- stage two is never entered. With both opted out under mode > `"other"`, both trees genuinely fail the second pass too, and the answer the > ordering rule demands is the first opted-out result, which the last resort > serves either way. So the mutation is invisible to this test not because > anything is recovered but because the skip never touches the result that > decides. What does tell a skipping scan apart is an opted-out result whose > tree the scan would accept: > `test_aot_compile_module_opted_out_result_keeps_its_place_in_the_scan`, in > this same commit, pins that with honest guards (both results accept under the > default filter, `[0]` opts out, a skipping scan serves `[1]`'s graph instead), > and `test_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts` in > the dispatch commit covers the false-rejection variant; the comment now says > so instead of claiming only a false rejection can see it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #196824 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #196767, #196817, #196815, #196816, #196818, #196819, #196820, #196821, #196895, #196904, #197055
…alike (#197071) Binding dominates the per-call cost of `AOTCompiledModel.__call__`. `prepare_f_locals` (`inspect.Signature.bind` plus `apply_defaults`) costs 2.4us on this machine against 1.3us for a `check()` that passes, and the parent binds every result it scans: ```python # parent: one bind per result scanned for result in results: f_locals = result.prepare_f_locals(self.model, *args, **kwargs) # 2.4us, every time bound.append(f_locals) if result._live_guard_manager().check(f_locals): # 1.3us return result.fn(self.model, *args, **kwargs) # a match at the fourth of four inputs pays four binds for one graph ``` Every result `aot_compile_module` produces binds alike: same parameter names, kinds and default objects, same `co_freevars` and the same closure cells, since `orig_forward` is read before any `ModelInput` context is entered. So one bind serves them all. This commit lets a call that reaches a second result reuse the first result's binding for it and every later one, across the scan and the re-check, when the results bind alike: ```python shared: bool | None = None for result in results: if bound and shared is None: # decided only once a SECOND result is reached shared = self._binds_alike(results) f_locals = bound[0] if shared else result.prepare_f_locals(self.model, *args, **kwargs) bound.append(f_locals) # one entry per result either way, so the re-check zips as before if result._live_guard_manager().check(f_locals): return result.fn(self.model, *args, **kwargs) ``` Measured in one process on a `ScaleModule` compiled for two and for four dtypes, the parent's `__call__` and this one exec'd from source into two subclasses over the same results and timed in alternation, best of 9, min of two rounds: | call | parent | this commit | |---|---|---| | match at `[1]` of two | 21.0us | 20.5us | | match at `[3]` of four | 30.3us | 22.7us | | no match, two results (raises) | 25.3us | 23.2us | | no match, four results (raises) | 36.2us | 27.5us | | match at `[0]`, one / two / four results | 15.9 / 16.9 / 16.0us | 15.8 / 16.2 / 16.9us | A match at `[0]`, which is every call to a single-result model, never reaches the verdict and costs what it did (machine at load average 6). Behaviour is the parent's for every call: the same result is served or the same error raised, and a call still judges the results it began with. What changes is the number of binds, and that editing `compiled_results` between calls, which the parent's snapshot already tolerated, is now stated in the class docstring rather than implied. Review order: `_binding_key`, then the `_binding_verdict` field and `_binds_alike`, then the `shared` lines of `__call__`, then the docstring, then the tests. ## Deciding "binds alike" without `inspect.Signature` equality ```python def _binding_key(artifacts): env, params = artifacts.runtime_env, artifacts.signature.parameters.values() return (tuple([(p.name, p.kind, id(p.default)) for p in params]), env.bytecode.co_freevars, tuple([id(cell) for cell in env.closure or ()])) ``` `_binding_key` compares exactly what `prepare_f_locals` reads, with defaults and cells by identity, as a tuple of tuples so that a key is what its name says. It deliberately does not compare `inspect.Signature`s: `Parameter.__eq__` takes `bool()` of `default == default` as a non-final `and` operand, so a `forward` with a tensor default made the first call raise for any model with two or more results, however it was built (`_aot_compile`, `deserialize` or the public constructor): ```python class M(torch.nn.Module): def forward(self, x, mask=torch.ones(3)): return x * mask # comparing Signatures -> RuntimeError: Boolean value of Tensor with more than one value is ambiguous ``` `test_module_dispatch_shares_a_binding_past_a_tensor_default` pins that, and the closure half is pinned by `test_module_dispatch_shares_a_binding_across_closure_cells`, whose hand-assembled model holds two cells of the same name. A model whose results do not agree (`deserialize` unpickles each blob on its own and the constructor is public) binds each result on its own, which `test_module_dispatch_binds_per_result_when_signatures_differ` pins. `test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature` counts `prepare_f_locals` on a four-input model for a call matched at `[3]` and expects one. A loaded model whose `forward` has a real default or a closure cell binds per result for the same reason: each blob unpickles through its own `AOTCompileUnpickler`, so equal defaults and cells come back as distinct objects and the identity key reads them as different. That is a false negative and never a false share, and it is accepted rather than closed with a memo shared across the per-result pickles, which would turn the artifact from a list of independent blobs into one stream and thread a shared pickler through `AOTCompiledFunction.serialize` and `deserialize`; a `forward` with neither, whose defaults are the `Parameter.empty` singleton, still shares one bind after a load. Both shared-binding tests round-trip and pin the loaded verdict as False. ## Decided at the second result, not ahead of the scan The first result is bound and checked exactly as the parent does, so a call it serves pays nothing for the sharing and a single-result model never consults the verdict at all. `test_module_dispatch_decides_a_shared_binding_past_the_first_result` pins that on a two-result model: a call `[0]` serves never calls `_binds_alike` and leaves the verdict at its default, the verdict over no results, and the next call, which `[0]` refuses, calls it once. Every binding, shared or not, is appended once per result in the scan, so the re-check zips `results` with `bound` as the parent does. ## Re-decided whenever the public list changes `compiled_results` is a public list; the docs teach callers to index into it and tests assemble models from it by hand. So the verdict is decided again whenever the list differs by length or identity from the contents it was reached over: ```python def _binds_alike(self, results): prior, shared = self._binding_verdict if len(results) == len(prior) and all(w() is r for w, r in zip(prior, results)): return shared # cached: 0.37us at two results, 0.47us at four key = _binding_key(results[0]._artifacts) if results else None shared = key is not None and all(_binding_key(r._artifacts) == key for r in results[1:]) self._binding_verdict = (tuple(weakref.ref(r) for r in results), shared) # ONE store return shared ``` A stale True would bind a later result from `compiled_results[0]`'s signature, and if a `guard_filter_fn` dropped the guard on the parameter the two disagree about, serve a graph for a call its guards never saw: ```python model.forward.compiled_results[1] = replaced # forward(x, mode=0), but compiled for mode=1 model(x) # stale True: [1] bound from [0]'s default -> serves x * 3, where eager answers x * 2 # re-decided: [1] bound on its own signature -> raises ``` `test_module_dispatch_rebinds_after_a_result_is_appended` and `test_module_dispatch_judges_a_replaced_result_on_its_own_binding` pin the re-decision, the second through that silent shape. The contents are remembered as weak references, so a result the caller drops from the list is not kept alive by the model until a later call decides again; `test_module_dispatch_does_not_keep_a_dropped_result_alive` pops one, collects, and finds its weakref dead. Deciding costs a `_binding_key` per result, about 1.0us each, and the cached identity check 0.37us for two results and 0.47us for four, 0.02us and 0.04us of which is dereferencing the weak references. ## One field, published with one store The verdict and the contents it was reached over are one field, `_binding_verdict`, so a call reads both with one attribute load and the re-decision publishes both with one attribute store, and the field's comment states the premise rather than the conclusion: a single attribute store publishes the pair indivisibly (an instance-dict store is atomic under the GIL and locked on free-threaded builds), so a reader sees the old pair or the new one and never one list's contents beside another's verdict. Two fields cannot be made consistent by store order: ```python # contents first, verdict second: # T1 stores new contents ... T2 identity-matches them, returns the PREVIOUS verdict (stale True), # binds the appended result from [0]'s default # verdict first, contents second: # T1 pops [1], decides True over the shorter list, stores it ... T2, which snapshotted both results # before the pop, matches the contents still published, takes that True, binds [1] from [0]'s # default and serves x * 3 for a call eager answers x * 2 ``` Both interleavings are forced deterministically. `test_module_dispatch_never_pairs_new_contents_with_a_stale_verdict` holds the deciding thread inside its first `_binding_key` on a `threading.Event` and calls the model from another thread in that window. `test_module_dispatch_never_pairs_old_contents_with_a_new_verdict` holds it right after its first attribute store (an `AOTCompiledModel` subclass whose `__setattr__` parks the decider) while a call that snapshotted both results before the pop decides. A window between the two halves of the publication is the one thing no test can pin, which is why there is none: whatever the single store publishes is all a reader can ever see, and that is what the second test asserts. Both tests register their cleanups once the decider has started, release before join, so a failed assertion neither joins an unstarted thread nor leaves a parked one behind, and wait at most 10s for the decider to park, so a decider that never reaches its parking point fails the test in seconds. The tests read `_binds_alike(tuple(model.compiled_results))` rather than the field. `_binds_alike` takes the tuple `__call__` snapshotted rather than reading the list itself, so the shared bind and the verdict are about the same contents the two passes iterate; the snapshot's own test is in the dispatch commit two below (#197055), where the per-result binds already need it. > **FAQ: Why not decide the verdict once at construction and call editing > `compiled_results` afterwards unsupported, dropping the re-decision, the weak > references and both threading tests?** Because nothing stops the edit and a > stale True fails silently. Measured by making `_binds_alike` return the stored > verdict whenever one exists (deciding once), against the 15 tests: > `test_module_dispatch_judges_a_replaced_result_on_its_own_binding` fails with > `RuntimeError not raised` -- `[1]`, compiled for `mode=1` and defaulting > `mode` to 0, is bound from `[0]`'s `mode=1` default and serves `x * 3` for a > call eager answers `x * 2` -- `test_module_dispatch_rebinds_after_a_result_is_appended` > errors with `GuardManager check failed`, and both interleaving tests time out > waiting for a decider that never re-decides. The dispatch commit below > (#197055) already snapshots the list because it is editable, so stating the > edit as supported is the position the code was taking; the class docstring > now says so. What deciding once would save is the cached identity check, > 0.37us at two results and 0.47us at four, and only on calls that reach a > second result; `_aot_compile` and `deserialize` construct once either way. > **FAQ: Why weak references rather than `id()`s for the remembered > contents?** Ids are reused once an object dies, so a list of ids could match > a new result that happens to occupy a dead one's address and hand it the old > verdict. A weak reference dereferences to the object or to None, so the > identity check is exact, and it costs 0.02us more than comparing the objects > directly for two results and 0.04us for four while keeping nothing alive. > **FAQ: Why cache the verdict at all instead of deciding on every call?** > Deciding costs a `_binding_key` per result, about 1.0us each: 4us at four > results, most of the 7us the three binds it saves there cost. The cached > identity check costs 0.37us at two results and 0.47us at four whatever it > decides, and a call `[0]` serves never pays it. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_module_dispatch_binds_a_call_once_for_results_sharing_a_signature python test/dynamo/test_aot_compile.py -k test_module_dispatch_decides_a_shared_binding_past_the_first_result python test/dynamo/test_aot_compile.py -k test_module_dispatch_binds_per_result_when_signatures_differ python test/dynamo/test_aot_compile.py -k test_module_dispatch_rebinds_after_a_result_is_appended python test/dynamo/test_aot_compile.py -k test_module_dispatch_judges_a_replaced_result_on_its_own_binding python test/dynamo/test_aot_compile.py -k test_module_dispatch_does_not_keep_a_dropped_result_alive python test/dynamo/test_aot_compile.py -k test_module_dispatch_never_pairs_new_contents_with_a_stale_verdict python test/dynamo/test_aot_compile.py -k test_module_dispatch_never_pairs_old_contents_with_a_new_verdict python test/dynamo/test_aot_compile.py -k test_module_dispatch_shares_a_binding_past_a_tensor_default python test/dynamo/test_aot_compile.py -k test_module_dispatch_shares_a_binding_across_closure_cells python test/dynamo/test_aot_compile.py ``` This commit adds 10 `test_module_dispatch_*` tests; the full file runs 182 tests and passes (6 skipped). All 10 fail at the parent, i.e. with the parent's `torch/_dynamo/aot_compile.py` under this commit's test file, on the missing `_binds_alike` (`AttributeError`); the retention test reaches it through the precondition that the verdict was decided over both results, since a parent without the cache has nothing to retain. The parent's five `test_module_dispatch_*` tests still pass here, and all 15 also pass with `torch._dynamo.config.use_recursive_dict_tags_for_guards = True` set for the run. Mutation controls, each run against the 15 tests at this commit and each failing only the tests named: making `_binds_alike` return the stored verdict whenever one exists (deciding once) fails the replaced-result test with `RuntimeError not raised`, errors the appended-result test with `GuardManager check failed` and times out both interleaving tests; deciding ahead of the scan fails the first-result test with `Expected '_binds_alike' to not have been called. Called 1 times`; never reusing the first binding fails the binds-once test (four binds counted, not one); keeping only the length check in the staleness test fails the replaced-result test with `RuntimeError not raised` (`[1]` served `x * 3` on `[0]`'s binding) and still passes the appended one; restoring `Signature` equality in `_binding_key` errors the tensor-default test with `Boolean value of Tensor with more than one value is ambiguous`; dropping the cells from the key fails the closure test with `True is not false`; remembering the results by strong reference fails the retention test (`... is not None`); splitting the field in two and publishing the contents before the key is computed errors the new-contents interleaving test with `GuardManager check failed` (the appended result bound from `[0]`'s default), and publishing the verdict before the contents fails the old-contents test with `RuntimeError not raised` (both two-field variants also error the first-result test, which reads the field they split). The `co_freevars` term of the key has no mismatch test: two results holding the same cell under different names take a hand-built code object, and the term is one tuple compare of what the bind reads. Authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #197071 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #196767, #196817, #196815, #196816, #196818, #196819, #196820, #196821, #196895, #196904, #197055, #196824
…e dispatch (#197047) The parent's `AOTCompiledModel.__call__` scans every compiled result for a guard match, re-checks every result, and then falls through into `compiled_results[0]`: ```python for result, f_locals in zip(results, bound): # scan if result._live_guard_manager().check(f_locals): return result.fn(...) for result, f_locals in zip(results, bound): # re-check if result._live_guard_manager().check(f_locals): return result.fn(...) return results[0](self.model, *args, **kwargs) # fall through: raises, OR runs if [0] opted out ``` The last line does not raise by itself. `AOTCompiledFunction.__call__` skips its guards when that one result has `disable_guard_check()` set, so what an unmatched call gets still turns on the POSITION of an opt-out: `compiled_results[0].disable_guard_check()` makes `[0]` run any call no result guards, while the same flag on `compiled_results[1]` is inert and the call raises `GuardManager check failed`. Measured on a two-input `ScaleModule` (float32 and float64) called with float16, each result's `fn` wrapped to record which one served: ``` PARENT [enabled, enabled] : RuntimeError: GuardManager check failed ... PARENT [enabled, opted_out] : RuntimeError: GuardManager check failed ... <- the flag on [1] is inert PARENT [opted_out, enabled] : SERVED by [0] PARENT [opted_out, opted_out] : SERVED by [0] ``` This commit adds a third stage between the re-check and the fall-through that serves the first opted-out result, from any index, and only after both passes found no match: ```python for result in results: # NEW: honour an opt-out from any position if not result._guard_check_enabled: return result.fn(self.model, *args, **kwargs) return results[0](self.model, *args, **kwargs) # only enabled results reach here, so it raises ``` ``` HEAD [enabled, enabled] : RuntimeError: GuardManager check failed ... HEAD [enabled, opted_out] : SERVED by [1] <- the one change HEAD [opted_out, enabled] : SERVED by [0] HEAD [opted_out, opted_out] : SERVED by [0] ``` The fall-through is then reached only when every result has its check enabled, so its comment now says that `results[0]` raises, not "run one of them". ## What the flag now means on a module `compiled_results[i].disable_guard_check()` on a module artifact now makes result `i` the fallback for any call no compiled input guards, from any index. At the parent only `i == 0` had that effect and an opt-out elsewhere was inert; the flag was therefore position-dependent, not a contract. The module path (`_aot_compile`, `ModelInput`) is private and its docstring says Experimental, so no BC guarantee is owed. Nothing the parent served is refused (`[opted_out, enabled]` still serves `[0]`); the only change is raise->serve for `[enabled, opted_out]`, and only after every result's guards were checked twice and none accepted. ```python model._aot_compile([ModelInput((x, 0), {}, []), ModelInput((x, 1), {}, [])]) # ModeBranchGlobalModule model.forward.compiled_results[1].disable_guard_check() model(x, 2) # neither input guards mode=2 # parent: RuntimeError: GuardManager check failed ... L['mode'] == 0 ([0] re-entered alone) # now: x * AOT_BRANCH_SCALE, [1]'s graph -- deliberately NOT eager's answer for mode=2: # serving a graph compiled for a different call is what the opt-out exists to do ``` Why serve rather than raise: on the function path `AOTCompiledFunction.__call__` short-circuits on the flag and runs the graph whatever it is called with, and the scan already serves an opted-out result whose guards pass, which is what an enabled result gets too, so raising on a no-match would leave `disable_guard_check()` with no effect at all on a model. It would also have to keep serving `[opted_out, enabled]`, which the parent serves, so "raise" was never available without a position rule of its own. A real match is always preferred to the opt-out: the scan and the re-check run over every result, opted out or not, before this stage is consulted, so the opted-out graph is served only for a call no compiled input guards. ## Where the stage sits, and the three orderings the tests pin Ordering matters more than it looks. With this stage ahead of the re-check, an opted-out result answers first and silently serves a graph compiled for a different call in exactly the case the re-check exists for: a first `check()` that refused from the recursive dict-tag fast path without running the tree. The parent pins that order from the fall-through's side with `test_module_dispatch_rechecks_before_honouring_an_opt_out` and `test_module_dispatch_rechecks_an_opted_out_result_whose_tree_accepts`; moving this stage ahead of the re-check serves `[0]`'s `x * 2` and fails both with `Mismatched elements: 9 / 9`, and the other twelve stay green. `test_module_dispatch_serves_an_opted_out_result_from_any_position` pins the other two orderings in three assertions: ```python model.forward.compiled_results[1].disable_guard_check() model(x, 2) == x * AOT_BRANCH_SCALE # [1] serves from index 1; the parent raised here model(x, 0) == x * 2 # [0]'s REAL match still outranks [1]'s opt-out: # the stage cannot be hoisted into the scan model.forward.compiled_results[0].disable_guard_check() model(x, 2) == x * 2 # both opted out, nothing matches: index order decides, # as it did at the fall-through ``` Moving the stage ahead of the scan as well fails the second assertion, and reversing the stage's iteration order fails only the third. `[opted_out, enabled]` with a match at `[1]` is `test_module_dispatch_rechecks_before_honouring_an_opt_out`. ## To review The five-line loop in `torch/_dynamo/aot_compile.py` between the re-check and the fall-through, and the fall-through's reworded comment; the one clause appended to the dispatch paragraph of the `AOTCompiledModel` docstring; the one test, three assertions; and the clause added to the `disable_guard_check()` entry of `docs/source/user_guide/torch_compiler/torch.compiler_aot_compile.md`, which described the flag only as the function path honours it ("runs whatever it is called with, without evaluating its guards") and now says that a module's dispatch still guard-checks an opted-out result and serves it on the opt-out alone only for a call no result's guards accept. Test Plan: ``` python test/dynamo/test_aot_compile.py -k test_module_dispatch_serves_an_opted_out_result_from_any_position python test/dynamo/test_aot_compile.py -k test_module_dispatch_ python test/dynamo/test_aot_compile.py lintrunner --take RUFF,PYFMT test/dynamo/test_aot_compile.py torch/_dynamo/aot_compile.py ``` The new test fails at the parent with `RuntimeError: GuardManager check failed` (the fall-through re-enters `compiled_results[0]`, whose guard check is enabled) and passes here; the other 13 `test_module_dispatch_*` tests pass at both. The full file runs 182 tests and passes (6 skipped). The table above was measured by building the model and opting results out per row at the parent and at this commit. Lint is clean. > **FAQ: Why does dispatch serve an opted-out result when nothing matched, when > #196929's description calls the parent's position-dependent serve an > accident?** Measured against the parent on a two-input `ScaleModule` (float32 > and float64) called with float16: `[opted_out, enabled]` is SERVED at the > parent and SERVED here, `[enabled, opted_out]` raises at the parent and is > SERVED here, and `[enabled, enabled]` raises in both. So serving an opted-out > result on a no-match is pre-existing behaviour, not new -- what is new is that > it no longer depends on the opt-out sitting at index 0. The defect #196929 > names is that whether you got a report at all turned on list order, since the > fall-through re-raised only because `compiled_results[0]` happened to have its > guard check enabled. Raising instead would make `disable_guard_check()` inert > on the model path, because the scan already serves an opted-out result whose > guards do pass, so the flag would buy nothing an enabled result does not > already get; it would also refuse the `[opted_out, enabled]` call the parent > serves today, and it would red > `test_module_dispatch_serves_an_opted_out_result_from_any_position`, which > pins exactly the `[enabled, opted_out]` serve. > > There is a third option: keep the fall-through but raise from the first > *enabled* result rather than `results[0]`, > `next((r for r in results if r._guard_check_enabled), results[0])`. That fixes > which result reports without widening what is served. Measured on the same > model it raises for `[enabled, enabled]`, `[enabled, opted_out]` and > `[opted_out, enabled]`, and serves only `[opted_out, opted_out]` (by `[0]`): > it refuses the `[opted_out, enabled]` no-match the parent serves today, and a > single opt-out next to any enabled result is inert on the no-match path, > which is the inert reading above unless every result opts out. That is a > coherent contract too, but a narrower one than the flag has on the function > path, so it was not taken. > > On the blast radius of one opt-out anywhere in the list: a real match is > always preferred to it. The scan and the re-check run over every result, opted > out or not, before the last resort is consulted, so the opted-out graph is > served only for a call no compiled input guards, which is exactly the call the > flag exists to serve; > `test_module_dispatch_rechecks_before_honouring_an_opt_out` pins that order, > and the new test's `model(x, 0)` assertion pins that a match at `[0]` > outranks an opt-out at `[1]`. Narrowing the flag to "suppress my own report > but still require a match" is the inert reading above, and is why the flag is > documented as model-wide on this path. > **FAQ: `_guard_check_enabled` is not serialized, so is this stage > in-process only?** Yes, and that is pre-existing on both paths: > `AOTCompiledFunction.serialize` copies `fn._artifacts.__dict__`, and the flag > is a field of the function, not of its artifacts, so a loaded result starts > enabled whether it is called directly or through a module's dispatch. The > opt-out has always been something the caller sets on the results it holds > after building or loading them; this commit changes where the module path > honours it, not whether it is saved. Authored with the assistance of Claude Code. Co-Authored-By: Claude Fable 5.1 <[email protected]> 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #197047 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #196767, #196817, #196815, #196816, #196818, #196819, #196820, #196821, #196895, #196904, #197055, #196824, #197071
Stack from ghstack (oldest at bottom):
Follow-up to the reviews of #196476, #196478 and #196479.
_keep_container_verbatimdecided a plain tuple in two steps: is it inguard_tree_values, and is it invalue_guarded_containers. The second aloneis the rule; the first held because
EQUALS_MATCHregisters the value itreads, a separate invariant whose failure would be the silent forever-miss the
rule exists to prevent. The tuple case now reads the recording alone:
That is a behaviour change for the case the two invariants disagree on: a
recorded tuple with no tree entry was pruned per value and is now carried
whole. A test builds exactly that state, and it fails on the previous commit.
A globals snapshot kept
__builtins__"as read" when some guard had registeredit and replaced it with the
builtinsmodule only when pruned. For an importedmodule
f_globals["__builtins__"]ISbuiltins.__dict__, and a tracedmodule's own dict binds that same object a second time under the
__builtins_dict___NDynamo installs; that dict is the one a savedBUILTIN_MATCH guard registers, so wherever one is saved the kept branch was
taken and the snapshot carried all of builtins (about 6 KB) next to
the filtered copy
Galready holds. The live builtins dict is now exempt fromthe keep contract by value rather than by name, so every slot holding it -- the
alias included -- travels as a reference resolved in the loading process rather
than as a copy, one shared
_LiveBuiltinsstanding for it so a second slot inthe same scope is a pickle memo reference rather than a second reduce. On a
scope carrying both keys that takes the dump from 6781 bytes to 729; a
cross-module snapshot, which has only
__builtins__, goes from 6758 to 706.The slot stays a dict, since a guard may have walked through it and rebakes
against whatever it holds at load. A dict without the key stays without
one, since
FunctionTypefalls back to the loading frame's builtins and aguard on the dict's shape must see the same keys;
FunctionTypeaccepts eithervalue. The key set is the module dict's at save time, names Dynamo installed
into it included, so such a guard is only as portable as those names.
The snapshot loop iterated the live module dict. A
CleanupHookpops the nameit owns, and it fires from a weakref callback (
CleanupManagerholds aweakref.refper traced code object, whose callback runs the hooks attached toit), so a code object collected during the dump pops a
__compiled_fn_Nor__builtins_dict___Nkey mid-loop and the next iteration raisesRuntimeError: dictionary changed size during iteration. The loop now walks a copy,dict(f_globals), which also makes the sentence above literally true: the keyset is the one the loop entered with, not whatever survived to its end.
The rarity is not the loop's own doing -- measured with
gc.callbacks,snapshotting a scope of 80
nn.Linears runs 82 iterations and takes zeroautomatic collections at the default gen-0 threshold (zero at 300, one at 10),
since it allocates almost nothing GC-tracked. What decides whether a callback
lands inside the loop is where the process-wide gen-0 counter already stood when
the dump began. Scanning that offset with default thresholds and no forced
collection, 1 of 200 positions raises against the live dict, and 0 of 200 once
the loop walks a copy; being a flake rather than a reproducible failure is why
the test forces the hook to fire from the loop's first
_prunecall instead ofwaiting for a collection. The copy is
dict(f_globals)rather thanlist(f_globals.items()): at a gen-0 threshold of 1, where a callback popping akey raises out of a live
for k, v in d.items()loop in all 50 trials, neitherspelling raises once, and the dict copy is shorter and materializes no N-entry
list of 2-tuples.
The 6 KB is a snapshot's cost, and
_reduce_function_by_valuebuilds a snapshotonly for a function whose own
__globals__is registered too. A plainCompilePackagecompile(
torch._dynamo.optimize("eager", package=CompilePackage(fn))) applies no guardfilter and keeps that BUILTIN_MATCH, so building its manager registers the dict
the guard reads through -- but the traced function's module dict is not
registered there, so no snapshot is built at all. Reading a global through a
function's
__globals__does register that dict, and it also guards thefunction itself with a CLOSURE_MATCH, which
serialize_guardsrefusesoutright, so with no filter at all an artifact built that way bypasses rather
than saving. The 6 KB is paid where a caller-supplied
guard_filter_fndropsthat function guard and keeps the BUILTIN_MATCH: there the parent embedded the
whole dict and the exemption hands back a reference instead. Both high-level
entry points filter the BUILTIN_MATCH away instead --
aot_compile's defaultguard_filter_fndrops everyis_globalentry and the alias's BUILTIN_MATCH isone, and
caching_precompile=Truedrops it as ID_MATCH-derived -- so under themnothing registers
builtins.__dict__and the parent embedded no copy of it: itpruned the alias slot to a sentinel and replaced
__builtins__with thebuiltins module. There the exemption instead hands those slots back the live
dict, 772 bytes to 729 on the same scope, which the same rebake argument covers.
On 3.14 the guard pickler read FORWARDREF annotations unguarded, so whatever
that read raised failed the dump. FORWARDREF reruns the annotate function, but
only NAME lookups are proxied -- the rest of the expression runs for real, so
whatever that real work raises comes out:
That would fail the dump for a slot the prune exists to make optional, so
_reduce_function_by_valuedrops the whole set instead, with a debug log namingthe code object by
co_qualnamewhere the runtime has one and byco_nameon3.10. That log line repeats the AOT pickler's
_pickleable_annotationsonerather than sharing it: the two handlers differ in policy (that one swallows a
RecursionError too, and afterwards drops unpicklable values key by key instead
of sentinelling them) and each logs under its own module's logger, which is what
tells the two drops apart in a
TORCH_LOGSrun, so what is left to share is aformat string. The handler sits at that caller
rather than inside the shared
_read_raw_annotations, which stays a pure reader raising for either format:the other caller, the AOT pickler's
evaluate=Trueone, already handles its ownread (it logs the reason it saw), so a keyword that selects a format does not
also select an error policy. A RecursionError is re-raised rather than dropped:
it is the dump's own limit, which
pickle_guards_statereports as a bypass, nota property of the annotation, and swallowing it would drop a set that reads fine
at any other depth. Dropping the whole set cannot silently break a guard: a
guard rooted at
fn.__annotations__evaluated them at trace time (the VALUEformat, cached on the function), so a read that raises at dump time is one no
guard performed. The 3.14 path had no test at all, since every annotation in the
suite either was an assigned dict or resolved; a 3.14-gated test now pins that
the TYPE_CHECKING-only name is genuinely unreadable outside the FORWARDREF read
-- a direct
__annotations__read raisesNameError, a premise pruning to asentinel cannot tell from a resolved class -- and that the f-string case drops
the set (CI runs this file on 3.14; there is no local 3.14 build).
Test and comment cleanups: the guarded-defaults test names the full-compile
round trip that can tell a whole-container guard from a per-element one instead
of forward-referencing it; the two snapshot tests assert on names their
module cannot lose instead of comparing whole key sets against a live module
dict a
CleanupHookcan pop from; thename_beside_unpicklable_defaultsubtest now says why the default prunes,which is that
bind_argsguards__defaults__with SEQUENCE_LENGTH and onlyEQUALS_MATCHrecords a tuple invalue_guarded_containers, so a length guardsurvives per-value pruning; the pickler
__init__comment no longer claimsomitting the recording prunes every container; the snapshot comment names both
regimes whose guard filter drops the alias's BUILTIN_MATCH; and the annotations
comment says what the keep branch there is for, which is a dict SUBCLASS assigned
onto
__annotations__that a guard registered (an exact dict is never carriedwhole on any version, and on 3.14 the read hands back a copy, so neither is a
subclass one) -- the branch stays, since deleting it would prune that mapping
per value and rebuild it as a plain dict. The snapshot comment also says what
the exemption costs, which is that a guard walking the slot rebakes against the
loading process's builtins rather than the binding the compile saw; and the two
builtins tests pin the reference identity alone, since a copy cannot be
isthelive dict, while an absolute byte bound over a stream whose size depends on the
pickle protocol and the per-version
SerializedCodepayload adds nothing to it.Kept as one commit rather than split three ways along the paragraphs above (the
tuple rule, the builtins exemption, the annotation guard are independent and
each carries its own test): this is the bottom PR of an already-submitted
pickler stack, so splitting it rebases and renumbers every PR above it; what
that buys is a finer bisect over three changes that already sit in disjoint
functions and cannot interact.
One #196476 comment is not a change here: the AOT pickler's own by-value
reducer carried only
__defaults__at that commit, so an AOT-rebuilt helperlost
__kwdefaults__and__dict__and its__name__was the qualname.#196685 and the commits between it and this one moved that pickler onto the
shared base, which is where those are already fixed.
Test Plan:
The preserves-module snapshot test asserts the rebuilt scope's
__builtins__comes back as whatever the live dict held (the module when this file runs as
__main__, the builtins dict when it is imported), and another pins the aliasslot: with the exemption keyed on the name that slot arrives as a copy of the
whole builtins dict, not the live dict. Six of the seven new tests fail on the
previous commit: that alias one,
test_snapshot_of_an_unguarded_builtins_dict_stays_a_dict,test_a_recorded_tuple_is_kept_verbatim_without_a_tree_entry(the behaviourchange above),
test_a_raising_annotation_read_drops_the_set_but_not_a_recursion_error(the parent's read is unguarded and nothing on its save path catches it),
test_snapshot_survives_a_cleanup_hook_pop_during_the_loop(the parent buildsthe snapshot as a comprehension over the same live dict) and, on a 3.14 shard,
test_reduce_prunes_an_unresolvable_annotation_and_drops_a_raising_onevia its f-string case. Only
test_snapshot_of_a_scope_without_builtins_stays_withoutpasses there, and iskept for the contract the exemption must not break: a scope that has no
__builtins__does not gain one. The TYPE_CHECKING test is 3.14-only and runsin CI, while the raising-read test patches the read itself, so the drop, its log
and the RecursionError re-raise are covered on every shard, 3.10 included.
Authored with an AI assistant.
Co-Authored-By: Claude Opus 5 [email protected]
FAQ
🤖 Generated with Claude Code