Repository navigation
[precompile] Add _varying_guard_slots and the PrecompileSummary builder - #197273
Closed
bobrenjc93 wants to merge 29 commits into
Closed
bobrenjc93 wants to merge 29 commits into
bobrenjc93 wants to merge 29 commits into
Conversation
[ghstack-poisoned]
This was referenced Sep 16, 2026
Closed
Closed
pytorchgreenlight
Bot
dismissed
their stale review
September 21, 2026 13:42
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
…er (#197273) (#197975) **Summary.** `_varying_guard_slots(guard_sets)` finds the guard slots that actually discriminate between the captured variants of a frame, which is what licenses a policy to leave every other slot out of the serialized copy. A slot is `(guard_type, source)`, the source as `GuardFact.source` spells it (the `GuardFilterEntry.name` with local scope stripped, `L['x']` -> `x`), and it varies in two cases: two variants of one frame recorded DIFFERENT facts for it, or it is present in some variants and absent in others, because a guard only one variant carries is what tells that variant apart and comparing values alone would call it invariant and drop it; the present-in-some case is the majority of what is kept, not an edge. A fact is the guard's rendered code and value; `GuardFact.enforced` says whether the serialized copy keeps the guard, not what it checks, so it is deliberately not part of the comparison. One variant can hold several facts on one slot (Dynamo installs a `HASATTR` per attribute name on the parent source, and `DICT_CONTAINS`/`SET_CONTAINS` a guard per key on the container), so the comparison is between each variant's set of facts for the slot, never between two facts inside one variant. Guards from different frames are never compared, since an entry frame guards its arguments while a resume frame guards whatever crossed the break, so the loop runs per frame key. `_summarize` assembles a `PrecompileSummary` from a `_DynamoCacheEntry` (frame, resume-function, guarded-code and backend-graph counts, and the bypassed and uncovered code names, one bare `co_name` per frame: uncovered is the frame that entered Dynamo, holds no guarded code and was not bypassed (`install()` `skip_code()`s a superset, every entry that is not bypassed and has no guarded codes whether or not it entered Dynamo, so a generated-but-never-executed resume entry is skipped there but is not a gap here), so a repeated `forward` is two frames and both lists are subsets of the frame count by construction; `backend_graphs` counts the backend ids of the entries that are not bypassed, the ones `install()` loads, because a save-time bypass in `PrecompileCacheEntry.from_cache_entry` marks the entry and leaves its ids in place) plus the dropped, kept, policy-dropped and risky slot sets, the truncated frame names (the compile path records those as `co_name (filename:firstlineno)`, once per code object, so that set cannot merge two frames), the capture errors, and the rendered check for each dropped slot that has one (`dropped_code`, one rendering per slot, the caller's pick among the variants that dropped it, which is what `PrecompileSummary.dropped_guard_code` documents; a slot without one gets no entry), computing `wont_generalize` on the way. Its slot-set parameters are keyword-only: four of them share one type, and a transposed `dropped`/`kept` pair would swap what the report calls dropped and kept with nothing to catch it (`PrecompileSummary` states its slot relations and checks none of them: the slots aggregate every frame and a slot names no frame, so a slot one frame's filter rejected and another frame's policy dropped is legitimately in both sets; the `dropped_guard_code` union is `dropped | policy_dropped`, which lists such a slot once, and does not name `risky` because a risky slot is a dropped slot). Both are private, like every other helper in the module that is not a filter a caller passes to CompilePackage; the session that consumes them is a later stack. ## Two variants of one frame ```python from torch.compiler._precompile_types import GuardFact from torch._dynamo.precompile_package import _varying_guard_slots x_f32 = GuardFact("TENSOR_MATCH", "x", (), "dtype=torch.float32, size=[4, 8]", True) x_f16 = GuardFact("TENSOR_MATCH", "x", (), "dtype=torch.float16, size=[4, 8]", True) flag = GuardFact("CONSTANT_MATCH", "flag", ("L['flag'] == True",), "", True) fn_id = GuardFact("ID_MATCH", "G['fn']", (), "is @m.py:3#abc mod.fn", False) has_w = GuardFact("HASATTR", "mod", ("hasattr(L['mod'], 'weight')",), "", True) has_b = GuardFact("HASATTR", "mod", ("hasattr(L['mod'], 'bias')",), "", True) guard_sets = {("forward", "m.py", 12): [frozenset({x_f32, fn_id, has_w, has_b}), frozenset({x_f16, flag, fn_id, has_w, has_b})]} _varying_guard_slots(guard_sets) # frozenset({("TENSOR_MATCH", "x"), # different facts in the two variants # ("CONSTANT_MATCH", "flag")}) # present in only one variant # ("ID_MATCH", "G['fn']") is NOT varying: identical in both, so a policy may drop it # ("HASATTR", "mod") is NOT varying either: two facts on one slot, the same set in both variants ``` Test Plan: ``` python test/dynamo/test_precompile_package.py TestPrecompilePackage.test_varying_guard_slots_are_the_differing_and_present_in_some_ones python test/dynamo/test_precompile_package.py TestPrecompilePackage.test_summarize_reads_the_frame_lists_off_the_entry 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 1150b36 as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197975 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974
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.
_varying_guard_slots(guard_sets)finds the guard slots that actually discriminate between the captured variants of a frame, which is what licenses a policy to leave every other slot out of the serialized copy. A slot is(guard_type, source), the source asGuardFact.sourcespells it (theGuardFilterEntry.namewith local scope stripped,L['x']->x), and it varies in two cases: two variants of one frame recorded DIFFERENT facts for it, or it is present in some variants and absent in others, because a guard only one variant carries is what tells that variant apart and comparing values alone would call it invariant and drop it; the present-in-some case is the majority of what is kept, not an edge. A fact is the guard's rendered code and value;GuardFact.enforcedsays whether the serialized copy keeps the guard, not what it checks, so it is deliberately not part of the comparison. One variant can hold several facts on one slot (Dynamo installs aHASATTRper attribute name on the parent source, andDICT_CONTAINS/SET_CONTAINSa guard per key on the container), so the comparison is between each variant's set of facts for the slot, never between two facts inside one variant. Guards from different frames are never compared, since an entry frame guards its arguments while a resume frame guards whatever crossed the break, so the loop runs per frame key._summarizeassembles aPrecompileSummaryfrom a_DynamoCacheEntry(frame, resume-function, guarded-code and backend-graph counts, and the bypassed and uncovered code names, one bareco_nameper frame: uncovered is the frame that entered Dynamo, holds no guarded code and was not bypassed (install()skip_code()s a superset, every entry that is not bypassed and has no guarded codes whether or not it entered Dynamo, so a generated-but-never-executed resume entry is skipped there but is not a gap here), so a repeatedforwardis two frames and both lists are subsets of the frame count by construction;backend_graphscounts the backend ids of the entries that are not bypassed, the onesinstall()loads, because a save-time bypass inPrecompileCacheEntry.from_cache_entrymarks the entry and leaves its ids in place) plus the dropped, kept, policy-dropped and risky slot sets, the truncated frame names (the compile path records those asco_name (filename:firstlineno), once per code object, so that set cannot merge two frames), the capture errors, and the rendered check for each dropped slot that has one (dropped_code, one rendering per slot, the caller's pick among the variants that dropped it, which is whatPrecompileSummary.dropped_guard_codedocuments; a slot without one gets no entry), computingwont_generalizeon the way. Its slot-set parameters are keyword-only: four of them share one type, and a transposeddropped/keptpair would swap what the report calls dropped and kept with nothing to catch it (PrecompileSummarystates its slot relations and checks none of them: the slots aggregate every frame and a slot names no frame, so a slot one frame's filter rejected and another frame's policy dropped is legitimately in both sets; thedropped_guard_codeunion isdropped | policy_dropped, which lists such a slot once, and does not nameriskybecause a risky slot is a dropped slot). Both are private, like every other helper in the module that is not a filter a caller passes to CompilePackage; the session that consumes them is a later stack.Two variants of one frame
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