Repository navigation
[precompile] Add PrecompileSummary, the coverage and guard report of a capture - #197260
Closed
bobrenjc93 wants to merge 19 commits into
Closed
bobrenjc93 wants to merge 19 commits into
bobrenjc93 wants to merge 19 commits into
Conversation
[ghstack-poisoned]
This was referenced Sep 16, 2026
Closed
Closed
pytorchgreenlight
Bot
dismissed
their stale review
September 21, 2026 15:22
This pull request was reverted; greenlight's approval no longer applies.
[ghstack-poisoned]
This was referenced Sep 21, 2026
Closed
Closed
Closed
Closed
Closed
Closed
Closed
Closed
bobrenjc93
added a commit
that referenced
this pull request
Sep 21, 2026
) **Summary.** Whatever autocast state the capture ran under is already baked into the artifact -- ATen casts for the eager backend, generated kernels for inductor -- but the artifact still re-dispatches at serve time (the eager graph's ATen calls, and on the inductor path every fallback op, which is emitted at its `.default` overload -- e.g. `aten.addbmm.default`, which AutocastCPU registers), so a serving process with autocast enabled would cast a second time. Both inlined drivers now run the graph under `torch._C._DisableAutocast()`, the `c10::impl::ExcludeDispatchKeyGuard` over `autocast_dispatch_keyset` (`torch/csrc/autograd/init.cpp`) that AOTAutograd already emits into its own generated wrappers as `_DisableAutocast_` when a compile ran under autocast (`torch/_functorch/_aot_autograd/runtime_wrappers.py`). It is one RAII exclusion of the autocast keys for every device: no per-device list, no nesting counter, and no `clear_autocast_cache()` on exit, so it is safe to enter unconditionally on every call and leaves the caller's autocast state exactly as it found it. This pins autocast off for the duration of the call regardless of capture-time or serve-time state, exactly like the eager driver's pre-existing unconditional `no_grad`; the programming-model docstring gets the same sentence in the later commit that rewrites it (E2). AOTAutograd's guard is conditional on the capture having run under autocast; precompile's is unconditional because the leak it closes runs the other way too (a capture made without autocast, served under it), which is the case the test exhibits. An earlier draft of this commit recorded a `GRAPH_DEVICES` metadata field and entered `torch.amp.autocast(dev, enabled=False)` per device; that reimplemented the primitive with a narrower cache-clear hazard (any exit that returns autocast's nesting count to zero wipes the process-wide cast cache), so the field, its emitter and its parser entry are gone and the artifact format is unchanged from the parent. ## Before and after ```python compiled = PrecompiledModule(lambda m, x: m(x), backend="eager") compiled._compile((model, x)) ns = {"__name__": "artifact"} exec(compiled.to_python_code(), ns) with torch.autocast("cpu", dtype=torch.bfloat16): out = ns["forward"](model, x) # parent: the captured graph re-dispatched under autocast and cast its inputs a second time (bf16 out) # now: the driver runs call(...) under torch._C._DisableAutocast() (fp32 out, equal to the # no-autocast call), and the caller's autocast state is as it was afterwards ``` ## The driver change ```python # _eager_forward: with _torch._C._DisableAutocast(), _torch.no_grad(): out = list(call([...])) # _inductor_forward: with _torch._C._DisableAutocast(): out = list(call([...])) ``` `test_artifact_neutralizes_ambient_autocast` (parametrized over both backends, CPU bf16 autocast) captures a `torch.addbmm` model and checks that a call under ambient autocast returns the fp32 result of eager `model(x)` computed outside any autocast, that the ambient region is still live and bf16 after the call, and that autocast is off again after the region. `addbmm` is the op that makes the inductor case load-bearing on CPU: `KERNEL_CPU(addbmm, lower_precision_fp)` registers it for AutocastCPU, `make_fallback(aten.addbmm)` leaves it undecomposed, and `FallbackKernel` keeps builtin aten ops at their functional overload, so the inductor artifact calls `torch.ops.aten.addbmm.default` (the `Linear`/`addmm` graph cannot show this: `extern_kernels.addmm` binds `addmm.out`, which autocast never registers). Deleting either guard fails its case: eager with `bfloat16 != float32`, inductor with `assert_tensor_metadata` raising `expected dtype torch.float32 but got torch.bfloat16`. Test Plan: ``` python test/test_precompile.py -k autocast python test/test_precompile.py lintrunner torch/_precompile.py torch/_precompile_driver.py test/test_precompile.py ``` Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: #197279 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595, #197265, #197267, #197268, #197269, #197270, #197266, #197271, #197272, #197273, #197274, #197275, #197721, #197276, #197278 Re-land of #197279, reverted in 70f4f9b as a dependent of #197262 (whose test the re-land below fixes). ghstack-source-id: bf1865a
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
…a capture (#197260) (#197964) **Problem.** The multi-graph precompile capture needs a report type that tells a caller what it captured and what it dropped, and nothing in the tree defines one. **Fix.** Add `PrecompileSummary`, a frozen keyword-only dataclass with documented fields, a coverage-only `complete` flag, per-type guard tallies and a one-line digest. It is data only; the producer that fills it comes later in the stack. **Summary.** `PrecompileSummary` is the frozen, keyword-only dataclass a multi-graph capture will hand back to describe what it observed: how many frames, graph-break continuations, guarded codes and backend graphs were captured, which frames were bypassed, truncated or left uncovered, and which guards were dropped, kept, dropped riskily, or dropped by the invariance policy. Nothing in this commit produces one -- the builder (`_summarize`), the guard filter and the lints it names live later in this stack -- so every `Attributes:` entry says what the field means to a consumer of the report and names the producer for how it is populated instead of repeating its rules, after two earlier drafts that restated the guard-filter rule went stale against it. The relations between the fields (`bypassed` and `uncovered_frames` never share a frame, `kept_guards` and `dropped_guards` are disjoint per frame variant but aggregate across frames, `policy_dropped_guards` is drawn from slots the filter kept) are stated in the docstrings and not enforced, because a `__post_init__` that raised on a bookkeeping collision would lose the whole report, which `capture_errors` exists to avoid. `complete` is the one piece of logic, a coverage-only flag with six terms (nothing bypassed, truncated or uncovered, no capture error, at least one guarded code and at least one backend graph), and `dropped_guard_types`, `kept_guard_types` and `__str__` derive the per-type tallies and a one-line digest that names risky drops and shouts the frame failures last. It is keyword-only because its four required fields are all `int`, so `PrecompileSummary(3, 0, 1, 1)` would be legal and unreadable, and the positional order would become part of a public contract once the type is exported from `torch.compiler.precompile` later in this stack. ## The fields ```python @dataclasses.dataclass(frozen=True, kw_only=True) class PrecompileSummary: frames: int # every frame the package holds an entry for resume_functions: int # of those, the graph-break continuations guarded_codes: int backend_graphs: int bypassed: tuple[str, ...] = () # co_name per frame truncated: tuple[str, ...] = () # "co_name (filename:firstlineno)" per code object uncovered_frames: tuple[str, ...] = () # co_name per frame wont_generalize: tuple[str, ...] = () # guard sources, not frame names dropped_guards: tuple[tuple[str, str], ...] = () # (guard_type, source) slots kept_guards: tuple[tuple[str, str], ...] = () risky_dropped_guards: tuple[tuple[str, str], ...] = () policy_dropped_guards: tuple[tuple[str, str], ...] = () dropped_guard_code: tuple[tuple[str, str, str], ...] = () # (guard_type, source, rendered_check) capture_errors: tuple[str, ...] = () # "ExceptionType: message", one per distinct exception ``` ## The frame fields `frames` counts every frame the package holds an entry for, the bypassed, truncated and uncovered ones included, and the docstring says so, because `bypassed` as "frames the package refused to record" otherwise reads as frames outside the count and `8 frames, ... 7 UNCOVERED` as fifteen frames; the builder later in this stack (`_summarize`) takes `frames` from `len(entry.codes)` and both `bypassed` and `uncovered_frames` from the same list, so both are subsets by construction, and the digest's frame clauses cut into the count rather than add to it. `bypassed` is documented as what `_DynamoCodeCacheEntry.bypassed` records: the package holds nothing installable for the frame because no compile of it recorded a guarded code and one was bypassed (either `OutputGraph.bypass_package` cause, guards that could not be serialized or a graph that held parameters by static address), or a backend artifact was missing at save; the frame still ran compiled during capture, the package kept no variant of it a load can serve, and an install re-traces it; it is not an eager fallback. Not "every compile was bypassed": `bypass_current_compile` sets the flag as `not guarded_codes` and `add_guarded_code` clears it, so a compile that raised before recording anything is neither a bypass nor a record and leaves the flag free for a later bypassed compile of the same frame. How each cause gets there (a save-time bypass leaves the stale guarded codes in the artifact for `CompilePackage.initialize` to drop, while a `bypass_package` compile never recorded them) is the package's business, so the field says what the consumer gets and leaves that to the producer. `uncovered_frames` is the frames the capture ran that ended with no guarded code and were not bypassed, a different cause and remedy from `bypassed` (an install `skip_code`s an uncovered frame, so only a re-capture recovers it, where it re-traces a bypassed one) and never the same frame (which is why the predicate excludes bypassed frames rather than leaning on their guarded codes, which a save-time bypass leaves in place). The docstring names three causes: a thin wrapper whose graphs landed in an inner frame, a frame Dynamo gave up on, and a frame whose compile raised, since `code_context` sets `has_compile_id` in its `finally`, for a compile attempted whether or not it finished, so one failure shows in the digest as both a CAPTURE ERROR and an UNCOVERED clause; and it states the one overlap, a frame that hit the recompile limit before it recorded a guarded code (the limit check runs inside `code_context` and reads the code object's pre-existing cache size, so a warm process gets there with no guarded code), which is in `truncated` too. The docstring says it is explicitly not a remainder, because which frames count as a gap is the producer's call and a frame the package holds an entry for but never ran is not one, so a consumer cannot recompute it as `frames` minus `bypassed` minus the frames that hold guarded code. An earlier draft had `uncovered_frames` arrive as a set of bare names, which the builder now reads off the entry instead (a frame that entered Dynamo, holds no guarded code and was not bypassed), so `2 UNCOVERED` is two frames and not two names; `install()` `skip_code()`s a superset of those frames (`if len(entry.guarded_codes) == 0`, with no `has_compile_id` test), which is why the docstring describes the field rather than equating it with the skip. The frame lists differ in what an entry is, and the docstring says so: ```python bypassed=("forward", "forward") # two frames, not a repeat: every nn.Module has a forward uncovered_frames=("helper",) # bare co_name; len() counts frames truncated=("forward (model.py:12)", "forward (model.py:40)") # once per code object; identifies a frame ``` `bypassed` and `uncovered_frames` hold one bare `co_name` per frame, so a name can repeat and their lengths count frames, while `truncated` holds `co_name (filename:firstlineno)`, recorded once per code object by the compile path that sees a frame hit the limit (the only producer of that set, in the follow-up stack, spells it that way, and a set of bare names would merge two `forward`s into one), so its entries do identify a frame. A bare name identifies none, which is why the `bypassed`/`uncovered_frames` relation is stated and not enforced. `truncated` is documented as a lower bound, which is why the digest prints it as `>=`: from a limit hit on, that frame and the frames it calls run without tracing (`FrameExecStrategy(RUN_ONLY, RUN_ONLY)` in `convert_frame.py`, whose second component is the action for callees), so a limit hit that would follow it there is never recorded; by the same mechanism every count and frame list is a lower bound once `truncated` is non-empty, and the class docstring says so. A callee the traced compiles reached is in the entry and counted; one first reached after the hit never enters Dynamo (under `RUN_ONLY` the nested callback is `Py_False`, `eval_frame_cpp.cpp`), so it gets no entry and is missing from `frames` and `uncovered_frames` alike, while sibling frames keep tracing and keep being recorded. ## The guard slot lists The four guard lists hold `(guard_type, source)` slots, the source spelled as `GuardFilterEntry.name`, the `Guard.name` with local scope stripped (`self.act`, not `L['self'].act`; `G['CFG'].width` unchanged). `dropped_guards` is every slot the serialized copy's guard filter rejected, the guards the serializer refuses plus whatever a caller-supplied filter dropped, not only the unserializable ones; that matches the `default_guard_filter_fn` docstring the next commit of this stack adds to `torch/_dynamo/precompile_package.py` ("Every dropped slot is reported in `PrecompileSummary.dropped_guards`, once however many variants dropped it") and is what the `dropped_guard_code` entry below relies on. Which guards a filter rejects is not restated here at all: the docstring names `default_guard_filter_fn` as the default (one sentence above the `Attributes:` block says the three rules it names live in `torch._dynamo.precompile_package`, whose filter this stack adds alongside this type and whose other two rules come later in the stack, so a reader of landed `main` knows where the targets are), defers the whole rule and every exemption to that filter's docstring, and says a caller-supplied filter decides its own set. Two earlier drafts did restate the rule and both went stale as the filter changed shape underneath them -- the first repeated two of its three by-type exemptions, the second characterized the exemptions as by-type when the filter now has two by-type exemptions plus one derived type it ignores -- and each time the stale rule predicted a drop on the pytree-registry guard essentially every capture keeps. That is the shape every `Attributes:` entry now follows: say what the field means to a consumer of the report, and name the producer for how it is populated instead of repeating its rules. A slot keeps its own type, so a `TENSOR_MATCH` that checked identity (`match_on_id_for_tensor` routes it through `ID_MATCH`) is listed as a dropped `TENSOR_MATCH`, the same type the tests use as the canonical kept guard. The class docstring states how the lists relate and why nothing enforces it. Within one frame variant `kept_guards` and `dropped_guards` are disjoint (the filter gives a slot one verdict, keep or reject), `risky_dropped_guards` is drawn from `dropped_guards` and `policy_dropped_guards` is disjoint from both it and `kept_guards` (the policy re-serializes each variant's guards from the pickle the filters already passed, so a policy drop is a slot the filter kept, taken out once it held identically across every captured variant, and is not checked either, so `(N kept)` never counts one; `policy_dropped_guards` is documented as those kept-then-dropped slots, with `_INVARIANT_DROPPABLE_GUARD_TYPES` named as the bound on what the policy may drop, rather than as "serializable slots", since that set also lists the identity types the default filter drops first). But the lists aggregate every captured frame: ```python # test_summary_guard_lists_aggregate_over_frames: two frames' guards on the builtin # len are one slot. One frame's caller filter rejected it and the drop told that # frame's variants apart (risky); the other frame's invariance policy dropped it. act = ("BUILTIN_MATCH", "G['__builtins_dict___<n>']['len']") summary = PrecompileSummary(frames=2, resume_functions=0, guarded_codes=2, backend_graphs=2, dropped_guards=(act,), risky_dropped_guards=(act,), policy_dropped_guards=(act,), dropped_guard_code=(act + (check,),)) summary.dropped_guard_types # {'BUILTIN_MATCH': 1}: distinct slots, not occurrences str(summary) # "2 frames (0 from graph breaks), 2 guarded codes, 2 backend graphs, dropped guards {'BUILTIN_MATCH': 1} (0 kept), RISKY drops [\"BUILTIN_MATCH G['__builtins_dict___<n>']['len']\"], 1 policy-dropped guard" ``` Each slot appears once however many frames or variants carried it (so `dropped_guard_types` counts distinct slots, not occurrences), and a slot names no frame, so two frames' `self.act` are one slot, a slot one frame kept and another dropped is in both `kept_guards` and `dropped_guards` (which is why the digest's `(N kept)` is the kept count beside the drops, not the other half of a total), and a slot one frame's filter rejected and another frame's invariance policy dropped is legitimately in both drop lists. The relations are therefore stated, not checked, the way the frame lists already are; a `__post_init__` that raised on them would turn a bookkeeping collision into the loss of the whole report, which `capture_errors` exists to avoid. The same holds for `dropped_guard_code`, whose slots come from the two drop lists, and for `wont_generalize`, whose every source is the source half of a `kept_guards` slot. ## `dropped_guard_code` `dropped_guard_code` carries the rendered check next to each dropped slot, because a slot such as `('HASATTR', "counts['pixel']")` can be either the benign companion of a kept `TENSOR_MATCH` or the only guard on an optional attribute, and only the rendered text tells them apart; it is for programmatic consumers, not the digest. A slot is absent from it when its guard rendered no check, i.e. its `GuardBuilder` method never set `Guard.code_list` (the only writer is `Guard.set_export_info`, reached through the builder's `_set_guard_export_info`, and `CheckFunctionManager` resets `code_list` before every build, so this is a statement about the pre-filter build the entries come from, not about the guard in general). That is not predictable from how the check is installed, and the docstring states the predicate and says so instead of offering a rule or enumerating guard types (an enumeration in a docstring would rot against `guards.py` unchecked); the evidence is recorded here instead: | guard type | installed through | renders a check | | --- | --- | --- | | `AUTOGRAD_SAVED_TENSORS_HOOKS` | a lambda | yes | | `DEFAULT_DEVICE` | a C++ leaf | yes | | `GLOBAL_STATE`, `TORCH_FUNCTION_STATE`, `DISPATCH_KEY_SET_MATCH`, `TENSOR_SUBCLASS_METADATA_MATCH` | | no | | `CLOSURE_MATCH` on a plain function | guards `__code__` through a separate guard | no | | `CLOSURE_MATCH` on any other callable | falls through to `FUNCTION_MATCH` -> `ID_MATCH` | yes | The entry holds one rendering however many variants dropped the slot, and the docstring says what that means for a check that embeds the guarded value (`EQUALS_MATCH` renders `L['n'] == 3`): variants that differ in the value render differently, the entry shows one variant's rendering, the producer's pick rather than a merge, so it tells the form of the check and not the value; that the slot varied at all is what `risky_dropped_guards` records. The alternative, several entries per slot sharing a `(guard_type, source)` prefix, would make the field grow with variants rather than with slots and would answer a question (`which values`) the field is not for. ## `wont_generalize` `wont_generalize` is documented as observed, not proven: a source is listed when a kept value-equality guard on a bare argument name pins it in some variant (`_pins_a_value` in `torch/_dynamo/precompile_package.py` is the rule, named rather than restated, so a kept `EQUALS_MATCH` on `self.eps` or `G['CFG'].width` is deliberately not one; `kept_guards` stays the authoritative list) and no other variant of the same frame guards it without pinning it, which is what the builder computes frame by frame (a variant that never guarded the source does not cancel the pin, and a frame that cancels its own pin does not cancel another frame's), rather than as a claim that every variant pins it. ## Keyword-only ```python PrecompileSummary(frames=3, resume_functions=0, guarded_codes=1, backend_graphs=1) # ok PrecompileSummary(3, 0, 1, 1) # TypeError: takes 1 positional argument but 5 were given ``` Its four required fields are all `int`, so the positional form would be legal and unreadable, and the positional order would become part of a public contract (the type is exported from `torch.compiler.precompile` later in this stack); the builder later in this stack (`_summarize`) and every test already construct it by keyword. ## complete Its `complete` property is the one piece of logic: a capture counts as complete only if nothing was bypassed, truncated or uncovered, no capture call raised, and it produced at least one guarded code and at least one backend graph. It is a coverage flag only. `risky_dropped_guards` is a lint finding, not a proof, and `wont_generalize` follows from any value the capture pinned, so neither enters `complete`; both describe how far a complete capture generalizes, and the digest reports them on their own. The `backend_graphs > 0` term matters because `allow_empty_graphs` lets a frame that compiled nothing still count as a guarded code, so `guarded_codes` alone cannot tell a real capture from an empty one (a model whose every graph sits behind a recursive `torch._dynamo.disable`). ```python def summary(**kw): base = dict(frames=1, resume_functions=0, guarded_codes=1, backend_graphs=1) base.update(kw) return PrecompileSummary(**base) summary().complete # True summary(backend_graphs=0).complete # False: nothing was compiled summary(guarded_codes=0).complete # False summary(capture_errors=("boom",)).complete # False summary(bypassed=("f",)).complete # False, likewise truncated / uncovered_frames risky = (("ID_MATCH", "self.act"),) summary(dropped_guards=risky, risky_dropped_guards=risky).complete # True: coverage only ``` `complete`, `dropped_guard_types` and `kept_guard_types` are all properties: each is an argument-free derivation of the fields, and one convention keeps `if summary.dropped_guard_types:` from silently passing on a bound method. ## The one-line digest ```python s = PrecompileSummary(frames=2, resume_functions=1, guarded_codes=3, backend_graphs=2, dropped_guards=(("ID_MATCH", "G['fn']"),), kept_guards=(("EQUALS_MATCH", "scale"), ("TENSOR_MATCH", "x")), wont_generalize=("scale",)) str(s) # "2 frames (1 from graph breaks), 3 guarded codes, 2 backend graphs, dropped guards {'ID_MATCH': 1} (2 kept), 1 value-pinned source" s.dropped_guard_types # {'ID_MATCH': 1} risky = (("HASATTR", "self.act"), ("ID_MATCH", "self.act")) wide = PrecompileSummary(frames=8, resume_functions=0, guarded_codes=1, backend_graphs=1, uncovered_frames=tuple(f"f{i}" for i in range(7)), dropped_guards=risky, risky_dropped_guards=risky, capture_errors=("RuntimeError: boom", "TypeError: bad", "ValueError: no")) str(wide) # "8 frames (0 from graph breaks), 1 guarded code, 1 backend graph, dropped guards {'HASATTR': 1, 'ID_MATCH': 1} (0 kept), RISKY drops ['HASATTR self.act', 'ID_MATCH self.act'], 7 UNCOVERED: ['f0', 'f1', 'f2', 'f3', 'f4'] +2 more, 3 CAPTURE ERRORS: 'RuntimeError: boom' +2 more" ``` Ordinary drops are counted by type with the kept count beside them for scale (a count, not a denominator: the two lists are disjoint per frame variant, not across frames), since every model drops the identity guards precompile cannot serialize. RISKY drops are few and actionable, so the digest names them, both halves of the slot, because two risky slots can share a source (a dropped `ID_MATCH` on `self.act` and a `HASATTR` checked on that object; a `HASATTR` slot's source is the object checked, the attribute is only in its rendering) and `['self.act', 'self.act']` would read as a duplicate. Policy drops and value-pinned sources are counted. The digest stays one line whatever the model: the four list clauses (RISKY, UNCOVERED, TRUNCATED, BYPASSED) show their first five entries and then `+N more`, and the CAPTURE ERROR clause, the one place the report carries prose a reader can act on, shows the first non-empty line of the first message (repr'd, so a multi-line Dynamo message cannot break the line; non-empty so a message that opens with a newline does not render as `''`) and `+N more` for the rest. `capture_errors` is documented as `ExceptionType: message` strings, one per distinct exception rather than per failed call (the producer collapses repeats of the same type and message, so ten inputs failing the same way render `1 CAPTURE ERROR`), the type name first, so a bare `assert` (whose `str()` is empty) still leaves the clause something to show. The count in front of the three frame clauses and the CAPTURE ERROR clause is still the full count (the RISKY clause carries no count, so its total is the entries shown plus `+N more`). Every counted noun agrees with its count (`1 guarded code`, `2 backend graphs`, `1 CAPTURE ERROR`); the shouted frame clauses (`1 UNCOVERED: ['helper']`) carry a list, not a noun. The guard clauses come first and the shouted frame failures (UNCOVERED, TRUNCATED, BYPASSED, CAPTURE ERROR) last, so a failure never sits between two notes. ## Tests All in `test/test_precompile.py`, next to the module's other tests. - `test_summary_complete_requires_every_term` pins all six terms of `complete` and that the guard fields never enter it. - `test_summary_digest_and_guard_type_counts` feeds every guard list sorted, as `_summarize` emits them, so the tally orderings its goldens pin are ones real output produces. It pins the digest for a capture with three dropped guards, a policy drop and a value-pinned source (which carries a `dropped_guard_code` entry the digest must not mention); for a clean capture with kept guards and no optional clause at all (`1 frame (0 from graph breaks), 1 guarded code, 1 backend graph`: kept guards appear only beside the drops); for a failing one whose two risky slots share a source and whose single capture error is a three-line message opening with a blank line (only its first non-empty line is shown); and for a wide one with seven uncovered frames and three errors (`['f0', 'f1', 'f2', 'f3', 'f4'] +2 more`, `'RuntimeError: boom' +2 more`), with singular and plural counts, plus the `dropped_guard_types` / `kept_guard_types` properties. - `test_summary_pickle_and_hash` round-trips a fully populated summary (every field set, including `dropped_guard_code` and `capture_errors`) through `pickle`, checks that the copy compares and hashes equal, pins that summary's digest (the only golden with all eight clauses: `bad` already pinned notes before the shouted UNCOVERED, TRUNCATED, BYPASSED, CAPTURE ERROR order, and this one adds `1 policy-dropped guard` and `1 value-pinned source` between the RISKY clause and UNCOVERED, which no other fixture places), and checks that positional construction raises the keyword-only `TypeError`. Only `PrecompileSummary` is round-tripped here: `GuardFact` gets its own round-trip with its keyword-only change two commits up, which also deletes `FrameInvariants` as unused. - `test_summary_guard_lists_aggregate_over_frames` pins the multi-frame case: one slot listed as dropped, risky and policy-dropped at once constructs, is counted once by `dropped_guard_types`, and renders once in each digest clause. Its comment credits the risky classification to the slot telling its frame's variants apart, not to the risky-drop lint, which waives a builtin read the ordinary way (`_reads_a_builtin`). Every policy-dropped fixture slot is a `BUILTIN_MATCH` on `G['__builtins_dict___<n>']['len']`, one of the four serializable types the default filter keeps and `_INVARIANT_DROPPABLE_GUARD_TYPES` lets the policy drop, and the only one of them with a source (`DUAL_LEVEL`, `FUNCTORCH_STACK_MATCH` and `AUTOGRAD_SAVED_TENSORS_HOOKS` are global-state guards); a `CONSTANT_MATCH` or `HASATTR` is `_SHAPE_BEARING_GUARD_TYPES`, never policy-dropped, so a fixture placing one on the policy side would pin a state the producer cannot emit. Likewise every fixture that lists a `wont_generalize` source keeps an `EQUALS_MATCH` on that bare name, since `_wont_generalize` returns nothing unless a kept slot passes `_pins_a_value`. Test Plan: ``` python test/test_precompile.py -k summary lintrunner torch/compiler/_precompile_types.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 94990b8 as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197964 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963
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):
Problem. The multi-graph precompile capture needs a report type that tells a caller what it captured and what it dropped, and nothing in the tree defines one.
Fix. Add
PrecompileSummary, a frozen keyword-only dataclass with documented fields, a coverage-onlycompleteflag, per-type guard tallies and a one-line digest. It is data only; the producer that fills it comes later in the stack.Summary.
PrecompileSummaryis the frozen, keyword-only dataclass a multi-graph capture will hand back to describe what it observed: how many frames, graph-break continuations, guarded codes and backend graphs were captured, which frames were bypassed, truncated or left uncovered, and which guards were dropped, kept, dropped riskily, or dropped by the invariance policy. Nothing in this commit produces one -- the builder (_summarize), the guard filter and the lints it names live later in this stack -- so everyAttributes:entry says what the field means to a consumer of the report and names the producer for how it is populated instead of repeating its rules, after two earlier drafts that restated the guard-filter rule went stale against it. The relations between the fields (bypassedanduncovered_framesnever share a frame,kept_guardsanddropped_guardsare disjoint per frame variant but aggregate across frames,policy_dropped_guardsis drawn from slots the filter kept) are stated in the docstrings and not enforced, because a__post_init__that raised on a bookkeeping collision would lose the whole report, whichcapture_errorsexists to avoid.completeis the one piece of logic, a coverage-only flag with six terms (nothing bypassed, truncated or uncovered, no capture error, at least one guarded code and at least one backend graph), anddropped_guard_types,kept_guard_typesand__str__derive the per-type tallies and a one-line digest that names risky drops and shouts the frame failures last. It is keyword-only because its four required fields are allint, soPrecompileSummary(3, 0, 1, 1)would be legal and unreadable, and the positional order would become part of a public contract once the type is exported fromtorch.compiler.precompilelater in this stack.The fields
The frame fields
framescounts every frame the package holds an entry for, the bypassed, truncated and uncovered ones included, and the docstring says so, becausebypassedas "frames the package refused to record" otherwise reads as frames outside the count and8 frames, ... 7 UNCOVEREDas fifteen frames; the builder later in this stack (_summarize) takesframesfromlen(entry.codes)and bothbypassedanduncovered_framesfrom the same list, so both are subsets by construction, and the digest's frame clauses cut into the count rather than add to it.bypassedis documented as what_DynamoCodeCacheEntry.bypassedrecords: the package holds nothing installable for the frame because no compile of it recorded a guarded code and one was bypassed (eitherOutputGraph.bypass_packagecause, guards that could not be serialized or a graph that held parameters by static address), or a backend artifact was missing at save; the frame still ran compiled during capture, the package kept no variant of it a load can serve, and an install re-traces it; it is not an eager fallback. Not "every compile was bypassed":bypass_current_compilesets the flag asnot guarded_codesandadd_guarded_codeclears it, so a compile that raised before recording anything is neither a bypass nor a record and leaves the flag free for a later bypassed compile of the same frame. How each cause gets there (a save-time bypass leaves the stale guarded codes in the artifact forCompilePackage.initializeto drop, while abypass_packagecompile never recorded them) is the package's business, so the field says what the consumer gets and leaves that to the producer.uncovered_framesis the frames the capture ran that ended with no guarded code and were not bypassed, a different cause and remedy frombypassed(an installskip_codes an uncovered frame, so only a re-capture recovers it, where it re-traces a bypassed one) and never the same frame (which is why the predicate excludes bypassed frames rather than leaning on their guarded codes, which a save-time bypass leaves in place). The docstring names three causes: a thin wrapper whose graphs landed in an inner frame, a frame Dynamo gave up on, and a frame whose compile raised, sincecode_contextsetshas_compile_idin itsfinally, for a compile attempted whether or not it finished, so one failure shows in the digest as both a CAPTURE ERROR and an UNCOVERED clause; and it states the one overlap, a frame that hit the recompile limit before it recorded a guarded code (the limit check runs insidecode_contextand reads the code object's pre-existing cache size, so a warm process gets there with no guarded code), which is intruncatedtoo. The docstring says it is explicitly not a remainder, because which frames count as a gap is the producer's call and a frame the package holds an entry for but never ran is not one, so a consumer cannot recompute it asframesminusbypassedminus the frames that hold guarded code. An earlier draft haduncovered_framesarrive as a set of bare names, which the builder now reads off the entry instead (a frame that entered Dynamo, holds no guarded code and was not bypassed), so2 UNCOVEREDis two frames and not two names;install()skip_code()s a superset of those frames (if len(entry.guarded_codes) == 0, with nohas_compile_idtest), which is why the docstring describes the field rather than equating it with the skip.The frame lists differ in what an entry is, and the docstring says so:
bypassedanduncovered_frameshold one bareco_nameper frame, so a name can repeat and their lengths count frames, whiletruncatedholdsco_name (filename:firstlineno), recorded once per code object by the compile path that sees a frame hit the limit (the only producer of that set, in the follow-up stack, spells it that way, and a set of bare names would merge twoforwards into one), so its entries do identify a frame. A bare name identifies none, which is why thebypassed/uncovered_framesrelation is stated and not enforced.truncatedis documented as a lower bound, which is why the digest prints it as>=: from a limit hit on, that frame and the frames it calls run without tracing (FrameExecStrategy(RUN_ONLY, RUN_ONLY)inconvert_frame.py, whose second component is the action for callees), so a limit hit that would follow it there is never recorded; by the same mechanism every count and frame list is a lower bound oncetruncatedis non-empty, and the class docstring says so. A callee the traced compiles reached is in the entry and counted; one first reached after the hit never enters Dynamo (underRUN_ONLYthe nested callback isPy_False,eval_frame_cpp.cpp), so it gets no entry and is missing fromframesanduncovered_framesalike, while sibling frames keep tracing and keep being recorded.The guard slot lists
The four guard lists hold
(guard_type, source)slots, the source spelled asGuardFilterEntry.name, theGuard.namewith local scope stripped (self.act, notL['self'].act;G['CFG'].widthunchanged).dropped_guardsis every slot the serialized copy's guard filter rejected, the guards the serializer refuses plus whatever a caller-supplied filter dropped, not only the unserializable ones; that matches thedefault_guard_filter_fndocstring the next commit of this stack adds totorch/_dynamo/precompile_package.py("Every dropped slot is reported inPrecompileSummary.dropped_guards, once however many variants dropped it") and is what thedropped_guard_codeentry below relies on. Which guards a filter rejects is not restated here at all: the docstring namesdefault_guard_filter_fnas the default (one sentence above theAttributes:block says the three rules it names live intorch._dynamo.precompile_package, whose filter this stack adds alongside this type and whose other two rules come later in the stack, so a reader of landedmainknows where the targets are), defers the whole rule and every exemption to that filter's docstring, and says a caller-supplied filter decides its own set. Two earlier drafts did restate the rule and both went stale as the filter changed shape underneath them -- the first repeated two of its three by-type exemptions, the second characterized the exemptions as by-type when the filter now has two by-type exemptions plus one derived type it ignores -- and each time the stale rule predicted a drop on the pytree-registry guard essentially every capture keeps. That is the shape everyAttributes:entry now follows: say what the field means to a consumer of the report, and name the producer for how it is populated instead of repeating its rules. A slot keeps its own type, so aTENSOR_MATCHthat checked identity (match_on_id_for_tensorroutes it throughID_MATCH) is listed as a droppedTENSOR_MATCH, the same type the tests use as the canonical kept guard.The class docstring states how the lists relate and why nothing enforces it. Within one frame variant
kept_guardsanddropped_guardsare disjoint (the filter gives a slot one verdict, keep or reject),risky_dropped_guardsis drawn fromdropped_guardsandpolicy_dropped_guardsis disjoint from both it andkept_guards(the policy re-serializes each variant's guards from the pickle the filters already passed, so a policy drop is a slot the filter kept, taken out once it held identically across every captured variant, and is not checked either, so(N kept)never counts one;policy_dropped_guardsis documented as those kept-then-dropped slots, with_INVARIANT_DROPPABLE_GUARD_TYPESnamed as the bound on what the policy may drop, rather than as "serializable slots", since that set also lists the identity types the default filter drops first). But the lists aggregate every captured frame:Each slot appears once however many frames or variants carried it (so
dropped_guard_typescounts distinct slots, not occurrences), and a slot names no frame, so two frames'self.actare one slot, a slot one frame kept and another dropped is in bothkept_guardsanddropped_guards(which is why the digest's(N kept)is the kept count beside the drops, not the other half of a total), and a slot one frame's filter rejected and another frame's invariance policy dropped is legitimately in both drop lists. The relations are therefore stated, not checked, the way the frame lists already are; a__post_init__that raised on them would turn a bookkeeping collision into the loss of the whole report, whichcapture_errorsexists to avoid. The same holds fordropped_guard_code, whose slots come from the two drop lists, and forwont_generalize, whose every source is the source half of akept_guardsslot.dropped_guard_codedropped_guard_codecarries the rendered check next to each dropped slot, because a slot such as('HASATTR', "counts['pixel']")can be either the benign companion of a keptTENSOR_MATCHor the only guard on an optional attribute, and only the rendered text tells them apart; it is for programmatic consumers, not the digest.A slot is absent from it when its guard rendered no check, i.e. its
GuardBuildermethod never setGuard.code_list(the only writer isGuard.set_export_info, reached through the builder's_set_guard_export_info, andCheckFunctionManagerresetscode_listbefore every build, so this is a statement about the pre-filter build the entries come from, not about the guard in general). That is not predictable from how the check is installed, and the docstring states the predicate and says so instead of offering a rule or enumerating guard types (an enumeration in a docstring would rot againstguards.pyunchecked); the evidence is recorded here instead:AUTOGRAD_SAVED_TENSORS_HOOKSDEFAULT_DEVICEGLOBAL_STATE,TORCH_FUNCTION_STATE,DISPATCH_KEY_SET_MATCH,TENSOR_SUBCLASS_METADATA_MATCHCLOSURE_MATCHon a plain function__code__through a separate guardCLOSURE_MATCHon any other callableFUNCTION_MATCH->ID_MATCHThe entry holds one rendering however many variants dropped the slot, and the docstring says what that means for a check that embeds the guarded value (
EQUALS_MATCHrendersL['n'] == 3): variants that differ in the value render differently, the entry shows one variant's rendering, the producer's pick rather than a merge, so it tells the form of the check and not the value; that the slot varied at all is whatrisky_dropped_guardsrecords. The alternative, several entries per slot sharing a(guard_type, source)prefix, would make the field grow with variants rather than with slots and would answer a question (which values) the field is not for.wont_generalizewont_generalizeis documented as observed, not proven: a source is listed when a kept value-equality guard on a bare argument name pins it in some variant (_pins_a_valueintorch/_dynamo/precompile_package.pyis the rule, named rather than restated, so a keptEQUALS_MATCHonself.epsorG['CFG'].widthis deliberately not one;kept_guardsstays the authoritative list) and no other variant of the same frame guards it without pinning it, which is what the builder computes frame by frame (a variant that never guarded the source does not cancel the pin, and a frame that cancels its own pin does not cancel another frame's), rather than as a claim that every variant pins it.Keyword-only
Its four required fields are all
int, so the positional form would be legal and unreadable, and the positional order would become part of a public contract (the type is exported fromtorch.compiler.precompilelater in this stack); the builder later in this stack (_summarize) and every test already construct it by keyword.complete
Its
completeproperty is the one piece of logic: a capture counts as complete only if nothing was bypassed, truncated or uncovered, no capture call raised, and it produced at least one guarded code and at least one backend graph. It is a coverage flag only.risky_dropped_guardsis a lint finding, not a proof, andwont_generalizefollows from any value the capture pinned, so neither enterscomplete; both describe how far a complete capture generalizes, and the digest reports them on their own. Thebackend_graphs > 0term matters becauseallow_empty_graphslets a frame that compiled nothing still count as a guarded code, soguarded_codesalone cannot tell a real capture from an empty one (a model whose every graph sits behind a recursivetorch._dynamo.disable).complete,dropped_guard_typesandkept_guard_typesare all properties: each is an argument-free derivation of the fields, and one convention keepsif summary.dropped_guard_types:from silently passing on a bound method.The one-line digest
Ordinary drops are counted by type with the kept count beside them for scale (a count, not a denominator: the two lists are disjoint per frame variant, not across frames), since every model drops the identity guards precompile cannot serialize. RISKY drops are few and actionable, so the digest names them, both halves of the slot, because two risky slots can share a source (a dropped
ID_MATCHonself.actand aHASATTRchecked on that object; aHASATTRslot's source is the object checked, the attribute is only in its rendering) and['self.act', 'self.act']would read as a duplicate. Policy drops and value-pinned sources are counted.The digest stays one line whatever the model: the four list clauses (RISKY, UNCOVERED, TRUNCATED, BYPASSED) show their first five entries and then
+N more, and the CAPTURE ERROR clause, the one place the report carries prose a reader can act on, shows the first non-empty line of the first message (repr'd, so a multi-line Dynamo message cannot break the line; non-empty so a message that opens with a newline does not render as'') and+N morefor the rest.capture_errorsis documented asExceptionType: messagestrings, one per distinct exception rather than per failed call (the producer collapses repeats of the same type and message, so ten inputs failing the same way render1 CAPTURE ERROR), the type name first, so a bareassert(whosestr()is empty) still leaves the clause something to show. The count in front of the three frame clauses and the CAPTURE ERROR clause is still the full count (the RISKY clause carries no count, so its total is the entries shown plus+N more). Every counted noun agrees with its count (1 guarded code,2 backend graphs,1 CAPTURE ERROR); the shouted frame clauses (1 UNCOVERED: ['helper']) carry a list, not a noun. The guard clauses come first and the shouted frame failures (UNCOVERED, TRUNCATED, BYPASSED, CAPTURE ERROR) last, so a failure never sits between two notes.Tests
All in
test/test_precompile.py, next to the module's other tests.test_summary_complete_requires_every_termpins all six terms ofcompleteand that the guard fields never enter it.test_summary_digest_and_guard_type_countsfeeds every guard list sorted, as_summarizeemits them, so the tally orderings its goldens pin are ones real output produces. It pins the digest for a capture with three dropped guards, a policy drop and a value-pinned source (which carries adropped_guard_codeentry the digest must not mention); for a clean capture with kept guards and no optional clause at all (1 frame (0 from graph breaks), 1 guarded code, 1 backend graph: kept guards appear only beside the drops); for a failing one whose two risky slots share a source and whose single capture error is a three-line message opening with a blank line (only its first non-empty line is shown); and for a wide one with seven uncovered frames and three errors (['f0', 'f1', 'f2', 'f3', 'f4'] +2 more,'RuntimeError: boom' +2 more), with singular and plural counts, plus thedropped_guard_types/kept_guard_typesproperties.test_summary_pickle_and_hashround-trips a fully populated summary (every field set, includingdropped_guard_codeandcapture_errors) throughpickle, checks that the copy compares and hashes equal, pins that summary's digest (the only golden with all eight clauses:badalready pinned notes before the shouted UNCOVERED, TRUNCATED, BYPASSED, CAPTURE ERROR order, and this one adds1 policy-dropped guardand1 value-pinned sourcebetween the RISKY clause and UNCOVERED, which no other fixture places), and checks that positional construction raises the keyword-onlyTypeError. OnlyPrecompileSummaryis round-tripped here:GuardFactgets its own round-trip with its keyword-only change two commits up, which also deletesFrameInvariantsas unused.test_summary_guard_lists_aggregate_over_framespins the multi-frame case: one slot listed as dropped, risky and policy-dropped at once constructs, is counted once bydropped_guard_types, and renders once in each digest clause. Its comment credits the risky classification to the slot telling its frame's variants apart, not to the risky-drop lint, which waives a builtin read the ordinary way (_reads_a_builtin).Every policy-dropped fixture slot is a
BUILTIN_MATCHonG['__builtins_dict___<n>']['len'], one of the four serializable types the default filter keeps and_INVARIANT_DROPPABLE_GUARD_TYPESlets the policy drop, and the only one of them with a source (DUAL_LEVEL,FUNCTORCH_STACK_MATCHandAUTOGRAD_SAVED_TENSORS_HOOKSare global-state guards); aCONSTANT_MATCHorHASATTRis_SHAPE_BEARING_GUARD_TYPES, never policy-dropped, so a fixture placing one on the policy side would pin a state the producer cannot emit. Likewise every fixture that lists awont_generalizesource keeps anEQUALS_MATCHon that bare name, since_wont_generalizereturns nothing unless a kept slot passes_pins_a_value.Test Plan:
Authored with an AI assistant.
🤖 Generated with Claude Code
Co-Authored-By: Claude Fable 5.1 [email protected]
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98