Skip to content

[aot_compile] Fix global guards on reloaded nn.Module artifacts - #192374

Closed
bobrenjc93 wants to merge 34 commits into
gh/bobrenjc93/981/basefrom
gh/bobrenjc93/981/head
Closed

bobrenjc93 wants to merge 34 commits into
gh/bobrenjc93/981/basefrom
gh/bobrenjc93/981/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Third of six. This one is a standalone aot_compile fix, and it also introduces
the CPU codegen target that the package layer below torch.compiler.precompile
uses to decide whether an artifact is safe to load on the machine reading it.

Guards on globals resolve against the traced function's global scope.
AOTCompiledFunction.deserialize takes an f_globals for this, but
AOTCompiledModel.deserialize never passed one, so a reloaded module artifact
rebuilt its guards against only what the serialized bytecode reconstructs. A
global Dynamo specialized away never appears there, and the guard then fails on
every call with "KeyError on G['...']".

Two details of the fix carry weight. The scope is resolved from model.forward,
not from the model: get_traced_fn returns Module._wrapped_call_impl for a
hooked module, which would silently inject nn.Module's namespace over a
colliding graph-input global. And it is threaded through a dedicated
_guard_globals rather than _extra_globals, which feeds forward_callable
and would rewire what the compiled bytecode reads. The scope is the loading
process's live module dict, by reference: a global rebound after load redirects
dispatch on the next call, which is the point. There is deliberately no fallback
to the serialized value, because the deployment model is capture on one machine
and serve on another, and a loud refusal there is recoverable where a silently
stale answer is not.

The CPU codegen target guards generated code: inductor bakes a vector width in,
so an artifact captured on one target and loaded on another would run kernels
for an ISA the host may not have. Artifacts that hold no generated code -- the
eager and aot_eager family -- are exempt, and skip the toolchain probe as well
as the comparison. Anything unrecognised is assumed to generate code, since a
false rejection at load is recoverable and running a foreign kernel is not.

Dispatch reporting on AOTCompiledModel changes too. When nothing matched it
used to run graph 0 so its guard check would raise, which always blamed the
first input; it now reports why each compiled input was rejected, one line
apiece, and consults an opted-out result only after a real match has been
sought.

Test Plan:

python test/dynamo/test_aot_compile.py
python test/dynamo/test_package.py
python test/test_precompile.py

The scope tests fail on the pre-change tree with KeyError on the guarded global;
the rebound-global and absent-global tests were also reproduced across two real
processes.

Authored with an AI assistant.

Differential Revision: D116222521

[ghstack-poisoned]
@bobrenjc93 bobrenjc93 added ciflow/trunk Trigger trunk jobs on your pull request topic: not user facing topic category labels Aug 6, 2026
@pytorch-bot

pytorch-bot Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (1 Unrelated Failure)

As of commit f9fd563 with merge base 1b4e490 (image):

BROKEN TRUNK - The following job 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.

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Aug 6, 2026
bobrenjc93 added a commit that referenced this pull request Aug 6, 2026
Guards on globals are resolved against the traced function's global scope.
AOTCompiledFunction.deserialize already accepts an f_globals argument for
this, and aot_compile_fullgraph supplies the traced function's __globals__ at
capture time, but AOTCompiledModel.deserialize never forwarded one. A reloaded
module artifact therefore rebuilt its guards against only the scope
reconstructible from the serialized bytecode (used_globals plus import
sources). A global that Dynamo specialized away during tracing never appears
in that bytecode, so it is missing from the scope and the guard fails at
dispatch with "KeyError on G['...']" -- for every call, not just mismatched
ones. This only reproduces when a global guard survives to the artifact, which
requires a caller-supplied guard_filter_fn, since the default one drops them.

The second change is diagnostic. When no compiled input's guards matched,
AOTCompiledModel.__call__ ran compiled_results[0] anyway so that its guard
check would raise. With several ModelInputs that always blames the first one,
regardless of which input is actually missing. It now reports why each
compiled input was rejected.

Note on the path not taken: the default guard_filter_fn drops every global
guard, which is the same thing torch.compiler.skip_guard_on_globals_unsafe
does explicitly -- and dropping a load-bearing global guard is silent, not
loud, so a multi-ModelInput model can dispatch to a graph traced under a
different global value and return a wrong answer. Narrowing that default is
the real fix, but it is not a one-line change: guard construction cannot
currently resolve arbitrary global references, and simply keeping them makes
eight existing tests fail with KeyError on G['torch'] and on builtins dicts.
That needs the guard scope threaded through separately, so this change only
makes the globals that callers explicitly keep work correctly, and leaves a
comment at the filter recording why it is still broad.

Test Plan:

Two new tests, both of which fail without this change -- the first with
"KeyError on G['GLOBAL_POOLING_CONFIG']", the second by reporting graph 0's
guard failure instead of a summary:

```
python test/dynamo/test_aot_compile.py \
  TestAOTCompile.test_aot_compile_module_dispatches_on_global_guard
python test/dynamo/test_aot_compile.py \
  TestAOTCompile.test_aot_compile_module_no_match_error
```

Full file, before and after:

```
python test/dynamo/test_aot_compile.py
```

41 tests / 3 errors before, 43 tests / the same 3 errors after. Those three
(test_aot_compile_with_aoti*) are a local environment gap -- AOTI's generated
header cannot find cuda.h -- and fail identically on a clean tree.

Authored with an AI assistant.


ghstack-source-id: be448de
Pull-Request: #192374
bobrenjc93 added a commit that referenced this pull request Aug 6, 2026
Guards on globals are resolved against the traced function's global scope.
AOTCompiledFunction.deserialize already accepts an f_globals argument for
this, and aot_compile_fullgraph supplies the traced function's __globals__ at
capture time, but AOTCompiledModel.deserialize never forwarded one. A reloaded
module artifact therefore rebuilt its guards against only the scope
reconstructible from the serialized bytecode (used_globals plus import
sources). A global that Dynamo specialized away during tracing never appears
in that bytecode, so it is missing from the scope and the guard fails at
dispatch with "KeyError on G['...']" -- for every call, not just mismatched
ones. This only reproduces when a global guard survives to the artifact, which
requires a caller-supplied guard_filter_fn, since the default one drops them.

The second change is diagnostic. When no compiled input's guards matched,
AOTCompiledModel.__call__ ran compiled_results[0] anyway so that its guard
check would raise. With several ModelInputs that always blames the first one,
regardless of which input is actually missing. It now reports why each
compiled input was rejected.

Note on the path not taken: the default guard_filter_fn drops every global
guard, which is the same thing torch.compiler.skip_guard_on_globals_unsafe
does explicitly -- and dropping a load-bearing global guard is silent, not
loud, so a multi-ModelInput model can dispatch to a graph traced under a
different global value and return a wrong answer. Narrowing that default is
the real fix, but it is not a one-line change: guard construction cannot
currently resolve arbitrary global references, and simply keeping them makes
eight existing tests fail with KeyError on G['torch'] and on builtins dicts.
That needs the guard scope threaded through separately, so this change only
makes the globals that callers explicitly keep work correctly, and leaves a
comment at the filter recording why it is still broad.

Test Plan:

Two new tests, both of which fail without this change -- the first with
"KeyError on G['GLOBAL_POOLING_CONFIG']", the second by reporting graph 0's
guard failure instead of a summary:

```
python test/dynamo/test_aot_compile.py \
  TestAOTCompile.test_aot_compile_module_dispatches_on_global_guard
python test/dynamo/test_aot_compile.py \
  TestAOTCompile.test_aot_compile_module_no_match_error
```

Full file, before and after:

```
python test/dynamo/test_aot_compile.py
```

41 tests / 3 errors before, 43 tests / the same 3 errors after. Those three
(test_aot_compile_with_aoti*) are a local environment gap -- AOTI's generated
header cannot find cuda.h -- and fail identically on a clean tree.

Authored with an AI assistant.


ghstack-source-id: be448de
Pull-Request: #192374
bobrenjc93 added a commit that referenced this pull request Aug 6, 2026
Guards on globals are resolved against the traced function's global scope.
AOTCompiledFunction.deserialize already accepts an f_globals argument for
this, and aot_compile_fullgraph supplies the traced function's __globals__ at
capture time, but AOTCompiledModel.deserialize never forwarded one. A reloaded
module artifact therefore rebuilt its guards against only the scope
reconstructible from the serialized bytecode (used_globals plus import
sources). A global that Dynamo specialized away during tracing never appears
in that bytecode, so it is missing from the scope and the guard fails at
dispatch with "KeyError on G['...']" -- for every call, not just mismatched
ones. This only reproduces when a global guard survives to the artifact, which
requires a caller-supplied guard_filter_fn, since the default one drops them.

The second change is diagnostic. When no compiled input's guards matched,
AOTCompiledModel.__call__ ran compiled_results[0] anyway so that its guard
check would raise. With several ModelInputs that always blames the first one,
regardless of which input is actually missing. It now reports why each
compiled input was rejected.

Note on the path not taken: the default guard_filter_fn drops every global
guard, which is the same thing torch.compiler.skip_guard_on_globals_unsafe
does explicitly -- and dropping a load-bearing global guard is silent, not
loud, so a multi-ModelInput model can dispatch to a graph traced under a
different global value and return a wrong answer. Narrowing that default is
the real fix, but it is not a one-line change: guard construction cannot
currently resolve arbitrary global references, and simply keeping them makes
eight existing tests fail with KeyError on G['torch'] and on builtins dicts.
That needs the guard scope threaded through separately, so this change only
makes the globals that callers explicitly keep work correctly, and leaves a
comment at the filter recording why it is still broad.

Test Plan:

Two new tests, both of which fail without this change -- the first with
"KeyError on G['GLOBAL_POOLING_CONFIG']", the second by reporting graph 0's
guard failure instead of a summary:

```
python test/dynamo/test_aot_compile.py \
  TestAOTCompile.test_aot_compile_module_dispatches_on_global_guard
python test/dynamo/test_aot_compile.py \
  TestAOTCompile.test_aot_compile_module_no_match_error
```

Full file, before and after:

```
python test/dynamo/test_aot_compile.py
```

41 tests / 3 errors before, 43 tests / the same 3 errors after. Those three
(test_aot_compile_with_aoti*) are a local environment gap -- AOTI's generated
header cannot find cuda.h -- and fail identically on a clean tree.

Authored with an AI assistant.


ghstack-source-id: be448de
Pull-Request: #192374
bobrenjc93 added a commit that referenced this pull request Aug 6, 2026
Guards on globals are resolved against the traced function's global scope.
AOTCompiledFunction.deserialize already accepts an f_globals argument for
this, and aot_compile_fullgraph supplies the traced function's __globals__ at
capture time, but AOTCompiledModel.deserialize never forwarded one. A reloaded
module artifact therefore rebuilt its guards against only the scope
reconstructible from the serialized bytecode (used_globals plus import
sources). A global that Dynamo specialized away during tracing never appears
in that bytecode, so it is missing from the scope and the guard fails at
dispatch with "KeyError on G['...']" -- for every call, not just mismatched
ones. This only reproduces when a global guard survives to the artifact, which
requires a caller-supplied guard_filter_fn, since the default one drops them.

The second change is diagnostic. When no compiled input's guards matched,
AOTCompiledModel.__call__ ran compiled_results[0] anyway so that its guard
check would raise. With several ModelInputs that always blames the first one,
regardless of which input is actually missing. It now reports why each
compiled input was rejected.

Note on the path not taken: the default guard_filter_fn drops every global
guard, which is the same thing torch.compiler.skip_guard_on_globals_unsafe
does explicitly -- and dropping a load-bearing global guard is silent, not
loud, so a multi-ModelInput model can dispatch to a graph traced under a
different global value and return a wrong answer. Narrowing that default is
the real fix, but it is not a one-line change: guard construction cannot
currently resolve arbitrary global references, and simply keeping them makes
eight existing tests fail with KeyError on G['torch'] and on builtins dicts.
That needs the guard scope threaded through separately, so this change only
makes the globals that callers explicitly keep work correctly, and leaves a
comment at the filter recording why it is still broad.

Test Plan:

Two new tests, both of which fail without this change -- the first with
"KeyError on G['GLOBAL_POOLING_CONFIG']", the second by reporting graph 0's
guard failure instead of a summary:

```
python test/dynamo/test_aot_compile.py \
  TestAOTCompile.test_aot_compile_module_dispatches_on_global_guard
python test/dynamo/test_aot_compile.py \
  TestAOTCompile.test_aot_compile_module_no_match_error
```

Full file, before and after:

```
python test/dynamo/test_aot_compile.py
```

41 tests / 3 errors before, 43 tests / the same 3 errors after. Those three
(test_aot_compile_with_aoti*) are a local environment gap -- AOTI's generated
header cannot find cuda.h -- and fail identically on a clean tree.

Authored with an AI assistant.


ghstack-source-id: be448de
Pull-Request: #192374
bobrenjc93 added a commit that referenced this pull request Aug 7, 2026
Guards on globals are resolved against the traced function's global scope.
AOTCompiledFunction.deserialize already accepts an f_globals argument for
this, and aot_compile_fullgraph supplies the traced function's __globals__ at
capture time, but AOTCompiledModel.deserialize never forwarded one. A reloaded
module artifact therefore rebuilt its guards against only the scope
reconstructible from the serialized bytecode (used_globals plus import
sources). A global that Dynamo specialized away during tracing never appears
in that bytecode, so it is missing from the scope and the guard fails at
dispatch with "KeyError on G['...']" -- for every call, not just mismatched
ones. This only reproduces when a global guard survives to the artifact, which
requires a caller-supplied guard_filter_fn, since the default one drops them.

The second change is diagnostic. When no compiled input's guards matched,
AOTCompiledModel.__call__ ran compiled_results[0] anyway so that its guard
check would raise. With several ModelInputs that always blames the first one,
regardless of which input is actually missing. It now reports why each
compiled input was rejected.

Note on the path not taken: the default guard_filter_fn drops every global
guard, which is the same thing torch.compiler.skip_guard_on_globals_unsafe
does explicitly -- and dropping a load-bearing global guard is silent, not
loud, so a multi-ModelInput model can dispatch to a graph traced under a
different global value and return a wrong answer. Narrowing that default is
the real fix, but it is not a one-line change: guard construction cannot
currently resolve arbitrary global references, and simply keeping them makes
eight existing tests fail with KeyError on G['torch'] and on builtins dicts.
That needs the guard scope threaded through separately, so this change only
makes the globals that callers explicitly keep work correctly, and leaves a
comment at the filter recording why it is still broad.

Test Plan:

Two new tests, both of which fail without this change -- the first with
"KeyError on G['GLOBAL_POOLING_CONFIG']", the second by reporting graph 0's
guard failure instead of a summary:

```
python test/dynamo/test_aot_compile.py \
  TestAOTCompile.test_aot_compile_module_dispatches_on_global_guard
python test/dynamo/test_aot_compile.py \
  TestAOTCompile.test_aot_compile_module_no_match_error
```

Full file, before and after:

```
python test/dynamo/test_aot_compile.py
```

41 tests / 3 errors before, 43 tests / the same 3 errors after. Those three
(test_aot_compile_with_aoti*) are a local environment gap -- AOTI's generated
header cannot find cuda.h -- and fail identically on a clean tree.

Authored with an AI assistant.


ghstack-source-id: be448de
Pull-Request: #192374
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@bobrenjc93 has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Aug 14, 2026
Guards on globals are resolved against the traced function's global scope.
AOTCompiledFunction.deserialize already accepts an f_globals argument for
this, and aot_compile_fullgraph supplies the traced function's __globals__ at
capture time, but AOTCompiledModel.deserialize never forwarded one. A reloaded
module artifact therefore rebuilt its guards against only the scope
reconstructible from the serialized bytecode (used_globals plus import
sources). A global that Dynamo specialized away during tracing never appears
in that bytecode, so it is missing from the scope and the guard fails at
dispatch with "KeyError on G['...']" -- on every call, not just on mismatched
ones. This only reproduces when a global guard survives into the artifact,
which needs a caller-supplied guard_filter_fn, since the default one drops
them all.

Two details of the fix are load-bearing. The scope is resolved from
model.forward rather than from the model, because get_traced_fn's nn.Module
branch returns Module._wrapped_call_impl whenever a forward hook is
registered: resolving from the model silently skips hooked modules and can
inject torch/nn/modules/module.py's namespace over a colliding graph-input
global. And it is threaded through a dedicated _guard_globals rather than
through _extra_globals, which feeds forward_callable and therefore rewires
what the compiled bytecode reads -- routed there, a reloaded artifact resolved
module-level globals against the loading process instead of against the
serialized snapshot, quietly changing results.

What that guard scope actually is matters, and an earlier version of this
change described it wrongly. The scope is the loading process's module dict
itself, handed to load_guard_manager by reference and not copied. The C++
guard manager holds the dict it is given, so a global rebound after the
artifact is loaded redirects dispatch on the next call. The first version
built a fresh dict -- dict(fn.__globals__) merged with the supplied scope --
which snapshotted the loading process at deserialization time: a serving
process that rebound a guarded global afterwards went on serving whichever
graph had matched at load time, silently and with the right shapes and
dtypes. There is also deliberately no fallback to the serialized scope. A
guarded global the loading process does not have now fails the guard and
raises "No AOT compiled graph matched ... KeyError on G['...']", where the
merge used to resolve it against the value baked into the artifact and serve.
That trade is chosen on purpose: this feature's deployment model is capture on
one machine and serve on another, so a loud refusal on the serving machine is
recoverable and a silent wrong answer is not. Dropping the merge costs
nothing measurable -- the dict(fn.__globals__) base only ever contributed
Dynamo's synthetic __import_*/__compiled_fn_* aliases, which no guard
references, plus a stale copy of used_globals.

Note that this liveness applies to the module path only. The function path,
torch.compiler.load_compiled_function(f_globals=...), still feeds
_extra_globals, which forward_callable copies into a fresh dict, so its guards
resolve against that copy. Giving functions a separate live guard scope is an
API change in torch/compiler/__init__.py and is left for a follow-up.

The rest is dispatch behaviour on AOTCompiledModel. When no compiled input's
guards matched, __call__ ran compiled_results[0] anyway so that its guard
check would raise, which with several ModelInputs always blames the first one.
It now reports why each compiled input was rejected, one line apiece, printing
the failing guard's verbose_code_parts rather than interpolating
GuardDebugInfo, whose multi-line repr destroys the per-entry layout. Raising
instead of running graph 0 would have removed an escape hatch on the way,
though: a result that had opted out with disable_guard_check() used to be
served by that fall-through. __call__ now looks for an opted-out result after
-- and only after -- a real guard match has been sought, so a module artifact
keeps the same opt-out a function artifact has for a mismatch the caller
judges benign, and dispatch is unchanged when nobody opted out. The ordering
there is the whole point and is now pinned by a test: an opted-out result
accepts anything, so folding it into the primary scan serves the first
artifact for a call the second one was compiled for.

Note on the path not taken: the default guard_filter_fn drops every global
guard, which is exactly what torch.compiler.skip_guard_on_globals_unsafe does
explicitly, and the "unsafe" in that name applies here too -- a dropped global
guard is silent, not loud, so a multi-ModelInput model can dispatch into a
graph traced under a different global value and return a wrong answer.
Narrowing that default is the real fix, and it is not a one-line change: guard
construction cannot resolve arbitrary global references today, and narrowing
the default to keep every serializable global guard makes three existing tests
in this file -- test_aot_compile_basic_forward,
test_aot_compile_repeat_interleave and test_aot_compile_with_redistribute --
fail with KeyError on G['_global_forward_hooks'], nn.Module's own hook dicts,
which the reconstructed scope has no binding for. That wants the guard scope
threaded through guard construction separately, so this change only makes the
globals a caller explicitly keeps work correctly, and leaves a comment at the
filter recording why it is still broad.

Test Plan:

Eight new tests in test/dynamo/test_aot_compile.py, all in TestAOTCompile.
The scope-plumbing ones fail without the change with KeyError on
G['GLOBAL_POOLING_CONFIG']; the hook variant keeps failing that way if the
scope is resolved from the model instead of from model.forward, which is how
the fix was first written:

```
python test/dynamo/test_aot_compile.py \
  TestAOTCompile.test_aot_compile_module_dispatches_on_global_guard
python test/dynamo/test_aot_compile.py \
  TestAOTCompile.test_aot_compile_module_scope_resolves_through_forward_hook
```

The dispatch ones fail because the old code raises graph 0's own guard failure
rather than a per-input summary, and because the opt-out has to be consulted
last:

```
python test/dynamo/test_aot_compile.py \
  TestAOTCompile.test_aot_compile_module_no_match_error
python test/dynamo/test_aot_compile.py \
  TestAOTCompile.test_aot_compile_module_disable_guard_check
python test/dynamo/test_aot_compile.py \
  TestAOTCompile.test_disable_guard_check_does_not_shadow_a_matching_result
```

And three pin the guard scope itself:

```
python test/dynamo/test_aot_compile.py \
  TestAOTCompile.test_aot_compile_module_reload_is_hermetic
python test/dynamo/test_aot_compile.py \
  TestAOTCompile.test_aot_compile_module_guards_track_rebound_global
python test/dynamo/test_aot_compile.py \
  TestAOTCompile.test_aot_compile_module_absent_global_fails_guard
```

The hermeticity test passes before and after by design -- it exists to fail if
the guard scope is ever routed back through _extra_globals, which was the
first version of this fix. Its rebind happens before the load, because
deserialization copies extra_globals into the reconstructed function's globals
and a rebind after the load is invisible either way. The other two fail on the
pre-change tree: the rebound-global one serves the "sum" graph after the
global is rebound to "mean", and the absent-global one succeeds where it must
raise. Both were also reproduced across two real processes, not just in one.

Reverting the guard-scope hunk back to the dict() merge, with everything else
in place, fails exactly those two and nothing else.

Full file:

```
python test/dynamo/test_aot_compile.py
```

41 tests / 3 errors at the base commit, 49 tests / the same 3 errors after.
Those three (test_aot_compile_with_aoti*) are a local environment gap -- AOTI's
generated header cannot find cuda.h -- and fail identically on a clean tree.

Authored with an AI assistant.
ghstack-source-id: 0624006
Pull-Request: #192374
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
This was referenced Aug 22, 2026
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@bobrenjc93 has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@bobrenjc93 has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

1 similar comment
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@bobrenjc93 has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Superseded by the canonical precompile stack #195353-#195362; this change lives in #195354. Closing to consolidate review there. The branch is kept on GitHub.

@bobrenjc93 bobrenjc93 closed this Sep 3, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/981/head branch November 11, 2026 01:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request meta-exported module: dynamo topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant