Repository navigation
[precompile] Report the value-pinned sources no captured variant will generalize - #197272
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 14:02
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
… generalize (#197272) (#197974) **Summary.** A non-tensor argument, and any value that crosses a graph break, is guarded by equality, so an int, bool or str argument yields an artifact that only serves calls reproducing that exact value; `PrecompileSummary.wont_generalize` is where a capture reports those, and this commit adds the two functions that compute it. `_pins_a_value(guard_type, name)` is true for a value-equality guard on a BARE name (a plain local, or the `___stackN` Dynamo gives a value crossing a break), and never for the empty source of a guard checked against no source. The value-equality guards are `CONSTANT_MATCH` (the front door, which delegates a bool to `BOOL_MATCH`, None to `NONE_MATCH`, a code object to `ID_MATCH` and everything else, ints included, to `EQUALS_MATCH`, and is the only guard method that derives into another one of these, so the slot's top-level type is enough), `EQUALS_MATCH`, `CONSTANT_SUBCLASS_MATCH` (the base value of an int/float/str subclass argument) and the two iterator guards `RANGE_ITERATOR_MATCH` and `COUNT_ITERATOR_MATCH`, which pin an iterator argument's exact position; length and key-set guards pin a container's structure rather than a value and are deliberately not counted; the set keys on guard type alone, so an `EQUALS_MATCH` installed on a container argument itself (a `dict_keys` or a frozenset of torch ops) is counted, its contents being the value the artifact then serves only for. A dotted or subscripted source such as `self.eps` or `G['CFG'].width` is reached through an argument rather than being one, which is where model config lives, and every `LayerNorm` contributes a `CONSTANT_MATCH` there, so counting those would flag every model. `_wont_generalize(kept, guard_sets)` starts from the pinned kept slots and keeps a source only if SOME frame pins it in a variant and no variant of that frame reaches it without pinning (a fact whose guard the filter dropped, `enforced` False, checks nothing and counts as a generic mention, not a pin, the drop itself being what `dropped_guards` reports; a variant's OWN companion guards on a source it pins, the `SEQUENCE_LENGTH` beside a `dict_keys` `EQUALS_MATCH`, are not a generic mention); a frame whose variants both pin a source and guard it generically cancels its own pin and nobody else's, because a source pinned in one variant is not pinned for the artifact: once two examples are captured the ordinary shape is one variant guarding `scale` by equality and another guarding it generically, and the second serves new values fine. Cancellation is per frame, like every comparison in this module, because a bare name means nothing across frames and `___stack0` names whatever crossed the break in EVERY resume frame -- a tensor in one, an `.item()` int in the next -- so a generic mention elsewhere must not erase a real pin. `GuardFact.source` and a kept slot's name share one spelling, the `GuardFilterEntry.name` with local scope stripped. The KNOWN GAPs are a constant inside a container argument, guarded on a subscripted source like `dims[0]` and therefore not counted, and the unspecialized int whose variant carries only a `TYPE_MATCH` on the name: if the trace then specializes the symbol, the `L['scale'] == 3` check is a `SHAPE_ENV` fact with an empty source, so the variant looks generic and cancels a sibling's pin that nothing serves. `test_wont_generalize_cancels_pins_only_within_a_frame` pins the predicate on both kinds of source, the in-frame cancellation, the cross-frame `___stack0` case, that a frame pinning `scale` in its only variant stays reported when the entry frame cancels its own `scale` pin, that a variant whose value guard was dropped cancels its sibling's pin, that a variant holding `EQUALS_MATCH` and `SEQUENCE_LENGTH` on one source keeps its pin (removing the per-variant `- here` subtraction fails it), that a pin with no kept slot is not reported, the empty source and both iterator types, and that every value-equality type is in the never-dropped shape-bearing set. ## Examples ```python from torch._dynamo.precompile_package import _pins_a_value, _wont_generalize _pins_a_value("EQUALS_MATCH", "scale") # True _pins_a_value("CONSTANT_MATCH", "___stack0") # True: a value that crossed a graph break _pins_a_value("CONSTANT_SUBCLASS_MATCH", "n") # True: an int-subclass argument _pins_a_value("CONSTANT_MATCH", "self.eps") # False: reached through self _pins_a_value("EQUALS_MATCH", "dims[0]") # False: subscripted (the known gap) _pins_a_value("TENSOR_MATCH", "x") # False: not a value-equality guard _pins_a_value("EQUALS_MATCH", "") # False: a guard checked against no source kept = {("EQUALS_MATCH", "scale"), ("EQUALS_MATCH", "mode"), ("CONSTANT_MATCH", "___stack0")} # entry frame: one variant pins scale and mode, another guards scale by TYPE_MATCH only; # one resume frame has ___stack0 as a tensor, another has it as the .item() int _wont_generalize(kept, guard_sets) # ("___stack0", "mode"): scale is served generically # by the entry's second variant; the tensor ___stack0 # in a different frame does not cancel the int one ``` Test Plan: ``` python test/dynamo/test_precompile_package.py -k test_wont_generalize_cancels_pins_only_within_a_frame 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 31e7603 as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197974 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973
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. A non-tensor argument, and any value that crosses a graph break, is guarded by equality, so an int, bool or str argument yields an artifact that only serves calls reproducing that exact value;
PrecompileSummary.wont_generalizeis where a capture reports those, and this commit adds the two functions that compute it._pins_a_value(guard_type, name)is true for a value-equality guard on a BARE name (a plain local, or the___stackNDynamo gives a value crossing a break), and never for the empty source of a guard checked against no source. The value-equality guards areCONSTANT_MATCH(the front door, which delegates a bool toBOOL_MATCH, None toNONE_MATCH, a code object toID_MATCHand everything else, ints included, toEQUALS_MATCH, and is the only guard method that derives into another one of these, so the slot's top-level type is enough),EQUALS_MATCH,CONSTANT_SUBCLASS_MATCH(the base value of an int/float/str subclass argument) and the two iterator guardsRANGE_ITERATOR_MATCHandCOUNT_ITERATOR_MATCH, which pin an iterator argument's exact position; length and key-set guards pin a container's structure rather than a value and are deliberately not counted; the set keys on guard type alone, so anEQUALS_MATCHinstalled on a container argument itself (adict_keysor a frozenset of torch ops) is counted, its contents being the value the artifact then serves only for. A dotted or subscripted source such asself.epsorG['CFG'].widthis reached through an argument rather than being one, which is where model config lives, and everyLayerNormcontributes aCONSTANT_MATCHthere, so counting those would flag every model._wont_generalize(kept, guard_sets)starts from the pinned kept slots and keeps a source only if SOME frame pins it in a variant and no variant of that frame reaches it without pinning (a fact whose guard the filter dropped,enforcedFalse, checks nothing and counts as a generic mention, not a pin, the drop itself being whatdropped_guardsreports; a variant's OWN companion guards on a source it pins, theSEQUENCE_LENGTHbeside adict_keysEQUALS_MATCH, are not a generic mention); a frame whose variants both pin a source and guard it generically cancels its own pin and nobody else's, because a source pinned in one variant is not pinned for the artifact: once two examples are captured the ordinary shape is one variant guardingscaleby equality and another guarding it generically, and the second serves new values fine. Cancellation is per frame, like every comparison in this module, because a bare name means nothing across frames and___stack0names whatever crossed the break in EVERY resume frame -- a tensor in one, an.item()int in the next -- so a generic mention elsewhere must not erase a real pin.GuardFact.sourceand a kept slot's name share one spelling, theGuardFilterEntry.namewith local scope stripped. The KNOWN GAPs are a constant inside a container argument, guarded on a subscripted source likedims[0]and therefore not counted, and the unspecialized int whose variant carries only aTYPE_MATCHon the name: if the trace then specializes the symbol, theL['scale'] == 3check is aSHAPE_ENVfact with an empty source, so the variant looks generic and cancels a sibling's pin that nothing serves.test_wont_generalize_cancels_pins_only_within_a_framepins the predicate on both kinds of source, the in-frame cancellation, the cross-frame___stack0case, that a frame pinningscalein its only variant stays reported when the entry frame cancels its ownscalepin, that a variant whose value guard was dropped cancels its sibling's pin, that a variant holdingEQUALS_MATCHandSEQUENCE_LENGTHon one source keeps its pin (removing the per-variant- heresubtraction fails it), that a pin with no kept slot is not reported, the empty source and both iterator types, and that every value-equality type is in the never-dropped shape-bearing set.Examples
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