Skip to content

[aot_compile] Cover a guarded global the loading process does not have - #196825

Closed
bobrenjc93 wants to merge 44 commits into
gh/bobrenjc93/1174/basefrom
gh/bobrenjc93/1174/head
Closed

bobrenjc93 wants to merge 44 commits into
gh/bobrenjc93/1174/basefrom
gh/bobrenjc93/1174/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary. Tests only, end to end: a module artifact guards a module-level
global, the loading process does not define it, and the call has to fail loudly
with a report that names the failing input ([0] KeyError on G['AOT_HERMETIC_WEIGHT']) and the scope its guards were rooted at, the globals
of the module where HermeticModule.forward is defined. The alternative,
falling back to the serialized scope, would make the guard a no-op checked
against capture-time state, which is the silent failure mode; loud is
recoverable on the serving machine. The test then takes the report's advice and
pins how far that goes at this commit: defining the name resolves the guard and
the call is served, but with the tensor serialized in the artifact rather than
the one just defined, because the bytecode's globals are built once at load and
a live value is substituted only for a name the scope had then. That
x @ saved assertion is recorded as the limitation it is, not the intended end
state: #196897, two commits up, makes a loaded module artifact re-read the live
value on every call and flips it to x @ (saved * 2), using this test as its
witness. It is a separate commit because a guarded global the loading process
lacks is a failure mode of its own, independent of where an opted-out result
sits in dispatch and of what the report says when a tree raised.

The scenario

# capture process: HermeticModule.forward reads the module-level AOT_HERMETIC_WEIGHT
model = torch.compile(HermeticModule(), fullgraph=True, backend="eager",
                      options={"guard_filter_fn": keep_global_guards})
model._aot_compile([ModelInput(args=(x,), kwargs={}, contexts=[])])
data = model._save_aot_compiled_module()

# loading process: the global is absent
torch._dynamo.reset()
saved = globals().pop("AOT_HERMETIC_WEIGHT")
reloaded = torch.compile(HermeticModule(), fullgraph=True, backend="eager")   # no guard_filter_fn: inert on a load
reloaded._load_aot_compiled_module(data)                                       # a module load takes no f_globals=
reloaded(x)
# RuntimeError: No AOT compiled graph matched this call. Tried 1 compiled input(s):
#   [0] KeyError on G['AOT_HERMETIC_WEIGHT']
# For [0]: a guarded global is missing from the globals of the function this HermeticModule instance's
#          forward resolves to, since that is the one the load resolved, here vars(test_aot_compile); ...
# Add a ModelInput covering this call, or check whether guard_filter_fn kept a guard ...

The reloading wrapper takes no guard_filter_fn: the load installs the
artifact's own guards and captures nothing, so the loading process's filter has
no say in what a loaded artifact checks. The sibling
test_aot_compile_module_reload_reads_the_live_global does pass a filter on
its reload, where it is equally inert.

Taking the advice, and what the recovery arm pins

globals()["AOT_HERMETIC_WEIGHT"] = saved * 2      # define it in the named scope, with a DIFFERENT value
reloaded(x) == x @ saved                          # served -- but with the tensor serialized in the artifact

The guards read the live scope by reference, so the new binding passes the kept
TENSOR_MATCH, which checks metadata and not values. The bytecode's globals
were built once, at load, and substitute a live value only for a name the scope
has then, so the value serialized with the artifact was never overwritten.
Binding saved * 2 and asserting x @ saved is what pins that, and it is what
makes the recovery assertion say which dict the dispatch READ rather than only
that it stopped raising: asserting x @ (saved * 2) instead fails
(Tensor-likes are not close! Mismatched elements: 9 / 9), and rooting the
guards at a copy of the live scope rather than the dict itself is caught first
by the hint assertion (the report drops the forward clause when the resolved
dict is not the one the guards hold), with the recovery arm as the second line
of defence.

That x @ saved value is the parent's load-time snapshot, recorded here as the
limitation it is and not as the intended end state: #196897, two commits up
this stack, makes a loaded module artifact re-read the live value on every call
and flips this very assertion to x @ (saved * 2), using this test as the
witness that its recorded name set is not intersected with the scope at load.
The pin stays in this commit so that flip lands as a measured behaviour change
rather than a silent one; the test comment says the same in one sentence,
without the PR number, so it reads correctly both before and after that commit.
Binding saved instead, which would make the arm invariant under #196897, was
considered and declined: it would leave this test unable to tell the live dict
from the serialized copy, and #196897 would have to re-add saved * 2 to use
it as a witness.

Both lines of the report, and which sibling pins what

The report is also asserted to carry the generic mismatch advice next to the
hint: a missing global counts as the mismatch it is, because the report cannot
tell whether a new ModelInput would read the absent global (one captured for
a branch that does not read it is served with the name still undefined), so
both lines are emitted, and for HermeticModule, which reads the global on its
only path, the hint is the actionable half.

The forward clause the test asserts is emitted when the scope model.forward
resolves to is the dict the guards hold (resolved is not None and resolved is missing_global._guard_globals), which is the case for a load that passed no
guard_globals=, resolved forward, and is not rebound after the load:

this test (un-rebound load)                       -> clause present, "here vars(test_aot_compile)" suffix
..._hint_covers_a_rebound_forward (rebinds BEFORE loading) -> clause present, no suffix (foreign dict)
..._survives_a_forward_resolve_that_raises (rebinds AFTER)  -> clause absent

What tells this test from the rebound sibling is the recovery arm: defining the
name in globals() serves the call here, where the same binding in that
sibling still raises.

Why its own test, and the fixture

Most of the load-bearing assertions are on #196823's no-match report and its
forward-naming hint, and the recovery assertion is on #196818's live-scope
rooting, so this could equally have been folded into #196823; it stays separate
because a guarded global the loading process does not have is a failure mode of
its own, and each of those gets the commit that pins it. The fixture is the
same HermeticModule and module-level weight
test_aot_compile_module_reload_reads_the_live_global uses, the test for the
opposite direction, rather than a second copy that differed only in an
unchecked scale factor. Like that sibling it hides the module dict's leaked
generated globals through the shared helper before capturing, since the scope
resolved from model.forward is this module's dict and the capture leaks
Dynamo's generated names into it. The load seeds nothing here, for the reason
that sibling's comment gives: the only kept global guard is rooted at
AOT_HERMETIC_WEIGHT, not at an import alias or the builtins-dict key.

No behaviour change vs the parent: the diff is one 66-line test, nothing under
torch/ moves.

Test Plan:

python test/dynamo/test_aot_compile.py -k test_aot_compile_module_absent_global_fails_guard

Run in one process with the tests that share the fixture and the report, which
unittest orders after this one, to show they still pass with it running first
(5 tests, OK):

python test/dynamo/test_aot_compile.py -k test_aot_compile_module_absent_global_fails_guard -k test_aot_compile_module_reload_reads_the_live_global -k test_missing_key_inside_a_present_global_is_not_a_missing_global -k test_no_match_message_keeps_the_advice_for_every_entry -k test_no_match_message_hint_covers_a_rebound_forward

The whole file was run at this commit:

python test/dynamo/test_aot_compile.py

Authored with the assistance of Claude Code.

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

FAQ

FAQ: why not rename AOT_HERMETIC_WEIGHT/HermeticModule to something that
says what the fixture is for? The fixture is not this commit's: git log -S
puts class HermeticModule and the module-level AOT_HERMETIC_WEIGHT in
#196820, which introduces them along with its test that a reloaded module
artifact reads the live global. #196825 reuses them rather than adding a
near-duplicate module and weight. A rename therefore has to rewrite the fixture
definition in #196820 together with every test body that uses it, which by this
commit is spread across several of the stack's commits, in a stack whose whole
point is one reviewable behaviour per commit -- for a naming preference, with no
change in what is covered. The name is a poor one and #196820 says so: what
these tests pin is that a load reads the LIVE global rather than a sealed
capture-time copy, which is the opposite of hermetic. The rename is a mechanical
follow-up once the stack lands, touching the definition and every commit's uses
together.

FAQ: the test pops AOT_HERMETIC_WEIGHT after _hide_leaked_dynamo_globals(),
and that order is what keeps cleanup from deleting the module-level fixture --
why is the dependency not spelled out here?
It is real: the helper snapshots
preexisting = frozenset(g) over g = globals() and its cleanup deletes every
name not in that snapshot, so a pop moved above the helper drops the name from
the snapshot and the cleanup deletes the module-level global for the rest of the
process. Measured by mutation -- with the helper call moved below the pop (after
the capture) this test still passes and the next test that reads the fixture dies
with NameError: name 'AOT_HERMETIC_WEIGHT' is not defined at its x @ AOT_HERMETIC_WEIGHT. The note is not added at this call site because the
dependency is a property of the shared helper, not of this test: six tests pop a
global around it, five of them in earlier commits of this stack (#196816,
#196823, #196824), and a note on one call site documents the helper's contract in
the one place that does not own it while leaving the other five bare. It belongs
in _hide_leaked_dynamo_globals's own comment, which already explains the
snapshot-and-restore and reaches all six call sites at once; that is a one-commit
change to the commit that introduces the helper, not to this test-only commit.

FAQ: why does this test not also assert Tried 1 compiled input(s) alongside
No AOT compiled graph matched?
Because the tried-count line is the report's
shape, which is pinned where the report is introduced: that commit asserts Tried 2 compiled input(s) together with the [0]/[1] entries and their line
positions, and pins the exact line count for a one-input report in its
odd-separators test. This test pins a different thing -- that a guarded global
the loading process lacks fails the guard and is reported as [0] KeyError on G['AOT_HERMETIC_WEIGHT'] -- and its [0] ... assertion already fails if the
entry for the single compiled input stops being emitted. Re-asserting the count
here would add a second place to update when the report's wording changes, for
coverage the report's own test already has.

🤖 Generated with Claude Code

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

Note: Links to docs will display an error until the docs builds have been completed.

❌ 2 Cancelled Jobs

As of commit 22f20bd with merge base 51d4378 (image):

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

  • Scope
    • Diff is one 66-line test added to test/dynamo/test_aot_compile.py; nothing under torch/ is touched, so there is no behaviour change to regress
    • Reuses the existing HermeticModule/AOT_HERMETIC_WEIGHT fixture at test_aot_compile.py:547-552 and keep_global_guards at :773 rather than adding new fixtures
  • Assertions match the implementation
    • "No AOT compiled graph matched" and "Add a ModelInput" are emitted unconditionally by _no_match_report at aot_compile.py:1604 and :1664
    • The hint substring matches the SUPPLIED branch f-string at aot_compile.py:881-882 with forward set at :1657; KeyError on G[...] comes from guards.cpp:5569
  • Test state safety
    • g.pop("AOT_HERMETIC_WEIGHT") at :5371 runs after _hide_leaked_dynamo_globals() at :5359, so the name is inside the preexisting snapshot at :1976 and the cleanup delete sweep at :1980-1982 skips it
    • The finally at :5409 rebinds the original object on every path, so the saved * 2 binding does not leak to later tests
  • Nothing triggering a human gate
    • No workflow, CI, or docs/policy files in the diff; no secrets, no eval/exec, no weakened check
    • Only human comments in /tmp/greenlight-pr.json are @claude invocations; no maintainer raised a concern

reason: clean
Reviewed commit: 22f20bd

Inference job

🐛 Report a wrong verdict

CANCELLED JOBS - The following jobs were cancelled. Please retry:

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

This was referenced Sep 11, 2026
pytorchmergebot pushed a commit that referenced this pull request Sep 17, 2026
…pplied-scope hint (#197048)

The commit below raises a report when no compiled graph matches, and when an
entry's guards failed on a global the process does not have it appends the
function path's `_missing_global_hint` for that entry on a `For [i, j]:` line,
one per distinct sentence, naming the entries that share it. For
a result whose scope is SUPPLIED -- a module load that resolved its guard scope
itself -- that sentence read `a guarded global is missing from the live scope
this artifact was loaded against, here vars(<module>)`, which names the dict
only when it is a module's namespace and otherwise says nothing about where the
name has to go. This commit has the report name the attribute the load resolved
the scope from: `the globals of the function this <Type> instance's forward
resolves to, since that is the one the load resolved`, keeping the `, here
vars(<module>)` suffix when that dict is a module's namespace.

The name is passed only when the guards really hold the dict that attribute
resolves to. `deserialize` skips `_resolve_guard_scope` entirely for a
caller-supplied `guard_globals=`, so a result loaded that way holds a dict no
forward resolves to and keeps the scope-neutral wording -- naming the class's
forward there would send the reader to a dict where the name is already defined
and dispatch still fails. The report decides by comparing the dict the guards
hold against a fresh resolution rather than a bit recorded at load, which costs
a `get_traced_fn` on the raise path only and also covers a rebind made after
the load. It asks only of a result whose scope is SUPPLIED: the CAPTURED and
RECONSTRUCTED wordings never name `forward`, and resolving it runs user code --
`get_traced_fn` formats a forward it refuses into its error before raising
(`Unsupported model code type {mod}` in convert_frame.py), and for a
`functools.partial` over the module that repr reaches the user's `extra_repr`,
outside the `(RuntimeError, AttributeError)` the helper catches. Dispatch calls
`result.fn(self.model, ...)` and never the instance's `forward`, so a rebind
after the load reaches only the report -- and on a SUPPLIED result the report
does resolve it, so that resolve is wrapped: any exception it raises degrades
the wording to the scope-neutral one rather than replacing the report with
itself. The gate narrows the window; the catch closes it.

The printed name is `this <Type> instance's forward`, the attribute the load
resolved the scope from, and not the class's `<Type>.forward`: the two are one
lookup until an instance rebinds `forward`, after which the guards read that
other function object's globals, so naming the class attribute would need a
second clause hedging for the rebind -- one that, for the rebound test below,
points at a dict where defining the name does not restore dispatch. Defining
the absent name in the resolved dict is what restores dispatch -- the guards
hold the dict by reference, so a name defined after the load resolves, while
the graph goes on reading the value serialized at capture, since the bytecode
globals are built once at load and a live value is substituted only for a name
the scope had then -- and defining it beside the class definition need not,
which `test_no_match_message_hint_covers_a_rebound_forward` asserts both ways
round for a rebind over foreign globals. An un-rebound load prints the same
forward-naming hint plus a `, here vars(<module>)` suffix; the rebound
function's dict is no module's namespace, so `_module_namespace_name` names
nothing and the suffix is absent. That is also why the rebound load is the test
that tells the instance attribute from the class's: defining the name beside
the class definition serves an un-rebound load, so nothing there distinguishes
the two.

The name is decided per entry, since the public constructor accepts results
of differing scopes: `_resolve_guard_scope(self.model)` runs at most once per
report, on the first SUPPLIED entry that named a missing global, and each
SUPPLIED entry compares that dict against its own `_guard_globals`; entries
whose sentences match then share one `For [i, j]:` line.

Behaviour change vs the commit below, on the module path only: for a load
(`AOTCompiledModel.deserialize` or `_load_aot_compiled_module`) that passed no
`guard_globals=` and whose instance `forward` still resolves to the dict the
load used, the `For [i, j]:` line reads `... the globals of the function this
<Type> instance's forward resolves to, since that is the one the load resolved,
here vars(m); define it there ...` instead of `... the live scope this artifact
was loaded against, here vars(m); define it there ...`. Every other wording --
the `guard_globals=` case, CAPTURED, RECONSTRUCTED, and the function path -- is
unchanged. The landed
`test_aot_compile_module_missing_global_hint_names_the_resolved_module` asserts
`, here vars(<module>); define it there` for the first and `loaded against;
define it there` for a `guard_globals=` copy of the namespace, and passes at
both commits.

Order to review: `_missing_global_hint`'s `forward=` keyword and the `where`
ternary in its SUPPLIED branch; then the report site in `_no_match_report`
(the SUPPLIED gate, the wrapped `_resolve_guard_scope`, the identity compare
that clears `forward`); then `RaisingReprModule` and the two tests.

Test Plan:

```
python test/dynamo/test_aot_compile.py -k test_no_match_message_hint_covers_a_rebound_forward
python test/dynamo/test_aot_compile.py -k test_no_match_report_survives_a_forward_resolve_that_raises
python test/dynamo/test_aot_compile.py -k test_aot_compile_module_missing_global_hint_names_the_resolved_module
python test/dynamo/test_aot_compile.py
```

The whole file runs 189 tests, `OK (skipped=6)`, two more than the commit
below. Run against the commit below's `aot_compile.py`,
`test_no_match_message_hint_covers_a_rebound_forward` fails: `"the function
this HermeticModule instance's forward resolves to" not found`, the report
carrying the neutral `the live scope this artifact was loaded against` instead.
`test_no_match_report_survives_a_forward_resolve_that_raises` PASSES there --
the neutral wording is what that commit prints for every SUPPLIED result -- so
it pins nothing about the commit below and exactly one thing about this one,
the catch: removing the `except Exception` around the resolve fails it with
`ValueError: extra_repr` escaping in place of the report. Never clearing
`forward` (dropping the identity compare) fails it on the scope-neutral
assertion, with a report that names `this RaisingReprModule instance's
forward`, and fails the landed
`test_aot_compile_module_missing_global_hint_names_the_resolved_module` on its
`guard_globals=` half, `'loaded against; define it there' not found`. Both
mutations measured at this commit.

`test_no_match_message_hint_covers_a_rebound_forward` saves an artifact
captured from an un-rebound `HermeticModule`, then loads it into an instance
whose `forward` is the same code object over a foreign globals dict `ns`, with
`AOT_HERMETIC_WEIGHT` popped from this module. The report names `this
HermeticModule instance's forward`; restoring the name in this module -- where
`HermeticModule.forward`, the class attribute, is defined -- still raises the
`KeyError on G['AOT_HERMETIC_WEIGHT']` report, asserted with
`assertRaisesRegex` on that text so that a different `RuntimeError` would not
pass; defining it in `ns` serves the call with `x @ saved`.

`test_no_match_report_survives_a_forward_resolve_that_raises` loads through
`AOTCompiledModel.deserialize(inst, data)` with no `guard_globals=`, so every
result is SUPPLIED and the report does resolve `forward`; it then rebinds the
instance's `forward` to a `functools.partial` over a module whose `extra_repr`
raises `ValueError`, asserts `repr(inst.forward)` raises it, and asserts the
report still arrives worded for `the live scope this artifact was loaded
against`, since the rebound forward resolves to no dict the guards hold.

Four more tests of this hint sit in #197001, the test-only commit directly
above: the hint stays scope-neutral for a caller-supplied `guard_globals=`, a
CAPTURED result's report names no `forward` and never resolves it, the advice
still reaches a report whose every entry named a missing global, and a missing
KEY inside a present global is not a missing global; three of them pin the gate
and the compare added here, and that commit's message says which edit to this
report each one catches.

Authored with the assistance of Claude Code.

> **FAQ: Why aren't the tests for every branch of this hint in this commit?**
> The report this hint sits in is the commit below, whose tests pin the
> report's entries, footer and the `For [i, j]:` line in its scope-neutral and
> CAPTURED wordings. The supplied-scope hint on an un-rebound load is pinned by
> #196825, a test-only commit higher in the stack, which also pins that the
> "Add a `ModelInput`" advice still reaches a report whose only failure is a
> missing global. What is pinned here, by
> `test_no_match_message_hint_covers_a_rebound_forward`, is that the hint names
> the INSTANCE attribute the load resolved the scope from: for an instance that
> rebound `forward` before the load the guards read another function object's
> globals, and that is where the absent name has to be defined. Showing that
> takes a load whose resolved scope is not the class's module -- an un-rebound
> load prints the same forward-naming hint plus a `, here vars(<module>)`
> suffix, and defining the name beside the class definition serves it, so
> nothing there tells the instance attribute from the class's. Folding
> #196825's test lines down here would put two unrelated behaviours -- this hint
> and a guarded global the loading process does not have -- in one commit,
> which is the split this re-slice exists to make; they land together in any
> case. Four more of the report's tests sit in #197001, the test-only commit
> directly above this one, split out so that this commit's review fits in one
> pass: `test_no_match_message_hint_stays_neutral_for_a_supplied_scope` (the
> hint stays scope-neutral for a caller-supplied `guard_globals=`),
> `test_missing_key_inside_a_present_global_is_not_a_missing_global` (a missing
> KEY inside a present global is not a missing global),
> `test_no_match_message_advises_an_input_for_a_missing_global` (the advice
> reaches a report whose every entry named a missing global) and
> `test_no_match_report_resolves_forward_only_for_a_supplied_scope` (a CAPTURED
> result's report names no `forward` and never resolves it). That commit's
> message says where each fails and which edit to this report each one catches.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

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

Pull Request resolved: #197048
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197049, #196823, #197149
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 2 checks: inductor / get-label-type / runner-determinator, inductor / unit-test / get-label-type / runner-determinator

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

pytorchmergebot pushed a commit that referenced this pull request Sep 18, 2026