Skip to content

[dynamo] fix pruning locals with ShapeEnvSource - #154752

Closed
isuruf wants to merge 1 commit into
gh/isuruf/144/basefrom
gh/isuruf/144/head
Closed

isuruf wants to merge 1 commit into
gh/isuruf/144/basefrom
gh/isuruf/144/head

Conversation

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented May 30, 2025 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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 b794509 with merge base 0f81c7a (image):

BROKEN TRUNK - The following jobs failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@isuruf

isuruf commented Jun 2, 2025

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Jun 2, 2025
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@isuruf

isuruf commented Jun 2, 2025

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

The merge job was canceled or timed out. This most often happen if two merge requests were issued for the same PR, or if merge job was waiting for more than 6 hours for tests to finish. In later case, please do not hesitate to reissue the merge command
For more information see pytorch-bot wiki.

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 2 checks: pull / cuda12.8-py3.10-gcc9-sm75 / test (pr_time_benchmarks, 1, 1, linux.g4dn.metal.nvidia.gpu), trunk / macos-py3-arm64 / test (default, 1, 3, macos-m1-stable)

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@github-actions
github-actions Bot deleted the gh/isuruf/144/head branch July 4, 2025 02:20
pytorchmergebot pushed a commit that referenced this pull request Sep 14, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants