Skip to content

[precompile] Add PrecompileSummary, the coverage and guard report of a capture (#197260) - #197964

Closed
bobrenjc93 wants to merge 1 commit into
gh/bobrenjc93/1378/basefrom
gh/bobrenjc93/1378/head
Closed

bobrenjc93 wants to merge 1 commit into
gh/bobrenjc93/1378/basefrom
gh/bobrenjc93/1378/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

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-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

@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_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, 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:

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 forwards 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:

# 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

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).

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

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

Co-Authored-By: Claude Fable 5.1 [email protected]

Reverted in 94990b8 as a dependent of #197262 and back in the stack unchanged.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/197964

Note: Links to docs will display an error until the docs builds have been completed.

⏳ No Failures, 36 Pending

As of commit 41d7a53 with merge base d78bbf2 (image):
💚 Looks good so far! There are no failures yet. 💚

🟢 GREEN LIGHT - PR approved to be merged without human review:

  • Scope
    • Adds only PrecompileSummary to torch/compiler/_precompile_types.py plus four tests in test/test_precompile.py; the sole import collections is stdlib.
    • No producer or consumer exists yet: the only other PrecompileSummary hit in the tree is a docstring reference in torch/_dynamo/precompile_package.py:64, not an import.
    • Private module (leading underscore), so no public API or documented-behavior change lands here.
  • Correctness
    • Traced every __str__ clause against each assertExpectedInline golden: clause order, count's singular/plural, some's five-entry cut with +N more, and the repr of the first non-empty capture-error line all agree.
    • complete's six terms match test_summary_complete_requires_every_term, including that the guard fields never flip it to False.
    • dropped_guard_types / kept_guard_types use collections.Counter over slot tuples, matching {'HASATTR': 1, 'ID_MATCH': 2} in test_summary_digest_and_guard_type_counts.
  • Testing
    • test_summary_pickle_and_hash round-trips a fully populated summary and pins the keyword-only TypeError the kw_only=True dataclass raises.
    • test_summary_guard_lists_aggregate_over_frames pins the one-slot-in-three-lists case the docstring states but deliberately does not enforce.
  • Safety
    • No secrets, no eval/exec/deserialization of external input, no CI workflow or gate edits; the diff touches no pull.yml or trunk.yml.
    • Removes no error handling or validation; the type is additive and the relations are documented as stated-not-checked so a bookkeeping collision cannot drop the report.

reason: clean
Reviewed commit: 41d7a53

Inference job

🐛 Report a wrong verdict

This comment was automatically generated by Dr. CI and updates every 15 minutes.

This was referenced Sep 21, 2026
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
… by its name (#197264) (#197965)

**Summary.** `_is_library_module(name)` answers whether torch or the standard library owns a module, which is the waiver the risky-drop lint (added two commits later) applies to a dropped identity guard on a library-owned value. A name is not an identity: `graphlib`, `queue`, `code` and `distutils` are all stdlib names a third party ships, and `import distutils` in a default setuptools install actually resolves to `site-packages/setuptools/_distutils`, selected by `SETUPTOOLS_USE_DISTUTILS`, which is exactly the config-chooses-the-implementation shape the lint exists to catch. So the top-level module must RESOLVE to code shipped with the interpreter, judged by the previous commit's `_located` (a placed `__file__`, else the inittab or the frozen table). Every imported dotted ancestor of the name is checked the same way, but an inner name only has to not be located ELSEWHERE: `pyexpat.errors` (registered by pyexpat's C init with neither `__file__` nor `__spec__`) and `torch.ops` (a `ModuleType` subclass whose `__file__` is a class attribute the module dict never sees) keep their waiver because their packages are located, while a shadowed submodule (a `collections.abc` under `site-packages`, a `torch.foo` outside the torch roots) loses it. A top-level name that is not imported or carries no location evidence (a namespace package, an exec'd module) and `None` are all untrusted. The torch arm alone has an escape hatch, and the docstring says so: a frozen torch gives `_torch_roots` nothing to anchor to, and then every torch name is waived on its name with no location evidence.

## Behaviour pinned by the tests

```python
from torch._dynamo import precompile_package as pp

stdlib_root = sysconfig.get_paths()["stdlib"]
shadowed = types.ModuleType("graphlib")
shadowed.__file__ = os.path.join(stdlib_root, "site-packages", "graphlib", "__init__.py")
with mock.patch.dict(sys.modules, {"graphlib": shadowed}), mock.patch.object(pp, "_install_roots", return_value=()):
    pp._is_library_module("graphlib")      # False: under an install dir, even though under the stdlib root and no install root is known

vendored = types.ModuleType("graphlib")    # no site-packages component in the path
vendored.__file__ = os.path.join(stdlib_root, "vendored", "graphlib", "__init__.py")
with mock.patch.dict(sys.modules, {"graphlib": vendored}), mock.patch.object(pp, "_install_roots", return_value=(pp._norm(os.path.join(stdlib_root, "vendored")),)):
    pp._is_library_module("graphlib")      # False: only the install-root exclusion catches this one
pp._classify_file.cache_clear()            # the verdict is cached per __file__
with mock.patch.dict(sys.modules, {"graphlib": vendored}), mock.patch.object(pp, "_install_roots", return_value=()):
    pp._is_library_module("graphlib")      # True: the same file is stdlib once nothing is installed there

with mock.patch.dict(sys.modules, {"graphlib": types.ModuleType("graphlib")}):
    pp._is_library_module("graphlib")      # False: no __file__, no __spec__ -- no evidence

fake_torch = types.ModuleType("torch")
fake_torch.__file__ = os.path.join(stdlib_root, "torch", "__init__.py")   # the stdlib dir itself is never a pip target
with mock.patch.dict(sys.modules, {"torch": fake_torch}):
    pp._is_library_module("torch")         # False: the top-level check, torch resolving outside the torch roots
foo = types.ModuleType("torch.foo")
foo.__file__ = os.path.join(stdlib_root, "torch", "foo.py")
with mock.patch.dict(sys.modules, {"torch.foo": foo}):
    pp._is_library_module("torch.foo")     # False: the ancestor loop, a located torch does not vouch for it
foo.__file__ = "foo.py"
with mock.patch.dict(sys.modules, {"torch.foo": foo}):
    pp._is_library_module("torch.foo")     # True: a relative __file__ is no evidence, and an inner name needs none
pp._is_library_module("collections.never_imported")   # True: an inner name that is not imported has nothing to check
with mock.patch.object(pp, "_torch_roots", return_value=()):
    pp._is_library_module("torch.never_imported")   # True: frozen torch, waived on the name alone

sub = types.ModuleType("sys.sub")
sub.__spec__ = importlib.machinery.ModuleSpec("sys.sub", importlib.machinery.BuiltinImporter, origin="built-in")
with mock.patch.dict(sys.modules, {"sys.sub": sub}):
    pp._is_library_module("sys.sub")       # False: "sys.sub" is not in sys.builtin_module_names, "sys" is

# On 3.11+ every frozen stdlib module also carries an absolute __file__ (whenever sys._stdlib_dir is
# known), so the real zipimport is decided by its path; a module dict without one reaches the frozen table.
frozen = importlib.machinery.FrozenImporter
zipimport_frozen = types.ModuleType("zipimport")
zipimport_frozen.__spec__ = importlib.machinery.ModuleSpec("zipimport", frozen, origin="frozen")
with mock.patch.dict(sys.modules, {"zipimport": zipimport_frozen}):
    pp._is_library_module("zipimport")     # True: the frozen table has zipimport
graphlib_frozen = types.ModuleType("graphlib")
graphlib_frozen.__spec__ = importlib.machinery.ModuleSpec("graphlib", frozen, origin="frozen")
with mock.patch.dict(sys.modules, {"graphlib": graphlib_frozen}):
    pp._is_library_module("graphlib")      # False: a frozen spec under a name the frozen table does not have

pp._is_library_module("torch._C._nn")      # True: located parent torch._C; _nn (no __file__, no __spec__) carries no evidence of its own
pp._is_library_module("pyexpat.errors")    # True: located parent, submodule (no __file__, no __spec__) not located elsewhere
pp._is_library_module("collections.abc")   # True, unless sys.modules["collections.abc"] resolves to site-packages
pp._is_library_module("not_a_stdlib_name") # False: not a stdlib name
with mock.patch.dict(sys.modules):
    sys.modules.pop("graphlib", None)
    pp._is_library_module("graphlib")      # False: a stdlib name that is not imported
pp._is_library_module(None)                # False
```

## The tests

Two module-level fixtures carry the rows. `_STDLIB_ROOT` is sysconfig's `stdlib`, the path every shadow row with an absolute `__file__` is spelled under and the directory the relative row is judged from (the stdlib dir itself is never a pip target, so no torch root holds the torch rows, while `site-packages/torch` IS one wherever purelib nests under stdlib). `_NOT_LIBRARY_MODULES` is a table of shadow modules, one row per refused shape, each labelled by the check that refuses it: under an install dir with `_install_roots` patched to `()` (only `_INSTALL_DIR_NAMES` refuses it), under a nested install root with no `site-packages` component (only the `_install_roots` exclusion does), no file and no spec, a relative file (judged with the cwd at `_STDLIB_ROOT`, where the real `graphlib.py` sits, so that without the `isabs` gate the name would resolve to stdlib and be waived), `torch` itself and `torch.foo` outside the torch roots (the top-level check and the ancestor loop), a dotted name under a built-in top (by spec; the `__loader__` leg is `_located`'s and pinned by its own tests), a frozen spec under a non-frozen name and a shadowed `collections.abc`; a `__file__` with an embedded NUL has no row, because `_is_library_module` refuses it whether `_classify_file`'s NUL gate answers None or `_norm` raises out of `_located` (the gate is pinned by `_classify_file`'s own tests).

`test_library_module_requires_the_name_to_resolve_to_the_library` is parametrized over `_NOT_LIBRARY_MODULES` so a regression names its row; the rows are built from `types.ModuleType` objects patched into `sys.modules` with `_install_roots` patched per row, so nothing touches the real interpreter layout, and the test clears `_classify_file`'s cache first, because that verdict is cached per `__file__` while `_install_roots` is patched per row, so a verdict another test left for a row's file would be read back under the wrong roots. Every row here is a refusal: no `True` path is exercised by this commit's test, so on its own it cannot tell the function from `return False`. The waiver side (the real torch and stdlib names, the evidence-only-at-the-top rule, and the location-free refusals: not a stdlib name, not imported, `None`) is pinned by the next commit's tests, which is where the code block above is exercised in full.

Test Plan:

```
python test/dynamo/test_precompile_package.py -k test_library_module
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 01ab03e as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197965
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
…nd the evidence-only-at-the-top rule (#197595) (#197966)

**Summary.** Tests only, for `_is_library_module` from the previous commit. That commit pins every shape the predicate refuses; this one pins what it must keep waiving: the real torch and stdlib names as they are laid out in the running interpreter, and the rule that location evidence is demanded only of the top-level name of a dotted module, never of its inner names. It is a separate commit so each half stays small enough to review in one sitting; the code is unchanged.

## Behaviour pinned by the tests

```python
from torch._dynamo import precompile_package as pp

pp._is_library_module("torch._C._nn")      # True: located parent torch._C; _nn (no __file__, no __spec__) carries no evidence of its own
pp._is_library_module("pyexpat.errors")    # True: located parent, submodule (no __file__, no __spec__) not located elsewhere
pp._is_library_module("collections.abc")   # True, unless sys.modules["collections.abc"] resolves to site-packages
pp._is_library_module("collections.never_imported")   # True: an inner name that is not imported has nothing to check
with mock.patch.object(pp, "_torch_roots", return_value=()):
    pp._is_library_module("torch.never_imported")   # True: frozen torch, waived on the name alone
foo = types.ModuleType("torch.foo")
foo.__file__ = "foo.py"
with mock.patch.dict(sys.modules, {"torch.foo": foo}):
    pp._is_library_module("torch.foo")     # True: a relative __file__ is no evidence, and an inner name needs none
with mock.patch.dict(sys.modules):
    sys.modules.pop("graphlib", None)
    pp._is_library_module("graphlib")      # False: a stdlib name that is not imported
pp._is_library_module("not_a_stdlib_name") # False: not a stdlib name
pp._is_library_module(None)                # False
```

## The tests

`_LIBRARY_NAMES` lists the torch and stdlib names that must keep their waiver, including the evidence-free inner names `torch._C._nn`, `torch.ops`, `pyexpat.errors` and `xml.parsers.expat.model`; the header's `import xml.parsers.expat` keeps the last one's top-level name in `sys.modules`, which a waiver requires. `test_library_module_keeps_the_waiver_for_the_real_library` is parametrized over it and clears `_classify_file`'s cache first, so it reads the real layout rather than a verdict a sibling interned under patched roots.

`test_library_module_needs_location_evidence_only_at_the_top` pins an unimported stdlib name, a non-stdlib name and `None` as untrusted, a relative `__file__` on an inner name keeping the waiver, an inner name that is not imported keeping it too (nothing under the name to check, and the package is located), the `under_a_nested_install_root` row's own file being stdlib once nothing is installed there, the frozen table's True on a fabricated file-less `zipimport`, and the frozen-torch early True.

Test Plan:

```
python test/dynamo/test_precompile_package.py -k test_library_module
lintrunner 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 c654400 as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197966
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
…rd hangs off (#197265) (#197967)

**Summary.** Dynamo guards every module it walks through, so the path down to `F.gelu` is guarded module by module, and that is what lets a dropped identity guard on an attribute be recognised as a read off a namespace rather than off an object a config could have swapped. `_module_namespaces(entries)` collects the module-valued guard entries rooted at a `GlobalSource` and returns the TRUSTED ones, mapped from source name to module. `_source_root(source)`, a one-line walk down `ChainedSource.base` to the root, is added here as the helper that finds that `GlobalSource`. A module is trusted if torch or the stdlib owns it (`_is_library_module`), if it is bound under its own name (`import mypkg`, or the `__import_x` alias Dynamo installs to reach an inlined function's globals, recognised through `_dynamo_alias_module`), or if it is an attribute of a trusted module under a name that module already owns: its own `__name__` (a plain `import own_sub` inside the parent) or the parent's name plus the attribute (`from . import sub`, and `import mypkg.layers`, which Dynamo guards as `G['mypkg'].layers`). An ALIASED user module is none of those: `if flag: import impl_b as impl` picks what `impl.op` resolves to per machine, and so does `from . import impl_b as impl` in a package `__init__`; inheriting the parent's trust without checking the name is what let that shape through in an earlier round. Library ownership is trusted under any binding, `import torch.nn.functional as F` included; the price, taken deliberately because flagging `F` would flag every model, is that an alias config picks between two torch modules is waived too, which `_is_risky_drop`'s KNOWN GAP records. Dynamo never guards a bare `__import_torch` alias, only the attributes read off it, so aliases with no module-valued entry are recovered from their name rather than treating `torch.Tensor` as a config-swappable slot. A config module (`torch.utils._config_module.ConfigModule`, e.g. `torch._dynamo.config`) is the one namespace whose bindings config chooses by definition, so it is never trusted, whoever owns it and however it is reached: the check is a trust verdict inside `is_trusted`, not a filter on what is collected, so a config module recovered from an `__import_x` alias (`from torch._dynamo.config import verbose` in an inlined function) is refused the same way as one bound under a plain name.

## Which namespaces are trusted

```python
import mypkg                 # G['mypkg']: trusted, bound under its own name
import mypkg.layers          # G['mypkg'].layers: trusted, mypkg is and owns the name mypkg.layers
import torch.nn.functional as F   # trusted: torch owns it, whatever the alias
import impl_b as impl        # NOT trusted: the alias is a slot the import picked
impl.deep                    # NOT trusted: a name impl owns, but impl itself is not trusted
config = torch._dynamo.config     # NOT trusted: a config module, whoever owns it
from torch._dynamo.config import verbose  # NOT trusted either: G['__import_torch_dot__dynamo_dot_config'] is recovered, then refused

# inside a trusted package __init__:
from . import sub            # trusted: module.__name__ == "mypkg.sub" == f"{parent}.sub"
from . import impl_b as impl # NOT trusted: "mypkg.impl_b" is neither "impl" nor "mypkg.impl"
```

The result feeds `_is_risky_drop` (next commit): a dropped guard whose source is in the returned dict, or whose `source.base.name` is one of its keys (an exact lookup, never a prefix match), is judged by the namespace's owner rather than flagged outright. `test_module_namespaces_trust_only_bindings_config_cannot_repoint` builds each shape above from hand-made `GuardFilterEntry` values and asserts the exact trusted set.

Test Plan:

```
python test/dynamo/test_precompile_package.py -k test_module_namespaces_trust_only_bindings_config_cannot_repoint
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 fde4ed9 as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197967
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
…r compared (#197267) (#197968)

**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_TYPES` are 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_TYPES` are 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 of `GuardBuilder`'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

```python
from torch._dynamo.precompile_package import _SHAPE_BEARING_GUARD_TYPES, _UNMODELLED_GUARD_TYPES

len(_SHAPE_BEARING_GUARD_TYPES), len(_UNMODELLED_GUARD_TYPES)  # (24, 12)
_SHAPE_BEARING_GUARD_TYPES & _UNMODELLED_GUARD_TYPES           # frozenset()
"TENSOR_MATCH" in _SHAPE_BEARING_GUARD_TYPES                   # True: compared, never dropped
"SHAPE_ENV" in _UNMODELLED_GUARD_TYPES                         # True: never compared, never dropped
"ID_MATCH" in _SHAPE_BEARING_GUARD_TYPES | _UNMODELLED_GUARD_TYPES   # False: classified next commit
```

Test Plan:

```
python -c "import torch._dynamo.precompile_package"
lintrunner torch/_dynamo/precompile_package.py
```

The classification tests land with the next commit, which adds the other two sets; run there:

```
python test/dynamo/test_precompile_package.py -k test_guard_policy_classification_is_total
python test/dynamo/test_precompile_package.py -k guard_type
```

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 c51118f as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197968
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967
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
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1378/head branch November 26, 2026 01:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants