Repository navigation
[precompile] Fingerprint what a guard checks when its rendered code does not say - #197271
Closed
bobrenjc93 wants to merge 28 commits into
Closed
bobrenjc93 wants to merge 28 commits into
bobrenjc93 wants to merge 28 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/197271
Note: Links to docs will display an error until the docs builds have been completed. ⏳ No Failures, 51 PendingAs of commit 9da2d1e with merge base d78bbf2 ( 🟡 GREEN LIGHT - PR was reverted - re-landing requires human review:
Green Light will not review this PR again, on this or any later commit; re-landing it needs a human approval. This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This was referenced Sep 16, 2026
Closed
Closed
pytorchgreenlight
Bot
dismissed
their stale review
September 21, 2026 14:37
This pull request was reverted; greenlight's approval no longer applies.
[ghstack-poisoned]
This was referenced Sep 21, 2026
Closed
Closed
Closed
Closed
Closed
Closed
Closed
Closed
bobrenjc93
added a commit
that referenced
this pull request
Sep 21, 2026
) **Summary.** Whatever autocast state the capture ran under is already baked into the artifact -- ATen casts for the eager backend, generated kernels for inductor -- but the artifact still re-dispatches at serve time (the eager graph's ATen calls, and on the inductor path every fallback op, which is emitted at its `.default` overload -- e.g. `aten.addbmm.default`, which AutocastCPU registers), so a serving process with autocast enabled would cast a second time. Both inlined drivers now run the graph under `torch._C._DisableAutocast()`, the `c10::impl::ExcludeDispatchKeyGuard` over `autocast_dispatch_keyset` (`torch/csrc/autograd/init.cpp`) that AOTAutograd already emits into its own generated wrappers as `_DisableAutocast_` when a compile ran under autocast (`torch/_functorch/_aot_autograd/runtime_wrappers.py`). It is one RAII exclusion of the autocast keys for every device: no per-device list, no nesting counter, and no `clear_autocast_cache()` on exit, so it is safe to enter unconditionally on every call and leaves the caller's autocast state exactly as it found it. This pins autocast off for the duration of the call regardless of capture-time or serve-time state, exactly like the eager driver's pre-existing unconditional `no_grad`; the programming-model docstring gets the same sentence in the later commit that rewrites it (E2). AOTAutograd's guard is conditional on the capture having run under autocast; precompile's is unconditional because the leak it closes runs the other way too (a capture made without autocast, served under it), which is the case the test exhibits. An earlier draft of this commit recorded a `GRAPH_DEVICES` metadata field and entered `torch.amp.autocast(dev, enabled=False)` per device; that reimplemented the primitive with a narrower cache-clear hazard (any exit that returns autocast's nesting count to zero wipes the process-wide cast cache), so the field, its emitter and its parser entry are gone and the artifact format is unchanged from the parent. ## Before and after ```python compiled = PrecompiledModule(lambda m, x: m(x), backend="eager") compiled._compile((model, x)) ns = {"__name__": "artifact"} exec(compiled.to_python_code(), ns) with torch.autocast("cpu", dtype=torch.bfloat16): out = ns["forward"](model, x) # parent: the captured graph re-dispatched under autocast and cast its inputs a second time (bf16 out) # now: the driver runs call(...) under torch._C._DisableAutocast() (fp32 out, equal to the # no-autocast call), and the caller's autocast state is as it was afterwards ``` ## The driver change ```python # _eager_forward: with _torch._C._DisableAutocast(), _torch.no_grad(): out = list(call([...])) # _inductor_forward: with _torch._C._DisableAutocast(): out = list(call([...])) ``` `test_artifact_neutralizes_ambient_autocast` (parametrized over both backends, CPU bf16 autocast) captures a `torch.addbmm` model and checks that a call under ambient autocast returns the fp32 result of eager `model(x)` computed outside any autocast, that the ambient region is still live and bf16 after the call, and that autocast is off again after the region. `addbmm` is the op that makes the inductor case load-bearing on CPU: `KERNEL_CPU(addbmm, lower_precision_fp)` registers it for AutocastCPU, `make_fallback(aten.addbmm)` leaves it undecomposed, and `FallbackKernel` keeps builtin aten ops at their functional overload, so the inductor artifact calls `torch.ops.aten.addbmm.default` (the `Linear`/`addmm` graph cannot show this: `extern_kernels.addmm` binds `addmm.out`, which autocast never registers). Deleting either guard fails its case: eager with `bfloat16 != float32`, inductor with `assert_tensor_metadata` raising `expected dtype torch.float32 but got torch.bfloat16`. Test Plan: ``` python test/test_precompile.py -k autocast python test/test_precompile.py lintrunner torch/_precompile.py torch/_precompile_driver.py test/test_precompile.py ``` Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: #197279 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595, #197265, #197267, #197268, #197269, #197270, #197266, #197271, #197272, #197273, #197274, #197275, #197721, #197276, #197278 Re-land of #197279, reverted in 70f4f9b as a dependent of #197262 (whose test the re-land below fixes). ghstack-source-id: bf1865a
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
…oes not say (#197271) (#197973) **Summary.** Most guards render code that names the value they check, but three kinds do not, and comparing their facts across variants by rendered code alone would call different specializations equal. `_value_fingerprint(entry)` supplies the missing discriminator: for a tensor it renders exactly what `TensorCheck` stores, via `get_tensor_guard_code_part` with the TLS-adjusted dispatch key set, because `TENSOR_MATCH`'s `code_list` carries only the `_dynamo_*_indices` checks while dtype, shape, python type and dispatch keys all live in the C++ leaf (a `Parameter` against a `Tensor`, or an inference-mode tensor against a `no_grad` one, splits a compilation exactly as dtype does); for `GRAD_MODE` and `DETERMINISTIC_ALGORITHMS`, which carry no name, code or value, it reads the same process state `GlobalStateGuard` snapshots; for `AUTOGRAD_SAVED_TENSORS_HOOKS` it names the installed hooks through `_saved_hooks_fingerprint` the way the guard compares them, since `_normalize` had to erase their ids: the guard stores `None` for any hooks it cannot inline, so plain-Python hooks and no hooks are one value, and inlineable fx `GraphModule` hooks are named by a digest of their rendered graph (KNOWN TRADEOFF: two distinct `GraphModule`s with identical code read as one hook set while the guard compares ids); and for an identity guard it uses `_object_identity`. Every other guard returns `""`, deliberately: `TYPE_MATCH` on an unspecialized int checks only that it is an int, and stamping `1` on one variant and `2` on the next would demote a real invariant into two identical "varies" lines. Every branch therefore dispatches on `entry.guard_type`, never on the value's type: the `NOT_NONE_MATCH` Dynamo installs on an optimizer's `.grad`, a `COW_TENSOR_MATCH`, or a `TYPE_MATCH` on a tensor attribute holds a tensor whose shape and dtype it never checks, and rendering them would split identical guards. `_fact_order` is the sort key for facts, and it includes the value because once boilerplate code parts are filtered a `TENSOR_MATCH` renders no code, so two shape specializations would otherwise tie and sort unstably. The docstring records the KNOWN GAP that under `dynamic=True` the concrete shape here is narrower than the guard, so a shape-generic `TENSOR_MATCH` reads as varying rather than invariant. ## What each guard type contributes ```python _value_fingerprint(grad_mode_entry) # "grad_enabled=True" (read from torch.is_grad_enabled()) _value_fingerprint(deterministic_entry) # "deterministic=False, warn_only=False" _value_fingerprint(saved_hooks_entry) # "hooks=None", or "hooks=(<sha>, <sha>)" for inlineable fx hooks _value_fingerprint(tensor_entry) # "check_tensor(<value>, Parameter, DispatchKeySet(...), torch.float32, ...)" _value_fingerprint(id_match_entry) # _object_identity(entry.value) _value_fingerprint(type_match_on_int_entry) # "" -- the rendered code already names the check _value_fingerprint(not_none_on_grad_entry) # "" -- a tensor value, but the guard checks only presence ``` A tensor whose guard part cannot be rendered (a `__torch_function__` subclass that refuses attribute reads) falls back to `type=..., <unrenderable>` rather than raising out of a lint, and a hooks read that fails renders `hooks=<unreadable>`, distinct from the `""` that means no discriminator is needed. `test_value_fingerprint_dispatches_on_the_guard_type` pins that five tensors differing in dtype, shape, `Parameter`-ness and inference mode render five distinct `check_tensor(<value>, ...)` strings, that `NOT_NONE_MATCH`, `TYPE_MATCH` and `COW_TENSOR_MATCH` on the same tensor render `""`, the `GRAD_MODE`, identity and unrenderable-subclass renderings, and that `_fact_order` orders by value. `test_saved_hooks_fingerprint_mirrors_what_the_guard_stores` pins `hooks=None` for both no hooks and plain-Python hooks and the per-graph digest for `GraphModule` hooks. Test Plan: ``` python test/dynamo/test_precompile_package.py -k fingerprint lintrunner torch/_dynamo/precompile_package.py test/dynamo/test_precompile_package.py ``` Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Fable 5.1 <[email protected]> Reverted in 602de98 as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197973 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):
Summary. Most guards render code that names the value they check, but three kinds do not, and comparing their facts across variants by rendered code alone would call different specializations equal.
_value_fingerprint(entry)supplies the missing discriminator: for a tensor it renders exactly whatTensorCheckstores, viaget_tensor_guard_code_partwith the TLS-adjusted dispatch key set, becauseTENSOR_MATCH'scode_listcarries only the_dynamo_*_indiceschecks while dtype, shape, python type and dispatch keys all live in the C++ leaf (aParameteragainst aTensor, or an inference-mode tensor against ano_gradone, splits a compilation exactly as dtype does); forGRAD_MODEandDETERMINISTIC_ALGORITHMS, which carry no name, code or value, it reads the same process stateGlobalStateGuardsnapshots; forAUTOGRAD_SAVED_TENSORS_HOOKSit names the installed hooks through_saved_hooks_fingerprintthe way the guard compares them, since_normalizehad to erase their ids: the guard storesNonefor any hooks it cannot inline, so plain-Python hooks and no hooks are one value, and inlineable fxGraphModulehooks are named by a digest of their rendered graph (KNOWN TRADEOFF: two distinctGraphModules with identical code read as one hook set while the guard compares ids); and for an identity guard it uses_object_identity. Every other guard returns"", deliberately:TYPE_MATCHon an unspecialized int checks only that it is an int, and stamping1on one variant and2on the next would demote a real invariant into two identical "varies" lines. Every branch therefore dispatches onentry.guard_type, never on the value's type: theNOT_NONE_MATCHDynamo installs on an optimizer's.grad, aCOW_TENSOR_MATCH, or aTYPE_MATCHon a tensor attribute holds a tensor whose shape and dtype it never checks, and rendering them would split identical guards._fact_orderis the sort key for facts, and it includes the value because once boilerplate code parts are filtered aTENSOR_MATCHrenders no code, so two shape specializations would otherwise tie and sort unstably. The docstring records the KNOWN GAP that underdynamic=Truethe concrete shape here is narrower than the guard, so a shape-genericTENSOR_MATCHreads as varying rather than invariant.What each guard type contributes
A tensor whose guard part cannot be rendered (a
__torch_function__subclass that refuses attribute reads) falls back totype=..., <unrenderable>rather than raising out of a lint, and a hooks read that fails rendershooks=<unreadable>, distinct from the""that means no discriminator is needed.test_value_fingerprint_dispatches_on_the_guard_typepins that five tensors differing in dtype, shape,Parameter-ness and inference mode render five distinctcheck_tensor(<value>, ...)strings, thatNOT_NONE_MATCH,TYPE_MATCHandCOW_TENSOR_MATCHon the same tensor render"", theGRAD_MODE, identity and unrenderable-subclass renderings, and that_fact_orderorders by value.test_saved_hooks_fingerprint_mirrors_what_the_guard_storespinshooks=Nonefor both no hooks and plain-Python hooks and the per-graph digest forGraphModulehooks.Test Plan:
Authored with an AI assistant.
🤖 Generated with Claude Code
Co-Authored-By: Claude Fable 5.1 [email protected]
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98