Repository navigation
[ref-stack][aot_compile] Fix global guards on reloaded nn.Module artifacts - #195354
bobrenjc93 wants to merge 57 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/195354
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit 28e7c03 with merge base 9d5a710 ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
A standalone aot_compile fix, which the precompile PR at the top of this stack also needs: it 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, keyword-only `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. Using the live scope has a side effect worth knowing about. Dynamo mints `__import_*` aliases into the TRACING process's globals (symbolic_convert.import_source) and roots guards at them -- every child nn.Module call guards its hook dicts through G['__import_torch_dot_nn_dot_modules_dot_module']. A process that only loads never traced, so its module dict has none of them. Loading therefore seeds the artifact's recorded import aliases into the user's live module globals with `setdefault`, so only the synthetic names are added and a real global the loading process already has keeps its live value. Each alias is resolved with `importlib.import_module` while the guard manager is being built, so a module the serving process cannot import raises at load rather than at the first call. 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. `emits_native_code(backend_name)` in package.py is the one place that decides this; `CompileArtifacts.check_compatibility` calls it directly, and eval_frame.py's `_backend_emits_native_code` helper resolves what `torch.compile` actually hands `_optimize`/`_optimize_assert` (a `_TorchCompileWrapper` whose `compiler_name` is the string the user wrote, or None) before asking. Anything unrecognised is assumed to generate code, since a false rejection at load is recoverable and running a foreign kernel is not. Which devices a graph targets is now a scan of the whole graph (`_graph_device_types`, returning a frozenset) rather than the device of the first meta value. The single-value read was wrong in two ways. Under dynamic shapes the leading placeholder is a SymInt, which has no device, so it reported "cpu" for an all-accelerator graph and hung a toolchain probe and a hard load-time rejection off that answer; values carrying no device now contribute nothing rather than defaulting. And collapsing to one device let a mixed cpu+accelerator graph -- for which inductor still emits vectorized native CPU kernels -- skip both recording and comparing the codegen target. Both `CompileArtifacts` (`device_types`, with a getattr fallback for artifacts pickled before the field existed) and `CompilePackage` accumulate the full set; `check_compatibility` and `_DynamoCacheEntry.check_versions` iterate it sorted, so the specific codegen-target refusal is not masked by a GPU-availability error; `cache_entry()` keys the toolchain probe on "cpu" being in the set and a loaded package restores the set for re-save. `CompilePackage.__init__`'s `requires_native_backend_compatibility` is keyword-only. 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. Review aot_compile.py first (the guard scope and `CompileArtifacts`), then package.py (`emits_native_code`, the alias seeding, the device set through `cache_entry`/`check_versions`), then graph_utils.py and eval_frame.py, then the tests. 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. The recording side is pinned so a regression cannot disarm itself through the predates-the-field skip: an inductor CPU capture records a non-None target, a mixed-device capture (GPU-gated) records one despite an accelerator being present, and a fabricated-graph test pins recording and refusal for `_DynamoCacheEntry` artifacts without needing an accelerator. Authored with an AI assistant. ghstack-source-id: 221166b Pull-Request: #195354
A standalone aot_compile fix, which the precompile PR at the top of this stack also needs: it 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, keyword-only `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. Using the live scope has a side effect worth knowing about. Dynamo mints `__import_*` aliases into the TRACING process's globals (symbolic_convert.import_source) and roots guards at them -- every child nn.Module call guards its hook dicts through G['__import_torch_dot_nn_dot_modules_dot_module']. A process that only loads never traced, so its module dict has none of them. Loading therefore seeds the artifact's recorded import aliases into the user's live module globals with `setdefault`, so only the synthetic names are added and a real global the loading process already has keeps its live value. Each alias is resolved with `importlib.import_module` while the guard manager is being built, so a module the serving process cannot import raises at load rather than at the first call. 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. `emits_native_code(backend_name)` in package.py is the one place that decides this; `CompileArtifacts.check_compatibility` calls it directly, and eval_frame.py's `_backend_emits_native_code` helper resolves what `torch.compile` actually hands `_optimize`/`_optimize_assert` (a `_TorchCompileWrapper` whose `compiler_name` is the string the user wrote, or None) before asking. Anything unrecognised is assumed to generate code, since a false rejection at load is recoverable and running a foreign kernel is not. Which devices a graph targets is now a scan of the whole graph (`_graph_device_types`, returning a frozenset) rather than the device of the first meta value. The single-value read was wrong in two ways. Under dynamic shapes the leading placeholder is a SymInt, which has no device, so it reported "cpu" for an all-accelerator graph and hung a toolchain probe and a hard load-time rejection off that answer; values carrying no device now contribute nothing rather than defaulting. And collapsing to one device let a mixed cpu+accelerator graph -- for which inductor still emits vectorized native CPU kernels -- skip both recording and comparing the codegen target. Both `CompileArtifacts` (`device_types`, with a getattr fallback for artifacts pickled before the field existed) and `CompilePackage` accumulate the full set; `check_compatibility` and `_DynamoCacheEntry.check_versions` iterate it sorted, so the specific codegen-target refusal is not masked by a GPU-availability error; `cache_entry()` keys the toolchain probe on "cpu" being in the set and a loaded package restores the set for re-save. `CompilePackage.__init__`'s `requires_native_backend_compatibility` is keyword-only. 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. Review aot_compile.py first (the guard scope and `CompileArtifacts`), then package.py (`emits_native_code`, the alias seeding, the device set through `cache_entry`/`check_versions`), then graph_utils.py and eval_frame.py, then the tests. 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. The recording side is pinned so a regression cannot disarm itself through the predates-the-field skip: an inductor CPU capture records a non-None target, a mixed-device capture (GPU-gated) records one despite an accelerator being present, and a fabricated-graph test pins recording and refusal for `_DynamoCacheEntry` artifacts without needing an accelerator. Authored with an AI assistant. ghstack-source-id: 221166b Pull-Request: #195354
A standalone aot_compile fix, which the precompile PR at the top of this stack also needs: it 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, keyword-only `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. Using the live scope has a side effect worth knowing about. Dynamo mints `__import_*` aliases into the TRACING process's globals (symbolic_convert.import_source) and roots guards at them -- every child nn.Module call guards its hook dicts through G['__import_torch_dot_nn_dot_modules_dot_module']. A process that only loads never traced, so its module dict has none of them. Loading therefore seeds the artifact's recorded import aliases into the user's live module globals with `setdefault`, so only the synthetic names are added and a real global the loading process already has keeps its live value. Each alias is resolved with `importlib.import_module` while the guard manager is being built, so a module the serving process cannot import raises at load rather than at the first call. 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. `emits_native_code(backend_name)` in package.py is the one place that decides this; `CompileArtifacts.check_compatibility` calls it directly, and eval_frame.py's `_backend_emits_native_code` helper resolves what `torch.compile` actually hands `_optimize`/`_optimize_assert` (a `_TorchCompileWrapper` whose `compiler_name` is the string the user wrote, or None) before asking. Anything unrecognised is assumed to generate code, since a false rejection at load is recoverable and running a foreign kernel is not. Which devices a graph targets is now a scan of the whole graph (`_graph_device_types`, returning a frozenset) rather than the device of the first meta value. The single-value read was wrong in two ways. Under dynamic shapes the leading placeholder is a SymInt, which has no device, so it reported "cpu" for an all-accelerator graph and hung a toolchain probe and a hard load-time rejection off that answer; values carrying no device now contribute nothing rather than defaulting. And collapsing to one device let a mixed cpu+accelerator graph -- for which inductor still emits vectorized native CPU kernels -- skip both recording and comparing the codegen target. Both `CompileArtifacts` (`device_types`, with a getattr fallback for artifacts pickled before the field existed) and `CompilePackage` accumulate the full set; `check_compatibility` and `_DynamoCacheEntry.check_versions` iterate it sorted, so the specific codegen-target refusal is not masked by a GPU-availability error; `cache_entry()` keys the toolchain probe on "cpu" being in the set and a loaded package restores the set for re-save. `CompilePackage.__init__`'s `requires_native_backend_compatibility` is keyword-only. 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. Review aot_compile.py first (the guard scope and `CompileArtifacts`), then package.py (`emits_native_code`, the alias seeding, the device set through `cache_entry`/`check_versions`), then graph_utils.py and eval_frame.py, then the tests. 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. The recording side is pinned so a regression cannot disarm itself through the predates-the-field skip: an inductor CPU capture records a non-None target, a mixed-device capture (GPU-gated) records one despite an accelerator being present, and a fabricated-graph test pins recording and refusal for `_DynamoCacheEntry` artifacts without needing an accelerator. Authored with an AI assistant. ghstack-source-id: 221166b Pull-Request: #195354
A standalone aot_compile fix, which the precompile PR at the top of this stack also needs: it 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, keyword-only `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. Using the live scope has a side effect worth knowing about. Dynamo mints `__import_*` aliases into the TRACING process's globals (symbolic_convert.import_source) and roots guards at them -- every child nn.Module call guards its hook dicts through G['__import_torch_dot_nn_dot_modules_dot_module']. A process that only loads never traced, so its module dict has none of them. Loading therefore seeds the artifact's recorded import aliases into the user's live module globals with `setdefault`, so only the synthetic names are added and a real global the loading process already has keeps its live value. Each alias is resolved with `importlib.import_module` while the guard manager is being built, so a module the serving process cannot import raises at load rather than at the first call. 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. `emits_native_code(backend_name)` in package.py is the one place that decides this; `CompileArtifacts.check_compatibility` calls it directly, and eval_frame.py's `_backend_emits_native_code` helper resolves what `torch.compile` actually hands `_optimize`/`_optimize_assert` (a `_TorchCompileWrapper` whose `compiler_name` is the string the user wrote, or None) before asking. Anything unrecognised is assumed to generate code, since a false rejection at load is recoverable and running a foreign kernel is not. Which devices a graph targets is now a scan of the whole graph (`_graph_device_types`, returning a frozenset) rather than the device of the first meta value. The single-value read was wrong in two ways. Under dynamic shapes the leading placeholder is a SymInt, which has no device, so it reported "cpu" for an all-accelerator graph and hung a toolchain probe and a hard load-time rejection off that answer; values carrying no device now contribute nothing rather than defaulting. And collapsing to one device let a mixed cpu+accelerator graph -- for which inductor still emits vectorized native CPU kernels -- skip both recording and comparing the codegen target. Both `CompileArtifacts` (`device_types`, with a getattr fallback for artifacts pickled before the field existed) and `CompilePackage` accumulate the full set; `check_compatibility` and `_DynamoCacheEntry.check_versions` iterate it sorted, so the specific codegen-target refusal is not masked by a GPU-availability error; `cache_entry()` keys the toolchain probe on "cpu" being in the set and a loaded package restores the set for re-save. `CompilePackage.__init__`'s `requires_native_backend_compatibility` is keyword-only. 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. Review aot_compile.py first (the guard scope and `CompileArtifacts`), then package.py (`emits_native_code`, the alias seeding, the device set through `cache_entry`/`check_versions`), then graph_utils.py and eval_frame.py, then the tests. 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. The recording side is pinned so a regression cannot disarm itself through the predates-the-field skip: an inductor CPU capture records a non-None target, a mixed-device capture (GPU-gated) records one despite an accelerator being present, and a fabricated-graph test pins recording and refusal for `_DynamoCacheEntry` artifacts without needing an accelerator. Authored with an AI assistant. ghstack-source-id: 221166b Pull-Request: #195354
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
|
@claude /pr-review |
[ghstack-poisoned]
|
@claude /pr-review |
|
Claude finished @bobrenjc93's task in 37m 42s —— View job Round 23: three of the four claimed fixes verify cleanly and this round closes a lot of standing items — but the predicate consolidation went the wrong direction and made the raising-branch missing-global detection dead code, and the new Full review of #195354PR Review: #195354SummaryFixes global guards on reloaded Delta since round 22, separating PR-owned from base-owned. The raw This PR's own delta is four items:
What closes this roundThe The The
And the raising-guard half of my long-standing Code QualityThe predicate consolidation made the except-branch missing-global detection dead code, silently undoing round 21's fix. except Exception as e:
detail = str(e).replace("\n", " ")
# A guard that RAISES a missing-global error still names the
# global; feed that into the same detection the non-raising
# branch uses ...
if "KeyError on G[" in detail:
missing_global = TrueNothing that raises can contain that substring. Concretely: The The sharp consequence is not the swallowed error message, it is the state: Hoisting
The The footer is still exclusive ( The guard-scope seeding is unconditional with respect to guard filtering ( A
The nested-compile-region config path is outside the in-scope sample. API Design (carried forward, all FAQ'd)
Both store reload sites take the constructor default The resume-name collision class is open at this commit. The Backward Compatibility (carried forward, both FAQ'd)A capture under A mixed cpu+accelerator artifact hard-fails on a host lacking the accelerator, where pre-PR it loaded — the device set is unioned, the collapse is accelerator-wins, and
TestingThis round's additions are the strongest test delta of any round: the Remaining gaps, each tied to a finding above:
RecommendationApprove with comments Three of the four changes verify cleanly and this round closes a lot: the Two things I would fix before merge, neither large. The predicate consolidation at Carrying forward: a test through |
[ghstack-poisoned]
|
@claude /pr-review |
|
Claude finished @bobrenjc93's task in 59m 20s —— View job Round 24: the Full review of #195354PR Review: #195354SummaryFixes global guards on reloaded Delta since round 23, separating PR-owned from base-owned. The raw This PR's own delta is four items:
What verifiesThe declaration reaches both aot entrypoints, which is the part I'd have expected to break. I traced it rather than trusting the comment. Via
No BC change for existing artifacts. The API DesignThe opt-out is a documented public contract with no misuse warning, and it is the one fail-open lever in a design that is otherwise fail-closed everywhere. The user guide now tells readers that a backend "declaring Relatedly, this attribute is now de facto public API — named in a user guide, read via The docs' exempt list is narrower than the code's.
Code Quality (carried forward, all re-verified at this head)The Sharpening this from round 23: footer selection is now pinned on the non-raising branch — The FAQ's justification for the dispatch loop's The The footer is exclusive ( The guard-scope seeding runs regardless of whether any global guard survived filtering ( A
The nested-compile-region config path is outside the in-scope sample. Both store reload sites take the constructor default The resume-name collision class is open at this commit. TestingThe new test never round-trips the flag it exists to persist. The test's negative half is also asserted only indirectly — Other gaps, each tied to a finding above:
RecommendationApprove with comments The opt-out is the right shape and it lands correctly on both entrypoints — I traced Three things I'd tighten. The opt-out is now advertised in a user guide as a supported declaration, and it is the only user-assertable fail-open lever in a design the FAQ repeatedly justifies as fail-closed — the docs should say that declaring it on a backend that does emit CPU kernels produces the silent wrong-result the gate exists to prevent, and that the attribute is read one Carrying forward: the FAQ's "the C++ guard tree never propagates" claim ( |
Guards on globals resolve against the traced function's global scope.
`AOTCompiledFunction.deserialize` takes `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, and
a global Dynamo specialized away failed every call with "KeyError on G['...']".
`AOTCompiledModel.deserialize` now resolves the scope from
`model.forward.__globals__` and passes it through a new keyword-only
`guard_globals`, kept apart from `_extra_globals`, which feeds the bytecode.
Guards read the live dict by reference: a rebind after load redirects dispatch,
and a missing global fails the guard with no fallback to serialized values. A
`forward` without `__globals__` warns and uses the reconstructed scope. Since
Dynamo roots guards at `__import_*` aliases it mints into the tracing
process's globals, loading inserts the recorded `__import_*` aliases and the
`__builtins_dict___N` key into the live dict without overwriting existing keys. A baked-in `__builtins_dict___N` would otherwise collide with the identical name a later compile in that module regenerates -- `unique_id` is a fresh per-process counter a load never advances -- so `install_global` now skips any name already bound in the global scope. Both public docstrings document this.
It also adds the CPU codegen target the precompile package layer needs.
`SystemInfo` records `(machine, vec_isa, vec_isa_width, vec_isa_macro, simdlen,
march)` for an artifact holding generated CPU code, and the load gate compares
the *resolved* target `(machine, vec_isa, vec_isa_width, vec_isa_macro)` against
what `pick_vec_isa()` picks on the host: the artifact's kernel source was tiled
for the capture ISA and the host recompiles it with its own. `pick_vec_isa()`
already folds the raw knobs (`cpp.simdlen` and `ATEN_CPU_CAPABILITY`; `march` never reaches it) into the
ISA it returns, so the resolved triple is the complete key; simdlen and march
stay in the recorded tuple for diagnostics but do not gate. The sample is taken
under the backend's own inductor config: `torch.compile(options={...})` builds a
`_TorchCompileInductorWrapper` that patches config such as `cpp.simdlen` only for
the duration of `backend()`, which has already returned by the time we sample, so
we re-apply that config while reading `SystemInfo.current()`; otherwise the
fingerprint would record the ambient ISA rather than the one the kernels were
tiled for. `emits_native_code(backend_name)` exempts eager-family artifacts from
the toolchain probe and the comparison.
`_graph_device_types` scans the whole graph instead of reading the first meta
value's device, which misreported a SymInt placeholder as "cpu" and let a mixed
cpu+accelerator graph skip the check.
The Triton-version and GPU-model checks now exempt off the artifact (the
receiver), not the loading host: an artifact built with Triton is rejected on a
Triton-less host, where before the host-side exemption let it load and then fail
later at kernel load.
User-visible: `AOTCompiledModel.__call__` raises `RuntimeError("No AOT compiled
graph matched ...")` listing why each input was rejected instead of running
graph 0's guards, and a result opted out via `disable_guard_check()` is
consulted only after every guarded result was rejected.
`CompilePackage.__init__`'s `requires_native_backend_compatibility` is
keyword-only.
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 the KeyError. Codegen-target
tests patch `_current_cpu_codegen_target` instead of
depending on host hardware.
Authored with an AI assistant.
FAQ
Q: Why does the gate compare only the resolved ISA (machine, vec_isa,
vec_isa_width, vec_isa_macro) and not simdlen and march too? An earlier version
compared all of them exactly.
A: Because pick_vec_isa() already folds simdlen and ATEN_CPU_CAPABILITY (march never reaches pick_vec_isa; it only changes how the same tiled source is compiled)
into the ISA it resolves -- a simdlen that caps the width picks a narrower ISA,
so the recorded width and macros already reflect it -- the resolved triple is
the complete correctness key. Comparing the raw simdlen/march knobs on top of it
is not merely redundant, it is wrong in two ways. First, it rejects an artifact
this host can reproduce: an artifact captured under cpp.simdlen=256 is loadable
on any host that resolves to the same 256-bit ISA, whether the host gets there by
default or via ATEN_CPU_CAPABILITY, yet a raw-simdlen comparison rejects the
default-knob host. Second, it makes the documented escape hatch ineffective --
setting cpp.simdlen to fix an ISA mismatch would only trade the ISA error for a
simdlen error. A related bug the exact comparison hid: the sample was read after
backend() returned, so the _TorchCompileInductorWrapper's config patch (e.g.
cpp.simdlen) had already exited and the fingerprint recorded the ambient ISA,
not the one the kernels were tiled for -- so an artifact could reject its own
build host and accept a wider one. This commit re-applies the wrapper's config
while sampling so the recorded ISA is the one the kernels were actually built
for, and gates on that resolved ISA. The gate is still fail-closed: a genuine
ISA/width/macro mismatch is refused, and the caller can fix it with
ATEN_CPU_CAPABILITY or cpp.simdlen.
Q: A wider host ISA (AVX-512 loading an AVX2 artifact) is a superset, so why
reject it instead of running the narrower kernels?
A: A wider ISA is not a superset here. The kernels were tiled for the narrower
width, so the wider host's masked loads zero-fill the lanes the narrow tiling
never wrote and its unmasked reductions then read them, changing the result.
The comparison is exact -- and it compares the recorded ISA name, its bit
width, and its build macros together -- because
VecSVE(128), VecSVE(256), and VecNEON overlap in name and/or width and only the
full fingerprint tells them apart.
Q: When the loading host has no usable CPU codegen target at all (no C++
toolchain), the check hard-refuses rather than loading best-effort. Isn't that
too aggressive?
A: Fail-closed on purpose. An artifact that recorded a CPU codegen target holds
vectorized CPU kernels that must be compiled to run, and a host with no
toolchain cannot build them, so there is nothing to run best-effort; refusing
with a clear message beats failing deep in compilation. Eager-family artifacts,
which bake no native code, are exempted up front by emits_native_code(), so this
refuses only artifacts that genuinely need a compiler.
Q: The CPU codegen fingerprint records tuple(vec_isa.build_macro()), but for
AVX-512 that macro is the constant CPU_CAPABILITY_AVX512 and does not encode the
bf16/fp16 probe. Two x86 hosts that differ only in AVX-512-BF16 / AMX-FP16
support then produce an identical fingerprint, yet build_arch_flags() appends
-mavx512bf16 / -mamx-fp16 only where supported -- so a capture host bakes bf16
intrinsics and a loading host without them recompiles wrong. Isn't that a
collision?
A: Correct, and a real gap: build_macro() captures the ISA family but not the
bf16/fp16 arch-flag suffixes, so the fingerprint is coarser than the code the
recompile actually emits. The fix is to record build_arch_flags() -- which
subsumes the macros and the -mavx512bf16 / -mamx-fp16 / SVE -msve-vector-bits
suffixes -- rather than build_macro(). That changes the recorded fingerprint
semantics and can only be validated by exercising the codegen path across ISAs,
so it is tracked as a follow-up rather than folded into this commit unverified;
until then the check is correct on ISA family and width and misses only the
same-family bf16/fp16 sub-variant. When that follow-up records build_arch_flags(), note the ordering trap: VecAVX512/VecAMX set _arch_flags as a side effect of their __bool__ probe, so the recorder must read build_arch_flags() only after bool() has run on the instance.
Q: An artifact saved under one backend and loaded under another disagrees on
whether the ISA gate applies (an inductor-saved entry loaded in an eager
session, or the reverse). How is that reconciled?
A: initialize() no longer clobbers _requires_native_backend_compatibility with
the loaded entry's value, so the constructor value -- taken from the backend the
caller is loading under -- stands. That fixes the load gate: an eager
constructor can no longer disarm the ISA check an inductor entry needs, so the
load never relaxes a host. The mirror direction is subtler: an inductor-saved
entry loaded in an eager-family (e.g. aot_eager) session and then re-saved
(literal "eager" records no bundled artifact, so only aot_eager reaches this)
would strip the fingerprint.
That is closed by the monotone OR-accumulate in #195913
(self._requires_native_backend_compatibility |= dynamo.requires...), which
neither the entry nor the constructor can relax; this commit removes only the
clobber the load gate needed.
Q: _graph_device_types walks the FX graph with its own heuristic instead of
reading V.graph.device_types, so it both over-reports (a false "cpu" for unused
placeholders arms the toolchain probe) and under-reports (string device= specs
are invisible). Why reimplement it?
A: The FX-level walk runs before inductor lowering, where V.graph.device_types
is not yet populated, so it cannot be read here; the heuristic is deliberately a
superset because arming the CPU toolchain probe for an artifact that turns out
to hold no CPU code only costs a load-time ISA check the caller can satisfy,
which is the fail-closed direction. String device= kwargs and a .to() device
argument are read, but only in those device positions -- not from any flat arg
-- because an autocast device type is a plain string positional of
_enter_autocast, and trusting every string leaf would inject a phantom "cuda"
into a CPU-only graph (unloadable on the very host that saved it) or a phantom
"cpu" from torch.utils.checkpoint's unconditional autocast("cpu") (arming the
ISA gate on an accelerator-only artifact). Device-carrying method calls beyond
.to()/.cuda()/.xpu() are still narrowing work tracked separately.
Q: A `functools.wraps` wrapper assigned to `forward` silently yields the wrong
guard scope: `get_traced_fn` never unwraps `__wrapped__` and `_get_signature`
uses `follow_wrapped=False`, so a wrapper defined in a different module resolves
guards against the decorator's module with no warning -- the very failure this PR
fixes, in a shape the fix does not cover. Why leave it?
A: The silent case is asymmetric wrapping only: `functools.wraps` copies
`__module__`/`__name__`/`__qualname__` but not `__globals__`, so when the same
wrapper is present at both save and load the scopes agree and the artifact is
correct. It breaks only if the capture and the runtime wrap `forward` in
different modules, which is not a shape any real serve path produces (the loaded
callable installs onto the recorded code object). Unwrapping `__wrapped__` and
comparing `original_code` against `traced_fn.__code__` to warn on the mismatch is
the right hardening and is tracked as follow-up; it is a detection improvement,
not a correctness fix for the paths this PR serves.
Q: Seeding `__builtins_dict___N` into the live module globals makes a later
`torch.compile` in that same module crash. `unique_id()` is a process-global monotonic
counter that a load-only process never advances, so the artifact bakes in the capture
process's `__builtins_dict___0`, deserialize writes that key into the module `__dict__`,
and the next `OutputGraph.__init__` there regenerates `__builtins_dict___0` and hits
`CleanupHook.create`, which raises because the name is already in scope. This is every
caller of the default `guard_filter_fn`, not just those who keep global guards.
A: Correct, and it was a real crash -- reproduced with the default filter. Fixed here in
`OutputGraph.install_global`: after minting a name from `unique_id`, it now skips any
name already bound in `self.global_scope` (`while name in self.global_scope: name =
unique_id(prefix)`) before installing, so a later compile that regenerates a baked-in
`__builtins_dict___N`/`__import_*` name transparently picks the next id instead of
colliding in `CleanupHook.create`. `unique_id` is monotonic, so the loop always
terminates. The seeding itself stays -- guards rooted at those names must resolve -- and
the collision it could cause on the next compile is what this fix removes.
Q: The AOT path inserts the `__import_*` aliases and the `__builtins_dict___N`
key straight into the caller's dict, without the `CleanupHook.disown` the
precompile path does first and without any `_installed_globals`/`uninstall`/
`__del__` bookkeeping -- and because the default `guard_filter_fn` drops every
`is_global` guard, the common path mutates a torch namespace for guards that were
filtered out. Isn't the missing cleanup a hazard?
A: The insertions are bounded and idempotent (`if name not in scope`), so this is
permanent-and-untracked, not unbounded growth, and it mirrors what tracing itself
already does into the same namespace at `symbolic_convert`. The precompile path
needs `disown` and `_installed_globals` because it supports `unload()`; the AOT
artifact has no uninstall surface by design (it is a load-and-run function, not an
installer), so there is nothing to take back out. Seeding a torch namespace when
the filter dropped the global guards is wasteful but harmless -- the keys are
inert if unread, and the one active hazard, a later compile colliding on a baked-in
name, is closed by `install_global` skipping already-bound names (see the collision
FAQ below). A cleanup API on `AOTCompiledFunction`/`AOTCompiledModel` and
gating the seed on whether global guards survived are both reasonable follow-ups;
neither changes a result today.
Q: `_backend_emits_native_code` classifies the same backend differently by
entrypoint and never classifies instance backends: `torch.compile(backend=eager)`
correctly yields `False` (the wrapper stamps `compiler_name`), but
`torch._dynamo.optimize(eager)` stringifies the raw callable to native, an
instance like `CompileCounter` has no `__name__`, and the aot path reads
`"unknown"` after `get_compiler_fn` erased the string. Worse, a user backend
whose function is named `eager` is silently exempted from the ISA gate. Why is
this acceptable?
A: The classifier is fail-closed by construction: an unrecognized backend is
assumed to emit native code and pays the ISA check, which only ever refuses a
load the caller can satisfy. The two "misclassified as native" cases
(`optimize(eager)`, instance backends) therefore cost a spurious toolchain probe,
never a wrong result. The one genuinely fail-open direction -- a user callable
coincidentally named `eager`/`aot_eager` tripping the name blacklist -- requires a
user to name their own inductor-lowering backend after an eager builtin, which is
not a shape that occurs in practice; a name-based blacklist is the only signal
available before `get_compiler_fn` runs, and tightening it (identity match rather
than name, and stamping `compiler_name` on `register_backend`) is tracked
separately. The `"unknown"` the aot path records is the same fail-closed default.
Q: `_NO_NATIVE_CODE_BACKENDS` omits every non-inductor backend that is not
eager-family -- `ts`/`aot_ts`, `invoke_subgraph`, `cudagraphs`, `openxla`, `tvm`,
the `*_TESTING_ONLY` gm-passthrough backends and the minifier backends -- so all
of them are now gated on host ISA even though none emit inductor CPU kernels.
Shouldn't they be exempt?
A: Same fail-closed rationale: these backends are rare enough that the exemption
list intentionally enumerates only the eager family (the common no-codegen path),
and everything else pays a host ISA check. (Correction: that check is NOT
satisfiable on every host -- ATEN_CPU_CAPABILITY / cpp.simdlen can only lower a
host's resolved ISA, never raise it, and a toolchain-less host resolves no target
at all -- so a user backend that bakes no native code now has an opt-out on the
aot_compile path too: declare `emits_native_code = False` on the backend callable
and the artifact records no codegen target and skips the gate, mirroring the
package's requires_native_backend_compatibility.)
Enumerating each additional no-native-code backend is a pure widening of the
exemption with no correctness stake and is deferred; the current list is
conservative in the safe direction.
Q: The mixed cpu+accelerator device change is a load-time behavior change on
existing artifacts that neither the description nor the FAQ mentions: pre-PR a
mixed graph whose first meta value was a CPU tensor recorded `device_type="cpu"`
and skipped the GPU check, so it loaded on a host lacking the accelerator;
post-PR the device set is unioned and every device is checked, so it now
hard-fails there. Isn't that a BC break?
A: It is an intentional correctness fix, and the new answer is the right one: an
artifact that genuinely uses an accelerator must not load on a host without it,
and the pre-PR behavior (silently skipping the GPU check because a CPU tensor
happened to be first) was the bug. The only wrinkle is message ordering -- when
both the accelerator is absent and the ISA differs, the user sees the ISA message
first because `sorted({"cpu","cuda"})` puts codegen first -- and that is
deliberate (ISA skew is fixable via `ATEN_CPU_CAPABILITY`/`cpp.simdlen`, device
absence is not, so leading with the fixable one is the better default). The
behavior change is called out here for the record.
Q: `check_codegen=False` returns early inside the GPU block, so for an
eager-family artifact carrying a cuda device the `toolkit_version`,
`triton_version` and `gpu_name` checks are all skipped -- and `gpu_name` is not a
"describes generated code" check the way the gate's comment justifies. Isn't
skipping `gpu_name` for an eager artifact wrong?
A: Intentional. An eager-family artifact bakes no device-specific code -- no
Triton kernels, no toolkit-versioned cubins, nothing pinned to a particular GPU
model -- so it is portable across accelerators of the same family, and all three
GPU checks exist to protect generated code that an eager artifact does not carry.
Gating them together under `check_codegen` is therefore correct for what the
artifact actually contains; `gpu_name` guarding an eager artifact would refuse a
load that is in fact safe. The comment's "describes generated code" framing is
about why the gate exists, not a per-check taxonomy.
Q: When the loading host reports no CPU codegen target at all,
`_cpu_codegen_target_problem` returns a message that does not name the machine
the artifact was built for. Shouldn't the message name it?
A: The enclosing `RuntimeError` already prints the full cached tuple
(`cached={self.cpu_codegen_target}`, machine included) next to `current=...`, so
the machine is named at the call site. The per-branch string only supplies the
component-level reason for the mismatch, and a `None` host has no component to
compare against -- duplicating the machine there would be redundant.
Q: pick_vec_isa() at save is expensive (seen around 18s cold). Why pay it there?
A: It is gated on needs_cpu_codegen, so only artifacts that will emit native
CPU code reach it, and pick_vec_isa() caches its result -- the probe runs once
per process, not once per save. Recording the resolved ISA at save is what lets
load fail closed against a host that would pick a different ISA; deferring the
probe to load would move the cost, not remove it.
Q: An artifact captured under options={'cpp.simdlen': N} loads only on a host
that resolves to N. Doesn't passing the same options={'cpp.simdlen': N} on the
loading side fix it?
A: No, and this is worth stating explicitly -- including the sharp corner that it
fails even on the very machine that built it, in the same process. On load there is
no backend wrapper, so check_compatibility() samples SystemInfo.current() ambiently
-- outside any torch.compile(options=...) patch, which only takes effect once
tracing begins. simdlen lived only in the per-compile options, never in the global
config, so nothing re-applies it at load and the build host re-resolves to its
native (wider) ISA and rejects its own artifact. The documented escape hatch on the
loading host is therefore the *global* torch._inductor.config.cpp.simdlen (or the
ATEN_CPU_CAPABILITY env var), set before the load, not the options= form. The
capture-time half is fixed here by widening the config.patch context to cover
CompileArtifacts / AOTCompiledFunction construction, so __post_init__'s self-check
samples under the same ISA the fingerprint recorded. Auto-re-applying the recorded
simdlen at load (so the round-trip needs no env/config) is a real improvement, but it
belongs with the load-side recompile-config plumbing that lands with the store-reload
work in #195913, not this commit's gate; the AOT load path deserializes bundled
kernels rather than recompiling from source, so the gate is a run-safety check and the
escape hatch is the supported reload path until then.
Q: The codegen fingerprint is armed from the backend and device
(emits_native_code(backend_name) and "cpu" in device_types), not from whether
inductor actually emitted a cpp kernel. An artifact whose CPU output is all
extern calls (torch.mm lowering to BLAS) still records a target, so the
load-time gate pays the full pick_vec_isa() dry-compile (~19s measured) for
nothing. Arm it from whether a cpp kernel was emitted.
A: The over-arming is deliberate and errs toward correctness. The gate rejects a
host whose resolved ISA differs from the one the kernels were tiled for; if we
under-arm -- record no target when a cpp kernel WAS emitted -- the gate accepts
an ISA-incompatible host and runs a mistiled kernel, a silent-wrong-result/crash
hazard that is strictly worse than a slow load. Arming on "the backend can emit
native CPU code" is the conservative superset that never under-arms. Precisely
detecting "inductor emitted zero cpp kernels for this graph" means introspecting
the compiled artifact's kernel sources, which is not reliably available at this
call site and, per the measurement's own method, needs a built inductor to
validate that the narrower signal never drops a real target; narrowing the arming
to it (and skipping the dry-compile when no cpp kernel exists) is the right
optimization but is tracked as follow-up rather than attempted without a build.
The one-time load cost is also amortized by TORCHINDUCTOR_CACHE_DIR.
Q: The remedy sentence points the user at ATEN_CPU_CAPABILITY /
torch._inductor.config.cpp.simdlen, but on fbcode/x86 pick_vec_isa()
short-circuits to VecAVX2() before reading either knob, so neither can move the
resolved ISA and _current_cpu_codegen_target() can never return None there. The
hint is inert in fbcode.
A: Correct that on fbcode/x86 pick_vec_isa() returns VecAVX2() unconditionally,
so the two knobs the hint names cannot change the resolved ISA and the escape
hatch is a no-op there. The hint is advisory and accurate off fbcode (OSS x86,
where valid_vec_isa_list()/cpp.simdlen/ATEN_CPU_CAPABILITY do resolve the ISA),
which is where an ISA-mismatch rejection is actually reachable; on fbcode the
fixed AVX2 target means two builds on the same machine class agree and the gate
does not fire in the first place. Conditioning the message on config.is_fbcode()
to drop the inert knob suggestion is a reasonable message-only refinement that
changes no gate behavior, deferred with the other fbcode-specific paths that
cannot be validated in this environment.
Q: The two store reload APIs -- DynamoStore.load_package and
DynamoCache.load_and_install_package -- construct CompilePackage(fn,
entry.dynamo) with the constructor default requires_native_backend_compatibility=True
and no backend to derive it from, and initialize() restores _device_types but
not the flag. So an eager package round-tripped through a store upgrades to
native on re-save: cache_entry() pays the pick_vec_isa() probe and stamps a
cpu_codegen_target onto an artifact that bakes no native code, which then
hard-refuses on an ISA-different host. Restore the flag from the entry here (it
records the value), or thread the kwarg through the store APIs.
A: Correct that at this commit the harm is real: the two store paths pass the
bare default True (the eval_frame path is the only one that derives the
constructor value from the backend, so the existing "the constructor value,
taken from the backend, stands" FAQ does not cover the store paths), and this
commit's cache_entry() probes eagerly, so a store round-trip of an eager package
re-saves as native. But the suggested entry-authoritative fix is the wrong
resolution, because at this commit the flag has no compile-path accumulation: it
is written once at construction and never OR'd by a later native compile. Making
the reloaded entry authoritative would fail OPEN in the mirror direction -- a
native session that reloads an eager entry (flag False) would then run native
compiles with the ISA gate disarmed and load a kernel built for another target
on an incompatible host, a silent-wrong-result hazard strictly worse than the
wasteful-but-safe over-arm this comment describes. The correct resolution lands
higher in this same stack (#195913): the flag is made monotone
(self._requires_native_backend_compatibility = self._requires_native_backend_compatibility
or dynamo.requires_native_backend_compatibility, which neither a reload nor a new
compile can relax), and the pick_vec_isa() probe is deferred out of cache_entry
-- the reload path stamps _system_info via SystemInfo.current(cpu_codegen=False)
carrying the entry's recorded target (None for an eager artifact) straight
through re-save, and the probe fires only in update_device_type during an actual
cpu-bearing compile. At the stack tip the store-reloaded eager package therefore
pays no probe and stamps no target on re-save -- exactly the harm this comment
asks for -- while a genuinely native new compile still arms the gate fail-closed.
The eager over-arm visible here is an intermediate-state artifact removed by that
deferred-probe change above it, not a shape the stack ships; adopting a local
entry-authoritative fix here would have to be reverted to reach the safe design.
Q: The CPU-codegen half of this commit -- SystemInfo, emits_native_code, the
check_compatibility rework, the fingerprint gate and roughly half the new tests
-- is an independent feature from the AOTCompiledModel.deserialize guard-scope
fix in the title, and it is the part that can newly hard-refuse a load. Split it
into (1) the guard-scope fix, (2) the _graph_device_types rewrite, and (3) the
CPU codegen fingerprint and gate so each lands on its own evidence.
A: Agreed on the logical separation, and in a fresh stack these would be three
commits. This commit sits deep in a 24-PR ghstack whose upper commits (the
capture session, save() entry point, and the monotone OR-accumulate /
deferred-probe changes that this very FAQ leans on) already depend on the
SystemInfo and emits_native_code surface introduced here; splitting it now
reindexes every PR above it and restarts their in-flight CI, which is a real cost
the reviewer explicitly flagged as "your call". The three parts are individually
reviewable in place: the guard-scope fix is the first three paragraphs and its
KeyError-reproducing tests, _graph_device_types is self-contained, and the
codegen gate is the part the FAQ scrutinizes. Keeping them together is the
smaller net change given the stack's current depth; the split is noted as the
right shape for any future reland.
Q: install_global's collision retry (the `while name in self.global_scope` loop)
lives only in install_global, not install_global_unsafe, which
install_resume_function_global calls directly. Doesn't the resume-name collision
class the retry closes survive for resume functions?
A: The durable separator lands higher in this stack, in #195911, not at this
commit -- `_resume_global_renames`, `package_token` and the per-package uuid are
all absent from package.py at this revision, so this answer describes where the
collision is closed, not code present here. #195911 renames a loaded package's
resume globals to `{name}_{package_token}` (uuid minted once in __init__) while a
fresh compile installs the bare `__resume_at_<offset>_<n>`, so the two can never
collide and install_global_unsafe's assert-only behavior is correct on the resume
path. `__builtins_dict___N` carries no such distinguisher, which is why the retry
loop was added to install_global for it here and now. Until #195911 the resume-name
collision class is pre-existing and open; ghstack lands each PR individually, so
main can carry this commit without #195911's separator for a window; the
resume-name collision in that window is pre-existing, not introduced here. (#195911 also makes an
intra-package duplicate resume name raise loudly, closing the last silent route.)
Q: load_compiled_function passes guard_globals=f_globals, conflating the globals
the function runs in with the globals guards evaluate against, despite the
docstring distinguishing them. Shouldn't they be separate?
A: They are intentionally the same here. A compiled function's guards check the
very globals that function will read at runtime -- that is the point of a global
guard -- so evaluating them against a different dict would guard state the
function never sees. deserialize() keeps guard_globals as a distinct parameter for
callers that genuinely have two dicts (a guard tree rooted in one module served
into another), but load_compiled_function is the common single-module entry point
and binds both to f_globals deliberately. Exposing a second kwarg on it would add
API surface for a split that this entry point, by construction, does not have. The
docstring describes the general deserialize() contract; the narrowing to one dict
at this call site is intended, not an oversight.
Q: The module path auto-resolves its guard scope, but
torch.compiler.load_compiled_function(f) with no f_globals still lands on the
function path and fails any surviving global guard with a bare KeyError on
G['...']. Why not record fn.__module__ at capture and resolve sys.modules[...] the
way AOTCompiledModel does?
A: This commit takes the cheaper of the two remedies the finding offers. When
_guard_globals is None and the guard fails on a KeyError on G[...],
AOTCompiledFunction.__call__ now appends a pointer telling the user to pass
f_globals to load_compiled_function, so the degraded mode names its own fix
instead of surfacing a bare KeyError; AOTCompiledModel's no-match footer gets the
same missing-global branch. Recording the defining module at capture and
resolving sys.modules[...] is the durable version and a reasonable follow-up, but
it is a capture-time schema change, whereas the pointer hint closes the
diagnosability gap without one. The condition is pre-existing, not a regression
introduced here.
Q: SystemInfo.current defaults cpu_codegen to True, which runs the expensive
pick_vec_isa() probe, yet every call site passes cpu_codegen=False explicitly.
Shouldn't the default be False so the probe is opt-in?
A: The default is deliberately the complete value, not the cheap one.
check_compatibility only compares cpu_codegen_target when it is not None, so a
SystemInfo built without the probe silently carries no codegen fingerprint and a
later load on a mismatched ISA is not caught -- a correctness hole. Building one
with the probe is merely slower. Every current call site already passes the flag
explicitly, so the default governs only a future caller that omits it;
defaulting to True means such a caller gets a correct-but-slower artifact rather
than a fast-but-silently-incompatible one. The False overrides sit exactly where
codegen is known to be irrelevant -- the field factory's placeholder and the no-
graph-captured case -- so the expensive probe is opt-OUT there, not opt-in
everywhere.
Q: AOTCompiledModel._no_match_message picks one footer via an exclusive
`if missing_global / else`, so when two results fail and only one lacks a global
the ModelInput hint on the other is dropped; and the two branches test "is a global
missing" with different predicates (`"G['"` over-matches, `"KeyError on G["`
under-matches). Shouldn't the hint be per-result and the predicate shared?
A: Both are real refinements and neither changes a report a user sees today. The
per-result `[i]` lines already print every failure with its own reason; only the
trailing hint is a single footer, so the mixed-cause pair loses advice, not
diagnosis -- and attaching the hint to the `[i]` line that triggered it is the
right shape (it also keeps the len(splitlines)==4 assertions intact), but that is
a message-layout change, not a correctness one. The predicate divergence is a
wording inconsistency: both predicates only gate whether the "pass f_globals / add
a ModelInput" hint is appended, so an over-match appends it spuriously and an
under-match omits it -- in both cases the load still fails with the same error and
the same per-result reasons. Consolidating on `"KeyError on G["` in both places is
the clean fix and is safe to fold; it is called out so the mismatch is not read as
two intentionally different checks.
Q: AOTCompiledFunction.__call__ appends a hint saying the guard scope "was
reconstructed from the serialized bytecode ... pass f_globals to
load_compiled_function", gated on `self._guard_globals is None` -- but that is also
true of every in-process capture that never serialized (the capture path passes
only _extra_globals), so a user who never saved can be told to pass f_globals.
Shouldn't it gate on an explicit "was deserialized" flag?
A: The hint is appended only when a guard actually FAILS on an absent global (a
KeyError reaching G['NAME']), not on every in-process run. A never-serialized
capture reaches it only if its live guards genuinely reference a global that was
deleted after capture -- in which case supplying the missing global (via f_globals
on a reload, or simply keeping it defined) is the correct remedy, so the advice is
directionally right even when the exact API name does not apply to an in-process
object. The predicate is broader than "was deserialized", and gating on an explicit
flag (or reusing _no_match_message's always-true phrasing) is a fair follow-up, but
the message only ever fires on a real missing-global failure, so it does not
misdirect a healthy in-process capture.
Q: `AOTCompiledModel.__call__`'s dispatch loop lets a raising `guard_check`
propagate, while `_no_match_message` tolerates a raising guard. Shouldn't the two
agree?
A: Fixed: the scan now treats a raising guard TREE as "did not match" and moves
on, and the report names the raiser as before. Binding errors are not tolerated:
`prepare_f_locals` runs outside the guarded region, so a call the signature
cannot accept still raises `bind_locals`' TypeError as the plain module would
(pinned by `test_aot_compile_module_wrong_arity_raises_type_error`) instead of a
no-match report telling the user to add a ModelInput. (The C++ guard tree never propagates --
`check_nopybind` clears and returns false -- so today's raisers are Python-side,
`prepare_f_locals` / `bind_locals`, which would fail the call for the same input
anyway; the fix is about the two paths agreeing.) `RaisingGuardManager.check` in
the existing test now raises too, so the scan loop is covered.
Q: `cache_entry()` samples `SystemInfo.current()` ambiently, so a package
compiled under `torch.compile(options={"cpp.simdlen": 256})` on an AVX-512 host
records the 512-bit ISA its kernels were not tiled for -- the bug the AOT half
fixes here. Which commit closes this?
A: Correct at this revision: `cache_entry()` runs from record_package/save_package
after the `_TorchCompileInductorWrapper`'s config_patches scope has exited, and
nothing on the package carries that config here. #195913 closes it directly: it
moves the probe out of `cache_entry` into `update_device_type(graph,
codegen_config=...)`, and convert_frame recovers the wrapper's config from the
compiler_fn chain (`_inductor_codegen_config`) and re-applies it with
`torch._inductor.config.patch` around the sample -- the same re-application
`aot_compile_fullgraph` does here. A local fix would have to stash the config on
the package and re-apply it in `cache_entry`, code #195913 deletes when it
relocates the probe, so the fix lands with the commit that owns the probe's new
home. The load side is unchanged (ambient, with the global cpp.simdlen /
ATEN_CPU_CAPABILITY escape hatch).
Q: The `test_save_guidance_when_a_locals_class_default_cannot_pickle` comment says
the shared "local object" substring covers the pure-Python pickler too, but that
pickler's message ("Can't pickle <class ...>: it's not found as ...") has no such
substring.
A: Right on the parenthetical (the headline -- that AttributeError never escapes --
is wrong: the C pickler `AOTCompilePickler` subclasses raises it unwrapped through
3.13, and 3.14 raises PicklingError "Can't pickle local object"). The pure-Python
pickler is unreachable from `AOTCompilePickler(pickle.Pickler)`, so the comment now
names the two versions' wordings and drops the pure-Python clause. The test moved
to #196454 with the code it pins, so the reword lives there.
Q: `test_eager_backend_entry_is_exempt_from_the_codegen_target`'s native half only
asserts `requires_native_backend_compatibility`; the target the probe recorded is
never checked, and asserting it directly would need a host toolchain.
A: Fixed: the native half patches `_current_cpu_codegen_target` to a sentinel
target and asserts the entry recorded exactly that, so it needs no toolchain.
Q: No test drives the `options=`-patched capture path in `aot_compile_fullgraph`;
the footer branch selection in `_no_match_message` is unpinned; the `__call__`
missing-global hint is unasserted; the ISA table is a hand-rolled loop rather than
`@parametrize`; `check_codegen=False` on cuda is untested.
A: Added: `test_aot_compile_samples_the_codegen_target_under_the_wrappers_config`
(the recorded simdlen is the wrapper's, the ambient config is untouched after),
`assertIn` on each footer in the two no-match tests,
`test_aot_compile_fn_missing_global_hint_names_f_globals`, the ISA table as named
`@parametrize` subtests, and a `check_codegen=False` GPU case in the Triton/GPU
exemption test.
Q: `(line,) = logs.output` plus a `functools.partial(` substring in the
partial-forward fallback test is brittle; the seeds test "sanitizes rather than
cleans up" by filtering `__import_*` names; the mixed-device test depends on
`check_versions` ordering.
A: The single-record unpacking is deliberate -- any extra deserialize warning
should fail the test, that is the contract -- and `functools.partial(` is the repr
Python has emitted for decades. The `__import_*` filter isolates from earlier
tests: any compile writes those aliases into the tracing module's globals
(symbolic_convert's `install_global`) and `CleanupHook` removes them on reset, so
the filter is scoping, not a cleanup leak. The ordering dependence is documented
at `check_versions` ("cpu first ..."); left as is.
Q: The `except (RuntimeError, AttributeError)` arm around `get_traced_fn` in
`aot_compile_module` has no test.
A: Reachable (`mod.forward = torch.add` has `__self__` but no `__func__`) but low
value: it only selects the warning text for an unresolvable guard scope, which the
existing scope tests already exercise on the resolvable side. Left to follow-up
rather than pinned here.
Q: pr-sanity-checks is red -- this commit grew to 2058 lines.
A: The AOT-pickler tests (five `TestAOTCompile` cases plus the whole
`TestAOTCompilePickler` class) exercise code that #196454 introduces, so they
moved down to that commit; this commit is now ~1700 lines and the combined tree is
unchanged.
Q: The AOT-compile page documents the new `f_globals` contract but not the other
new user-visible load failure: an inductor artifact recorded a CPU codegen target
and is refused on a host that resolves a different one, with `ATEN_CPU_CAPABILITY`
/ the global `cpp.simdlen` as the escape hatch.
A: Added to "Choosing a backend" (the section that already contrasts inductor and
eager): what is recorded, the exact error, why a wider ISA is not a superset, how
to make the host resolve the recorded ISA before loading, that `options=` does
not apply at load time, and that eager/aot_eager artifacts are exempt; plus a
cross-reference from `load_compiled_function`'s Returns.
Q: `optimize_assert`'s copy of the `native_backend` threading is untested; the
eager-exemption test only takes the `_optimize` branch, so the two call sites can
drift.
A: The test is now parametrized over `fullgraph` (False -> `_optimize`, True ->
`optimize_assert`) so both paths are pinned.
Q: `initialize()` restores `_device_types` from the cache entry but not
`requires_native_backend_compatibility`, and neither store load path passes the
kwarg, so a loaded eager package loses its exemption and re-saves with a baked
codegen target.
A: Correct at this revision; #195913 closes it in both ways the review lists:
`initialize()` ORs the entry's flag into the package's (monotone, with the probe
deferred), AND `DynamoStore.load_package` / `load_and_install_package` pass
`requires_native_backend_compatibility=entry.dynamo.requires_native_backend_compatibility`
so a False survives the constructor default. The eval_frame path (a native
session reloading an eager entry) is why the entry is not made authoritative on
its own: that would fail open. The manual kwarg in
`test_loaded_eager_package_stays_exempt_on_resave` models that eval_frame path.
Q: The blacklist rationale ("a false rejection at load is recoverable") does not
hold on the `aot_compile` path: `CompileArtifacts` derives the gate solely from the
backend name, so a user backend that emits no native code is fingerprinted with the
capture ISA and cannot be loaded on a narrower or toolchain-less host.
A: Fixed: `CompileArtifacts.requires_native_backend_compatibility` (default True
so artifacts saved before the field keep loading) is set at capture from the
backend -- the eager family by name, or any callable declaring
`emits_native_code = False` (honoured by `_backend_emits_native_code` for the
package path too) -- and `check_compatibility` skips the ISA gate when it is
False. Pinned by `test_aot_compile_backend_declaring_no_native_code_skips_the_isa_gate`
(no target recorded; loads with a host that resolves no target). The docs now
state the true scope: every backend outside the eager family is gated unless it
declares otherwise.
Q: The install-collision retry lands on `install_global` only, but
`install_global_by_id` and the resume-function install also reach `CleanupHook.create`,
which raises on a name that already exists.
A: The resume half is closed by #195911's per-package token rename (the FAQ above
says where). `install_global_by_id` names (`___module_<name>_<id>_c<compile_id>`)
are never seeded by any load path -- `install()` seeds only `import_sources` and
`function_names`, and the AOT loader seeds import aliases and the builtins-dict
key -- so there is no baked-in name for a later compile to collide with (probe:
capture, reset, load, recompile in the same module: OK). Only `__builtins_dict___N`
carries no distinguisher, which is why the retry is scoped to it.
Q: `linux-docs` is red from this PR up.
A: The cross-reference added last round used a `#heading` anchor, which this
docs build (no `myst_heading_anchors`) does not resolve; it now uses the file's
explicit `(choosing-a-backend)=` label and a `{ref}` role.
ghstack-source-id: 6fed4ac
Pull-Request: #195354
[ghstack-poisoned]
Guards on globals resolve against the traced function's global scope.
`AOTCompiledFunction.deserialize` takes `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, and
a global Dynamo specialized away failed every call with "KeyError on G['...']".
`AOTCompiledModel.deserialize` now resolves the scope from
`model.forward.__globals__` and passes it through a new keyword-only
`guard_globals`, kept apart from `_extra_globals`, which feeds the bytecode.
Guards read the live dict by reference: a rebind after load redirects dispatch,
and a missing global fails the guard with no fallback to serialized values. A
`forward` without `__globals__` warns and uses the reconstructed scope. Since
Dynamo roots guards at `__import_*` aliases it mints into the tracing
process's globals, loading inserts the recorded `__import_*` aliases and the
`__builtins_dict___N` key into the live dict without overwriting existing keys. A baked-in `__builtins_dict___N` would otherwise collide with the identical name a later compile in that module regenerates -- `unique_id` is a fresh per-process counter a load never advances -- so `install_global` now skips any name already bound in the global scope. Both public docstrings document this.
It also adds the CPU codegen target the precompile package layer needs.
`SystemInfo` records `(machine, vec_isa, vec_isa_width, vec_isa_macro, simdlen,
march)` for an artifact holding generated CPU code, and the load gate compares
the *resolved* target `(machine, vec_isa, vec_isa_width, vec_isa_macro)` against
what `pick_vec_isa()` picks on the host: the artifact's kernel source was tiled
for the capture ISA and the host recompiles it with its own. `pick_vec_isa()`
already folds the raw knobs (`cpp.simdlen` and `ATEN_CPU_CAPABILITY`; `march` never reaches it) into the
ISA it returns, so the resolved triple is the complete key; simdlen and march
stay in the recorded tuple for diagnostics but do not gate. The sample is taken
under the backend's own inductor config: `torch.compile(options={...})` builds a
`_TorchCompileInductorWrapper` that patches config such as `cpp.simdlen` only for
the duration of `backend()`, which has already returned by the time we sample, so
we re-apply that config while reading `SystemInfo.current()`; otherwise the
fingerprint would record the ambient ISA rather than the one the kernels were
tiled for. `emits_native_code(backend_name)` exempts eager-family artifacts from
the toolchain probe and the comparison.
`_graph_device_types` scans the whole graph instead of reading the first meta
value's device, which misreported a SymInt placeholder as "cpu" and let a mixed
cpu+accelerator graph skip the check.
The Triton-version and GPU-model checks now exempt off the artifact (the
receiver), not the loading host: an artifact built with Triton is rejected on a
Triton-less host, where before the host-side exemption let it load and then fail
later at kernel load.
User-visible: `AOTCompiledModel.__call__` raises `RuntimeError("No AOT compiled
graph matched ...")` listing why each input was rejected instead of running
graph 0's guards, and a result opted out via `disable_guard_check()` is
consulted only after every guarded result was rejected.
`CompilePackage.__init__`'s `requires_native_backend_compatibility` is
keyword-only.
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 the KeyError. Codegen-target
tests patch `_current_cpu_codegen_target` instead of
depending on host hardware.
Authored with an AI assistant.
FAQ
Q: Why does the gate compare only the resolved ISA (machine, vec_isa,
vec_isa_width, vec_isa_macro) and not simdlen and march too? An earlier version
compared all of them exactly.
A: Because pick_vec_isa() already folds simdlen and ATEN_CPU_CAPABILITY (march never reaches pick_vec_isa; it only changes how the same tiled source is compiled)
into the ISA it resolves -- a simdlen that caps the width picks a narrower ISA,
so the recorded width and macros already reflect it -- the resolved triple is
the complete correctness key. Comparing the raw simdlen/march knobs on top of it
is not merely redundant, it is wrong in two ways. First, it rejects an artifact
this host can reproduce: an artifact captured under cpp.simdlen=256 is loadable
on any host that resolves to the same 256-bit ISA, whether the host gets there by
default or via ATEN_CPU_CAPABILITY, yet a raw-simdlen comparison rejects the
default-knob host. Second, it makes the documented escape hatch ineffective --
setting cpp.simdlen to fix an ISA mismatch would only trade the ISA error for a
simdlen error. A related bug the exact comparison hid: the sample was read after
backend() returned, so the _TorchCompileInductorWrapper's config patch (e.g.
cpp.simdlen) had already exited and the fingerprint recorded the ambient ISA,
not the one the kernels were tiled for -- so an artifact could reject its own
build host and accept a wider one. This commit re-applies the wrapper's config
while sampling so the recorded ISA is the one the kernels were actually built
for, and gates on that resolved ISA. The gate is still fail-closed: a genuine
ISA/width/macro mismatch is refused, and the caller can fix it with
ATEN_CPU_CAPABILITY or cpp.simdlen.
Q: A wider host ISA (AVX-512 loading an AVX2 artifact) is a superset, so why
reject it instead of running the narrower kernels?
A: A wider ISA is not a superset here. The kernels were tiled for the narrower
width, so the wider host's masked loads zero-fill the lanes the narrow tiling
never wrote and its unmasked reductions then read them, changing the result.
The comparison is exact -- and it compares the recorded ISA name, its bit
width, and its build macros together -- because
VecSVE(128), VecSVE(256), and VecNEON overlap in name and/or width and only the
full fingerprint tells them apart.
Q: When the loading host has no usable CPU codegen target at all (no C++
toolchain), the check hard-refuses rather than loading best-effort. Isn't that
too aggressive?
A: Fail-closed on purpose. An artifact that recorded a CPU codegen target holds
vectorized CPU kernels that must be compiled to run, and a host with no
toolchain cannot build them, so there is nothing to run best-effort; refusing
with a clear message beats failing deep in compilation. Eager-family artifacts,
which bake no native code, are exempted up front by emits_native_code(), so this
refuses only artifacts that genuinely need a compiler.
Q: The CPU codegen fingerprint records tuple(vec_isa.build_macro()), but for
AVX-512 that macro is the constant CPU_CAPABILITY_AVX512 and does not encode the
bf16/fp16 probe. Two x86 hosts that differ only in AVX-512-BF16 / AMX-FP16
support then produce an identical fingerprint, yet build_arch_flags() appends
-mavx512bf16 / -mamx-fp16 only where supported -- so a capture host bakes bf16
intrinsics and a loading host without them recompiles wrong. Isn't that a
collision?
A: Correct, and a real gap: build_macro() captures the ISA family but not the
bf16/fp16 arch-flag suffixes, so the fingerprint is coarser than the code the
recompile actually emits. The fix is to record build_arch_flags() -- which
subsumes the macros and the -mavx512bf16 / -mamx-fp16 / SVE -msve-vector-bits
suffixes -- rather than build_macro(). That changes the recorded fingerprint
semantics and can only be validated by exercising the codegen path across ISAs,
so it is tracked as a follow-up rather than folded into this commit unverified;
until then the check is correct on ISA family and width and misses only the
same-family bf16/fp16 sub-variant. When that follow-up records build_arch_flags(), note the ordering trap: VecAVX512/VecAMX set _arch_flags as a side effect of their __bool__ probe, so the recorder must read build_arch_flags() only after bool() has run on the instance.
Q: An artifact saved under one backend and loaded under another disagrees on
whether the ISA gate applies (an inductor-saved entry loaded in an eager
session, or the reverse). How is that reconciled?
A: initialize() no longer clobbers _requires_native_backend_compatibility with
the loaded entry's value, so the constructor value -- taken from the backend the
caller is loading under -- stands. That fixes the load gate: an eager
constructor can no longer disarm the ISA check an inductor entry needs, so the
load never relaxes a host. The mirror direction is subtler: an inductor-saved
entry loaded in an eager-family (e.g. aot_eager) session and then re-saved
(literal "eager" records no bundled artifact, so only aot_eager reaches this)
would strip the fingerprint.
That is closed by the monotone OR-accumulate in #195913
(self._requires_native_backend_compatibility |= dynamo.requires...), which
neither the entry nor the constructor can relax; this commit removes only the
clobber the load gate needed.
Q: _graph_device_types walks the FX graph with its own heuristic instead of
reading V.graph.device_types, so it both over-reports (a false "cpu" for unused
placeholders arms the toolchain probe) and under-reports (string device= specs
are invisible). Why reimplement it?
A: The FX-level walk runs before inductor lowering, where V.graph.device_types
is not yet populated, so it cannot be read here; the heuristic is deliberately a
superset because arming the CPU toolchain probe for an artifact that turns out
to hold no CPU code only costs a load-time ISA check the caller can satisfy,
which is the fail-closed direction. String device= kwargs and a .to() device
argument are read, but only in those device positions -- not from any flat arg
-- because an autocast device type is a plain string positional of
_enter_autocast, and trusting every string leaf would inject a phantom "cuda"
into a CPU-only graph (unloadable on the very host that saved it) or a phantom
"cpu" from torch.utils.checkpoint's unconditional autocast("cpu") (arming the
ISA gate on an accelerator-only artifact). Device-carrying method calls beyond
.to()/.cuda()/.xpu() are still narrowing work tracked separately.
Q: A `functools.wraps` wrapper assigned to `forward` silently yields the wrong
guard scope: `get_traced_fn` never unwraps `__wrapped__` and `_get_signature`
uses `follow_wrapped=False`, so a wrapper defined in a different module resolves
guards against the decorator's module with no warning -- the very failure this PR
fixes, in a shape the fix does not cover. Why leave it?
A: The silent case is asymmetric wrapping only: `functools.wraps` copies
`__module__`/`__name__`/`__qualname__` but not `__globals__`, so when the same
wrapper is present at both save and load the scopes agree and the artifact is
correct. It breaks only if the capture and the runtime wrap `forward` in
different modules, which is not a shape any real serve path produces (the loaded
callable installs onto the recorded code object). Unwrapping `__wrapped__` and
comparing `original_code` against `traced_fn.__code__` to warn on the mismatch is
the right hardening and is tracked as follow-up; it is a detection improvement,
not a correctness fix for the paths this PR serves.
Q: Seeding `__builtins_dict___N` into the live module globals makes a later
`torch.compile` in that same module crash. `unique_id()` is a process-global monotonic
counter that a load-only process never advances, so the artifact bakes in the capture
process's `__builtins_dict___0`, deserialize writes that key into the module `__dict__`,
and the next `OutputGraph.__init__` there regenerates `__builtins_dict___0` and hits
`CleanupHook.create`, which raises because the name is already in scope. This is every
caller of the default `guard_filter_fn`, not just those who keep global guards.
A: Correct, and it was a real crash -- reproduced with the default filter. Fixed here in
`OutputGraph.install_global`: after minting a name from `unique_id`, it now skips any
name already bound in `self.global_scope` (`while name in self.global_scope: name =
unique_id(prefix)`) before installing, so a later compile that regenerates a baked-in
`__builtins_dict___N`/`__import_*` name transparently picks the next id instead of
colliding in `CleanupHook.create`. `unique_id` is monotonic, so the loop always
terminates. The seeding itself stays -- guards rooted at those names must resolve -- and
the collision it could cause on the next compile is what this fix removes.
Q: The AOT path inserts the `__import_*` aliases and the `__builtins_dict___N`
key straight into the caller's dict, without the `CleanupHook.disown` the
precompile path does first and without any `_installed_globals`/`uninstall`/
`__del__` bookkeeping -- and because the default `guard_filter_fn` drops every
`is_global` guard, the common path mutates a torch namespace for guards that were
filtered out. Isn't the missing cleanup a hazard?
A: The insertions are bounded and idempotent (`if name not in scope`), so this is
permanent-and-untracked, not unbounded growth, and it mirrors what tracing itself
already does into the same namespace at `symbolic_convert`. The precompile path
needs `disown` and `_installed_globals` because it supports `unload()`; the AOT
artifact has no uninstall surface by design (it is a load-and-run function, not an
installer), so there is nothing to take back out. Seeding a torch namespace when
the filter dropped the global guards is wasteful but harmless -- the keys are
inert if unread, and the one active hazard, a later compile colliding on a baked-in
name, is closed by `install_global` skipping already-bound names (see the collision
FAQ below). A cleanup API on `AOTCompiledFunction`/`AOTCompiledModel` and
gating the seed on whether global guards survived are both reasonable follow-ups;
neither changes a result today.
Q: `_backend_emits_native_code` classifies the same backend differently by
entrypoint and never classifies instance backends: `torch.compile(backend=eager)`
correctly yields `False` (the wrapper stamps `compiler_name`), but
`torch._dynamo.optimize(eager)` stringifies the raw callable to native, an
instance like `CompileCounter` has no `__name__`, and the aot path reads
`"unknown"` after `get_compiler_fn` erased the string. Worse, a user backend
whose function is named `eager` is silently exempted from the ISA gate. Why is
this acceptable?
A: The classifier is fail-closed by construction: an unrecognized backend is
assumed to emit native code and pays the ISA check, which only ever refuses a
load the caller can satisfy. The two "misclassified as native" cases
(`optimize(eager)`, instance backends) therefore cost a spurious toolchain probe,
never a wrong result. The one genuinely fail-open direction -- a user callable
coincidentally named `eager`/`aot_eager` tripping the name blacklist -- requires a
user to name their own inductor-lowering backend after an eager builtin, which is
not a shape that occurs in practice; a name-based blacklist is the only signal
available before `get_compiler_fn` runs, and tightening it (identity match rather
than name, and stamping `compiler_name` on `register_backend`) is tracked
separately. The `"unknown"` the aot path records is the same fail-closed default.
Q: `_NO_NATIVE_CODE_BACKENDS` omits every non-inductor backend that is not
eager-family -- `ts`/`aot_ts`, `invoke_subgraph`, `cudagraphs`, `openxla`, `tvm`,
the `*_TESTING_ONLY` gm-passthrough backends and the minifier backends -- so all
of them are now gated on host ISA even though none emit inductor CPU kernels.
Shouldn't they be exempt?
A: Same fail-closed rationale: these backends are rare enough that the exemption
list intentionally enumerates only the eager family (the common no-codegen path),
and everything else pays a host ISA check. (Correction: that check is NOT
satisfiable on every host -- ATEN_CPU_CAPABILITY / cpp.simdlen can only lower a
host's resolved ISA, never raise it, and a toolchain-less host resolves no target
at all -- so a user backend that bakes no native code now has an opt-out on the
aot_compile path too: declare `emits_native_code = False` on the backend callable
and the artifact records no codegen target and skips the gate, mirroring the
package's requires_native_backend_compatibility.)
Enumerating each additional no-native-code backend is a pure widening of the
exemption with no correctness stake and is deferred; the current list is
conservative in the safe direction.
Q: The mixed cpu+accelerator device change is a load-time behavior change on
existing artifacts that neither the description nor the FAQ mentions: pre-PR a
mixed graph whose first meta value was a CPU tensor recorded `device_type="cpu"`
and skipped the GPU check, so it loaded on a host lacking the accelerator;
post-PR the device set is unioned and every device is checked, so it now
hard-fails there. Isn't that a BC break?
A: It is an intentional correctness fix, and the new answer is the right one: an
artifact that genuinely uses an accelerator must not load on a host without it,
and the pre-PR behavior (silently skipping the GPU check because a CPU tensor
happened to be first) was the bug. The only wrinkle is message ordering -- when
both the accelerator is absent and the ISA differs, the user sees the ISA message
first because `sorted({"cpu","cuda"})` puts codegen first -- and that is
deliberate (ISA skew is fixable via `ATEN_CPU_CAPABILITY`/`cpp.simdlen`, device
absence is not, so leading with the fixable one is the better default). The
behavior change is called out here for the record.
Q: `check_codegen=False` returns early inside the GPU block, so for an
eager-family artifact carrying a cuda device the `toolkit_version`,
`triton_version` and `gpu_name` checks are all skipped -- and `gpu_name` is not a
"describes generated code" check the way the gate's comment justifies. Isn't
skipping `gpu_name` for an eager artifact wrong?
A: Intentional. An eager-family artifact bakes no device-specific code -- no
Triton kernels, no toolkit-versioned cubins, nothing pinned to a particular GPU
model -- so it is portable across accelerators of the same family, and all three
GPU checks exist to protect generated code that an eager artifact does not carry.
Gating them together under `check_codegen` is therefore correct for what the
artifact actually contains; `gpu_name` guarding an eager artifact would refuse a
load that is in fact safe. The comment's "describes generated code" framing is
about why the gate exists, not a per-check taxonomy.
Q: When the loading host reports no CPU codegen target at all,
`_cpu_codegen_target_problem` returns a message that does not name the machine
the artifact was built for. Shouldn't the message name it?
A: The enclosing `RuntimeError` already prints the full cached tuple
(`cached={self.cpu_codegen_target}`, machine included) next to `current=...`, so
the machine is named at the call site. The per-branch string only supplies the
component-level reason for the mismatch, and a `None` host has no component to
compare against -- duplicating the machine there would be redundant.
Q: pick_vec_isa() at save is expensive (seen around 18s cold). Why pay it there?
A: It is gated on needs_cpu_codegen, so only artifacts that will emit native
CPU code reach it, and pick_vec_isa() caches its result -- the probe runs once
per process, not once per save. Recording the resolved ISA at save is what lets
load fail closed against a host that would pick a different ISA; deferring the
probe to load would move the cost, not remove it.
Q: An artifact captured under options={'cpp.simdlen': N} loads only on a host
that resolves to N. Doesn't passing the same options={'cpp.simdlen': N} on the
loading side fix it?
A: No, and this is worth stating explicitly -- including the sharp corner that it
fails even on the very machine that built it, in the same process. On load there is
no backend wrapper, so check_compatibility() samples SystemInfo.current() ambiently
-- outside any torch.compile(options=...) patch, which only takes effect once
tracing begins. simdlen lived only in the per-compile options, never in the global
config, so nothing re-applies it at load and the build host re-resolves to its
native (wider) ISA and rejects its own artifact. The documented escape hatch on the
loading host is therefore the *global* torch._inductor.config.cpp.simdlen (or the
ATEN_CPU_CAPABILITY env var), set before the load, not the options= form. The
capture-time half is fixed here by widening the config.patch context to cover
CompileArtifacts / AOTCompiledFunction construction, so __post_init__'s self-check
samples under the same ISA the fingerprint recorded. Auto-re-applying the recorded
simdlen at load (so the round-trip needs no env/config) is a real improvement, but it
belongs with the load-side recompile-config plumbing that lands with the store-reload
work in #195913, not this commit's gate; the AOT load path deserializes bundled
kernels rather than recompiling from source, so the gate is a run-safety check and the
escape hatch is the supported reload path until then.
Q: The codegen fingerprint is armed from the backend and device
(emits_native_code(backend_name) and "cpu" in device_types), not from whether
inductor actually emitted a cpp kernel. An artifact whose CPU output is all
extern calls (torch.mm lowering to BLAS) still records a target, so the
load-time gate pays the full pick_vec_isa() dry-compile (~19s measured) for
nothing. Arm it from whether a cpp kernel was emitted.
A: The over-arming is deliberate and errs toward correctness. The gate rejects a
host whose resolved ISA differs from the one the kernels were tiled for; if we
under-arm -- record no target when a cpp kernel WAS emitted -- the gate accepts
an ISA-incompatible host and runs a mistiled kernel, a silent-wrong-result/crash
hazard that is strictly worse than a slow load. Arming on "the backend can emit
native CPU code" is the conservative superset that never under-arms. Precisely
detecting "inductor emitted zero cpp kernels for this graph" means introspecting
the compiled artifact's kernel sources, which is not reliably available at this
call site and, per the measurement's own method, needs a built inductor to
validate that the narrower signal never drops a real target; narrowing the arming
to it (and skipping the dry-compile when no cpp kernel exists) is the right
optimization but is tracked as follow-up rather than attempted without a build.
The one-time load cost is also amortized by TORCHINDUCTOR_CACHE_DIR.
Q: The remedy sentence points the user at ATEN_CPU_CAPABILITY /
torch._inductor.config.cpp.simdlen, but on fbcode/x86 pick_vec_isa()
short-circuits to VecAVX2() before reading either knob, so neither can move the
resolved ISA and _current_cpu_codegen_target() can never return None there. The
hint is inert in fbcode.
A: Correct that on fbcode/x86 pick_vec_isa() returns VecAVX2() unconditionally,
so the two knobs the hint names cannot change the resolved ISA and the escape
hatch is a no-op there. The hint is advisory and accurate off fbcode (OSS x86,
where valid_vec_isa_list()/cpp.simdlen/ATEN_CPU_CAPABILITY do resolve the ISA),
which is where an ISA-mismatch rejection is actually reachable; on fbcode the
fixed AVX2 target means two builds on the same machine class agree and the gate
does not fire in the first place. Conditioning the message on config.is_fbcode()
to drop the inert knob suggestion is a reasonable message-only refinement that
changes no gate behavior, deferred with the other fbcode-specific paths that
cannot be validated in this environment.
Q: The two store reload APIs -- DynamoStore.load_package and
DynamoCache.load_and_install_package -- construct CompilePackage(fn,
entry.dynamo) with the constructor default requires_native_backend_compatibility=True
and no backend to derive it from, and initialize() restores _device_types but
not the flag. So an eager package round-tripped through a store upgrades to
native on re-save: cache_entry() pays the pick_vec_isa() probe and stamps a
cpu_codegen_target onto an artifact that bakes no native code, which then
hard-refuses on an ISA-different host. Restore the flag from the entry here (it
records the value), or thread the kwarg through the store APIs.
A: Correct that at this commit the harm is real: the two store paths pass the
bare default True (the eval_frame path is the only one that derives the
constructor value from the backend, so the existing "the constructor value,
taken from the backend, stands" FAQ does not cover the store paths), and this
commit's cache_entry() probes eagerly, so a store round-trip of an eager package
re-saves as native. But the suggested entry-authoritative fix is the wrong
resolution, because at this commit the flag has no compile-path accumulation: it
is written once at construction and never OR'd by a later native compile. Making
the reloaded entry authoritative would fail OPEN in the mirror direction -- a
native session that reloads an eager entry (flag False) would then run native
compiles with the ISA gate disarmed and load a kernel built for another target
on an incompatible host, a silent-wrong-result hazard strictly worse than the
wasteful-but-safe over-arm this comment describes. The correct resolution lands
higher in this same stack (#195913): the flag is made monotone
(self._requires_native_backend_compatibility = self._requires_native_backend_compatibility
or dynamo.requires_native_backend_compatibility, which neither a reload nor a new
compile can relax), and the pick_vec_isa() probe is deferred out of cache_entry
-- the reload path stamps _system_info via SystemInfo.current(cpu_codegen=False)
carrying the entry's recorded target (None for an eager artifact) straight
through re-save, and the probe fires only in update_device_type during an actual
cpu-bearing compile. At the stack tip the store-reloaded eager package therefore
pays no probe and stamps no target on re-save -- exactly the harm this comment
asks for -- while a genuinely native new compile still arms the gate fail-closed.
The eager over-arm visible here is an intermediate-state artifact removed by that
deferred-probe change above it, not a shape the stack ships; adopting a local
entry-authoritative fix here would have to be reverted to reach the safe design.
Q: The CPU-codegen half of this commit -- SystemInfo, emits_native_code, the
check_compatibility rework, the fingerprint gate and roughly half the new tests
-- is an independent feature from the AOTCompiledModel.deserialize guard-scope
fix in the title, and it is the part that can newly hard-refuse a load. Split it
into (1) the guard-scope fix, (2) the _graph_device_types rewrite, and (3) the
CPU codegen fingerprint and gate so each lands on its own evidence.
A: Agreed on the logical separation, and in a fresh stack these would be three
commits. This commit sits deep in a 24-PR ghstack whose upper commits (the
capture session, save() entry point, and the monotone OR-accumulate /
deferred-probe changes that this very FAQ leans on) already depend on the
SystemInfo and emits_native_code surface introduced here; splitting it now
reindexes every PR above it and restarts their in-flight CI, which is a real cost
the reviewer explicitly flagged as "your call". The three parts are individually
reviewable in place: the guard-scope fix is the first three paragraphs and its
KeyError-reproducing tests, _graph_device_types is self-contained, and the
codegen gate is the part the FAQ scrutinizes. Keeping them together is the
smaller net change given the stack's current depth; the split is noted as the
right shape for any future reland.
Q: install_global's collision retry (the `while name in self.global_scope` loop)
lives only in install_global, not install_global_unsafe, which
install_resume_function_global calls directly. Doesn't the resume-name collision
class the retry closes survive for resume functions?
A: The durable separator lands higher in this stack, in #195911, not at this
commit -- `_resume_global_renames`, `package_token` and the per-package uuid are
all absent from package.py at this revision, so this answer describes where the
collision is closed, not code present here. #195911 renames a loaded package's
resume globals to `{name}_{package_token}` (uuid minted once in __init__) while a
fresh compile installs the bare `__resume_at_<offset>_<n>`, so the two can never
collide and install_global_unsafe's assert-only behavior is correct on the resume
path. `__builtins_dict___N` carries no such distinguisher, which is why the retry
loop was added to install_global for it here and now. Until #195911 the resume-name
collision class is pre-existing and open; ghstack lands each PR individually, so
main can carry this commit without #195911's separator for a window; the
resume-name collision in that window is pre-existing, not introduced here. (#195911 also makes an
intra-package duplicate resume name raise loudly, closing the last silent route.)
Q: load_compiled_function passes guard_globals=f_globals, conflating the globals
the function runs in with the globals guards evaluate against, despite the
docstring distinguishing them. Shouldn't they be separate?
A: They are intentionally the same here. A compiled function's guards check the
very globals that function will read at runtime -- that is the point of a global
guard -- so evaluating them against a different dict would guard state the
function never sees. deserialize() keeps guard_globals as a distinct parameter for
callers that genuinely have two dicts (a guard tree rooted in one module served
into another), but load_compiled_function is the common single-module entry point
and binds both to f_globals deliberately. Exposing a second kwarg on it would add
API surface for a split that this entry point, by construction, does not have. The
docstring describes the general deserialize() contract; the narrowing to one dict
at this call site is intended, not an oversight.
Q: The module path auto-resolves its guard scope, but
torch.compiler.load_compiled_function(f) with no f_globals still lands on the
function path and fails any surviving global guard with a bare KeyError on
G['...']. Why not record fn.__module__ at capture and resolve sys.modules[...] the
way AOTCompiledModel does?
A: This commit takes the cheaper of the two remedies the finding offers. When
_guard_globals is None and the guard fails on a KeyError on G[...],
AOTCompiledFunction.__call__ now appends a pointer telling the user to pass
f_globals to load_compiled_function, so the degraded mode names its own fix
instead of surfacing a bare KeyError; AOTCompiledModel's no-match footer gets the
same missing-global branch. Recording the defining module at capture and
resolving sys.modules[...] is the durable version and a reasonable follow-up, but
it is a capture-time schema change, whereas the pointer hint closes the
diagnosability gap without one. The condition is pre-existing, not a regression
introduced here.
Q: SystemInfo.current defaults cpu_codegen to True, which runs the expensive
pick_vec_isa() probe, yet every call site passes cpu_codegen=False explicitly.
Shouldn't the default be False so the probe is opt-in?
A: The default is deliberately the complete value, not the cheap one.
check_compatibility only compares cpu_codegen_target when it is not None, so a
SystemInfo built without the probe silently carries no codegen fingerprint and a
later load on a mismatched ISA is not caught -- a correctness hole. Building one
with the probe is merely slower. Every current call site already passes the flag
explicitly, so the default governs only a future caller that omits it;
defaulting to True means such a caller gets a correct-but-slower artifact rather
than a fast-but-silently-incompatible one. The False overrides sit exactly where
codegen is known to be irrelevant -- the field factory's placeholder and the no-
graph-captured case -- so the expensive probe is opt-OUT there, not opt-in
everywhere.
Q: AOTCompiledModel._no_match_message picks one footer via an exclusive
`if missing_global / else`, so when two results fail and only one lacks a global
the ModelInput hint on the other is dropped; and the two branches test "is a global
missing" with different predicates (`"G['"` over-matches, `"KeyError on G["`
under-matches). Shouldn't the hint be per-result and the predicate shared?
A: Both are real refinements and neither changes a report a user sees today. The
per-result `[i]` lines already print every failure with its own reason; only the
trailing hint is a single footer, so the mixed-cause pair loses advice, not
diagnosis -- and attaching the hint to the `[i]` line that triggered it is the
right shape (it also keeps the len(splitlines)==4 assertions intact), but that is
a message-layout change, not a correctness one. The predicate divergence is a
wording inconsistency: both predicates only gate whether the "pass f_globals / add
a ModelInput" hint is appended, so an over-match appends it spuriously and an
under-match omits it -- in both cases the load still fails with the same error and
the same per-result reasons. Consolidating on `"KeyError on G["` in both places is
the clean fix and is safe to fold; it is called out so the mismatch is not read as
two intentionally different checks.
Q: AOTCompiledFunction.__call__ appends a hint saying the guard scope "was
reconstructed from the serialized bytecode ... pass f_globals to
load_compiled_function", gated on `self._guard_globals is None` -- but that is also
true of every in-process capture that never serialized (the capture path passes
only _extra_globals), so a user who never saved can be told to pass f_globals.
Shouldn't it gate on an explicit "was deserialized" flag?
A: The hint is appended only when a guard actually FAILS on an absent global (a
KeyError reaching G['NAME']), not on every in-process run. A never-serialized
capture reaches it only if its live guards genuinely reference a global that was
deleted after capture -- in which case supplying the missing global (via f_globals
on a reload, or simply keeping it defined) is the correct remedy, so the advice is
directionally right even when the exact API name does not apply to an in-process
object. The predicate is broader than "was deserialized", and gating on an explicit
flag (or reusing _no_match_message's always-true phrasing) is a fair follow-up, but
the message only ever fires on a real missing-global failure, so it does not
misdirect a healthy in-process capture.
Q: `AOTCompiledModel.__call__`'s dispatch loop lets a raising `guard_check`
propagate, while `_no_match_message` tolerates a raising guard. Shouldn't the two
agree?
A: Fixed: the scan now treats a raising guard TREE as "did not match" and moves
on, and the report names the raiser as before. Binding errors are not tolerated:
`prepare_f_locals` runs outside the guarded region, so a call the signature
cannot accept still raises `bind_locals`' TypeError as the plain module would
(pinned by `test_aot_compile_module_wrong_arity_raises_type_error`) instead of a
no-match report telling the user to add a ModelInput. (Correction to an earlier
wording: the C++ guard tree does not swallow everything. A Python-level failure
inside a guard is cleared by `check_nopybind` and reported as no-match -- the
verbose variant renders it as `KeyError on G['...']` -- but a `TORCH_CHECK` or
`py::cast` failure unwinds through `RootGuardManager::check` and reaches Python
as a RuntimeError, which the scan now treats as "this entry did not match" and
reports by name rather than failing the whole call. `RootGuardManager::check`
restoring `PythonTorchFunctionTLS` by hand on that unwinding path is a
pre-existing guards.cpp issue this commit does not change. The Python-side
raisers, `prepare_f_locals` / `bind_locals`, would fail the call for the same
input anyway; the fix is about the two paths agreeing.) `RaisingGuardManager.check` in
the existing test now raises too, so the scan loop is covered.
Q: `cache_entry()` samples `SystemInfo.current()` ambiently, so a package
compiled under `torch.compile(options={"cpp.simdlen": 256})` on an AVX-512 host
records the 512-bit ISA its kernels were not tiled for -- the bug the AOT half
fixes here. Which commit closes this?
A: Correct at this revision: `cache_entry()` runs from record_package/save_package
after the `_TorchCompileInductorWrapper`'s config_patches scope has exited, and
nothing on the package carries that config here. #195913 closes it directly: it
moves the probe out of `cache_entry` into `update_device_type(graph,
codegen_config=...)`, and convert_frame recovers the wrapper's config from the
compiler_fn chain (`_inductor_codegen_config`) and re-applies it with
`torch._inductor.config.patch` around the sample -- the same re-application
`aot_compile_fullgraph` does here. A local fix would have to stash the config on
the package and re-apply it in `cache_entry`, code #195913 deletes when it
relocates the probe, so the fix lands with the commit that owns the probe's new
home. The load side is unchanged (ambient, with the global cpp.simdlen /
ATEN_CPU_CAPABILITY escape hatch).
Q: The `test_save_guidance_when_a_locals_class_default_cannot_pickle` comment says
the shared "local object" substring covers the pure-Python pickler too, but that
pickler's message ("Can't pickle <class ...>: it's not found as ...") has no such
substring.
A: Right on the parenthetical (the headline -- that AttributeError never escapes --
is wrong: the C pickler `AOTCompilePickler` subclasses raises it unwrapped through
3.13, and 3.14 raises PicklingError "Can't pickle local object"). The pure-Python
pickler is unreachable from `AOTCompilePickler(pickle.Pickler)`, so the comment now
names the two versions' wordings and drops the pure-Python clause. The test moved
to #196454 with the code it pins, so the reword lives there.
Q: `test_eager_backend_entry_is_exempt_from_the_codegen_target`'s native half only
asserts `requires_native_backend_compatibility`; the target the probe recorded is
never checked, and asserting it directly would need a host toolchain.
A: Fixed: the native half patches `_current_cpu_codegen_target` to a sentinel
target and asserts the entry recorded exactly that, so it needs no toolchain.
Q: No test drives the `options=`-patched capture path in `aot_compile_fullgraph`;
the footer branch selection in `_no_match_message` is unpinned; the `__call__`
missing-global hint is unasserted; the ISA table is a hand-rolled loop rather than
`@parametrize`; `check_codegen=False` on cuda is untested.
A: Added: `test_aot_compile_samples_the_codegen_target_under_the_wrappers_config`
(the recorded simdlen is the wrapper's, the ambient config is untouched after),
`assertIn` on each footer in the two no-match tests,
`test_aot_compile_fn_missing_global_hint_names_f_globals`, the ISA table as named
`@parametrize` subtests, and a `check_codegen=False` GPU case in the Triton/GPU
exemption test.
Q: `(line,) = logs.output` plus a `functools.partial(` substring in the
partial-forward fallback test is brittle; the seeds test "sanitizes rather than
cleans up" by filtering `__import_*` names; the mixed-device test depends on
`check_versions` ordering.
A: The single-record unpacking is deliberate -- any extra deserialize warning
should fail the test, that is the contract -- and `functools.partial(` is the repr
Python has emitted for decades. The `__import_*` filter isolates from earlier
tests: any compile writes those aliases into the tracing module's globals
(symbolic_convert's `install_global`) and `CleanupHook` removes them on reset, so
the filter is scoping, not a cleanup leak. The ordering dependence is documented
at `check_versions` ("cpu first ..."); left as is.
Q: The `except (RuntimeError, AttributeError)` arm around `get_traced_fn` in
`aot_compile_module` has no test.
A: Reachable (`mod.forward = torch.add` has `__self__` but no `__func__`) but low
value: it only selects the warning text for an unresolvable guard scope, which the
existing scope tests already exercise on the resolvable side. Left to follow-up
rather than pinned here.
Q: pr-sanity-checks is red -- this commit grew to 2058 lines.
A: The AOT-pickler tests (five `TestAOTCompile` cases plus the whole
`TestAOTCompilePickler` class) exercise code that #196454 introduces, so they
moved down to that commit; this commit is now ~1700 lines and the combined tree is
unchanged.
Q: The AOT-compile page documents the new `f_globals` contract but not the other
new user-visible load failure: an inductor artifact recorded a CPU codegen target
and is refused on a host that resolves a different one, with `ATEN_CPU_CAPABILITY`
/ the global `cpp.simdlen` as the escape hatch.
A: Added to "Choosing a backend" (the section that already contrasts inductor and
eager): what is recorded, the exact error, why a wider ISA is not a superset, how
to make the host resolve the recorded ISA before loading, that `options=` does
not apply at load time, and that eager/aot_eager artifacts are exempt; plus a
cross-reference from `load_compiled_function`'s Returns.
Q: `optimize_assert`'s copy of the `native_backend` threading is untested; the
eager-exemption test only takes the `_optimize` branch, so the two call sites can
drift.
A: The test is now parametrized over `fullgraph` (False -> `_optimize`, True ->
`optimize_assert`) so both paths are pinned.
Q: `initialize()` restores `_device_types` from the cache entry but not
`requires_native_backend_compatibility`, and neither store load path passes the
kwarg, so a loaded eager package loses its exemption and re-saves with a baked
codegen target.
A: Correct at this revision; #195913 closes it in both ways the review lists:
`initialize()` ORs the entry's flag into the package's (monotone, with the probe
deferred), AND `DynamoStore.load_package` / `load_and_install_package` pass
`requires_native_backend_compatibility=entry.dynamo.requires_native_backend_compatibility`
so a False survives the constructor default. The eval_frame path (a native
session reloading an eager entry) is why the entry is not made authoritative on
its own: that would fail open. The manual kwarg in
`test_loaded_eager_package_stays_exempt_on_resave` models that eval_frame path.
Q: The blacklist rationale ("a false rejection at load is recoverable") does not
hold on the `aot_compile` path: `CompileArtifacts` derives the gate solely from the
backend name, so a user backend that emits no native code is fingerprinted with the
capture ISA and cannot be loaded on a narrower or toolchain-less host.
A: Fixed: `CompileArtifacts.requires_native_backend_compatibility` (default True
so artifacts saved before the field keep loading) is set at capture from the
backend -- the eager family by name, or any callable declaring
`emits_native_code = False` (honoured by `_backend_emits_native_code` for the
package path too) -- and `check_compatibility` skips the ISA gate when it is
False. Pinned by `test_aot_compile_backend_declaring_no_native_code_skips_the_isa_gate`
(no target recorded; loads with a host that resolves no target). The docs now
state the true scope: every backend outside the eager family is gated unless it
declares otherwise.
Q: The install-collision retry lands on `install_global` only, but
`install_global_by_id` and the resume-function install also reach `CleanupHook.create`,
which raises on a name that already exists.
A: The resume half is closed by #195911's per-package token rename (the FAQ above
says where). `install_global_by_id` names (`___module_<name>_<id>_c<compile_id>`)
are never seeded by any load path -- `install()` seeds only `import_sources` and
`function_names`, and the AOT loader seeds import aliases and the builtins-dict
key -- so there is no baked-in name for a later compile to collide with (probe:
capture, reset, load, recompile in the same module: OK). Only `__builtins_dict___N`
carries no distinguisher, which is why the retry is scoped to it.
Q: `linux-docs` is red from this PR up.
A: The cross-reference added last round used a `#heading` anchor, which this
docs build (no `myst_heading_anchors`) does not resolve; it now uses the file's
explicit `(choosing-a-backend)=` label and a `{ref}` role.
Q: `test_check_compatibility_compares_artifact_against_current_machine` is red
from this PR up.
A: My round-38 change made the ISA gate a conjunction of the backend name and the
new capture-time flag `requires_native_backend_compatibility`; the test flipped
only the name, so the gate stayed disarmed and `assertRaises` failed. The eager
arm now asserts the flag is False for an eager capture and then arms it, so the
name exemption and the receiver-order checks are each pinned on their own.
Q: The opt-out `emits_native_code = False` is a fail-open escape hatch documented
with no warning about what declaring it wrongly costs, and nothing says where it
must live for a wrapped backend.
A: The user guide now says both: the attribute is read off the callable handed to
`torch.compile` or that callable's `compiler_fn` (so for `aot_autograd(fw_compiler=
...)` it goes on the returned object), only the literal False counts, and
declaring it on a backend that does emit native code disables the only check
between a mis-targeted artifact and a first-call crash. The docs also name the
`_NO_NATIVE_CODE_BACKENDS` family rather than listing two of its members.
Q: The attribute is de facto public API with no home in the `SerializableCallable`
protocol; `register_backend` should accept and stamp it so the classifier can
match by identity instead of by name.
A: Not in this commit. A protocol attribute would make it a property of every
serializable backend, but the flag describes the backend's codegen, not its
serializability, and most backends never set it. Stamping via `register_backend`
only covers registered backends; the user callable handed straight to
`torch.compile` is the case the opt-out exists for. Matching the in-tree eager
family by identity rather than name is a reasonable follow-up once the registry
grows that surface; the `__name__ == "eager"` collision it would close is already
FAQ'd above as accepted.
Q: `getattr(..., "emits_native_code", True) is not False` treats a method or a
truthy non-bool as native.
A: Deliberate: the gate fails closed. Anything but the literal False -- a method
(`is not False` on a bound method), a string, a missing attribute -- keeps the
artifact fingerprinted. The docs now say "the plain attribute
`emits_native_code = False`; any other value counts as native".
Q: The raising-guard branch of `_no_match_message` tests `"KeyError on G[" in
detail`, but a raising guard's `str(e)` is the bare KeyError text, so the
predicate is dead.
A: Fixed: the branch now tests `kind == "KeyError" and "G['" in detail`, and
`test_no_match_message_survives_a_raising_guard` asserts the missing-global footer
is present.
Q: `AOTCompiledFunction.__call__`'s missing-global hint says the scope "was
reconstructed from the serialized bytecode" and points at `load_compiled_function`,
but `_guard_globals` defaults to None on an in-process capture that was never
serialized.
A: Fixed: the hint reuses `_no_match_message`'s neutral phrasing (a guarded
global is missing from this process; define it or load with an `f_globals`
carrying it). `AOTCompiledModel` never reaches that branch: its `__call__` has
its own no-match report.
Q: `_simdlen`/`_march` are unpacked and never read in `_cpu_codegen_target_problem`.
A: `cached[:4]` now.
Q: The no-native-code test never round-trips the artifact through save/load, and
nothing pins that the same backend WITHOUT the declaration is fingerprinted.
A: Both added to `test_aot_compile_backend_declaring_no_native_code_skips_the_isa_gate`:
the artifact is saved and reloaded on a host that resolves no codegen target and
still serves, and an undeclared twin of the backend records
`requires_native_backend_compatibility=True` with the capture target.
Q: A subgraph tiled under a nested compile region's own `cpp.simdlen`
(`_patch_nested_region_inductor_config`) is fingerprinted with the ambient ISA.
A: Known and out of scope for the gate: the fingerprint is per artifact, and an
artifact whose regions were tiled for different widths cannot be described by
one target. Nested regions with their own simdlen are an inductor feature the AOT
path does not compose with today; when it does, the fingerprint should become the
set of targets the regions resolved, which is a follow-up to that composition, not
to this gate.
Q: No test where an opted-out result's guard evaluation raises.
A: The raising-guard scan is backend-agnostic (it runs before any backend
attribute is consulted), and `test_no_match_message_survives_a_raising_guard`
covers it; repeating it under the opt-out would exercise the same lines.
Q: `VecNEON` is never instantiated in either test file, so NEON-vs-SVE128 is
covered only by literal tuples.
A: `VecNEON` cannot be instantiated on the x86 hosts CI runs these files on
(`pick_vec_isa` never returns it there, and constructing it by hand exercises no
x86 codepath), so the literal target tuples are the honest cross-architecture
coverage available; the arm64 CI job runs the same comparison end to end through
the real `pick_vec_isa`.
ghstack-source-id: 2b8291a
Pull-Request: #195354
|
@claude please re-review: round-39 fixes are in (all inline threads addressed; FAQ updated in the description). |
|
Claude finished @bobrenjc93's task in 11m 6s —— View job Round 25: all four round-24 items land correctly — the dead predicate is fixed and pinned, the opt-out now round-trips through disk, and the docs carry the misuse warning — but the Full review of #195354PR Review: #195354SummaryFixes global guards on reloaded Delta since round 24. Diffing the round-24 PR-owned three-dot diff against the current one isolates 116 changed lines, and every one is a response to a round-24 item. Base-owned this round (absent from This PR's own delta is five items:
What verifiesThe predicate fix is correct and reachable. And it is now pinned: The opt-out test now covers the thing the field serializes for. The The eager-arm arming fix is a real repair, not cosmetic.
API DesignThe docs' placement rule is wrong for the example it gives. The general rule matches the code —
The accurate statement is simpler and covers both entrypoints: set it on the callable you pass to The misuse warning is now present and correctly scoped.
Both store reload sites take the constructor default The resume-name collision class is open at this commit. Code Quality (carried forward)The FAQ's justification for the dispatch loop's The footer is exclusive ( The guard-scope seeding runs regardless of whether any global guard survived filtering ( A
The recorded The nested-compile-region config path is outside the in-scope sample. Backward Compatibility (carried forward, both FAQ'd)A mixed cpu+accelerator artifact hard-fails on a host lacking the accelerator, where pre-PR it loaded — the device set is unioned, the collapse is accelerator-wins (
A capture under TestingThe strongest addition is the save/reload half of the opt-out test — it is the one assertion that would catch a serialization regression on the new field, and it needs no host toolchain. The second footer Remaining gaps:
RecommendationApprove All four round-24 items land, and three of them are the tighter version of what I asked for. The predicate fix is better than the round-22 form it restores — requiring One thing I would correct, docs-only: the placement rule names Carrying forward, none blocking: a test through |
[ghstack-poisoned]
Guards on globals resolve against the traced function's global scope.
`AOTCompiledFunction.deserialize` takes `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, and
a global Dynamo specialized away failed every call with "KeyError on G['...']".
`AOTCompiledModel.deserialize` now resolves the scope from
`model.forward.__globals__` and passes it through a new keyword-only
`guard_globals`, kept apart from `_extra_globals`, which feeds the bytecode.
Guards read the live dict by reference: a rebind after load redirects dispatch,
and a missing global fails the guard with no fallback to serialized values. A
`forward` without `__globals__` warns and uses the reconstructed scope. Since
Dynamo roots guards at `__import_*` aliases it mints into the tracing
process's globals, loading inserts the recorded `__import_*` aliases and the
`__builtins_dict___N` key into the live dict without overwriting existing keys. A baked-in `__builtins_dict___N` would otherwise collide with the identical name a later compile in that module regenerates -- `unique_id` is a fresh per-process counter a load never advances -- so `install_global` now skips any name already bound in the global scope. Both public docstrings document this.
It also adds the CPU codegen target the precompile package layer needs.
`SystemInfo` records `(machine, vec_isa, vec_isa_width, vec_isa_macro, simdlen,
march)` for an artifact holding generated CPU code, and the load gate compares
the *resolved* target `(machine, vec_isa, vec_isa_width, vec_isa_macro)` against
what `pick_vec_isa()` picks on the host: the artifact's kernel source was tiled
for the capture ISA and the host recompiles it with its own. `pick_vec_isa()`
already folds the raw knobs (`cpp.simdlen` and `ATEN_CPU_CAPABILITY`; `march` never reaches it) into the
ISA it returns, so the resolved triple is the complete key; simdlen and march
stay in the recorded tuple for diagnostics but do not gate. The sample is taken
under the backend's own inductor config: `torch.compile(options={...})` builds a
`_TorchCompileInductorWrapper` that patches config such as `cpp.simdlen` only for
the duration of `backend()`, which has already returned by the time we sample, so
we re-apply that config while reading `SystemInfo.current()`; otherwise the
fingerprint would record the ambient ISA rather than the one the kernels were
tiled for. `emits_native_code(backend_name)` exempts eager-family artifacts from
the toolchain probe and the comparison.
`_graph_device_types` scans the whole graph instead of reading the first meta
value's device, which misreported a SymInt placeholder as "cpu" and let a mixed
cpu+accelerator graph skip the check.
The Triton-version and GPU-model checks now exempt off the artifact (the
receiver), not the loading host: an artifact built with Triton is rejected on a
Triton-less host, where before the host-side exemption let it load and then fail
later at kernel load.
User-visible: `AOTCompiledModel.__call__` raises `RuntimeError("No AOT compiled
graph matched ...")` listing why each input was rejected instead of running
graph 0's guards, and a result opted out via `disable_guard_check()` is
consulted only after every guarded result was rejected.
`CompilePackage.__init__`'s `requires_native_backend_compatibility` is
keyword-only.
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 the KeyError. Codegen-target
tests patch `_current_cpu_codegen_target` instead of
depending on host hardware.
Authored with an AI assistant.
FAQ
Q: Why does the gate compare only the resolved ISA (machine, vec_isa,
vec_isa_width, vec_isa_macro) and not simdlen and march too? An earlier version
compared all of them exactly.
A: Because pick_vec_isa() already folds simdlen and ATEN_CPU_CAPABILITY (march never reaches pick_vec_isa; it only changes how the same tiled source is compiled)
into the ISA it resolves -- a simdlen that caps the width picks a narrower ISA,
so the recorded width and macros already reflect it -- the resolved triple is
the complete correctness key. Comparing the raw simdlen/march knobs on top of it
is not merely redundant, it is wrong in two ways. First, it rejects an artifact
this host can reproduce: an artifact captured under cpp.simdlen=256 is loadable
on any host that resolves to the same 256-bit ISA, whether the host gets there by
default or via ATEN_CPU_CAPABILITY, yet a raw-simdlen comparison rejects the
default-knob host. Second, it makes the documented escape hatch ineffective --
setting cpp.simdlen to fix an ISA mismatch would only trade the ISA error for a
simdlen error. A related bug the exact comparison hid: the sample was read after
backend() returned, so the _TorchCompileInductorWrapper's config patch (e.g.
cpp.simdlen) had already exited and the fingerprint recorded the ambient ISA,
not the one the kernels were tiled for -- so an artifact could reject its own
build host and accept a wider one. This commit re-applies the wrapper's config
while sampling so the recorded ISA is the one the kernels were actually built
for, and gates on that resolved ISA. The gate is still fail-closed: a genuine
ISA/width/macro mismatch is refused, and the caller can fix it with
ATEN_CPU_CAPABILITY or cpp.simdlen.
Q: A wider host ISA (AVX-512 loading an AVX2 artifact) is a superset, so why
reject it instead of running the narrower kernels?
A: A wider ISA is not a superset here. The kernels were tiled for the narrower
width, so the wider host's masked loads zero-fill the lanes the narrow tiling
never wrote and its unmasked reductions then read them, changing the result.
The comparison is exact -- and it compares the recorded ISA name, its bit
width, and its build macros together -- because
VecSVE(128), VecSVE(256), and VecNEON overlap in name and/or width and only the
full fingerprint tells them apart.
Q: When the loading host has no usable CPU codegen target at all (no C++
toolchain), the check hard-refuses rather than loading best-effort. Isn't that
too aggressive?
A: Fail-closed on purpose. An artifact that recorded a CPU codegen target holds
vectorized CPU kernels that must be compiled to run, and a host with no
toolchain cannot build them, so there is nothing to run best-effort; refusing
with a clear message beats failing deep in compilation. Eager-family artifacts,
which bake no native code, are exempted up front by emits_native_code(), so this
refuses only artifacts that genuinely need a compiler.
Q: The CPU codegen fingerprint records tuple(vec_isa.build_macro()), but for
AVX-512 that macro is the constant CPU_CAPABILITY_AVX512 and does not encode the
bf16/fp16 probe. Two x86 hosts that differ only in AVX-512-BF16 / AMX-FP16
support then produce an identical fingerprint, yet build_arch_flags() appends
-mavx512bf16 / -mamx-fp16 only where supported -- so a capture host bakes bf16
intrinsics and a loading host without them recompiles wrong. Isn't that a
collision?
A: Correct, and a real gap: build_macro() captures the ISA family but not the
bf16/fp16 arch-flag suffixes, so the fingerprint is coarser than the code the
recompile actually emits. The fix is to record build_arch_flags() -- which
subsumes the macros and the -mavx512bf16 / -mamx-fp16 / SVE -msve-vector-bits
suffixes -- rather than build_macro(). That changes the recorded fingerprint
semantics and can only be validated by exercising the codegen path across ISAs,
so it is tracked as a follow-up rather than folded into this commit unverified;
until then the check is correct on ISA family and width and misses only the
same-family bf16/fp16 sub-variant. When that follow-up records build_arch_flags(), note the ordering trap: VecAVX512/VecAMX set _arch_flags as a side effect of their __bool__ probe, so the recorder must read build_arch_flags() only after bool() has run on the instance.
Q: An artifact saved under one backend and loaded under another disagrees on
whether the ISA gate applies (an inductor-saved entry loaded in an eager
session, or the reverse). How is that reconciled?
A: initialize() no longer clobbers _requires_native_backend_compatibility with
the loaded entry's value, so the constructor value -- taken from the backend the
caller is loading under -- stands. That fixes the load gate: an eager
constructor can no longer disarm the ISA check an inductor entry needs, so the
load never relaxes a host. The mirror direction is subtler: an inductor-saved
entry loaded in an eager-family (e.g. aot_eager) session and then re-saved
(literal "eager" records no bundled artifact, so only aot_eager reaches this)
would strip the fingerprint.
That is closed by the monotone OR-accumulate in #195913
(self._requires_native_backend_compatibility |= dynamo.requires...), which
neither the entry nor the constructor can relax; this commit removes only the
clobber the load gate needed.
Q: _graph_device_types walks the FX graph with its own heuristic instead of
reading V.graph.device_types, so it both over-reports (a false "cpu" for unused
placeholders arms the toolchain probe) and under-reports (string device= specs
are invisible). Why reimplement it?
A: The FX-level walk runs before inductor lowering, where V.graph.device_types
is not yet populated, so it cannot be read here; the heuristic is deliberately a
superset because arming the CPU toolchain probe for an artifact that turns out
to hold no CPU code only costs a load-time ISA check the caller can satisfy,
which is the fail-closed direction. String device= kwargs and a .to() device
argument are read, but only in those device positions -- not from any flat arg
-- because an autocast device type is a plain string positional of
_enter_autocast, and trusting every string leaf would inject a phantom "cuda"
into a CPU-only graph (unloadable on the very host that saved it) or a phantom
"cpu" from torch.utils.checkpoint's unconditional autocast("cpu") (arming the
ISA gate on an accelerator-only artifact). Device-carrying method calls beyond
.to()/.cuda()/.xpu() are still narrowing work tracked separately.
Q: A `functools.wraps` wrapper assigned to `forward` silently yields the wrong
guard scope: `get_traced_fn` never unwraps `__wrapped__` and `_get_signature`
uses `follow_wrapped=False`, so a wrapper defined in a different module resolves
guards against the decorator's module with no warning -- the very failure this PR
fixes, in a shape the fix does not cover. Why leave it?
A: The silent case is asymmetric wrapping only: `functools.wraps` copies
`__module__`/`__name__`/`__qualname__` but not `__globals__`, so when the same
wrapper is present at both save and load the scopes agree and the artifact is
correct. It breaks only if the capture and the runtime wrap `forward` in
different modules, which is not a shape any real serve path produces (the loaded
callable installs onto the recorded code object). Unwrapping `__wrapped__` and
comparing `original_code` against `traced_fn.__code__` to warn on the mismatch is
the right hardening and is tracked as follow-up; it is a detection improvement,
not a correctness fix for the paths this PR serves.
Q: Seeding `__builtins_dict___N` into the live module globals makes a later
`torch.compile` in that same module crash. `unique_id()` is a process-global monotonic
counter that a load-only process never advances, so the artifact bakes in the capture
process's `__builtins_dict___0`, deserialize writes that key into the module `__dict__`,
and the next `OutputGraph.__init__` there regenerates `__builtins_dict___0` and hits
`CleanupHook.create`, which raises because the name is already in scope. This is every
caller of the default `guard_filter_fn`, not just those who keep global guards.
A: Correct, and it was a real crash -- reproduced with the default filter. Fixed here in
`OutputGraph.install_global`: after minting a name from `unique_id`, it now skips any
name already bound in `self.global_scope` (`while name in self.global_scope: name =
unique_id(prefix)`) before installing, so a later compile that regenerates a baked-in
`__builtins_dict___N`/`__import_*` name transparently picks the next id instead of
colliding in `CleanupHook.create`. `unique_id` is monotonic, so the loop always
terminates. The seeding itself stays -- guards rooted at those names must resolve -- and
the collision it could cause on the next compile is what this fix removes.
Q: The AOT path inserts the `__import_*` aliases and the `__builtins_dict___N`
key straight into the caller's dict, without the `CleanupHook.disown` the
precompile path does first and without any `_installed_globals`/`uninstall`/
`__del__` bookkeeping -- and because the default `guard_filter_fn` drops every
`is_global` guard, the common path mutates a torch namespace for guards that were
filtered out. Isn't the missing cleanup a hazard?
A: The insertions are bounded and idempotent (`if name not in scope`), so this is
permanent-and-untracked, not unbounded growth, and it mirrors what tracing itself
already does into the same namespace at `symbolic_convert`. The precompile path
needs `disown` and `_installed_globals` because it supports `unload()`; the AOT
artifact has no uninstall surface by design (it is a load-and-run function, not an
installer), so there is nothing to take back out. Seeding a torch namespace when
the filter dropped the global guards is wasteful but harmless -- the keys are
inert if unread, and the one active hazard, a later compile colliding on a baked-in
name, is closed by `install_global` skipping already-bound names (see the collision
FAQ below). A cleanup API on `AOTCompiledFunction`/`AOTCompiledModel` and
gating the seed on whether global guards survived are both reasonable follow-ups;
neither changes a result today.
Q: `_backend_emits_native_code` classifies the same backend differently by
entrypoint and never classifies instance backends: `torch.compile(backend=eager)`
correctly yields `False` (the wrapper stamps `compiler_name`), but
`torch._dynamo.optimize(eager)` stringifies the raw callable to native, an
instance like `CompileCounter` has no `__name__`, and the aot path reads
`"unknown"` after `get_compiler_fn` erased the string. Worse, a user backend
whose function is named `eager` is silently exempted from the ISA gate. Why is
this acceptable?
A: The classifier is fail-closed by construction: an unrecognized backend is
assumed to emit native code and pays the ISA check, which only ever refuses a
load the caller can satisfy. The two "misclassified as native" cases
(`optimize(eager)`, instance backends) therefore cost a spurious toolchain probe,
never a wrong result. The one genuinely fail-open direction -- a user callable
coincidentally named `eager`/`aot_eager` tripping the name blacklist -- requires a
user to name their own inductor-lowering backend after an eager builtin, which is
not a shape that occurs in practice; a name-based blacklist is the only signal
available before `get_compiler_fn` runs, and tightening it (identity match rather
than name, and stamping `compiler_name` on `register_backend`) is tracked
separately. The `"unknown"` the aot path records is the same fail-closed default.
Q: `_NO_NATIVE_CODE_BACKENDS` omits every non-inductor backend that is not
eager-family -- `ts`/`aot_ts`, `invoke_subgraph`, `cudagraphs`, `openxla`, `tvm`,
the `*_TESTING_ONLY` gm-passthrough backends and the minifier backends -- so all
of them are now gated on host ISA even though none emit inductor CPU kernels.
Shouldn't they be exempt?
A: Same fail-closed rationale: these backends are rare enough that the exemption
list intentionally enumerates only the eager family (the common no-codegen path),
and everything else pays a host ISA check. (Correction: that check is NOT
satisfiable on every host -- ATEN_CPU_CAPABILITY / cpp.simdlen can only lower a
host's resolved ISA, never raise it, and a toolchain-less host resolves no target
at all -- so a user backend that bakes no native code now has an opt-out on the
aot_compile path too: declare `emits_native_code = False` on the backend callable
and the artifact records no codegen target and skips the gate, mirroring the
package's requires_native_backend_compatibility.)
Enumerating each additional no-native-code backend is a pure widening of the
exemption with no correctness stake and is deferred; the current list is
conservative in the safe direction.
Q: The mixed cpu+accelerator device change is a load-time behavior change on
existing artifacts that neither the description nor the FAQ mentions: pre-PR a
mixed graph whose first meta value was a CPU tensor recorded `device_type="cpu"`
and skipped the GPU check, so it loaded on a host lacking the accelerator;
post-PR the device set is unioned and every device is checked, so it now
hard-fails there. Isn't that a BC break?
A: It is an intentional correctness fix, and the new answer is the right one: an
artifact that genuinely uses an accelerator must not load on a host without it,
and the pre-PR behavior (silently skipping the GPU check because a CPU tensor
happened to be first) was the bug. The only wrinkle is message ordering -- when
both the accelerator is absent and the ISA differs, the user sees the ISA message
first because `sorted({"cpu","cuda"})` puts codegen first -- and that is
deliberate (ISA skew is fixable via `ATEN_CPU_CAPABILITY`/`cpp.simdlen`, device
absence is not, so leading with the fixable one is the better default). The
behavior change is called out here for the record.
Q: `check_codegen=False` returns early inside the GPU block, so for an
eager-family artifact carrying a cuda device the `toolkit_version`,
`triton_version` and `gpu_name` checks are all skipped -- and `gpu_name` is not a
"describes generated code" check the way the gate's comment justifies. Isn't
skipping `gpu_name` for an eager artifact wrong?
A: Intentional. An eager-family artifact bakes no device-specific code -- no
Triton kernels, no toolkit-versioned cubins, nothing pinned to a particular GPU
model -- so it is portable across accelerators of the same family, and all three
GPU checks exist to protect generated code that an eager artifact does not carry.
Gating them together under `check_codegen` is therefore correct for what the
artifact actually contains; `gpu_name` guarding an eager artifact would refuse a
load that is in fact safe. The comment's "describes generated code" framing is
about why the gate exists, not a per-check taxonomy.
Q: When the loading host reports no CPU codegen target at all,
`_cpu_codegen_target_problem` returns a message that does not name the machine
the artifact was built for. Shouldn't the message name it?
A: The enclosing `RuntimeError` already prints the full cached tuple
(`cached={self.cpu_codegen_target}`, machine included) next to `current=...`, so
the machine is named at the call site. The per-branch string only supplies the
component-level reason for the mismatch, and a `None` host has no component to
compare against -- duplicating the machine there would be redundant.
Q: pick_vec_isa() at save is expensive (seen around 18s cold). Why pay it there?
A: It is gated on needs_cpu_codegen, so only artifacts that will emit native
CPU code reach it, and pick_vec_isa() caches its result -- the probe runs once
per process, not once per save. Recording the resolved ISA at save is what lets
load fail closed against a host that would pick a different ISA; deferring the
probe to load would move the cost, not remove it.
Q: An artifact captured under options={'cpp.simdlen': N} loads only on a host
that resolves to N. Doesn't passing the same options={'cpp.simdlen': N} on the
loading side fix it?
A: No, and this is worth stating explicitly -- including the sharp corner that it
fails even on the very machine that built it, in the same process. On load there is
no backend wrapper, so check_compatibility() samples SystemInfo.current() ambiently
-- outside any torch.compile(options=...) patch, which only takes effect once
tracing begins. simdlen lived only in the per-compile options, never in the global
config, so nothing re-applies it at load and the build host re-resolves to its
native (wider) ISA and rejects its own artifact. The documented escape hatch on the
loading host is therefore the *global* torch._inductor.config.cpp.simdlen (or the
ATEN_CPU_CAPABILITY env var), set before the load, not the options= form. The
capture-time half is fixed here by widening the config.patch context to cover
CompileArtifacts / AOTCompiledFunction construction, so __post_init__'s self-check
samples under the same ISA the fingerprint recorded. Auto-re-applying the recorded
simdlen at load (so the round-trip needs no env/config) is a real improvement, but it
belongs with the load-side recompile-config plumbing that lands with the store-reload
work in #195913, not this commit's gate; the AOT load path deserializes bundled
kernels rather than recompiling from source, so the gate is a run-safety check and the
escape hatch is the supported reload path until then.
Q: The codegen fingerprint is armed from the backend and device
(emits_native_code(backend_name) and "cpu" in device_types), not from whether
inductor actually emitted a cpp kernel. An artifact whose CPU output is all
extern calls (torch.mm lowering to BLAS) still records a target, so the
load-time gate pays the full pick_vec_isa() dry-compile (~19s measured) for
nothing. Arm it from whether a cpp kernel was emitted.
A: The over-arming is deliberate and errs toward correctness. The gate rejects a
host whose resolved ISA differs from the one the kernels were tiled for; if we
under-arm -- record no target when a cpp kernel WAS emitted -- the gate accepts
an ISA-incompatible host and runs a mistiled kernel, a silent-wrong-result/crash
hazard that is strictly worse than a slow load. Arming on "the backend can emit
native CPU code" is the conservative superset that never under-arms. Precisely
detecting "inductor emitted zero cpp kernels for this graph" means introspecting
the compiled artifact's kernel sources, which is not reliably available at this
call site and, per the measurement's own method, needs a built inductor to
validate that the narrower signal never drops a real target; narrowing the arming
to it (and skipping the dry-compile when no cpp kernel exists) is the right
optimization but is tracked as follow-up rather than attempted without a build.
The one-time load cost is also amortized by TORCHINDUCTOR_CACHE_DIR.
Q: The remedy sentence points the user at ATEN_CPU_CAPABILITY /
torch._inductor.config.cpp.simdlen, but on fbcode/x86 pick_vec_isa()
short-circuits to VecAVX2() before reading either knob, so neither can move the
resolved ISA and _current_cpu_codegen_target() can never return None there. The
hint is inert in fbcode.
A: Correct that on fbcode/x86 pick_vec_isa() returns VecAVX2() unconditionally,
so the two knobs the hint names cannot change the resolved ISA and the escape
hatch is a no-op there. The hint is advisory and accurate off fbcode (OSS x86,
where valid_vec_isa_list()/cpp.simdlen/ATEN_CPU_CAPABILITY do resolve the ISA),
which is where an ISA-mismatch rejection is actually reachable; on fbcode the
fixed AVX2 target means two builds on the same machine class agree and the gate
does not fire in the first place. Conditioning the message on config.is_fbcode()
to drop the inert knob suggestion is a reasonable message-only refinement that
changes no gate behavior, deferred with the other fbcode-specific paths that
cannot be validated in this environment.
Q: The two store reload APIs -- DynamoStore.load_package and
DynamoCache.load_and_install_package -- construct CompilePackage(fn,
entry.dynamo) with the constructor default requires_native_backend_compatibility=True
and no backend to derive it from, and initialize() restores _device_types but
not the flag. So an eager package round-tripped through a store upgrades to
native on re-save: cache_entry() pays the pick_vec_isa() probe and stamps a
cpu_codegen_target onto an artifact that bakes no native code, which then
hard-refuses on an ISA-different host. Restore the flag from the entry here (it
records the value), or thread the kwarg through the store APIs.
A: Correct that at this commit the harm is real: the two store paths pass the
bare default True (the eval_frame path is the only one that derives the
constructor value from the backend, so the existing "the constructor value,
taken from the backend, stands" FAQ does not cover the store paths), and this
commit's cache_entry() probes eagerly, so a store round-trip of an eager package
re-saves as native. But the suggested entry-authoritative fix is the wrong
resolution, because at this commit the flag has no compile-path accumulation: it
is written once at construction and never OR'd by a later native compile. Making
the reloaded entry authoritative would fail OPEN in the mirror direction -- a
native session that reloads an eager entry (flag False) would then run native
compiles with the ISA gate disarmed and load a kernel built for another target
on an incompatible host, a silent-wrong-result hazard strictly worse than the
wasteful-but-safe over-arm this comment describes. The correct resolution lands
higher in this same stack (#195913): the flag is made monotone
(self._requires_native_backend_compatibility = self._requires_native_backend_compatibility
or dynamo.requires_native_backend_compatibility, which neither a reload nor a new
compile can relax), and the pick_vec_isa() probe is deferred out of cache_entry
-- the reload path stamps _system_info via SystemInfo.current(cpu_codegen=False)
carrying the entry's recorded target (None for an eager artifact) straight
through re-save, and the probe fires only in update_device_type during an actual
cpu-bearing compile. At the stack tip the store-reloaded eager package therefore
pays no probe and stamps no target on re-save -- exactly the harm this comment
asks for -- while a genuinely native new compile still arms the gate fail-closed.
The eager over-arm visible here is an intermediate-state artifact removed by that
deferred-probe change above it, not a shape the stack ships; adopting a local
entry-authoritative fix here would have to be reverted to reach the safe design.
Q: The CPU-codegen half of this commit -- SystemInfo, emits_native_code, the
check_compatibility rework, the fingerprint gate and roughly half the new tests
-- is an independent feature from the AOTCompiledModel.deserialize guard-scope
fix in the title, and it is the part that can newly hard-refuse a load. Split it
into (1) the guard-scope fix, (2) the _graph_device_types rewrite, and (3) the
CPU codegen fingerprint and gate so each lands on its own evidence.
A: Agreed on the logical separation, and in a fresh stack these would be three
commits. This commit sits deep in a 24-PR ghstack whose upper commits (the
capture session, save() entry point, and the monotone OR-accumulate /
deferred-probe changes that this very FAQ leans on) already depend on the
SystemInfo and emits_native_code surface introduced here; splitting it now
reindexes every PR above it and restarts their in-flight CI, which is a real cost
the reviewer explicitly flagged as "your call". The three parts are individually
reviewable in place: the guard-scope fix is the first three paragraphs and its
KeyError-reproducing tests, _graph_device_types is self-contained, and the
codegen gate is the part the FAQ scrutinizes. Keeping them together is the
smaller net change given the stack's current depth; the split is noted as the
right shape for any future reland.
Q: install_global's collision retry (the `while name in self.global_scope` loop)
lives only in install_global, not install_global_unsafe, which
install_resume_function_global calls directly. Doesn't the resume-name collision
class the retry closes survive for resume functions?
A: The durable separator lands higher in this stack, in #195911, not at this
commit -- `_resume_global_renames`, `package_token` and the per-package uuid are
all absent from package.py at this revision, so this answer describes where the
collision is closed, not code present here. #195911 renames a loaded package's
resume globals to `{name}_{package_token}` (uuid minted once in __init__) while a
fresh compile installs the bare `__resume_at_<offset>_<n>`, so the two can never
collide and install_global_unsafe's assert-only behavior is correct on the resume
path. `__builtins_dict___N` carries no such distinguisher, which is why the retry
loop was added to install_global for it here and now. Until #195911 the resume-name
collision class is pre-existing and open; ghstack lands each PR individually, so
main can carry this commit without #195911's separator for a window; the
resume-name collision in that window is pre-existing, not introduced here. (#195911 also makes an
intra-package duplicate resume name raise loudly, closing the last silent route.)
Q: load_compiled_function passes guard_globals=f_globals, conflating the globals
the function runs in with the globals guards evaluate against, despite the
docstring distinguishing them. Shouldn't they be separate?
A: They are intentionally the same here. A compiled function's guards check the
very globals that function will read at runtime -- that is the point of a global
guard -- so evaluating them against a different dict would guard state the
function never sees. deserialize() keeps guard_globals as a distinct parameter for
callers that genuinely have two dicts (a guard tree rooted in one module served
into another), but load_compiled_function is the common single-module entry point
and binds both to f_globals deliberately. Exposing a second kwarg on it would add
API surface for a split that this entry point, by construction, does not have. The
docstring describes the general deserialize() contract; the narrowing to one dict
at this call site is intended, not an oversight.
Q: The module path auto-resolves its guard scope, but
torch.compiler.load_compiled_function(f) with no f_globals still lands on the
function path and fails any surviving global guard with a bare KeyError on
G['...']. Why not record fn.__module__ at capture and resolve sys.modules[...] the
way AOTCompiledModel does?
A: This commit takes the cheaper of the two remedies the finding offers. When
_guard_globals is None and the guard fails on a KeyError on G[...],
AOTCompiledFunction.__call__ now appends a pointer telling the user to pass
f_globals to load_compiled_function, so the degraded mode names its own fix
instead of surfacing a bare KeyError; AOTCompiledModel's no-match footer gets the
same missing-global branch. Recording the defining module at capture and
resolving sys.modules[...] is the durable version and a reasonable follow-up, but
it is a capture-time schema change, whereas the pointer hint closes the
diagnosability gap without one. The condition is pre-existing, not a regression
introduced here.
Q: SystemInfo.current defaults cpu_codegen to True, which runs the expensive
pick_vec_isa() probe, yet every call site passes cpu_codegen=False explicitly.
Shouldn't the default be False so the probe is opt-in?
A: The default is deliberately the complete value, not the cheap one.
check_compatibility only compares cpu_codegen_target when it is not None, so a
SystemInfo built without the probe silently carries no codegen fingerprint and a
later load on a mismatched ISA is not caught -- a correctness hole. Building one
with the probe is merely slower. Every current call site already passes the flag
explicitly, so the default governs only a future caller that omits it;
defaulting to True means such a caller gets a correct-but-slower artifact rather
than a fast-but-silently-incompatible one. The False overrides sit exactly where
codegen is known to be irrelevant -- the field factory's placeholder and the no-
graph-captured case -- so the expensive probe is opt-OUT there, not opt-in
everywhere.
Q: AOTCompiledModel._no_match_message picks one footer via an exclusive
`if missing_global / else`, so when two results fail and only one lacks a global
the ModelInput hint on the other is dropped; and the two branches test "is a global
missing" with different predicates (`"G['"` over-matches, `"KeyError on G["`
under-matches). Shouldn't the hint be per-result and the predicate shared?
A: Both are real refinements and neither changes a report a user sees today. The
per-result `[i]` lines already print every failure with its own reason; only the
trailing hint is a single footer, so the mixed-cause pair loses advice, not
diagnosis -- and attaching the hint to the `[i]` line that triggered it is the
right shape (it also keeps the len(splitlines)==4 assertions intact), but that is
a message-layout change, not a correctness one. The predicate divergence is a
wording inconsistency: both predicates only gate whether the "pass f_globals / add
a ModelInput" hint is appended, so an over-match appends it spuriously and an
under-match omits it -- in both cases the load still fails with the same error and
the same per-result reasons. The two branches now use predicates fitted to their
inputs: the raising branch tests `kind == "KeyError" and "G['" in detail` (a raised
KeyError stringifies to the bare `"G['NAME']"`, so the verbose-report text
`"KeyError on G["` can never appear there) and the non-raising branch keeps
`"KeyError on G["` over the verbose parts. They are intentionally different, not
drift.
Q: AOTCompiledFunction.__call__ appends a hint saying the guard scope "was
reconstructed from the serialized bytecode ... pass f_globals to
load_compiled_function", gated on `self._guard_globals is None` -- but that is also
true of every in-process capture that never serialized (the capture path passes
only _extra_globals), so a user who never saved can be told to pass f_globals.
Shouldn't it gate on an explicit "was deserialized" flag?
A: The hint is appended only when a guard actually FAILS on an absent global (a
KeyError reaching G['NAME']), not on every in-process run. A never-serialized
capture reaches it only if its live guards genuinely reference a global that was
deleted after capture -- in which case supplying the missing global (via f_globals
on a reload, or simply keeping it defined) is the correct remedy, so the advice is
directionally right even when the exact API name does not apply to an in-process
object. The predicate is broader than "was deserialized", and gating on an explicit
flag (or reusing _no_match_message's always-true phrasing) is a fair follow-up, but
the message only ever fires on a real missing-global failure, so it does not
misdirect a healthy in-process capture.
Q: `AOTCompiledModel.__call__`'s dispatch loop lets a raising `guard_check`
propagate, while `_no_match_message` tolerates a raising guard. Shouldn't the two
agree?
A: Fixed: the scan now treats a raising guard TREE as "did not match" and moves
on, and the report names the raiser as before. Binding errors are not tolerated:
`prepare_f_locals` runs outside the guarded region, so a call the signature
cannot accept still raises `bind_locals`' TypeError as the plain module would
(pinned by `test_aot_compile_module_wrong_arity_raises_type_error`) instead of a
no-match report telling the user to add a ModelInput. (Correction to an earlier
wording: the C++ guard tree does not swallow everything. A Python-level failure
inside a guard is cleared by `check_nopybind` and reported as no-match -- the
verbose variant renders it as `KeyError on G['...']` -- but a `TORCH_CHECK` or
`py::cast` failure unwinds through `RootGuardManager::check` and reaches Python
as a RuntimeError, which the scan now treats as "this entry did not match" and
reports by name rather than failing the whole call. `RootGuardManager::check`
restoring `PythonTorchFunctionTLS` by hand on that unwinding path is a
pre-existing guards.cpp issue this commit does not change. The Python-side
raisers, `prepare_f_locals` / `bind_locals`, would fail the call for the same
input anyway; the fix is about the two paths agreeing.) `RaisingGuardManager.check` in
the existing test now raises too, so the scan loop is covered.
Q: `cache_entry()` samples `SystemInfo.current()` ambiently, so a package
compiled under `torch.compile(options={"cpp.simdlen": 256})` on an AVX-512 host
records the 512-bit ISA its kernels were not tiled for -- the bug the AOT half
fixes here. Which commit closes this?
A: Correct at this revision: `cache_entry()` runs from record_package/save_package
after the `_TorchCompileInductorWrapper`'s config_patches scope has exited, and
nothing on the package carries that config here. #195913 closes it directly: it
moves the probe out of `cache_entry` into `update_device_type(graph,
codegen_config=...)`, and convert_frame recovers the wrapper's config from the
compiler_fn chain (`_inductor_codegen_config`) and re-applies it with
`torch._inductor.config.patch` around the sample -- the same re-application
`aot_compile_fullgraph` does here. A local fix would have to stash the config on
the package and re-apply it in `cache_entry`, code #195913 deletes when it
relocates the probe, so the fix lands with the commit that owns the probe's new
home. The load side is unchanged (ambient, with the global cpp.simdlen /
ATEN_CPU_CAPABILITY escape hatch).
Q: The `test_save_guidance_when_a_locals_class_default_cannot_pickle` comment says
the shared "local object" substring covers the pure-Python pickler too, but that
pickler's message ("Can't pickle <class ...>: it's not found as ...") has no such
substring.
A: Right on the parenthetical (the headline -- that AttributeError never escapes --
is wrong: the C pickler `AOTCompilePickler` subclasses raises it unwrapped through
3.13, and 3.14 raises PicklingError "Can't pickle local object"). The pure-Python
pickler is unreachable from `AOTCompilePickler(pickle.Pickler)`, so the comment now
names the two versions' wordings and drops the pure-Python clause. The test moved
to #196454 with the code it pins, so the reword lives there.
Q: `test_eager_backend_entry_is_exempt_from_the_codegen_target`'s native half only
asserts `requires_native_backend_compatibility`; the target the probe recorded is
never checked, and asserting it directly would need a host toolchain.
A: Fixed: the native half patches `_current_cpu_codegen_target` to a sentinel
target and asserts the entry recorded exactly that, so it needs no toolchain.
Q: No test drives the `options=`-patched capture path in `aot_compile_fullgraph`;
the footer branch selection in `_no_match_message` is unpinned; the `__call__`
missing-global hint is unasserted; the ISA table is a hand-rolled loop rather than
`@parametrize`; `check_codegen=False` on cuda is untested.
A: Added: `test_aot_compile_samples_the_codegen_target_under_the_wrappers_config`
(the recorded simdlen is the wrapper's, the ambient config is untouched after),
`assertIn` on each footer in the two no-match tests,
`test_aot_compile_fn_missing_global_hint_names_f_globals`, the ISA table as named
`@parametrize` subtests, and a `check_codegen=False` GPU case in the Triton/GPU
exemption test.
Q: `(line,) = logs.output` plus a `functools.partial(` substring in the
partial-forward fallback test is brittle; the seeds test "sanitizes rather than
cleans up" by filtering `__import_*` names; the mixed-device test depends on
`check_versions` ordering.
A: The single-record unpacking is deliberate -- any extra deserialize warning
should fail the test, that is the contract -- and `functools.partial(` is the repr
Python has emitted for decades. The `__import_*` filter isolates from earlier
tests: any compile writes those aliases into the tracing module's globals
(symbolic_convert's `install_global`) and `CleanupHook` removes them on reset, so
the filter is scoping, not a cleanup leak. The ordering dependence is documented
at `check_versions` ("cpu first ..."); left as is.
Q: The `except (RuntimeError, AttributeError)` arm around `get_traced_fn` in
`aot_compile_module` has no test.
A: Reachable (`mod.forward = torch.add` has `__self__` but no `__func__`) but low
value: it only selects the warning text for an unresolvable guard scope, which the
existing scope tests already exercise on the resolvable side. Left to follow-up
rather than pinned here.
Q: pr-sanity-checks is red -- this commit grew to 2058 lines.
A: The AOT-pickler tests (five `TestAOTCompile` cases plus the whole
`TestAOTCompilePickler` class) exercise code that #196454 introduces, so they
moved down to that commit; this commit is now ~1700 lines and the combined tree is
unchanged.
Q: The AOT-compile page documents the new `f_globals` contract but not the other
new user-visible load failure: an inductor artifact recorded a CPU codegen target
and is refused on a host that resolves a different one, with `ATEN_CPU_CAPABILITY`
/ the global `cpp.simdlen` as the escape hatch.
A: Added to "Choosing a backend" (the section that already contrasts inductor and
eager): what is recorded, the exact error, why a wider ISA is not a superset, how
to make the host resolve the recorded ISA before loading, that `options=` does
not apply at load time, and that eager/aot_eager artifacts are exempt; plus a
cross-reference from `load_compiled_function`'s Returns.
Q: `optimize_assert`'s copy of the `native_backend` threading is untested; the
eager-exemption test only takes the `_optimize` branch, so the two call sites can
drift.
A: The test is now parametrized over `fullgraph` (False -> `_optimize`, True ->
`optimize_assert`) so both paths are pinned.
Q: `initialize()` restores `_device_types` from the cache entry but not
`requires_native_backend_compatibility`, and neither store load path passes the
kwarg, so a loaded eager package loses its exemption and re-saves with a baked
codegen target.
A: Correct at this revision; #195913 closes it in both ways the review lists:
`initialize()` ORs the entry's flag into the package's (monotone, with the probe
deferred), AND `DynamoStore.load_package` / `load_and_install_package` pass
`requires_native_backend_compatibility=entry.dynamo.requires_native_backend_compatibility`
so a False survives the constructor default. The eval_frame path (a native
session reloading an eager entry) is why the entry is not made authoritative on
its own: that would fail open. The manual kwarg in
`test_loaded_eager_package_stays_exempt_on_resave` models that eval_frame path.
Q: The blacklist rationale ("a false rejection at load is recoverable") does not
hold on the `aot_compile` path: `CompileArtifacts` derives the gate solely from the
backend name, so a user backend that emits no native code is fingerprinted with the
capture ISA and cannot be loaded on a narrower or toolchain-less host.
A: Fixed: `CompileArtifacts.requires_native_backend_compatibility` (default True
so artifacts saved before the field keep loading) is set at capture from the
backend -- the eager family by name, or any callable declaring
`emits_native_code = False` (honoured by `_backend_emits_native_code` for the
package path too) -- and `check_compatibility` skips the ISA gate when it is
False. Pinned by `test_aot_compile_backend_declaring_no_native_code_skips_the_isa_gate`
(no target recorded; loads with a host that resolves no target). The docs now
state the true scope: every backend outside the eager family is gated unless it
declares otherwise.
Q: The install-collision retry lands on `install_global` only, but
`install_global_by_id` and the resume-function install also reach `CleanupHook.create`,
which raises on a name that already exists.
A: The resume half is closed by #195911's per-package token rename (the FAQ above
says where). `install_global_by_id` names (`___module_<name>_<id>_c<compile_id>`)
are never seeded by any load path -- `install()` seeds only `import_sources` and
`function_names`, and the AOT loader seeds import aliases and the builtins-dict
key -- so there is no baked-in name for a later compile to collide with (probe:
capture, reset, load, recompile in the same module: OK). Only `__builtins_dict___N`
carries no distinguisher, which is why the retry is scoped to it.
Q: `linux-docs` is red from this PR up.
A: The cross-reference added last round used a `#heading` anchor, which this
docs build (no `myst_heading_anchors`) does not resolve; it now uses the file's
explicit `(choosing-a-backend)=` label and a `{ref}` role.
Q: `test_check_compatibility_compares_artifact_against_current_machine` is red
from this PR up.
A: My round-38 change made the ISA gate a conjunction of the backend name and the
new capture-time flag `requires_native_backend_compatibility`; the test flipped
only the name, so the gate stayed disarmed and `assertRaises` failed. The eager
arm now asserts the flag is False for an eager capture and then arms it, so the
name exemption and the receiver-order checks are each pinned on their own.
Q: The opt-out `emits_native_code = False` is a fail-open escape hatch documented
with no warning about what declaring it wrongly costs, and nothing says where it
must live for a wrapped backend.
A: The user guide now says both: the attribute is read off the object passed as
`backend=` to `torch.compile` (a registered name resolves to its function first),
so for `aot_autograd(fw_compiler=...)` it goes on the returned `AotAutograd`
object and not on `fw_compiler`; only the literal False counts; and
declaring it on a backend that does emit native code disables the only check
between a mis-targeted artifact and a first-call crash. The docs also name the
`_NO_NATIVE_CODE_BACKENDS` family rather than listing two of its members.
Q: The attribute is de facto public API with no home in the `SerializableCallable`
protocol; `register_backend` should accept and stamp it so the classifier can
match by identity instead of by name.
A: Not in this commit. A protocol attribute would make it a property of every
serializable backend, but the flag describes the backend's codegen, not its
serializability, and most backends never set it. Stamping via `register_backend`
only covers registered backends; the user callable handed straight to
`torch.compile` is the case the opt-out exists for. Matching the in-tree eager
family by identity rather than name is a reasonable follow-up once the registry
grows that surface; the `__name__ == "eager"` collision it would close is already
FAQ'd above as accepted.
Q: `getattr(..., "emits_native_code", True) is not False` treats a method or a
truthy non-bool as native.
A: Deliberate: the gate fails closed. Anything but the literal False -- a method
(`is not False` on a bound method), a string, a missing attribute -- keeps the
artifact fingerprinted. The docs now say "the plain attribute
`emits_native_code = False`; any other value counts as native".
Q: The raising-guard branch of `_no_match_message` tests `"KeyError on G[" in
detail`, but a raising guard's `str(e)` is the bare KeyError text, so the
predicate is dead.
A: Fixed: the branch now tests `kind == "KeyError" and "G['" in detail`, and
`test_no_match_message_survives_a_raising_guard` asserts the missing-global footer
is present.
Q: `AOTCompiledFunction.__call__`'s missing-global hint says the scope "was
reconstructed from the serialized bytecode" and points at `load_compiled_function`,
but `_guard_globals` defaults to None on an in-process capture that was never
serialized.
A: Fixed: the hint reuses `_no_match_message`'s neutral phrasing (a guarded
global is missing from this process; define it or load with an `f_globals`
carrying it). `AOTCompiledModel` never reaches that branch: its `__call__` has
its own no-match report.
Q: `_simdlen`/`_march` are unpacked and never read in `_cpu_codegen_target_problem`.
A: `cached[:4]` now.
Q: The no-native-code test never round-trips the artifact through save/load, and
nothing pins that the same backend WITHOUT the declaration is fingerprinted.
A: Both added to `test_aot_compile_backend_declaring_no_native_code_skips_the_isa_gate`:
the artifact is saved and reloaded on a host that resolves no codegen target and
still serves, and an undeclared twin of the backend records
`requires_native_backend_compatibility=True` with the capture target.
Q: A subgraph tiled under a nested compile region's own `cpp.simdlen`
(`_patch_nested_region_inductor_config`) is fingerprinted with the ambient ISA.
A: Known and out of scope for the gate: the fingerprint is per artifact, and an
artifact whose regions were tiled for different widths cannot be described by
one target. Nested regions with their own simdlen are an inductor feature the AOT
path does not compose with today; when it does, the fingerprint should become the
set of targets the regions resolved, which is a follow-up to that composition, not
to this gate.
Q: No test where an opted-out result's guard evaluation raises.
A: The raising-guard scan is backend-agnostic (it runs before any backend
attribute is consulted), and `test_no_match_message_survives_a_raising_guard`
covers it; repeating it under the opt-out would exercise the same lines.
Q: `VecNEON` is never instantiated in either test file, so NEON-vs-SVE128 is
covered only by literal tuples.
A: `VecNEON` cannot be instantiated on the x86 hosts CI runs these files on
(`pick_vec_isa` never returns it there, and constructing it by hand exercises no
x86 codepath), so the literal target tuples are the honest cross-architecture
coverage available; the arm64 CI job runs the same comparison end to end through
the real `pick_vec_isa`.
Q: The docs say the attribute is read "off that callable's compiler_fn when it
is a wrapper", but `aot_autograd()` returns an `AotAutograd` whose `__name__` is
"compiler_fn" and which has no `compiler_fn` attribute. Which wrapper is meant?
A: Only torch.compile's own `_TorchCompileWrapper`, which stores the user's
backend as `.compiler_fn`; the one-hop getattr exists to see through it.
`AotAutograd` is never unwrapped (it IS the wrapper's compiler_fn), so the docs
now state the rule without naming an internal: set it on the object passed as
`backend=`. One limit for the record: `torch._dynamo.optimize("name")` with a
registered NAME string never resolves the name before classifying, so a
declaration on the registered function is honoured only through
`torch.compile`; the string path falls back to the name blacklist (fail-closed,
native).
Q: The mismatch RuntimeError prints the full six-tuple, so a 256-vs-None
simdlen/march tail can read as the cause while the remedy names cpp.simdlen.
A: The tail is diagnostic on purpose (`_cpu_codegen_target_problem`'s docstring:
simdlen and march stay in the recorded tuple for diagnostics but do not gate),
and the `problem` sentence appended to the same error names the exact gating
component (machine, or ISA/width/macros) with both values, so the cause is
stated next to the tuple. Labelling the two trailing fields is a wording
refinement left for follow-up.
Q: Neither shipped store reload path is exercised for the package flag.
A: The kwarg threading through `DynamoStore.load_package` /
`load_and_install_package` lands in #195913, which owns that seam; the test
belongs there (noted for that PR's next round), not in this commit whose reload
sites are unchanged.
ghstack-source-id: bdfdf3539edd4d29fcd1a3b27d39bde4cc837bad
Pull-Request: https://github.com/pytorch/pytorch/pull/195354
|
@claude please re-review: round-40 fixes are in (every finding from the last review is fixed or answered in the description's FAQ). |
|
Claude finished @bobrenjc93's task in 6m 8s —— View job Re-reviewing PR #195354 (round 26)
Round 26: the delta is a single docs paragraph and it is exactly the round-25 fix — the reworded placement rule is now correct for Full review of #195354PR Review: #195354SummaryFixes global guards on reloaded Delta since round 25. I diffed the PR-owned three-dot diff at the round-25 head ( -the callable handed to `torch.compile`, or off that callable's `compiler_fn`
-when it is a wrapper, so for `aot_autograd(fw_compiler=...)` set it on the
-object `aot_autograd` returns. Declaring it on a backend that does emit
+the object handed to `torch.compile` as `backend` (for a registered backend
+name, off the function that name resolves to), never off anything that object
+wraps: for `aot_autograd(fw_compiler=...)` set it on the object `aot_autograd`
+returns, not on `fw_compiler`. Declaring it on a backend that does emitNo production code changed, no tests changed. Everything else in the Verification of the reword: correct, and it fixes the exact confusionMy round-25 objection was that the old wording described the mechanism as "off that callable's The new wording states the rule in user-visible terms and adds the explicit negative. Checked against the code:
Scoping it to One thing worth a sentence for completeness, not a defect: Standing items, all re-verified at this headNothing regressed, and nothing new. Line numbers refreshed: Fail-open direction in the name classifier.
Both store reload sites take the constructor default The resume-name collision class is open at this commit. The dispatch loop's The footer is exclusive ( The The guard-scope seeding runs regardless of whether any global guard survived filtering (
A Nested-compile-region config patches are outside the in-scope sample ( Mixed cpu+accelerator BC change and TestingNo test changes this round. Remaining gaps, unchanged and all previously discussed:
RecommendationApprove The one-paragraph reword is exactly the round-25 fix and it is correct. The rule is now stated in terms of the object the user passes rather than an internal attribute, the registered-name case is called out, and the explicit "not on Nothing blocking, and no new findings. Carrying forward as follow-ups, none of which need to hold this up: a test through |
…t of snapshots, guard the 3.14 annotation read (#196767) Follow-up to the reviews of #196476, #196478 and #196479. `_keep_container_verbatim` decided a plain tuple in two steps: is it in `guard_tree_values`, and is it in `value_guarded_containers`. The second alone is the rule; the first held because `EQUALS_MATCH` registers the value it reads, a separate invariant whose failure would be the silent forever-miss the rule exists to prevent. The tuple case now reads the recording alone: ```python if type(container) is tuple: return id(container) in self.value_guarded_containers if type(container) is dict: return False return self._keep(container) ``` That is a behaviour change for the case the two invariants disagree on: a recorded tuple with no tree entry was pruned per value and is now carried whole. A test builds exactly that state, and it fails on the previous commit. A globals snapshot kept `__builtins__` "as read" when some guard had registered it and replaced it with the `builtins` module only when pruned. For an imported module `f_globals["__builtins__"]` IS `builtins.__dict__`, and a traced module's own dict binds that same object a second time under the `__builtins_dict___N` Dynamo installs; that dict is the one a saved BUILTIN_MATCH guard registers, so wherever one is saved the kept branch was taken and the snapshot carried all of builtins (about 6 KB) next to the filtered copy `G` already holds. The live builtins dict is now exempt from the keep contract by value rather than by name, so every slot holding it -- the alias included -- travels as a reference resolved in the loading process rather than as a copy, one shared `_LiveBuiltins` standing for it so a second slot in the same scope is a pickle memo reference rather than a second reduce. On a scope carrying both keys that takes the dump from 6781 bytes to 729; a cross-module snapshot, which has only `__builtins__`, goes from 6758 to 706. The slot stays a dict, since a guard may have walked through it and rebakes against whatever it holds at load. A dict without the key stays without one, since `FunctionType` falls back to the loading frame's builtins and a guard on the dict's shape must see the same keys; `FunctionType` accepts either value. The key set is the module dict's at save time, names Dynamo installed into it included, so such a guard is only as portable as those names. The snapshot loop iterated the live module dict. A `CleanupHook` pops the name it owns, and it fires from a weakref callback (`CleanupManager` holds a `weakref.ref` per traced code object, whose callback runs the hooks attached to it), so a code object collected during the dump pops a `__compiled_fn_N` or `__builtins_dict___N` key mid-loop and the next iteration raises `RuntimeError: dictionary changed size during iteration`. The loop now walks a copy, `dict(f_globals)`, which also makes the sentence above literally true: the key set is the one the loop entered with, not whatever survived to its end. The rarity is not the loop's own doing -- measured with `gc.callbacks`, snapshotting a scope of 80 `nn.Linear`s runs 82 iterations and takes zero automatic collections at the default gen-0 threshold (zero at 300, one at 10), since it allocates almost nothing GC-tracked. What decides whether a callback lands inside the loop is where the process-wide gen-0 counter already stood when the dump began. Scanning that offset with default thresholds and no forced collection, 1 of 200 positions raises against the live dict, and 0 of 200 once the loop walks a copy; being a flake rather than a reproducible failure is why the test forces the hook to fire from the loop's first `_prune` call instead of waiting for a collection. The copy is `dict(f_globals)` rather than `list(f_globals.items())`: at a gen-0 threshold of 1, where a callback popping a key raises out of a live `for k, v in d.items()` loop in all 50 trials, neither spelling raises once, and the dict copy is shorter and materializes no N-entry list of 2-tuples. The 6 KB is a snapshot's cost, and `_reduce_function_by_value` builds a snapshot only for a function whose own `__globals__` is registered too. A plain `CompilePackage` compile (`torch._dynamo.optimize("eager", package=CompilePackage(fn))`) applies no guard filter and keeps that BUILTIN_MATCH, so building its manager registers the dict the guard reads through -- but the traced function's module dict is not registered there, so no snapshot is built at all. Reading a global through a function's `__globals__` does register that dict, and it also guards the function itself with a CLOSURE_MATCH, which `serialize_guards` refuses outright, so with no filter at all an artifact built that way bypasses rather than saving. The 6 KB is paid where a caller-supplied `guard_filter_fn` drops that function guard and keeps the BUILTIN_MATCH: there the parent embedded the whole dict and the exemption hands back a reference instead. Both high-level entry points filter the BUILTIN_MATCH away instead -- `aot_compile`'s default `guard_filter_fn` drops every `is_global` entry and the alias's BUILTIN_MATCH is one, and `caching_precompile=True` drops it as ID_MATCH-derived -- so under them nothing registers `builtins.__dict__` and the parent embedded no copy of it: it pruned the alias slot to a sentinel and replaced `__builtins__` with the builtins module. There the exemption instead hands those slots back the live dict, 772 bytes to 729 on the same scope, which the same rebake argument covers. On 3.14 the guard pickler read FORWARDREF annotations unguarded, so whatever that read raised failed the dump. FORWARDREF reruns the annotate function, but only NAME lookups are proxied -- the rest of the expression runs for real, so whatever that real work raises comes out: ```python def f(x: f"{Missing}"): # TypeError: the proxy refuses __format__ def f(x: ()[0]): # IndexError: no proxy is involved at all def f(x: "%s" % Missing): # reads fine -- it is the operation, not the name ``` That would fail the dump for a slot the prune exists to make optional, so `_reduce_function_by_value` drops the whole set instead, with a debug log naming the code object by `co_qualname` where the runtime has one and by `co_name` on 3.10. That log line repeats the AOT pickler's `_pickleable_annotations` one rather than sharing it: the two handlers differ in policy (that one swallows a RecursionError too, and afterwards drops unpicklable values key by key instead of sentinelling them) and each logs under its own module's logger, which is what tells the two drops apart in a `TORCH_LOGS` run, so what is left to share is a format string. The handler sits at that caller rather than inside the shared `_read_raw_annotations`, which stays a pure reader raising for either format: the other caller, the AOT pickler's `evaluate=True` one, already handles its own read (it logs the reason it saw), so a keyword that selects a format does not also select an error policy. A RecursionError is re-raised rather than dropped: it is the dump's own limit, which `pickle_guards_state` reports as a bypass, not a property of the annotation, and swallowing it would drop a set that reads fine at any other depth. Dropping the whole set cannot silently break a guard: a guard rooted at `fn.__annotations__` evaluated them at trace time (the VALUE format, cached on the function), so a read that raises at dump time is one no guard performed. The 3.14 path had no test at all, since every annotation in the suite either was an assigned dict or resolved; a 3.14-gated test now pins that the TYPE_CHECKING-only name is genuinely unreadable outside the FORWARDREF read -- a direct `__annotations__` read raises `NameError`, a premise pruning to a sentinel cannot tell from a resolved class -- and that the f-string case drops the set (CI runs this file on 3.14; there is no local 3.14 build). Test and comment cleanups: the guarded-defaults test names the full-compile round trip that can tell a whole-container guard from a per-element one instead of forward-referencing it; the two snapshot tests assert on names their module cannot lose instead of comparing whole key sets against a live module dict a `CleanupHook` can pop from; the `name_beside_unpicklable_default` subtest now says why the default prunes, which is that `bind_args` guards `__defaults__` with SEQUENCE_LENGTH and only `EQUALS_MATCH` records a tuple in `value_guarded_containers`, so a length guard survives per-value pruning; the pickler `__init__` comment no longer claims omitting the recording prunes every container; the snapshot comment names both regimes whose guard filter drops the alias's BUILTIN_MATCH; and the annotations comment says what the keep branch there is for, which is a dict SUBCLASS assigned onto `__annotations__` that a guard registered (an exact dict is never carried whole on any version, and on 3.14 the read hands back a copy, so neither is a subclass one) -- the branch stays, since deleting it would prune that mapping per value and rebuild it as a plain dict. The snapshot comment also says what the exemption costs, which is that a guard walking the slot rebakes against the loading process's builtins rather than the binding the compile saw; and the two builtins tests pin the reference identity alone, since a copy cannot be `is` the live dict, while an absolute byte bound over a stream whose size depends on the pickle protocol and the per-version `SerializedCode` payload adds nothing to it. Kept as one commit rather than split three ways along the paragraphs above (the tuple rule, the builtins exemption, the annotation guard are independent and each carries its own test): this is the bottom PR of an already-submitted pickler stack, so splitting it rebases and renumbers every PR above it; what that buys is a finer bisect over three changes that already sit in disjoint functions and cannot interact. One #196476 comment is not a change here: the AOT pickler's own by-value reducer carried only `__defaults__` at that commit, so an AOT-rebuilt helper lost `__kwdefaults__` and `__dict__` and its `__name__` was the qualname. #196685 and the commits between it and this one moved that pickler onto the shared base, which is where those are already fixed. Test Plan: ``` python test/dynamo/test_guard_serialization.py python test/dynamo/test_guard_serialization.py -k test_snapshot_survives_a_cleanup_hook_pop_during_the_loop python test/dynamo/test_guard_serialization.py -k snapshot -k verbatim -k alias -k unresolvable_annotation -k raising_annotation_read -k without_builtins -k length_guarded -k name_beside_unpicklable_default python test/dynamo/test_aot_compile.py -k Pickler python test/dynamo/test_package.py ``` The preserves-module snapshot test asserts the rebuilt scope's `__builtins__` comes back as whatever the live dict held (the module when this file runs as `__main__`, the builtins dict when it is imported), and another pins the alias slot: with the exemption keyed on the name that slot arrives as a copy of the whole builtins dict, not the live dict. Six of the seven new tests fail on the previous commit: that alias one, `test_snapshot_of_an_unguarded_builtins_dict_stays_a_dict`, `test_a_recorded_tuple_is_kept_verbatim_without_a_tree_entry` (the behaviour change above), `test_a_raising_annotation_read_drops_the_set_but_not_a_recursion_error` (the parent's read is unguarded and nothing on its save path catches it), `test_snapshot_survives_a_cleanup_hook_pop_during_the_loop` (the parent builds the snapshot as a comprehension over the same live dict) and, on a 3.14 shard, `test_reduce_prunes_an_unresolvable_annotation_and_drops_a_raising_one` via its f-string case. Only `test_snapshot_of_a_scope_without_builtins_stays_without` passes there, and is kept for the contract the exemption must not break: a scope that has no `__builtins__` does not gain one. The TYPE_CHECKING test is 3.14-only and runs in CI, while the raising-read test patches the read itself, so the drop, its log and the RecursionError re-raise are covered on every shard, 3.10 included. Authored with an AI assistant. Co-Authored-By: Claude Opus 5 <[email protected]> ## FAQ > **FAQ: why is this not three commits (tuple rule / builtins exemption / 3.14 > annotation guard)?** The three changes are independent, each already carries its > own test, and the message's paragraphs are the seam -- but #196767 is the > pre-existing bottom PR of the pickler stack, not part of the #195354 re-slice > this round is doing. Splitting it renumbers and rebases every PR above it, and > what that buys is a finer bisect over three behaviour changes that already sit in > disjoint functions (`_keep_container_verbatim`, `_globals_snapshot`, the > annotation read in `_reduce_function_by_value`) and cannot interact. The commit > message keeps the three-way structure so a bisect landing here can tell which > behaviour it is. > **FAQ: isn't the `_keep_container_verbatim(raw_annotations)` keep branch dead code > now?** No, only on 3.14. Below 3.14 the read hands back `fn.__annotations__` > itself, and CPython lets that be a `dict` subclass; a subclass instance falls past > the `type(container) is dict` rule to the identity check, so a guard-registered > one is still carried whole (verified: it round-trips as the subclass, while > unregistered it comes back a plain dict of sentinels). Deleting the call would > silently change that case, so the call stays and the comment now states exactly > when it fires instead of the misleading 3.14-specific parenthetical it replaced. > **FAQ: the review asked for "FORWARDREF raises for an operation the proxy will > not represent". Why does the comment say something else?** Because that is not > the rule either, and the comment now has to be right in both directions. On > 3.14.7 the discriminator is `_Stringifier.__format__`, which > `annotationlib.py:520` raises from outright, not string formatting as a class: > `f"{Missing}"` and `f"{Missing:>10}"` raise, while `f"{Missing!r}"`, > `f"{Missing!s}"`, `f"{Missing=}"`, `"%s" % Missing` and `str(Missing)` all read > fine and give `{'x': 'Missing'}` -- those convert to `str` before the format > opcode, so the proxy's `__str__`/`__repr__` answers. And the proxy is not the > only way out: `()[0]`, `1/0` and `{}["k"]` raise with no proxy involved at all, > and `"".join([Missing])` raises from a real callee rejecting the proxy (`expected > str instance, _Stringifier found`). One sentence covers all three: only NAME > lookups are proxied, and the rest of the expression runs for real. That is what > the comment now says, and it is why `[Missing][0]` -- an expression with real > work that does not fail -- still reads back a `ForwardRef`. > **FAQ: the review says the `expected_keys` assertions can flake in either > direction. Isn't a `list()` at the capture the matching fix?** No, on both > counts. `CleanupHook.__call__` only ever `pop`s and nothing on the dump path > installs a name into a traced module dict, so the snapshot can only ever come > back a subset of the captured key set -- one direction, not two. And a `list()` > would not close it, because the hole is not inside an iteration: it is the gap > between `expected_keys = set(g)` and the dump, on a dict that is this test > module's live globals. That capture is itself a third exposure the finding did > not name -- `set(g)` iterates the live dict, so a hook firing during that > statement raises `RuntimeError` from the test body. Both tests therefore stop > comparing whole key sets and assert `assertIn` on names their module cannot > lose, which is what each was pinning (the module's own state arrived; the shared > scope is not the half-loaded copy) without depending on a key Dynamo owns. > **FAQ: Was `list(f_globals.items())` really exposed to a `CleanupHook` pop, > and is that what `dict(f_globals)` fixes?** > > Measured on 3.12.14 with `gc.set_threshold(1, 1, 1)` and a `gc.callbacks` > entry that pops a key out of a 5000-entry dict: a live > `for k, v in d.items()` loop that allocates per step raises > `RuntimeError: dictionary changed size during iteration` in all 50 trials, > while `list(d.items())` and `dict(d)` each raise in 0 of 50 -- both see one > or two collections during the call, but those land at a bytecode boundary > outside the C-level copy rather than between two iterator steps. The window > inside `list()` therefore did not reproduce on this interpreter, and the > change is not a bug fix: the loop walks `dict(f_globals)` because it is the > shorter spelling and materializes no N-entry list of 2-tuples, and the > comment above it now claims only what the measurement supports, which is > that iterating the LIVE dict while pruning is what raises. > **FAQ: the annotation on `raw_annotations: dict[str, Any] = {}` is redundant > and sits on the fallback rebinding -- the `try` binding two statements up > already comes from `_read_raw_annotations`, declared `-> dict[str, Any]`, so > drop it and leave `raw_annotations = {}`.** Declined: dropping it turns > PYREFLY red. `pyrefly.toml:143-146` switches `implicit-any` on for > `torch/_dynamo/**`, and pyrefly types each binding on its own rather than > joining the branches, so a bare empty literal is an error regardless of what > the other branch binds. Measured with pyrefly 0.58.0, the version pinned in > `tools/linter/adapters/pyrefly_linter.py`, on a standalone reduction of > exactly this shape (a `-> dict[str, Any]` callee in the `try`, a bare `= {}` > in the `except`): `Cannot infer type of empty container; it will be treated > as containing Any [implicit-any]` on the fallback line without the > annotation, and clean with it. The callee's declared return type does not > reach the `except` branch -- only a declaration gives `{}` a contextual type > -- and `torch/_dynamo/guards.py` is otherwise clean today (`pyrefly check > --config pyrefly.toml torch/_dynamo/guards.py` reports 0 errors, 28 > suppressed), so this would be a new error on a line the PR touches. The one > variant that also measures clean is moving the annotation up onto the `try` > binding; it was not taken because there it merely restates the callee's > declared return type, whereas on the fallback it is the only binding pyrefly > cannot infer. > **FAQ: the review says the 3.14 test's fixture rots "if that name ever gets > defined at this module's scope". Doesn't the new `NameError` assertion pin a > premise that a stray `TYPE_CHECKING` import could already break?** No -- that > particular vector cannot reach the fixture, and the assertion went in anyway > because the rest of the finding is right. `inner` is built by `exec` into a fresh > namespace, `ns = {"__name__": __name__}` > (`test/dynamo/test_guard_serialization.py:1767`), so the annotate function's > globals are `ns` and not this module's: measured on 3.14.7 with `class > OnlyUnderTypeChecking` defined at the module scope of the running file, > `inner.__annotate__.__globals__ is ns` is `True`, `"OnlyUnderTypeChecking" in ns` > is `False`, and the direct read still raises `NameError: name > 'OnlyUnderTypeChecking' is not defined`. The reachable rot is an edit to that > seed dict or to the `exec` string. What does hold is the non-discrimination: > every unguarded annotation prunes to a sentinel (`torch/_dynamo/guards.py:4535` > over `_prune` at `:4380-4383`, which keeps only a literal or a guard-registered > value), so measured on 3.12.14 a fully RESOLVED class annotation comes back > `_Missing` as well, and the assertion at `:1787` could not tell a proxy from a > resolved class. One line can: `inner.__annotations__` raising `NameError` before > the dump, which is the exact premise `_read_raw_annotations` cites for asking for > the FORWARDREF format at all (`torch/_dynamo/package.py:320-322`). It passes on > the fixture as written and fails loudly on the seeded namespace. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #196767 Approved by: https://github.com/pytorchgreenlight
Stack from ghstack (oldest at bottom):
Summary. A reloaded
nn.Moduleartifact rebuilt its global guards againstonly the scope the serialized bytecode reconstructs, because
AOTCompiledModel.deserializenever passed anf_globals, so any global Dynamohad specialized away failed every call with
KeyError on G['...']. The loadnow resolves the guard scope from
model.forward.__globals__and re-roots theguards at that live dict through a new keyword-only
guard_globals, seedinginto it the
__import_*aliases and__builtins_dict___Nkey Dynamo mintedin the tracing process, never overwriting a key already there, and
install_globalskips a name a load already bound so a later compile in thatmodule cannot collide with it. When no compiled input's guards match, module
dispatch now raises a report naming why each input was rejected instead of
re-running graph 0's guards, and a result opted out via
disable_guard_check()is consulted only after every guarded result wasrejected. Separately,
SystemInfogains a CPU codegen target so the precompileload gate compares the vector ISA an artifact's CPU kernels were tiled for
against the one
pick_vec_isa()picks on the host, sampled under thetorch.compilewrapper's own inductor config and skipped for backends thatemit no native code. Two smaller correctness fixes ride along: the device scan
reads the whole graph rather than the first meta leaf, and the Triton-version
and GPU-model checks exempt off the artifact rather than the loading host.
Guard scope for a reloaded module artifact
AOTCompiledFunction.deserializetakesf_globalsfor this, butAOTCompiledModel.deserializenever passed one. It now resolves the scope frommodel.forward.__globals__(viaget_traced_fn(forward), since for a hookedmodule
get_traced_fn(model)would returnModule._wrapped_call_implandnn.Module's namespace) and passes it through a new keyword-onlyguard_globals, kept apart from_extra_globals, which feeds the bytecode:Guards read the live dict by reference: a rebind after load redirects dispatch,
and a missing global fails the guard with no fallback to serialized values. A
forwardwithout__globals__(afunctools.partial, say) warns and uses thereconstructed scope. Since Dynamo roots guards at
__import_*aliases it mintsinto the tracing process's globals, loading inserts the recorded
__import_*aliases and the
__builtins_dict___Nkey into the live dict withoutoverwriting existing keys:
A baked-in
__builtins_dict___Nwould otherwise collide with the identicalname a later compile in that module regenerates (
unique_idis a freshper-process counter a load never advances), so
install_globalnow skips anyname already bound in the global scope:
torch.compiler.load_compiled_functionforwards itsf_globalsasguard_globalstoo, and both public docstrings document the by-reference read,the seeding, and the no-fallback contract.
Dispatch: a report instead of graph 0's guard error
AOTCompiledModel.__call__scans every result for a real match first (a guardtree that raises counts as "did not match", and the report names the raiser), then
serves the first result opted out via
disable_guard_check(), and only thenraises the report. A call the signature cannot bind still raises
bind_locals'TypeError, as the plain module call would. When an entry failed on a missingglobal, the footer says so instead of the generic advice.
The CPU codegen target
SystemInforecords(machine, vec_isa, vec_isa_width, vec_isa_macro, simdlen, march)for an artifact holding generated CPU code, and the load gate comparesthe resolved target
(machine, vec_isa, vec_isa_width, vec_isa_macro)against what
pick_vec_isa()picks on the host: the artifact's kernel sourcewas tiled for the capture ISA and the host recompiles it with its own.
pick_vec_isa()already folds the raw knobs (cpp.simdlenandATEN_CPU_CAPABILITY;marchnever reaches it) into the ISA it returns, sothe resolved triple is the complete key; simdlen and march stay in the recorded
tuple for diagnostics but do not gate. The name and width must both agree
(
VecSVE(128)/VecSVE(256)share the nameasimd), and the build macrosdisambiguate further (
VecNEONandVecSVE(128)share name and width butcompile with different capability macros). A wider host ISA is not a superset:
its masked loads zero-fill the lanes the narrower tiling never wrote.
The sample is taken under the backend's own inductor config.
torch.compile(options={...})builds a_TorchCompileInductorWrapperthatpatches config such as
cpp.simdlenonly for the duration ofbackend(),which has already returned by the time we sample, so we re-apply that config
while reading
SystemInfo.current():Otherwise the fingerprint would record the ambient ISA rather than the one the
kernels were tiled for, and an artifact could reject its own build host and
accept a wider one.
emits_native_code(backend_name)exempts eager-familyartifacts from the toolchain probe and the comparison (a blacklist on purpose:
anything unrecognised, a user callable included, is assumed to emit code, since
a false rejection at load is recoverable and running a kernel built for another
ISA is not), and a user backend can declare
emits_native_code = Falseon thecallable it hands
torch.compile.CompilePackage.__init__takes the samedecision as the keyword-only
requires_native_backend_compatibility, whicheval_framecomputes from the backend beforeget_compiler_fnerases itsname. Device EXISTENCE stays outside that exemption: an artifact holding cuda
tensors cannot run without cuda whatever backend produced it.
The device scan reads the whole graph
_graph_device_typesscans the whole graph instead of reading the first metavalue's device, which misreported a SymInt placeholder as "cpu" and let a mixed
cpu+accelerator graph skip the check. It returns every device type the graph
names, from meta leaves, from
.cuda()/.xpu()calls, and from the two devicepositions (a
device=kwarg and.to()'s device argument, where a bare stringis parsed by
torch.device; autocast device strings are ordinary positionalargs and never reach it), minus
meta. An empty result means the graph namesno device, which is not "cpu"; callers lower that to CPU code.
CompilePackageunions what its frames named, and both
CompileArtifactsand_DynamoCacheEntrykeep the collapsed accelerator-winsdevice_typefor BCbeside the new
device_typesset, since a mixed graph still emits native CPUcode that has to be gated.
Triton and GPU checks exempt off the artifact
The Triton-version and GPU-model checks now exempt off the artifact (the
receiver), not the loading host: an artifact built with Triton is rejected on a
Triton-less host, where before the host-side exemption let it load and then
fail later at kernel load. Making the cached info the receiver also labels
mismatch messages
cached=..., matching_DynamoCacheEntry.check_versions.User-visible changes
AOTCompiledModel.__call__raisesRuntimeError("No AOT compiled graph matched ...")listing why each input was rejected instead of running graph 0'sguards, and a result opted out via
disable_guard_check()is consulted onlyafter every guarded result was rejected.
CompilePackage.__init__'srequires_native_backend_compatibilityis keyword-only. An artifact savedbefore
cpu_codegen_targetandrequires_native_backend_compatibilityexistedkeeps loading: both default to values that skip the new gate.
Test Plan:
The scope tests fail on the pre-change tree with the KeyError. Codegen-target
tests patch
_current_cpu_codegen_targetinstead ofdepending on host hardware.
Authored with an AI assistant.
FAQ
Q: Why does the gate compare only the resolved ISA (machine, vec_isa,
vec_isa_width, vec_isa_macro) and not simdlen and march too? An earlier version
compared all of them exactly.
A: Because pick_vec_isa() already folds simdlen and ATEN_CPU_CAPABILITY (march never reaches pick_vec_isa; it only changes how the same tiled source is compiled)
into the ISA it resolves -- a simdlen that caps the width picks a narrower ISA,
so the recorded width and macros already reflect it -- the resolved triple is
the complete correctness key. Comparing the raw simdlen/march knobs on top of it
is not merely redundant, it is wrong in two ways. First, it rejects an artifact
this host can reproduce: an artifact captured under cpp.simdlen=256 is loadable
on any host that resolves to the same 256-bit ISA, whether the host gets there by
default or via ATEN_CPU_CAPABILITY, yet a raw-simdlen comparison rejects the
default-knob host. Second, it makes the documented escape hatch ineffective --
setting cpp.simdlen to fix an ISA mismatch would only trade the ISA error for a
simdlen error. A related bug the exact comparison hid: the sample was read after
backend() returned, so the _TorchCompileInductorWrapper's config patch (e.g.
cpp.simdlen) had already exited and the fingerprint recorded the ambient ISA,
not the one the kernels were tiled for -- so an artifact could reject its own
build host and accept a wider one. This commit re-applies the wrapper's config
while sampling so the recorded ISA is the one the kernels were actually built
for, and gates on that resolved ISA. The gate is still fail-closed: a genuine
ISA/width/macro mismatch is refused, and the caller can fix it with
ATEN_CPU_CAPABILITY or cpp.simdlen.
Q: A wider host ISA (AVX-512 loading an AVX2 artifact) is a superset, so why
reject it instead of running the narrower kernels?
A: A wider ISA is not a superset here. The kernels were tiled for the narrower
width, so the wider host's masked loads zero-fill the lanes the narrow tiling
never wrote and its unmasked reductions then read them, changing the result.
The comparison is exact -- and it compares the recorded ISA name, its bit
width, and its build macros together -- because
VecSVE(128), VecSVE(256), and VecNEON overlap in name and/or width and only the
full fingerprint tells them apart.
Q: When the loading host has no usable CPU codegen target at all (no C++
toolchain), the check hard-refuses rather than loading best-effort. Isn't that
too aggressive?
A: Fail-closed on purpose. An artifact that recorded a CPU codegen target holds
vectorized CPU kernels that must be compiled to run, and a host with no
toolchain cannot build them, so there is nothing to run best-effort; refusing
with a clear message beats failing deep in compilation. Eager-family artifacts,
which bake no native code, are exempted up front by emits_native_code(), so this
refuses only artifacts that genuinely need a compiler.
Q: The CPU codegen fingerprint records tuple(vec_isa.build_macro()), but for
AVX-512 that macro is the constant CPU_CAPABILITY_AVX512 and does not encode the
bf16/fp16 probe. Two x86 hosts that differ only in AVX-512-BF16 / AMX-FP16
support then produce an identical fingerprint, yet build_arch_flags() appends
-mavx512bf16 / -mamx-fp16 only where supported -- so a capture host bakes bf16
intrinsics and a loading host without them recompiles wrong. Isn't that a
collision?
A: Correct, and a real gap: build_macro() captures the ISA family but not the
bf16/fp16 arch-flag suffixes, so the fingerprint is coarser than the code the
recompile actually emits. The fix is to record build_arch_flags() -- which
subsumes the macros and the -mavx512bf16 / -mamx-fp16 / SVE -msve-vector-bits
suffixes -- rather than build_macro(). That changes the recorded fingerprint
semantics and can only be validated by exercising the codegen path across ISAs,
so it is tracked as a follow-up rather than folded into this commit unverified;
until then the check is correct on ISA family and width and misses only the
same-family bf16/fp16 sub-variant. When that follow-up records build_arch_flags(), note the ordering trap: VecAVX512/VecAMX set _arch_flags as a side effect of their bool probe, so the recorder must read build_arch_flags() only after bool() has run on the instance.
Q: An artifact saved under one backend and loaded under another disagrees on
whether the ISA gate applies (an inductor-saved entry loaded in an eager
session, or the reverse). How is that reconciled?
A: initialize() no longer clobbers _requires_native_backend_compatibility with
the loaded entry's value, so the constructor value -- taken from the backend the
caller is loading under -- stands. That fixes the load gate: an eager
constructor can no longer disarm the ISA check an inductor entry needs, so the
load never relaxes a host. The mirror direction is subtler: an inductor-saved
entry loaded in an eager-family (e.g. aot_eager) session and then re-saved
(literal "eager" records no bundled artifact, so only aot_eager reaches this)
would strip the fingerprint.
That is closed by the monotone OR-accumulate in #195913
(self._requires_native_backend_compatibility |= dynamo.requires...), which
neither the entry nor the constructor can relax; this commit removes only the
clobber the load gate needed.
Q: _graph_device_types walks the FX graph with its own heuristic instead of
reading V.graph.device_types, so it both over-reports (a false "cpu" for unused
placeholders arms the toolchain probe) and under-reports (string device= specs
are invisible). Why reimplement it?
A: The FX-level walk runs before inductor lowering, where V.graph.device_types
is not yet populated, so it cannot be read here; the heuristic is deliberately a
superset because arming the CPU toolchain probe for an artifact that turns out
to hold no CPU code only costs a load-time ISA check the caller can satisfy,
which is the fail-closed direction. String device= kwargs and a .to() device
argument are read, but only in those device positions -- not from any flat arg
-- because an autocast device type is a plain string positional of
_enter_autocast, and trusting every string leaf would inject a phantom "cuda"
into a CPU-only graph (unloadable on the very host that saved it) or a phantom
"cpu" from torch.utils.checkpoint's unconditional autocast("cpu") (arming the
ISA gate on an accelerator-only artifact). Device-carrying method calls beyond
.to()/.cuda()/.xpu() are still narrowing work tracked separately.
Q: A
functools.wrapswrapper assigned toforwardsilently yields the wrongguard scope:
get_traced_fnnever unwraps__wrapped__and_get_signatureuses
follow_wrapped=False, so a wrapper defined in a different module resolvesguards against the decorator's module with no warning -- the very failure this PR
fixes, in a shape the fix does not cover. Why leave it?
A: The silent case is asymmetric wrapping only:
functools.wrapscopies__module__/__name__/__qualname__but not__globals__, so when the samewrapper is present at both save and load the scopes agree and the artifact is
correct. It breaks only if the capture and the runtime wrap
forwardindifferent modules, which is not a shape any real serve path produces (the loaded
callable installs onto the recorded code object). Unwrapping
__wrapped__andcomparing
original_codeagainsttraced_fn.__code__to warn on the mismatch isthe right hardening and is tracked as follow-up; it is a detection improvement,
not a correctness fix for the paths this PR serves.
Q: Seeding
__builtins_dict___Ninto the live module globals makes a latertorch.compilein that same module crash.unique_id()is a process-global monotoniccounter that a load-only process never advances, so the artifact bakes in the capture
process's
__builtins_dict___0, deserialize writes that key into the module__dict__,and the next
OutputGraph.__init__there regenerates__builtins_dict___0and hitsCleanupHook.create, which raises because the name is already in scope. This is everycaller of the default
guard_filter_fn, not just those who keep global guards.A: Correct, and it was a real crash -- reproduced with the default filter. Fixed here in
OutputGraph.install_global: after minting a name fromunique_id, it now skips anyname already bound in
self.global_scope(while name in self.global_scope: name = unique_id(prefix)) before installing, so a later compile that regenerates a baked-in__builtins_dict___N/__import_*name transparently picks the next id instead ofcolliding in
CleanupHook.create.unique_idis monotonic, so the loop alwaysterminates. The seeding itself stays -- guards rooted at those names must resolve -- and
the collision it could cause on the next compile is what this fix removes.
Q: The AOT path inserts the
__import_*aliases and the__builtins_dict___Nkey straight into the caller's dict, without the
CleanupHook.disowntheprecompile path does first and without any
_installed_globals/uninstall/__del__bookkeeping -- and because the defaultguard_filter_fndrops everyis_globalguard, the common path mutates a torch namespace for guards that werefiltered out. Isn't the missing cleanup a hazard?
A: The insertions are bounded and idempotent (
if name not in scope), so this ispermanent-and-untracked, not unbounded growth, and it mirrors what tracing itself
already does into the same namespace at
symbolic_convert. The precompile pathneeds
disownand_installed_globalsbecause it supportsunload(); the AOTartifact has no uninstall surface by design (it is a load-and-run function, not an
installer), so there is nothing to take back out. Seeding a torch namespace when
the filter dropped the global guards is wasteful but harmless -- the keys are
inert if unread, and the one active hazard, a later compile colliding on a baked-in
name, is closed by
install_globalskipping already-bound names (see the collisionFAQ below). A cleanup API on
AOTCompiledFunction/AOTCompiledModelandgating the seed on whether global guards survived are both reasonable follow-ups;
neither changes a result today.
Q:
_backend_emits_native_codeclassifies the same backend differently byentrypoint and never classifies instance backends:
torch.compile(backend=eager)correctly yields
False(the wrapper stampscompiler_name), buttorch._dynamo.optimize(eager)stringifies the raw callable to native, aninstance like
CompileCounterhas no__name__, and the aot path reads"unknown"afterget_compiler_fnerased the string. Worse, a user backendwhose function is named
eageris silently exempted from the ISA gate. Why isthis acceptable?
A: The classifier is fail-closed by construction: an unrecognized backend is
assumed to emit native code and pays the ISA check, which only ever refuses a
load the caller can satisfy. The two "misclassified as native" cases
(
optimize(eager), instance backends) therefore cost a spurious toolchain probe,never a wrong result. The one genuinely fail-open direction -- a user callable
coincidentally named
eager/aot_eagertripping the name blacklist -- requires auser to name their own inductor-lowering backend after an eager builtin, which is
not a shape that occurs in practice; a name-based blacklist is the only signal
available before
get_compiler_fnruns, and tightening it (identity match ratherthan name, and stamping
compiler_nameonregister_backend) is trackedseparately. The
"unknown"the aot path records is the same fail-closed default.Q:
_NO_NATIVE_CODE_BACKENDSomits every non-inductor backend that is noteager-family --
ts/aot_ts,invoke_subgraph,cudagraphs,openxla,tvm,the
*_TESTING_ONLYgm-passthrough backends and the minifier backends -- so allof them are now gated on host ISA even though none emit inductor CPU kernels.
Shouldn't they be exempt?
A: Same fail-closed rationale: these backends are rare enough that the exemption
list intentionally enumerates only the eager family (the common no-codegen path),
and everything else pays a host ISA check. (Correction: that check is NOT
satisfiable on every host -- ATEN_CPU_CAPABILITY / cpp.simdlen can only lower a
host's resolved ISA, never raise it, and a toolchain-less host resolves no target
at all -- so a user backend that bakes no native code now has an opt-out on the
aot_compile path too: declare
emits_native_code = Falseon the backend callableand the artifact records no codegen target and skips the gate, mirroring the
package's requires_native_backend_compatibility.)
Enumerating each additional no-native-code backend is a pure widening of the
exemption with no correctness stake and is deferred; the current list is
conservative in the safe direction.
Q: The mixed cpu+accelerator device change is a load-time behavior change on
existing artifacts that neither the description nor the FAQ mentions: pre-PR a
mixed graph whose first meta value was a CPU tensor recorded
device_type="cpu"and skipped the GPU check, so it loaded on a host lacking the accelerator;
post-PR the device set is unioned and every device is checked, so it now
hard-fails there. Isn't that a BC break?
A: It is an intentional correctness fix, and the new answer is the right one: an
artifact that genuinely uses an accelerator must not load on a host without it,
and the pre-PR behavior (silently skipping the GPU check because a CPU tensor
happened to be first) was the bug. The only wrinkle is message ordering -- when
both the accelerator is absent and the ISA differs, the user sees the ISA message
first because
sorted({"cpu","cuda"})puts codegen first -- and that isdeliberate (ISA skew is fixable via
ATEN_CPU_CAPABILITY/cpp.simdlen, deviceabsence is not, so leading with the fixable one is the better default). The
behavior change is called out here for the record.
Q:
check_codegen=Falsereturns early inside the GPU block, so for aneager-family artifact carrying a cuda device the
toolkit_version,triton_versionandgpu_namechecks are all skipped -- andgpu_nameis not a"describes generated code" check the way the gate's comment justifies. Isn't
skipping
gpu_namefor an eager artifact wrong?A: Intentional. An eager-family artifact bakes no device-specific code -- no
Triton kernels, no toolkit-versioned cubins, nothing pinned to a particular GPU
model -- so it is portable across accelerators of the same family, and all three
GPU checks exist to protect generated code that an eager artifact does not carry.
Gating them together under
check_codegenis therefore correct for what theartifact actually contains;
gpu_nameguarding an eager artifact would refuse aload that is in fact safe. The comment's "describes generated code" framing is
about why the gate exists, not a per-check taxonomy.
Q: When the loading host reports no CPU codegen target at all,
_cpu_codegen_target_problemreturns a message that does not name the machinethe artifact was built for. Shouldn't the message name it?
A: The enclosing
RuntimeErroralready prints the full cached tuple(
cached={self.cpu_codegen_target}, machine included) next tocurrent=..., sothe machine is named at the call site. The per-branch string only supplies the
component-level reason for the mismatch, and a
Nonehost has no component tocompare against -- duplicating the machine there would be redundant.
Q: pick_vec_isa() at save is expensive (seen around 18s cold). Why pay it there?
A: It is gated on needs_cpu_codegen, so only artifacts that will emit native
CPU code reach it, and pick_vec_isa() caches its result -- the probe runs once
per process, not once per save. Recording the resolved ISA at save is what lets
load fail closed against a host that would pick a different ISA; deferring the
probe to load would move the cost, not remove it.
Q: An artifact captured under options={'cpp.simdlen': N} loads only on a host
that resolves to N. Doesn't passing the same options={'cpp.simdlen': N} on the
loading side fix it?
A: No, and this is worth stating explicitly -- including the sharp corner that it
fails even on the very machine that built it, in the same process. On load there is
no backend wrapper, so check_compatibility() samples SystemInfo.current() ambiently
-- outside any torch.compile(options=...) patch, which only takes effect once
tracing begins. simdlen lived only in the per-compile options, never in the global
config, so nothing re-applies it at load and the build host re-resolves to its
native (wider) ISA and rejects its own artifact. The documented escape hatch on the
loading host is therefore the global torch._inductor.config.cpp.simdlen (or the
ATEN_CPU_CAPABILITY env var), set before the load, not the options= form. The
capture-time half is fixed here by widening the config.patch context to cover
CompileArtifacts / AOTCompiledFunction construction, so post_init's self-check
samples under the same ISA the fingerprint recorded. Auto-re-applying the recorded
simdlen at load (so the round-trip needs no env/config) is a real improvement, but it
belongs with the load-side recompile-config plumbing that lands with the store-reload
work in #195913, not this commit's gate; the AOT load path deserializes bundled
kernels rather than recompiling from source, so the gate is a run-safety check and the
escape hatch is the supported reload path until then.
Q: The codegen fingerprint is armed from the backend and device
(emits_native_code(backend_name) and "cpu" in device_types), not from whether
inductor actually emitted a cpp kernel. An artifact whose CPU output is all
extern calls (torch.mm lowering to BLAS) still records a target, so the
load-time gate pays the full pick_vec_isa() dry-compile (~19s measured) for
nothing. Arm it from whether a cpp kernel was emitted.
A: The over-arming is deliberate and errs toward correctness. The gate rejects a
host whose resolved ISA differs from the one the kernels were tiled for; if we
under-arm -- record no target when a cpp kernel WAS emitted -- the gate accepts
an ISA-incompatible host and runs a mistiled kernel, a silent-wrong-result/crash
hazard that is strictly worse than a slow load. Arming on "the backend can emit
native CPU code" is the conservative superset that never under-arms. Precisely
detecting "inductor emitted zero cpp kernels for this graph" means introspecting
the compiled artifact's kernel sources, which is not reliably available at this
call site and, per the measurement's own method, needs a built inductor to
validate that the narrower signal never drops a real target; narrowing the arming
to it (and skipping the dry-compile when no cpp kernel exists) is the right
optimization but is tracked as follow-up rather than attempted without a build.
The one-time load cost is also amortized by TORCHINDUCTOR_CACHE_DIR.
Q: The remedy sentence points the user at ATEN_CPU_CAPABILITY /
torch._inductor.config.cpp.simdlen, but on fbcode/x86 pick_vec_isa()
short-circuits to VecAVX2() before reading either knob, so neither can move the
resolved ISA and _current_cpu_codegen_target() can never return None there. The
hint is inert in fbcode.
A: Correct that on fbcode/x86 pick_vec_isa() returns VecAVX2() unconditionally,
so the two knobs the hint names cannot change the resolved ISA and the escape
hatch is a no-op there. The hint is advisory and accurate off fbcode (OSS x86,
where valid_vec_isa_list()/cpp.simdlen/ATEN_CPU_CAPABILITY do resolve the ISA),
which is where an ISA-mismatch rejection is actually reachable; on fbcode the
fixed AVX2 target means two builds on the same machine class agree and the gate
does not fire in the first place. Conditioning the message on config.is_fbcode()
to drop the inert knob suggestion is a reasonable message-only refinement that
changes no gate behavior, deferred with the other fbcode-specific paths that
cannot be validated in this environment.
Q: The two store reload APIs -- DynamoStore.load_package and
DynamoCache.load_and_install_package -- construct CompilePackage(fn,
entry.dynamo) with the constructor default requires_native_backend_compatibility=True
and no backend to derive it from, and initialize() restores _device_types but
not the flag. So an eager package round-tripped through a store upgrades to
native on re-save: cache_entry() pays the pick_vec_isa() probe and stamps a
cpu_codegen_target onto an artifact that bakes no native code, which then
hard-refuses on an ISA-different host. Restore the flag from the entry here (it
records the value), or thread the kwarg through the store APIs.
A: Correct that at this commit the harm is real: the two store paths pass the
bare default True (the eval_frame path is the only one that derives the
constructor value from the backend, so the existing "the constructor value,
taken from the backend, stands" FAQ does not cover the store paths), and this
commit's cache_entry() probes eagerly, so a store round-trip of an eager package
re-saves as native. But the suggested entry-authoritative fix is the wrong
resolution, because at this commit the flag has no compile-path accumulation: it
is written once at construction and never OR'd by a later native compile. Making
the reloaded entry authoritative would fail OPEN in the mirror direction -- a
native session that reloads an eager entry (flag False) would then run native
compiles with the ISA gate disarmed and load a kernel built for another target
on an incompatible host, a silent-wrong-result hazard strictly worse than the
wasteful-but-safe over-arm this comment describes. The correct resolution lands
higher in this same stack (#195913): the flag is made monotone
(self._requires_native_backend_compatibility = self._requires_native_backend_compatibility
or dynamo.requires_native_backend_compatibility, which neither a reload nor a new
compile can relax), and the pick_vec_isa() probe is deferred out of cache_entry
-- the reload path stamps _system_info via SystemInfo.current(cpu_codegen=False)
carrying the entry's recorded target (None for an eager artifact) straight
through re-save, and the probe fires only in update_device_type during an actual
cpu-bearing compile. At the stack tip the store-reloaded eager package therefore
pays no probe and stamps no target on re-save -- exactly the harm this comment
asks for -- while a genuinely native new compile still arms the gate fail-closed.
The eager over-arm visible here is an intermediate-state artifact removed by that
deferred-probe change above it, not a shape the stack ships; adopting a local
entry-authoritative fix here would have to be reverted to reach the safe design.
Q: The CPU-codegen half of this commit -- SystemInfo, emits_native_code, the
check_compatibility rework, the fingerprint gate and roughly half the new tests
-- is an independent feature from the AOTCompiledModel.deserialize guard-scope
fix in the title, and it is the part that can newly hard-refuse a load. Split it
into (1) the guard-scope fix, (2) the _graph_device_types rewrite, and (3) the
CPU codegen fingerprint and gate so each lands on its own evidence.
A: Agreed on the logical separation, and in a fresh stack these would be three
commits. This commit sits deep in a 24-PR ghstack whose upper commits (the
capture session, save() entry point, and the monotone OR-accumulate /
deferred-probe changes that this very FAQ leans on) already depend on the
SystemInfo and emits_native_code surface introduced here; splitting it now
reindexes every PR above it and restarts their in-flight CI, which is a real cost
the reviewer explicitly flagged as "your call". The three parts are individually
reviewable in place: the guard-scope fix is the first three paragraphs and its
KeyError-reproducing tests, _graph_device_types is self-contained, and the
codegen gate is the part the FAQ scrutinizes. Keeping them together is the
smaller net change given the stack's current depth; the split is noted as the
right shape for any future reland.
Q: install_global's collision retry (the
while name in self.global_scopeloop)lives only in install_global, not install_global_unsafe, which
install_resume_function_global calls directly. Doesn't the resume-name collision
class the retry closes survive for resume functions?
A: The durable separator lands higher in this stack, in #195911, not at this
commit --
_resume_global_renames,package_tokenand the per-package uuid areall absent from package.py at this revision, so this answer describes where the
collision is closed, not code present here. #195911 renames a loaded package's
resume globals to
{name}_{package_token}(uuid minted once in init) while afresh compile installs the bare
__resume_at_<offset>_<n>, so the two can nevercollide and install_global_unsafe's assert-only behavior is correct on the resume
path.
__builtins_dict___Ncarries no such distinguisher, which is why the retryloop was added to install_global for it here and now. Until #195911 the resume-name
collision class is pre-existing and open; ghstack lands each PR individually, so
main can carry this commit without #195911's separator for a window; the
resume-name collision in that window is pre-existing, not introduced here. (#195911 also makes an
intra-package duplicate resume name raise loudly, closing the last silent route.)
Q: load_compiled_function passes guard_globals=f_globals, conflating the globals
the function runs in with the globals guards evaluate against, despite the
docstring distinguishing them. Shouldn't they be separate?
A: They are intentionally the same here. A compiled function's guards check the
very globals that function will read at runtime -- that is the point of a global
guard -- so evaluating them against a different dict would guard state the
function never sees. deserialize() keeps guard_globals as a distinct parameter for
callers that genuinely have two dicts (a guard tree rooted in one module served
into another), but load_compiled_function is the common single-module entry point
and binds both to f_globals deliberately. Exposing a second kwarg on it would add
API surface for a split that this entry point, by construction, does not have. The
docstring describes the general deserialize() contract; the narrowing to one dict
at this call site is intended, not an oversight.
Q: The module path auto-resolves its guard scope, but
torch.compiler.load_compiled_function(f) with no f_globals still lands on the
function path and fails any surviving global guard with a bare KeyError on
G['...']. Why not record fn.module at capture and resolve sys.modules[...] the
way AOTCompiledModel does?
A: This commit takes the cheaper of the two remedies the finding offers. When
_guard_globals is None and the guard fails on a KeyError on G[...],
AOTCompiledFunction.call now appends a pointer telling the user to pass
f_globals to load_compiled_function, so the degraded mode names its own fix
instead of surfacing a bare KeyError; AOTCompiledModel's no-match footer gets the
same missing-global branch. Recording the defining module at capture and
resolving sys.modules[...] is the durable version and a reasonable follow-up, but
it is a capture-time schema change, whereas the pointer hint closes the
diagnosability gap without one. The condition is pre-existing, not a regression
introduced here.
Q: SystemInfo.current defaults cpu_codegen to True, which runs the expensive
pick_vec_isa() probe, yet every call site passes cpu_codegen=False explicitly.
Shouldn't the default be False so the probe is opt-in?
A: The default is deliberately the complete value, not the cheap one.
check_compatibility only compares cpu_codegen_target when it is not None, so a
SystemInfo built without the probe silently carries no codegen fingerprint and a
later load on a mismatched ISA is not caught -- a correctness hole. Building one
with the probe is merely slower. Every current call site already passes the flag
explicitly, so the default governs only a future caller that omits it;
defaulting to True means such a caller gets a correct-but-slower artifact rather
than a fast-but-silently-incompatible one. The False overrides sit exactly where
codegen is known to be irrelevant -- the field factory's placeholder and the no-
graph-captured case -- so the expensive probe is opt-OUT there, not opt-in
everywhere.
Q: AOTCompiledModel._no_match_message picks one footer via an exclusive
if missing_global / else, so when two results fail and only one lacks a globalthe ModelInput hint on the other is dropped; and the two branches test "is a global
missing" with different predicates (
"G['"over-matches,"KeyError on G["under-matches). Shouldn't the hint be per-result and the predicate shared?
A: Both are real refinements and neither changes a report a user sees today. The
per-result
[i]lines already print every failure with its own reason; only thetrailing hint is a single footer, so the mixed-cause pair loses advice, not
diagnosis -- and attaching the hint to the
[i]line that triggered it is theright shape (it also keeps the len(splitlines)==4 assertions intact), but that is
a message-layout change, not a correctness one. The predicate divergence is a
wording inconsistency: both predicates only gate whether the "pass f_globals / add
a ModelInput" hint is appended, so an over-match appends it spuriously and an
under-match omits it -- in both cases the load still fails with the same error and
the same per-result reasons. The two branches now use predicates fitted to their
inputs: the raising branch tests
kind == "KeyError" and "G['" in detail(a raisedKeyError stringifies to the bare
"G['NAME']", so the verbose-report text"KeyError on G["can never appear there) and the non-raising branch keeps"KeyError on G["over the verbose parts. They are intentionally different, notdrift.
Q: AOTCompiledFunction.call appends a hint saying the guard scope "was
reconstructed from the serialized bytecode ... pass f_globals to
load_compiled_function", gated on
self._guard_globals is None-- but that is alsotrue of every in-process capture that never serialized (the capture path passes
only _extra_globals), so a user who never saved can be told to pass f_globals.
Shouldn't it gate on an explicit "was deserialized" flag?
A: The hint is appended only when a guard actually FAILS on an absent global (a
KeyError reaching G['NAME']), not on every in-process run. A never-serialized
capture reaches it only if its live guards genuinely reference a global that was
deleted after capture -- in which case supplying the missing global (via f_globals
on a reload, or simply keeping it defined) is the correct remedy, so the advice is
directionally right even when the exact API name does not apply to an in-process
object. The predicate is broader than "was deserialized", and gating on an explicit
flag (or reusing _no_match_message's always-true phrasing) is a fair follow-up, but
the message only ever fires on a real missing-global failure, so it does not
misdirect a healthy in-process capture.
Q:
AOTCompiledModel.__call__'s dispatch loop lets a raisingguard_checkpropagate, while
_no_match_messagetolerates a raising guard. Shouldn't the twoagree?
A: Fixed: the scan now treats a raising guard TREE as "did not match" and moves
on, and the report names the raiser as before. Binding errors are not tolerated:
prepare_f_localsruns outside the guarded region, so a call the signaturecannot accept still raises
bind_locals' TypeError as the plain module would(pinned by
test_aot_compile_module_wrong_arity_raises_type_error) instead of ano-match report telling the user to add a ModelInput. (Correction to an earlier
wording: the C++ guard tree does not swallow everything. A Python-level failure
inside a guard is cleared by
check_nopybindand reported as no-match -- theverbose variant renders it as
KeyError on G['...']-- but aTORCH_CHECKorpy::castfailure unwinds throughRootGuardManager::checkand reaches Pythonas a RuntimeError, which the scan now treats as "this entry did not match" and
reports by name rather than failing the whole call.
RootGuardManager::checkrestoring
PythonTorchFunctionTLSby hand on that unwinding path is apre-existing guards.cpp issue this commit does not change. The Python-side
raisers,
prepare_f_locals/bind_locals, would fail the call for the sameinput anyway; the fix is about the two paths agreeing.)
RaisingGuardManager.checkinthe existing test now raises too, so the scan loop is covered.
Q:
cache_entry()samplesSystemInfo.current()ambiently, so a packagecompiled under
torch.compile(options={"cpp.simdlen": 256})on an AVX-512 hostrecords the 512-bit ISA its kernels were not tiled for -- the bug the AOT half
fixes here. Which commit closes this?
A: Correct at this revision:
cache_entry()runs from record_package/save_packageafter the
_TorchCompileInductorWrapper's config_patches scope has exited, andnothing on the package carries that config here. #195913 closes it directly: it
moves the probe out of
cache_entryintoupdate_device_type(graph, codegen_config=...), and convert_frame recovers the wrapper's config from thecompiler_fn chain (
_inductor_codegen_config) and re-applies it withtorch._inductor.config.patcharound the sample -- the same re-applicationaot_compile_fullgraphdoes here. A local fix would have to stash the config onthe package and re-apply it in
cache_entry, code #195913 deletes when itrelocates the probe, so the fix lands with the commit that owns the probe's new
home. The load side is unchanged (ambient, with the global cpp.simdlen /
ATEN_CPU_CAPABILITY escape hatch).
Q: The
test_save_guidance_when_a_locals_class_default_cannot_picklecomment saysthe shared "local object" substring covers the pure-Python pickler too, but that
pickler's message ("Can't pickle <class ...>: it's not found as ...") has no such
substring.
A: Right on the parenthetical (the headline -- that AttributeError never escapes --
is wrong: the C pickler
AOTCompilePicklersubclasses raises it unwrapped through3.13, and 3.14 raises PicklingError "Can't pickle local object"). The pure-Python
pickler is unreachable from
AOTCompilePickler(pickle.Pickler), so the comment nownames the two versions' wordings and drops the pure-Python clause. The test moved
to #196454 with the code it pins, so the reword lives there.
Q:
test_eager_backend_entry_is_exempt_from_the_codegen_target's native half onlyasserts
requires_native_backend_compatibility; the target the probe recorded isnever checked, and asserting it directly would need a host toolchain.
A: Fixed: the native half patches
_current_cpu_codegen_targetto a sentineltarget and asserts the entry recorded exactly that, so it needs no toolchain.
Q: No test drives the
options=-patched capture path inaot_compile_fullgraph;the footer branch selection in
_no_match_messageis unpinned; the__call__missing-global hint is unasserted; the ISA table is a hand-rolled loop rather than
@parametrize;check_codegen=Falseon cuda is untested.A: Added:
test_aot_compile_samples_the_codegen_target_under_the_wrappers_config(the recorded simdlen is the wrapper's, the ambient config is untouched after),
assertInon each footer in the two no-match tests,test_aot_compile_fn_missing_global_hint_names_f_globals, the ISA table as named@parametrizesubtests, and acheck_codegen=FalseGPU case in the Triton/GPUexemption test.
Q:
(line,) = logs.outputplus afunctools.partial(substring in thepartial-forward fallback test is brittle; the seeds test "sanitizes rather than
cleans up" by filtering
__import_*names; the mixed-device test depends oncheck_versionsordering.A: The single-record unpacking is deliberate -- any extra deserialize warning
should fail the test, that is the contract -- and
functools.partial(is the reprPython has emitted for decades. The
__import_*filter isolates from earliertests: any compile writes those aliases into the tracing module's globals
(symbolic_convert's
install_global) andCleanupHookremoves them on reset, sothe filter is scoping, not a cleanup leak. The ordering dependence is documented
at
check_versions("cpu first ..."); left as is.Q: The
except (RuntimeError, AttributeError)arm aroundget_traced_fninaot_compile_modulehas no test.A: Reachable (
mod.forward = torch.addhas__self__but no__func__) but lowvalue: it only selects the warning text for an unresolvable guard scope, which the
existing scope tests already exercise on the resolvable side. Left to follow-up
rather than pinned here.
Q: pr-sanity-checks is red -- this commit grew to 2058 lines.
A: The AOT-pickler tests (five
TestAOTCompilecases plus the wholeTestAOTCompilePicklerclass) exercise code that #196454 introduces, so theymoved down to that commit; this commit is now ~1700 lines and the combined tree is
unchanged.
Q: The AOT-compile page documents the new
f_globalscontract but not the othernew user-visible load failure: an inductor artifact recorded a CPU codegen target
and is refused on a host that resolves a different one, with
ATEN_CPU_CAPABILITY/ the global
cpp.simdlenas the escape hatch.A: Added to "Choosing a backend" (the section that already contrasts inductor and
eager): what is recorded, the exact error, why a wider ISA is not a superset, how
to make the host resolve the recorded ISA before loading, that
options=doesnot apply at load time, and that eager/aot_eager artifacts are exempt; plus a
cross-reference from
load_compiled_function's Returns.Q:
optimize_assert's copy of thenative_backendthreading is untested; theeager-exemption test only takes the
_optimizebranch, so the two call sites candrift.
A: The test is now parametrized over
fullgraph(False ->_optimize, True ->optimize_assert) so both paths are pinned.Q:
initialize()restores_device_typesfrom the cache entry but notrequires_native_backend_compatibility, and neither store load path passes thekwarg, so a loaded eager package loses its exemption and re-saves with a baked
codegen target.
A: Correct at this revision; #195913 closes it in both ways the review lists:
initialize()ORs the entry's flag into the package's (monotone, with the probedeferred), AND
DynamoStore.load_package/load_and_install_packagepassrequires_native_backend_compatibility=entry.dynamo.requires_native_backend_compatibilityso a False survives the constructor default. The eval_frame path (a native
session reloading an eager entry) is why the entry is not made authoritative on
its own: that would fail open. The manual kwarg in
test_loaded_eager_package_stays_exempt_on_resavemodels that eval_frame path.Q: The blacklist rationale ("a false rejection at load is recoverable") does not
hold on the
aot_compilepath:CompileArtifactsderives the gate solely from thebackend name, so a user backend that emits no native code is fingerprinted with the
capture ISA and cannot be loaded on a narrower or toolchain-less host.
A: Fixed:
CompileArtifacts.requires_native_backend_compatibility(default Trueso artifacts saved before the field keep loading) is set at capture from the
backend -- the eager family by name, or any callable declaring
emits_native_code = False(honoured by_backend_emits_native_codefor thepackage path too) -- and
check_compatibilityskips the ISA gate when it isFalse. Pinned by
test_aot_compile_backend_declaring_no_native_code_skips_the_isa_gate(no target recorded; loads with a host that resolves no target). The docs now
state the true scope: every backend outside the eager family is gated unless it
declares otherwise.
Q: The install-collision retry lands on
install_globalonly, butinstall_global_by_idand the resume-function install also reachCleanupHook.create,which raises on a name that already exists.
A: The resume half is closed by #195911's per-package token rename (the FAQ above
says where).
install_global_by_idnames (___module_<name>_<id>_c<compile_id>)are never seeded by any load path --
install()seeds onlyimport_sourcesandfunction_names, and the AOT loader seeds import aliases and the builtins-dictkey -- so there is no baked-in name for a later compile to collide with (probe:
capture, reset, load, recompile in the same module: OK). Only
__builtins_dict___Ncarries no distinguisher, which is why the retry is scoped to it.
Q:
linux-docsis red from this PR up.A: The cross-reference added last round used a
#headinganchor, which thisdocs build (no
myst_heading_anchors) does not resolve; it now uses the file'sexplicit
(choosing-a-backend)=label and a{ref}role.Q:
test_check_compatibility_compares_artifact_against_current_machineis redfrom this PR up.
A: My round-38 change made the ISA gate a conjunction of the backend name and the
new capture-time flag
requires_native_backend_compatibility; the test flippedonly the name, so the gate stayed disarmed and
assertRaisesfailed. The eagerarm now asserts the flag is False for an eager capture and then arms it, so the
name exemption and the receiver-order checks are each pinned on their own.
Q: The opt-out
emits_native_code = Falseis a fail-open escape hatch documentedwith no warning about what declaring it wrongly costs, and nothing says where it
must live for a wrapped backend.
A: The user guide now says both: the attribute is read off the object passed as
backend=totorch.compile(a registered name resolves to its function first),so for
aot_autograd(fw_compiler=...)it goes on the returnedAotAutogradobject and not on
fw_compiler; only the literal False counts; anddeclaring it on a backend that does emit native code disables the only check
between a mis-targeted artifact and a first-call crash. The docs also name the
_NO_NATIVE_CODE_BACKENDSfamily rather than listing two of its members.Q: The attribute is de facto public API with no home in the
SerializableCallableprotocol;
register_backendshould accept and stamp it so the classifier canmatch by identity instead of by name.
A: Not in this commit. A protocol attribute would make it a property of every
serializable backend, but the flag describes the backend's codegen, not its
serializability, and most backends never set it. Stamping via
register_backendonly covers registered backends; the user callable handed straight to
torch.compileis the case the opt-out exists for. Matching the in-tree eagerfamily by identity rather than name is a reasonable follow-up once the registry
grows that surface; the
__name__ == "eager"collision it would close is alreadyFAQ'd above as accepted.
Q:
getattr(..., "emits_native_code", True) is not Falsetreats a method or atruthy non-bool as native.
A: Deliberate: the gate fails closed. Anything but the literal False -- a method
(
is not Falseon a bound method), a string, a missing attribute -- keeps theartifact fingerprinted. The docs now say "the plain attribute
emits_native_code = False; any other value counts as native".Q: The raising-guard branch of
_no_match_messagetests"KeyError on G[" in detail, but a raising guard'sstr(e)is the bare KeyError text, so thepredicate is dead.
A: Fixed: the branch now tests
kind == "KeyError" and "G['" in detail, andtest_no_match_message_survives_a_raising_guardasserts the missing-global footeris present.
Q:
AOTCompiledFunction.__call__'s missing-global hint says the scope "wasreconstructed from the serialized bytecode" and points at
load_compiled_function,but
_guard_globalsdefaults to None on an in-process capture that was neverserialized.
A: Fixed: the hint reuses
_no_match_message's neutral phrasing (a guardedglobal is missing from this process; define it or load with an
f_globalscarrying it).
AOTCompiledModelnever reaches that branch: its__call__hasits own no-match report.
Q:
_simdlen/_marchare unpacked and never read in_cpu_codegen_target_problem.A:
cached[:4]now.Q: The no-native-code test never round-trips the artifact through save/load, and
nothing pins that the same backend WITHOUT the declaration is fingerprinted.
A: Both added to
test_aot_compile_backend_declaring_no_native_code_skips_the_isa_gate:the artifact is saved and reloaded on a host that resolves no codegen target and
still serves, and an undeclared twin of the backend records
requires_native_backend_compatibility=Truewith the capture target.Q: A subgraph tiled under a nested compile region's own
cpp.simdlen(
_patch_nested_region_inductor_config) is fingerprinted with the ambient ISA.A: Known and out of scope for the gate: the fingerprint is per artifact, and an
artifact whose regions were tiled for different widths cannot be described by
one target. Nested regions with their own simdlen are an inductor feature the AOT
path does not compose with today; when it does, the fingerprint should become the
set of targets the regions resolved, which is a follow-up to that composition, not
to this gate.
Q: No test where an opted-out result's guard evaluation raises.
A: The raising-guard scan is backend-agnostic (it runs before any backend
attribute is consulted), and
test_no_match_message_survives_a_raising_guardcovers it; repeating it under the opt-out would exercise the same lines.
Q:
VecNEONis never instantiated in either test file, so NEON-vs-SVE128 iscovered only by literal tuples.
A:
VecNEONcannot be instantiated on the x86 hosts CI runs these files on(
pick_vec_isanever returns it there, and constructing it by hand exercises nox86 codepath), so the literal target tuples are the honest cross-architecture
coverage available; the arm64 CI job runs the same comparison end to end through
the real
pick_vec_isa.Q: The docs say the attribute is read "off that callable's compiler_fn when it
is a wrapper", but
aot_autograd()returns anAotAutogradwhose__name__is"compiler_fn" and which has no
compiler_fnattribute. Which wrapper is meant?A: Only torch.compile's own
_TorchCompileWrapper, which stores the user'sbackend as
.compiler_fn; the one-hop getattr exists to see through it.AotAutogradis never unwrapped (it IS the wrapper's compiler_fn), so the docsnow state the rule without naming an internal: set it on the object passed as
backend=. One limit for the record:torch._dynamo.optimize("name")with aregistered NAME string never resolves the name before classifying, so a
declaration on the registered function is honoured only through
torch.compile; the string path falls back to the name blacklist (fail-closed,native).
Q: The mismatch RuntimeError prints the full six-tuple, so a 256-vs-None
simdlen/march tail can read as the cause while the remedy names cpp.simdlen.
A: The tail is diagnostic on purpose (
_cpu_codegen_target_problem's docstring:simdlen and march stay in the recorded tuple for diagnostics but do not gate),
and the
problemsentence appended to the same error names the exact gatingcomponent (machine, or ISA/width/macros) with both values, so the cause is
stated next to the tuple. Labelling the two trailing fields is a wording
refinement left for follow-up.
Q: Neither shipped store reload path is exercised for the package flag.
A: The kwarg threading through
DynamoStore.load_package/load_and_install_packagelands in #195913, which owns that seam; the testbelongs there (noted for that PR's next round), not in this commit whose reload
sites are unchanged.