Repository navigation
[precompile] Classify the guard types that are never dropped and never compared (#197267) - #197968
Closed
bobrenjc93 wants to merge 1 commit into
Closed
bobrenjc93 wants to merge 1 commit into
bobrenjc93 wants to merge 1 commit into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/197968
Note: Links to docs will display an error until the docs builds have been completed. ⏳ 57 Pending, 2 Unrelated FailuresAs of commit 872ddac with merge base d78bbf2 ( 🟢 GREEN LIGHT - PR approved to be merged without human review:
reason: UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This was referenced Sep 21, 2026
Closed
Closed
Closed
Collaborator
|
Starting merge as part of PR stack under #197981 |
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
… totality test (#197268) (#197969) **Summary.** With the shape-bearing and unmodelled sets in place, this commit adds the other two and the test that makes the classification enforceable. `_IDENTITY_GUARD_TYPES` freezes `CheckFunctionManager.UNSUPPORTED_SERIALIZATION_GUARD_TYPES`, both for the fingerprinting code that follows and as the base of `_INVARIANT_DROPPABLE_GUARD_TYPES`, the ONLY guard types an invariance policy may drop, and only when proven invariant across every captured variant: the identity guards the default filter drops anyway as unserializable, derived from that same set so the two cannot disagree, plus `BUILTIN_MATCH`, an identity match the default filter keeps; the ambient-state guards (`DEFAULT_DEVICE`, `FUNCTORCH_STACK_MATCH`, `DUAL_LEVEL`, `AUTOGRAD_SAVED_TENSORS_HOOKS`) are unmodelled per the previous commit, so nothing outside identity is droppable. `_NOOP_GUARD_TYPES` (`DETERMINISTIC_ALGORITHMS`, `GRAD_MODE`) are markers whose `GuardBuilder` method is `pass` and whose check is made by `GLOBAL_STATE`'s leaf, so nothing about them is ever serialized or dropped, and `_is_noop_guard_type` adds `EMPTY_NN_MODULE_HOOKS_DICT` under the default `skip_nnmodule_hook_guards`, where the builder emits nothing for it; with the skip off it emits a real `SEQUENCE_LENGTH`, which is why the previous commit classified it shape-bearing rather than droppable. `test_guard_policy_classification_is_total` enumerates every uppercase callable on `GuardBuilder` (through `dir`, so a method added on `GuardBuilderBase` or a mixin counts) and asserts the four sets cover all of them, contain nothing else, are pairwise disjoint, and that the identity set is inside the droppable one, so a guard type added to Dynamo fails this test until someone triages it and is KEPT unconditionally until then. Guards installed outside `GuardBuilder` -- the root manager's `DuplicateInputs` and `StorageOverlap` exprs and the dimension-marking lambda -- never reach the guard filter and are outside the policy as well. `test_noop_guard_type_follows_the_hook_guard_config` pins the config-dependent answer. ## The test ```python guard_types = {name for name in dir(GuardBuilder) if name.isupper() and callable(getattr(GuardBuilder, name))} sets = { "_SHAPE_BEARING_GUARD_TYPES": _SHAPE_BEARING_GUARD_TYPES, "_UNMODELLED_GUARD_TYPES": _UNMODELLED_GUARD_TYPES, "_INVARIANT_DROPPABLE_GUARD_TYPES": _INVARIANT_DROPPABLE_GUARD_TYPES, "_NOOP_GUARD_TYPES": _NOOP_GUARD_TYPES, } classified = frozenset().union(*sets.values()) assert guard_types - classified == set() # "unclassified GuardBuilder guard type(s): add each to exactly one policy set" assert classified - guard_types == set() # "phantom entries: no GuardBuilder method by these names" for (a_name, a), (b_name, b) in itertools.combinations(sets.items(), 2): assert not (a & b) assert _IDENTITY_GUARD_TYPES <= _INVARIANT_DROPPABLE_GUARD_TYPES ``` ```python _is_noop_guard_type("GRAD_MODE") # True _is_noop_guard_type("EMPTY_NN_MODULE_HOOKS_DICT") # True under the default config, False under # torch._dynamo.config.patch(skip_nnmodule_hook_guards=False) ``` Test Plan: ``` python test/dynamo/test_precompile_package.py -k test_guard_policy_classification_is_total python test/dynamo/test_precompile_package.py -k test_noop_guard_type_follows_the_hook_guard_config 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 ca5b700 as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197969 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
…ered guard code (#197269) (#197970) **Summary.** The invariants report a later commit writes is meant to be committed to a repository and diffed across runs, so anything in a rendered guard that differs run to run has to be scrubbed first. `_normalize` replaces the object address in `___check_obj_id(..., 140311678493200), type=` renderings, the `(id, id)` tuple in `top_saved_tensors_hooks ids == (...)`, the per-process counter Dynamo appends to the builtins dict it installs (`__builtins_dict___6`), and the `_<id>_c<n>` suffix `OutputGraph.install_global_by_id` bakes into an identifier, where neither of the other patterns can see it (transformers' Qwen2 installs three such globals; torch itself is installed under an empty prefix as `_<id>_c<n>`). Those are exactly the three minted families `aot_compile._MINTED_GLOBAL_PREFIXES` names as able to root a serializable guard; `__compiled_fn_*` and `__resume_at_*` are codegen-only `LOAD_GLOBAL` targets and are deliberately not matched, since a pattern for them would have to guess at a shape (`__resume_at_<offset>_<counter>`, `__compiled_fn_<n>_<uuid>`) no guard ever renders. Each pattern is anchored to the call shape that carries the address, because a bare `\b\d{9,}\b` also eats a user constant such as a dict key or slice bound, and two variants guarding different values would then render the same fact and invent an invariant neither holds; for the `install_global_by_id` shape the digit width is that anchor, since the prefix can be empty and `w_1_c2` is a plausible user identifier. `_render_code` applies the normalization to every part of a guard's `code_list`, and `_hash_text` is the 12-hex-digit sha256 prefix the fingerprints that follow use. `test_normalize_scrubs_addresses_and_counters_but_not_user_constants` is a table over both directions: everything run-varying is erased, and nothing meaningful is. ## Before and after ```python from torch._dynamo.precompile_package import _normalize _normalize("___check_obj_id(G['fn'], 140311678493200), type=<class 'function'>") # "___check_obj_id(G['fn'], <id>), type=<class 'function'>" _normalize("G['__builtins_dict___6']['len']") # "G['__builtins_dict___<n>']['len']" _normalize("G['__import_mod_140311678493200_c1']") # "G['__import_mod_<id>_c<n>']" _normalize("G['_140311678493200_c3'] is not None") # "G['_<id>_c<n>'] is not None" _normalize("top_saved_tensors_hooks ids == (139, 140)") # "top_saved_tensors_hooks ids == (<ids>)" _normalize("L['dims'][0] == 140311678493200") # unchanged: a bare number is a user constant, not an address _normalize("L['w_1_c2'] == 3") # unchanged: a short counter-looking identifier is the user's ``` Test Plan: ``` python test/dynamo/test_precompile_package.py -k test_normalize_scrubs_addresses_and_counters_but_not_user_constants 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 73422e9 as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197970 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
…e guard report (#197270) (#197971) **Summary.** `_normalize` strips the address an identity guard renders, so the report needs another stable name for the object it guarded, or two variants holding different callables at one source collapse into one fact and are reported as an invariant neither holds. `_object_identity(value)` names a module by `__name__`, and a callable by where it is DEFINED plus a digest of its body: `is @<basename>:<firstlineno>#<fingerprint> <module>.<qualname>`, truncated to 160 characters with the discriminating part FIRST, because a qualname alone can exceed the limit on a transformers lambda nested in a long module path, and a digest appended at the end would be cut off exactly where it is needed. The digest comes from `_code_fingerprint`, a sha256 prefix over `co_code`, `co_names`, `co_varnames`, `co_freevars`, `co_cellvars` and the stable constants, which is what tells apart an `ACT2FN`-style table whose lambdas are all written on one source line and so agree on file AND lineno. `_stable_consts` reduces `co_consts` to what reprs the same in every process, recursing into tuples, frozensets (sorted by repr) and nested code objects instead of dropping them, because two lambdas that differ only in `x * (1, 2)` versus `x * (1, 3)`, or only inside an inner lambda, are genuinely different variants and dropping the container is what let them collide. A const of any other type keeps its SLOT as a type marker for the same reason: `x[..., 0]` and `x[0, ...]` fold to one const tuple at the same index, so dropping the unrecognized `Ellipsis` merged them (Ellipsis and NotImplemented repr by name and are kept by value). Only the code object is named, not the data bound to it, and the docstring says so: two closures from one factory, two functions differing only in `__defaults__`, bound methods of two instances and every `functools.partial` render the same. The digest is stable across processes but not across Python versions, since `co_code` is version-specific bytecode. ## The collision the test pins ```python from torch._dynamo.precompile_package import _code_fingerprint, _object_identity left, right = (lambda x: x * (1, 2)), (lambda x: x * (1, 3)) left.__code__.co_code == right.__code__.co_code # True: only co_consts differ _code_fingerprint(left.__code__) == _code_fingerprint(right.__code__) # False # same for a frozenset constant, a nested code object, and an Ellipsis subscript: (lambda x: x in {1, 2}), (lambda x: x in {1, 3}) (lambda x: (lambda y: y + 1)), (lambda x: (lambda y: y + 2)) (lambda x: x[..., 0]), (lambda x: x[0, ...]) _object_identity(torch.nn.functional) # "is module torch.nn.functional" _object_identity(left) # "is @test_x.py:12#3f9a... __main__.<lambda>" _object_identity(object()) # "is a builtins.object" ``` `test_code_fingerprint_recurses_into_container_and_nested_consts` asserts, for each of the four pairs, that `co_code` agrees and the fingerprints differ, that an unrenderable const keeps its slot, and that the same source compiled twice agrees. `test_code_fingerprint_is_stable_across_processes` checks the digest of a fixed snippet against a fresh interpreter, which is the only thing that holds the "committed and diffed" line. `test_object_identity_puts_the_digest_before_the_truncation_point` pins the module and fallback renderings and that, on a qualname longer than the bound, the site and digest survive the cut. Test Plan: ``` python test/dynamo/test_precompile_package.py -k test_code_fingerprint_recurses_into_container_and_nested_consts python test/dynamo/test_precompile_package.py -k test_code_fingerprint_is_stable_across_processes python test/dynamo/test_precompile_package.py -k test_object_identity_puts_the_digest_before_the_truncation_point 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 e4639d6 as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197971 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
…ization dropped (#197266) (#197972) **Summary.** Serialization drops every identity guard, so precompiling gives up on noticing that a guarded object was rebound; `_is_risky_drop(entry, namespaces)` is the lint that says which of those drops can plausibly change results on a capture-here / serve-there deployment, where the concern is DIVERGENCE: the serving machine runs the same source but a config, flag or environment variable picks a different object. It intersects the binding SITE with who owns the value, because either test alone is wrong: `self.act = getattr(F, cfg.activation)` and `self.act = cfg.act_fn` are the same swappable slot, so calling the first benign because `F.gelu` is torch-owned waves through capture-gelu-serve-silu, while `if flag: import impl_b as impl` then `impl.op` is a read off a module namespace exactly like `F.gelu` but the module is user code an env var chose. Three bindings are waived: a builtin read the ordinary way, an attribute read off a trusted namespace that torch or the stdlib owns or that owns a def of that same name, and a global bound to a def of the same name when torch or the stdlib owns the def or it lives in the file doing the reading; instance attributes, closure cells, aliased imports, cross-module `from x import op`, registry lookups, reads off a config module and an entry whose value could not be read are all risky. The docstring records the KNOWN GAP: every waiver judges the object capture happened to bind, not the statement that bound it, so a name bound conditionally is waived whenever the branch taken at capture is a waived shape, a third party that rebinds `F.gelu` at import is waived, and so is an alias config picks between two torch modules. `dropped_guards` stays the authoritative list; this is a lint over it, not a proof. `test_risky_drop_decision_table` pins every shape found so far on hand-built entries. One shape's source spelling is Dynamo's own: under `nested_graph_breaks=True` a callee's `act = pick()` crosses the break as `L['__nested_frame_values'][0][k]` rather than `L['act']`, and `test_risky_drop_sees_the_slot_behind_a_nested_resume` drives that layout and the flat one through a real compile, so the slot is flagged and the def read inside `pick()` waived either way. The capture-session corpus that drives real compiles through the same predicate belongs to a later stack. ## The decision, in order ```python def _is_risky_drop(entry, namespaces): source, value = entry.orig_guard.originating_source, entry.value if _is_dynamo_synthesized(source): return False # Dynamo's own generated resume functions if source.name in namespaces: return False # the guard IS on a trusted module if _reads_a_builtin(source, value): return False # len, sorted via __builtins_dict__ if not entry.has_value: return True # nothing to judge ownership by if isinstance(source, AttrSource): ns = namespaces.get(source.base.name) if ns is not None: # F.gelu, own_helpers.call ... return not (_is_library_module(ns.__name__) or (_owning_module(value) == ns.__name__ and value.__name__ == source.member)) if isinstance(source, GlobalSource) and getattr(value, "__name__", None) == source.global_name: return not (_is_library_module(_owning_module(value)) # from torch.nn.functional import silu or _defined_where_read(value, source.global_name, entry.orig_guard.user_stack)) # def in this file return True ``` ```python F.gelu(x) # waived: torch owns torch.nn.functional own_helpers.call(x) # waived: own_helpers owns a def named call own_helpers.act(x) # RISKY: act is bound to some other def, i.e. a slot cpkg.op(x) # RISKY: re-exported from cpkg.impl_b, chosen by an import elsewhere self.act(x) # RISKY: an instance attribute is a slot impl.op(x) # import impl_b as impl RISKY: the alias is the slot config.attn_impl(x) # RISKY: a config module is never a trusted namespace ``` Test Plan: ``` python test/dynamo/test_precompile_package.py -k test_risky_drop 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 e0ba7af as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197972 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971
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
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
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
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
…e runs under (#197274) (#197976) **Summary.** A multi-graph capture needs three configuration changes for as long as one of the caller's calls runs, and `_capture_config(training)` is the context manager that applies them. It patches `torch._functorch.config` with `bundled_autograd_cache=True`, so backends serialize into the artifact rather than the process-local inductor cache, and `bypass_autograd_cache_key=True`, because `AOTAutogradCache` refuses to KEY a graph that calls anything outside its allowlist and a refusal means it never saves, leaving the capture with nothing to serialize; a precompile artifact is addressed by backend id and pinned to one torch build, so a nonce key is fine, as `torch._dynamo.aot_compile` already does. With `training=True` it also sets `force_non_lazy_backward_lowering`, since AOTAutograd otherwise defers the backward to the first `.backward()` and a training capture that never makes one would record no backend. Under `torch._dynamo.config.strict_precompile` it sets `strict_autograd_cache` too: `AOTAutogradCache.try_load` honours `strict_precompile`, but the save side only checks `strict_autograd_cache`, so without it a bundled entry that fails to pickle is dropped with a warning and the capture is short one backend, which only surfaces as a missing backend when the artifact is written. It patches `torch._dynamo.config.allow_empty_graphs=True` so an empty graph still counts as a compiled frame whose guards reach the artifact; the docstring records that this also extends the lifetime of objects the frame holds (see `ReproTests.test_weakref_callback`). Entering with `torch.compiler.config.force_disable_caches` set raises `PackageError` up front: compiled backends reach the artifact through the AOTAutograd cache path, which that setting turns off, so the capture would record no graphs and only fail at write time, as missing backends. This mirrors the check `torch.compile(...).aot_compile` already makes. ## Nesting `ConfigModule.patch` is re-entrant and per-thread (each patch keeps its saved values on a `ContextVar` stack), so every scope simply patches and restores for itself: nested scopes unwind in order, an inner `training=True` lowers the backward while it is open even inside a `training=False` scope, and a worker thread entering the scope patches only itself. ```python from torch._dynamo.precompile_package import _capture_config with _capture_config(training=False): # patches applied with _capture_config(training=True): # force_non_lazy_backward_lowering on ... ... # back to the outer scope's values # everything restored, even if the body raised ``` Test Plan: ``` python test/dynamo/test_precompile_package.py TestPrecompilePackage.test_capture_config_is_scoped_per_entry_and_per_thread TestPrecompilePackage.test_capture_config_refuses_disabled_caches_and_honours_strict 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 743d735 as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197976 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
…h allow_empty_graphs (#197275) (#197977) **Summary.** `_AllowEmptyGraphsConvertFrame` is the `ConvertFrame` subclass a precompile capture will install beneath the `CatchErrorsWrapper` that `torch._dynamo.optimize` builds: it wraps every frame compilation in an `allow_empty_graphs=True` patch and reverts it afterwards. The reason is coverage: an uncovered no-op branch must become a guarded variant rather than Dynamo's ordinary eager-only `SkipFrame`, whose skip applies to the code object, so one fallback call permanently skips that frame and no later call can capture its other variants. `_capture_config` patches the same flag for the duration of the caller's calls, and the converter patches it again so the package's frames get it whenever this converter compiles them, including recompiles of a loaded artifact, which run outside any capture-config scope. It sits beneath `CatchErrorsWrapper` rather than replacing it for two reasons: the wrapper's skipfile, `config.disable` and namedtuple checks reject most intercepted frames before any compile, and patching there would make each of them pay a patch and a revert (and two config-hash invalidations) for nothing; and `log_dynamo_start` builds the `dynamo_start` user stack that tlparse shows by cutting at the first `convert_frame.py` frame, so a subclass frame outside the wrapper would survive as a bogus leaf, while a frame beneath it is cut. The converter passes `skip + 1` down so the traceback arithmetic accounts for its own frame. A frame under `DistributedDataParallel` with `optimize_ddp="ddp_optimizer"` reaches the converter through `CatchErrorsWrapper`'s `_clone_with_backend` hook, which the next commit in this stack overrides; the docstring says so. `_ALLOW_EMPTY_GRAPHS` is built once with `torch._dynamo.config._make_closure_patcher`, because `config.patch()` allocates a class and a `ContextVar` on every call and this runs on every frame Dynamo compiles for a package. The `OptimizeContext` wiring that installs the converter belongs to the capture session and is not part of this stack; nothing constructs the class here except its tests, which install it beneath the wrapper exactly that way and check end to end that a function whose first call traces an empty graph still gets its later variant compiled (a plain `ConvertFrame` compiles nothing after the no-op call) and that the flag is back off afterwards; and that the `finally` revert runs when the wrapped compile raises, with the flag on and `skip` incremented by one for the inner call, so the process-wide `ContextVar` behind `allow_empty_graphs` does not leak and the traceback arithmetic accounts for the converter's frame. ## Shape of the converter ```python class _AllowEmptyGraphsConvertFrame(ConvertFrame): def __call__(self, frame, cache_entry, hooks, frame_state, skip=0): revert = _ALLOW_EMPTY_GRAPHS() # allow_empty_graphs=True for this frame try: return super().__call__(frame, cache_entry, hooks, frame_state, skip=skip + 1) finally: revert() # how a session will use it, replacing the converter torch._dynamo.optimize built: # optimize_ctx.callback._torchdynamo_orig_backend = _AllowEmptyGraphsConvertFrame( # backend, optimize_ctx.callback.hooks, package=package, recompile_limit=recompile_limit # ) ``` Test Plan: ``` python test/dynamo/test_precompile_package.py TestPrecompilePackage.test_allow_empty_graphs_convert_frame_keeps_a_no_op_frame_compilable python test/dynamo/test_precompile_package.py TestPrecompilePackage.test_allow_empty_graphs_convert_frame_reverts_the_flag_when_the_compile_raises 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 5574388 as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197977 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
…onverter is asked to clone (#197721) (#197978) **Summary.** DDP plus a package is not supported, and the converter refuses it by name: `_clone_with_backend` is the hook `CatchErrorsWrapper` calls only for a frame under an active `DistributedDataParallel` module in `optimize_ddp="ddp_optimizer"` mode (the default, `optimize_ddp=True`), and when a package is attached the converter's override returns a callable that raises `PackageError` in place of the clone, naming `torch._dynamo.config.optimize_ddp`, the `"no_optimization"` setting that does work, and the `"python_reducer"` and `"python_reducer_without_compiled_forward"` modes, which bypass DDPOptimizer as well (`CatchErrorsWrapper` takes its DDPOptimizer branch only when `get_optimize_ddp_mode()` is `"ddp_optimizer"`). The raise sits in the returned callable rather than the property getter because `CatchErrorsWrapper` first reads the attribute through `hasattr` as a capability probe and only then calls it; `hasattr` swallows only `AttributeError`, so a getter that raised would raise `PackageError` out of the probe itself, before the wrapper reaches the call it means to make (its own `AssertionError` is reachable only for converters that lack the attribute, which this subclass never does). Without a package the override returns a clone of the same subclass built with the same hooks and recompile limit, so the flag survives a DDP clone the way it survives an ordinary compile; the base clone would have rebuilt a plain `ConvertFrame` and silently dropped the patch, and there is no artifact to protect, so refusing would describe an id the object never records. A package-less converter is what the tests build, and what a capture session may build before it attaches a package. Refusing is the only honest answer: DDPOptimizer splits the Dynamo graph into per-bucket submodules and compiles each one separately, `propagate_metadata` copies only `meta` and `_param_name_to_source` onto them, so no bucket carries the `_backend_id` the outer graph was given and the package's `backend_ids` names an id under which no AOTAutograd artifact is ever recorded; the base `ConvertFrame` clone, which silently drops the package, would have turned that into an uncovered frame, and the previous round's package-preserving clone would have turned it into a save-time `Backend ... is not found` error that never mentions DDP. Construction is not the place for the check, because `optimize_ddp` is `True` by default and the branch also needs an active DDP module, which exists only inside a DDP forward. The other site that rebuilds a plain `ConvertFrame`, `eval_frame._create_wrapped_callback` behind the process-wide `set_stance(backend=...)` and the `eager_then_compile` stances, is deliberately left alone: a stance replaces the whole callback with an unpackaged one and is outside what a capture session promises. The base `ConvertFrame._clone_with_backend`, which the `caching_precompile` callback (`eval_frame._optimize`) still takes under DDP and which drops its package the same silent way, is base code this stack does not touch and is deferred. The DDP rationale lives in a comment on the override; the class docstring keeps two sentences pointing at it. Nothing constructs `_AllowEmptyGraphsConvertFrame` here except its tests, which take the wrapper down its DDPOptimizer branch with a stub active DDP module and check that a converter holding a package still answers the wrapper's `hasattr` probe and refuses the frame with a `PackageError` naming the `DistributedDataParallel` forward and the `optimize_ddp="no_optimization"` remedy under both `True` and `"ddp_optimizer"` while `"no_optimization"` compiles it normally, and that a package-less converter built from a fresh `CompileCounter` and `Hooks` clones to the same subclass with the same hooks and recompile limit. ## Shape of the override ```python class _AllowEmptyGraphsConvertFrame(ConvertFrame): def _clone_with_backend(self): # property; asked for only by CatchErrorsWrapper's DDPOptimizer branch if self._inner_convert._package is None: # no artifact to protect: keep the subclass return lambda backend: type(self)(backend, self._hooks, recompile_limit=self._recompile_limit) def refuse(backend) -> NoReturn: raise PackageError(f"Cannot precompile a DistributedDataParallel forward with torch._dynamo.config.optimize_ddp={...!r}: ... Set torch._dynamo.config.optimize_ddp=\"no_optimization\" ...; the \"python_reducer\" ... modes bypass DDPOptimizer as well") return refuse ``` Test Plan: ``` python test/dynamo/test_precompile_package.py TestPrecompilePackage.test_allow_empty_graphs_convert_frame_refuses_a_ddp_optimizer_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 71397e1 as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197978 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
#197276) (#197979) **Summary.** When a computation needs to guard on a dim the caller marked with `mark_unbacked`, `_capture` catches make_fx's `GuardOnDataDependentSymNode` and raises a `PrecompileError` explaining that an unbacked dim cannot be guarded and how to restructure. That message was built inline inside `_capture`, and the dynamo tracer that later commits add hits the same condition through Dynamo, so the construction moves into `_unbacked_guard_error(e)` and `_capture` raises what it returns. The text is unchanged; the one behavioural difference is that an exception with an empty message no longer trips `str(e).splitlines()[0]` on an empty list, since the helper takes `(str(e).splitlines() or [""])[0]`. The existing unbacked tests in `test/test_precompile.py` cover the path. ## Before and after ```python # parent, inside _capture: except GuardOnDataDependentSymNode as e: raise PrecompileError( "precompile: fn needs to guard on a dim marked with mark_unbacked ..." f"{str(e).splitlines()[0]}" ) from e # now: except GuardOnDataDependentSymNode as e: raise _unbacked_guard_error(e) from e _unbacked_guard_error(RuntimeError("")).args[0].endswith("Underlying: ") # True: no IndexError on an empty message ``` Test Plan: ``` python test/test_precompile.py -k unbacked -k guard_required lintrunner torch/_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]> Reverted in 2b8b6df as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197979 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
…97980) **Summary.** `load` recovers the calling convention of an artifact by parsing `python_code` with `ast` and reading the top-level `NAME = <literal>` assignments, and until now it required one fixed set of names: the make_fx driver's `PARAM_NAMES`, `OUT_SPEC`, `USER_INPUT_SHAPES` and so on. A dynamo-tracer artifact carries a different set, because its multi-graph driver rehydrates frames from opaque blobs rather than reading a parameter list, so the required set is now chosen by the `TRACER` literal: absent (every artifact written before this) or anything but `"dynamo"` keeps the make_fx set unchanged, while `"dynamo"` requires `BACKEND`, `FN_NAME`, `FRAMES`, `DROPPED_GUARDS`, `RISKY_DROPPED_GUARDS`, `WONT_GENERALIZE`, `_FRAMES`, `_BACKENDS`, `_ENTRY_BINDING` and the two versions that lock the blobs to the build that wrote them, `_DYNAMO_PYTHON_VERSION` for the marshalled bytecode and `TORCH_VERSION` for the pickled guard state (the multi-graph driver refuses to unpickle it under another torch build; a make_fx artifact inlines neither, so it needs no such lock), and a `SERVING_MODE == "installed"` artifact swaps `_FRAMES`/`_BACKENDS` for `_PACKAGE` and `UNREACHABLE_WITHOUT_INSTALL`. The parser collects the top-level assignments in one pass, last assignment winning as it would under `exec`, so the literal that selects the required set and the value reported for it are the same assignment. A consumed name whose value is not a Python literal, `TRACER` and `SERVING_MODE` included, raises `PrecompileError` naming the constant instead of a raw `ValueError` (or, for a set or dict literal with an unhashable member, `TypeError`) out of `ast.literal_eval`; an unconsumed top-level assignment is still skipped with a debug log. Four names are parsed when present but never required, so an auditor gets them back as data and older artifacts load unchanged: `TRACER` and `SERVING_MODE`, which select the required set and so would check nothing as members of it (`SERVING_MODE` defaults to `"standalone"` in the result), and the guard-audit sections `POLICY_DROPPED_GUARDS` and `DROPPED_GUARD_CODE`. The emitter of the dynamo set lives further up the stack; this commit lands the reader first so those artifacts load the moment they are produced. ## Before and after ```python from torch._precompile import _parse_artifact_metadata _parse_artifact_metadata('TRACER = "dynamo"\nBACKEND = "eager"\n') # parent: PrecompileError: python_code is missing calling-convention metadata ['BUFFER_NAMES', ...] # (the make_fx names were always required) # now: PrecompileError: python_code is missing calling-convention metadata # ['DROPPED_GUARDS', 'FN_NAME', 'FRAMES', 'RISKY_DROPPED_GUARDS', ...] -- the dynamo set _parse_artifact_metadata("BACKEND = object()\n...") # parent: ValueError: malformed node or string ... (out of ast.literal_eval) # now: PrecompileError: python_code 'BACKEND' calling-convention metadata is malformed; it must be a Python literal. meta = _parse_artifact_metadata(make_fx_python_code) meta["SERVING_MODE"] # "standalone": filled in for artifacts that predate the field ``` `test_parse_artifact_metadata_required_set_follows_tracer` pins the three required sets from hand-written sources (make_fx both with `TRACER` absent and with `TRACER = 'other'`), and `test_parse_artifact_metadata_literals` parses a complete standalone and a complete installed dynamo source and covers the optional sections, the `SERVING_MODE` default, last-assignment-wins and the malformed-literal error on both a call and an unhashable set member. The existing load tests (`test_load_invalid_python_code_rejected`, `test_missing_calling_convention_metadata_rejected`, the export/reload round trips) keep passing. Test Plan: ``` python test/test_precompile.py -k parse_artifact_metadata python test/test_precompile.py lintrunner torch/_precompile.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]> Reverted in bc6503f as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197980 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
) (#197981) **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]> Reverted in 70f4f9b as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197981 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979, #197980
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 22, 2026
…pes (#197982) **Summary.** These are the three public-facing types of the caller-driven precompile API that later commits build on, added here as plain classes in `torch/_precompile.py` with no public export yet. `MakeFxTracer` is a frozen dataclass holding the one make_fx-specific knob, `decompositions`, and is what a caller will pass as `tracer=` to select the single-trace front-end. `PrecompiledRunnable` is the base type `load` will return: a callable with the captured `fn`'s calling convention that can also be entered as a context manager and unloaded, with `installed = False` and no-op `__enter__`/`__exit__`/`unload` for a standalone artifact. `Capture` is the base type the capture entry point will return, whose three methods all raise `NotImplementedError` until a concrete capture fills them in. `PrecompiledModule`, the existing make_fx runnable, now subclasses `PrecompiledRunnable` and forwards keyword arguments from `__call__` to the loaded forward; the make_fx drivers take positional arguments only, so a keyword argument fails there with the usual `TypeError` at the call, and the multi-graph driver will bind them. The three types keep their truthful `__module__` (`torch._precompile`) here: nothing exports them yet, and the commit that makes `torch.compiler.precompile` a module re-homes `MakeFxTracer` and `Capture` under it together with the other re-exports. `MakeFxTracer` has no consumer yet either: the callable API's string `tracer=` and its separate `decompositions=` parameter are retired together with that API later in this stack, where `tracer=MakeFxTracer(...)` takes over. The new `Self` annotation import lives in the `TYPE_CHECKING` block, next to the `Callable`/`Mapping` one the module already had. ```python @dataclasses.dataclass(frozen=True) class MakeFxTracer: decompositions: dict | None = None # forwarded to make_fx as decomposition_table class PrecompiledRunnable: installed: bool = False # True for the installing shape, added later def __call__(self, *args, **kwargs): raise NotImplementedError def __enter__(self): return self def __exit__(self, *exc): self.unload() def unload(self) -> None: ... # no-op: a standalone artifact installed nothing class Capture: def __enter__(self): raise NotImplementedError def __exit__(self, *exc): raise NotImplementedError def __call__(self, *args, **kwargs): raise NotImplementedError class PrecompiledModule(PrecompiledRunnable): # was: class PrecompiledModule: def __call__(self, *args, **kwargs): ... return self._loaded_forward(*args, **kwargs) # was: (*args) ``` ```python f = PrecompiledModule._from_loaded(forward, backend="eager") # what load() builds isinstance(f, PrecompiledRunnable) # True now with f: # enters and exits as a no-op f(model, x) ``` `test_precompiled_module_is_a_standalone_runnable` pins the reparenting: `isinstance`, `installed == False`, the no-op `with`/`unload`, keyword forwarding, and the not-runnable refusal of a bare `PrecompiledModule`. Test Plan: ``` python test/test_precompile.py -k test_precompiled_module_is_a_standalone_runnable python test/test_precompile.py lintrunner torch/_precompile.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: #197982 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979, #197980, #197981
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 22, 2026
… optional (#197983) **Summary.** `_make_inlined_forward(python_code)` is the no-cache path of `load`: it `exec`s the self-contained artifact and hands back its `forward`, logging a warning first because `python_code` is untrusted executable input. It gains a keyword-only `warn=True`. Every `load` keeps warning exactly as before; the one caller that will pass `warn=False` is the capture itself, which in the caller-driven design renders the artifact in-process and immediately self-loads it to run the caller's call -- that source was just produced by this process, is not untrusted input, and warning on every capture would drown the real warning. The comment above the warning says the same: a load is never silent, only the capture-time self-load passes `warn=False`. The `options` dict handed to `compile_to_python` is annotated `dict[str, object]` instead of `dict[str, Any]`; no runtime change. The existing export/reload tests in `test/test_precompile.py` cover the warning path, which is unchanged for them, and `test_inlined_forward_warns_unless_told_not_to` pins both settings directly: one warning per `_make_inlined_forward(code)` and none for `warn=False`. ## Before and after ```python _make_inlined_forward(python_code) # parent and now: warns # WARNING torch.compiler.precompile.load is about to EXEC python_code, which is untrusted # executable input (it runs inlined kernels / graph code). Only exec python_code you produced # or otherwise trust (Note [precompile programming model], invariant 7). _make_inlined_forward(python_code, warn=False) # new: silent, for the capture-time self-load only ``` Test Plan: ``` python test/test_precompile.py -k test_inlined_forward_warns_unless_told_not_to python test/test_precompile.py lintrunner torch/_precompile.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: #197983 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979, #197980, #197981, #197982
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 22, 2026
…frame (#197984) **Summary.** A capture with graph breaks or several guarded variants is not one graph, so its artifact cannot inline a single `call`; it has to carry every frame Dynamo compiled and dispatch among them. `_multigraph_frames(entry)` turns a `_DynamoCacheEntry` into the list of plain dicts the driver rebuilds from, one per code: `is_entry` for `codes[0]`, which is where `CompilePackage` records the captured callable and reads it back from (`main, *codes`), so no name heuristic is involved and neither a bypassed entry nor a same-named submodule frame can move it; `bypassed`, the code's flag; the serialized `code`; its `python_module`; the `import_sources` aliases its bytecode reads; the `resume_names` a continuation is bound under; and one `variants` record per guarded code holding `guards_state` and `dynamo_code`. A bypassed code keeps its record, flagged and without variants, the way `install()` keeps its global binding but none of its guarded codes: the frame ahead of a bypassed continuation still does `LOAD_GLOBAL` on its resume name, so dropping the record would leave a dangling global, and a bypassed code's guarded codes are dead (they name a backend that was missing at save time). `_MULTIGRAPH_GENERATED_HEADER` is the banner of that artifact and `_SERVING_NOTES` the two paragraphs, keyed by serving mode, that say what loading the artifact does to the process (a standalone artifact mutates nothing and refuses uncovered calls; an installed one mutates code objects and compiles fresh on a miss). `_b64` is the base64-of-pickle encoding the opaque sections use. Nothing renders these yet; the source builder that does is part of the capture session. `test_multigraph_frames_record_every_dynamo_frame` in `test/test_precompile.py` builds a real `_DynamoCacheEntry` (bypassed entry, same-named helper, healthy and bypassed continuations) and checks the records. ```python _multigraph_frames(entry) ``` Test Plan: ``` python test/test_precompile.py -k test_multigraph_frames_record_every_dynamo_frame lintrunner torch/_precompile.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: #197984 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979, #197980, #197981, #197982, #197983
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 22, 2026
…dispatch (#197985) **Summary.** A standalone multi-graph artifact dispatches explicitly: the caller invokes the entry frame, and a continuation is reached only because the frame ahead of it does `LOAD_GLOBAL` on the resume name capture minted. A frame Dynamo compiled that is entered by an ordinary Python call -- an inner `nn.Module.__call__` wrapper, an un-inlinable helper -- is reachable only through the frame evaluator, which a source artifact does not use, so it would run eager when served. `_reachable_frames(frames)` computes the set that IS reachable as a worklist fixpoint: start from the entry, and each time a frame becomes reachable add the `co_names` of its variant bytecode (recursing into nested code constants) to the names seen, then admit every frame one of whose `resume_names` is among them. Each frame's bytecode is walked once. Asking merely whether a frame carries a resume name is not the same question, because a continuation whose parent is itself unreachable is just as dead, and counting it as covered under-reports how much of the artifact will run eager. `_serving_mode(frames)` reduces that to the artifact's mode: `"standalone"` when the reachable frames are exactly the frames with variants, `"installed"` otherwise. Either mismatch defeats a source artifact: an unreachable frame with variants would silently give up its compiled variant and run eager, and a reachable frame WITHOUT variants -- a bypassed continuation -- would raise on the very path capture exercised, since a standalone artifact has no compiler behind it. Installing has one, so such captures are served that way. `test_reachable_frames_follow_resume_names` in `test/test_precompile.py` covers the multi-hop chain (one hop through a nested code object), the unreachable helper, a continuation named only by that helper, an unreferenced resume name, and the bypassed-continuation case. ```python frames = [entry, cont_a, cont_b, helper] _reachable_frames(frames) # {0, 1, 2} _serving_mode(frames) # "installed": helper has variants but is unreachable _serving_mode(frames[:3]) # "standalone" _serving_mode([entry, bypassed_cont_a, cont_b]) # "installed": reachable, but nothing to serve ``` Test Plan: ``` python test/test_precompile.py -k test_reachable_frames_follow_resume_names lintrunner torch/_precompile.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: #197985 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979, #197980, #197981, #197982, #197983, #197984
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 22, 2026
… and name the cause (#197986) **Summary.** The multi-graph driver rebuilds the entry function from its code object, and a code object carries no closure: a closure entry cannot be built at all. That is a capture-time fact, so `_reject_uninstallable_entry(frames, entry)` refuses it at capture rather than at load on the serving machine. (Defaults, which a code object does not carry either, are recorded into the artifact by a later commit rather than refused.) It also handles the entry with no dispatchable graph, which has two very different causes that call for different advice. If Dynamo BYPASSED the entry frame -- its guards could not be serialized, or a backend artifact was missing when the package was saved -- the frame record carries the `bypassed` flag `_multigraph_frames` copied from the code, and the error says so and points at where Dynamo logged the reason (the package-bypass warning; the `precompile_cache_bypass` / `dynamo_cache_bypass` artifacts under tlparse), because the thin-wrapper advice would then send the caller restructuring code that was never the problem. If the entry compiled but produced no guarded code, the caller handed precompile a thin wrapper -- an `nn.Module`, or a forward that immediately delegates -- so Dynamo compiled the wrapper's inner frame instead, and the error says to capture the function that calls the model. Only the ENTRY record is consulted, so a bypassed helper or continuation beside a healthy entry refuses nothing, and a capture with no frames at all says nothing rather than guess. `test_no_dispatchable_graph_names_the_cause` in `test/test_precompile.py` builds real `_DynamoCacheEntry` / `_DynamoCodeCacheEntry` values and feeds them through `_multigraph_frames`, so it exercises the records the function actually receives; it walks the bypassed entry, the thin wrapper beside a bypassed helper, the healthy entry beside a bypassed continuation, the empty capture and the closure entry. ## The diagnostics ```python _reject_uninstallable_entry(_multigraph_frames(entry_whose_codes0_is_bypassed), entry) # PrecompileError: precompile captured no dispatchable graph for 'fwd_loss_bwd': the entry # frame was BYPASSED during capture (its guards could not be serialized, or a backend # artifact was missing when the package was saved), so no variant of it can be served. # Dynamo logged the reason: look for the package-bypass warning, or the # precompile_cache_bypass / dynamo_cache_bypass artifacts under tlparse. Fix that rather # than restructuring the captured callable. _reject_uninstallable_entry([{"is_entry": True, "bypassed": False, "variants": [], ...}], entry) # PrecompileError: ... The entry frame produced no guarded code, so the artifact would serve # nothing. This happens when the captured callable is a thin wrapper ... Capture the function # that CALLS the model, e.g. precompile.capture(lambda m, x: m(x), ...) and calling cap(model, x). _reject_uninstallable_entry([healthy_entry, bypassed_continuation], entry) # returns _reject_uninstallable_entry([], entry) # returns _reject_uninstallable_entry([{"is_entry": True, "variants": [v], "code": code_with_freevars, ...}], entry) # PrecompileError: precompile cannot build a self-contained artifact for 'step': it closes over # ['scale'], and this capture has to rebuild the entry from its code object ... ``` Test Plan: ``` python test/test_precompile.py -k test_no_dispatchable_graph_names_the_cause lintrunner torch/_precompile.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: #197986 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979, #197980, #197981, #197982, #197983, #197984, #197985
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 22, 2026
…7987) **Summary.** `_build_multigraph_forward` is the driver a multi-graph artifact inlines: where the single-graph drivers call one `call`, this one rebuilds the captured ENTRY frame from its `_FRAMES` record and returns a `forward` that DISPATCHES among that frame's variants at call time. It is deliberately standalone -- nothing is installed onto the running program's code objects and no frame evaluator is involved -- so an artifact serves exactly what it captured and writes nothing into the captured module but names Dynamo minted while tracing; a call no variant's guards accept RAISES a `PrecompileError` rather than compiling, because there is no compiler behind a source artifact. That error names both ways a call can miss -- a guard on the arguments or on a module global the graph baked in no longer holds (restore the environment), or a call shape capture never exercised (add an example and recapture) -- since only the second is a coverage gap that recapturing fixes. It rebuilds one `GuardManager` per variant through `load_guards_state`/`load_guard_manager`, re-minting the `__builtins_dict___N` key Dynamo guards builtins through (the tracing process had it in its globals; a loading process never traced, and `CompilePackage.install` re-mints it the same way), wraps each variant's transformed bytecode in a `types.FunctionType` over the live globals of the module the frame was compiled in, and dispatches by rebuilding the frame's `f_locals` from the call: the arguments bound with `inspect.Signature` through `torch._dynamo.aot_compile.bind_locals`, so keyword-only parameters, `*args`, `**kwargs` and the entry's recorded defaults land under their names exactly as Python binds them. The first variant whose `manager.check(f_locals)` passes runs; the managers are checked in two passes, as `AOTCompiledModel.__call__` does, because a tag-safe root's no-tensor-aliasing fast path (`GuardManager::check_nopybind`) can refuse without running its tree and disarms itself, so only a second `check` evaluates the tree it skipped. An entry with free variables is refused (capture already refuses one, so its arrival is a malformed artifact, not something to rebuild over empty cells); that refusal and the recorded defaults are gated on the record's `is_entry` flag, so neither reaches a continuation once one is built. Those globals are the LIVE module dict, as `CompilePackage.install` has it, for the rebuilt bytecode and the guards alike: a module-level global the graph baked in as a constant is guarded by EQUALS_MATCH, which the default filter keeps, and only a live dict lets a rebinding after load fail that guard instead of passing against a stale copy, and lets a global the frame writes (side-effect replay emits `STORE_GLOBAL` into the transformed bytecode) land where the module reads it. The driver binds none of its own names there -- not the metadata constants, not `forward` -- only names Dynamo minted while tracing: that module's import aliases, re-imported; its builtins dict key; and the artifact's compiled subgraphs under their backend ids behind `torch._dynamo.disable` (every backend id is seeded into each module the driver opens, where `install` binds a code entry's own ids only; the ids are uuid-suffixed dunders, so no user name is shadowed). The standalone note in `_SERVING_NOTES` is narrowed to match: nothing is installed onto code objects and no frame evaluator is involved, and the only global state loading touches is the captured module, where those minted names are re-seeded and stay. Each is bound the way `install` binds it, `CleanupHook.disown` first so a pre-reset compile's hook cannot delete the binding once its code object is collected, and the builtins key is refused if it is already bound to anything but the module's builtins dict, as `install` refuses it. A module that does not import here -- the defining module or an alias alike -- surfaces as the documented torch-build lock `PrecompileError`, and a frame captured from a script's `__main__` is refused outright, because `importlib.import_module("__main__")` succeeds in every process and would hand the serving script's globals to the guards silently. An entry with no variant -- BYPASSED at capture, or trivial and run eager by Dynamo -- is diagnosed by cause at build rather than as a coverage gap at the call. Before any of that, `_DYNAMO_PYTHON_VERSION` is checked against the running interpreter, because `SerializedCode.to_code_object` feeds the recorded `co_*` fields to `types.CodeType` in the running interpreter's `get_code_keys()` order, so a foreign artifact either raises a bare `TypeError` on a changed field set or builds a code object whose bytecode is foreign and crashes when a variant runs, and `TORCH_VERSION` against `torch.__version__`, because `_FRAMES` carries pickled Dynamo guard state that no other build promises to unpickle and the import check cannot see a build whose modules all still import. Both names, like `_FRAMES`, `_BACKENDS` and `_ENTRY_BINDING`, are read bare: `_parse_artifact_metadata` already refuses a dynamo artifact that lacks them. Only the entry frame is rebuilt here. A graph-break continuation is reached by `LOAD_GLOBAL` on the resume name Dynamo minted, so serving one means binding its dispatcher in the module under that name, with the closure factory a continuation that closes over locals is emitted as, and a zero-variant continuation's refusal deferred to the call that reaches it; that is #197286. Nothing emits this driver into an artifact yet, so no artifact with a graph break exists in between. The function is a single `def` with nested helpers, with its `TYPE_CHECKING` placeholders; keeping it one unit is what lets the source builder emit it with one `inspect.getsource`. ## Dispatch ```python # emitted into the artifact after the metadata and the subgraph sources forward = _build_multigraph_forward() forward(model, x) # f_locals = {"model": model, "x": x, "rest": (), "scale": 2.0} # (Signature.bind + the recorded defaults); the first # variant whose guard manager accepts them runs forward(model, x, scale=3.0) # no variant matches: # PrecompileError: precompile: no captured variant of 'step' matches this call (2 captured). # Either a guard on the call's arguments or on a module global the graph baked in no longer # holds (restore that environment), or this call shape was never captured: the artifact serves # only what capture exercised, so add an example covering it and recapture. ``` ```python # on a different Python # PrecompileError: precompile: this artifact was produced on Python 3.12 and cannot load on 3.13: # it inlines serialized code objects whose bytecode and field layout are Python-version-locked. # Regenerate the artifact under the serving Python. ``` Nothing emits this driver into an artifact yet; the source builder that does is part of the capture session. The test builds the records the driver reads from a real `CompilePackage` capture of a function with no graph break (two calls, the second passing a `*args` tensor: `len(rest)` is a constant in the graph, so the entry recompiles and carries two variants whose outputs differ by one, and dispatch has to pick rather than just run; a keyword-only default the call omits; a module global the entry reads), asserts `_serving_mode` calls it standalone with one frame of two variants, `exec`s the driver's source into a bare namespace with the Dynamo-minted globals scrubbed from the test module, and checks that each captured call dispatches to the variant that produced its answer, that rebinding the module global the entry reads fails its guard and refuses rather than serving the stale graph (and serves again once restored), that an uncovered call refuses, that the builtins key is minted into the captured module and a foreign binding of it is refused, and that every build-time refusal is diagnosed by its own cause: both version locks, a `__main__` frame, an unimportable module, a BYPASSED and a trivial entry, a closure entry, and a record set with no entry. Test Plan: ``` python test/test_precompile.py -k test_multigraph_driver_dispatches_entry_frame python test/test_precompile.py lintrunner --take RUFF,PYFMT,FLAKE8,CODESPELL,PYREFLY 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: #197987 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979, #197980, #197981, #197982, #197983, #197984, #197985, #197986
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 22, 2026
…eal Dynamo backend graph (#197988) **Summary.** This is a follow-up to the `_graph_has_dynamic_shapes` fix that made the probe read `"example_value"` as well as `"val"`: it adds the end-to-end regression test that fix was missing and tightens the surrounding prose. `test_dynamo_dynamic_graph_runs_at_multiple_shapes` compiles a module with `torch.compile(dynamic=True)` through a recording backend, lowers the captured graph with `compile_to_python`, and runs the artifact at three batch sizes; on the parent of the original fix the artifact specialized to the example size and failed `assert_size_stride` at every other size. The helper's docstring and the two unit tests now say precisely which graphs carry which key: make_fx writes only `"val"`, the graph Dynamo hands a torch.compile backend carries only `"example_value"`, and Dynamo's export paths stamp `"val"` as well, so `"val"` alone does not identify a make_fx graph. The unit test also covers the union in the other direction (a symbolic `"val"` beside a static `"example_value"`). The code change is prose only; the behaviour under test is the `_graph_has_dynamic_shapes` change in #197258 (the second commit of this stack), which is kept byte-identical because it is already approved. ## Test Plan ``` python test/functorch/test_compile_to_python.py -k dynamic_graph_runs_at_multiple_shapes python test/functorch/test_compile_to_python.py -k graph_has_dynamic_shapes python test/functorch/test_compile_to_python.py ``` Authored with an AI assistant (Claude Code). Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: #197988 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979, #197980, #197981, #197982, #197983, #197984, #197985, #197986, #197987
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 22, 2026
…iver (#197989) **Summary.** The entry-only `_build_multigraph_forward` from #197743 rebuilds and dispatches the entry frame only; this one makes it rebuild every captured frame from the `_FRAMES` records, so a capture with graph breaks serves standalone. A continuation is reached the way Dynamo emits it -- the frame ahead of it does `LOAD_GLOBAL` on the resume name Dynamo minted in the module both were compiled in (a continuation is recorded under its parent's module; under `config.nested_graph_breaks`, default False, an inlined frame's continuation is recorded under the inlined function's module while the root frame's bytecode does the `LOAD_GLOBAL`) -- so the driver now builds a dispatcher per frame and binds each continuation's dispatcher in that module under its resume names, `CleanupHook.disown` first like the other minted names. A continuation that closes over locals is bound as a FACTORY taking the closure tuple, the way Dynamo emits it and the frame ahead of it calls it, and its `f_locals` are rebuilt the way `AOTCompiledFunction.prepare_f_locals` does: the closure cells' contents first (a cell unbound at the graph break is absent, as it is from a real frame's `f_locals`), then the arguments bound through `bind_locals`, with a comprehension iterator argument that Dynamo spells `.N` in the resume code's `co_varnames` renamed back from the `implicitN` that `inspect.signature` gives it, since the guards are rooted at the bytecode name; the `inspect.Signature` is taken over a throwaway function with empty cells since a code object with free variables cannot be wrapped without them. A module is opened only for a frame with variants: a zero-variant record is dead, never imports its module, and binds its refusal only into a module a live frame already opened (an unopened module means no frame is left to name it), so a dead record naming a module the serving process cannot import neither refuses the load nor binds anything. Resume names are minted by a per-process counter (`unique_id_unbound_in`; backend ids carry a uuid4 and cannot collide), so two standalone artifacts of the same module captured in different processes can mint the same resume name and, loaded into one process, would silently overwrite each other's continuations (the entry bytecode's `LOAD_GLOBAL` cannot be renamed at load); every continuation dispatcher the driver binds under a resume name therefore carries its artifact's tag (the first 16 hex digits of the sha256 of `_FRAMES` and `_BACKENDS` together, so two artifacts emitted from one capture with different backends get different tags) in `__precompile_artifact__` -- the entry dispatcher handed back as `forward` carries nothing -- and, before anything is seeded, a pre-pass over the frames checks every resume name a frame would bind (in a module some frame with variants opens; the check imports the module and seeds nothing): the name must be unbound or hold this artifact's own dispatcher (rebuilding rebinds), otherwise the load is refused with a `PrecompileError` naming the module and the resume name and, for a holder carrying another artifact's tag, both tags and "only one standalone artifact per captured module can serve continuations in a process", or, for an untagged holder, "this process already holds it (a live compile of the same function, or a user binding); load the artifact in a fresh process". There is deliberately no same-continuation permit: a live compile of the same function holds its resume name for entry bytecode Dynamo already emitted, and rebinding it would point that `LOAD_GLOBAL` at a dispatcher that cannot recompile, so the capturing process itself is refused when it loads the artifact it just emitted, and a fresh process serves it. Because the check precedes the dispatcher loop, a refused load mutates nothing in the module; in particular a second artifact of one capture (the same backend ids, other `_BACKENDS`) cannot rebind the live artifact's subgraphs before it is refused. `_seed` itself stays the plain disown-and-overwrite of the previous commit, so the untagged values (import aliases, the builtins dict, the compiled subgraphs) overwrite as before. An artifact with no entry frame is now refused before any module is opened. A load the driver refuses for another reason partway through (a later frame's unimportable alias, a foreign builtins key) leaves the names it had already seeded in the captured module; there is no unwind, and the docstring says so. A frame with no variant -- BYPASSED at capture, or trivial and run eager by Dynamo -- is still diagnosed by cause rather than as a coverage gap, but where the entry raises at build, a continuation's refusal is deferred to the call that reaches it, since by `_serving_mode`'s contract a standalone artifact's zero-variant continuation is unreachable yet must still bind its resume names. Everything else -- the version locks, the `__main__` and import refusals, the live module dict, the builtins key re-mint, the coverage-gap `PrecompileError` -- is unchanged from the previous commit. The edits are interior to the one function, which stays a single `def` with nested helpers so the source builder can still emit it with one `inspect.getsource`. ## Dispatch ```python # emitted into the artifact after the metadata and the subgraph sources forward = _build_multigraph_forward() forward(model, x) # entry f_locals = {"model": model, "x": x, "rest": (), "scale": 2.0}; # the entry's bytecode reaches the continuation by LOAD_GLOBAL on # __resume_at_N, bound in the captured module by this driver forward(model, x, torch.ones(1), torch.ones(1)) # entry matches, no continuation variant does: # PrecompileError: precompile: no captured variant of 'torch_dynamo_resume_in_step_at_N' matches # this call (2 captured). Either a guard on the call's arguments or on a module global the graph # baked in no longer holds (restore that environment), or this call shape was never captured: the # artifact serves only what capture exercised, so add an example covering it and recapture. ``` Nothing emits this driver into an artifact yet; the source builder that does is part of the capture session. The test builds the records the driver reads from a real `CompilePackage` capture (two calls, so the continuation carries two variants whose outputs differ; a keyword-only default the call omits, `*args`, and a continuation closing over a cell of the entry frame), asserts `_serving_mode` calls it standalone and the continuation carries more than one variant, `exec`s the driver's source into a bare namespace that also binds `torch` to `None` (the collision the captured module's binding has to win), builds once in the capturing process before the Dynamo-minted globals are scrubbed from the test module (the live compile still holds the continuation's resume name, so the load is refused with the fresh-process message), then with those globals scrubbed checks that every captured call dispatches to the variant that produced its answer, that rebinding a module global the entry reads fails its guard and refuses rather than serving the stale graph (and serves again once restored), that an uncovered call refuses at the entry and at the continuation, that rebuilding the same artifact succeeds, that a foreign function bound under one of its resume names refuses the build, as does an artifact with the same `_FRAMES` and backend ids but other `_BACKENDS` (a second artifact of one capture, its subgraphs rotated across the ids), after which the live artifact still serves its own answer -- the refusal preceded any rebinding of the shared backend ids -- and one with other `_FRAMES` and renamed backend ids (another process's capture), each refused on the resume name it shares with the live one (the later rows scrub the live artifact first), that a zero-variant continuation, trivial or BYPASSED, is diagnosed by cause at the call that reaches it (the BYPASSED build succeeds), and that a dead record naming an unimportable module neither refuses the load nor binds anything. The build-time refusals (the version locks, `__main__`, the builtins key, a zero-variant or closure entry, no entry) stay covered by the previous commit's entry-only test, which keeps passing unchanged. Test Plan: ``` python test/test_precompile.py -k test_multigraph_driver_dispatches_captured_frames python test/test_precompile.py -k multigraph python test/test_precompile.py lintrunner --take RUFF,PYFMT,FLAKE8,CODESPELL,PYREFLY 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: #197989 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979, #197980, #197981, #197982, #197983, #197984, #197985, #197986, #197987, #197988
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 22, 2026
…197990) **Summary.** Two small pieces complete the multi-graph artifact plumbing in `torch/_precompile.py`. `_entry_binding(fn)` records the entry's `__defaults__` and `__kwdefaults__`, which a code object does not carry; without them a defaulted parameter is absent from the served call's `f_locals` and every guard misses. Closure cells are deliberately not recorded: a closure entry is refused earlier (a rebuilt cell would be a new object Dynamo's identity guard misses anyway), and the driver refuses one that arrives regardless rather than rebuilding it over empty cells. `_emit_multigraph_driver_source()` renders `_build_multigraph_forward` into the artifact with `inspect.getsource`, the same path the other drivers use, followed by `forward = _build_multigraph_forward()` and the same `if __name__ == "__main__"` hint block the single-graph artifacts end in. `import inspect` moves to module scope, replacing the function-local import `_emit_driver_source` had. Because that section ends in a top-level assignment, `_parse_artifact_metadata` no longer describes one as hypothetical and skips `forward` without the "unrecognized assignment" debug line, which stays a signal for a malformed artifact. ## Examples ```python def step(model, x, scale=2.0, *, mode="sum"): ... _entry_binding(step) # {"defaults": (2.0,), "kwdefaults": {"mode": "sum"}} _emit_multigraph_driver_source() # "\ndef _build_multigraph_forward():\n ...\n\n\nforward = _build_multigraph_forward()\n\n\nif __name__ == \"__main__\":\n ..." ``` Test Plan: ``` python test/test_precompile.py -k test_entry_binding_records_defaults -k test_emit_multigraph_driver_source_is_a_complete_section python test/test_precompile.py lintrunner torch/_precompile.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: #197990 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979, #197980, #197981, #197982, #197983, #197984, #197985, #197986, #197987, #197988, #197989
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 later invariance policy may leave a guard out of the serialized artifact when it held identically across every captured variant, and this commit names the two classes of guard that must never take part in that. Each set states two independent properties, never dropped and never compared.
_SHAPE_BEARING_GUARD_TYPESare the guard types that pin an input's shape, value or kind; the report compares them across variants and a policy never drops one, because with a single captured example nothing can discriminate, and what would disappear is the check that the runtime input looks like the captured one at all._UNMODELLED_GUARD_TYPESare the guard types on ambient or process state that the guard leaf checks for itself and that nothing in this module fingerprints; calling two of them equal would assert a precondition the report cannot see, so they are reported as undetermined rather than compared, and they are never dropped because a policy may drop only what its droppable set names. Both sets are plain sorted literals with a header stating the criterion; membership was settled over the review rounds of this PR, and the four-set partition ofGuardBuilder's methods (these two plus the identity and no-op sets) is pinned by the totality test in the next commit, so a guard type added to Dynamo is kept unconditionally until someone classifies it.Membership
Test Plan:
The classification tests land with the next commit, which adds the other two sets; run there:
Authored with an AI assistant.
🤖 Generated with Claude Code
Co-Authored-By: Claude Fable 5.1 [email protected]
Reverted in c51118f as a dependent of #197262 and back in the stack unchanged.
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98