Skip to content

[precompile] Render a multi-graph capture as a standalone artifact pair - #198136

Closed
bobrenjc93 wants to merge 31 commits into
gh/bobrenjc93/1444/basefrom
gh/bobrenjc93/1444/head
Closed

bobrenjc93 wants to merge 31 commits into
gh/bobrenjc93/1444/basefrom
gh/bobrenjc93/1444/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Problem. The multi-graph driver landed with the frame records it rebuilds from (_multigraph_frames, _serving_mode, _reject_uninstallable_entry, _entry_binding) but nothing that writes the artifact it runs in, so a Dynamo CompilePackage capture still has no (python_code, cache) form that load can read.

Fix. Add the writer: _build_multigraph_python_source renders the cache entry, its backend artifacts and a PrecompileSummary as python_code (readable metadata beside three opaque blobs, then the inlined driver), and _build_multigraph_artifact wraps it into the pair, refusing a capture the standalone driver cannot serve faithfully and writing the tagged cache envelope.

Summary. The multi-graph driver (_emit_multigraph_driver_source) and the frame-record helpers it rebuilds from were already in place, but nothing rendered a Dynamo CompilePackage cache entry into the python_code the driver runs in, so a multi-graph capture could not be written to disk or reloaded. This commit adds _build_multigraph_python_source, which emits the readable metadata (BACKEND, TRACER = "dynamo", SERVING_MODE = "standalone", FN_NAME, the per-frame variant counts, the dropped, risky and pinned guard lists, the two version locks) as top-level literals beside the three opaque blobs the inlined driver rebuilds from (_ENTRY_BINDING, _FRAMES, _BACKENDS), followed by the driver section. _build_multigraph_artifact wraps that into the (python_code, cache) pair: it runs the existing entry refusals, then refuses a capture whose compiled frames the entry cannot reach (they would run eager, silently giving up the compiled variant), and writes the cache envelope tagged tracer: "dynamo" with the inductor bundle CacheArtifactManager.serialize() returns for a capture that ran under a fresh cache. The key constraint is that the metadata set emitted is exactly the one _parse_artifact_metadata already requires for TRACER == "dynamo", so the existing AST-walk loader recovers it without executing the artifact, and with two front-ends now producing pairs the cache envelope carries a tracer tag on both ("dynamo" here, "make_fx" from PrecompiledModule.to_cache_bytes) that _runnable_from_pair checks against the source's TRACER the way it checks the backend, absence on either side reading as make_fx so pairs written before the tag load unchanged. The compiled subgraphs stay pickled rather than rendered as source; that is a follow-up, and the artifact header says so.

Where this fits

The stack replaces the callable torch.compiler.precompile(fn, *example_inputs) (trace once on inputs passed up front, pair returned in memory) with a caller-driven context manager: capture(fn, artifact_path=, cache_path=) is entered with a with block, the caller calls it on as many example inputs as they like (each graph break and recompiled variant is folded in), the (python_code, cache) pair is written to the two files on exit, and load(artifact_path, cache_path) serves it in a fresh process. The end-to-end example and the PR-by-PR map live in #197993's "The new API, end to end" section. This PR is plumbing for the multi-call DynamoTracer capture (#198138): it renders a multi-graph capture as one standalone artifact.

The readable head of the rendered artifact

_build_multigraph_python_source writes _MULTIGRAPH_GENERATED_HEADER, then _SERVING_NOTES["standalone"], then section 1, whose every value is a Python literal. Schematically, for the test's two-shape capture of a step with one graph break on the eager backend:

# Generated by torch.compiler.precompile (multi-graph) -- do not edit.
# ...
# Sections below are labelled. What is OPAQUE is base64 of pickled Dynamo state --
# the guard trees, the transformed bytecode and the compiled subgraphs -- because
# those have no readable source form here. Everything else is meant to be read and
# reviewed.
# Nothing is installed onto your code objects and no frame evaluator is involved; ...

# ======================================================================
# 1. What was captured (readable)
# ======================================================================
BACKEND = 'eager'
TRACER = "dynamo"
SERVING_MODE = "standalone"
FN_NAME = '...step'                      # entry.fn_name
_DYNAMO_PYTHON_VERSION = (3, 12)         # locks the marshalled bytecode
TORCH_VERSION = '2.x...'                 # locks the pickled guard state

# frame name -> number of captured variants. ...
FRAMES = [
    ('step', 2),
    ('torch_dynamo_resume_in_step_at_<line>', 2),
]

# Guards that could NOT be serialized and are therefore not checked at
# serve time. ...
DROPPED_GUARDS = [['MODULE_MATCH', 'model']]
RISKY_DROPPED_GUARDS = []

# What a dropped slot above actually checked, where it renders one.
DROPPED_GUARD_CODE = []

# Values pinned to exactly what capture saw; any other value misses.
WONT_GENERALIZE = ()

# The entry's default arguments: a code object carries none, and the
# driver rebuilds the entry from one.
_ENTRY_BINDING = '<base64 pickle>'

Each FRAMES row is (frame["code"].co_name, len(frame["variants"])) over the frames list _build_multigraph_artifact computed once with _multigraph_frames(entry); the guard lists come straight from the PrecompileSummary (dropped_guards, risky_dropped_guards, dropped_guard_code, wont_generalize). _ENTRY_BINDING is _b64(entry_binding); if the entry's defaults do not pickle, the renderer raises a PrecompileError naming the entry and saying defaults must be picklable, instead of letting the pickle error surface raw.

The header text changed with this commit: the parent's header promised that compiled subgraphs "DO have [a readable form] and are emitted as source"; the new header lists them with the guard trees and bytecode as OPAQUE, because that is what this renderer does today.

The opaque blobs and the driver

Sections 2 to 4 follow the readable head:

# 2. Guard trees and transformed bytecode -- OPAQUE
# base64(pickle) of one record per frame: the frame's code object, its
# variants' serialized guard state and Dynamo bytecode, and the globals it reads. ...
_FRAMES = '<base64 pickle of _multigraph_frames(entry)>'

# 3. Compiled subgraphs -- OPAQUE
# base64(pickle) of the backend artifacts the frames call by name: the
# bundled AOTAutograd entries (inductor) or the captured fx graphs (eager).
_BACKENDS = '<base64 pickle of dict(backends)>'

# 4. Driver: rebuild the guards, wire the names, dispatch (readable)
<_emit_multigraph_driver_source()>

The driver section is the one _emit_multigraph_driver_source already emits; this commit adds no driver logic. The set of names emitted above -- BACKEND, FN_NAME, FRAMES, DROPPED_GUARDS, RISKY_DROPPED_GUARDS, WONT_GENERALIZE, _FRAMES, _BACKENDS, _DYNAMO_PYTHON_VERSION, _ENTRY_BINDING, TORCH_VERSION -- is exactly the wanted set _parse_artifact_metadata requires when TRACER == "dynamo" and SERVING_MODE is not "installed", so load reads it with the existing AST walk and literal_eval, never executing the artifact.

Refusals before anything is rendered

_build_multigraph_artifact first runs _reject_uninstallable_entry(frames, entry), the existing entry refusals, unchanged. That has to come first: an entry with no variant (a bypassed entry, say) reaches nothing, and the reachability check below would misreport it as a graph break to move. It then computes _reachable_frames(frames) -- the entry, plus any continuation some already-reachable frame's bytecode names -- and refuses a capture with a compiled frame outside that set:

unreachable = sorted(
    f"{frame['python_module']}.{frame['code'].co_name}"
    for i, frame in enumerate(frames)
    if frame["variants"] and i not in reachable
)
if unreachable:
    raise PrecompileError(
        f"precompile captured frame(s) a standalone artifact cannot reach from "
        f"the entry {entry.fn_name!r}: {unreachable}. A source artifact "
        f"dispatches only the entry frame and the graph-break continuations its "
        f"bytecode names; a frame entered by an ordinary call -- a graph break "
        f"inside a child module's forward, say -- would run eager. ..."
    )

The asymmetry is deliberate. A reachable frame WITHOUT a variant is left to the driver, which raises at the call that reaches it, naming the gap. A frame WITH variants the entry cannot reach would instead run eager and silently give up its compiled variant, so that capture is refused up front, with the two remedies in the message (move the graph break into the entry, or make the child module compile in one piece). Only after both checks is the source rendered.

The cache half

python_code is self-contained -- it carries the frames, the guard trees and the compiled subgraphs -- so cache is the same acceleration it is for the make_fx form:

inductor_bundle = None
if backend != "eager":
    # The dynamo capture runs under with_fresh_cache(), so this is exactly
    # what the capture's compiles recorded.
    saved = CacheArtifactManager.serialize()
    inductor_bundle = None if saved is None else saved[0]
torch.save(
    {
        "format": _CACHE_FORMAT,
        "version": _CACHE_VERSION,
        "backend": backend,
        "tracer": "dynamo",
        "code_hash": hashlib.sha256(python_code.encode()).hexdigest(),
        "artifact": inductor_bundle,
    },
    buf,
)

The tracer: "dynamo" tag is what _runnable_from_pair's pairing check compares against the python_code's TRACER, so this cache cannot be served under a make_fx artifact or vice versa; the code_hash is the existing invariant-7 binding of the cache to this exact python_code.

The tracer tag and the pairing check

With two front-ends writing (python_code, cache) pairs, backend and code_hash alone no longer say which renderer a cache belongs to, so both envelopes now name their tracer. PrecompiledModule.to_cache_bytes writes "tracer": self._tracer ("make_fx", the only value it renders today) beside the existing keys, and the multi-graph writer above hardcodes "dynamo". _runnable_from_pair reads the source side from the parsed metadata and compares it before the code_hash check:

# TRACER is absent on make_fx artifacts predating the tag; the cache envelope
# defaults the same way, so an older pair still matches.
tracer = cast(str, meta.get("TRACER", "make_fx"))
...
if blob.get("tracer", "make_fx") != tracer:
    raise PrecompileError(
        f"cache tracer {blob.get('tracer', 'make_fx')!r} does not match "
        f"the python_code tracer {tracer!r}; the cache and python_code "
        "came from different precompile captures."
    )

The check sits next to the backend-mismatch refusal and uses the same wording, so a make_fx cache handed to a Dynamo source (or the reverse) is refused as a wrong pairing rather than reaching the code_hash comparison or the inductor cache priming. Only the make_fx renderer leaves TRACER out of python_code, so absence on the source side means make_fx, and an envelope with no tracer key defaults the same way: a pair written before this commit loads exactly as it did. load's docstring now lists tracer with backend and code_hash as the mismatches that are fatal, while a foreign format/version still only degrades to JIT.

Tests

test_multigraph_artifact_round_trips_a_hand_built_package fills a CompilePackage through torch._dynamo.optimize(backend="eager", package=package, guard_filter_fn=default_guard_filter_fn) on a step(model, x, *, scale=2.0) with a graph_break() and a second input shape, points the frame records at an importable alias of the test module (the driver refuses __main__), and renders with _build_multigraph_artifact(entry, backends, summary, "eager", step). It then checks the parsed metadata and the cache tag:

meta = _parse_artifact_metadata(python_code)
meta["TRACER"], meta["SERVING_MODE"], meta["BACKEND"]   # "dynamo", "standalone", "eager"
meta["FN_NAME"]                                          # step.__qualname__
[name for name, _ in meta["FRAMES"]]                     # co_name of every entry.codes[i]
meta["DROPPED_GUARDS"]                                   # [["MODULE_MATCH", "model"]]
blob = torch.load(io.BytesIO(cache), weights_only=True)
blob["tracer"], blob["artifact"]                         # "dynamo", None (eager backend)

After torch._dynamo.reset() and scrubbing the names Dynamo minted into the module during capture (so the guards cannot pass on tracing leftovers), _runnable_from_pair(python_code, cache, _trusted=True) reports installed == False, returns the eager-compiled results for both captured shapes, refuses x2.double() with "no captured variant", and refuses a make_fx cache from _precompile_pair(...) against the Dynamo source with a PrecompileError mentioning tracer. The same test then pins the two build-time refusals: patching step.__kwdefaults__ to {"scale": lambda: 2.0} makes _build_multigraph_artifact raise "defaults must be picklable", and marking entry.codes[0] bypassed with no guarded codes raises "entry frame was BYPASSED" rather than the unreachable-frame message.

test_multigraph_artifact_refuses_a_frame_the_entry_cannot_reach captures step(child, x) whose _GraphBreakingChild graph-breaks inside its own forward, so the child's forward compiles as a separate frame entered by an ordinary call; _build_multigraph_artifact refuses it with "cannot reach from the entry".

test_load_pairs_the_cache_on_its_tracer_tag covers the tag from the make_fx side: the envelope self._write produces reads blob["tracer"] == "make_fx"; rewriting the blob with "tracer": "dynamo" and reloading it against the same make_fx python_code raises a PrecompileError mentioning tracer; deleting the key and reloading serves self.model(self.x) unchanged, which is the pre-tag pair. The three envelope tests that pin the key set -- test_cache_holds_only_artifact, test_cache_envelope_is_weights_only_safe and test_backend_eager_no_inductor_lowering -- now expect {"artifact", "format", "version", "backend", "tracer", "code_hash"}.

Test Plan:

test_multigraph_artifact_round_trips_a_hand_built_package fills a package through torch._dynamo.optimize(package=...) with a graph break and a second shape, renders it, checks the parsed metadata and the cache tag, serves both captured calls through _runnable_from_pair after a Dynamo reset (and refuses an uncovered dtype), refuses a make_fx cache against the Dynamo source, an unpicklable default, and a bypassed entry (as bypassed, not as an unreachable continuation); test_multigraph_artifact_refuses_a_frame_the_entry_cannot_reach graph-breaks inside a child module's forward; test_load_pairs_the_cache_on_its_tracer_tag covers the tag present, altered and absent, and the three envelope tests that pin the key set gain it.

python test/test_precompile.py
lintrunner -a torch/_precompile.py test/test_precompile.py

Authored with an AI assistant.

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 3 Cancelled Jobs, 1 Unrelated Failure

As of commit f1ffba7 with merge base 12a7c44 (image):

🟡 GREEN LIGHT - PR requires human review:

  • Triviality
    • New feature, not a trivial class: adds _build_multigraph_python_source and _build_multigraph_artifact (~180 lines) in torch/_precompile.py
    • New refusal logic (unreachable-frame, unpicklable-defaults) is design a reviewer would weigh, as the PR thread's review rounds show
  • Serialized format and load behavior
    • to_cache_bytes adds a tracer key to the cache envelope while _CACHE_VERSION stays at 1
    • _runnable_from_pair gains a hard-failing PrecompileError on a tracer mismatch, which changes what load accepts
  • Design dispositions for a human
    • The author declined to route through _serving_mode, relying on a gate in #​198216 that is not in this checkout
    • The inductor bundle comes from process-global CacheArtifactManager.serialize(), with only a docstring precondition

reason: not_trivial
Reviewed commit: f1ffba7

Inference job

🐛 Report a wrong verdict

CANCELLED JOBS - The following jobs were cancelled. Please retry:

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93 bobrenjc93 changed the title [precompile] Render a multi-graph capture as a standalone artifact pair [no-ci] [precompile] Render a multi-graph capture as a standalone artifact pair Sep 22, 2026
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93 bobrenjc93 added ciflow/trunk Trigger trunk jobs on your pull request topic: not user facing topic category labels Sep 22, 2026
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
pytorchmergebot pushed a commit that referenced this pull request Sep 29, 2026
…#198137)

**Problem.** `torch/_dynamo/precompile_package.py` held the pieces of a multi-graph capture -- the guard filter, the compiler configuration, the guard classification, the summary builder -- but nothing drove them, so no caller could record a function's compiled variants.

**Fix.** Add `PrecompileSession`, a context manager that compiles the function into a fresh `CompilePackage` under a recording guard filter and reports what the calls covered as a `PrecompileSummary`, with `precompile_capture(fn, *, backend, guard_filter_fn, recompile_limit, dynamic)` as its entry point.

**Summary.** The module had `default_guard_filter_fn`, `_capture_config`, the guard classification and `_summarize`, but no driver, so nothing under `torch/` could capture a function's variants. `PrecompileSession` is that driver: entering it compiles `fn` through `torch._dynamo.optimize` with a fresh `CompilePackage`, a filter that records every kept and dropped guard slot, the caller's `dynamic` and `recompile_limit`, and `isolate_recompiles=True`, and hands back a callable whose calls run under `_capture_config`. That callable records any exception a call raised for the summary and, after every call, takes the bundled AOTAutograd artifacts filed under its backend ids out of `PrecompileContext` with the new `take_artifact`, so another capture's `clear()` between calls cannot lose them. The key constraint is that the filter runs once per compilation, spells every slot through `_normalize` so the kept, dropped and risky sets and the facts compare with each other, and keys its `GuardFact` set by the code object the new `CompilePackage.current_entry` property names, which lets `summary()` report a dropped slot whose source held different values across a frame's variants as risky. Rendering the session as an artifact behind the coverage and guard gates is the next PR; the guard-drop invariance policy, the drift probe and the installed serving mode of the reference stack are out by design, and `truncated` is always empty.

## Where this fits

The stack replaces the callable `torch.compiler.precompile(fn, *example_inputs)` (trace once on inputs passed up front, pair returned in memory) with a caller-driven context manager: `capture(fn, artifact_path=, cache_path=)` is entered with a `with` block, the caller calls it on as many example inputs as they like (each graph break and recompiled variant is folded in), the `(python_code, cache)` pair is written to the two files on exit, and `load(artifact_path, cache_path)` serves it in a fresh process. The end-to-end example and the PR-by-PR map live in #197993's "The new API, end to end" section. This PR adds `PrecompileSession`, the multi-graph capture that the multi-call `DynamoTracer` front-end of `capture()` (#198138) is built on.

## Entering a session

The new test drives a graph-breaking step at two shapes and reads the summary inside the block:

```python
from torch._dynamo.precompile_package import precompile_capture

def step(model, x):
    y = model(x)
    torch._dynamo.graph_break()
    return y.sum(dim=0) + y.shape[0]

model = torch.nn.Linear(4, 4)
x2, x3 = torch.ones(2, 4), torch.ones(3, 4)
session = precompile_capture(step, backend="eager")
with session as call:
    call(model, x2)   # compiles step and its graph-break continuation
    call(model, x3)   # recompiles both for the second shape
    summary = session.summary()
call(model, x2)       # PackageError: "PrecompileSession is not active"
```

`__enter__` does one thing:

```python
self._compiled = torch._dynamo.optimize(
    self._backend,
    package=self._package,              # a fresh CompilePackage(fn)
    guard_filter_fn=self._guard_filter_fn,
    dynamic=self._dynamic,
    recompile_limit=self._recompile_limit,
    isolate_recompiles=True,
)(self._fn)
return self._call
```

`isolate_recompiles=True` gives the package its own cache region: a function captured (or compiled) earlier in the process would otherwise serve its existing cache entries and this package would record nothing. The test pins this by opening a `second` session on the same `step` after the first and checking `second.summary().guarded_codes >= 2`. A session cannot be re-entered: the test re-enters the finished `session` and expects `PackageError` ("cannot be re-entered; start a new capture").

## Each call runs under the capture configuration

The configuration is per call, not per block, so user code between calls (`optimizer.step`, data loading, a later `save()`) runs in the ambient configuration:

```python
def _call(self, *args, **kwargs):
    if self._compiled is None or self._finished:
        raise PackageError("PrecompileSession is not active")
    limit = max(self._recompile_limit, torch._dynamo.config.accumulated_recompile_limit)
    try:
        with _capture_config(), torch._dynamo.config.patch(accumulated_recompile_limit=limit):
            return self._compiled(*args, **kwargs)
    except Exception as e:
        message = f"{type(e).__name__}: {e}"
        if message not in self._capture_errors:
            self._capture_errors.append(message)
        raise
    finally:
        self._take_backend_artifacts()
```

The ambient `accumulated_recompile_limit` is raised to at least the per-frame limit so the explicit `recompile_limit` is the effective one. An `Exception` is recorded once (deduplicated by message) and re-raised; a `BaseException` such as `KeyboardInterrupt` is not a capture error and propagates unrecorded. Either way the `finally` takes the call's backend artifacts (see "Taking the backend artifacts after every call" below). The test calls `call(model, torch.ones(2, 5))` on a `Linear(4, 4)`, catches the `RuntimeError`, and checks `failed.summary().complete` is false with exactly one `capture_errors` entry.

## The recording guard filter

A dropped guard does not fail at serving time; it silently widens what a graph is reused for, so the drops have to be inspectable. The session wraps `default_guard_filter_fn` (or the caller's filter) and, per compilation, records the decision for every `(guard_type, source)` slot:

```python
decisions = list(inner(entries))
default_kept = default_guard_filter_fn(entries) if self._custom_guard_filter else decisions
for keep, by_default, entry in zip(decisions, default_kept, entries):
    slot = (entry.guard_type, _normalize(strip_local_scope(entry.name)))
    enforced = keep or (_is_noop_guard_type(entry.guard_type) and global_state_kept)
    if enforced:
        self._kept_guards.add(slot)
    else:
        self._dropped_guards.add(slot)
        if rendered := " ; ".join(_render_code(entry.code_parts)):
            self._dropped_guard_code.setdefault(slot, rendered)
        if by_default or _is_risky_drop(entry, namespaces):
            self._risky_dropped_guards.add(slot)
    if entry.guard_type not in _UNMODELLED_GUARD_TYPES:
        facts.add(_GuardFact(guard_type=..., source=slot[1], code=..., value=_value_fingerprint(entry), enforced=enforced))
```

Every slot is normalized once, and `GuardFact.source` reuses `slot[1]`, so the dropped, risky and kept sets and the per-variant facts share one spelling and compare as equals. A dropped slot's rendered code is recorded only when it renders to something. A no-op guard type counts as enforced when `GLOBAL_STATE` is kept, since that is where its check lives. A drop the default filter would not have made (`by_default` true under a custom filter) is risky by construction: nothing here can say what the caller gave up. The test pins this with a custom filter that drops every `TENSOR_MATCH`:

```python
custom = precompile_capture(step, backend="eager",
                            guard_filter_fn=lambda es: [e.guard_type != "TENSOR_MATCH" for e in es])
with custom as call:
    call(model, x2)
("TENSOR_MATCH", "x") in custom.summary().risky_dropped_guards   # True
``` Unmodelled guard types are never compared, so they contribute no fact. One filter call is one compilation, and the package knows which frame is being compiled, so the fact set is filed under that frame:

```python
current = self._package.current_entry          # new property on CompilePackage
code = current.python_code
key = (code.co_name, code.co_filename, code.co_firstlineno)   # else ("<unknown>", "<unknown>", 0)
self._guard_sets.setdefault(key, []).append(frozenset(facts))
```

## `summary()`

`summary()` feeds the recorded sets to the landed `_summarize`, adding one more risk rule first: a dropped slot whose source held different values across a frame's variants is risky, because that guard was what told the variants apart and cannot pick between them at serve time. Merely being absent from one variant (a `MODULE_MATCH` a branch does not touch) is not. `test_a_dropped_guard_that_tells_variants_apart_is_risky` pins the rule: it rebinds the same-file global def `_act` (whose `CLOSURE_MATCH` the default filter drops) between two `dynamic=False` calls of `_through_act`, and `("CLOSURE_MATCH", "G['_act']")` is reported risky only when the def changed between the variants; it fails with the rule removed.

```python
risky = set(self._risky_dropped_guards)
for variants in self._guard_sets.values():
    values = {}
    for facts in variants:
        for f in facts:
            if not f.enforced:
                values.setdefault((f.guard_type, f.source), set()).add(f.value)
    risky |= {slot for slot, seen in values.items() if len(seen) > 1}
return _summarize(self._package.cache_entry(), dropped=..., kept=..., policy_dropped=set(),
                  risky=risky, truncated=frozenset(), capture_errors=..., guard_sets=..., dropped_code=...)
```

For the two-shape capture above the test checks:

```python
summary.complete                                  # True
(summary.frames, summary.resume_functions)        # (2, 1): step and its continuation
summary.guarded_codes >= 3                        # recompiled for the second shape
"MODULE_MATCH" in summary.dropped_guard_types     # the default filter's drop
("CLOSURE_MATCH", "G['torch']._dynamo.graph_break") in summary.dropped_guards
summary.kept_guards                               # non-empty
summary.risky_dropped_guards                      # ()
```

## Taking the backend artifacts after every call

The AOTAutograd cache records a bundled entry under each graph's backend id as the graph compiles, into a process-global list on `PrecompileContext`. After every call, in `_call`'s `finally`, the session moves this package's entries out of that list through the new `take_artifact`, a `pop` next to `serialize_artifact_by_key`; `__exit__` only marks the session finished and drops the compiled callable:

```python
@classmethod
def take_artifact(cls, key: str) -> BackendCacheArtifact[Any] | None:
    return cls._backend_artifacts_by_key.pop(_BackendId(key), None)

# PrecompileSession._take_backend_artifacts
for backend_id in self._package.cache_entry().backend_ids:
    if backend_id not in self._backend_artifacts:
        artifact = PrecompileContext.take_artifact(backend_id)
        if artifact is not None:
            self._backend_artifacts[backend_id] = artifact
```

Taking them as the capture goes keeps another capture's `PrecompileContext.clear()` between calls from losing them. Ownership moves to the session: once taken, an id is no longer found by `serialize_artifact_by_key`, as the `take_artifact` docstring says.

## `precompile_capture` and what it refuses

`precompile_capture` builds the session after three up-front refusals, each pinned by the test:

```python
precompile_capture(functools.partial(step, model))   # PackageError: "... cannot capture a partial ..."
precompile_capture(model)                            # PackageError: "... capture the function that CALLS the model ..."
precompile_capture(model.forward)                    # PackageError: "... cannot capture a bound method ..."
```

A `functools.partial` is refused because its bound arguments are not on the code object. A bare `nn.Module` is refused because Dynamo compiles it through its own wrapper frame, whose graphs close over the module, which a standalone artifact cannot rebuild; the message suggests a module-level `def step(model, x): return model(x)`. A bound method (`types.MethodType`) is refused because the artifact rebuilds `fn` from its code object, whose first parameter is the receiver: a captured `model.forward` would be served as `f(model, x)` instead of `f(x)`, so the message points at a module-level function that takes the receiver as an argument. `recompile_limit` defaults to 256, well above Dynamo's usual 8, because a precompile deliberately wants one compiled variant per condition, whereas the normal limit exists to catch runaway recompilation. Runtime guards stay intact during capture: `guard_filter_fn` applies only to the serialized guard state, so every call observes the same recompilation behavior as ordinary `torch.compile`.

## Scope

Rendering the session as an artifact, behind the coverage and guard gates, is the next commit (#198216). Not here, by design: the guard-drop invariance policy, the drift probe and the installed serving mode of the reference stack; `truncated` is always empty. `test_precompile_session_captures_variants_and_summarizes` pins everything above except the varied-value rule, which `test_a_dropped_guard_that_tells_variants_apart_is_risky` pins.

Test Plan:

`test_precompile_session_captures_variants_and_summarizes` captures a graph-breaking step at two shapes and checks the summary (frames, continuation, variants, dropped and kept slots), the inactive-session and re-entry refusals, a call that raised, a second session on the same function, a custom filter's drop reported risky, and the partial/module/bound-method refusals. `test_a_dropped_guard_that_tells_variants_apart_is_risky` rebinds a same-file global def between two static-shape calls and checks the dropped slot is reported risky only when the def changed (it fails with the varied-value rule removed).

```
python test/dynamo/test_precompile_package.py
python test/dynamo/test_package.py
lintrunner -a torch/_dynamo/precompile_package.py torch/_dynamo/precompile_context.py torch/_dynamo/package.py test/dynamo/test_precompile_package.py
```

Authored with an AI assistant.

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

Pull Request resolved: #198137
Approved by: https://github.com/aorenste
ghstack dependencies: #198211, #198223, #198283, #198284, #197993, #198213, #198135, #198243, #198214, #198136, #198215
pytorchmergebot pushed a commit that referenced this pull request Oct 6, 2026
…e and guard gates (#198216)

**Problem.** A `PrecompileSession` can capture calls and report on them through `summary()`, but nothing turns what it captured into the `(python_code, cache)` artifact, so a caller-driven capture still cannot produce anything to save or load.

**Fix.** Add `PrecompileSession.snapshot_artifact()`, which runs the coverage and guard gates, gathers the compiled subgraphs by backend id, and hands them to `_build_multigraph_artifact`, while leaving the session open so a caller can checkpoint mid-block.

**Summary.** The parent commit's `PrecompileSession` runs the caller's calls under `_capture_config` and the wrapped guard filter and exposes `summary()`, but its docstring still says "Rendering the artifact is the next commit's", so a capture had no way to become an artifact. This commit adds `snapshot_artifact()`, which renders everything captured SO FAR as the `(python_code, cache)` pair and leaves the session able to capture more, which is what lets a caller checkpoint mid-block. It runs the gates first, through `_gated_summary`, so a refusal renders nothing: `require_no_risky_drops` refuses the risky dropped guards the summary reports (the rest, such as unserializable identity guards, are listed in the artifact), and `require_complete` a capture whose call raised, that compiled no code or no graph, or that left a frame uncovered or bypassed, and it refuses any other incomplete summary as a backstop; each refusal names a remedy, and every one except the no-compiled-code refusal also names the flag that accepts the gap. `_collect_backends` then gathers the compiled subgraphs by backend id -- the bundled AOTAutograd entries taken from `PrecompileContext` for inductor, the captured fx graphs and `noop_graph_call` wrapped as `EagerCacheArtifact`s for eager -- and names any id without a serializable artifact rather than writing an artifact that would fail at load. Both gates default on, and a capture whose dropped guards are all harmless renders, and `test_precompile_session_renders_behind_the_gates`, parametrized over the eager and inductor backends, pins the mid-block render, the after-exit render, the risky-drop refusal, and the no-compiled-code and raised-call refusals.

## Where this fits

The stack replaces the callable `torch.compiler.precompile(fn, *example_inputs)` (trace once on inputs passed up front, pair returned in memory) with a caller-driven context manager: `capture(fn, artifact_path=, cache_path=)` is entered with a `with` block, the caller calls it on as many example inputs as they like (each graph break and recompiled variant is folded in), the `(python_code, cache)` pair is written to the two files on exit, and `load(artifact_path, cache_path)` serves it in a fresh process. The end-to-end example and the PR-by-PR map live in #197993's "The new API, end to end" section. This PR renders a `PrecompileSession` as an artifact behind the coverage and guard gates; `capture(..., tracer=DynamoTracer())` (#198138) writes through it.

## Rendering mid-block and after exit

`snapshot_artifact()` does not finish the session. The test runs under `@parametrize("backend", ["eager", "inductor"])`; its fixture graph-breaks once, so each call produces two frames, and the mid-block render already shows both:

```python
def step(model, x):
    y = model(x)
    torch._dynamo.graph_break()
    return y.sum(dim=0) + y.shape[0]

model = torch.nn.Linear(4, 4)
session = precompile_package.precompile_capture(step, backend=backend)   # "eager" or "inductor"
with session as call:
    call(model, torch.ones(2, 4))
    python_code, cache = session.snapshot_artifact()   # mid-block checkpoint
    len(_parse_artifact_metadata(python_code)["FRAMES"])  # 2; the session stays open
    call(model, torch.ones(3, 4))                        # a second variant still captures
summary = session.summary()
python_code, cache = session.snapshot_artifact()         # after exit, renders both variants
```

The rendered metadata agrees with the summary: `meta["TRACER"] == "dynamo"`, `meta["FN_NAME"] == step.__qualname__`, `sum(n for _, n in meta["FRAMES"]) == summary.guarded_codes`, `meta["DROPPED_GUARDS"] == [list(s) for s in summary.dropped_guards]`, and `torch.load(io.BytesIO(cache), weights_only=True)` carries `(backend, "dynamo")` as its `backend` and `tracer` tag. Under inductor every backend graph is a bundled entry the session takes out of `PrecompileContext`, so the after-exit render only passes if the second render still finds the artifacts of the variants the first render already collected; under eager the fx graphs themselves are the artifacts. The `snapshot_artifact` docstring also records a precondition: under inductor the cache half bundles whatever `CacheArtifactManager` recorded, so the session should run under `with_fresh_cache()` (as `capture()` does) to keep the bundle to this session's compiles. The rendering itself is unchanged code, `_build_multigraph_artifact(self._package.cache_entry(), backends, summary, self._backend, self._fn)`.

## The gates run first, so a refusal renders nothing

`_gated_summary` takes the two keyword flags and checks them against `summary()` in order, raising `PackageError` with a remedy and, for every refusal except `guarded_codes == 0` (whose only remedy is to run the callable inside the block), the flag that accepts the gap:

```python
summary = self.summary()
if require_no_risky_drops and summary.risky_dropped_guards:
    raise PackageError(...)   # the risky subset: a slot whose value differed between variants,
                              # a configuration-dependent identity slot, or a custom-filter drop
if require_complete:
    if summary.capture_errors: ...       # a captured call raised
    if summary.guarded_codes == 0: ...   # nothing was run inside the block
    if summary.backend_graphs == 0: ...  # every captured frame was empty
    if summary.uncovered_frames: ...     # a frame produced no guarded code (dispatch-only, or a graph break)
    if summary.bypassed: ...             # a frame whose guards could not be serialized
    # Backstop: the branches above only add detail, and any reason they
    # do not name (a truncated frame) still refuses.
    if not summary.complete:
        raise PackageError(
            f"Precompilation is incomplete: {summary}. Pass "
            "require_complete=False to save the partial artifact."
        )
return summary
```

The per-reason branches only make the message specific; the final `summary.complete` check is what guarantees that no incomplete summary slips through, including a reason none of them names. Truncation is the example: `PrecompileSummary` carries a `truncated` field, but sessions never report truncation yet (`summary()` passes `truncated=frozenset()`), so today the backstop only guards against a future reason. Only after the summary passes does `snapshot_artifact` collect backends and render, so a refused capture never writes a partial `python_code`. The same session from above shows the default policy rendering and exercises the completeness gate, and a separate eager session exercises the risky-drop gate:

```python
# The default policy renders: the capture dropped only harmless guards.
python_code, cache = session.snapshot_artifact()
self.assertTrue(summary.dropped_guards)
self.assertFalse(summary.risky_dropped_guards)

# A session that never ran its callable has nothing to render.
empty = precompile_package.precompile_capture(step, backend="eager")
with empty:
    pass
with self.assertRaisesRegex(PackageError, "no compiled code"):
    empty.snapshot_artifact()

# A session whose call raised is incomplete unless the caller accepts it.
failed = precompile_package.precompile_capture(step, backend="eager")
with failed as call:
    call(model, torch.ones(2, 4))
    with self.assertRaises(RuntimeError):
        call(model, torch.ones(2, 5))   # Linear(4, 4) rejects a width-5 input
with self.assertRaisesRegex(PackageError, "captured call raised"):
    failed.snapshot_artifact()
python_code, _ = failed.snapshot_artifact(require_complete=False)   # the partial artifact

# The risky-drop gate is on by default; a custom filter's drop is risky.
default = precompile_package.default_guard_filter_fn
custom = precompile_package.precompile_capture(
    step,
    backend="eager",
    guard_filter_fn=lambda es: [keep and e.name != "x" for keep, e in zip(default(es), es)],
)
with custom as call:
    call(model, torch.ones(2, 4))
with self.assertRaisesRegex(PackageError, "can affect dispatch"):
    custom.snapshot_artifact()                        # the dropped tensor guard on `x` is risky
custom.snapshot_artifact(require_no_risky_drops=False)   # accepted explicitly, renders
```

The custom filter keeps everything `default_guard_filter_fn` keeps except the tensor guard on `x`, so the only difference from the default-policy session is one drop that came from a custom filter, and that alone is enough for the default-on risky-drop gate to refuse.

## Collecting the backends by id

`_collect_backends` first calls `_take_backend_artifacts()` to move this capture's bundled AOTAutograd entries out of `PrecompileContext`, then walks `entry.backend_ids` in sorted order:

```python
for backend_id in sorted(entry.backend_ids):
    artifact = self._backend_artifacts.get(backend_id)      # inductor: the bundled AOTAutograd entry
    backend = self._package.cached_backends.get(backend_id)
    if artifact is None and backend is not None:
        if self._backend == "eager" or backend is noop_graph_call:
            artifact = EagerCacheArtifact(key=backend_id, content=backend)  # eager: the fx graph itself
    if artifact is None:
        missing.append(backend_id)
    else:
        collected[str(backend_id)] = artifact
```

An eager "backend" is an fx graph with no compiled artifact of its own, and `output_graph` short-circuits an empty graph to `noop_graph_call` without filing anything under its id even though the bytecode still names it; both are carried as-is. Any id left without an artifact is named rather than written, because an artifact missing a subgraph would fail at load instead of here:

```python
if missing:
    raise PackageError(
        f"precompile captured {len(entry.backend_ids)} backend graph(s) but "
        f"{len(missing)} of them recorded no serializable artifact: {missing}. "
        f"The {self._backend!r} backend reaches the artifact through the AOTAutograd "
        f"cache (bundled_autograd_cache); a graph that cache bypassed cannot be served. "
        f"Check TORCH_LOGS=+aot for the bypass reason."
    )
```

## Tests

`test_precompile_session_renders_behind_the_gates`, under both the eager and inductor backends, renders mid-block and after exit, checks the parsed metadata and the cache tag against the summary, checks that the default policy renders a capture whose dropped guards are all harmless, and exercises the risky-drop gate with a filter that drops a tensor guard, an empty session, and a session whose call raised with and without `require_complete`. The `PrecompileSession` docstring now points at `snapshot_artifact` instead of deferring rendering to the next commit, and records that the artifact is standalone: it rebuilds each captured frame from its code object and guard trees and installs nothing, so a frame the entry cannot reach through a graph-break continuation (such as a child module's forward that graph-breaks) is refused at render rather than served eager.

Test Plan:

`test_precompile_session_renders_behind_the_gates`, under both the eager and inductor backends, renders mid-block and after exit, checks the parsed metadata and the cache tag against the summary, checks that the default policy renders a capture whose dropped guards are all harmless, and exercises the risky-drop gate with a filter that drops a tensor guard, an empty session, and a session whose call raised with and without `require_complete`.

```
python test/dynamo/test_precompile_package.py
lintrunner -a torch/_dynamo/precompile_package.py test/dynamo/test_precompile_package.py
```

Authored with an AI assistant.

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

Pull Request resolved: #198216
Approved by: https://github.com/aorenste
ghstack dependencies: #198211, #198223, #198283, #198284, #197993, #198213, #198135, #198243, #198214, #198136, #198215, #198137
pytorchmergebot pushed a commit that referenced this pull request Oct 6, 2026
…ce (#198528)

**Problem.** On Python 3.10, `_get_code_source` raises `BytesWarning` under `python -bb` when a module holds both `b""` and an int that hashes to 0, so any precompile capture that records such a module's function fails.

**Fix.** The walk over `co_consts` now recurses into code constants only, so non-code constants never reach the `seen` set.

**Summary.** `_get_code_source` finds where a code object lives in its module by walking functions, methods, closures and `co_consts`, and on Python 3.10, which has no `co_qualname`, it starts at the module and adds every constant it reaches to a `seen` set. `b""` and `0` hash equal, so a set holding both compares them, and that comparison is a `BytesWarning`, which CI's `python -bb` raises. This matters for precompile because `PrecompileSession` records every inlined user function through `CompilePackage._add_user_function` -> `_get_code_source`, and the DynamoTracer capture in #198138 above is the first to resolve a code object of a class local to a test module, so its tests fail on the py3.10 CI job without this change. Only a code constant can hold the target code, so every path the walk finds is unchanged; the non-code constants are simply no longer visited. The alternative, keying `seen` by `id()`, was rejected because it would keep visiting constants that cannot matter.

## The change

```python
for i, const in enumerate(obj.co_consts):
    if not inspect.iscode(const):  # new: b"", ints, etc. never reach `seen`
        continue
    if (res := _find_code_source(const)) is not None:
        return f".co_consts[{i}]{res}"
```

`test_code_source_walk_skips_non_code_constants` pins it: it resolves a method of a function-local class whose enclosing function holds `b""` and `2**61 - 1` (hash 0, like `b""`), under `-bb` with `sys.version_info` patched to 3.10, and checks that the returned path evaluates back to the same code object.

Test Plan:

`test_code_source_walk_skips_non_code_constants` in test/dynamo/test_package.py runs `_get_code_source` under `python -bb` in a subprocess, with `sys.version_info` patched to 3.10, on a method of a class local to a function whose constants include `b""` and `2**61 - 1` (both hash to 0; a literal `0` would too, but newer Pythons keep small ints out of `co_consts`). It checks that the returned path resolves back to the same code object. Without the fix it fails with `BytesWarning: Comparison between bytes and int`.

```
python test/dynamo/test_package.py
lintrunner -a test/dynamo/test_package.py torch/_dynamo/package.py
```

Authored with an AI assistant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Pull Request resolved: #198528
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #198211, #198223, #198283, #198284, #197993, #198213, #198135, #198243, #198214, #198136, #198215, #198137, #198216
pytorchmergebot pushed a commit that referenced this pull request Oct 9, 2026
…r PR (#199883)

Follow-up to the review of #198216, which has landed; this does not amend it.

PrecompileSession kept its backend artifacts as dict[_BackendId, Any] and
_collect_backends returned dict[str, Any], although every value is a
BackendCacheArtifact: either what PrecompileContext.take_artifact returned or
an EagerCacheArtifact built for an eager or noop graph. Both are now annotated
as BackendCacheArtifact[Any], so the .get() branch in _collect_backends is
type-checked instead of Any.

test_precompile_session_renders_behind_the_gates is parametrized over the
backend, but its empty, failed and custom-filter scenarios hardcode
backend="eager", so the inductor instantiation re-ran the same eager captures.
They move into a non-parametrized test_precompile_session_snapshot_refuses_behind_the_gates,
unchanged.

Test Plan:

```
lintrunner -a torch/_dynamo/precompile_package.py test/dynamo/test_precompile_package.py
python test/dynamo/test_precompile_package.py
python test/test_precompile.py
```

Both suites pass.

This PR was authored with the help of an AI assistant (Claude Code).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Pull Request resolved: #199883
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #198211, #198223, #198283, #198284, #197993, #198213, #198135, #198243, #198214, #198136, #198215, #198137, #198216, #198528
pytorchmergebot pushed a commit that referenced this pull request Oct 10, 2026
#198138)

**Problem.** `torch.compiler.precompile.capture()` only took a `MakeFxTracer`: one positional call, one ATen trace, no graph breaks, no recompiled variants, no keyword arguments. The `PrecompileSession` of the previous commits can record all of those, but nothing in the public module reached it.

**Fix.** Add `DynamoTracer`, the multi-graph front-end passed as `tracer=`, and `_DynamoCapture`, the `Capture` that drives a `PrecompileSession` across as many calls as the block makes and writes the standalone artifact on a clean exit, so `load()` serves it in a fresh process.

**Summary.** `capture()` accepted a `MakeFxTracer` and nothing else, so a function with a graph break, a shape-dependent branch or a keyword argument could not be precompiled through `torch.compiler.precompile` even though `PrecompileSession` and `snapshot_artifact` could already record and render such captures. This commit adds `DynamoTracer(guard_filter_fn, recompile_limit, dynamic, require_complete, require_no_risky_drops)` beside `MakeFxTracer`, and `_DynamoCapture`, which runs the block under a fresh `CacheArtifactManager` cache, serializes its calls under an `RLock`, counts attempted calls, refuses a recursive re-entry, and writes the pair behind the two `require_*` gates on a clean exit only. The artifact is standalone, so `fn` must be a module-level function of an importable module, an artifact whose capture graph-broke cannot load beside the live compile that captured it (the continuation names collide, and `load` says so), and it is locked to the producing Python version and torch build. A Dynamo capture runs every call in the caller's grad mode and lowers a backward whenever grad is enabled, so a training step that calls `.backward()` is captured like any other call and the served artifact accumulates `.grad` like eager. `MakeFxTracer` stays the default for two more commits, package and recompile errors surface as `PrecompileError`, and mid-block `save()` is the next commit's, so `save()` on this tracer raises a `PrecompileError` saying its artifact is written when the block exits.

## Where this fits

The stack replaces the callable `torch.compiler.precompile(fn, *example_inputs)` (trace once on inputs passed up front, pair returned in memory) with a caller-driven context manager: `capture(fn, artifact_path=, cache_path=)` is entered with a `with` block, the caller calls it on as many example inputs as they like, the `(python_code, cache)` pair is written to the two files on exit, and `load(artifact_path, cache_path)` serves it in a fresh process. The end-to-end example and the PR-by-PR map live in #197993's "The new API, end to end" section. This PR is where `capture()` becomes multi-call: `DynamoTracer` takes as many calls as the caller makes and folds every graph break and recompile they exercise into one artifact. It becomes the default tracer in #198217. The Python 3.10 `-bb` fix to the code-constant walk in `_find_code_source`, which the recursive-capture test here first exercises, lives in #198528 directly below.

## The golden path

The new tests write a module with a graph-breaking step, capture it over two shapes and a keyword default, and serve it in a fresh process:

```python
# precompile_golden_<uuid>.py, importable from sys.path
def step(model, x, *, scale=1.0):
    y = model(x) * scale * SCALE
    torch._dynamo.graph_break()
    if y.shape[0] > 2:
        y = y + 1
    return y.sum(dim=0)
```

```python
from torch.compiler.precompile import capture, DynamoTracer, load

with capture(step, artifact_path="m.py", cache_path="m.cache", tracer=DynamoTracer(), backend="inductor") as cap:
    y2 = cap(model, x2)               # step and its graph-break continuation
    y3 = cap(model, x3, scale=0.5)    # the branch recompiles the continuation; the keyword is a second entry variant
# exit: TRACER = "dynamo", SERVING_MODE = "standalone", FN_NAME = 'step' in m.py

load("m.py", "m.cache")               # in this process: PrecompileError, the message says to use a fresh process
```

```python
# a fresh process
f = torch.compiler.precompile.load("m.py", "m.cache")
f(model, x2)                          # == y2
f(model, x3, scale=0.5)               # == y3
f(model, x2.double())                 # PrecompileError: no captured variant
```

The last line is the standalone contract: there is no compiler behind a source artifact, so a call no variant covers raises rather than silently serving. `test_graph_breaks_and_recompiles_round_trip_in_a_fresh_process` pins this on both backends, including the in-process collision refusal; `test_a_single_graph_serves_in_process` pins the no-graph-break case, where `load` works in the capturing process, `f.installed` is false, `with f:` and `f.unload()` are no-ops, a second `Model()` swaps weights in, and `f(model, x3)` after a shape-2 capture raises `no captured variant`.

## `DynamoTracer` carries the multi-graph knobs

```python
@dataclasses.dataclass(frozen=True)
class DynamoTracer:
    guard_filter_fn: Callable[[Sequence[Any]], Sequence[bool]] | None = None
    recompile_limit: int = 256
    dynamic: bool | None = None
    require_complete: bool = True
    require_no_risky_drops: bool = True
```

`guard_filter_fn` takes the `GuardFilterEntry` records (`guard_type`, `name`, ...) and returns one keep flag per entry, filtering the guards kept in the serialized artifact (runtime capture guards are always retained; the default drops only what cannot be serialized). `recompile_limit` caps recompilations per frame: a call past it runs eager and is absent from the artifact without any gate refusing it, which the docstring states. `dynamic` forces dynamic shapes as `torch.compile(dynamic=)` does. The `require_*` gates refuse, at write time, an artifact with a coverage gap (`require_complete`: a bypassed or uncovered frame, a call that raised) or one whose dropped guards told captured variants apart or hang off a configuration-chosen slot (`require_no_risky_drops`). Other dropped guards, such as the identity guards every model drops because they cannot be serialized, are listed in the artifact rather than refused; there is deliberately no gate that refuses every drop, since every capture would trip it. The annotation stays `Sequence[Any]` rather than naming `GuardFilterEntry`, because torch/compiler/precompile.py resolves the re-homed classes' annotations with `typing.get_type_hints` at import.

```python
DynamoTracer(dynamic=True)                         # capture single on x2 -> the artifact serves x3 too
DynamoTracer(guard_filter_fn=drop_x)               # exit: PrecompileError "can affect dispatch"
DynamoTracer(guard_filter_fn=drop_x, require_no_risky_drops=False)   # writes an artifact that loads
DynamoTracer(dynamic=False, recompile_limit=1)     # cap(x2); cap(x3) -> served x3 raises "no captured variant"
```

`test_the_tracer_knobs_reach_the_session` pins all four lines, where `drop_x` drops the guard on `x` on top of `default_guard_filter_fn` (dropping what tells the shapes apart). `test_dropped_guards_are_listed_in_the_artifact` shows the default capture of `single` listing `['MODULE_MATCH', ...` in the artifact's dropped guards and writing the artifact regardless.

## `capture()` dispatches on the tracer

```python
tracer: MakeFxTracer | DynamoTracer = MakeFxTracer()
...
if isinstance(tracer, MakeFxTracer):
    return _MakeFxCapture(fn, artifact_path, cache_path, backend=backend, decompositions=tracer.decompositions)
if not isinstance(tracer, DynamoTracer):
    raise TypeError("precompile.capture tracer must be a MakeFxTracer or DynamoTracer, got ...")
if backend not in ("inductor", "eager"):
    raise ValueError(f"precompile backend must be 'inductor' or 'eager', got {backend!r}.")
try:
    session = precompile_capture(fn, backend=backend, guard_filter_fn=tracer.guard_filter_fn, recompile_limit=tracer.recompile_limit, dynamic=tracer.dynamic)
except PackageError as e:
    raise PrecompileError(str(e)) from e
return _DynamoCapture(session, artifact_path, cache_path, require_complete=..., require_no_risky_drops=...)
```

The make_fx front-end validates `backend` when it builds its `PrecompiledModule`; the Dynamo front-end builds none, so `capture()` checks it before creating the session. `precompile_capture`'s up-front refusals now surface as `PrecompileError`. `test_entries_a_standalone_artifact_cannot_rebuild_are_refused` pins the entries a standalone artifact cannot rebuild: a bare `nn.Module` is refused by `capture()` itself (`CALLS the model`: Dynamo compiles its wrapper frame, whose graphs close over the module), and a closure entry is refused once the block calls it (`closes over`), since a code object cannot rebuild what the closure captured. A `functools.partial` never reaches the tracer: `capture()` refuses it with a `TypeError` (`takes the function itself, not a functools.partial`) before dispatching. `_MakeFxCapture`'s two refusals (a keyword argument, a second call) now point at `tracer=DynamoTracer()` instead of just explaining themselves.

## `_DynamoCapture` drives the session

Entering the block opens a fresh cache before the session, and undoes it if the session refuses to enter:

```python
def __enter__(self):
    with self._lock:
        if self._call is not None or self._exited:
            raise PrecompileError("this capture has already been entered; capture() returns a fresh capture per call.")
        self._fresh_cache = CacheArtifactManager.with_fresh_cache()
        self._fresh_cache.__enter__()
        try:
            self._call = self._map(self._session.__enter__)
        except BaseException:
            self._fresh_cache.__exit__(None, None, None)
            self._fresh_cache = None
            raise
    return self
```

The capture's compiles record into the process-global cache-artifact list, which the cache half of the artifact bundles to prime the kernel caches on load; a fresh one means the bundle holds only this capture's compiles. The swap spans the whole `with` block, not just the calls, so the `capture()` docstring now says a `DynamoTracer` capture records the kernel-cache artifacts of everything compiled inside the block: compile nothing else there, and do not overlap two such captures. `_map` is the one place `PackageError` and `RecompileError` become `PrecompileError`.

Each call is serialized under an `RLock`, refuses a call before `__enter__` or after `__exit__` (`capture is not active`), refuses `fn` calling the capture it is being captured through (`re-entered recursively`), and counts the call before it runs:

```python
def __call__(self, *args, **kwargs):
    with self._lock:
        ...
        self._in_call = True
        # Counted before the call: a call that raised is for the session's
        # require_complete gate to report, not "nothing was captured".
        self._calls += 1
        try:
            return self._map(self._call, *args, **kwargs)
        finally:
            self._in_call = False
```

The lock is what makes concurrent callers safe: every call feeds the one session, and without it a call that finds another thread's call in flight would trip the `_in_call` check and be refused as a recursive re-entry. `test_calls_from_several_threads_are_serialized` starts eight threads (four on `x2`, four on `x3`) inside one block, checks each result against eager `step`, and asserts no errors and a written artifact. Counting attempts rather than successes matters for a block whose only calls raised: it made calls, so exit goes on to `snapshot_artifact`, and the session's `require_complete` report lists the capture errors instead of the misleading `nothing was captured`.

Exit writes on a clean block only, and holds a gate refusal until the session and cache are torn down:

```python
def __exit__(self, *exc):
    with self._lock:
        error = None
        try:
            if exc[0] is None:
                try:
                    if self._calls == 0:
                        raise PrecompileError("nothing was captured: call the capture with your example arguments inside the `with` block.")
                    self._write()        # snapshot_artifact(**gates) then _write_artifact(...)
                except BaseException as e:
                    error = e
            self._exited = True
            try:
                self._map(self._session.__exit__, *exc)
            except BaseException as e:
                if error is None:
                    raise
                raise e from error
        finally:
            if self._fresh_cache is not None:
                self._fresh_cache.__exit__(None, None, None)
                self._fresh_cache = None
    if exc[0] is None and error is not None:
        raise error
```

A teardown error that follows a gate refusal is raised `from` the refusal, so the refusal is not lost, and the fresh cache is always exited with `(None, None, None)` rather than with the in-flight exception. `_write` renders through `self._session.snapshot_artifact(**self._gates)` and hands the pair to `_write_artifact`; an `OSError` there becomes a `PrecompileError` (`precompile could not write the artifact`), and since `_write_artifact` leaves the previous pair in place the last good pair is still loadable.

`test_a_raised_call_is_refused_at_exit_and_writes_nothing` pins the gate: a second call with `torch.randn(2, 5)` into a `Linear(4, 4)` raises `RuntimeError` inside the block, the block itself runs to completion, exit raises `PrecompileError` (`captured call raised`) through `require_complete`, and neither `m.py` nor `m.cache` exists afterwards. The same test covers a block whose only call raised, which reaches the same `captured call raised` gate rather than `nothing was captured`, and `DynamoTracer(require_complete=False)`, which writes the partial artifact instead.

`test_misuse_is_refused` pins the rest of the lifecycle:

```python
capture(single, ..., tracer=DynamoTracer(), backend="aot_eager")   # ValueError: backend
capture(single, ..., tracer=object())                              # TypeError: tracer must be
cap(model, x2)                        # before the block: PrecompileError "not active"
with cap: pass                        # PrecompileError "nothing was captured"
with cap: pass                        # again: PrecompileError "already been entered"
cap(model, x2)                        # after it: PrecompileError "not active"
cap(Reentrant(), x2)                  # forward calls cap: PrecompileError "re-entered recursively"
raise KeyError("the block's own")     # inside a block: propagates unchanged, nothing written
# _write_artifact mocked to raise OSError: PrecompileError "could not write"
```

## Grad mode and the training step

`capture()` has no grad-mode flag. A Dynamo capture runs every call in the caller's own grad mode and lowers a backward whenever grad is enabled: a `.backward()` in `fn` graph-breaks and re-runs at serve time through the live autograd engine, accumulating `.grad` like eager, so the artifact should be served under the grad mode it was captured in.

```python
def train_step(model, x):
    model(x).sum().backward()

with capture(train_step, ..., tracer=DynamoTracer(), backend=backend) as cap:   # backend: "inductor" or "eager"
    cap(model, x2)                    # returns None; model.lin.weight.grad matches an eager step

# a fresh process, model reloaded from the pre-step state dict
f = torch.compiler.precompile.load("m.py", "m.cache")
f(model, x2)                          # returns None; every parameter's .grad matches the eager step
```

`test_training_step_grads_match_eager_in_a_fresh_process`, parametrized over `inductor` and `eager`, pins this: it runs an eager step on a `Model` loaded from the same state dict, checks the capture's `lin.weight` grad against it, restores the pre-step weights, and serves the artifact in a fresh process, asserting each parameter's `.grad` against the eager one.

## The artifact does not mix with a make_fx pair

`test_a_dynamo_pair_does_not_mix_with_a_make_fx_pair` captures `single` once with `DynamoTracer()` and once with `MakeFxTracer()` into two pairs; `load` of the Dynamo artifact with the make_fx cache raises `PrecompileError` mentioning `tracer`, and the reverse raises `tracer` or `does not match`. `load`'s docstring now says a Dynamo artifact takes keyword arguments, carries its compiled subgraphs inside `python_code` so it serves without JIT even with no usable cache, is a no-op to enter and unload, re-seeds the names Dynamo minted into the captured module, and must be loaded in a fresh process when its capture graph-broke.

## Exports, docs and scope

`DynamoTracer` joins `torch.compiler.precompile.__all__`, the `__module__` re-homing loop, the public-members test, and the API reference (`.. autoclass:: torch.compiler.precompile.DynamoTracer` in docs/source/torch.compiler_api.md). The tests pass `tracer=DynamoTracer()` explicitly through `_capture`. Mid-block `save()` checkpoints and the `summary()` report are the next commit's (#198227), so `_DynamoCapture.save()` raises `PrecompileError` (`save() is not supported on a DynamoTracer capture yet: its artifact is written when the block exits.`) rather than the base class's bare `NotImplementedError`, and the `capture()` and `Capture` docstrings' `save()` sentences say it applies to a `MakeFxTracer` capture only, for now. The module Note's `tracer:` paragraph now describes both tracers (`MakeFxTracer` the default; `DynamoTracer` standalone and version-locked, with invariants 1, 2, 3 and 6 left as the make_fx contract, refusing uncovered calls through its guards and listing the guards it could not serialize as `DROPPED_GUARDS`) instead of saying `dynamo` raises `NotImplementedError`. Deliberately absent, as follow-ups: the installed serving mode (`load(fn=)`), the rendered-as-source subgraphs, the invariants report and the per-frame drift probe. The fresh-process tests are skipped under the crossref harness, whose active dispatch mode Dynamo guards on and a fresh process lacks.

## What this leaves for later PRs

- Mid-block `save()` comes in #198227. Here, `save()` on a Dynamo capture raises `PrecompileError`.
- Making `DynamoTracer` the default tracer comes in #198217. Here `MakeFxTracer` is still the default.
- The lifecycle refactor is #198423. The `__enter__`/`__call__`/`__exit__` bodies quoted above become `_start`/`_run`/`_finish` on the shared `Capture` base class there. The behaviour is the same, but the code at the top of the stack looks different from what this description shows.
- Installed serving. This PR is standalone only, and lists installed mode above as a follow-up (`load(fn=)`). #198523 is that follow-up, except that the mode is picked automatically when the artifact is written rather than through a `load(fn=)` argument. So the `capture()` docstring paragraph this PR adds ("A Dynamo artifact is STANDALONE ... is refused at write time") is one of the stale docstrings on #198523's cleanup list, together with `PrecompileSession`'s, which comes from a lower PR.

Test Plan:

`TestPrecompileDynamoCapture` in test/test_precompile.py, passing `tracer=DynamoTracer()` explicitly: the graph-break/recompile round trip through a fresh process on both backends (with the in-process collision refusal), a single-graph capture served in process (weight swap, no-op enter/unload, uncovered call), a training step on both backends served in a fresh process whose `.grad` matches eager, the raised-call gate at exit (including a block whose only call raised, and `require_complete=False` writing the partial artifact), the misuse refusals (bad backend or tracer, a call outside the block, a re-entered or recursive capture, an empty block, a block raising its own exception, a write failure), calls from eight threads at once (which, unserialized, are refused as recursive re-entries), the `dynamic`, `guard_filter_fn`, `require_no_risky_drops` and `recompile_limit` knobs, the dropped guards listed in the artifact, the module/closure/partial refusals, and the make_fx/dynamo pair mismatch. The fresh-process tests are skipped under the crossref harness, whose active dispatch mode Dynamo guards on and a fresh process lacks.

```
python test/test_precompile.py
PYTORCH_TEST_WITH_CROSSREF=1 python test/test_precompile.py -k TestPrecompileDynamoCapture
lintrunner -a torch/_precompile.py torch/compiler/precompile.py test/test_precompile.py docs/source/torch.compiler_api.md
```

Authored with an AI assistant.

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

Pull Request resolved: #198138
Approved by: https://github.com/MengjiaoZhou
ghstack dependencies: #198211, #198223, #198283, #198284, #197993, #198213, #198135, #198243, #198214, #198136, #198215, #198137, #198216, #198528, #199883
pytorchmergebot pushed a commit that referenced this pull request Oct 10, 2026
…198227)

**Problem.** A Dynamo capture wrote its artifact only when the `with` block exited cleanly, so a job that died mid-loop left nothing on disk, and there was no way to read the coverage or guard report the session had built up.

**Fix.** `_DynamoCapture` gains `save()`, which checkpoints everything captured so far to the same two files without ending the capture, and `summary()`, which returns the session's `PrecompileSummary` inside the block and after it.

**Summary.** A Dynamo capture that dies mid-loop left nothing on disk, because the artifact was written only on a clean exit. `_DynamoCapture.save()` now renders and writes everything captured so far to the same `artifact_path` / `cache_path` pair without ending the capture, so each call re-renders and rewrites both files and a job that dies between saves leaves the last checkpoint loadable, while a gate refusal or a write failure raises and writes nothing partial with the capture still open. Exit writes only when there are calls the last save did not cover, tracked as the call count the last write saw, which starts at `-1` so a block that never called still raises the nothing-captured error rather than writing an empty artifact. Calls, saves and `summary()` share the capture's one lock, so a `save()` never snapshots the capture mid-compile, and a `save()` from inside `fn` is refused. `summary()` exposes the session's `PrecompileSummary` -- coverage, recompilation, failure and guard information for everything captured so far -- readable inside the block and after it, including after a gate refusal, since the refusal is raised only after teardown.

## Where this fits

The stack replaces the callable `torch.compiler.precompile(fn, *example_inputs)` (trace once on inputs passed up front, pair returned in memory) with a caller-driven context manager: `capture(fn, artifact_path=, cache_path=)` is entered with a `with` block, the caller calls it on as many example inputs as they like (each graph break and recompiled variant is folded in), the `(python_code, cache)` pair is written to the two files on exit, and `load(artifact_path, cache_path)` serves it in a fresh process. The end-to-end example and the PR-by-PR map live in #197993's "The new API, end to end" section. This PR adds `cap.save()` checkpoints and `cap.summary()` (coverage, recompiles, dropped guards) to the multi-call `DynamoTracer` capture from #198138.

## save() checkpoints mid-block

The parent wrote once, from `__exit__`, and its `save()` raised "not supported on a DynamoTracer capture yet". `save()` is now the same `_write()` -- `snapshot_artifact(**self._gates)` then `_write_artifact` -- callable from inside the block, behind the same three refusals a call has (not entered or already exited, inside `fn`, nothing captured yet):

```python
with capture(single, artifact_path=artifact, cache_path=cache, tracer=DynamoTracer()) as cap:
    cap.save()                 # PrecompileError: nothing was captured ...
    cap(model, x2)
    cap.save()                 # write 1: m.py / m.cache hold the x2 variant, loadable now
    cap(model, x3)
    cap.save()                 # write 2: both files rewritten, now differ from write 1
# exit: the last save() covered every call -> no third write
cap.save()                     # PrecompileError: capture is not active ...
cap.summary().complete         # True: still readable after exit
```

Each `save()` rewrites both files from scratch. A `require_*` gate refusal or an `OSError` from the rewrite raises out of `save()` as a `PrecompileError`; `_write_artifact` leaves the previous pair in place, so the last good checkpoint is still loadable and the capture stays open for more calls or another `save()`. A `save()` from inside `fn` is refused, and that refused call is a raised call, so a block that then raises writes nothing and the previous pair survives:

```python
class SavesFromFn(torch.nn.Module):
    def forward(self, x):
        return torch._dynamo.disable(cap.save)()

with capture(single, ...) as cap:
    cap(SavesFromFn(), x2)     # PrecompileError: save() was called from inside fn ...
    raise KeyError("the block's own")
# m.py is still byte-equal to the last checkpoint above
```

With `save()` now on both tracers, the `Capture`, `Capture.save` and `capture()` docstrings drop the parent's "a `MakeFxTracer` capture only, for now" qualifier.

## Exit writes only what the last save did not cover

Exit tracks the call count the last write saw:

```python
# __init__
self._saved_calls = -1          # not 0: a block that never called is still dirty at exit

# _write, after _write_artifact succeeds
self._saved_calls = self._calls

# __exit__: parent wrote on every clean exit
if exc[0] is None:
# now
if exc[0] is None and self._calls > self._saved_calls:
```

So a block whose last `save()` covered every call writes nothing at exit, a block with calls after the last `save()` writes a final checkpoint, and a block that never called (`_calls` is 0, above the `-1` start) still reaches the `"nothing was captured"` error instead of writing an empty artifact. A block that raised still writes nothing, as before. Because `__call__` counts a call before running it, a call that raised after the last `save()` still makes the block dirty, so it reaches the exit gate and is refused there:

```python
with capture(step, ...) as cap:
    cap(model, x2)
    cap.save()
    cap(model, torch.randn(2, 5))   # raises RuntimeError, but _calls is already 2
# exit: PrecompileError: captured call raised ...
```

## summary() inside and after the block

```python
with capture(step, artifact_path=artifact, cache_path=cache, tracer=DynamoTracer()) as cap:
    cap(model, x2)
    cap(model, x3, scale=0.5)
    summary = cap.summary()
summary.complete           # True
summary.frames             # 2: the entry and its graph-break continuation
summary.resume_functions   # 1
summary.guarded_codes      # >= 3: a variant per call the guards told apart
```

`summary()` is `self._map(self._session.summary)` under the capture's lock, so `PackageError` / `RecompileError` surface as `PrecompileError` like every other session call. It is readable after a gate refusal too, because `__exit__` holds the refusal and re-raises it only after teardown:

```python
with self.assertRaisesRegex(PrecompileError, "captured call raised"):
    with capture(step, ...) as cap:
        cap(model, x2)
        with self.assertRaises(RuntimeError):
            cap(model, torch.randn(2, 5))
        cap.summary().complete     # False: the raised call is a coverage gap
cap.summary().complete             # False, after the refusal
# nothing written: neither m.py nor m.cache exists
```

The dropped guards move from being documented as an artifact list (`DROPPED_GUARDS`) to being reported through the capture's `summary()`; the artifact still lists the same slots:

```python
with capture(single, ...) as cap:
    cap(model, x2)
    summary = cap.summary()
"MODULE_MATCH" in summary.dropped_guard_types   # the default filter drops the model identity guard
summary.kept_guards                             # non-empty
summary.risky_dropped_guards                    # ()
for guard_type, source in summary.dropped_guards:
    assert f"[{guard_type!r}, {source!r}]" in open(artifact).read()
```

## Tests

- `test_save_checkpoints_mid_block` enters a `mock.patch` wrapping `_write_artifact` before the capture, so the count also sees any write exit makes. It pins the pre-call `"nothing was captured"` refusal, loads the first checkpoint in process, reads the file again after the second `save()` (`call_count == 2`, bytes differ from the first checkpoint), checks exit leaves `call_count` at 2, refuses `save()` after exit (`"not active"`) and from inside `fn` (`"from inside fn"`), reads `summary()` after exit, and checks the file still equals the last checkpoint after the block raised `KeyError`.
- `test_a_raised_call_is_refused_at_exit_and_writes_nothing` gains the `summary().complete` assertions inside and after the refused block, and a case where the call raises after a `save()`; that case fails with `_calls += 1` moved after the call.
- `test_dropped_guards_are_reported_in_the_summary_and_the_artifact` replaces the parent's `test_dropped_guards_are_listed_in_the_artifact`.
- `test_graph_breaks_and_recompiles_round_trip_in_a_fresh_process` gains the `frames` / `resume_functions` / `guarded_codes` assertions shown above.

Test Plan:

`test_save_checkpoints_mid_block` checkpoints after the first call and loads that checkpoint in process, saves again after the second call and checks that exit writes nothing more, and refuses a save() after exit or from inside `fn`, with `summary()` still readable after exit; `test_a_raised_call_is_refused_at_exit_and_writes_nothing` also pins that a call raising after the last save() still reaches the exit gate (it fails with `_calls += 1` moved after the call) and that `summary()` is readable after the refusal; `test_dropped_guards_are_reported_in_the_summary_and_the_artifact` reads the default filter's drops from the summary and the artifact; the round-trip and raised-call tests gain their summary assertions. `summary()` reads the session under the capture's lock, like calls and saves.

```
python test/test_precompile.py
lintrunner -a torch/_precompile.py test/test_precompile.py
```

Authored with an AI assistant.

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

Pull Request resolved: #198227
Approved by: https://github.com/MengjiaoZhou
ghstack dependencies: #198211, #198223, #198283, #198284, #197993, #198213, #198135, #198243, #198214, #198136, #198215, #198137, #198216, #198528, #199883, #198138
pytorchmergebot pushed a commit that referenced this pull request Oct 10, 2026
…#198217)

**Problem.** `capture()` still defaults to `MakeFxTracer()`, a single non-strict trace that takes exactly one positional call, although the Dynamo front-end is served and takes as many calls as the caller makes; the docs' example `fn` is a lambda, which the standalone Dynamo artifact refuses.

**Fix.** Flip the default to `DynamoTracer()`, move the "(the default)" marker in the docstrings and Note [precompile programming model] to `DynamoTracer`, show a module-level `step` with two calls in the docs, and let the Dynamo tests rely on the default.

**Summary.** Until this commit a bare `capture(step, artifact_path=..., cache_path=...)` was a make_fx capture that accepted exactly one positional call and refused a second, so a caller who wanted the multi-call Dynamo capture had to ask for it with `tracer=DynamoTracer()`. Now the bare call is the Dynamo capture, which takes as many calls as the caller makes, keyword arguments included, and `tracer=MakeFxTracer()` is the explicit opt-in. The Dynamo default does refuse some `fn`s a `MakeFxTracer` capture accepts: its standalone artifact rebuilds the entry from its code object, so `fn` must be a module-level function of an importable module, not a lambda or a closure. The make_fx form stays available for those and for the single non-strict trace with its explicit contract. Neither tracer's behaviour changes; the module docstring, the Note's tracer paragraph, the `capture()` docstring, the API reference and the user guide now name `DynamoTracer` as the default, and the one test that silently relied on the old default is pinned to `MakeFxTracer` with a Dynamo twin added.

## Where this fits

The stack replaces the callable `torch.compiler.precompile(fn, *example_inputs)` (trace once on inputs passed up front, pair returned in memory) with a caller-driven context manager: `capture(fn, artifact_path=, cache_path=)` is entered with a `with` block, the caller calls it on as many example inputs as they like (each graph break and recompiled variant is folded in), the `(python_code, cache)` pair is written to the two files on exit, and `load(artifact_path, cache_path)` serves it in a fresh process. This PR makes `DynamoTracer` the default tracer, so `capture()` is multi-call out of the box, and makes the docs describe that API.

## The default flips

```python
def capture(fn, /, *, artifact_path, cache_path,
            tracer: MakeFxTracer | DynamoTracer = MakeFxTracer(),   # parent
            tracer: MakeFxTracer | DynamoTracer = DynamoTracer(),   # now
            backend: str = "inductor") -> Capture:
```

What a caller observes, with `step` a module-level function of an importable module:

```python
with torch.compiler.precompile.capture(
    step, artifact_path="m.py", cache_path="m.cache"
) as cap:
    y1 = cap(model, x1)
    y2 = cap(model, x2)   # parent: refused, make_fx takes exactly ONE positional call
                          # now: folded in, a recompile or graph break becomes another variant

# The single non-strict trace is still there, asked for by name, and it is the
# only form that also takes a lambda:
with torch.compiler.precompile.capture(
    lambda model, x: model(x), artifact_path="fx.py", cache_path="fx.cache",
    tracer=MakeFxTracer(),
) as cap:
    y = cap(model, x1)    # exactly one call, under the Note's contract
```

The flip is not a pure widening. The Dynamo default takes more calls, but its artifact is STANDALONE and rebuilds the entry from its code object, so a lambda, a closure or a function defined in `__main__` that a make_fx default accepted is now refused and needs `tracer=MakeFxTracer()`.

## The docstrings name the default

The module docstring of `torch/_precompile.py` now lists `DynamoTracer` among the re-exported public types (`Capture`, `DynamoTracer`, `MakeFxTracer`, `PrecompiledRunnable`) and describes both front-ends over the one pair they both write, the default first: `DynamoTracer` drives a `PrecompileSession` (`torch/_dynamo/precompile_package.py`) across the caller's calls, and the multi-graph frame records and driver emitter render every frame Dynamo compiled (the entry, its graph-break continuations and its recompiled variants); `MakeFxTracer` drives `PrecompiledModule`, a NON-STRICT make_fx trace of one execution of `fn`, lowered through `compile_to_python` with `backend="inductor"` or inlined with `backend="eager"`.

The tracer paragraph of Note [precompile programming model] moves "(the default)" from `MakeFxTracer` to `DynamoTracer`, and now says the guards that could not be serialized are reported in `PrecompileSummary.dropped_guards` (it said "listed in the artifact (DROPPED_GUARDS)"). Its content is otherwise unchanged: invariants 1, 2, 3 and 6 are the make_fx contract, and under Dynamo a call outside the captured variants is REFUSED by the guards rather than silently served.

`DynamoTracer`'s class docstring gains "(the default)", and the `capture()` docstring moves the marker from the `MakeFxTracer` sentence to the `DynamoTracer` one. Its example `fn` changes accordingly:

```python
# parent
# ``fn`` is the whole computation, e.g. ``lambda model, x: model(x)``: ...
# now
# ``fn`` is the whole computation, e.g. a module-level ``def step(model, x): return
# model(x)`` (only a :class:`MakeFxTracer` capture also takes a lambda): ...
```

## The docs show the multi-call capture

`docs/source/torch.compiler_api.md` and `docs/source/user_guide/torch_compiler/torch.compiler.md` swap the `lambda model, x: model(x)` example for a module-level `step` and two calls:

```python
# step is a module-level function: def step(model, x): return model(x)
with torch.compiler.precompile.capture(
    step, artifact_path="m.py", cache_path="m.cache"
) as cap:
    y1 = cap(model, x1)
    y2 = cap(model, x2)  # a recompile or graph break becomes another variant

f = torch.compiler.precompile.load("m.py", "m.cache")  # in a fresh process
y = f(model, x1)
```

The API reference also explains the two tracers in one sentence (the default `DynamoTracer` records every frame Dynamo compiles and the artifact dispatches among them by their guards; `MakeFxTracer` is a single non-strict trace under the Note's contract) and lists `DynamoTracer` ahead of `MakeFxTracer` in the autoclass entries.

## Tests

`TestPrecompileDynamoCapture._capture` in `test/test_precompile.py` drops its `kwargs.setdefault("tracer", DynamoTracer())`, so every Dynamo test now exercises the default the way a user hits it. The make_fx tests already pass `tracer=MakeFxTracer()` explicitly (`TestPrecompileCapture._capture` sets it as a default kwarg), with one exception: `test_capture_takes_pathlike_paths_and_the_default_tracer` called `capture()` directly with no tracer and a module-level `_files_fn`. It is renamed `test_capture_takes_pathlike_paths` and pins `tracer=MakeFxTracer()`, and `TestPrecompileDynamoCapture` gets its own `test_capture_takes_pathlike_paths`, which captures the generated module's `single` under the default tracer with `pathlib.Path` paths and checks the loaded result, so the default tracer keeps that coverage.

Test Plan:

```
python test/test_precompile.py
python test/dynamo/test_precompile_package.py
lintrunner -a torch/_precompile.py test/test_precompile.py docs/source/torch.compiler_api.md docs/source/user_guide/torch_compiler/torch.compiler.md
```

Authored with an AI assistant.

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

Pull Request resolved: #198217
Approved by: https://github.com/MengjiaoZhou
ghstack dependencies: #198211, #198223, #198283, #198284, #197993, #198213, #198135, #198243, #198214, #198136, #198215, #198137, #198216, #198528, #199883, #198138, #198227
pytorchmergebot pushed a commit that referenced this pull request Oct 10, 2026
**Problem.** Each tracer's capture ran its own `with`-block lifecycle from its own flags, so a Dynamo capture misused after its block gave different errors than a make_fx one, and a spent make_fx capture kept the pair its docstring says it drops.

**Fix.** `Capture` owns the lifecycle as one state field under one lock, and the tracers implement only the hooks it calls.

**Summary.** `_MakeFxCapture` tracked its block with two booleans, `_entered` and `_exited`, which are really three states, and `_DynamoCapture` kept its own `_exited` flag and its own copies of `__enter__`, `__exit__`, `__call__` and `save()`. The two front-ends therefore drifted: a Dynamo capture called after its block said "not active" where make_fx says "already exited", and make_fx's `__exit__` never cleared the pair that `Capture`'s docstring says a spent capture does not keep. `Capture` now holds the lifecycle as one field, `new`/`active`/`spent`, owns the four methods and their not-active, already-entered and spent messages, and a tracer implements only `_start`, `_run`, `_save` and `_finish`, where `_finish` drops the pair on every exit. The Dynamo capture's `RLock`, which serializes the block's calls, saves, exit and `summary()` because every call feeds one `PrecompileSession`, moves into `Capture` with the lifecycle. The messages a make_fx capture gives do not change, and a Dynamo capture now gives the same ones.

These are review cleanups on `capture()` from #198135; that PR and #198243 are approved, so both are left as they are. The `Generic` typing of `Capture` and the tensor-only leaves snapshot that earlier revisions of this PR carried now live in #198529 and #198530.

## What a Dynamo capture says now

```python
cap = capture(fn, ...)          # a DynamoTracer capture
cap(x)                          # "before calling it" (unchanged)
with cap:
    with cap: ...               # "already been entered" (unchanged)
cap(x)                          # after the block: a call, save() or `with cap:`
# parent: "not active" / "already been entered"
# now:    "already exited", the same as make_fx
```

The `save()` checkpoint contract moves from `_DynamoCapture`'s override onto the public `Capture.save` docstring, since it holds for both tracers and `help(cap.save)` shows only the base docstring: each call rewrites both files, a refusal or failed write raises but writes nothing partial and the capture stays open, and it raises `PrecompileError` outside the `with` block. `test_calls_from_several_threads_are_serialized` pins the lock.

Test Plan:

`test_misuse_is_refused` in `TestPrecompileDynamoCapture` moves to the shared messages, and `test_save_checkpoints_mid_block` now expects "already exited" for a save after exit. The make_fx lifecycle tests pass without changes (`test_a_capture_must_be_entered_before_it_is_called`, `test_a_capture_is_over_once_its_block_exits`, `test_save_after_a_raising_block_is_refused`, `test_a_capture_is_single_use`), which pins that its messages did not move.

```
python test/test_precompile.py
python test/dynamo/test_precompile_package.py
lintrunner -a torch/_precompile.py test/test_precompile.py
```

Authored with an AI assistant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Pull Request resolved: #198423
Approved by: https://github.com/MengjiaoZhou
ghstack dependencies: #198211, #198223, #198283, #198284, #197993, #198213, #198135, #198243, #198214, #198136, #198215, #198137, #198216, #198528, #199883, #198138, #198227, #198217
pytorchmergebot pushed a commit that referenced this pull request Oct 10, 2026
**Summary.** `capture()` took `fn: Callable[..., object]` and `Capture.__call__` returned `object`, so calling a capture threw away `fn`'s types. The documented `y = cap(model, x); y.sum()` therefore failed type-checking, and every typed caller had to cast. `Capture` is now `Generic[_P, _R]` over `fn`'s signature, the same way `torch.compile` types its result with `_InputT`/`_RetT`, and `capture(fn: Callable[_P, _R], ...)` returns `Capture[_P, _R]`. Returning a `Callable[_P, _R]` would not work, because that type has no `__enter__` or `save()`. Nothing changes at runtime, and `load()` stays untyped, since it rebuilds the callable from disk.

Review cleanup on `capture()` from #198135, stacked at the top like the lifecycle change below it.

```python
def step(model: torch.nn.Module, x: torch.Tensor) -> torch.Tensor:
    return model(x)

with capture(step, artifact_path="m.py", cache_path="m.cache") as cap:
    y = cap(model, x)  # parent: y: object; now: y: Tensor
    y.sum()
```

Test Plan:

No runtime behaviour changes. To check the typing, I ran pyrefly on a scratch caller: `y = cap(torch.nn.Linear(2, 2), torch.randn(2))` infers `y: Tensor`, and `cap("not a module", 3)` is reported as two `bad-argument-type` errors. No CI check pins this inference.

```
python test/test_precompile.py
lintrunner -a torch/_precompile.py
```

Authored with an AI assistant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Pull Request resolved: #198529
Approved by: https://github.com/MengjiaoZhou
ghstack dependencies: #198211, #198223, #198283, #198284, #197993, #198213, #198135, #198243, #198214, #198136, #198215, #198137, #198216, #198528, #199883, #198138, #198227, #198217, #198423
pytorchmergebot pushed a commit that referenced this pull request Oct 10, 2026
…ts (#198530)

**Summary.** `_trace_without_side_effects` snapshots the buffers and tensor inputs a static trace could mutate, so the serve that follows is the only execution the caller sees. It built `tensors` from the module buffers plus every pytree leaf of `args`, the modules themselves and any non-tensor leaves included, and applied `isinstance(t, torch.Tensor)` only inside the snapshot comprehension. The leaves are now filtered to tensors up front, so `tensors` holds only tensors and the snapshot needs no type check. The parameter-exclusion set loses the non-tensor ids too, which never matched anything because a live non-tensor object cannot share an id with a live parameter. What gets snapshotted is unchanged; this is review cleanup from #198243, which is approved, so it lands here at the top of the stack instead of in that commit.

```python
# parent
leaves = pytree.tree_leaves(args)
saved = {id(t): (t, t.detach().clone()) for t in tensors if isinstance(t, torch.Tensor) and id(t) not in params}
# now
leaves = [t for t in pytree.tree_leaves(args) if isinstance(t, torch.Tensor)]
saved = {id(t): (t, t.detach().clone()) for t in tensors if id(t) not in params}
```

Test Plan:

`test_a_capture_applies_in_place_updates_once`, `test_a_capture_refuses_an_in_place_parameter_update` and `test_a_trace_that_raises_leaves_buffers_and_inputs_as_they_were` in test/test_precompile.py cover this path and pass unchanged.

```
python test/test_precompile.py
lintrunner -a torch/_precompile.py
```

Authored with an AI assistant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Pull Request resolved: #198530
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #198211, #198223, #198283, #198284, #197993, #198213, #198135, #198243, #198214, #198136, #198215, #198137, #198216, #198528, #199883, #198138, #198227, #198217, #198423, #198529
bobrenjc93 added a commit that referenced this pull request Oct 10, 2026
…ard lists

Addresses aorenste's review of #198136, which is approved and so is left
untouched.

A multi-graph artifact rendered `DROPPED_GUARDS` and `RISKY_DROPPED_GUARDS` but
not `PrecompileSummary.policy_dropped_guards`, while `DROPPED_GUARD_CODE` draws
its slots from both `dropped_guards` and `policy_dropped_guards`. So the
artifact could list the check for a slot that no list above it names, and a
capture that discarded a precondition by policy would read like one that had
none. `_parse_artifact_metadata` already accepts `POLICY_DROPPED_GUARDS`, so the
renderer now writes it next to the other two. Nothing fills the field yet
(`PrecompileSession` passes an empty policy set), so this is latent until the
invariance policy is wired in, and today's artifacts gain an empty list.

Test Plan:

`test_multigraph_artifact_round_trips_a_hand_built_package` now builds its
summary with a policy drop and that drop's guard code. It checks that the
rendered `POLICY_DROPPED_GUARDS` round-trips, and that every slot in
`DROPPED_GUARD_CODE` is named by `DROPPED_GUARDS` or `POLICY_DROPPED_GUARDS`.
With the render line removed, the test fails with `KeyError:
'POLICY_DROPPED_GUARDS'`.

```
python test/test_precompile.py -k round_trips_a_hand_built
python test/test_precompile.py
lintrunner test/test_precompile.py torch/_precompile.py
```

This PR was authored with the help of an AI assistant (Claude).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ghstack-source-id: b272e31
Pull-Request: #198920
bobrenjc93 added a commit that referenced this pull request Oct 10, 2026
…ard lists

Addresses aorenste's review of #198136, which is approved and so is left
untouched.

A multi-graph artifact rendered `DROPPED_GUARDS` and `RISKY_DROPPED_GUARDS` but
not `PrecompileSummary.policy_dropped_guards`, while `DROPPED_GUARD_CODE` draws
its slots from both `dropped_guards` and `policy_dropped_guards`. So the
artifact could list the check for a slot that no list above it names, and a
capture that discarded a precondition by policy would read like one that had
none. `_parse_artifact_metadata` already accepts `POLICY_DROPPED_GUARDS`, so the
renderer now writes it next to the other two. Nothing fills the field yet
(`PrecompileSession` passes an empty policy set), so this is latent until the
invariance policy is wired in, and today's artifacts gain an empty list.

Test Plan:

`test_multigraph_artifact_round_trips_a_hand_built_package` now builds its
summary with a policy drop and that drop's guard code. It checks that the
rendered `POLICY_DROPPED_GUARDS` round-trips, and that every slot in
`DROPPED_GUARD_CODE` is named by `DROPPED_GUARDS` or `POLICY_DROPPED_GUARDS`.
With the render line removed, the test fails with `KeyError:
'POLICY_DROPPED_GUARDS'`.

```
python test/test_precompile.py -k round_trips_a_hand_built
python test/test_precompile.py
lintrunner test/test_precompile.py torch/_precompile.py
```

This PR was authored with the help of an AI assistant (Claude).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ghstack-source-id: 706ef66
Pull-Request: #198920
bobrenjc93 added a commit that referenced this pull request Oct 10, 2026
…ard lists

Addresses aorenste's review of #198136, which is approved and so is left
untouched.

A multi-graph artifact rendered `DROPPED_GUARDS` and `RISKY_DROPPED_GUARDS` but
not `PrecompileSummary.policy_dropped_guards`, while `DROPPED_GUARD_CODE` draws
its slots from both `dropped_guards` and `policy_dropped_guards`. So the
artifact could list the check for a slot that no list above it names, and a
capture that discarded a precondition by policy would read like one that had
none. `_parse_artifact_metadata` already accepts `POLICY_DROPPED_GUARDS`, so the
renderer now writes it next to the other two. Nothing fills the field yet
(`PrecompileSession` passes an empty policy set), so this is latent until the
invariance policy is wired in, and today's artifacts gain an empty list.

Test Plan:

`test_multigraph_artifact_round_trips_a_hand_built_package` now builds its
summary with a policy drop and that drop's guard code. It checks that the
rendered `POLICY_DROPPED_GUARDS` round-trips, and that every slot in
`DROPPED_GUARD_CODE` is named by `DROPPED_GUARDS` or `POLICY_DROPPED_GUARDS`.
With the render line removed, the test fails with `KeyError:
'POLICY_DROPPED_GUARDS'`.

```
python test/test_precompile.py -k round_trips_a_hand_built
python test/test_precompile.py
lintrunner test/test_precompile.py torch/_precompile.py
```

This PR was authored with the help of an AI assistant (Claude).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ghstack-source-id: 706ef66
Pull-Request: #198920
bobrenjc93 added a commit that referenced this pull request Oct 10, 2026
…ard lists

Addresses aorenste's review of #198136, which is approved and so is left
untouched.

A multi-graph artifact rendered `DROPPED_GUARDS` and `RISKY_DROPPED_GUARDS` but
not `PrecompileSummary.policy_dropped_guards`, while `DROPPED_GUARD_CODE` draws
its slots from both `dropped_guards` and `policy_dropped_guards`. So the
artifact could list the check for a slot that no list above it names, and a
capture that discarded a precondition by policy would read like one that had
none. `_parse_artifact_metadata` already accepts `POLICY_DROPPED_GUARDS`, so the
renderer now writes it next to the other two. Nothing fills the field yet
(`PrecompileSession` passes an empty policy set), so this is latent until the
invariance policy is wired in, and today's artifacts gain an empty list.

Test Plan:

`test_multigraph_artifact_round_trips_a_hand_built_package` now builds its
summary with a policy drop and that drop's guard code. It checks that the
rendered `POLICY_DROPPED_GUARDS` round-trips, and that every slot in
`DROPPED_GUARD_CODE` is named by `DROPPED_GUARDS` or `POLICY_DROPPED_GUARDS`.
With the render line removed, the test fails with `KeyError:
'POLICY_DROPPED_GUARDS'`.

```
python test/test_precompile.py -k round_trips_a_hand_built
python test/test_precompile.py
lintrunner test/test_precompile.py torch/_precompile.py
```

This PR was authored with the help of an AI assistant (Claude).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ghstack-source-id: 706ef66
Pull-Request: #198920
bobrenjc93 added a commit that referenced this pull request Oct 10, 2026
…ard lists

Addresses aorenste's review of #198136, which is approved and so is left
untouched.

A multi-graph artifact rendered `DROPPED_GUARDS` and `RISKY_DROPPED_GUARDS` but
not `PrecompileSummary.policy_dropped_guards`, while `DROPPED_GUARD_CODE` draws
its slots from both `dropped_guards` and `policy_dropped_guards`. So the
artifact could list the check for a slot that no list above it names, and a
capture that discarded a precondition by policy would read like one that had
none. `_parse_artifact_metadata` already accepts `POLICY_DROPPED_GUARDS`, so the
renderer now writes it next to the other two. Nothing fills the field yet
(`PrecompileSession` passes an empty policy set), so this is latent until the
invariance policy is wired in, and today's artifacts gain an empty list.

Test Plan:

`test_multigraph_artifact_round_trips_a_hand_built_package` now builds its
summary with a policy drop and that drop's guard code. It checks that the
rendered `POLICY_DROPPED_GUARDS` round-trips, and that every slot in
`DROPPED_GUARD_CODE` is named by `DROPPED_GUARDS` or `POLICY_DROPPED_GUARDS`.
With the render line removed, the test fails with `KeyError:
'POLICY_DROPPED_GUARDS'`.

```
python test/test_precompile.py -k round_trips_a_hand_built
python test/test_precompile.py
lintrunner test/test_precompile.py torch/_precompile.py
```

This PR was authored with the help of an AI assistant (Claude).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ghstack-source-id: 706ef66
Pull-Request: #198920
bobrenjc93 added a commit that referenced this pull request Oct 10, 2026
…ard lists

Addresses aorenste's review of #198136, which is approved and so is left
untouched.

A multi-graph artifact rendered `DROPPED_GUARDS` and `RISKY_DROPPED_GUARDS` but
not `PrecompileSummary.policy_dropped_guards`, while `DROPPED_GUARD_CODE` draws
its slots from both `dropped_guards` and `policy_dropped_guards`. So the
artifact could list the check for a slot that no list above it names, and a
capture that discarded a precondition by policy would read like one that had
none. `_parse_artifact_metadata` already accepts `POLICY_DROPPED_GUARDS`, so the
renderer now writes it next to the other two. Nothing fills the field yet
(`PrecompileSession` passes an empty policy set), so this is latent until the
invariance policy is wired in, and today's artifacts gain an empty list.

Test Plan:

`test_multigraph_artifact_round_trips_a_hand_built_package` now builds its
summary with a policy drop and that drop's guard code. It checks that the
rendered `POLICY_DROPPED_GUARDS` round-trips, and that every slot in
`DROPPED_GUARD_CODE` is named by `DROPPED_GUARDS` or `POLICY_DROPPED_GUARDS`.
With the render line removed, the test fails with `KeyError:
'POLICY_DROPPED_GUARDS'`.

```
python test/test_precompile.py -k round_trips_a_hand_built
python test/test_precompile.py
lintrunner test/test_precompile.py torch/_precompile.py
```

This PR was authored with the help of an AI assistant (Claude).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ghstack-source-id: 706ef66
Pull-Request: #198920
bobrenjc93 added a commit that referenced this pull request Oct 10, 2026
…ard lists

Addresses aorenste's review of #198136, which is approved and so is left
untouched.

A multi-graph artifact rendered `DROPPED_GUARDS` and `RISKY_DROPPED_GUARDS` but
not `PrecompileSummary.policy_dropped_guards`, while `DROPPED_GUARD_CODE` draws
its slots from both `dropped_guards` and `policy_dropped_guards`. So the
artifact could list the check for a slot that no list above it names, and a
capture that discarded a precondition by policy would read like one that had
none. `_parse_artifact_metadata` already accepts `POLICY_DROPPED_GUARDS`, so the
renderer now writes it next to the other two. Nothing fills the field yet
(`PrecompileSession` passes an empty policy set), so this is latent until the
invariance policy is wired in, and today's artifacts gain an empty list.

Test Plan:

`test_multigraph_artifact_round_trips_a_hand_built_package` now builds its
summary with a policy drop and that drop's guard code. It checks that the
rendered `POLICY_DROPPED_GUARDS` round-trips, and that every slot in
`DROPPED_GUARD_CODE` is named by `DROPPED_GUARDS` or `POLICY_DROPPED_GUARDS`.
With the render line removed, the test fails with `KeyError:
'POLICY_DROPPED_GUARDS'`.

```
python test/test_precompile.py -k round_trips_a_hand_built
python test/test_precompile.py
lintrunner test/test_precompile.py torch/_precompile.py
```

This PR was authored with the help of an AI assistant (Claude).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ghstack-source-id: 706ef66
Pull-Request: #198920
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…e and guard gates (pytorch#198216)

**Problem.** A `PrecompileSession` can capture calls and report on them through `summary()`, but nothing turns what it captured into the `(python_code, cache)` artifact, so a caller-driven capture still cannot produce anything to save or load.

**Fix.** Add `PrecompileSession.snapshot_artifact()`, which runs the coverage and guard gates, gathers the compiled subgraphs by backend id, and hands them to `_build_multigraph_artifact`, while leaving the session open so a caller can checkpoint mid-block.

**Summary.** The parent commit's `PrecompileSession` runs the caller's calls under `_capture_config` and the wrapped guard filter and exposes `summary()`, but its docstring still says "Rendering the artifact is the next commit's", so a capture had no way to become an artifact. This commit adds `snapshot_artifact()`, which renders everything captured SO FAR as the `(python_code, cache)` pair and leaves the session able to capture more, which is what lets a caller checkpoint mid-block. It runs the gates first, through `_gated_summary`, so a refusal renders nothing: `require_no_risky_drops` refuses the risky dropped guards the summary reports (the rest, such as unserializable identity guards, are listed in the artifact), and `require_complete` a capture whose call raised, that compiled no code or no graph, or that left a frame uncovered or bypassed, and it refuses any other incomplete summary as a backstop; each refusal names a remedy, and every one except the no-compiled-code refusal also names the flag that accepts the gap. `_collect_backends` then gathers the compiled subgraphs by backend id -- the bundled AOTAutograd entries taken from `PrecompileContext` for inductor, the captured fx graphs and `noop_graph_call` wrapped as `EagerCacheArtifact`s for eager -- and names any id without a serializable artifact rather than writing an artifact that would fail at load. Both gates default on, and a capture whose dropped guards are all harmless renders, and `test_precompile_session_renders_behind_the_gates`, parametrized over the eager and inductor backends, pins the mid-block render, the after-exit render, the risky-drop refusal, and the no-compiled-code and raised-call refusals.

## Where this fits

The stack replaces the callable `torch.compiler.precompile(fn, *example_inputs)` (trace once on inputs passed up front, pair returned in memory) with a caller-driven context manager: `capture(fn, artifact_path=, cache_path=)` is entered with a `with` block, the caller calls it on as many example inputs as they like (each graph break and recompiled variant is folded in), the `(python_code, cache)` pair is written to the two files on exit, and `load(artifact_path, cache_path)` serves it in a fresh process. The end-to-end example and the PR-by-PR map live in pytorch#197993's "The new API, end to end" section. This PR renders a `PrecompileSession` as an artifact behind the coverage and guard gates; `capture(..., tracer=DynamoTracer())` (pytorch#198138) writes through it.

## Rendering mid-block and after exit

`snapshot_artifact()` does not finish the session. The test runs under `@parametrize("backend", ["eager", "inductor"])`; its fixture graph-breaks once, so each call produces two frames, and the mid-block render already shows both:

```python
def step(model, x):
    y = model(x)
    torch._dynamo.graph_break()
    return y.sum(dim=0) + y.shape[0]

model = torch.nn.Linear(4, 4)
session = precompile_package.precompile_capture(step, backend=backend)   # "eager" or "inductor"
with session as call:
    call(model, torch.ones(2, 4))
    python_code, cache = session.snapshot_artifact()   # mid-block checkpoint
    len(_parse_artifact_metadata(python_code)["FRAMES"])  # 2; the session stays open
    call(model, torch.ones(3, 4))                        # a second variant still captures
summary = session.summary()
python_code, cache = session.snapshot_artifact()         # after exit, renders both variants
```

The rendered metadata agrees with the summary: `meta["TRACER"] == "dynamo"`, `meta["FN_NAME"] == step.__qualname__`, `sum(n for _, n in meta["FRAMES"]) == summary.guarded_codes`, `meta["DROPPED_GUARDS"] == [list(s) for s in summary.dropped_guards]`, and `torch.load(io.BytesIO(cache), weights_only=True)` carries `(backend, "dynamo")` as its `backend` and `tracer` tag. Under inductor every backend graph is a bundled entry the session takes out of `PrecompileContext`, so the after-exit render only passes if the second render still finds the artifacts of the variants the first render already collected; under eager the fx graphs themselves are the artifacts. The `snapshot_artifact` docstring also records a precondition: under inductor the cache half bundles whatever `CacheArtifactManager` recorded, so the session should run under `with_fresh_cache()` (as `capture()` does) to keep the bundle to this session's compiles. The rendering itself is unchanged code, `_build_multigraph_artifact(self._package.cache_entry(), backends, summary, self._backend, self._fn)`.

## The gates run first, so a refusal renders nothing

`_gated_summary` takes the two keyword flags and checks them against `summary()` in order, raising `PackageError` with a remedy and, for every refusal except `guarded_codes == 0` (whose only remedy is to run the callable inside the block), the flag that accepts the gap:

```python
summary = self.summary()
if require_no_risky_drops and summary.risky_dropped_guards:
    raise PackageError(...)   # the risky subset: a slot whose value differed between variants,
                              # a configuration-dependent identity slot, or a custom-filter drop
if require_complete:
    if summary.capture_errors: ...       # a captured call raised
    if summary.guarded_codes == 0: ...   # nothing was run inside the block
    if summary.backend_graphs == 0: ...  # every captured frame was empty
    if summary.uncovered_frames: ...     # a frame produced no guarded code (dispatch-only, or a graph break)
    if summary.bypassed: ...             # a frame whose guards could not be serialized
    # Backstop: the branches above only add detail, and any reason they
    # do not name (a truncated frame) still refuses.
    if not summary.complete:
        raise PackageError(
            f"Precompilation is incomplete: {summary}. Pass "
            "require_complete=False to save the partial artifact."
        )
return summary
```

The per-reason branches only make the message specific; the final `summary.complete` check is what guarantees that no incomplete summary slips through, including a reason none of them names. Truncation is the example: `PrecompileSummary` carries a `truncated` field, but sessions never report truncation yet (`summary()` passes `truncated=frozenset()`), so today the backstop only guards against a future reason. Only after the summary passes does `snapshot_artifact` collect backends and render, so a refused capture never writes a partial `python_code`. The same session from above shows the default policy rendering and exercises the completeness gate, and a separate eager session exercises the risky-drop gate:

```python
# The default policy renders: the capture dropped only harmless guards.
python_code, cache = session.snapshot_artifact()
self.assertTrue(summary.dropped_guards)
self.assertFalse(summary.risky_dropped_guards)

# A session that never ran its callable has nothing to render.
empty = precompile_package.precompile_capture(step, backend="eager")
with empty:
    pass
with self.assertRaisesRegex(PackageError, "no compiled code"):
    empty.snapshot_artifact()

# A session whose call raised is incomplete unless the caller accepts it.
failed = precompile_package.precompile_capture(step, backend="eager")
with failed as call:
    call(model, torch.ones(2, 4))
    with self.assertRaises(RuntimeError):
        call(model, torch.ones(2, 5))   # Linear(4, 4) rejects a width-5 input
with self.assertRaisesRegex(PackageError, "captured call raised"):
    failed.snapshot_artifact()
python_code, _ = failed.snapshot_artifact(require_complete=False)   # the partial artifact

# The risky-drop gate is on by default; a custom filter's drop is risky.
default = precompile_package.default_guard_filter_fn
custom = precompile_package.precompile_capture(
    step,
    backend="eager",
    guard_filter_fn=lambda es: [keep and e.name != "x" for keep, e in zip(default(es), es)],
)
with custom as call:
    call(model, torch.ones(2, 4))
with self.assertRaisesRegex(PackageError, "can affect dispatch"):
    custom.snapshot_artifact()                        # the dropped tensor guard on `x` is risky
custom.snapshot_artifact(require_no_risky_drops=False)   # accepted explicitly, renders
```

The custom filter keeps everything `default_guard_filter_fn` keeps except the tensor guard on `x`, so the only difference from the default-policy session is one drop that came from a custom filter, and that alone is enough for the default-on risky-drop gate to refuse.

## Collecting the backends by id

`_collect_backends` first calls `_take_backend_artifacts()` to move this capture's bundled AOTAutograd entries out of `PrecompileContext`, then walks `entry.backend_ids` in sorted order:

```python
for backend_id in sorted(entry.backend_ids):
    artifact = self._backend_artifacts.get(backend_id)      # inductor: the bundled AOTAutograd entry
    backend = self._package.cached_backends.get(backend_id)
    if artifact is None and backend is not None:
        if self._backend == "eager" or backend is noop_graph_call:
            artifact = EagerCacheArtifact(key=backend_id, content=backend)  # eager: the fx graph itself
    if artifact is None:
        missing.append(backend_id)
    else:
        collected[str(backend_id)] = artifact
```

An eager "backend" is an fx graph with no compiled artifact of its own, and `output_graph` short-circuits an empty graph to `noop_graph_call` without filing anything under its id even though the bytecode still names it; both are carried as-is. Any id left without an artifact is named rather than written, because an artifact missing a subgraph would fail at load instead of here:

```python
if missing:
    raise PackageError(
        f"precompile captured {len(entry.backend_ids)} backend graph(s) but "
        f"{len(missing)} of them recorded no serializable artifact: {missing}. "
        f"The {self._backend!r} backend reaches the artifact through the AOTAutograd "
        f"cache (bundled_autograd_cache); a graph that cache bypassed cannot be served. "
        f"Check TORCH_LOGS=+aot for the bypass reason."
    )
```

## Tests

`test_precompile_session_renders_behind_the_gates`, under both the eager and inductor backends, renders mid-block and after exit, checks the parsed metadata and the cache tag against the summary, checks that the default policy renders a capture whose dropped guards are all harmless, and exercises the risky-drop gate with a filter that drops a tensor guard, an empty session, and a session whose call raised with and without `require_complete`. The `PrecompileSession` docstring now points at `snapshot_artifact` instead of deferring rendering to the next commit, and records that the artifact is standalone: it rebuilds each captured frame from its code object and guard trees and installs nothing, so a frame the entry cannot reach through a graph-break continuation (such as a child module's forward that graph-breaks) is refused at render rather than served eager.

Test Plan:

`test_precompile_session_renders_behind_the_gates`, under both the eager and inductor backends, renders mid-block and after exit, checks the parsed metadata and the cache tag against the summary, checks that the default policy renders a capture whose dropped guards are all harmless, and exercises the risky-drop gate with a filter that drops a tensor guard, an empty session, and a session whose call raised with and without `require_complete`.

```
python test/dynamo/test_precompile_package.py
lintrunner -a torch/_dynamo/precompile_package.py test/dynamo/test_precompile_package.py
```

Authored with an AI assistant.

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

Pull Request resolved: pytorch#198216
Approved by: https://github.com/aorenste
ghstack dependencies: pytorch#198211, pytorch#198223, pytorch#198283, pytorch#198284, pytorch#197993, pytorch#198213, pytorch#198135, pytorch#198243, pytorch#198214, pytorch#198136, pytorch#198215, pytorch#198137
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…ce (pytorch#198528)

**Problem.** On Python 3.10, `_get_code_source` raises `BytesWarning` under `python -bb` when a module holds both `b""` and an int that hashes to 0, so any precompile capture that records such a module's function fails.

**Fix.** The walk over `co_consts` now recurses into code constants only, so non-code constants never reach the `seen` set.

**Summary.** `_get_code_source` finds where a code object lives in its module by walking functions, methods, closures and `co_consts`, and on Python 3.10, which has no `co_qualname`, it starts at the module and adds every constant it reaches to a `seen` set. `b""` and `0` hash equal, so a set holding both compares them, and that comparison is a `BytesWarning`, which CI's `python -bb` raises. This matters for precompile because `PrecompileSession` records every inlined user function through `CompilePackage._add_user_function` -> `_get_code_source`, and the DynamoTracer capture in pytorch#198138 above is the first to resolve a code object of a class local to a test module, so its tests fail on the py3.10 CI job without this change. Only a code constant can hold the target code, so every path the walk finds is unchanged; the non-code constants are simply no longer visited. The alternative, keying `seen` by `id()`, was rejected because it would keep visiting constants that cannot matter.

## The change

```python
for i, const in enumerate(obj.co_consts):
    if not inspect.iscode(const):  # new: b"", ints, etc. never reach `seen`
        continue
    if (res := _find_code_source(const)) is not None:
        return f".co_consts[{i}]{res}"
```

`test_code_source_walk_skips_non_code_constants` pins it: it resolves a method of a function-local class whose enclosing function holds `b""` and `2**61 - 1` (hash 0, like `b""`), under `-bb` with `sys.version_info` patched to 3.10, and checks that the returned path evaluates back to the same code object.

Test Plan:

`test_code_source_walk_skips_non_code_constants` in test/dynamo/test_package.py runs `_get_code_source` under `python -bb` in a subprocess, with `sys.version_info` patched to 3.10, on a method of a class local to a function whose constants include `b""` and `2**61 - 1` (both hash to 0; a literal `0` would too, but newer Pythons keep small ints out of `co_consts`). It checks that the returned path resolves back to the same code object. Without the fix it fails with `BytesWarning: Comparison between bytes and int`.

```
python test/dynamo/test_package.py
lintrunner -a test/dynamo/test_package.py torch/_dynamo/package.py
```

Authored with an AI assistant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Pull Request resolved: pytorch#198528
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: pytorch#198211, pytorch#198223, pytorch#198283, pytorch#198284, pytorch#197993, pytorch#198213, pytorch#198135, pytorch#198243, pytorch#198214, pytorch#198136, pytorch#198215, pytorch#198137, pytorch#198216
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…r PR (pytorch#199883)

Follow-up to the review of pytorch#198216, which has landed; this does not amend it.

PrecompileSession kept its backend artifacts as dict[_BackendId, Any] and
_collect_backends returned dict[str, Any], although every value is a
BackendCacheArtifact: either what PrecompileContext.take_artifact returned or
an EagerCacheArtifact built for an eager or noop graph. Both are now annotated
as BackendCacheArtifact[Any], so the .get() branch in _collect_backends is
type-checked instead of Any.

test_precompile_session_renders_behind_the_gates is parametrized over the
backend, but its empty, failed and custom-filter scenarios hardcode
backend="eager", so the inductor instantiation re-ran the same eager captures.
They move into a non-parametrized test_precompile_session_snapshot_refuses_behind_the_gates,
unchanged.

Test Plan:

```
lintrunner -a torch/_dynamo/precompile_package.py test/dynamo/test_precompile_package.py
python test/dynamo/test_precompile_package.py
python test/test_precompile.py
```

Both suites pass.

This PR was authored with the help of an AI assistant (Claude Code).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Pull Request resolved: pytorch#199883
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: pytorch#198211, pytorch#198223, pytorch#198283, pytorch#198284, pytorch#197993, pytorch#198213, pytorch#198135, pytorch#198243, pytorch#198214, pytorch#198136, pytorch#198215, pytorch#198137, pytorch#198216, pytorch#198528
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
pytorch#198138)

**Problem.** `torch.compiler.precompile.capture()` only took a `MakeFxTracer`: one positional call, one ATen trace, no graph breaks, no recompiled variants, no keyword arguments. The `PrecompileSession` of the previous commits can record all of those, but nothing in the public module reached it.

**Fix.** Add `DynamoTracer`, the multi-graph front-end passed as `tracer=`, and `_DynamoCapture`, the `Capture` that drives a `PrecompileSession` across as many calls as the block makes and writes the standalone artifact on a clean exit, so `load()` serves it in a fresh process.

**Summary.** `capture()` accepted a `MakeFxTracer` and nothing else, so a function with a graph break, a shape-dependent branch or a keyword argument could not be precompiled through `torch.compiler.precompile` even though `PrecompileSession` and `snapshot_artifact` could already record and render such captures. This commit adds `DynamoTracer(guard_filter_fn, recompile_limit, dynamic, require_complete, require_no_risky_drops)` beside `MakeFxTracer`, and `_DynamoCapture`, which runs the block under a fresh `CacheArtifactManager` cache, serializes its calls under an `RLock`, counts attempted calls, refuses a recursive re-entry, and writes the pair behind the two `require_*` gates on a clean exit only. The artifact is standalone, so `fn` must be a module-level function of an importable module, an artifact whose capture graph-broke cannot load beside the live compile that captured it (the continuation names collide, and `load` says so), and it is locked to the producing Python version and torch build. A Dynamo capture runs every call in the caller's grad mode and lowers a backward whenever grad is enabled, so a training step that calls `.backward()` is captured like any other call and the served artifact accumulates `.grad` like eager. `MakeFxTracer` stays the default for two more commits, package and recompile errors surface as `PrecompileError`, and mid-block `save()` is the next commit's, so `save()` on this tracer raises a `PrecompileError` saying its artifact is written when the block exits.

## Where this fits

The stack replaces the callable `torch.compiler.precompile(fn, *example_inputs)` (trace once on inputs passed up front, pair returned in memory) with a caller-driven context manager: `capture(fn, artifact_path=, cache_path=)` is entered with a `with` block, the caller calls it on as many example inputs as they like, the `(python_code, cache)` pair is written to the two files on exit, and `load(artifact_path, cache_path)` serves it in a fresh process. The end-to-end example and the PR-by-PR map live in pytorch#197993's "The new API, end to end" section. This PR is where `capture()` becomes multi-call: `DynamoTracer` takes as many calls as the caller makes and folds every graph break and recompile they exercise into one artifact. It becomes the default tracer in pytorch#198217. The Python 3.10 `-bb` fix to the code-constant walk in `_find_code_source`, which the recursive-capture test here first exercises, lives in pytorch#198528 directly below.

## The golden path

The new tests write a module with a graph-breaking step, capture it over two shapes and a keyword default, and serve it in a fresh process:

```python
# precompile_golden_<uuid>.py, importable from sys.path
def step(model, x, *, scale=1.0):
    y = model(x) * scale * SCALE
    torch._dynamo.graph_break()
    if y.shape[0] > 2:
        y = y + 1
    return y.sum(dim=0)
```

```python
from torch.compiler.precompile import capture, DynamoTracer, load

with capture(step, artifact_path="m.py", cache_path="m.cache", tracer=DynamoTracer(), backend="inductor") as cap:
    y2 = cap(model, x2)               # step and its graph-break continuation
    y3 = cap(model, x3, scale=0.5)    # the branch recompiles the continuation; the keyword is a second entry variant
# exit: TRACER = "dynamo", SERVING_MODE = "standalone", FN_NAME = 'step' in m.py

load("m.py", "m.cache")               # in this process: PrecompileError, the message says to use a fresh process
```

```python
# a fresh process
f = torch.compiler.precompile.load("m.py", "m.cache")
f(model, x2)                          # == y2
f(model, x3, scale=0.5)               # == y3
f(model, x2.double())                 # PrecompileError: no captured variant
```

The last line is the standalone contract: there is no compiler behind a source artifact, so a call no variant covers raises rather than silently serving. `test_graph_breaks_and_recompiles_round_trip_in_a_fresh_process` pins this on both backends, including the in-process collision refusal; `test_a_single_graph_serves_in_process` pins the no-graph-break case, where `load` works in the capturing process, `f.installed` is false, `with f:` and `f.unload()` are no-ops, a second `Model()` swaps weights in, and `f(model, x3)` after a shape-2 capture raises `no captured variant`.

## `DynamoTracer` carries the multi-graph knobs

```python
@dataclasses.dataclass(frozen=True)
class DynamoTracer:
    guard_filter_fn: Callable[[Sequence[Any]], Sequence[bool]] | None = None
    recompile_limit: int = 256
    dynamic: bool | None = None
    require_complete: bool = True
    require_no_risky_drops: bool = True
```

`guard_filter_fn` takes the `GuardFilterEntry` records (`guard_type`, `name`, ...) and returns one keep flag per entry, filtering the guards kept in the serialized artifact (runtime capture guards are always retained; the default drops only what cannot be serialized). `recompile_limit` caps recompilations per frame: a call past it runs eager and is absent from the artifact without any gate refusing it, which the docstring states. `dynamic` forces dynamic shapes as `torch.compile(dynamic=)` does. The `require_*` gates refuse, at write time, an artifact with a coverage gap (`require_complete`: a bypassed or uncovered frame, a call that raised) or one whose dropped guards told captured variants apart or hang off a configuration-chosen slot (`require_no_risky_drops`). Other dropped guards, such as the identity guards every model drops because they cannot be serialized, are listed in the artifact rather than refused; there is deliberately no gate that refuses every drop, since every capture would trip it. The annotation stays `Sequence[Any]` rather than naming `GuardFilterEntry`, because torch/compiler/precompile.py resolves the re-homed classes' annotations with `typing.get_type_hints` at import.

```python
DynamoTracer(dynamic=True)                         # capture single on x2 -> the artifact serves x3 too
DynamoTracer(guard_filter_fn=drop_x)               # exit: PrecompileError "can affect dispatch"
DynamoTracer(guard_filter_fn=drop_x, require_no_risky_drops=False)   # writes an artifact that loads
DynamoTracer(dynamic=False, recompile_limit=1)     # cap(x2); cap(x3) -> served x3 raises "no captured variant"
```

`test_the_tracer_knobs_reach_the_session` pins all four lines, where `drop_x` drops the guard on `x` on top of `default_guard_filter_fn` (dropping what tells the shapes apart). `test_dropped_guards_are_listed_in_the_artifact` shows the default capture of `single` listing `['MODULE_MATCH', ...` in the artifact's dropped guards and writing the artifact regardless.

## `capture()` dispatches on the tracer

```python
tracer: MakeFxTracer | DynamoTracer = MakeFxTracer()
...
if isinstance(tracer, MakeFxTracer):
    return _MakeFxCapture(fn, artifact_path, cache_path, backend=backend, decompositions=tracer.decompositions)
if not isinstance(tracer, DynamoTracer):
    raise TypeError("precompile.capture tracer must be a MakeFxTracer or DynamoTracer, got ...")
if backend not in ("inductor", "eager"):
    raise ValueError(f"precompile backend must be 'inductor' or 'eager', got {backend!r}.")
try:
    session = precompile_capture(fn, backend=backend, guard_filter_fn=tracer.guard_filter_fn, recompile_limit=tracer.recompile_limit, dynamic=tracer.dynamic)
except PackageError as e:
    raise PrecompileError(str(e)) from e
return _DynamoCapture(session, artifact_path, cache_path, require_complete=..., require_no_risky_drops=...)
```

The make_fx front-end validates `backend` when it builds its `PrecompiledModule`; the Dynamo front-end builds none, so `capture()` checks it before creating the session. `precompile_capture`'s up-front refusals now surface as `PrecompileError`. `test_entries_a_standalone_artifact_cannot_rebuild_are_refused` pins the entries a standalone artifact cannot rebuild: a bare `nn.Module` is refused by `capture()` itself (`CALLS the model`: Dynamo compiles its wrapper frame, whose graphs close over the module), and a closure entry is refused once the block calls it (`closes over`), since a code object cannot rebuild what the closure captured. A `functools.partial` never reaches the tracer: `capture()` refuses it with a `TypeError` (`takes the function itself, not a functools.partial`) before dispatching. `_MakeFxCapture`'s two refusals (a keyword argument, a second call) now point at `tracer=DynamoTracer()` instead of just explaining themselves.

## `_DynamoCapture` drives the session

Entering the block opens a fresh cache before the session, and undoes it if the session refuses to enter:

```python
def __enter__(self):
    with self._lock:
        if self._call is not None or self._exited:
            raise PrecompileError("this capture has already been entered; capture() returns a fresh capture per call.")
        self._fresh_cache = CacheArtifactManager.with_fresh_cache()
        self._fresh_cache.__enter__()
        try:
            self._call = self._map(self._session.__enter__)
        except BaseException:
            self._fresh_cache.__exit__(None, None, None)
            self._fresh_cache = None
            raise
    return self
```

The capture's compiles record into the process-global cache-artifact list, which the cache half of the artifact bundles to prime the kernel caches on load; a fresh one means the bundle holds only this capture's compiles. The swap spans the whole `with` block, not just the calls, so the `capture()` docstring now says a `DynamoTracer` capture records the kernel-cache artifacts of everything compiled inside the block: compile nothing else there, and do not overlap two such captures. `_map` is the one place `PackageError` and `RecompileError` become `PrecompileError`.

Each call is serialized under an `RLock`, refuses a call before `__enter__` or after `__exit__` (`capture is not active`), refuses `fn` calling the capture it is being captured through (`re-entered recursively`), and counts the call before it runs:

```python
def __call__(self, *args, **kwargs):
    with self._lock:
        ...
        self._in_call = True
        # Counted before the call: a call that raised is for the session's
        # require_complete gate to report, not "nothing was captured".
        self._calls += 1
        try:
            return self._map(self._call, *args, **kwargs)
        finally:
            self._in_call = False
```

The lock is what makes concurrent callers safe: every call feeds the one session, and without it a call that finds another thread's call in flight would trip the `_in_call` check and be refused as a recursive re-entry. `test_calls_from_several_threads_are_serialized` starts eight threads (four on `x2`, four on `x3`) inside one block, checks each result against eager `step`, and asserts no errors and a written artifact. Counting attempts rather than successes matters for a block whose only calls raised: it made calls, so exit goes on to `snapshot_artifact`, and the session's `require_complete` report lists the capture errors instead of the misleading `nothing was captured`.

Exit writes on a clean block only, and holds a gate refusal until the session and cache are torn down:

```python
def __exit__(self, *exc):
    with self._lock:
        error = None
        try:
            if exc[0] is None:
                try:
                    if self._calls == 0:
                        raise PrecompileError("nothing was captured: call the capture with your example arguments inside the `with` block.")
                    self._write()        # snapshot_artifact(**gates) then _write_artifact(...)
                except BaseException as e:
                    error = e
            self._exited = True
            try:
                self._map(self._session.__exit__, *exc)
            except BaseException as e:
                if error is None:
                    raise
                raise e from error
        finally:
            if self._fresh_cache is not None:
                self._fresh_cache.__exit__(None, None, None)
                self._fresh_cache = None
    if exc[0] is None and error is not None:
        raise error
```

A teardown error that follows a gate refusal is raised `from` the refusal, so the refusal is not lost, and the fresh cache is always exited with `(None, None, None)` rather than with the in-flight exception. `_write` renders through `self._session.snapshot_artifact(**self._gates)` and hands the pair to `_write_artifact`; an `OSError` there becomes a `PrecompileError` (`precompile could not write the artifact`), and since `_write_artifact` leaves the previous pair in place the last good pair is still loadable.

`test_a_raised_call_is_refused_at_exit_and_writes_nothing` pins the gate: a second call with `torch.randn(2, 5)` into a `Linear(4, 4)` raises `RuntimeError` inside the block, the block itself runs to completion, exit raises `PrecompileError` (`captured call raised`) through `require_complete`, and neither `m.py` nor `m.cache` exists afterwards. The same test covers a block whose only call raised, which reaches the same `captured call raised` gate rather than `nothing was captured`, and `DynamoTracer(require_complete=False)`, which writes the partial artifact instead.

`test_misuse_is_refused` pins the rest of the lifecycle:

```python
capture(single, ..., tracer=DynamoTracer(), backend="aot_eager")   # ValueError: backend
capture(single, ..., tracer=object())                              # TypeError: tracer must be
cap(model, x2)                        # before the block: PrecompileError "not active"
with cap: pass                        # PrecompileError "nothing was captured"
with cap: pass                        # again: PrecompileError "already been entered"
cap(model, x2)                        # after it: PrecompileError "not active"
cap(Reentrant(), x2)                  # forward calls cap: PrecompileError "re-entered recursively"
raise KeyError("the block's own")     # inside a block: propagates unchanged, nothing written
# _write_artifact mocked to raise OSError: PrecompileError "could not write"
```

## Grad mode and the training step

`capture()` has no grad-mode flag. A Dynamo capture runs every call in the caller's own grad mode and lowers a backward whenever grad is enabled: a `.backward()` in `fn` graph-breaks and re-runs at serve time through the live autograd engine, accumulating `.grad` like eager, so the artifact should be served under the grad mode it was captured in.

```python
def train_step(model, x):
    model(x).sum().backward()

with capture(train_step, ..., tracer=DynamoTracer(), backend=backend) as cap:   # backend: "inductor" or "eager"
    cap(model, x2)                    # returns None; model.lin.weight.grad matches an eager step

# a fresh process, model reloaded from the pre-step state dict
f = torch.compiler.precompile.load("m.py", "m.cache")
f(model, x2)                          # returns None; every parameter's .grad matches the eager step
```

`test_training_step_grads_match_eager_in_a_fresh_process`, parametrized over `inductor` and `eager`, pins this: it runs an eager step on a `Model` loaded from the same state dict, checks the capture's `lin.weight` grad against it, restores the pre-step weights, and serves the artifact in a fresh process, asserting each parameter's `.grad` against the eager one.

## The artifact does not mix with a make_fx pair

`test_a_dynamo_pair_does_not_mix_with_a_make_fx_pair` captures `single` once with `DynamoTracer()` and once with `MakeFxTracer()` into two pairs; `load` of the Dynamo artifact with the make_fx cache raises `PrecompileError` mentioning `tracer`, and the reverse raises `tracer` or `does not match`. `load`'s docstring now says a Dynamo artifact takes keyword arguments, carries its compiled subgraphs inside `python_code` so it serves without JIT even with no usable cache, is a no-op to enter and unload, re-seeds the names Dynamo minted into the captured module, and must be loaded in a fresh process when its capture graph-broke.

## Exports, docs and scope

`DynamoTracer` joins `torch.compiler.precompile.__all__`, the `__module__` re-homing loop, the public-members test, and the API reference (`.. autoclass:: torch.compiler.precompile.DynamoTracer` in docs/source/torch.compiler_api.md). The tests pass `tracer=DynamoTracer()` explicitly through `_capture`. Mid-block `save()` checkpoints and the `summary()` report are the next commit's (pytorch#198227), so `_DynamoCapture.save()` raises `PrecompileError` (`save() is not supported on a DynamoTracer capture yet: its artifact is written when the block exits.`) rather than the base class's bare `NotImplementedError`, and the `capture()` and `Capture` docstrings' `save()` sentences say it applies to a `MakeFxTracer` capture only, for now. The module Note's `tracer:` paragraph now describes both tracers (`MakeFxTracer` the default; `DynamoTracer` standalone and version-locked, with invariants 1, 2, 3 and 6 left as the make_fx contract, refusing uncovered calls through its guards and listing the guards it could not serialize as `DROPPED_GUARDS`) instead of saying `dynamo` raises `NotImplementedError`. Deliberately absent, as follow-ups: the installed serving mode (`load(fn=)`), the rendered-as-source subgraphs, the invariants report and the per-frame drift probe. The fresh-process tests are skipped under the crossref harness, whose active dispatch mode Dynamo guards on and a fresh process lacks.

## What this leaves for later PRs

- Mid-block `save()` comes in pytorch#198227. Here, `save()` on a Dynamo capture raises `PrecompileError`.
- Making `DynamoTracer` the default tracer comes in pytorch#198217. Here `MakeFxTracer` is still the default.
- The lifecycle refactor is pytorch#198423. The `__enter__`/`__call__`/`__exit__` bodies quoted above become `_start`/`_run`/`_finish` on the shared `Capture` base class there. The behaviour is the same, but the code at the top of the stack looks different from what this description shows.
- Installed serving. This PR is standalone only, and lists installed mode above as a follow-up (`load(fn=)`). pytorch#198523 is that follow-up, except that the mode is picked automatically when the artifact is written rather than through a `load(fn=)` argument. So the `capture()` docstring paragraph this PR adds ("A Dynamo artifact is STANDALONE ... is refused at write time") is one of the stale docstrings on pytorch#198523's cleanup list, together with `PrecompileSession`'s, which comes from a lower PR.

Test Plan:

`TestPrecompileDynamoCapture` in test/test_precompile.py, passing `tracer=DynamoTracer()` explicitly: the graph-break/recompile round trip through a fresh process on both backends (with the in-process collision refusal), a single-graph capture served in process (weight swap, no-op enter/unload, uncovered call), a training step on both backends served in a fresh process whose `.grad` matches eager, the raised-call gate at exit (including a block whose only call raised, and `require_complete=False` writing the partial artifact), the misuse refusals (bad backend or tracer, a call outside the block, a re-entered or recursive capture, an empty block, a block raising its own exception, a write failure), calls from eight threads at once (which, unserialized, are refused as recursive re-entries), the `dynamic`, `guard_filter_fn`, `require_no_risky_drops` and `recompile_limit` knobs, the dropped guards listed in the artifact, the module/closure/partial refusals, and the make_fx/dynamo pair mismatch. The fresh-process tests are skipped under the crossref harness, whose active dispatch mode Dynamo guards on and a fresh process lacks.

```
python test/test_precompile.py
PYTORCH_TEST_WITH_CROSSREF=1 python test/test_precompile.py -k TestPrecompileDynamoCapture
lintrunner -a torch/_precompile.py torch/compiler/precompile.py test/test_precompile.py docs/source/torch.compiler_api.md
```

Authored with an AI assistant.

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

Pull Request resolved: pytorch#198138
Approved by: https://github.com/MengjiaoZhou
ghstack dependencies: pytorch#198211, pytorch#198223, pytorch#198283, pytorch#198284, pytorch#197993, pytorch#198213, pytorch#198135, pytorch#198243, pytorch#198214, pytorch#198136, pytorch#198215, pytorch#198137, pytorch#198216, pytorch#198528, pytorch#199883
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…ytorch#198227)

**Problem.** A Dynamo capture wrote its artifact only when the `with` block exited cleanly, so a job that died mid-loop left nothing on disk, and there was no way to read the coverage or guard report the session had built up.

**Fix.** `_DynamoCapture` gains `save()`, which checkpoints everything captured so far to the same two files without ending the capture, and `summary()`, which returns the session's `PrecompileSummary` inside the block and after it.

**Summary.** A Dynamo capture that dies mid-loop left nothing on disk, because the artifact was written only on a clean exit. `_DynamoCapture.save()` now renders and writes everything captured so far to the same `artifact_path` / `cache_path` pair without ending the capture, so each call re-renders and rewrites both files and a job that dies between saves leaves the last checkpoint loadable, while a gate refusal or a write failure raises and writes nothing partial with the capture still open. Exit writes only when there are calls the last save did not cover, tracked as the call count the last write saw, which starts at `-1` so a block that never called still raises the nothing-captured error rather than writing an empty artifact. Calls, saves and `summary()` share the capture's one lock, so a `save()` never snapshots the capture mid-compile, and a `save()` from inside `fn` is refused. `summary()` exposes the session's `PrecompileSummary` -- coverage, recompilation, failure and guard information for everything captured so far -- readable inside the block and after it, including after a gate refusal, since the refusal is raised only after teardown.

## Where this fits

The stack replaces the callable `torch.compiler.precompile(fn, *example_inputs)` (trace once on inputs passed up front, pair returned in memory) with a caller-driven context manager: `capture(fn, artifact_path=, cache_path=)` is entered with a `with` block, the caller calls it on as many example inputs as they like (each graph break and recompiled variant is folded in), the `(python_code, cache)` pair is written to the two files on exit, and `load(artifact_path, cache_path)` serves it in a fresh process. The end-to-end example and the PR-by-PR map live in pytorch#197993's "The new API, end to end" section. This PR adds `cap.save()` checkpoints and `cap.summary()` (coverage, recompiles, dropped guards) to the multi-call `DynamoTracer` capture from pytorch#198138.

## save() checkpoints mid-block

The parent wrote once, from `__exit__`, and its `save()` raised "not supported on a DynamoTracer capture yet". `save()` is now the same `_write()` -- `snapshot_artifact(**self._gates)` then `_write_artifact` -- callable from inside the block, behind the same three refusals a call has (not entered or already exited, inside `fn`, nothing captured yet):

```python
with capture(single, artifact_path=artifact, cache_path=cache, tracer=DynamoTracer()) as cap:
    cap.save()                 # PrecompileError: nothing was captured ...
    cap(model, x2)
    cap.save()                 # write 1: m.py / m.cache hold the x2 variant, loadable now
    cap(model, x3)
    cap.save()                 # write 2: both files rewritten, now differ from write 1
# exit: the last save() covered every call -> no third write
cap.save()                     # PrecompileError: capture is not active ...
cap.summary().complete         # True: still readable after exit
```

Each `save()` rewrites both files from scratch. A `require_*` gate refusal or an `OSError` from the rewrite raises out of `save()` as a `PrecompileError`; `_write_artifact` leaves the previous pair in place, so the last good checkpoint is still loadable and the capture stays open for more calls or another `save()`. A `save()` from inside `fn` is refused, and that refused call is a raised call, so a block that then raises writes nothing and the previous pair survives:

```python
class SavesFromFn(torch.nn.Module):
    def forward(self, x):
        return torch._dynamo.disable(cap.save)()

with capture(single, ...) as cap:
    cap(SavesFromFn(), x2)     # PrecompileError: save() was called from inside fn ...
    raise KeyError("the block's own")
# m.py is still byte-equal to the last checkpoint above
```

With `save()` now on both tracers, the `Capture`, `Capture.save` and `capture()` docstrings drop the parent's "a `MakeFxTracer` capture only, for now" qualifier.

## Exit writes only what the last save did not cover

Exit tracks the call count the last write saw:

```python
# __init__
self._saved_calls = -1          # not 0: a block that never called is still dirty at exit

# _write, after _write_artifact succeeds
self._saved_calls = self._calls

# __exit__: parent wrote on every clean exit
if exc[0] is None:
# now
if exc[0] is None and self._calls > self._saved_calls:
```

So a block whose last `save()` covered every call writes nothing at exit, a block with calls after the last `save()` writes a final checkpoint, and a block that never called (`_calls` is 0, above the `-1` start) still reaches the `"nothing was captured"` error instead of writing an empty artifact. A block that raised still writes nothing, as before. Because `__call__` counts a call before running it, a call that raised after the last `save()` still makes the block dirty, so it reaches the exit gate and is refused there:

```python
with capture(step, ...) as cap:
    cap(model, x2)
    cap.save()
    cap(model, torch.randn(2, 5))   # raises RuntimeError, but _calls is already 2
# exit: PrecompileError: captured call raised ...
```

## summary() inside and after the block

```python
with capture(step, artifact_path=artifact, cache_path=cache, tracer=DynamoTracer()) as cap:
    cap(model, x2)
    cap(model, x3, scale=0.5)
    summary = cap.summary()
summary.complete           # True
summary.frames             # 2: the entry and its graph-break continuation
summary.resume_functions   # 1
summary.guarded_codes      # >= 3: a variant per call the guards told apart
```

`summary()` is `self._map(self._session.summary)` under the capture's lock, so `PackageError` / `RecompileError` surface as `PrecompileError` like every other session call. It is readable after a gate refusal too, because `__exit__` holds the refusal and re-raises it only after teardown:

```python
with self.assertRaisesRegex(PrecompileError, "captured call raised"):
    with capture(step, ...) as cap:
        cap(model, x2)
        with self.assertRaises(RuntimeError):
            cap(model, torch.randn(2, 5))
        cap.summary().complete     # False: the raised call is a coverage gap
cap.summary().complete             # False, after the refusal
# nothing written: neither m.py nor m.cache exists
```

The dropped guards move from being documented as an artifact list (`DROPPED_GUARDS`) to being reported through the capture's `summary()`; the artifact still lists the same slots:

```python
with capture(single, ...) as cap:
    cap(model, x2)
    summary = cap.summary()
"MODULE_MATCH" in summary.dropped_guard_types   # the default filter drops the model identity guard
summary.kept_guards                             # non-empty
summary.risky_dropped_guards                    # ()
for guard_type, source in summary.dropped_guards:
    assert f"[{guard_type!r}, {source!r}]" in open(artifact).read()
```

## Tests

- `test_save_checkpoints_mid_block` enters a `mock.patch` wrapping `_write_artifact` before the capture, so the count also sees any write exit makes. It pins the pre-call `"nothing was captured"` refusal, loads the first checkpoint in process, reads the file again after the second `save()` (`call_count == 2`, bytes differ from the first checkpoint), checks exit leaves `call_count` at 2, refuses `save()` after exit (`"not active"`) and from inside `fn` (`"from inside fn"`), reads `summary()` after exit, and checks the file still equals the last checkpoint after the block raised `KeyError`.
- `test_a_raised_call_is_refused_at_exit_and_writes_nothing` gains the `summary().complete` assertions inside and after the refused block, and a case where the call raises after a `save()`; that case fails with `_calls += 1` moved after the call.
- `test_dropped_guards_are_reported_in_the_summary_and_the_artifact` replaces the parent's `test_dropped_guards_are_listed_in_the_artifact`.
- `test_graph_breaks_and_recompiles_round_trip_in_a_fresh_process` gains the `frames` / `resume_functions` / `guarded_codes` assertions shown above.

Test Plan:

`test_save_checkpoints_mid_block` checkpoints after the first call and loads that checkpoint in process, saves again after the second call and checks that exit writes nothing more, and refuses a save() after exit or from inside `fn`, with `summary()` still readable after exit; `test_a_raised_call_is_refused_at_exit_and_writes_nothing` also pins that a call raising after the last save() still reaches the exit gate (it fails with `_calls += 1` moved after the call) and that `summary()` is readable after the refusal; `test_dropped_guards_are_reported_in_the_summary_and_the_artifact` reads the default filter's drops from the summary and the artifact; the round-trip and raised-call tests gain their summary assertions. `summary()` reads the session under the capture's lock, like calls and saves.

```
python test/test_precompile.py
lintrunner -a torch/_precompile.py test/test_precompile.py
```

Authored with an AI assistant.

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

Pull Request resolved: pytorch#198227
Approved by: https://github.com/MengjiaoZhou
ghstack dependencies: pytorch#198211, pytorch#198223, pytorch#198283, pytorch#198284, pytorch#197993, pytorch#198213, pytorch#198135, pytorch#198243, pytorch#198214, pytorch#198136, pytorch#198215, pytorch#198137, pytorch#198216, pytorch#198528, pytorch#199883, pytorch#198138
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…pytorch#198217)

**Problem.** `capture()` still defaults to `MakeFxTracer()`, a single non-strict trace that takes exactly one positional call, although the Dynamo front-end is served and takes as many calls as the caller makes; the docs' example `fn` is a lambda, which the standalone Dynamo artifact refuses.

**Fix.** Flip the default to `DynamoTracer()`, move the "(the default)" marker in the docstrings and Note [precompile programming model] to `DynamoTracer`, show a module-level `step` with two calls in the docs, and let the Dynamo tests rely on the default.

**Summary.** Until this commit a bare `capture(step, artifact_path=..., cache_path=...)` was a make_fx capture that accepted exactly one positional call and refused a second, so a caller who wanted the multi-call Dynamo capture had to ask for it with `tracer=DynamoTracer()`. Now the bare call is the Dynamo capture, which takes as many calls as the caller makes, keyword arguments included, and `tracer=MakeFxTracer()` is the explicit opt-in. The Dynamo default does refuse some `fn`s a `MakeFxTracer` capture accepts: its standalone artifact rebuilds the entry from its code object, so `fn` must be a module-level function of an importable module, not a lambda or a closure. The make_fx form stays available for those and for the single non-strict trace with its explicit contract. Neither tracer's behaviour changes; the module docstring, the Note's tracer paragraph, the `capture()` docstring, the API reference and the user guide now name `DynamoTracer` as the default, and the one test that silently relied on the old default is pinned to `MakeFxTracer` with a Dynamo twin added.

## Where this fits

The stack replaces the callable `torch.compiler.precompile(fn, *example_inputs)` (trace once on inputs passed up front, pair returned in memory) with a caller-driven context manager: `capture(fn, artifact_path=, cache_path=)` is entered with a `with` block, the caller calls it on as many example inputs as they like (each graph break and recompiled variant is folded in), the `(python_code, cache)` pair is written to the two files on exit, and `load(artifact_path, cache_path)` serves it in a fresh process. This PR makes `DynamoTracer` the default tracer, so `capture()` is multi-call out of the box, and makes the docs describe that API.

## The default flips

```python
def capture(fn, /, *, artifact_path, cache_path,
            tracer: MakeFxTracer | DynamoTracer = MakeFxTracer(),   # parent
            tracer: MakeFxTracer | DynamoTracer = DynamoTracer(),   # now
            backend: str = "inductor") -> Capture:
```

What a caller observes, with `step` a module-level function of an importable module:

```python
with torch.compiler.precompile.capture(
    step, artifact_path="m.py", cache_path="m.cache"
) as cap:
    y1 = cap(model, x1)
    y2 = cap(model, x2)   # parent: refused, make_fx takes exactly ONE positional call
                          # now: folded in, a recompile or graph break becomes another variant

# The single non-strict trace is still there, asked for by name, and it is the
# only form that also takes a lambda:
with torch.compiler.precompile.capture(
    lambda model, x: model(x), artifact_path="fx.py", cache_path="fx.cache",
    tracer=MakeFxTracer(),
) as cap:
    y = cap(model, x1)    # exactly one call, under the Note's contract
```

The flip is not a pure widening. The Dynamo default takes more calls, but its artifact is STANDALONE and rebuilds the entry from its code object, so a lambda, a closure or a function defined in `__main__` that a make_fx default accepted is now refused and needs `tracer=MakeFxTracer()`.

## The docstrings name the default

The module docstring of `torch/_precompile.py` now lists `DynamoTracer` among the re-exported public types (`Capture`, `DynamoTracer`, `MakeFxTracer`, `PrecompiledRunnable`) and describes both front-ends over the one pair they both write, the default first: `DynamoTracer` drives a `PrecompileSession` (`torch/_dynamo/precompile_package.py`) across the caller's calls, and the multi-graph frame records and driver emitter render every frame Dynamo compiled (the entry, its graph-break continuations and its recompiled variants); `MakeFxTracer` drives `PrecompiledModule`, a NON-STRICT make_fx trace of one execution of `fn`, lowered through `compile_to_python` with `backend="inductor"` or inlined with `backend="eager"`.

The tracer paragraph of Note [precompile programming model] moves "(the default)" from `MakeFxTracer` to `DynamoTracer`, and now says the guards that could not be serialized are reported in `PrecompileSummary.dropped_guards` (it said "listed in the artifact (DROPPED_GUARDS)"). Its content is otherwise unchanged: invariants 1, 2, 3 and 6 are the make_fx contract, and under Dynamo a call outside the captured variants is REFUSED by the guards rather than silently served.

`DynamoTracer`'s class docstring gains "(the default)", and the `capture()` docstring moves the marker from the `MakeFxTracer` sentence to the `DynamoTracer` one. Its example `fn` changes accordingly:

```python
# parent
# ``fn`` is the whole computation, e.g. ``lambda model, x: model(x)``: ...
# now
# ``fn`` is the whole computation, e.g. a module-level ``def step(model, x): return
# model(x)`` (only a :class:`MakeFxTracer` capture also takes a lambda): ...
```

## The docs show the multi-call capture

`docs/source/torch.compiler_api.md` and `docs/source/user_guide/torch_compiler/torch.compiler.md` swap the `lambda model, x: model(x)` example for a module-level `step` and two calls:

```python
# step is a module-level function: def step(model, x): return model(x)
with torch.compiler.precompile.capture(
    step, artifact_path="m.py", cache_path="m.cache"
) as cap:
    y1 = cap(model, x1)
    y2 = cap(model, x2)  # a recompile or graph break becomes another variant

f = torch.compiler.precompile.load("m.py", "m.cache")  # in a fresh process
y = f(model, x1)
```

The API reference also explains the two tracers in one sentence (the default `DynamoTracer` records every frame Dynamo compiles and the artifact dispatches among them by their guards; `MakeFxTracer` is a single non-strict trace under the Note's contract) and lists `DynamoTracer` ahead of `MakeFxTracer` in the autoclass entries.

## Tests

`TestPrecompileDynamoCapture._capture` in `test/test_precompile.py` drops its `kwargs.setdefault("tracer", DynamoTracer())`, so every Dynamo test now exercises the default the way a user hits it. The make_fx tests already pass `tracer=MakeFxTracer()` explicitly (`TestPrecompileCapture._capture` sets it as a default kwarg), with one exception: `test_capture_takes_pathlike_paths_and_the_default_tracer` called `capture()` directly with no tracer and a module-level `_files_fn`. It is renamed `test_capture_takes_pathlike_paths` and pins `tracer=MakeFxTracer()`, and `TestPrecompileDynamoCapture` gets its own `test_capture_takes_pathlike_paths`, which captures the generated module's `single` under the default tracer with `pathlib.Path` paths and checks the loaded result, so the default tracer keeps that coverage.

Test Plan:

```
python test/test_precompile.py
python test/dynamo/test_precompile_package.py
lintrunner -a torch/_precompile.py test/test_precompile.py docs/source/torch.compiler_api.md docs/source/user_guide/torch_compiler/torch.compiler.md
```

Authored with an AI assistant.

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

Pull Request resolved: pytorch#198217
Approved by: https://github.com/MengjiaoZhou
ghstack dependencies: pytorch#198211, pytorch#198223, pytorch#198283, pytorch#198284, pytorch#197993, pytorch#198213, pytorch#198135, pytorch#198243, pytorch#198214, pytorch#198136, pytorch#198215, pytorch#198137, pytorch#198216, pytorch#198528, pytorch#199883, pytorch#198138, pytorch#198227
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
**Problem.** Each tracer's capture ran its own `with`-block lifecycle from its own flags, so a Dynamo capture misused after its block gave different errors than a make_fx one, and a spent make_fx capture kept the pair its docstring says it drops.

**Fix.** `Capture` owns the lifecycle as one state field under one lock, and the tracers implement only the hooks it calls.

**Summary.** `_MakeFxCapture` tracked its block with two booleans, `_entered` and `_exited`, which are really three states, and `_DynamoCapture` kept its own `_exited` flag and its own copies of `__enter__`, `__exit__`, `__call__` and `save()`. The two front-ends therefore drifted: a Dynamo capture called after its block said "not active" where make_fx says "already exited", and make_fx's `__exit__` never cleared the pair that `Capture`'s docstring says a spent capture does not keep. `Capture` now holds the lifecycle as one field, `new`/`active`/`spent`, owns the four methods and their not-active, already-entered and spent messages, and a tracer implements only `_start`, `_run`, `_save` and `_finish`, where `_finish` drops the pair on every exit. The Dynamo capture's `RLock`, which serializes the block's calls, saves, exit and `summary()` because every call feeds one `PrecompileSession`, moves into `Capture` with the lifecycle. The messages a make_fx capture gives do not change, and a Dynamo capture now gives the same ones.

These are review cleanups on `capture()` from pytorch#198135; that PR and pytorch#198243 are approved, so both are left as they are. The `Generic` typing of `Capture` and the tensor-only leaves snapshot that earlier revisions of this PR carried now live in pytorch#198529 and pytorch#198530.

## What a Dynamo capture says now

```python
cap = capture(fn, ...)          # a DynamoTracer capture
cap(x)                          # "before calling it" (unchanged)
with cap:
    with cap: ...               # "already been entered" (unchanged)
cap(x)                          # after the block: a call, save() or `with cap:`
# parent: "not active" / "already been entered"
# now:    "already exited", the same as make_fx
```

The `save()` checkpoint contract moves from `_DynamoCapture`'s override onto the public `Capture.save` docstring, since it holds for both tracers and `help(cap.save)` shows only the base docstring: each call rewrites both files, a refusal or failed write raises but writes nothing partial and the capture stays open, and it raises `PrecompileError` outside the `with` block. `test_calls_from_several_threads_are_serialized` pins the lock.

Test Plan:

`test_misuse_is_refused` in `TestPrecompileDynamoCapture` moves to the shared messages, and `test_save_checkpoints_mid_block` now expects "already exited" for a save after exit. The make_fx lifecycle tests pass without changes (`test_a_capture_must_be_entered_before_it_is_called`, `test_a_capture_is_over_once_its_block_exits`, `test_save_after_a_raising_block_is_refused`, `test_a_capture_is_single_use`), which pins that its messages did not move.

```
python test/test_precompile.py
python test/dynamo/test_precompile_package.py
lintrunner -a torch/_precompile.py test/test_precompile.py
```

Authored with an AI assistant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Pull Request resolved: pytorch#198423
Approved by: https://github.com/MengjiaoZhou
ghstack dependencies: pytorch#198211, pytorch#198223, pytorch#198283, pytorch#198284, pytorch#197993, pytorch#198213, pytorch#198135, pytorch#198243, pytorch#198214, pytorch#198136, pytorch#198215, pytorch#198137, pytorch#198216, pytorch#198528, pytorch#199883, pytorch#198138, pytorch#198227, pytorch#198217
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
**Summary.** `capture()` took `fn: Callable[..., object]` and `Capture.__call__` returned `object`, so calling a capture threw away `fn`'s types. The documented `y = cap(model, x); y.sum()` therefore failed type-checking, and every typed caller had to cast. `Capture` is now `Generic[_P, _R]` over `fn`'s signature, the same way `torch.compile` types its result with `_InputT`/`_RetT`, and `capture(fn: Callable[_P, _R], ...)` returns `Capture[_P, _R]`. Returning a `Callable[_P, _R]` would not work, because that type has no `__enter__` or `save()`. Nothing changes at runtime, and `load()` stays untyped, since it rebuilds the callable from disk.

Review cleanup on `capture()` from pytorch#198135, stacked at the top like the lifecycle change below it.

```python
def step(model: torch.nn.Module, x: torch.Tensor) -> torch.Tensor:
    return model(x)

with capture(step, artifact_path="m.py", cache_path="m.cache") as cap:
    y = cap(model, x)  # parent: y: object; now: y: Tensor
    y.sum()
```

Test Plan:

No runtime behaviour changes. To check the typing, I ran pyrefly on a scratch caller: `y = cap(torch.nn.Linear(2, 2), torch.randn(2))` infers `y: Tensor`, and `cap("not a module", 3)` is reported as two `bad-argument-type` errors. No CI check pins this inference.

```
python test/test_precompile.py
lintrunner -a torch/_precompile.py
```

Authored with an AI assistant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Pull Request resolved: pytorch#198529
Approved by: https://github.com/MengjiaoZhou
ghstack dependencies: pytorch#198211, pytorch#198223, pytorch#198283, pytorch#198284, pytorch#197993, pytorch#198213, pytorch#198135, pytorch#198243, pytorch#198214, pytorch#198136, pytorch#198215, pytorch#198137, pytorch#198216, pytorch#198528, pytorch#199883, pytorch#198138, pytorch#198227, pytorch#198217, pytorch#198423
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…ts (pytorch#198530)

**Summary.** `_trace_without_side_effects` snapshots the buffers and tensor inputs a static trace could mutate, so the serve that follows is the only execution the caller sees. It built `tensors` from the module buffers plus every pytree leaf of `args`, the modules themselves and any non-tensor leaves included, and applied `isinstance(t, torch.Tensor)` only inside the snapshot comprehension. The leaves are now filtered to tensors up front, so `tensors` holds only tensors and the snapshot needs no type check. The parameter-exclusion set loses the non-tensor ids too, which never matched anything because a live non-tensor object cannot share an id with a live parameter. What gets snapshotted is unchanged; this is review cleanup from pytorch#198243, which is approved, so it lands here at the top of the stack instead of in that commit.

```python
# parent
leaves = pytree.tree_leaves(args)
saved = {id(t): (t, t.detach().clone()) for t in tensors if isinstance(t, torch.Tensor) and id(t) not in params}
# now
leaves = [t for t in pytree.tree_leaves(args) if isinstance(t, torch.Tensor)]
saved = {id(t): (t, t.detach().clone()) for t in tensors if id(t) not in params}
```

Test Plan:

`test_a_capture_applies_in_place_updates_once`, `test_a_capture_refuses_an_in_place_parameter_update` and `test_a_trace_that_raises_leaves_buffers_and_inputs_as_they_were` in test/test_precompile.py cover this path and pass unchanged.

```
python test/test_precompile.py
lintrunner -a torch/_precompile.py
```

Authored with an AI assistant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Pull Request resolved: pytorch#198530
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: pytorch#198211, pytorch#198223, pytorch#198283, pytorch#198284, pytorch#197993, pytorch#198213, pytorch#198135, pytorch#198243, pytorch#198214, pytorch#198136, pytorch#198215, pytorch#198137, pytorch#198216, pytorch#198528, pytorch#199883, pytorch#198138, pytorch#198227, pytorch#198217, pytorch#198423, pytorch#198529
pytorchmergebot pushed a commit that referenced this pull request Oct 12, 2026
…ard lists (#198920)

Addresses aorenste's review of #198136, which is approved and so is left
untouched.

A multi-graph artifact rendered `DROPPED_GUARDS` and `RISKY_DROPPED_GUARDS` but
not `PrecompileSummary.policy_dropped_guards`, while `DROPPED_GUARD_CODE` draws
its slots from both `dropped_guards` and `policy_dropped_guards`. So the
artifact could list the check for a slot that no list above it names, and a
capture that discarded a precondition by policy would read like one that had
none. `_parse_artifact_metadata` already accepts `POLICY_DROPPED_GUARDS`, so the
renderer now writes it next to the other two. Nothing fills the field yet
(`PrecompileSession` passes an empty policy set), so this is latent until the
invariance policy is wired in, and today's artifacts gain an empty list.

Test Plan:

`test_multigraph_artifact_round_trips_a_hand_built_package` now builds its
summary with a policy drop and that drop's guard code. It checks that the
rendered `POLICY_DROPPED_GUARDS` round-trips, and that every slot in
`DROPPED_GUARD_CODE` is named by `DROPPED_GUARDS` or `POLICY_DROPPED_GUARDS`.
With the render line removed, the test fails with `KeyError:
'POLICY_DROPPED_GUARDS'`.

```
python test/test_precompile.py -k round_trips_a_hand_built
python test/test_precompile.py
lintrunner test/test_precompile.py torch/_precompile.py
```

This PR was authored with the help of an AI assistant (Claude).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Pull Request resolved: #198920
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #198558
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1444/head branch November 30, 2026 01:52
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.

3 participants