Skip to content

[precompile] Route the callable API's tests through the pair helpers - #198211

Closed
bobrenjc93 wants to merge 3 commits into
gh/bobrenjc93/1447/basefrom
gh/bobrenjc93/1447/head
Closed

bobrenjc93 wants to merge 3 commits into
gh/bobrenjc93/1447/basefrom
gh/bobrenjc93/1447/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Problem. torch.compiler.precompile(fn, *example_inputs) is being replaced by a module whose entry points take the caller's own calls and file paths, and that switch cannot land while roughly 250 call sites in test/test_precompile.py spell the callable directly.

Fix. A test-only commit: every direct use of the callable and of precompile.load in the suite now goes through the file's two module-level helpers, _precompile_pair(fn, *args, **kwargs) and the new _load_pair(python_code, cache), so the switch above re-points the whole suite in one place.

Summary. test/test_precompile.py spelled torch.compiler.precompile(...) and torch.compiler.precompile.load(...) at roughly 250 call sites, so the module-form switch above this commit could not land without editing every one of them alongside the library change. The tests themselves are worth keeping: almost all of them exercise the make_fx capture, the drivers' runtime checks and the loader's envelope handling, which the module form keeps. This commit changes no behaviour and no library code; it routes every direct use of the callable through the file's existing _precompile_pair indirection (added with the fake-tensor capture for exactly this purpose) and a matching _load_pair for precompile.load. The two helpers are the only places in the suite that still name the entry points, so the switch re-points them once and the suite runs unchanged on either side of it. The handful of tests that assert on the callable object itself (its identity, pickling and public binding) still spell it, and go with the switch.

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 groundwork with no behaviour change: it routes the old callable API's tests through the _precompile_pair / _load_pair helpers, so the retirement in #197993 can switch the helpers instead of deleting tests.

The two indirection points

_precompile_pair already existed; its docstring is rewritten to say what it is now for, and _load_pair is added next to it. Nothing under torch/ changes.

# test/test_precompile.py, module level
def _precompile_pair(fn, *args, **kwargs):
    """One indirection point over the callable entry point: every test below drives
    the make_fx capture through this helper rather than spelling the callable, so a
    change of entry point re-points the whole suite here."""
    return torch.compiler.precompile(fn, *args, **kwargs)

def _load_pair(python_code, cache):
    """Reconstruct a runnable from an in-memory ``(python_code, cache)`` pair through
    the callable API's ``load``; the second indirection point, for the same reason."""
    return torch.compiler.precompile.load(python_code, cache)

The _default_and_inlined_loaders fixture, which every "default vs inlined path" test iterates, is rerouted the same way, so the inlined path's _strip_artifact(cache) still flows into the same loader:

# parent
yield "default", torch.compiler.precompile.load(code, cache)
if backend == "inductor":
    yield "inlined", torch.compiler.precompile.load(code, _strip_artifact(cache))

# now
yield "default", _load_pair(code, cache)
if backend == "inductor":
    yield "inlined", _load_pair(code, _strip_artifact(cache))

What a rewritten call site looks like

Each hunk is a mechanical rename; positional arguments, keyword arguments (backend=, decompositions=, tracer=, **kwargs) and the surrounding assertions are untouched. test_export_and_reload_roundtrip is representative:

# parent
code, cache = torch.compiler.precompile(lambda model, x: model(x), m, x)
self.assertIn("PARAM_NAMES = ['lin.weight', 'lin.bias']", code)
f_c = torch.compiler.precompile.load(code, cache)
self.assertEqual(f_c(m, x), m(x))

# now
code, cache = _precompile_pair(lambda model, x: model(x), m, x)
self.assertIn("PARAM_NAMES = ['lin.weight', 'lin.bias']", code)
f_c = _load_pair(code, cache)
self.assertEqual(f_c(m, x), m(x))

Refusal tests keep their assertRaisesRegex and only swap the callee, as in test_constant_tensor_is_rejected and test_backend_invalid_raises:

with self.assertRaisesRegex(PrecompileError, "hard-coded"):
    _precompile_pair(lambda x: x + captured, torch.randn(3))   # parent: torch.compiler.precompile(...)

with self.assertRaisesRegex(ValueError, "backend must be 'inductor' or 'eager'"):
    _precompile_pair(lambda x, y: x + y, a, b, backend="nope")  # parent: torch.compiler.precompile(...)

Where the shorter name lets a call fit on one line, the formatter re-joins it (test_tracer_default_and_explicit_make_fx, test_tracer_dynamo_not_implemented, test_cached_and_inlined_paths_agree and a few others); those are the only hunks whose line counts change.

rewritten in this diff count
torch.compiler.precompile(...) -> _precompile_pair(...) 136 lines
torch.compiler.precompile.load(...) -> _load_pair(...) 118 lines
library files touched 0

What still spells the callable

Four tests assert on the callable object itself rather than on what it captures, and keep the direct spelling because they are the tests the switch retires: test_public_api_surface (callable(torch.compiler.precompile), .load, .PrecompileError, __module__), test_singleton_pickle_deepcopy_roundtrip (repr(p) == "torch.compiler.precompile"), test_public_identity_module_and_qualname (load.__qualname__ == "precompile.load") and test_precompile_error_public_binding. Apart from those and the two helper bodies, the only remaining mentions are in comments and one "format": "torch.compiler.precompile" string.

Tests

No test is added or removed; the whole file is the test. The suite runs the same 213 tests as main, and the 21 errors on this machine (CUDA numerics and autotune tests) are the environment's missing triton and are identical to main's.

Test Plan:

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

Same 213 tests as main; the 21 errors on this machine (CUDA numerics and autotune tests) are the environment's missing triton and are identical to main's.

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

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

❌ 1 New Failure, 1 Unrelated Failure

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

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

  • Triviality
    • Mechanical refactor: routes direct torch.compiler.precompile(...) and .load(...) calls in test/test_precompile.py through _precompile_pair / new _load_pair
    • Read every hunk; each call keeps the same positional args, kwargs, and surrounding assertion, and only formatter re-joins change line counts
    • Invariant: both helpers forward unchanged to the callable, and load in torch/_precompile.py takes exactly (python_code, cache)
  • Scope
    • Only test/test_precompile.py changes; no library, conftest, or CI file is touched, and no test is added or removed
    • torch/_precompile.py has no caller-frame inspection, so the added indirection cannot change what is captured
  • Socialization
    • Both helpers are module-private to the test file; the remaining direct spellings are the introspection tests that check the callable itself

reason: clean
Reviewed commit: e71048a

Inference job

🐛 Report a wrong verdict

NEW FAILURE - The following job has failed:

  • trunk / macos-py3-arm64 / test (default, 2, 3, macos-m1-stable) (gh)
    test/inductor/test_compiled_autograd.py::TestCompiledAutograd::test_autograd_cpp_node_basic_is_traceable_False

    AI verdict: AI verdict: probably not related

    The suspect PR only changes test/test_precompile.py. It routes existing tests through local helper functions and touches no library code. The failure is test_compiled_autograd.py::test_autograd_cpp_node_basic_is_traceable_False hanging until the 30-minute per-test timeout on macOS while it builds a C++ extension. The PR's code can't reach that path, and the merge base already had a similar C++-extension JIT failure on the same macOS runners.

    Full reasoning on HUD →

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]
@bobrenjc93 bobrenjc93 changed the title [precompile] Retire the callable API's device numerics and unbacked-shape tests [precompile] Route the callable API's tests through the pair helpers Sep 22, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 10m 42s —— View job


The code change is a clean, verifiably mechanical refactor, but the PR description does not describe this diff — it claims to delete TestPrecompileNumerics and dozens of callable-API tests, while the diff deletes zero tests.

Full review

PR Review: #198211

Summary

Routes ~269 call sites in test/test_precompile.py from torch.compiler.precompile(...) / torch.compiler.precompile.load(...) through the _precompile_pair / new _load_pair indirection helpers. The code change itself is sound and I could not find a single non-mechanical edit in it; the problems are in the description, two style leftovers, and one coverage question about where this stack is heading.

Code Quality

  • The PR description describes a different change. The body says this commit "removes TestPrecompileNumerics, the device-generic suite instantiated through instantiate_device_type_tests, together with the second half of TestPrecompile's callable-API tests: the unbacked / mark_unbacked dynamic-shape cases, the memory-format and layout cases, the cache-bundle and autotune reload cases, and the artifact-drift refusals." None of that happened:

    Claim Reality
    TestPrecompileNumerics removed still present, test/test_precompile.py:3379
    instantiate_device_type_tests call removed still present, test/test_precompile.py:3911
    tests removed git diff ... | grep -E "^[-+][[:space:]]*def test_" returns 0 lines
    test count 167 at base, 167 at HEAD
    mark_unbacked / layout / cache-bundle cases gone all still present (e.g. :2073, :1891, :1048)
    "artifact-drift refusals" the string drift appears 0 times at base and 0 at HEAD

    Only the final clause ("Nothing under torch/ changes") holds. The description also has the intent exactly inverted — it says the removed tests "call torch.compiler.precompile(...) directly", whereas the diff's entire effect is to stop calling it directly while keeping every test. The title is the accurate one. Since ghstack pushes the commit body to the PR description, this needs a ghstack -u after fixing, and the whole stack narrative in the body ("the tests that exercise only the callable form go first, in two test-only commits") should be re-checked against what the commits actually do.

  • test/test_precompile.py:56-59 — the _precompile_pair docstring describes a commit that does not exist yet and is hard to parse on its own terms: "the module switch above this commit retires torch.compiler.precompile(fn, *args) and re-points these two helpers at the make_fx internals it drove, so every test below keeps covering them." A reader at this commit cannot check any of that. State what the helper is (one indirection point for the callable API, so a later switch re-points it in one place) and drop the forward reference to a specific unlanded commit; it will be stale the moment the stack is reordered.

  • test/test_precompile.py:63-65 — _load_pair's docstring is circular: "behind the same indirection as _precompile_pair" tells the reader nothing that the one-line body doesn't already say. Either describe the contract or drop the docstring.

  • test/test_precompile.py:1964-1967 and :2630-2633 — two calls stay split across lines where the collapsed form now fits. Both are held open by a magic trailing comma, so black will not rejoin them and the reflow that fixed the rest of the file skipped them:

    # 1964-1967 -> 82 cols collapsed
    self.assertEqual(_load_pair(code, _strip_artifact(cache))(m, row), m(row))
    
    # 2630-2633 -> 69 cols collapsed
    yield "inlined", _load_pair(code, _strip_artifact(cache))

    CLAUDE.md is explicit that a linter-induced line split is less readable than the single line and should be put back. Fix this →

Testing

  • After the later commit re-points these helpers at the make_fx internals, the public callable API loses all behavioral coverage. Post-refactor, every surviving mention of torch.compiler.precompile outside the two helper bodies is introspection only — callable(...) and assertIs(...PrecompileError) at :1670-1675, pickle/deepcopy/repr at :2291-2294, load.__module__ / __qualname__ at :2395-2399, and the alias check at :2708. So the moment _precompile_pair / _load_pair stop calling torch.compiler.precompile, nothing in this file ever invokes the public entry point again; test_public_api_surface would keep passing against a callable that no longer works. If the intent is that torch.compiler.precompile is retired outright, that is fine and the introspection tests should go with it — but if it stays public even as a thin shim over the module form, please keep at least one end-to-end test calling it directly (capture + load + numerics), rather than routing 100% of behavioral coverage through the indirection.

Recommendation

Request Changes

The diff is mechanically correct — I checked every hunk, including the argument-by-argument reconstruction of the collapsed multi-line calls (:930, :1279, :1300, :1362, :1404, :1437, :1882-1889, :2642, :3009, :3017 and the rest), the preserved third msg argument at :1749, the _strip_artifact / backend= / decompositions= kwargs, and the trailing path-label comments; nothing was lost, reordered, or inverted, and no call site was missed. What blocks approval is not the code but the description: it asserts a large test deletion that did not occur, which makes the commit message actively misleading for anyone bisecting this stack later. Fix the body (and ghstack -u), collapse the two leftover splits, and rewrite the two docstrings so they stand alone at this commit.

· branch `gh/bobrenjc93/1447/head`

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Thanks. Dispositions for the findings above, new head e71048a:

PR description describes a different change. Open: correct. This PR number was reused when the stack was re-sliced; the body on GitHub is the old test-deletion text, while the commit message (ghstack-source-id orig branch) describes the port. Ghstack does not refresh existing bodies and description edits are handled by the PR owner, so the body update is with @bobrenjc93 rather than pushed from here. The commit message is the accurate one.

_precompile_pair docstring forward-references an unlanded commit. Fixed in e71048a: it now states what the helper is at this commit (one indirection point over the callable entry point, so a change of entry point re-points the suite here), with no reference to a specific later commit.

_load_pair docstring is circular. Fixed in e71048a: it now states the contract (a runnable from an in-memory pair through the callable API's load) rather than pointing at the sibling helper.

Two calls left split by a magic trailing comma. Fixed in e71048a: both collapsed to one line.

Public callable loses behavioural coverage once the helpers are re-pointed. Declined: the callable is retired outright two commits up (#197993 removes _PrecompileApi and the introspection tests with it); there is no shim to keep a direct end-to-end test for.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 5m 19s —— View job


All three actionable findings from the previous round are fixed in e71048a6cad, the two declined items are reasonable, and the only thing still open is the stale PR body — which is the author's to edit, so this is an approve.

Re-review of `e71048a6cad`

Verification of the fix commit

git diff 6fa0968..e71048a touches exactly five places, all of them the ones raised last round. Nothing else moved.

1. _precompile_pair docstring — fixed. test/test_precompile.py:56-59 now reads as a standalone statement of what the helper is, with no reference to an unlanded commit:

"""One indirection point over the callable entry point: every test below drives
the make_fx capture through this helper rather than spelling the callable, so a
change of entry point re-points the whole suite here."""

A reader at this commit can check every clause of that against the file in front of them, which was the whole complaint. It also reads better than the base version at :57-58 ("Public-API entry point for the tests added with the fake-tensor capture...the tracer/module switch above this commit"), which had the same forward-reference problem.

2. _load_pair docstring — fixed. :63-65 now leads with the contract rather than pointing at its sibling:

"""Reconstruct a runnable from an in-memory ``(python_code, cache)`` pair through
the callable API's ``load``; the second indirection point, for the same reason."""

The trailing "for the same reason" is still a soft back-reference, but it's now a footnote on a sentence that stands on its own. Good enough.

3. The two magic-trailing-comma splits — collapsed. Both verified in the file, both under the configured 88-column limit (pyproject.toml:438):

  • :1965 — self.assertEqual(_load_pair(code, _strip_artifact(cache))(m, row), m(row)) (82 cols)
  • :2628 — yield "inlined", _load_pair(code, _strip_artifact(cache)) (69 cols)

I then swept every remaining multi-line _precompile_pair( / _load_pair( call site to check none of them is also collapsible, and each one genuinely exceeds 88 when joined — the closest are :1837-1839 (89) and :1883-1885 (89), both over by one column, so black is right to keep them split. No line in the added diff exceeds 88. Nothing left to collapse.

Re-verification of the port itself

Still mechanical, and now larger (+263/-346 across the three commits):

Check Result
test defs added/removed in diff 0
test count, base vs HEAD 167 vs 167
class defs added/removed 0
non-test def added 1 (_load_pair)
_pair call sites, base vs HEAD 13 vs 268
added lines not mentioning a _pair helper 7 — the two docstrings, _load_pair's one-line body, blanks

That last row is the useful one: every single added line in the whole PR is either a _pair call or part of the _load_pair definition. There is no room in the diff for a smuggled behavioral change. TestPrecompileNumerics (:3374) and instantiate_device_type_tests (:3906) are both still present and untouched, and torch/ is untouched.

Declined items

  • Stale PR body. Your disposition — the number was reused when the stack was re-sliced, the commit message is the accurate one, ghstack won't refresh an existing body — is plausible and the fix is genuinely yours to make, not mine. Two caveats worth a minute of your time: (a) the body on GitHub is what a reviewer opens and what a future bisector reads, so until it's edited the mismatch is live regardless of what the commit message says; and (b) I can't verify the commit message from this checkout — the local commits are ghstack-poisoned placeholders ([UPDATE] Update), so "the commit message is the accurate one" is taken on trust here. If the body went stale from a re-slice, it's worth checking whether the sibling PRs in the stack picked up the same mismatch.
  • Callable loses behavioral coverage. Reasonable as stated: if [precompile] Make torch.compiler.precompile a module and retire the callable API #197993 removes _PrecompileApi outright along with the introspection tests, there is no shim and nothing to anchor an end-to-end test to, so the coverage I was worried about has no subject. I could not open [precompile] Make torch.compiler.precompile a module and retire the callable API #197993 from this environment to confirm. Note the residual, which is transient and not worth acting on: at the switch commit — after the helpers are re-pointed at the make_fx internals but before [precompile] Make torch.compiler.precompile a module and retire the callable API #197993 deletes the callable — torch.compiler.precompile still exists and no test in this file invokes it behaviorally, so the introspection assertions at :1671-1676, :2289-2292, :2396-2397 and :2703 would pass against a callable that nothing exercises. One commit's worth of exposure inside your own stack, closed by [precompile] Make torch.compiler.precompile a module and retire the callable API #197993.

What I could not run

No .venv in the working directory and lintrunner / ruff / python3 are not on the path in this job, so I verified line lengths and syntax structurally (grep-based column scan against the configured 88, plus the call-site sweep above) rather than by running lintrunner -a or the suite. Your commit body records python test/test_precompile.py and lintrunner -a test/test_precompile.py; the CI run on this head is the authority.

Recommendation

Approve — pending only the PR body edit on your side.

· branch `gh/bobrenjc93/1447/head`

pytorchmergebot pushed a commit that referenced this pull request Sep 23, 2026
…#198223)

**Problem.** The loader that turns a `(python_code, cache)` pair back into a runnable lives inside `_PrecompileApi.load`, a method on the callable API object, even though nothing in it uses the object; the module form that replaces that callable two commits up needs the same loader and would have to re-add it.

**Fix.** Move the method body, verbatim, to a module-level `_runnable_from_pair(python_code, cache)` next to the loader helpers it uses, and leave the method as a one-line delegation.

**Summary.** `_PrecompileApi.load(python_code, cache)` holds the loader: it validates the source as a precompile artifact through `_parse_artifact_metadata`, refuses a cache whose `backend` or `code_hash` does not pair with it, degrades a foreign format/version envelope to JIT'ing from the source, primes the inductor kernel caches from the bundle, execs the inlined driver and wraps the result. Nothing in that body depends on the callable it hangs off, yet the module form that replaces the callable two commits up needs exactly this core for its own `load(artifact_path, cache_path)`, so leaving it as a method would make that switch re-add the loader under a new name. This commit moves the body, verbatim, to a module-level `_runnable_from_pair(python_code, cache)` defined just above the class, beside the loader helpers it uses, and leaves the method delegating to it. The constraint is that the move is byte-for-byte, so the loader's history stays readable as a move and the later switch removes the class without touching the loader. Nothing else changes: the messages that still say `precompile()` are reworded where the callable actually disappears, two commits up, and the capture-time self-load flag arrives with its caller.

## 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 groundwork with no behaviour change: it moves the old callable API's load body into the private `_runnable_from_pair`, the core the new `load()` (#198213) is built on.

## The move

Parent: the loader is the body of the method, from the `import torch._dynamo` that fixes the import order down to the `PrecompiledModule._from_loaded` wrap.

```python
class _PrecompileApi:
    def load(self, python_code: str, cache: bytes) -> Callable[..., object]:
        import torch._dynamo
        meta = _parse_artifact_metadata(python_code)
        backend = cast(str, meta["BACKEND"])
        ...  # envelope check, cache priming
        forward = _make_inlined_forward(python_code)
        return PrecompiledModule._from_loaded(forward, backend=backend)
```

Now: the same lines, unchanged, sit in a module-level function defined right after `_read_artifact` and before the class, and the method delegates.

```python
def _runnable_from_pair(python_code: str, cache: bytes) -> PrecompiledRunnable:
    """Reconstruct a runnable from an in-memory ``(python_code, cache)`` pair."""
    import torch._dynamo
    meta = _parse_artifact_metadata(python_code)
    backend = cast(str, meta["BACKEND"])
    ...  # envelope check, cache priming -- identical to the parent
    forward = _make_inlined_forward(python_code)
    return PrecompiledModule._from_loaded(forward, backend=backend)

class _PrecompileApi:
    def load(self, python_code: str, cache: bytes) -> Callable[..., object]:
        return _runnable_from_pair(python_code, cache)
```

`self` was never read inside the body, which is what makes the move mechanical. Two commits up the module form builds its own `load(artifact_path, cache_path)` on `_runnable_from_pair`, and the class goes away without re-adding any of this.

## What the loader core does

The one behaviour worth seeing is the pairing check. A cache is acceleration only, so an envelope with a foreign `format`/`version` is logged and dropped, and the source JITs; a `backend` or `code_hash` that disagrees with `python_code` means the two came from different `precompile()` calls, and that hard-fails rather than running under foreign metadata.

```python
blob = torch.load(io.BytesIO(cache), weights_only=True)
if blob.get("format") != _CACHE_FORMAT or blob.get("version") != _CACHE_VERSION:
    log.warning("... Falling back to JIT from python_code.")   # degrade
    blob = None
if blob is not None:
    if blob.get("backend") != backend:
        raise PrecompileError("cache backend ... does not match the python_code backend ...")
    expected_code_hash = hashlib.sha256(python_code.encode()).hexdigest()
    if blob.get("code_hash") != expected_code_hash:
        raise PrecompileError("cache does not match python_code (its code_hash ... != sha256(python_code) ...)")
    artifact = blob.get("artifact")
```

When the check passes, `torch.compiler.load_cache_artifacts(artifact)` primes the inductor kernel caches (a failure there is also only a warning), and `_make_inlined_forward(python_code)` execs the driver inlined in the source, which now hits the warm caches instead of recompiling. All of this is carried over unchanged; see Note [precompile programming model], invariant 7, for the pairing rule.

## What stays put

- The warning and error strings still say `torch.compiler.precompile.load` and `precompile()`. They are reworded in the commit that actually removes the callable, two commits up, so this diff stays a pure move.
- The capture-time self-load flag is not part of this commit; it arrives with the caller that needs it.
- The suite drives the loader through the `_load_pair` helper in `test/test_precompile.py`, which still calls `torch.compiler.precompile.load(python_code, cache)` and therefore exercises the delegation as well as the moved body.

Test Plan:

Behaviour-preserving move; the existing suite drives the loader through `_load_pair`, which still calls the method.

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

Authored with an AI assistant.

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

Pull Request resolved: #198223
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #198211
pytorchmergebot pushed a commit that referenced this pull request Sep 23, 2026
…ve the suite through it (#198283)

**Problem.** The `backend` and `tracer` checks live in `_PrecompileApi.__call__`, the callable `torch.compiler.precompile(fn, *example_inputs)`, and the test suite drives everything through that callable; the commit two PRs up that retires the callable would therefore have to relocate the checks and re-point the suite as well as switch the public surface.

**Fix.** Move both checks into `PrecompiledModule.__init__`, make `_parse_artifact_metadata` refuse an unknown `BACKEND` so the load path gets the same protection before any exec, and re-point the suite's `_precompile_pair` / `_load_pair` helpers at `PrecompiledModule` and `_runnable_from_pair`.

**Summary.** `torch.compiler.precompile(fn, *example_inputs, backend=, tracer=, decompositions=)` is a `_PrecompileApi` singleton whose `__call__` validates `backend` and `tracer`, builds a `PrecompiledModule`, runs `_compile(example_inputs)` and renders `(python_code, cache)`, and its `load` delegates to `_runnable_from_pair`. Two commits up (#197993) the callable is retired in favour of a `torch.compiler.precompile` module, and anything still living only in the callable would have to move in that same diff, so this commit moves it out first and leaves the retirement a switch of the public surface and nothing else. The validation now sits in `PrecompiledModule.__init__`, the one place the make_fx front-end constructs, and because the load path reaches that constructor with a `backend` read out of the artifact, `_parse_artifact_metadata` also refuses an unknown `BACKEND` as a `PrecompileError` before anything is exec'd. The test helpers `_precompile_pair` and `_load_pair` build and load the pair the way `__call__` and `load` do, but below the callable, so every behavioural test runs on code that survives the retirement, while `test_callable_api_end_to_end` keeps one end-to-end check of the public callable on both backends until #197993 removes it with the callable. There is no behaviour change for a caller of the callable: the error types and texts are unchanged, and the only new refusal is for an artifact whose `BACKEND` tag no precompile capture could have written.

## 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 groundwork with no behaviour change: the callable still exists here and is retired two PRs up in #197993. It was split out of #197993 so each PR is small enough to review.

## Argument validation moves to `PrecompiledModule.__init__`

Parent: `_PrecompileApi.__call__` checked `backend` and `tracer` before constructing the module, so only the callable was guarded.

```python
class _PrecompileApi:
    def __call__(self, fn, *example_inputs, backend="inductor", tracer="make_fx", decompositions=None):
        torch._C._log_api_usage_once("torch.compiler.precompile")
        if backend not in ("inductor", "eager"):
            raise ValueError(f"precompile backend must be 'inductor' or 'eager', got {backend!r}.")
        if tracer not in ("make_fx", "dynamo"):
            raise ValueError(f"precompile tracer must be 'make_fx' or 'dynamo', got {tracer!r}.")
        compiled = PrecompiledModule(fn, backend=backend, tracer=tracer, decompositions=decompositions)
        ...
```

Now: the same two checks, with the same text, open `PrecompiledModule.__init__`, and `__call__` goes straight from `_log_api_usage_once` to the constructor. An unknown backend can no longer fall through to the inductor path and into the artifact's `BACKEND` tag, whichever entry point builds the module:

```python
from torch._precompile import PrecompiledModule

PrecompiledModule(lambda x, y: x + y, backend="nope")
# ValueError: precompile backend must be 'inductor' or 'eager', got 'nope'.
PrecompiledModule(lambda x, y: x + y, tracer="nope")
# ValueError: precompile tracer must be 'make_fx' or 'dynamo', got 'nope'.
PrecompiledModule(lambda x, y: x + y, tracer="dynamo")   # accepted here; _compile raises NotImplementedError

torch.compiler.precompile(lambda x, y: x + y, a, b, backend="nope")
# parent and now: the same ValueError, now raised by the constructor __call__ builds
```

`test_backend_invalid_raises` and `test_tracer_invalid_raises` pin the error type and text with the same `assertRaisesRegex` strings as before; `test_backend_invalid_raises` is only relocated next to its tracer twin.

## The load path gets the check before any exec

The load path reaches that constructor too, through `PrecompiledModule._from_loaded` (`cls(None, backend=backend)`), with a `backend` read out of the artifact rather than chosen by the caller. A `ValueError` from the constructor is the wrong shape for a malformed artifact, and it would fire only after `python_code` had been exec'd, so `_parse_artifact_metadata` now refuses an unknown `BACKEND` value up front, as a `PrecompileError`, the way it refuses the other malformed-artifact shapes:

```python
from torch._precompile import _parse_artifact_metadata

m, x = torch.nn.Linear(4, 3).eval(), torch.randn(2, 4)
code, cache = _precompile_pair(lambda model, xx: model(xx), m, x, backend="eager")
bad_code = code.replace("BACKEND = 'eager'", "BACKEND = 'nope'")

_parse_artifact_metadata(bad_code)
# PrecompileError: python_code names an unknown backend 'nope'; a torch.compiler.precompile artifact is 'inductor' or 'eager'.

# the source is parsed before the cache is read, so the untouched cache is enough:
_load_pair(bad_code, cache)
# PrecompileError: python_code names an unknown backend 'nope'; ...   (raised before any exec)
```

`test_artifact_backend_value_is_validated_before_exec` pins both halves: the parser alone, and the full `_load_pair` with the capture's own cache, since the parse runs before the cache is even read.

## The suite's two indirection points move below the callable

Parent: both helpers spelled the callable.

```python
def _precompile_pair(fn, *args, **kwargs):
    return torch.compiler.precompile(fn, *args, **kwargs)

def _load_pair(python_code, cache):
    return torch.compiler.precompile.load(python_code, cache)
```

Now: `_precompile_pair` builds the pair exactly the way `__call__` does, and `_load_pair` calls the loader core `load` delegates to.

```python
def _precompile_pair(fn, *args, **kwargs):
    from torch._precompile import PrecompiledModule

    compiled = PrecompiledModule(fn, **kwargs)
    compiled._compile(args)
    python_code = compiled.to_python_code()
    return python_code, compiled.to_cache_bytes(python_code)

def _load_pair(python_code, cache):
    return torch._precompile._runnable_from_pair(python_code, cache)
```

The only step of `__call__` the helper skips is its `_log_api_usage_once`. Because validation now lives in the constructor, the invalid-argument tests still see it through the helper. Every behavioural test of the make_fx capture, the drivers and the loader therefore runs on the code that survives the retirement, and the tests that still exercise the callable object itself are the ones the retirement removes.

Because the helpers bypass the public callable, the callable keeps one end-to-end check of its own until it goes. `test_callable_api_end_to_end`, parametrized over `backend` in `("inductor", "eager")`, drives `torch.compiler.precompile(...)` and `torch.compiler.precompile.load(...)` and compares against eager:

```python
@parametrize("backend", ("inductor", "eager"))
def test_callable_api_end_to_end(self, backend):
    m = torch.nn.Linear(4, 3).eval()
    x = torch.randn(2, 4)
    python_code, cache = torch.compiler.precompile(
        lambda model, xx: model(xx), m, x, backend=backend
    )
    self.assertEqual(torch.compiler.precompile.load(python_code, cache)(m, x), m(x))
```

It pins only that `backend=` reaches the render on both backends and that `load` runs the result. It does not cover `decompositions=` forwarding: an empty table is indistinguishable from the default, so the test passes none, and `test_decompositions_kwarg` covers the constructor-side plumbing. It is removed with the other tests of the callable object when #197993 retires the callable.

Test Plan:

```
python test/test_precompile.py
lintrunner --take RUFF,PYFMT,FLAKE8,DOCSTRING_LINTER,NOQA,CODESPELL torch/_precompile.py test/test_precompile.py
```

The error set on this machine (CUDA numerics and autotune tests, missing triton) is identical to main's.

Authored with an AI assistant.

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

Pull Request resolved: #198283
Approved by: https://github.com/aorenste
ghstack dependencies: #198211, #198223
pytorchmergebot pushed a commit that referenced this pull request Sep 24, 2026
…the Note and keep internals out of PrecompileSummary's docstring (#198284)

**Problem.** Two caveats of `torch.compiler.precompile` (a shared `shape_id` for `mark_unbacked` dims that must be equal, and which part of a capture is thread-serialized) are written down only in the callable's `__call__` docstring, which #197993, the next PR up, deletes along with the callable; separately, `PrecompileSummary`'s docstring names private implementation that would end up on the public docs page once #197993 renders it with `autoclass`.

**Fix.** Move both caveats into Note [precompile programming model] in `torch/_precompile.py`, leaving a one-line pointer to each in the docstring, and restate `PrecompileSummary`'s docstring in public terms with the private cross-references moved into code comments.

**Summary.** The callable's `__call__` docstring is the only place that says two `mark_unbacked` dims which must be equal at runtime need a shared `shape_id`, and that concurrent `backend="inductor"` captures are serialized by an internal lock while the make_fx trace and `backend="eager"` are not. #197993 deletes that docstring with the callable, so without this commit both caveats would vanish from the source, and the equal-dims one guards against a silent wrong result: independently marked dims bake an equal-size assumption because the capture's deferred `Eq(u0, u1)` runtime assert is not harvested yet. This commit moves the first caveat under invariant 3 of Note [precompile programming model] and the second beside the Note's backend paragraph, now naming the lock as `_COMPILE_LOCK` in `torch/_functorch/_aot_autograd/to_standalone_python.py`, where every surface that survives the retirement points, and leaves a one-line pointer to each in the docstring for the commits in between, with the shape_id pointer still stating that independently marked dims fail silently. It also strips private names (`OutputGraph.bypass_package`, `FrameExecStrategy`, `_pins_a_value`, `default_guard_filter_fn`, `_INVARIANT_DROPPABLE_GUARD_TYPES`, `Guard.code_list`, `allow_empty_graphs`, and the "added by this stack" paragraph) from `PrecompileSummary`'s docstring, which becomes public once #197993 renders it on the docs page, and moves those cross-references into comments in the class body and in `complete()` so a maintainer still finds the producer's rules, and gives `GuardFact.source` and the `_precompile_types.py` module docstring the same treatment. It is docs-only: no code changes, and the one test edit is a reworded comment.

## 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 docs-only groundwork split out of #197993 so each PR is small enough to review: it gives the callable's last two docstring-only caveats a home that outlives the callable, and makes `PrecompileSummary`'s docstring fit for the public page #197993 renders it on.

## The two caveats move into the Note

Parent: the callable's `__call__` docstring carries both.

```python
    def __call__(...):
        """...
        THREADING: the inductor lowering step drives process-global compiler state
        and is serialized by an internal lock, so concurrent ``backend="inductor"``
        calls lower one at a time. The make_fx capture phase and the ``backend="eager"``
        path are NOT serialized.
        ...
        Dims that MUST be equal at runtime (e.g. two inputs combined by a broadcast that
        requires equal sizes, ``model(a) + model(b)``) MUST be given a SHARED ``shape_id``
        so a mismatch is rejected; marking two such dims INDEPENDENTLY currently bakes a
        SILENT equal-size assumption and a runtime mismatch does NOT raise the loud failure
        eager gives (invariant 3). This is a harvesting gap, not an inherent limit of the
        standalone artifact: the capture ShapeEnv DOES record the equality (as a deferred
        runtime assert, e.g. ``Eq(u0, u1)``), but precompile does not yet harvest/enforce
        those relational asserts in the driver -- only the decorator's declared min/max feed
        the runtime bound checks. A shared ``shape_id`` is the way to get the check today.
        """
```

Now: the docstring keeps a one-line pointer to each, and the shape_id pointer still states the hazard. The THREADING pointer sits below the `backend` bullet list it qualifies, and the shape_id caveat folds into the existing shared-`shape_id` sentence of the `mark_unbacked` paragraph, whose earlier "(invariant 3)" reference is the only one it needs.

```python
        ``backend`` selects how the captured graph is realized:

        - ``"inductor"`` (default): ...
        - ``"eager"``: ...

        Concurrent ``backend="inductor"`` calls lower one at a time (THREADING in the
        Note).
        ...
        ``PrecompileError``. Dims sharing a ``shape_id`` reuse one symbol (equal by
        construction), so dims that must be equal at runtime need one: marking them
        independently bakes a silent equal-size assumption. ``min``/``max`` become
        runtime asserts. Other dims stay static.
```

The shape_id caveat extends the `mark_unbacked` paragraph of invariant 3 in the Note:

```python
#    ... a graph that needs to
#    guard on / specialize a marked dim fails LOUDLY at capture (PrecompileError) instead
#    of baking a silently-wrong result. Dims that MUST be equal at runtime (e.g. two
#    inputs combined by a broadcast that requires equal sizes, ``model(a) + model(b)``)
#    MUST share a ``shape_id``: marking them INDEPENDENTLY bakes a SILENT equal-size
#    assumption, and a runtime mismatch does not raise the loud failure eager gives. The
#    capture ShapeEnv records the equality as a deferred runtime assert (e.g.
#    ``Eq(u0, u1)``), but precompile does not yet harvest those relational asserts --
#    only mark_unbacked's min/max feed the runtime bound checks -- so a shared
#    ``shape_id`` is the way to get the check today.
```

The threading caveat becomes its own paragraph between the Note's `backend:` and `tracer:` paragraphs:

```python
# THREADING: the inductor lowering drives process-global compiler state and is
# serialized by _COMPILE_LOCK (torch/_functorch/_aot_autograd/to_standalone_python.py),
# so concurrent backend="inductor" captures lower one at a time. The make_fx trace
# and the backend="eager" path are NOT serialized.
```

The test that pins the shape_id behaviour, `test_unbacked_equality_shared_vs_independent_shape_id`, called that text the "invariant 3 DANGER note"; its comment now reads `MAJOR1 (invariant 3, shared shape_id)` to match. The test itself is unchanged.

## `PrecompileSummary` keeps its internals out of the public docstring

After #197993, `docs/source/torch.compiler_api.md` renders this class with `.. autoclass:: torch.compiler.precompile.PrecompileSummary`, so what a reader of the docs page (or `help(torch.compiler.precompile.PrecompileSummary)`) sees is this docstring. Each private name is replaced by a public description of the same rule:

| Attribute / method | Parent names | Now says |
| --- | --- | --- |
| guard fields intro, and `GuardFact.source` | `GuardFilterEntry.name`, `Guard.name` | the source spelled with the local scope stripped |
| (class) | "Three entries below name the rule they follow in `torch._dynamo.precompile_package`; that module and its filter are added by this stack..." | paragraph removed |
| `bypassed` | `OutputGraph.bypass_package` | its guards could not be serialized, or its graph held parameters by static address |
| `truncated` | its `FrameExecStrategy` is `RUN_ONLY` for the frame and its callees | the frame and the frames it calls run without tracing |
| `uncovered_frames` | "A different cause and remedy from `bypassed`", with the remedy in a parenthetical: an install `skip_code`s an uncovered frame, so only a re-capture recovers it, where it re-traces a bypassed one | "A different cause from `bypassed`"; the parenthetical is dropped (see below) |
| `wont_generalize` | `_pins_a_value` in `torch._dynamo.precompile_package` is the rule | the rule stated inline: a kept value-equality guard on a bare argument name that pins a value |
| `dropped_guards` | which guards a filter rejects is "that filter's own contract, stated in its docstring and not repeated here: the default is `default_guard_filter_fn` in `torch._dynamo.precompile_package`" | the default filter's rule stated inline: it drops a guard when the serializer refuses its type or a type its check derives, i.e. the identity guards (`ID_MATCH`, `FUNCTION_MATCH`, `NN_MODULE` and the like), `WEAKREF_ALIVE` and most `DICT_VERSION` guards ("most" because `default_guard_filter_fn` keeps a `DICT_VERSION` derived by a `DICT_KEYS_MATCH`), so a load cannot notice that the objects they checked were rebound, mutated or collected; passing the filter does not make a guard serializable (it keeps `TYPE_MATCH` and `BUILTIN_MATCH` by type, including a local-scope `TYPE_MATCH` the serializer refuses, so serialization then fails loudly); a caller-supplied filter decides its own set |
| `policy_dropped_guards` | `_INVARIANT_DROPPABLE_GUARD_TYPES` bounds what it may drop | only guard types from a fixed set are eligible |
| `dropped_guard_code` | its `GuardBuilder` method set `Guard.code_list` | a slot whose guard rendered a check |
| `complete()` | `allow_empty_graphs` lets a frame that compiled nothing count | a frame that compiled nothing can still count as one guarded code |

The cross-references are not lost: they move into comments a maintainer reading the source still finds, one in the class body

```python
    # The producer's rules live in torch._dynamo.precompile_package:
    # default_guard_filter_fn (dropped_guards), _pins_a_value (wont_generalize),
    # _INVARIANT_DROPPABLE_GUARD_TYPES (policy_dropped_guards); a bypassed frame is
    # one OutputGraph.bypass_package flagged; dropped_guard_code holds the
    # Guard.code_list a GuardBuilder method rendered.

    frames: int
```

and one in `complete()`:

```python
        # torch._dynamo.config.allow_empty_graphs is what lets an empty frame count.
        return (
            not self.bypassed
            ...
```

Apart from the private names, the attribute descriptions say the same thing as before, re-wrapped where a sentence got shorter (`bypassed`, `uncovered_frames`, `dropped_guards`, `policy_dropped_guards` and `dropped_guard_code` are re-flowed to one width), with two deliberate corrections to `bypassed` and `uncovered_frames` described below; no field, method or behaviour changes. `dropped_guards` is the one entry that gains text: since `default_guard_filter_fn` is private, the docstring is now where a public reader learns what the default filter drops, instead of deferring to the filter's own docstring.

## `bypassed` and `uncovered_frames` now describe what a load does

The parent's `bypassed` entry ended "an install re-traces it rather than skipping it as trivial", and `uncovered_frames` contrasted the two remedies through the same install behaviour. Installed serving is not reachable from a capture in this stack: `_serving_mode` in `torch/_precompile.py` has no production caller (only unit tests call it), the artifact reader defaults `SERVING_MODE` to `"standalone"`, and the multigraph renderer higher in the stack writes `"standalone"` unconditionally. In a standalone artifact a bypassed continuation has no variants, so the driver binds a deferred refusal ("was BYPASSED during capture ...") and a call that reaches it raises; a bypassed entry frame is refused at capture by `_reject_uninstallable_entry`. So `bypassed` now ends "the package kept no variant of it a load can serve, so a call that reaches it raises", and `uncovered_frames` says only "A different cause from `bypassed`, never the same frame", dropping the remedy parenthetical whose re-trace half described `install()`, which a precompile load never calls.

```python
# a fn whose graph-break continuation Dynamo bypassed during capture
fn_loaded = load("a.py", "a.cache")
fn_loaded(x)   # parent docstring: "an install re-traces it"
               # now (and in fact): raises, naming the frame as BYPASSED during capture
```

The stale comments above the driver's refusal and in `_serving_mode`'s docstring, which still describe installed serving, predate this PR and are left for the PR that turns installed serving on; that PR must update this `bypassed` entry at the same time.

## `GuardFact.source` and the module docstring

`GuardFact` lives in the same module and its `source` attribute used the same private spelling, which it drops (parent: "spelled as `GuardFilterEntry.name`, i.e. the `Guard.name` with local scope stripped") and now reads "The guarded source with the local scope stripped (`L['x']` -> `x`)". The cross-reference moves to a comment in the class body:

```python
    # source is GuardFilterEntry.name (torch._dynamo.types): Guard.name with the
    # local scope stripped.

    guard_type: str
```

The module docstring of `torch/compiler/_precompile_types.py` said twice that its importers arrive "later in this stack", and that `import torch` loads this module. Both were wrong at this commit: `torch/_dynamo/precompile_package.py` already imports the module below this stack, and it is that module's only importer. The docstring now states the constraint rather than an import chain:

```python
"""Plain-data types the multi-graph precompile capture reports through.

A leaf module on purpose: it must stay importable without ``torch._dynamo``, so
that the public ``torch.compiler.precompile`` surface can export these types
without ``import torch`` loading Dynamo, while the Dynamo-side internals
(``torch/_dynamo/precompile_package.py``, which imports this module) use them
without an import cycle. Import-wise the types could live in
``torch/_precompile.py``; keeping them out of it is layering: the Dynamo
internals must not depend on the make_fx capture module, which the multi-graph
capture session makes an importer of those internals. ...
"""
```

It also calls the session that makes the make_fx capture module an importer of the Dynamo internals "the multi-graph capture session" rather than "the follow-up".

Test Plan:

```
python test/test_precompile.py
lintrunner --take RUFF,PYFMT,FLAKE8,DOCSTRING_LINTER,NOQA,CODESPELL torch/_precompile.py torch/compiler/_precompile_types.py test/test_precompile.py
```

No code changes; the error set is identical to main's.

Authored with an AI assistant.

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

Pull Request resolved: #198284
Approved by: https://github.com/aorenste
ghstack dependencies: #198211, #198223, #198283
pytorchmergebot pushed a commit that referenced this pull request Sep 24, 2026
…allable API (#197993)

> **Landing note: this PR is not usable on its own.** After this commit `torch.compiler.precompile` exports only types (`Capture`, `MakeFxTracer`, `PrecompiledRunnable`, `PrecompileSummary`, and a re-exported `PrecompileError`). There is no `capture()` and no `load()` yet, and the callable is gone, so `torch.compiler.precompile(fn, x)` raises `TypeError: 'module' object is not callable` and `torch.compiler.precompile.load(...)` raises `AttributeError`. Landed alone, this is a regression against main, which ships the v2.14 callable. The smallest landing unit that leaves a usable API is #197993 through #198135: `load(artifact_path, cache_path)` arrives in #198213 and `capture(..., tracer=MakeFxTracer())` in #198135, which together bring back the callable's single-call make_fx capture, now over two files. The multi-call `DynamoTracer` is usable from #198138 and becomes the default tracer in #198217. #198213 and everything above it currently carry `[no-ci]` titles, so they need CI turned on before they can land with this PR.

**Problem.** `torch.compiler.precompile` is a callable object, a `_PrecompileApi` singleton: `precompile(fn, *example_inputs, backend=, tracer=, decompositions=)` traces `fn` once, on inputs you hand it up front, and returns a `(python_code, cache)` pair that `precompile.load(python_code, cache)` reloads. The API this stack replaces it with is a caller-driven context manager: `capture(fn, artifact_path=, cache_path=)` is entered with a `with` block, you call it on as many different example inputs as you like (each graph break and recompiled variant they exercise is folded in), the artifact is written to two files when the block exits, and `load(artifact_path, cache_path)` serves it in a fresh process. A callable singleton cannot also be the module those two entry points and their types live in.

**Fix.** Retire the callable and make `torch.compiler.precompile` a real submodule, `torch/compiler/precompile.py`, that exports the four public types (`Capture`, `MakeFxTracer`, `PrecompiledRunnable`, `PrecompileSummary`) and re-exports `PrecompileError`. The entry points (`capture`, `load`) are deliberately NOT in this commit; they arrive in the next commits, so this is the one commit in the series where behaviour changes for a caller.

**Summary.** Until this commit `torch.compiler.precompile` was an instance of `_PrecompileApi` in `torch/_precompile.py`, whose `__call__` traced `fn` on example inputs and whose `load` method reloaded the returned pair. That shape cannot host the caller-driven API, whose `capture` and `load` take the caller's own calls and file paths and need a module namespace to live in together with their types, so this is deliberately the point in the stack where behaviour changes. With everything else the callable carried already moved down the stack (argument validation and the test helpers in #198283, its docstring caveats in #198284), this commit deletes `_PrecompileApi` and adds `torch/compiler/precompile.py`, which imports the four types from the private modules, resolves their string annotations with `typing.get_type_hints` into `__annotations__`, and sets their `__module__` to `torch.compiler.precompile`, so pickle, Sphinx and `test_public_bindings` all find them at the public path. The re-homing has to be a loop in this module, after the classes exist, because `@dataclass` dereferences `sys.modules[cls.__module__]` while decorating and `torch.compiler.precompile` is not yet imported when the class bodies in `torch/_precompile.py` run. Anyone calling `torch.compiler.precompile(...)` today gets a `TypeError` after this commit; the API is a documented prototype with no deprecation cycle, but this is a breaking change for current callers and the commit to hold back if that is not yet acceptable.

## The new API, end to end

This PR is the first step of the replacement, so here is where the stack ends up (the top PR, #198217, where `DynamoTracer` is the default tracer):

```python
import torch.compiler.precompile as precompile

# Capture: YOUR loop makes the calls; every input it exercises is folded in.
with precompile.capture(step, artifact_path="m.py", cache_path="m.cache") as cap:
    for x in example_inputs:     # different shapes/branches -> recompiles, graph breaks
        y = cap(model, x)        # runs for real and returns step(model, x)
    cap.save()                   # optional: checkpoint the pair mid-block
    print(cap.summary())         # coverage, recompiles, dropped guards
# the (python_code, cache) pair is written to m.py / m.cache on exit

# Serve, in a fresh process:
f = precompile.load("m.py", "m.cache")    # PrecompiledRunnable
out = f(model, x)                         # dispatches among the captured variants by guards;
                                          # an input no variant covers raises
```

`capture(..., tracer=MakeFxTracer())` keeps a single-call, make_fx-traced front-end for code with no graph breaks: it takes exactly one call, since one ATen trace records one execution. The stack adds the pieces bottom-up, and it lands as a unit, so no landed state exposes the gap between this PR and the entry points:

| PR | Adds |
|---|---|
| #198283 | groundwork: `backend`/`tracer` validation moves into `PrecompiledModule.__init__`, and the test helpers drive the internals directly |
| #198284 | groundwork (docs-only): the callable's `shape_id` and threading caveats move into the Note, and private names leave `PrecompileSummary`'s docstring |
| #197993 (this) | `torch.compiler.precompile` becomes a module; the callable API is retired |
| #198213 | `load(artifact_path, cache_path)` |
| #198135 | `capture()` as a context manager, with the one-call `MakeFxTracer` |
| #198137, #198216 | `PrecompileSession`, the multi-graph capture underneath, and its artifact |
| #198138 | `DynamoTracer`: a multi-call `capture()` |
| #198227 | `save()` checkpoints and `summary()` for Dynamo captures |
| #198217 | `DynamoTracer` is the default tracer; docs |

The old-to-new mapping for a current caller:

```python
# old: trace once, on inputs passed up front; the pair comes back in memory
python_code, cache = torch.compiler.precompile(step, model, x)
f = torch.compiler.precompile.load(python_code, cache)

# new: the caller's own calls drive the capture; the pair goes to files
with torch.compiler.precompile.capture(step, artifact_path="m.py", cache_path="m.cache") as cap:
    cap(model, x)
f = torch.compiler.precompile.load("m.py", "m.cache")
```

## Before and after

```python
model, x = torch.nn.Linear(2, 2), torch.ones(1, 2)

# parent: a callable singleton that traces on the inputs you pass
python_code, cache = torch.compiler.precompile(lambda m, x: m(x), model, x)
f = torch.compiler.precompile.load(python_code, cache)
out = f(model, x)

# now: a module
import torch.compiler.precompile as p
type(p)                                   # <class 'module'>
p.__all__                                 # ['Capture', 'MakeFxTracer', 'PrecompiledRunnable', 'PrecompileSummary']
p.MakeFxTracer, p.Capture, p.PrecompiledRunnable, p.PrecompileSummary
p.PrecompileError is torch.compiler.PrecompileError   # True, re-exported
torch.compiler.precompile(lambda m, x: m(x), model, x)
# TypeError: 'module' object is not callable
hasattr(p, "load"), hasattr(p, "capture")  # (False, False): the entry points come in the next commits
```

`torch/compiler/__init__.py` used to import `precompile` and `PrecompileError` from `torch._precompile`; it now imports `PrecompileError` from there and `precompile` as a submodule (`from . import config, precompile`); the comment above them says the order of the two imports is not load-bearing, since the submodule imports `torch._precompile` itself. `"precompile"` and `"PrecompileError"` stay in `torch.compiler.__all__`. The `_PrecompileApi` class goes, together with its `__reduce__`/`__repr__` singleton fixups, the `__name__`/`__qualname__`/`__doc__` assignments on the instance, the `_PrecompileApi.load.__module__`/`__qualname__` overrides and the `torch._C._log_api_usage_once("torch.compiler.precompile")` call in its `__call__`. The loader core it delegated to, `_runnable_from_pair(python_code, cache)` (moved out of the method three commits down), stays, since the module's `load` builds on it in the next commit, #198213; its docstring now names only that module `load` as the thing built on it. Between this commit and those the module has no entry point, and the make_fx internals (`_capture`, `PrecompiledModule`) stay in `torch/_precompile.py`, unreachable from the public surface. The module docstring of `torch/_precompile.py` is cut down to this commit's state: the make_fx capture internals behind the public module, whose types `torch/compiler/precompile.py` re-exports, with `capture` and `load` named as the entry points the following commits add rather than described as if they existed.

## What already moved below this PR

This PR was split so its diff is only the switch itself. The two PRs directly below it carry everything else the callable owned, so it is not repeated here:

- #198283 moves the `backend`/`tracer` checks from `_PrecompileApi.__call__` into `PrecompiledModule.__init__`, has `_parse_artifact_metadata` refuse an unknown `BACKEND` tag as a `PrecompileError` before anything is exec'd, and re-points the suite's `_precompile_pair` / `_load_pair` helpers at `PrecompiledModule` and `_runnable_from_pair`. Its description has the before/after and the tests (`test_backend_invalid_raises`, `test_tracer_invalid_raises`, `test_artifact_backend_value_is_validated_before_exec`).
- #198284 is docs-only: it moves the shared-`shape_id` and threading caveats from the callable's docstring into Note [precompile programming model], and moves the private names out of `PrecompileSummary`'s docstring into a code comment, since that docstring is rendered into the public reference by this PR.

## What the new module does

The whole module is a re-export plus one loop:

```python
# torch/compiler/precompile.py
import typing

from torch._precompile import Capture, MakeFxTracer, PrecompiledRunnable, PrecompileError  # noqa: F401
from torch.compiler._precompile_types import PrecompileSummary

for _t in (Capture, MakeFxTracer, PrecompiledRunnable, PrecompileSummary):
    _t.__annotations__ = typing.get_type_hints(_t)   # resolve strings against the DEFINING module first
    _t.__module__ = "torch.compiler.precompile"
del _t
del typing

__all__ = ["Capture", "MakeFxTracer", "PrecompiledRunnable", "PrecompileSummary"]
```

Three things in that loop are load-bearing. First, the order: `torch/_precompile.py` uses `from __future__ import annotations`, so a class's annotations are strings, and `typing.get_type_hints` resolves them in the namespace of `sys.modules[cls.__module__]`. Re-homing first and resolving later would make `get_type_hints` look up any non-builtin name (a `Callable`-typed field, say) in the new module's namespace and fail. Today every class-level annotation resolves anywhere -- `MakeFxTracer`'s is `dict | None`, `PrecompiledRunnable`'s is `installed: bool`, and `Capture` has none, so for it the loop is the `__module__` assignment alone -- and resolving before the re-homing keeps that true for whatever is added later. Second, what is deliberately left alone: `@dataclass` snapshots each field's annotation string at decoration into `Field.type` and into `__init__.__annotations__`, and the loop does not rewrite those, because nothing here reads them; `__annotations__` is what `get_type_hints` and the public-members test consult, and the comment in the loop says so. Third, why a loop here rather than `__module__ = "torch.compiler.precompile"` in each class body: `@dataclass` dereferences `sys.modules[cls.__module__]` while decorating, and `torch.compiler.precompile` is still being imported when those class bodies run.

```python
p.MakeFxTracer.__module__            # "torch.compiler.precompile"
typing.get_type_hints(p.MakeFxTracer)        # {'decompositions': dict | None}, resolved, not a string
typing.get_type_hints(p.PrecompileSummary)   # every field resolved, none left as a string
pickle.loads(pickle.dumps(p.PrecompileSummary(frames=1, resume_functions=0, guarded_codes=1, backend_graphs=1)))   # resolves through the public path
inspect.getsource(p.MakeFxTracer)    # OSError: could not find class definition
```

The last line is the cost: `inspect.getsource` resolves a class's file through `sys.modules[cls.__module__]`, and there is no class body in `torch/compiler/precompile.py`, so it raises `OSError` and Sphinx drops the `[SOURCE]` link for these types. `torch/onnx/__init__.py` makes the same trade for its public types, and the comment on `test_precompile_member_module_and_qualname_resolve_to_it` names it.

## `PrecompileError` stays in `torch.compiler`

```python
torch.compiler.PrecompileError.__module__     # "torch.compiler", unchanged
torch.compiler.PrecompileError.__qualname__   # parent: "precompile.PrecompileError"; now: "PrecompileError"
```

Its home is `torch.compiler`, for the conventional `except torch.compiler.PrecompileError`; the module re-exports it only so `torch.compiler.precompile.PrecompileError` also resolves, and it is not in `__all__` or in the re-homing loop. The parent set `__module__` and `__qualname__` on it by assignment at the bottom of `torch/_precompile.py`, next to the same fixups for `_PrecompileApi.load`; the class now declares `__module__ = "torch.compiler"` in its body and the `__qualname__` override goes away with the singleton. Because it is outside the loop, any string annotation it grows resolves against `torch.compiler`, so they must stay builtin-resolvable; a comment on the class says so.

`GuardFact`, the private per-guard fact that the internals of `torch/_dynamo/precompile_package.py` consume, stays in `torch/compiler/_precompile_types.py` and is not exported.

## Docs: rendered from the source instead of written by hand

`docs/source/torch.compiler_api.md` documented the callable with hand-written `.. py:function:: precompile(...)` and `.. py:method:: precompile.load(...)` blocks, which Sphinx never checked against the object. They are replaced by:

```rst
.. py:module:: torch.compiler.precompile
.. currentmodule:: torch.compiler

.. autoexception:: torch.compiler.PrecompileError
.. autoclass:: torch.compiler.precompile.MakeFxTracer
.. autoclass:: torch.compiler.precompile.Capture
.. autoclass:: torch.compiler.precompile.PrecompiledRunnable
   :members: unload
.. autoclass:: torch.compiler.precompile.PrecompileSummary
   :members: complete, dropped_guard_types, kept_guard_types
```

`.. py:module::` registers `torch.compiler.precompile` as a module, which opts its `__all__` into the docs coverage gate for the names not already on `conf.py`'s bare-name ignore list (`Capture` is, through the datapipes class of the same name), and the four exported types render with `.. autoclass::` from their docstrings, so the reference cannot drift from the source. The prose above them describes what the module documents -- the tracer configuration a capture takes, the capture handle it returns, the runnable a load returns, and the coverage and guard report -- and the prototype warning names the module only. The user-guide paragraph in `docs/source/user_guide/torch_compiler/torch.compiler.md` replaces its `precompile(lambda model, x: model(x), model, x)` example with a description of the caller-driven capture that names no function yet.

`installed` is not a `:members:` entry because autodoc reads a bare (PEP-224) attribute docstring from the source of `sys.modules[cls.__module__]`, which after the re-homing is `torch/compiler/precompile.py`, where there is no class body, so it rendered blank. The attribute is documented in the class docstring's `Attributes:` block instead, and the comment on the re-homing loop says why:

```python
class PrecompiledRunnable:
    """...
    Attributes:
        installed: Whether calling this handle installs onto the captured code
            objects; ``False`` for a standalone artifact.
    """

    installed: bool = False
    # parent: """Whether calling this handle installs onto the captured code objects."""
```

```python
# torch/compiler/precompile.py, above the loop
# Their attributes are documented in the class docstring: Sphinx reads a bare
# attribute docstring from the source of sys.modules[cls.__module__], now this file.
```

The deleted hand-written blocks also carried two things that belong to no exported type, and each has a rendered home:

- **The make_fx capture contract**, from the `py:function` note, moves into `MakeFxTracer`'s docstring, which `.. autoclass::` renders. Its new paragraph says every tensor `fn` reads is an argument or a registered parameter/buffer of an `nn.Module` argument; shapes are static unless a dim is marked with `mark_unbacked` (`torch._dynamo.decorators`, inductor backend only), which captures it as an unbacked symint so one artifact serves any runtime size and a graph that needs to guard on it fails at capture; dims that must be equal at runtime must share a `shape_id`, since dims marked independently bake a silent equal-size assumption and a mismatch at runtime is not caught; each input's dtype and device are specialized (a runtime mismatch is rejected), inductor also specializes on memory format, and a nested-tensor example input is refused. The full list stays in Note [precompile programming model] in `torch/_precompile.py`, which the paragraph cites.
- **The `exec`/trust warning** of the `py:method:: precompile.load` block is deliberately not restored here: this commit has no entry point that execs anything. It returns with `load`'s own rendered docstring in the next commit, #198213 ("Both files are trusted, EXECUTABLE input: load only artifacts you produced or otherwise trust.").

Because `PrecompileSummary`'s docstring is rendered into the public reference from here on, #198284 below already stripped the private names it cited.

## Tests

Because #198283 already routes every test that used the callable through `_precompile_pair` and `_load_pair`, which drive `PrecompiledModule` and `_runnable_from_pair` directly, every behavioural test of the make_fx capture, the drivers and the loader runs unchanged on both sides of the switch; this PR only rewords the two helpers' docstrings to call the callable retired.

Four tests are removed. Three asserted on the callable object itself: `test_public_api_surface` and `test_public_identity_module_and_qualname` (its identity, `__module__` and the `precompile.load` qualname) and `test_singleton_pickle_deepcopy_roundtrip` (its pickling as a singleton). The fourth is `test_callable_api_end_to_end`, parametrized over inductor and eager, which #198283 two commits down added as the callable's one end-to-end check; the render and load paths it drove stay covered through `_precompile_pair` / `_load_pair`. The guards in `test_public_api_surface` that were not about the callable (`"precompile"` in `torch.compiler.__all__`, absent from `torch.__all__`, and `hasattr(torch, "precompile")` false) move into `test_precompile_public_members_are_the_exported_types`. Four tests take the removed ones' place, two of them parametrized over `_PRECOMPILE_PUBLIC_MEMBERS`, the public callables of `torch.compiler.precompile`:

```python
def test_precompile_public_members_are_the_exported_types(self):
    # pins the list, so the two parametrized tests cannot degenerate to zero cases
    exported = {"Capture", "MakeFxTracer", "PrecompiledRunnable", "PrecompileSummary"}
    self.assertEqual(set(torch.compiler.precompile.__all__), exported)
    self.assertEqual(set(_PRECOMPILE_PUBLIC_MEMBERS), exported | {"PrecompileError"})

@parametrize("name", _PRECOMPILE_PUBLIC_MEMBERS)
def test_precompile_public_members_resolve(self, name):
    hints = typing.get_type_hints(member)              # every annotation resolves ...
    self.assertEqual(set(hints), set(inspect.get_annotations(member)))
    for hint in hints.values():
        self.assertNotIsInstance(hint, str)            # ... to an object, not a string

def test_precompile_module_identity(self):
    self.assertIs(importlib.import_module("torch.compiler.precompile"), torch.compiler.precompile)
    self.assertIs(sys.modules["torch.compiler.precompile"], torch.compiler.precompile)

@parametrize("name", _PRECOMPILE_PUBLIC_MEMBERS)
def test_precompile_member_module_and_qualname_resolve_to_it(self, name):
    # walk sys.modules[member.__module__] + member.__qualname__ back to the object itself
```

Test Plan:

```
python test/test_precompile.py
lintrunner -a torch/compiler/__init__.py torch/compiler/precompile.py torch/compiler/_precompile_types.py torch/_precompile.py test/test_precompile.py docs/source/torch.compiler_api.md docs/source/user_guide/torch_compiler/torch.compiler.md
```

221 tests; the 21 errors on this machine (CUDA numerics and autotune tests) are the environment's missing triton and are identical to main's.

Authored with an AI assistant.

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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: #197993
Approved by: https://github.com/aorenste
ghstack dependencies: #198211, #198223, #198283, #198284
pytorchmergebot pushed a commit that referenced this pull request Sep 24, 2026
**Problem.** After the switch from a callable to a module, `torch.compiler.precompile` had no entry point: a capture could write its `(python_code, cache)` pair to disk, but nothing public could read that pair back and run it.

**Fix.** Add `torch.compiler.precompile.load(artifact_path, cache_path)`, the consuming half, over the loader core the switch kept.

**Summary.** The module switch left `torch.compiler.precompile` with no entry point, so the on-disk pair a capture writes could not be reloaded through any public name. This commit adds the consuming half first: `load(artifact_path, cache_path)` reads the pair with `_read_artifact` (already in place) and hands it to `_runnable_from_pair`, the loader core the switch kept from the callable API's `load`, which validates the source as a precompile artifact through `_parse_artifact_metadata`, refuses a cache whose `backend` or `code_hash` does not pair with the source, degrades a foreign format/version envelope to JIT'ing from the source, primes the inductor kernel caches from the bundle, and exec's the inlined driver. `load` reads the source's `BACKEND` and checks the cache's `backend` tag against it; the cache is acceleration only, primed when it carries a bundle. `load` is re-homed where it is defined rather than in the loop that re-homes the types, because a function's string annotations resolve through its own globals rather than its `__module__`. The loader's messages stop saying `precompile()` -- a pair is now from a `capture`, and the warnings name `torch.compiler.precompile` rather than one entry point, since the capture-time self-load above will run the same code -- and the module Note's invariant 7 follows.

## 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 the serving half, `load(artifact_path, cache_path)`. The capture half comes next in #198135.

## The entry point

```python
import torch
from torch.compiler.precompile import load, PrecompiledRunnable

# A capture wrote the pair; in the suite, TestPrecompileLoad writes it with
# _precompile_pair(_files_fn, model, x, backend=...) + _write_artifact.
f = torch.compiler.precompile.load("m.py", "m.cache")
isinstance(f, PrecompiledRunnable)   # True
f.installed                          # False: a standalone artifact installs nothing
f(model, x)                          # same argument structure _files_fn took: (model, x)
```

`load` is two lines over what was already there:

```python
def load(artifact_path, cache_path) -> PrecompiledRunnable:
    torch._C._log_api_usage_once("torch.compiler.precompile.load")
    python_code, cache = _read_artifact(artifact_path, cache_path)
    return _runnable_from_pair(python_code, cache)
```

`_runnable_from_pair` is unchanged in what it does: it validates the source as a precompile artifact through `_parse_artifact_metadata`, reads the source's `BACKEND` and checks the cache's `backend` tag against it, unpickles the envelope with `weights_only=True`, primes the inductor kernel caches through `torch.compiler.load_cache_artifacts` when the cache carries a bundle, and exec's the inlined driver with `_make_inlined_forward`. Its docstring now calls it the core of `load`, which reads the pair off disk first, instead of "the loader core the module's `load` builds on".

The round trip is pinned by `test_load_round_trips_the_pair` on both backends: the served result equals eager `model(x)`, no weights are baked in, so a structurally identical `_FilesModel()` with other weights serves its own answer, and the handle's context manager and `unload()` are no-ops. `test_load_in_a_fresh_process` saves the model's `state_dict`, `x` and the eager `expected = model(x)` with `torch.save`, then runs `_FRESH_PROCESS_LOADER` under `sys.executable`, which rebuilds the model from the `state_dict`, calls `torch.compiler.precompile.load(artifact, cache)` and `assert_close`s the served result against that eager `expected`.

## What load refuses, and what it only warns about

```python
load("m.py", "other.cache")           # cache from a different capture (same backend)
# PrecompileError: cache does not match python_code (its code_hash ... != sha256(python_code) ...);
#                  the cache and python_code came from different precompile captures. ...

load("m.py", "missing.cache")         # a missing cache
# PrecompileError: precompile could not read the artifact pair (artifact_path='m.py', cache_path='missing.cache'): ...
```

Both are `test_load_refuses_a_pair_from_two_captures_or_a_missing_cache`, which writes a second pair with `x=torch.randn(3, 4)` and pairs the first artifact with its cache. A cache whose `format`/`version` does not match is not fatal: the cache is acceleration only, so `load` logs a warning and degrades to JIT'ing from `python_code`, as does an envelope it cannot read or a bundle it cannot prime.

Those messages are reworded. Where the parent said `"came from different precompile() calls"` and `"Pair each cache with the python_code from the same precompile() call"`, the refusals now say `"different precompile captures"` and `"the same capture"`, and the three `log.warning` calls that began `torch.compiler.precompile.load ...` now begin `torch.compiler.precompile ...`: the capture-time self-load above runs the same core, so naming one entry point would be wrong there. The two sentences of Note [precompile programming model] invariant 7 that said `precompile() calls` follow the same wording.

## Export, re-homing and docs

```python
# torch/compiler/precompile.py
from torch._precompile import Capture, load, MakeFxTracer, PrecompiledRunnable, PrecompileError
for _t in (Capture, MakeFxTracer, PrecompiledRunnable, PrecompileSummary):
    _t.__module__ = "torch.compiler.precompile"       # classes: re-homed here (parent)
__all__ = ["load", "Capture", "MakeFxTracer", "PrecompiledRunnable", "PrecompileSummary"]

# torch/_precompile.py
__all__: list[str] = []                               # the private module exports nothing
...
load.__module__ = "torch.compiler.precompile"         # function: re-homed where it is defined
```

`load` joins `__all__` as its first name; the four types were exported and re-homed by the parent. `load` is re-homed where it is defined, since a function's string annotations resolve through its own globals rather than its `__module__` (`test_precompile_public_members_resolve` pins that every export's annotations resolve, and `test_precompile_public_members_are_the_exported_types` pins the now five-name `__all__`). The private module's `__all__` stays empty, with its comment rewritten to say the public surface (`capture`, `load` and their types) lives in `torch/compiler/precompile.py` and `PrecompileError` in `torch/compiler/__init__.py`, so `test_public_bindings` sees one public location. The API reference in `docs/source/torch.compiler_api.md` renders `load` with `autofunction` ahead of the types, and its lead-in now says it documents the module's `load` and its public types.

Test Plan:

`TestPrecompileLoad` writes pairs with the suite's `_precompile_pair` plus `_write_artifact` and loads them: the round trip on both backends (weight swap, no-op enter/unload), a fresh-process load through `sys.executable`, and the mismatched-pair and missing-cache refusals; the fresh-process load compares the served result against eager.

```
python test/test_precompile.py
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: #198213
Approved by: https://github.com/aorenste
ghstack dependencies: #198211, #198223, #198283, #198284, #197993
pytorchmergebot pushed a commit that referenced this pull request Sep 24, 2026
…fact pair (#198135)

**Problem.** `torch.compiler.precompile` can `load` an on-disk `(python_code, cache)` pair but nothing in the module writes one: there is no public way to capture `fn` and produce the artifact `load` expects.

**Fix.** Add `capture(fn, /, *, artifact_path, cache_path, tracer=MakeFxTracer(), backend="inductor")`, a `Capture` context manager that traces one call with make_fx, serves it through the freshly rendered artifact, and writes the pair on clean exit or on `cap.save()`.

**Summary.** With `load` in place, this adds the producing half of the module: `capture(...)` returns a `Capture`, and entered as a context manager and called like `fn`, it runs the call through the freshly rendered artifact, so the caller gets exactly what serving returns, and writes the `(python_code, cache)` pair to the two paths when the block exits cleanly or whenever `cap.save()` is called inside it. The make_fx front-end is the only tracer here: `_MakeFxCapture` takes exactly one positional call and refuses a second, since the trace records one execution, and a `MakeFxTracer(decompositions=...)` table is forwarded into that trace. A step that calls `.backward()` captures its parameter gradients, which the artifact scatters onto the runtime model; the trace runs with grad enabled and the drivers pin their own grad mode, so there is no grad-mode knob. The capture must be entered before it is called and is over once its block exits, so a `cap(model, x)` outside the `with` block, before or after, raises instead of running the whole trace and writing nothing; the rendered pair is recorded only once the serve has returned, so a call whose serve raised can be retried and a clean exit never writes a pair known not to run; a block that raises, or never calls the capture, writes nothing; and a capture is single-use, with `save()` refused outside its block. `capture()` validates the arguments its callee cannot (a tracer of the wrong type is a `TypeError`, and so is a `functools.partial`; a bad `backend` stays the `ValueError` `PrecompiledModule.__init__` already raises), the self-load goes through `_runnable_from_pair(..., _trusted=True)`, a keyword added here with its only caller, so the exec warning a load of untrusted source emits is suppressed for source rendered in-process a moment ago, and `capture` is re-homed to `torch.compiler.precompile` beside `load`, with the API reference and user guide showing the capture/load pair.

## 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 `capture()` as the context manager, with `MakeFxTracer` as its only tracer so far. The one-call limit here is `MakeFxTracer`'s (one ATen trace records one execution), not the API's: the multi-call `DynamoTracer` capture arrives in #198138 and becomes the default in #198217.

## The capture/load pair

`capture` is caller-driven: it returns a `Capture` and runs nothing until the block calls it. The call inside the block is served by the artifact, and the two files land when the block exits.

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

with capture(lambda model, x: model(x), artifact_path="m.py", cache_path="m.cache") as cap:
    y = cap(model, x)          # served through the rendered artifact, == model(x)

f = load("m.py", "m.cache")   # PrecompiledRunnable; f.installed is False
f(model, x)                    # == model(x)
f(other, x)                    # == other(x): no weights are baked in
```

`test_capture_and_load_round_trip` pins this on both backends: the call result, the load, the weight swap onto a structurally identical `_FilesModel`, and that the standalone artifact's `with f:` and `f.unload()` are no-ops. `capture()` validates only the arguments its callee cannot; the `backend` check is not duplicated, since `PrecompiledModule.__init__` already raises the `ValueError` when `_MakeFxCapture` builds its module (`test_capture_validates_backend_and_tracer`):

```python
capture(fn, ..., backend="nope")           # ValueError from PrecompiledModule: precompile backend must be 'inductor' or 'eager'
capture(fn, ..., tracer="make_fx")         # TypeError: precompile.capture tracer must be a MakeFxTracer
capture(functools.partial(fn, model), ...) # TypeError: ... takes the function itself, not a functools.partial
```

The partial is a `TypeError` like the bad tracer: the artifact rebuilds the call from the function's own parameters, so a pre-bound model or argument would not be one of them. Pass the underlying function and give them as call arguments. Both paths may be `os.PathLike`, and the tracer may be left at its `MakeFxTracer()` default: `test_capture_takes_pathlike_paths_and_the_default_tracer` captures into `pathlib.Path(self.dir) / "sub" / "m.py"` and `.../"m.cache"` and loads the pair back with the same `Path` objects; the same test pins `capture()`'s `backend` default to `"inductor"`.

## One positional call, only inside the block, and nothing written on a bad block

`_MakeFxCapture` is single-shot: a make_fx trace records the ATen ops of one execution, and there is no notion of guards or recompiled variants here, so a second call could add nothing. Arguments are positional only, as the loaded artifact takes them.

```python
with capture(_files_fn, artifact_path=..., cache_path=..., backend="eager") as cap:
    cap(model, x=x)     # ValueError: positional arguments only
    cap(model, x)       # traced and served
    cap(model, x)       # PrecompileError: captures a single call ...
```

The capture must be entered before it is called and is over once its block exits. Outside the block nothing would be written at exit, so `__call__` refuses up front rather than running the whole trace for a missing artifact; `__enter__` arms `_entered` and `__exit__` clears it whether the block exited cleanly or raised, so a call after the block is refused the same way as a call before it:

```python
cap = capture(_files_fn, artifact_path=..., cache_path=..., backend="eager")
cap(model, x)           # PrecompileError: capture is not active: enter it with a `with` block ...
# artifact_path does not exist

with cap:
    raise RuntimeError("boom")   # propagates
cap(model, x)           # PrecompileError: capture is not active; still nothing on disk

with capture(_files_fn, ...) as cap:
    cap(model, x)                # pair written at exit
cap(model, x)           # PrecompileError: capture is not active
```

The pair is assigned to `self._rendered` only after the serve has returned, so a call whose serve raised leaves the capture retryable and gives exit and `save()` nothing to write; `test_a_serve_that_raises_leaves_the_capture_retryable` patches `torch._precompile._runnable_from_pair` to raise, asserts the artifact does not exist, then makes the same call again and gets `model(x)` back with the pair on disk after exit:

```python
with capture(_files_fn, ..., backend="eager") as cap:
    with mock.patch("torch._precompile._runnable_from_pair", side_effect=RuntimeError("serve failed")):
        cap(model, x)            # RuntimeError: serve failed; artifact does not exist
    cap(model, x)                # == model(x): the capture was not consumed
# artifact exists
```

`__exit__` writes only on a clean exit that captured a call. A block that raises writes nothing it has not already saved, and one that never called the capture leaves both paths untouched; the empty block surfaces as `PrecompileError("nothing was captured ...")` from the exit-time `save()`, rather than writing an empty artifact, and the `Capture` docstring now documents both.

```python
with capture(_files_fn, ...):
    pass                       # PrecompileError: nothing was captured; no files

with capture(_files_fn, ...) as cap:
    cap(model, x)
    raise RuntimeError("boom") # propagates; artifact and cache do not exist
```

Pinned by `test_a_make_fx_capture_takes_exactly_one_positional_call`, `test_a_capture_must_be_entered_before_it_is_called`, `test_a_capture_is_over_once_its_block_exits` (both the raising and the clean exit), `test_a_serve_that_raises_leaves_the_capture_retryable` and `test_a_block_without_a_call_or_that_raises_writes_nothing`.

## `save()` checkpoints the pair mid-block

`Capture.save()` joins the contract: it writes everything captured so far to the same two files without ending the capture. For a make_fx capture there is nothing further to fold in, so `save()` and block exit write identical bytes.

```python
with capture(_files_fn, ..., backend="eager") as cap:
    cap.save()                        # PrecompileError: nothing was captured
    cap(model, x)
    cap.save()                        # pair on disk; load(...) already works here
    saved = open(artifact, "rb").read()
# exit rewrites the same bytes: open(artifact, "rb").read() == saved
```

`test_save_checkpoints_the_pair_exit_rewrites` reads the file after `save()`, loads and runs it inside the block, and asserts the exit rewrite is byte-identical.

## A capture is single-use, and only its block writes

`__exit__` writes through a private `_write()`, and the public `save()` refuses outside the block, so a block that raised cannot have its withheld pair published afterwards. `__enter__` refuses a capture that is already entered or has exited, so a nested `with` cannot disarm the outer block and a second block cannot silently rewrite the previous trace's bytes. A failed write surfaces as a `PrecompileError`, with the previous pair left in place. The messages match the ones `_DynamoCapture` uses higher in the stack, except that a call or `save()` after the block has exited says so ("its block has already exited, and a capture is single-use; call capture() again for a fresh one.") instead of telling the caller to enter a `with` block that `__enter__` would then refuse. `__enter__` after the block has exited gives the same message. A call whose serve raised records nothing, so if the block swallows that error, the exit raises "nothing was captured: the capture's call raised, so there is no pair to write." A block that never called the capture still gets the "call the capture with your example arguments" message. The `Capture` and `capture()` docstrings state that a capture is single-use, including after a failed write at exit: the spent capture does not keep its pair, so the caller fixes the path and captures again. `Capture.save` documents that it raises outside the block.

```python
cap = capture(_files_fn, ..., backend="eager")
try:
    with cap:
        cap(model, x)
        raise RuntimeError("boom")    # exit writes nothing
except RuntimeError:
    pass
cap.save()                            # PrecompileError: capture is not active: its block has
                                      #   already exited, and a capture is single-use; ...
with cap:                             # PrecompileError: this capture has already been entered;
    ...                               #   capture() returns a fresh capture per call.
```

`test_save_after_a_raising_block_is_refused`, `test_a_capture_is_over_once_its_block_exits` ("already exited" after a raising and a clean exit), `test_a_capture_must_be_entered_before_it_is_called` (a call and a `save()` before the block), `test_a_swallowed_serve_failure_is_named_at_exit`, `test_a_capture_is_single_use` (nested and second block) and `test_an_exit_time_write_failure_raises_precompile_error` (an `OSError` from `_write_artifact` during `__exit__`) pin these.

## Decompositions reach the trace

`tracer` carries the tracer-specific configuration; `capture()` unpacks `tracer.decompositions` into the `PrecompiledModule` it builds, so a decomposition table given to `MakeFxTracer` is the one make_fx traces with.

```python
called = []

def my_relu_decomp(x):
    called.append(True)
    return (x > 0) * x

tracer = MakeFxTracer(decompositions={torch.ops.aten.relu.default: my_relu_decomp})
with capture(_files_fn, ..., backend="eager", tracer=tracer) as cap:
    y = cap(model, x)          # called == [True]; y == model(x)
```

`test_decompositions_forward_through_the_tracer` asserts the decomposition ran and the served result still matches eager.

## A backward step is captured without a flag

There is no grad-mode knob: the trace runs with grad enabled and the drivers pin their own grad mode, so the caller's ambient mode is not consulted. A step that calls `.backward()` therefore captures its parameter gradients, and the artifact scatters them onto whichever model is passed at runtime, returning `fn`'s own result (`None` here).

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

with capture(train_step, ..., backend=backend) as cap:
    cap(model, x)                      # returns None; model.lin.weight.grad populated

load(artifact, cache)(runtime, x)      # runtime.lin.{weight,bias}.grad == eager grads
```

`test_a_backward_step_scatters_grads_onto_the_runtime_model` runs on both backends and compares both the captured model's and a fresh runtime model's grads against an eager `_FilesModel` with the same state dict.

## The trusted self-load, recorded after the serve

The call inside the block is served by the same path `load` takes, so what the caller gets back is exactly what serving produces (invariants checked, grads scattered onto the model). `python_code` is built once and threaded into `to_cache_bytes` so `code_hash` covers exactly the bytes written. The pair is assigned to `self._rendered` only after the serve has returned: a serve that raised leaves the capture retryable, and neither exit nor `save()` has a pair known not to run to write (the retry is exercised above).

```python
# torch/_precompile.py, _MakeFxCapture.__call__
self._module._compile(args)
python_code = self._module.to_python_code()
rendered = (python_code, self._module.to_cache_bytes(python_code))
result = _runnable_from_pair(*rendered, _trusted=True)(*args)
self._rendered = rendered
return result
```

`_runnable_from_pair(python_code, cache, *, _trusted=False)` is the shared core of `load` (which reads the pair off disk first) and this self-load. `_trusted` is added here with its only caller: the source was rendered in-process a moment ago, so it is not untrusted input, and the keyword forwards as `_make_inlined_forward(python_code, warn=not _trusted)` to suppress the per-load exec warning. `load` itself keeps the default and still warns. The round-trip test asserts the suppression with `assertNoLogs("torch._precompile", level="WARNING")` around the captured call. `Callable` also leaves the `TYPE_CHECKING` block in this PR and becomes a runtime `from collections.abc import Callable` import in `torch/_precompile.py`.

## Re-homing and docs

`capture` joins `load` in the `__module__ = "torch.compiler.precompile"` loop at the bottom of `torch/_precompile.py`, so introspection (test_public_bindings, Sphinx, `help()`) resolves both under the public path; both are re-homed where they are defined because a function's annotations resolve through its own globals, not its `__module__`. `torch/compiler/precompile.py` exports `capture` and its docstring now points at `capture` and `load` rather than listing the types. The API reference gains `.. autofunction:: torch.compiler.precompile.capture` and `:members: save` on `Capture`, and both it and the user guide show the capture/load block above. `test_precompile_public_members_are_the_exported_types` adds `"capture"` to the pinned export list.

Test Plan:

`TestPrecompileCapture` in test/test_precompile.py: the round trip on both backends (call result, load, weight swap, no-op enter/unload), the one-call/positional-only refusals, the not-entered and after-exit refusals, a serve that raises leaving the capture retryable with nothing written, `PathLike` paths into a new directory with the default tracer, nothing written on a raising or empty block, `save()` mid-block, backend/tracer/partial validation, a `MakeFxTracer(decompositions=...)` table reaching the trace, and a `.backward()` step on both backends whose grads match eager on the captured and on a runtime model.

```
python test/test_precompile.py
lintrunner -a torch/_precompile.py torch/compiler/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: #198135
Approved by: https://github.com/aorenste
ghstack dependencies: #198211, #198223, #198283, #198284, #197993, #198213
pytorchmergebot pushed a commit that referenced this pull request Sep 24, 2026
**Problem.** A make_fx capture ran the caller's `fn` twice, once to trace it and once to serve the rendered artifact. Every in-place update in `fn`, such as a BatchNorm's running stats or an `x.add_(1)`, landed twice. The hazard comes from the commit directly below, which added `capture()` and its serve; the two land together.

**Fix.** Restore the buffers and tensor inputs the trace changed, so the serve is the one execution the caller sees. Refuse a `fn` that updates a parameter in place, detected from the traced graph.

**Summary.** `_MakeFxCapture.__call__` traces `fn` with make_fx, then serves the freshly rendered artifact on the real arguments so the caller gets exactly what serving returns. A static trace runs on the real example tensors, though, so one captured call of a training-mode BatchNorm left `num_batches_tracked == 2` and a `x.add_(1)` added 2. The trace now snapshots the modules' buffers and the tensor arguments, and after tracing copies back any value that changed, the same treatment `_capture` already gives `.grad`; changed values are found by comparing values, because under make_fx the batch-norm kernel's running-stat update does not bump the buffer's version. Parameters are not snapshotted, because that would clone every parameter up front, so a `fn` that updates one in place (an optimizer step) is refused with a `PrecompileError`, found by scanning the traced graph for a write into a parameter placeholder rather than by version counter, which a write through `p.data` does not bump. An unbacked (`mark_unbacked`) capture traces on fake tensors, so it skips the snapshot and the scan entirely.

## 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 fixes the `MakeFxTracer` capture from #198135 so in-place updates in `fn` land once, not twice.

## Before and after

```python
import torch
from torch.compiler.precompile import capture, MakeFxTracer

def step(m, x):
    y = m(x)
    x.add_(1)
    return y.sum()

m = torch.nn.BatchNorm1d(4).train()
x = torch.zeros(3, 4)
with capture(step, artifact_path="a.py", cache_path="a.cache", tracer=MakeFxTracer()) as cap:
    cap(m, x)

m.num_batches_tracked   # parent: 2   now: 1
x[0, 0]                 # parent: 2.0 now: 1.0
```

Measured on both `backend="eager"` and `backend="inductor"`, with the same numbers on each.

## How the trace is kept side-effect free

```python
def _trace_without_side_effects(self, args):
    if _has_unbacked_marks(args):
        self._module._compile(args)          # traces on fakes; only the serve touches the reals
        return
    mods = [a for a in args if isinstance(a, torch.nn.Module)]
    leaves = pytree.tree_leaves(args)
    # a parameter also passed as a plain argument is snapshotted like any input
    params = {id(p) for m in mods for p in m.parameters()} - {id(t) for t in leaves}
    tensors = [*(b for m in mods for b in m.buffers()), *leaves]
    saved = {id(t): (t, t.detach().clone()) for t in tensors
             if isinstance(t, torch.Tensor) and id(t) not in params}
    try:
        self._module._compile(args)          # the make_fx trace
    finally:
        with torch.no_grad():
            for t, value in saved.values():
                if not torch.equal(t, value):  # by value: BN does not bump _version
                    t.copy_(value)
    if _writes_a_parameter(self._module._gm, len(self._module._param_names)):
        raise PrecompileError("MakeFxTracer cannot capture a fn that updates a parameter in place ...")
```

The restore runs in `finally`, so a trace that raises also leaves the caller's buffers and inputs as they were.

A parameter passed to `fn` both inside its module and as a plain tensor argument (`cap(model, model.lin.weight, x)`) is traced as that user input, so the parameter scan below would not see a write to it. It is therefore left out of `params` and snapshotted and restored by value like any other input, and the serve applies its update once.

## How a parameter write is detected

The params are the first `len(_param_names)` placeholders of the traced graph. `_writes_a_parameter` looks for an op whose schema marks an argument `alias_info.is_write`, and walks that argument back to its base through `_aliased_input`:

```python
# A write can reach a parameter placeholder in several graph shapes:
w.add_(1)                                  # add_ directly on the placeholder
w.data.add_(1)                             # add_ on aten.alias(placeholder)
w.chunk(2)[0].add_(1)                      # add_ on getitem(split(placeholder))
for row in w.unbind(0): row.mul_(0.9)      # mul_ on getitem(unbind(placeholder))
torch._foreach_add_(list(m.parameters()), 1)  # a Tensor(a!)[] argument, walked per element
```

`_aliased_input` steps through `operator.getitem` to the list it indexes. For a schema op it follows the argument whose alias set matches the return's, so an `out=` overload walks to `out`, not to its first argument; `torch.mul(w.detach(), 2, out=buf).add_(1)` with `buf` an input still captures. `split`/`unbind`, whose alias set sits on the list elements, follow their one aliased argument.

The graph is used rather than `p._version` because a write through `.data` bumps no counter the parameter shares: with a version check, `p.data.add_(1)` in `fn` was captured silently and the weight ended up +2. Checking fake-tensor storage (`StorageWeakRef` on each node's `meta["val"]`) was also tried and rejected: in a real-mode trace a view's fake value does not share its placeholder's storage, so `.data`, `chunk` and `unbind` writes were missed. `p.data = new` (a rebind) leaves no op in the graph at all; that is a pre-existing make_fx limitation this PR does not change.

```python
def step(model, x):
    with torch.no_grad():
        model.lin.weight.add_(1)   # an optimizer-style in-place update
    return model(x)

with capture(step, ..., backend="eager") as cap:
    cap(model, x)
# PrecompileError: MakeFxTracer cannot capture a fn that updates a parameter in place
# (e.g. an optimizer step): serving the capture would apply the update a second time,
# and the trace has already applied it once. Step the optimizer outside the captured fn.
```

## Alternatives rejected

- **Return the trace's own outputs and drop the serve.** An unbacked capture traces on fake tensors and has no real output to return, and `.grad` reaches the caller's model only through the served artifact.
- **Document the double update.** That would leave the default MakeFxTracer silently wrong for any model with batch norm.
- **Snapshot and restore parameters too.** That clones every parameter up front on every capture; the refusal costs nothing on the common path.

## Tests

| Test | Pins |
|---|---|
| `test_a_capture_applies_in_place_updates_once` (inductor, eager) | result, `num_batches_tracked`, running mean and `x` match a single eager step |
| `test_a_capture_refuses_an_in_place_parameter_update` (direct, `.data`, `chunk`, `unbind`, `_foreach_add_`; inductor, eager) | the refusal, and that no artifact is written |
| `test_a_parameter_passed_as_an_argument_is_updated_once` (inductor, eager) | a parameter also passed as a plain argument is updated once, not refused |
| `test_a_trace_that_raises_leaves_buffers_and_inputs_as_they_were` | the restore runs when `fn` raises, and nothing is written |

Test Plan:

`test_a_capture_applies_in_place_updates_once` (both backends) captures a BatchNorm step that also does `x.add_(1)`, and checks the result, `num_batches_tracked`, the running mean and `x` against a single eager step. `test_a_capture_refuses_an_in_place_parameter_update` pins the refusal, for a direct write, a write through `.data`, a write through a `chunk` or `unbind` piece, and a `_foreach_add_` over the parameters, on both backends, and checks that nothing is written. `test_a_parameter_passed_as_an_argument_is_updated_once` covers a parameter that `fn` also receives as a plain tensor argument: it is snapshotted with the inputs, so the serve applies its update once. `test_a_trace_that_raises_leaves_buffers_and_inputs_as_they_were` checks the restore also runs when `fn` raises.

```
python test/test_precompile.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: #198243
Approved by: https://github.com/aorenste
ghstack dependencies: #198211, #198223, #198283, #198284, #197993, #198213, #198135
pytorchmergebot pushed a commit that referenced this pull request Sep 28, 2026
…hon (#198214)

**Problem.** When a captured step ends in `.backward()`, Dynamo compiles nothing of the continuation it resumes after that call: `convert_frame` skips it when no tensor reaches it (`return None`), and it traces no ops in it (`SkipFrame`) when one does (`return loss`). Either way the continuation runs as plain Python during capture, and its record still exists (the frame ahead names it by resume name) but has no variant, so a standalone artifact treated it as a coverage gap: `_serving_mode` sent the capture to installed serving and the driver bound a refusal under the resume name.

**Fix.** The record now says `trivial` for a code entry with no guarded code that was not bypassed, `_serving_mode` counts such a non-entry frame as covered when reached and harmless when not, and the driver rebuilds it as a plain function over its code object in the captured module's scope, so the frame runs at serve time exactly as it ran during capture.

**Summary.** A standalone multi-graph artifact rebuilds each captured frame from its record, and a continuation with no variant used to be read as a frame the artifact could not serve. That was wrong for the continuation after a trailing `.backward()`: whether Dynamo skipped it before tracing or traced it and found no ops, it ran eager during capture, and yet the capture was sent to installed serving while a call reaching the frame in a standalone rebuild would have raised. `_multigraph_frames` now records `trivial = not code.guarded_codes and not code.bypassed`, `_serving_mode` treats a trivial non-entry frame as covered, and `_build_multigraph_forward` binds such a frame as a `types.FunctionType` over its code object in the captured module's scope (a factory over the closure tuple when it has free variables, the way Dynamo binds one). The design constraint is that the entry never qualifies and a bypassed frame never does, because a trivial entry means the whole capture ran eager and a bypassed frame's variants were dropped rather than never made. A bypassed continuation is unchanged: it still sends the capture to installing and still refuses at the call that reaches it.

## 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): continuation frames Dynamo compiled nothing of are served as plain functions. The standalone artifact pair these records feed is rendered in #198136, directly above.

## Background: frames, variants and the two serving modes

A graph break splits a captured function into an **entry** frame and **continuation** frames, the `__resume_at_...` functions Dynamo mints for the code after each break. `_multigraph_frames` keeps one record per frame, and two of its fields matter here:

```python
{
    "is_entry": ...,   # the user's function itself, not a resume function
    "variants": [...], # the frame's compiled guarded codes
    "bypassed": ...,   # it had guarded codes, but they were dropped (unserializable
                       # guards, a missing backend artifact); install keeps the
                       # binding but none of the codes
    ...
}
```

`_serving_mode(frames)` then picks how the pair is served. `"standalone"` means the driver rebuilds every frame from its record with no Dynamo in the loop. `"installed"` means the capture is installed into a live Dynamo, which has a compiler behind it for anything the records do not cover. The parent's rule for standalone was that every frame the entry can reach has variants.

## The frames Dynamo compiled nothing of

`.backward()` is a graph break, so a typical training step is an entry plus a continuation. The new test is parametrized over three steps whose continuation gets no variant:

```python
def no_tensor(model, x):          # continuation reaches no tensor: skipped before tracing
    (model(x) * _MULTIGRAPH_SCALE).sum().backward()

def no_ops(model, x):             # continuation traced, no ops found: SkipFrame
    loss = (model(x) * _MULTIGRAPH_SCALE).sum()
    loss.backward()
    return loss

def _closure_step(model, x):      # module-level; continuation has free variables
    loss = (model(x) * _MULTIGRAPH_SCALE).sum()
    loss.backward()
    get = lambda: loss
    return get()

package = CompilePackage(step)
compiled = torch._dynamo.optimize(backend="eager", package=package, guard_filter_fn=default_guard_filter_fn)(step)
compiled(model, x)
frames = _multigraph_frames(package.cache_entry())
```

In `no_tensor` the continuation only returns `None`, so `convert_frame` skips it before compiling. In `no_ops` the loss reaches it, Dynamo enters it, finds no ops and raises `SkipFrame("No ops traced")`, so its record has `has_compile_id` set but still no guarded code; `closure` also hands the loss to its continuation, which builds and calls the lambda without keeping any guarded code. In all three the continuation runs as plain Python during capture, and it is not bypassed. The parent produced the same records minus the `trivial` key, so the continuation -- reachable from the entry's bytecode, no variant -- was indistinguishable from a bypassed continuation:

```python
_serving_mode(frames)  # parent: "installed" -- a reachable frame has no variants
step(model, x)         # parent, standalone rebuild: the resume name is bound to a refusal,
                       # so the call raises at the continuation
                       # now: "standalone", and the continuation runs as plain Python
```

The records now read:

```python
[f["trivial"] for f in frames[:2]]        # [False, True]
[len(f["variants"]) for f in frames[:2]]  # [1, 0]
all(f["trivial"] for f in frames[1:])     # True: in "closure" the lambda's frame is recorded too
```

## 1. Recording `trivial`

```python
# torch/_precompile.py, _multigraph_frames
{
    "is_entry": i == 0,
    "bypassed": code.bypassed,
    # now: no variant and not bypassed -- Dynamo skipped the frame or traced
    # no ops in it, so it ran eager during capture and the driver runs it eager too
    "trivial": not code.guarded_codes and not code.bypassed,
    "code": code.python_code,
    ...
}
```

The key is the absence of guarded code, not the compile id (see "Alternative considered" below). A bypassed frame is excluded on purpose: its guarded codes are dead for a different reason (its guards could not be serialized, or a backend artifact was missing), and install keeps its binding but none of its codes.

## 2. Counting it as covered

```python
# torch/_precompile.py, _serving_mode
reachable = _reachable_frames(frames)
# parent: covered = {i for i, frame in enumerate(frames) if frame["variants"]}
#         return "standalone" if covered == reachable else "installed"
compiled = {i for i, frame in enumerate(frames) if frame["variants"]}
trivial = {i for i, f in enumerate(frames) if f["trivial"] and not f["is_entry"]}
return "standalone" if compiled <= reachable <= compiled | trivial else "installed"
```

Every compiled frame must still be reachable (an unreachable one would run eager, giving up its variant), and every reachable frame must be compiled or trivial. A trivial frame that is not reached costs nothing, which is what the `closure` shape's recorded lambda needs. The entry is excluded because a trivial entry means the whole capture ran eager, which is not something an artifact should serve. The test pins both verdicts on the same records:

```python
_serving_mode(frames)                  # now: "standalone" (parent: "installed")
frames[1].update(trivial=False, bypassed=True)
_serving_mode(frames)                  # "installed": a bypassed continuation is still a gap
```

## 3. Rebuilding it as plain Python

```python
# torch/_precompile_driver.py, _make_dispatcher
if frame["trivial"] and not is_entry:
    scope = _scope(frame)

    def _plain(closure):
        return types.FunctionType(target, scope, target.co_name, None, closure)

    if target.co_freevars:
        return _plain
    return _plain(None)
if not frame["variants"]:
    ... # parent: this branch bound a refusal under the resume name
```

The branch sits ahead of the existing no-variant refusal, so a trivial continuation never reaches it. `_scope(frame)` opens the captured module so the bytecode's `LOAD_GLOBAL`s read the module's live dict, the same scope a compiled variant is bound over; the driver's module-scope comment now says a module is opened only for a frame the driver serves, and a dead record never imports its module. When the code object closes over locals (the `closure` shape), Dynamo binds the continuation as a factory taking the closure tuple and the frame ahead passes one, so the driver returns `_plain` itself in that case and a bound function otherwise -- mirroring the `factory` / `dispatch` split the compiled path already uses. The resume-name collision pre-check in `_build_multigraph_forward` now opens the module of every frame `_make_dispatcher` opens a scope for (`variants`, or `trivial` and not the entry), so a trivial continuation recorded under another module under `config.nested_graph_breaks` has its resume names checked too.

## What did not change

A bypassed continuation is unchanged: it still sends the capture to installing, and it still refuses at the call that reaches it, since its variants were dropped rather than never made and running it eager would silently give up compilation. The refusal branch that remains now covers a bypassed frame, and for a frame that is not bypassed it is reached only by the entry: every non-bypassed non-entry frame without variants is trivial and takes the branch above. A bypassed continuation still binds its resume names in a standalone artifact, so its refusal is deferred to a call; a no-variant entry raises directly instead of binding a refusal.

## Alternative considered

Keying `trivial` on `has_compile_id` (a frame Dynamo never started compiling) was rejected. It would miss the common `return loss` step (`no_ops` above), whose continuation Dynamo enters and then skips, so it has a compile id and no guarded code.

## Tests

`test_trivial_continuation_is_served_as_plain_python` is parametrized over the three shapes:

| shape | continuation after `.backward()` | path it pins |
|---|---|---|
| `no_tensor` | reaches no tensor; `convert_frame` skips it | plain function |
| `no_ops` | `return loss`; Dynamo enters it, traces no ops (`SkipFrame`) | plain function, compile id without guarded code |
| `closure` | `_closure_step` builds a lambda over `loss` | factory over the closure tuple; unreached lambda record |

For each shape the test captures the step and checks the `[False, True]` / `[1, 0]` records (and that every frame past the entry is trivial). It checks the `_serving_mode` verdict before and after modelling the continuation as bypassed (`trivial=False, bypassed=True`). It then rebuilds the driver from the records in this process -- `exec` of `_build_multigraph_forward`'s source over the pickled frames and backends, with the captured module aliased into `sys.modules` -- and serves the step on a fresh `Linear` loaded from the captured model's state dict, comparing its return value, `weight.grad` and `bias.grad` with an eager run of the step.

Test Plan:

`test_trivial_continuation_is_served_as_plain_python` captures a step whose continuation after `.backward()` reaches no tensor, one that returns the loss, and one whose continuation closes over a cell of the frame ahead (the factory path), checks the record and both `_serving_mode` verdicts, rebuilds the driver from the records and serves the step in this process, comparing the runtime model's grads with eager.

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

Authored with an AI assistant.

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

Pull Request resolved: #198214
Approved by: https://github.com/aorenste
ghstack dependencies: #198211, #198223, #198283, #198284, #197993, #198213, #198135, #198243
pytorchmergebot pushed a commit that referenced this pull request Sep 28, 2026
…ir (#198136)

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

```python
# 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:

```python
# 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:

```python
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:

```python
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:

```python
# 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:

```python
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]>

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

**Problem.** `_capture_config` only forced the backward to lower eagerly for `training=True`, but AOTAutograd does not save a grad-enabled graph to the bundled cache until its backward has been lowered, so an ordinary inference capture made outside `torch.no_grad()` compiled fine and then had nothing to put in the artifact.

**Fix.** Set `force_non_lazy_backward_lowering` unconditionally in the capture config and drop the `training` parameter it used to gate on.

**Summary.** `_capture_config(training)` added `force_non_lazy_backward_lowering` to its functorch patch only when `training=True`, leaving inference captures with AOTAutograd's default of lowering a graph's backward lazily on the first `.backward()`. The cache entry the bundled artifact is built from is saved only once the backward has been lowered, so a graph compiled with grad enabled whose backward was never lowered records no backend at all -- and that is the ordinary inference case, a capture made outside `torch.no_grad()` on a model whose parameters require grad. The flag is now set unconditionally, so a graph compiled with grad enabled carries its backward into the artifact, and a call served under that grad mode returns outputs with a `grad_fn` as eager does. A call made under `torch.no_grad()` still compiles an inference graph, because the flag only changes when a backward that AOTAutograd would build anyway gets lowered, not whether one exists. With nothing left for it to select, the `training` parameter goes, and the two `_capture_config` tests pin the unconditional flag and its scoping.

## 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): the capture config always lowers the backward eagerly, so a grad-enabled call records its artifact.

## The patch dict, before and after

The parent built the functorch patch and then appended the eager-lowering flag under a condition:

```python
# parent: torch/_dynamo/precompile_package.py
@contextlib.contextmanager
def _capture_config(training: bool) -> Iterator[None]:
    functorch_patch = {
        "bundled_autograd_cache": True,
        "bypass_autograd_cache_key": True,
    }
    if training:
        functorch_patch["force_non_lazy_backward_lowering"] = True
    ...
```

Now the flag is part of the dict itself and the parameter is gone:

```python
# now
@contextlib.contextmanager
def _capture_config() -> Iterator[None]:
    functorch_patch = {
        "bundled_autograd_cache": True,
        "force_non_lazy_backward_lowering": True,
        "bypass_autograd_cache_key": True,
    }
    ...
```

The rest of the scope is unchanged: `strict_autograd_cache` still follows `torch._dynamo.config.strict_precompile`, `allow_empty_graphs` is still patched on, and `force_disable_caches` still raises `PackageError` up front. The docstring now says why the backward lowers eagerly for every capture: a graph compiled with grad enabled whose backward was never lowered is never saved, so a capture that never makes one -- a training step, or an inference call made outside `torch.no_grad()` -- would record no backend at all.

## Why an inference capture was affected

AOTAutograd lowers a graph's backward lazily, on the first `.backward()`, and the bundled cache entry is saved only once that has happened. A capture that only runs forwards never triggers the lowering:

```python
model = torch.nn.Linear(4, 4)          # parameters require grad
with _capture_config(training=False):  # parent: no eager lowering
    compiled(model, x)                 # grad enabled -> joint graph, backward deferred
# parent: no .backward() ever ran, so the entry was never saved -> no backend in the artifact
# now:    the backward is lowered at compile time, the entry is saved, the artifact has a backend
```

Under `torch.no_grad()` there is no backward to lower, so that path compiles an inference graph exactly as before.

## Tests

Both `_capture_config` tests move to the parameterless call and pin the flag as unconditional. `test_capture_config_is_scoped_per_entry_and_per_thread` reads the four patched flags in order (`bundled_autograd_cache`, `bypass_autograd_cache_key`, `force_non_lazy_backward_lowering`, `allow_empty_graphs`) from an all-`False` ambient:

```python
# parent
with _capture_config(training=False):
    self.assertEqual(flags(), (True, True, False, True))
    with _capture_config(training=True):
        self.assertEqual(flags(), (True, True, True, True))
    self.assertEqual(flags(), (True, True, False, True))

# now
with _capture_config():
    self.assertEqual(flags(), (True, True, True, True))
    with _capture_config():
        self.assertEqual(flags(), (True, True, True, True))
    self.assertEqual(flags(), (True, True, True, True))
self.assertEqual(flags(), ambient)
```

The same test still checks that an exception inside the scope restores the ambient flags, and that a worker thread holding its own `_capture_config()` scope sees `(True, True, True, True)` while the main thread's flags are untouched. `test_capture_config_refuses_disabled_caches_and_honours_strict` keeps its `force_disable_caches` refusal and its `strict_precompile` -> `strict_autograd_cache` checks, now written as `with _capture_config():`.

Test Plan:

```
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: #198215
Approved by: https://github.com/aorenste
ghstack dependencies: #198211, #198223, #198283, #198284, #197993, #198213, #198135, #198243, #198214, #198136
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
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
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1447/head branch November 29, 2026 01:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants