Skip to content

[precompile] Serve a capture whose child frame graph-broke by installing it - #198523

Closed
bobrenjc93 wants to merge 10 commits into
gh/bobrenjc93/1484/basefrom
gh/bobrenjc93/1484/head
Closed

bobrenjc93 wants to merge 10 commits into
gh/bobrenjc93/1484/basefrom
gh/bobrenjc93/1484/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Problem. A capture whose graph break sits inside a function the entry calls (a child module's forward, say) was refused at write time, which rules out most real models with a graph break below the top-level function.

Fix. Such a capture is now written as an installed-mode artifact: loading it installs the captured Dynamo entries onto the live code objects and serves every call under fail_on_recompile.

Summary. A standalone artifact can serve only frames the entry reaches through a graph-break continuation, because its driver dispatches by binding the resume names the entry's bytecode loads. A graph break inside a called function compiles that function as its own frame, which the entry reaches by an ordinary call the dispatcher never sees, so _build_multigraph_artifact refused the capture ("cannot reach from the entry"). This PR renders those captures as SERVING_MODE = "installed", carrying the whole Dynamo package in one _PACKAGE blob, and their driver _build_installed_forward installs it with CompilePackage.install, exactly as a warm torch.compile package load does. Every call is served under fail_on_recompile, so the standalone contract holds: the artifact serves only what capture exercised, and an uncovered call raises instead of compiling. Everything used is already on main, so the change is Python-only, and unload, error wrapping, the process-global stance and same-process loading are left to the PRs above.

Background: how a standalone artifact serves

When a captured function graph-breaks, Dynamo splits it into frames: the entry compiled up to the break, and a resume function the entry's rewritten bytecode reaches by LOAD_GLOBAL. The standalone driver, _build_multigraph_forward, rebuilds each frame from its code object and guard trees and binds a dispatcher under each resume name, so the entry's bytecode loads the dispatcher, which picks the captured variant whose guards match. Nothing is installed into Dynamo, and no compiler runs at serve time.

That reaches only frames named by a resume name. The test fixture:

def breaking_helper(y):
    y = y.sin()
    torch._dynamo.graph_break()
    return y.cos()

def calls_breaking_helper(model, x):
    return breaking_helper(model(x)) + 1

The break is inside breaking_helper, not in the entry. Dynamo compiles breaking_helper (and its own continuation) as separate frames, and the entry reaches it with an ordinary Python call. The standalone dispatcher never sees that call, so served standalone, breaking_helper would silently run eager.

# parent: capture(calls_breaking_helper) -> PrecompileError "... cannot reach from the entry ..."
# now:    the artifact is written with SERVING_MODE = "installed" and serves compiled

Render side (torch/_precompile.py): a mode choice instead of a refusal

unreachable = _unreachable_frames(frames)   # compiled frames no continuation reaches, by fqn
mode = "installed" if unreachable else "standalone"
binding = _entry_binding(entry_fn) if mode == "standalone" else None

An installed artifact writes the following instead of _FRAMES, _BACKENDS and _ENTRY_BINDING:

SERVING_MODE = "installed"
# Frames entered by an ordinary call; served by installing.
UNREACHABLE_WITHOUT_INSTALL = ['mod.breaking_helper', 'mod.torch_dynamo_resume_in_breaking_helper_at_N']
_PACKAGE = '...'   # base64(pickle) of the Dynamo cache entry (guards, transformed
                   # bytecode) and the backend artifacts it calls by id -- OPAQUE
forward = _build_installed_forward()

_parse_artifact_metadata already reads SERVING_MODE, so the format needs no new concept, and load() now sets the handle's installed flag from it. A reachable frame with no variant still keeps the capture standalone: the driver runs a trivial one eager, as capture did, and refuses a bypassed one when a call reaches it.

Serve side (torch/_precompile_driver.py): hand serving back to Dynamo

package = CompilePackage(fn, dynamo)            # fn imported by module name + FN_NAME
compiled = torch._dynamo.optimize(BACKEND, package=package)(fn)
package.install(package_state["backends"])      # guarded entries onto the live code objects

def forward(*args, **kwargs):
    with torch.compiler.set_stance("fail_on_recompile"):
        return compiled(*args, **kwargs)

CompilePackage.install puts the captured entries onto the real code objects of calls_breaking_helper and breaking_helper, so the ordinary call into the helper hits an installed cache entry through Dynamo's own frame evaluator. Before installing, the driver refuses with a PrecompileError when the Python version differs from capture (the bytecode is marshalled), when the torch version differs (the guard state is pickled), when the function was defined in __main__, or when it is no longer importable.

Why fail_on_recompile, and the rejected alternative

Serving under fail_on_recompile keeps the standalone contract: the artifact serves only what capture exercised, and an uncovered call raises rather than compiling. The alternative, letting the installed artifact recompile at serve time (the old #195921 design), needs serve-time-compile accounting and isolation machinery this stack does not have.

Tests

Test Pins
test_multigraph_artifact_installs_a_frame_the_entry_cannot_reach the render: SERVING_MODE = "installed", an UNREACHABLE_WITHOUT_INSTALL list, forward = _build_installed_forward(), and no _FRAMES blob
test_a_frame_the_entry_cannot_reach_is_served_installed (both backends) captures calls_breaking_helper on two shapes, checks the unreachable list names the helper and its continuation, and serves it in a fresh process; since that process serves under fail_on_recompile, a correct result proves every frame, the helper's included, hit an installed entry instead of compiling, and an uncovered dtype must raise

Left to the PRs above

This PR is kept to the minimum that serves; each gap is its own draft on top.

Gap in this PR Addressed in
An uncovered call surfaces as fail_on_recompile's RuntimeError, not a PrecompileError, and a failed install is not wrapped #198556
set_stance(...) per call flips the process-global stance, so another thread's torch.compile raises while a call is being served #198557 (the refusal is bound into the artifact's own callback; compiled_autograd is refused at load)
Loading in a process that already compiled those frames leaves live entries that serve misses #198558 (refused at load)
unload()/__exit__ do not take the install back out (CompilePackage.uninstall resets only the entry's code object) not yet; the docs say to serve from a process you can throw away

Test Plan:

The new end-to-end test captures calls_breaking_helper (whose helper graph
breaks) on two shapes, checks the artifact renders as installed, and serves
it in a fresh process for both backends. Because the fresh process serves
under fail_on_recompile, a correct result also proves every frame, the
helper's included, hit an installed entry instead of compiling. The loader
then checks that an uncovered dtype raises.

python test/test_precompile.py -k cannot_reach -k emit_multigraph_driver -k served_installed -k round_trip_in_a_fresh -k single_graph_serves
python test/test_precompile.py

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

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

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ 1 Pending, 1 Unrelated Failure

As of commit fbabae5 with merge base a4849a9 (image):

🟡 GREEN LIGHT - PR requires human review:

  • Triviality
    • New serving mode: _build_multigraph_artifact now renders SERVING_MODE = "installed" where it used to raise "cannot reach from the entry"
    • New driver _build_installed_forward in torch/_precompile_driver.py unpickles _PACKAGE and calls CompilePackage.install onto live code objects
    • Fits no trivial class: this is a feature with new design, not one bugfix
  • User-facing behavior
    • capture() and load() docstrings now promise a different contract: a refused capture now loads and mutates global state
    • PrecompiledRunnable.installed can now be True; unload() is documented as a no-op that leaves entries installed
  • Known gaps deferred to the stack
    • The forward closure calls torch.compiler.set_stance("fail_on_recompile") on every call, which flips process-global state
    • The PR body defers error wrapping, the stance fix and same-process load refusal to #​198556 to #​198558, so a human should decide on landing order

reason: not_trivial
Reviewed commit: fbabae5

Inference job

🐛 Report a wrong verdict

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.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 2m 26s —— View job


The installed path works, but some state is now out of date: PrecompiledRunnable.installed stays False, and the capture() docs still say these captures are refused. The per-call stance flip is also process-global, so it races with other threads.

PR Review: #198523

Summary

Captures that have a frame the entry can't reach are now rendered as SERVING_MODE = "installed". They load by calling CompilePackage.install and every call runs under set_stance("fail_on_recompile"). The problems are stale contracts and docs, a second copy of the serving-mode decision, and a stance flip that isn't thread-safe.

Thread Safety

  • torch/_precompile_driver.py (_build_installed_forward.<forward>): torch.compiler.set_stance changes the process-global _stance. It runs on every call.
    • While one thread is inside forward, any other thread's torch.compile calls run under fail_on_recompile and raise on their first compile.
    • Two overlapping forward calls can also restore the stance out of order, which leaves the wrong stance behind.
    • Standalone artifacts touch no global state, so this is a new hazard. Either set the stance once at install time and document it as part of the global-state contract, or document that installed artifacts must not be called concurrently with other compiles.

API Design

  • torch/_precompile.py:436: PrecompiledRunnable.installed is documented as "Whether calling this handle installs onto the captured code objects". _runnable_from_pair still builds every Dynamo artifact through PrecompiledModule._from_loaded(forward, backend=backend), so installed is False for an installed artifact.
    • Installation also happens when the file is loaded (the exec of python_code runs package.install), not when the handle is called or entered.
    • Deferring unload() to a follow-up is reasonable. The flag that tells the caller global state was mutated should still be right in this PR: set it from meta["SERVING_MODE"].
  • torch/_precompile.py:3182-3187: the capture() docstring still says "A Dynamo artifact is STANDALONE ... installs nothing ... a frame the entry cannot reach ... is refused at write time". That now contradicts both the behavior and the updated load() docstring.
  • torch/_precompile_driver.py (_build_installed_forward): the "no guard set covers this call" error type depends on the mode.
    • Standalone raises PrecompileError("no captured variant ..."). Installed raises a bare RuntimeError from fail_on_recompile.
    • Source drift is also newly exposed. CompilePackage(fn, dynamo) checksums inlined_sources against the live module and raises a plain RuntimeError("Source code changes detected ...") at load. That escapes the PrecompileError contract, and a standalone artifact is immune to it.
    • The PR description already defers the first point. The second one is new. At minimum, wrap CompilePackage(...) and install in the same _PrecompileError translation used for the import failure just above.

Code Quality

  • torch/_precompile.py:2123-2136: _serving_mode(frames) already decides between "standalone" and "installed", and nothing calls it.
    • Its rule is also different: it picks installed when a reachable frame has no variant, and it treats trivial continuations as covered.
    • _build_multigraph_artifact now re-derives the mode inline from unreachable, so there are two sources of truth that disagree.
    • Either call _serving_mode and pass the mode down, or delete it and state the rule once.
  • torch/_precompile.py:2217-2220: _build_multigraph_python_source now takes unreachable: list[str] and uses its truthiness as the mode switch. The standalone half ends in an early return. Passing an explicit mode (see above) and keeping the list only for the readable UNREACHABLE_WITHOUT_INSTALL literal would make the branch obvious.
  • Installed artifacts still emit and require _ENTRY_BINDING, and _emit_multigraph_driver_source still computes it (it raises if it can't pickle it). _build_installed_forward never reads it; CompilePackage uses the live fn's defaults. Drop it from the installed branch and from the wanted set for SERVING_MODE == "installed".

Testing

  • test/test_precompile.py:4661 (_GOLDEN_LOADER): except (torch.compiler.PrecompileError, RuntimeError) is redundant, because PrecompileError subclasses RuntimeError.
    • Because the loader is shared, every standalone round-trip test now also accepts a fail_on_recompile message. A standalone regression that starts compiling at serve time would pass.
    • Have the loader take the expected mode, or assert on SERVING_MODE before choosing which message is acceptable.
  • test_a_frame_the_entry_cannot_reach_is_served_installed only asserts "breaking_helper" is somewhere in python_code. Assert the actual UNREACHABLE_WITHOUT_INSTALL value (e.g. ['<mod>.breaking_helper']) so a wrong reachability classification is caught.
  • No test covers loading an installed artifact in the capturing process. load() still says graph-broken artifacts can't load beside the live compile; installing onto code objects that already have live cache entries is a different failure mode. Either test it or refuse it explicitly.

Recommendation

Request Changes: the installed flag and the capture() docstring are wrong after this change. The stance handling needs a thread-safety decision or explicit documentation.

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 24, 2026
…ing it

A graph break inside a function the entry calls (a child module's forward,
say) makes Dynamo compile that function as a frame of its own. The entry
reaches it by an ordinary call, not by LOAD_GLOBAL of a resume name, so the
standalone dispatcher in `_build_multigraph_forward` can never intercept it.
`_build_multigraph_artifact` therefore refused every such capture ("cannot
reach from the entry"), which rules out most real models with a graph break
below the top-level function.

This renders those captures as `SERVING_MODE = "installed"` instead, which
`_parse_artifact_metadata` already reads. The artifact carries the Dynamo cache
entry and backend artifacts as one `_PACKAGE` blob, plus the readable
`UNREACHABLE_WITHOUT_INSTALL` list. Its driver, `_build_installed_forward`,
imports the captured function and rebuilds `CompilePackage(fn, dynamo)`. It
then calls `CompilePackage.install`, which puts the guarded entries onto the
live code objects exactly as a warm torch.compile package load does, and
serves every call under `set_stance("fail_on_recompile")`.

Serving under `fail_on_recompile` keeps the standalone contract: the artifact
serves only what capture exercised, and an uncovered call raises rather than
compiling. The alternative, letting the installed artifact recompile at serve
time (the old #195921 design), needs serve-time-compile accounting and
isolation machinery this stack does not have. Everything used here is already
on main, so the change is Python-only.

Deliberately left for follow-ups: `unload()`/`__exit__` do not yet take the
install back out (`CompilePackage.uninstall` resets only the entry's code
object), and an uncovered call surfaces as fail_on_recompile's RuntimeError
rather than a PrecompileError.

Test Plan:

The new end-to-end test captures `calls_breaking_helper` (whose helper graph
breaks) on two shapes, checks the artifact renders as installed, and serves
it in a fresh process for both backends. Because the fresh process serves
under fail_on_recompile, a correct result also proves every frame, the
helper's included, hit an installed entry instead of compiling. The loader
then checks that an uncovered dtype raises.

```
python test/test_precompile.py -k cannot_reach -k emit_multigraph_driver -k served_installed -k round_trip_in_a_fresh -k single_graph_serves
python test/test_precompile.py
```

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ghstack-source-id: 2df4555
Pull-Request: #198523
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude review this PR. Earlier bot reviews and my replies are in this thread; please verify the fixes and dispositions.

@claude

claude Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

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


None of the earlier review's findings have been addressed in the current head (5c84588), and there are no author replies in this thread to check dispositions against.

PR Review: #198523

Summary

The PR serves a capture that has a frame the entry can't reach by emitting SERVING_MODE = "installed". Loading that artifact runs CompilePackage.install, and every call then runs under fail_on_recompile.

Status of earlier findings: the thread contains no replies from the author, only the @claude trigger, so there were no dispositions to check. The [UPDATE] commit (643ef7e..5c84588) only touches base-stack content: the module docstring, the save() docs, the pathlike test and the checkpoint-test ordering. None of the files and lines named in the earlier review changed. I re-checked every earlier finding against HEAD and all of them still apply. They are restated below with current line numbers.

Thread Safety

  • torch/_precompile_driver.py:788-790 (_build_installed_forward.<forward>): still open. Each call runs torch.compiler.set_stance("fail_on_recompile"), which changes the process-global stance.
    • While one thread is inside an installed forward, any unrelated torch.compile in another thread raises on its first compile.
    • Overlapping calls can restore the stance out of order.
    • Standalone artifacts touch no global state. Either decide the stance contract at install time and document it, or document that an installed artifact must not run concurrently with other compiles.

API Design

  • torch/_precompile.py:436-440 and :3126: still open. PrecompiledRunnable.installed stays False for an installed artifact, because _runnable_from_pair still returns PrecompiledModule._from_loaded(forward, backend=backend) for every Dynamo artifact.
    • The docstring also says "Whether calling this handle installs". In fact the install happens when the loader execs python_code, before the handle exists.
    • Set installed from meta["SERVING_MODE"] and fix the wording, even though unload() is deferred.
  • torch/_precompile.py:3186-3190: still open. The capture() docstring still says "A Dynamo artifact is STANDALONE ... installs nothing ... a frame the entry cannot reach ... is refused at write time". That contradicts both the new behavior and the updated load() docstring at :3298-3302.
  • torch/_precompile_driver.py:783-785: still open.
    • CompilePackage(fn, dynamo) checksums inlined_sources against the live module (torch/_dynamo/package.py:1106). If the source has drifted, it raises a bare RuntimeError("Source code changes detected ...") at load, outside the PrecompileError contract.
    • A standalone artifact isn't exposed to this at all.
    • Wrap CompilePackage(...) and package.install(...) in the same _PrecompileError translation used for the import failure just above.
    • The uncovered-call RuntimeError is explicitly deferred in the PR description; this is a separate gap.

Code Quality

  • torch/_precompile.py:2125-2138: still open. _serving_mode(frames) still exists and nothing calls it.
    • Its rule differs from the new inline rule at :2239 ("installed" if unreachable).
    • It also chooses installed for a reachable frame that has no variant, and it treats trivial continuations as covered.
    • That leaves two disagreeing sources of truth for the mode. Call _serving_mode and pass the mode down, or delete it.
  • torch/_precompile.py:2239 and :2296-2315: still open.
    • The unreachable list's truthiness is the mode switch, and the installed branch ends in an early return partway through the function.
    • Pass an explicit mode and keep unreachable only for the readable UNREACHABLE_WITHOUT_INSTALL literal.
  • torch/_precompile.py:2294 and :1809: still open. Installed artifacts still emit _ENTRY_BINDING, and the loader still requires it (it isn't removed from wanted when the mode is installed), but _build_installed_forward never reads it.
    • _entry_binding(entry_fn) can also raise when the binding isn't picklable, so an installed capture can be refused for data it never uses.
    • Drop it from the installed branch and from the installed wanted set.

Testing

  • test/test_precompile.py:4660-4662 (_GOLDEN_LOADER): still open.
    • except (PrecompileError, RuntimeError) is redundant, because PrecompileError subclasses RuntimeError.
    • Worse, this loader is shared, so every standalone round-trip test now also accepts a fail_on_recompile message. A regression where a standalone artifact starts going through Dynamo at serve time would still pass.
    • Pick the accepted message from the artifact's SERVING_MODE.
  • test/test_precompile.py:4776: still open. assertIn("breaking_helper", python_code) matches anywhere in the file, including the embedded source. Assert the exact UNREACHABLE_WITHOUT_INSTALL = [...] line so a misclassified reachability set is caught.
  • Still open: no test loads an installed artifact in the capturing process. There, package.install puts entries onto code objects that already carry live cache entries from the capture. Either test that case or refuse it explicitly.

Recommendation

Request Changes: all of the earlier findings are still unaddressed. The main blockers are the wrong installed flag, the stale capture() docstring, and the thread-safety decision on the global stance.

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 24, 2026
…ing it

A graph break inside a function the entry calls (a child module's forward,
say) makes Dynamo compile that function as a frame of its own. The entry
reaches it by an ordinary call, not by LOAD_GLOBAL of a resume name, so the
standalone dispatcher in `_build_multigraph_forward` can never intercept it.
`_build_multigraph_artifact` therefore refused every such capture ("cannot
reach from the entry"), which rules out most real models with a graph break
below the top-level function.

This renders those captures as `SERVING_MODE = "installed"` instead, which
`_parse_artifact_metadata` already reads. The artifact carries the Dynamo cache
entry and backend artifacts as one `_PACKAGE` blob, plus the readable
`UNREACHABLE_WITHOUT_INSTALL` list. Its driver, `_build_installed_forward`,
imports the captured function and rebuilds `CompilePackage(fn, dynamo)`. It
then calls `CompilePackage.install`, which puts the guarded entries onto the
live code objects exactly as a warm torch.compile package load does, and
serves every call under `set_stance("fail_on_recompile")`.

Serving under `fail_on_recompile` keeps the standalone contract: the artifact
serves only what capture exercised, and an uncovered call raises rather than
compiling. The alternative, letting the installed artifact recompile at serve
time (the old #195921 design), needs serve-time-compile accounting and
isolation machinery this stack does not have. Everything used here is already
on main, so the change is Python-only.

Deliberately left for follow-ups: `unload()`/`__exit__` do not yet take the
install back out (`CompilePackage.uninstall` resets only the entry's code
object), and an uncovered call surfaces as fail_on_recompile's RuntimeError
rather than a PrecompileError.

Test Plan:

The new end-to-end test captures `calls_breaking_helper` (whose helper graph
breaks) on two shapes, checks the artifact renders as installed, and serves
it in a fresh process for both backends. Because the fresh process serves
under fail_on_recompile, a correct result also proves every frame, the
helper's included, hit an installed entry instead of compiling. The loader
then checks that an uncovered dtype raises.

```
python test/test_precompile.py -k cannot_reach -k emit_multigraph_driver -k served_installed -k round_trip_in_a_fresh -k single_graph_serves
python test/test_precompile.py
```

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ghstack-source-id: 2ffb419
Pull-Request: #198523
@bobrenjc93 bobrenjc93 changed the title [precompile] Serve a capture whose child frame graph-broke by installing it [no-ci] [precompile] Serve a capture whose child frame graph-broke by installing it Sep 24, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude review this PR. Earlier bot reviews and my replies are in this thread; please verify the fixes and dispositions.

@claude

claude Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 46s —— View job


All of the earlier findings are still open at the current head (32cacb4). There are no author replies in this thread, so there were no dispositions to check.

PR Review: #198523

Summary

The PR serves a capture that has a frame the entry can't reach by emitting SERVING_MODE = "installed". Loading that artifact runs CompilePackage.install, and every call then runs under fail_on_recompile.

What changed since the last review: the thread still has only @claude triggers from the author and no replies to earlier findings. The new [UPDATE] (5c84588..32cacb4) makes two changes:

  • It rewraps the first paragraph of the capture() docstring. The stale "STANDALONE ... refused at write time" paragraph is left as it was.
  • It changes test/dynamo/test_package.py::test_code_source_walk_skips_non_code_constants. That is base-stack content, not part of this PR's diff.

None of the code or tests named in the earlier reviews changed. I re-checked every finding against HEAD.

# Earlier finding Status Current location
1 The per-call set_stance("fail_on_recompile") changes the process-global stance, which isn't thread-safe Open torch/_precompile_driver.py:787-789
2 PrecompiledRunnable.installed stays False for installed artifacts, and its docstring says install happens "when calling this handle" Open torch/_precompile.py:436-440, :3126
3 The capture() docstring says Dynamo artifacts are STANDALONE and unreachable frames are refused Open (the new commit only rewrapped the paragraph above it) torch/_precompile.py:3185-3189
4 CompilePackage(fn, dynamo) source-drift RuntimeError and install failures escape the PrecompileError contract Open torch/_precompile_driver.py:783-785
5 _serving_mode(frames) isn't called and uses a different rule from the inline "installed" if unreachable Open torch/_precompile.py:2125-2138 vs :2239
6 The truthiness of unreachable doubles as the mode switch, with an early return mid-function Open torch/_precompile.py:2239, :2296-2315
7 _ENTRY_BINDING is still emitted and required for installed artifacts, but it's unused, and _entry_binding() can refuse a capture over it Open torch/_precompile.py:2294, :1813-1815
8 _GOLDEN_LOADER catches (PrecompileError, RuntimeError), which is redundant, and it lets standalone tests accept a fail_on_recompile message Open test/test_precompile.py:4660-4662
9 assertIn("breaking_helper", python_code) matches the embedded source; assert the exact UNREACHABLE_WITHOUT_INSTALL = [...] line Open test/test_precompile.py:4776
10 No test (and no explicit refusal) covers loading an installed artifact in the capturing process, where live cache entries already exist Open —

The full reasoning for each item is in the first review above and still applies as written.

Recommendation

Request Changes: nothing from the earlier reviews has been addressed. The blockers are still:

If you've decided to defer or reject any of these, reply in the thread and I'll check against that on the next pass.

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 24, 2026
…ing it

A graph break inside a function the entry calls (a child module's forward,
say) makes Dynamo compile that function as a frame of its own. The entry
reaches it by an ordinary call, not by LOAD_GLOBAL of a resume name, so the
standalone dispatcher in `_build_multigraph_forward` can never intercept it.
`_build_multigraph_artifact` therefore refused every such capture ("cannot
reach from the entry"), which rules out most real models with a graph break
below the top-level function.

This renders those captures as `SERVING_MODE = "installed"` instead, which
`_parse_artifact_metadata` already reads. The artifact carries the Dynamo cache
entry and backend artifacts as one `_PACKAGE` blob, plus the readable
`UNREACHABLE_WITHOUT_INSTALL` list. Its driver, `_build_installed_forward`,
imports the captured function and rebuilds `CompilePackage(fn, dynamo)`. It
then calls `CompilePackage.install`, which puts the guarded entries onto the
live code objects exactly as a warm torch.compile package load does, and
serves every call under `set_stance("fail_on_recompile")`.

Serving under `fail_on_recompile` keeps the standalone contract: the artifact
serves only what capture exercised, and an uncovered call raises rather than
compiling. The alternative, letting the installed artifact recompile at serve
time (the old #195921 design), needs serve-time-compile accounting and
isolation machinery this stack does not have. Everything used here is already
on main, so the change is Python-only.

Deliberately left for follow-ups: `unload()`/`__exit__` do not yet take the
install back out (`CompilePackage.uninstall` resets only the entry's code
object), and an uncovered call surfaces as fail_on_recompile's RuntimeError
rather than a PrecompileError.

Test Plan:

The new end-to-end test captures `calls_breaking_helper` (whose helper graph
breaks) on two shapes, checks the artifact renders as installed, and serves
it in a fresh process for both backends. Because the fresh process serves
under fail_on_recompile, a correct result also proves every frame, the
helper's included, hit an installed entry instead of compiling. The loader
then checks that an uncovered dtype raises.

```
python test/test_precompile.py -k cannot_reach -k emit_multigraph_driver -k served_installed -k round_trip_in_a_fresh -k single_graph_serves
python test/test_precompile.py
```

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ghstack-source-id: 9c00b6b
Pull-Request: #198523
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude review this PR. Earlier bot reviews and my replies are in this thread; please verify the fixes and dispositions.

@claude

claude Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 47s —— View job


All 10 earlier findings are still open at the current head (70dd157). The thread has no replies from you yet, so there were no fixes or dispositions to check.

PR Review: #198523

Summary

The PR serves a capture that has a frame the entry can't reach by emitting SERVING_MODE = "installed". Loading that artifact runs CompilePackage.install, and every call then runs under fail_on_recompile.

What changed since the last review (32cacb4 → 70dd157): the new [UPDATE] only brings in base-stack changes. git diff 32cacb4 70dd157 matches the base update dc8814b..9035669: the precompile programming-model note wording and the PrecompiledModule._compile tracer error message. None of this PR's own lines changed. The thread still has only @claude triggers from you and no replies to the findings.

I re-checked each finding against HEAD:

# Earlier finding Status Current location
1 Each call runs set_stance("fail_on_recompile"), which changes the process-global stance. That isn't thread-safe: other threads' compiles fail, and overlapping calls can restore the stance out of order Open torch/_precompile_driver.py:786-788
2 PrecompiledRunnable.installed stays False for installed artifacts, and its docstring says install happens "when calling this handle" (it actually happens at load) Open torch/_precompile.py:438, :3128
3 The capture() docstring still says Dynamo artifacts are STANDALONE and that unreachable frames are "refused at write time" Open torch/_precompile.py:3191
4 Errors from CompilePackage(fn, dynamo) (a source-drift RuntimeError) and from package.install(...) escape the PrecompileError contract Open torch/_precompile_driver.py:782-784
5 Nothing calls _serving_mode(frames), and its rule differs from the inline "installed" if unreachable Open torch/_precompile.py:2127 vs :2241
6 The truthiness of unreachable doubles as the mode switch, and the installed branch returns early partway through the function Open torch/_precompile.py:2241, :2296-2317
7 Installed artifacts still emit and require _ENTRY_BINDING, which is never used, and _entry_binding() can refuse a capture over it Open torch/_precompile.py:2296, :1811
8 The shared _GOLDEN_LOADER catches (PrecompileError, RuntimeError), which is redundant, so every standalone round-trip test now also accepts a fail_on_recompile failure Open test/test_precompile.py:4660
9 assertIn("breaking_helper", python_code) also matches the embedded source. Assert the exact UNREACHABLE_WITHOUT_INSTALL = [...] line instead Open test/test_precompile.py:4776
10 No test covers loading an installed artifact in the capturing process, where live cache entries already exist, and nothing refuses that case explicitly Open —

The first review in this thread has the full reasoning for each item, and it still applies as written.

Recommendation

Request Changes: nothing from the earlier reviews has been addressed. The blockers are still #1 (the global-stance thread-safety decision), #2 (the wrong installed flag), #3 (the stale capture() docstring) and #8 (the shared test loader that weakens the standalone tests).

If you plan to defer or reject any of these, reply in the thread with which ones and why, and I'll check against that next time. Pushing a new [UPDATE] alone won't change the result unless it touches these lines.

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

/easycla

bobrenjc93 added a commit that referenced this pull request Oct 10, 2026
…ing it

A graph break inside a function the entry calls (a child module's forward,
say) makes Dynamo compile that function as a frame of its own. The entry
reaches it by an ordinary call, not by LOAD_GLOBAL of a resume name, so the
standalone dispatcher in `_build_multigraph_forward` can never intercept it.
`_build_multigraph_artifact` therefore refused every such capture ("cannot
reach from the entry"), which rules out most real models with a graph break
below the top-level function.

This renders those captures as `SERVING_MODE = "installed"` instead, which
`_parse_artifact_metadata` already reads. The artifact carries the Dynamo cache
entry and backend artifacts as one `_PACKAGE` blob, plus the readable
`UNREACHABLE_WITHOUT_INSTALL` list. Its driver, `_build_installed_forward`,
imports the captured function and rebuilds `CompilePackage(fn, dynamo)`. It
then calls `CompilePackage.install`, which puts the guarded entries onto the
live code objects exactly as a warm torch.compile package load does, and
serves every call under `set_stance("fail_on_recompile")`.

Serving under `fail_on_recompile` keeps the standalone contract: the artifact
serves only what capture exercised, and an uncovered call raises rather than
compiling. The alternative, letting the installed artifact recompile at serve
time (the old #195921 design), needs serve-time-compile accounting and
isolation machinery this stack does not have. Everything used here is already
on main, so the change is Python-only.

Deliberately left for follow-ups: `unload()`/`__exit__` do not yet take the
install back out (`CompilePackage.uninstall` resets only the entry's code
object), and an uncovered call surfaces as fail_on_recompile's RuntimeError
rather than a PrecompileError.

Test Plan:

The new end-to-end test captures `calls_breaking_helper` (whose helper graph
breaks) on two shapes, checks the artifact renders as installed, and serves
it in a fresh process for both backends. Because the fresh process serves
under fail_on_recompile, a correct result also proves every frame, the
helper's included, hit an installed entry instead of compiling. The loader
then checks that an uncovered dtype raises.

```
python test/test_precompile.py -k cannot_reach -k emit_multigraph_driver -k served_installed -k round_trip_in_a_fresh -k single_graph_serves
python test/test_precompile.py
```

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ghstack-source-id: d01d837
Pull-Request: #198523
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 1m 16s —— View job


The new [UPDATE] at 80d150d is only a rebase, and this PR's own code is unchanged since the last review (53be9ca). I found no new issues.

PR Review: #198523

Summary

The PR serves a capture with a frame the entry can't reach by rendering it as SERVING_MODE = "installed". Loading that artifact runs CompilePackage.install, and every call then runs under fail_on_recompile.

How I checked that only the base moved:

  • The PR's own patch has the same per-file stats before and after the update (9d54eeba..53be9ca1 and 2540738c..80d150d6): 4 files, +241/−113.
  • In the four PR files, the only change between the two heads (53be9ca1..80d150d6) is the same 3-line addition the base update brought in (9d54eeba..2540738c). That addition puts LIST_REVERSEITERATOR_LEN, CURRENT_STREAM_MATCH and FX_ANNOTATION into the guard-type sets in torch/_dynamo/precompile_package.py. It belongs to the base stack, not to this PR.

These earlier items are still deferred to the stacked PRs, and I haven't checked them because this job can't see those branches:

Recommendation

Approve, provided #198556–#198558 land in the same stack.

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 39s —— View job


The new [UPDATE] at c7d8a64 is a rebase onto the new base (6192385) with one comment merged in, and I found no new issues. This PR's own code is unchanged since the last review (80d150d).

PR Review: #198523

Summary

Captures with a frame the entry can't reach are now rendered as SERVING_MODE = "installed". Loading the artifact runs CompilePackage.install, and every call then runs under fail_on_recompile.

I compared the PR's patch before the update (2540738c..80d150d6) with the patch after it (61923858..c7d8a645).

  • Apart from shifted hunk offsets, the only difference is in torch/_precompile_driver.py:557-561.
  • There, the base update added a sentence ("An unnamed trivial record lands here too and binds nothing...") to the if not frame["variants"] comment. This PR's rewording of that comment now keeps the sentence. The merged comment reads correctly against the code beside it.
  • All other changes in git diff 80d150d c7d8a64 came from the base update (2540738c..61923858), not from this PR.

The earlier items are still deferred to the stacked PRs. This job can't see those branches, so I haven't checked them:

Recommendation

Approve, provided #198556 to #198558 land in the same stack.

bobrenjc93 added a commit that referenced this pull request Oct 10, 2026
…ing it

A graph break inside a function the entry calls (a child module's forward,
say) makes Dynamo compile that function as a frame of its own. The entry
reaches it by an ordinary call, not by LOAD_GLOBAL of a resume name, so the
standalone dispatcher in `_build_multigraph_forward` can never intercept it.
`_build_multigraph_artifact` therefore refused every such capture ("cannot
reach from the entry"), which rules out most real models with a graph break
below the top-level function.

This renders those captures as `SERVING_MODE = "installed"` instead, which
`_parse_artifact_metadata` already reads. The artifact carries the Dynamo cache
entry and backend artifacts as one `_PACKAGE` blob, plus the readable
`UNREACHABLE_WITHOUT_INSTALL` list. Its driver, `_build_installed_forward`,
imports the captured function and rebuilds `CompilePackage(fn, dynamo)`. It
then calls `CompilePackage.install`, which puts the guarded entries onto the
live code objects exactly as a warm torch.compile package load does, and
serves every call under `set_stance("fail_on_recompile")`.

Serving under `fail_on_recompile` keeps the standalone contract: the artifact
serves only what capture exercised, and an uncovered call raises rather than
compiling. The alternative, letting the installed artifact recompile at serve
time (the old #195921 design), needs serve-time-compile accounting and
isolation machinery this stack does not have. Everything used here is already
on main, so the change is Python-only.

Deliberately left for follow-ups: `unload()`/`__exit__` do not yet take the
install back out (`CompilePackage.uninstall` resets only the entry's code
object), and an uncovered call surfaces as fail_on_recompile's RuntimeError
rather than a PrecompileError.

Test Plan:

The new end-to-end test captures `calls_breaking_helper` (whose helper graph
breaks) on two shapes, checks the artifact renders as installed, and serves
it in a fresh process for both backends. Because the fresh process serves
under fail_on_recompile, a correct result also proves every frame, the
helper's included, hit an installed entry instead of compiling. The loader
then checks that an uncovered dtype raises.

```
python test/test_precompile.py -k cannot_reach -k emit_multigraph_driver -k served_installed -k round_trip_in_a_fresh -k single_graph_serves
python test/test_precompile.py
```

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

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

A graph break inside a function the entry calls (a child module's forward,
say) makes Dynamo compile that function as a frame of its own. The entry
reaches it by an ordinary call, not by LOAD_GLOBAL of a resume name, so the
standalone dispatcher in `_build_multigraph_forward` can never intercept it.
`_build_multigraph_artifact` therefore refused every such capture ("cannot
reach from the entry"), which rules out most real models with a graph break
below the top-level function.

This renders those captures as `SERVING_MODE = "installed"` instead, which
`_parse_artifact_metadata` already reads. The artifact carries the Dynamo cache
entry and backend artifacts as one `_PACKAGE` blob, plus the readable
`UNREACHABLE_WITHOUT_INSTALL` list. Its driver, `_build_installed_forward`,
imports the captured function and rebuilds `CompilePackage(fn, dynamo)`. It
then calls `CompilePackage.install`, which puts the guarded entries onto the
live code objects exactly as a warm torch.compile package load does, and
serves every call under `set_stance("fail_on_recompile")`.

Serving under `fail_on_recompile` keeps the standalone contract: the artifact
serves only what capture exercised, and an uncovered call raises rather than
compiling. The alternative, letting the installed artifact recompile at serve
time (the old #195921 design), needs serve-time-compile accounting and
isolation machinery this stack does not have. Everything used here is already
on main, so the change is Python-only.

Deliberately left for follow-ups: `unload()`/`__exit__` do not yet take the
install back out (`CompilePackage.uninstall` resets only the entry's code
object), and an uncovered call surfaces as fail_on_recompile's RuntimeError
rather than a PrecompileError.

Test Plan:

The new end-to-end test captures `calls_breaking_helper` (whose helper graph
breaks) on two shapes, checks the artifact renders as installed, and serves
it in a fresh process for both backends. Because the fresh process serves
under fail_on_recompile, a correct result also proves every frame, the
helper's included, hit an installed entry instead of compiling. The loader
then checks that an uncovered dtype raises.

```
python test/test_precompile.py -k cannot_reach -k emit_multigraph_driver -k served_installed -k round_trip_in_a_fresh -k single_graph_serves
python test/test_precompile.py
```

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

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

A graph break inside a function the entry calls (a child module's forward,
say) makes Dynamo compile that function as a frame of its own. The entry
reaches it by an ordinary call, not by LOAD_GLOBAL of a resume name, so the
standalone dispatcher in `_build_multigraph_forward` can never intercept it.
`_build_multigraph_artifact` therefore refused every such capture ("cannot
reach from the entry"), which rules out most real models with a graph break
below the top-level function.

This renders those captures as `SERVING_MODE = "installed"` instead, which
`_parse_artifact_metadata` already reads. The artifact carries the Dynamo cache
entry and backend artifacts as one `_PACKAGE` blob, plus the readable
`UNREACHABLE_WITHOUT_INSTALL` list. Its driver, `_build_installed_forward`,
imports the captured function and rebuilds `CompilePackage(fn, dynamo)`. It
then calls `CompilePackage.install`, which puts the guarded entries onto the
live code objects exactly as a warm torch.compile package load does, and
serves every call under `set_stance("fail_on_recompile")`.

Serving under `fail_on_recompile` keeps the standalone contract: the artifact
serves only what capture exercised, and an uncovered call raises rather than
compiling. The alternative, letting the installed artifact recompile at serve
time (the old #195921 design), needs serve-time-compile accounting and
isolation machinery this stack does not have. Everything used here is already
on main, so the change is Python-only.

Deliberately left for follow-ups: `unload()`/`__exit__` do not yet take the
install back out (`CompilePackage.uninstall` resets only the entry's code
object), and an uncovered call surfaces as fail_on_recompile's RuntimeError
rather than a PrecompileError.

Test Plan:

The new end-to-end test captures `calls_breaking_helper` (whose helper graph
breaks) on two shapes, checks the artifact renders as installed, and serves
it in a fresh process for both backends. Because the fresh process serves
under fail_on_recompile, a correct result also proves every frame, the
helper's included, hit an installed entry instead of compiling. The loader
then checks that an uncovered dtype raises.

```
python test/test_precompile.py -k cannot_reach -k emit_multigraph_driver -k served_installed -k round_trip_in_a_fresh -k single_graph_serves
python test/test_precompile.py
```

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

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

A graph break inside a function the entry calls (a child module's forward,
say) makes Dynamo compile that function as a frame of its own. The entry
reaches it by an ordinary call, not by LOAD_GLOBAL of a resume name, so the
standalone dispatcher in `_build_multigraph_forward` can never intercept it.
`_build_multigraph_artifact` therefore refused every such capture ("cannot
reach from the entry"), which rules out most real models with a graph break
below the top-level function.

This renders those captures as `SERVING_MODE = "installed"` instead, which
`_parse_artifact_metadata` already reads. The artifact carries the Dynamo cache
entry and backend artifacts as one `_PACKAGE` blob, plus the readable
`UNREACHABLE_WITHOUT_INSTALL` list. Its driver, `_build_installed_forward`,
imports the captured function and rebuilds `CompilePackage(fn, dynamo)`. It
then calls `CompilePackage.install`, which puts the guarded entries onto the
live code objects exactly as a warm torch.compile package load does, and
serves every call under `set_stance("fail_on_recompile")`.

Serving under `fail_on_recompile` keeps the standalone contract: the artifact
serves only what capture exercised, and an uncovered call raises rather than
compiling. The alternative, letting the installed artifact recompile at serve
time (the old #195921 design), needs serve-time-compile accounting and
isolation machinery this stack does not have. Everything used here is already
on main, so the change is Python-only.

Deliberately left for follow-ups: `unload()`/`__exit__` do not yet take the
install back out (`CompilePackage.uninstall` resets only the entry's code
object), and an uncovered call surfaces as fail_on_recompile's RuntimeError
rather than a PrecompileError.

Test Plan:

The new end-to-end test captures `calls_breaking_helper` (whose helper graph
breaks) on two shapes, checks the artifact renders as installed, and serves
it in a fresh process for both backends. Because the fresh process serves
under fail_on_recompile, a correct result also proves every frame, the
helper's included, hit an installed entry instead of compiling. The loader
then checks that an uncovered dtype raises.

```
python test/test_precompile.py -k cannot_reach -k emit_multigraph_driver -k served_installed -k round_trip_in_a_fresh -k single_graph_serves
python test/test_precompile.py
```

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

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

A graph break inside a function the entry calls (a child module's forward,
say) makes Dynamo compile that function as a frame of its own. The entry
reaches it by an ordinary call, not by LOAD_GLOBAL of a resume name, so the
standalone dispatcher in `_build_multigraph_forward` can never intercept it.
`_build_multigraph_artifact` therefore refused every such capture ("cannot
reach from the entry"), which rules out most real models with a graph break
below the top-level function.

This renders those captures as `SERVING_MODE = "installed"` instead, which
`_parse_artifact_metadata` already reads. The artifact carries the Dynamo cache
entry and backend artifacts as one `_PACKAGE` blob, plus the readable
`UNREACHABLE_WITHOUT_INSTALL` list. Its driver, `_build_installed_forward`,
imports the captured function and rebuilds `CompilePackage(fn, dynamo)`. It
then calls `CompilePackage.install`, which puts the guarded entries onto the
live code objects exactly as a warm torch.compile package load does, and
serves every call under `set_stance("fail_on_recompile")`.

Serving under `fail_on_recompile` keeps the standalone contract: the artifact
serves only what capture exercised, and an uncovered call raises rather than
compiling. The alternative, letting the installed artifact recompile at serve
time (the old #195921 design), needs serve-time-compile accounting and
isolation machinery this stack does not have. Everything used here is already
on main, so the change is Python-only.

Deliberately left for follow-ups: `unload()`/`__exit__` do not yet take the
install back out (`CompilePackage.uninstall` resets only the entry's code
object), and an uncovered call surfaces as fail_on_recompile's RuntimeError
rather than a PrecompileError.

Test Plan:

The new end-to-end test captures `calls_breaking_helper` (whose helper graph
breaks) on two shapes, checks the artifact renders as installed, and serves
it in a fresh process for both backends. Because the fresh process serves
under fail_on_recompile, a correct result also proves every frame, the
helper's included, hit an installed entry instead of compiling. The loader
then checks that an uncovered dtype raises.

```
python test/test_precompile.py -k cannot_reach -k emit_multigraph_driver -k served_installed -k round_trip_in_a_fresh -k single_graph_serves
python test/test_precompile.py
```

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

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

A graph break inside a function the entry calls (a child module's forward,
say) makes Dynamo compile that function as a frame of its own. The entry
reaches it by an ordinary call, not by LOAD_GLOBAL of a resume name, so the
standalone dispatcher in `_build_multigraph_forward` can never intercept it.
`_build_multigraph_artifact` therefore refused every such capture ("cannot
reach from the entry"), which rules out most real models with a graph break
below the top-level function.

This renders those captures as `SERVING_MODE = "installed"` instead, which
`_parse_artifact_metadata` already reads. The artifact carries the Dynamo cache
entry and backend artifacts as one `_PACKAGE` blob, plus the readable
`UNREACHABLE_WITHOUT_INSTALL` list. Its driver, `_build_installed_forward`,
imports the captured function and rebuilds `CompilePackage(fn, dynamo)`. It
then calls `CompilePackage.install`, which puts the guarded entries onto the
live code objects exactly as a warm torch.compile package load does, and
serves every call under `set_stance("fail_on_recompile")`.

Serving under `fail_on_recompile` keeps the standalone contract: the artifact
serves only what capture exercised, and an uncovered call raises rather than
compiling. The alternative, letting the installed artifact recompile at serve
time (the old #195921 design), needs serve-time-compile accounting and
isolation machinery this stack does not have. Everything used here is already
on main, so the change is Python-only.

Deliberately left for follow-ups: `unload()`/`__exit__` do not yet take the
install back out (`CompilePackage.uninstall` resets only the entry's code
object), and an uncovered call surfaces as fail_on_recompile's RuntimeError
rather than a PrecompileError.

Test Plan:

The new end-to-end test captures `calls_breaking_helper` (whose helper graph
breaks) on two shapes, checks the artifact renders as installed, and serves
it in a fresh process for both backends. Because the fresh process serves
under fail_on_recompile, a correct result also proves every frame, the
helper's included, hit an installed entry instead of compiling. The loader
then checks that an uncovered dtype raises.

```
python test/test_precompile.py -k cannot_reach -k emit_multigraph_driver -k served_installed -k round_trip_in_a_fresh -k single_graph_serves
python test/test_precompile.py
```

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

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

A graph break inside a function the entry calls (a child module's forward,
say) makes Dynamo compile that function as a frame of its own. The entry
reaches it by an ordinary call, not by LOAD_GLOBAL of a resume name, so the
standalone dispatcher in `_build_multigraph_forward` can never intercept it.
`_build_multigraph_artifact` therefore refused every such capture ("cannot
reach from the entry"), which rules out most real models with a graph break
below the top-level function.

This renders those captures as `SERVING_MODE = "installed"` instead, which
`_parse_artifact_metadata` already reads. The artifact carries the Dynamo cache
entry and backend artifacts as one `_PACKAGE` blob, plus the readable
`UNREACHABLE_WITHOUT_INSTALL` list. Its driver, `_build_installed_forward`,
imports the captured function and rebuilds `CompilePackage(fn, dynamo)`. It
then calls `CompilePackage.install`, which puts the guarded entries onto the
live code objects exactly as a warm torch.compile package load does, and
serves every call under `set_stance("fail_on_recompile")`.

Serving under `fail_on_recompile` keeps the standalone contract: the artifact
serves only what capture exercised, and an uncovered call raises rather than
compiling. The alternative, letting the installed artifact recompile at serve
time (the old #195921 design), needs serve-time-compile accounting and
isolation machinery this stack does not have. Everything used here is already
on main, so the change is Python-only.

Deliberately left for follow-ups: `unload()`/`__exit__` do not yet take the
install back out (`CompilePackage.uninstall` resets only the entry's code
object), and an uncovered call surfaces as fail_on_recompile's RuntimeError
rather than a PrecompileError.

Test Plan:

The new end-to-end test captures `calls_breaking_helper` (whose helper graph
breaks) on two shapes, checks the artifact renders as installed, and serves
it in a fresh process for both backends. Because the fresh process serves
under fail_on_recompile, a correct result also proves every frame, the
helper's included, hit an installed entry instead of compiling. The loader
then checks that an uncovered dtype raises.

```
python test/test_precompile.py -k cannot_reach -k emit_multigraph_driver -k served_installed -k round_trip_in_a_fresh -k single_graph_serves
python test/test_precompile.py
```

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ghstack-source-id: ab5e097
Pull-Request: #198523
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 52s —— View job


The new [UPDATE] at fbabae5 is only a rebase onto the new base (ea24f21). This PR's own code hasn't changed since the last review (c7d8a64), and I found no new issues.

PR Review: #198523

Summary

Captures that have a frame the entry can't reach are now rendered as SERVING_MODE = "installed". Loading the artifact runs CompilePackage.install, and every call then runs under fail_on_recompile.

How I checked that only the base moved:

  • The PR's own patch has the same per-file stats before and after the update (61923858..c7d8a645 and ea24f217..fbabae5e): 4 files, +242/−115.
  • Across the four PR files, the only change between the two heads (c7d8a64..fbabae5) is in test/test_precompile.py. It moves torch._dynamo.reset(), _scrub_minted and the driver build below the _callback_step capture, and expands the comment. That hunk is identical to the base update's own change to the same file (61923858..ea24f217), so it belongs to the base stack, not to this PR.
  • The other 27 files in git diff c7d8a64 fbabae5 all come from the base update.

These earlier items are still deferred to the stacked PRs. This job can't see those branches, so I haven't checked them:

Recommendation

Approve, provided #198556 to #198558 land in the same stack.

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #198557

pytorchmergebot pushed a commit that referenced this pull request Oct 11, 2026
…o install (#198556)

An installed artifact rebuilds `CompilePackage(fn, dynamo)` against the live
module when it loads, and that constructor checksums every inlined source
against the module on disk. A source that changed since capture raised a bare
`RuntimeError("Source code changes detected ...")` out of `load()`, outside the
`PrecompileError` contract; a standalone artifact is never exposed to it.
`_build_installed_forward` now translates any failure of the package rebuild or
`install` into a `PrecompileError` naming the captured function, the same way
it already does for an unimportable module.

A call no captured variant covers had the same gap: the `fail_on_recompile`
stance raises a plain `RuntimeError`, where a standalone artifact raises
`PrecompileError("no captured variant ...")`. `forward` now re-raises that
stance error, and only that one (matched on its stable message), as a
`PrecompileError` with the same wording, so both serving modes refuse an
uncovered call the same way and the fresh-process loader checks one contract.

Test Plan:

The new test captures the installed-mode golden function, edits the helper's
source on disk, and checks a fresh process's `load` raises `PrecompileError`.
The installed round-trip test's uncovered call now expects `PrecompileError`.

```
python test/test_precompile.py -k served_installed -k changed_source
python test/test_precompile.py
```

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Pull Request resolved: #198556
Approved by: https://github.com/Mingming-Ding
ghstack dependencies: #198523
pytorchmergebot pushed a commit that referenced this pull request Oct 11, 2026
…lobal stance (#198557)

**Problem.** An installed artifact served every call by setting the process-global `fail_on_recompile` stance, so while one thread was inside a served call, every other thread's `torch.compile` raised on its first compile, and two overlapping calls could restore the stance out of order.

**Fix.** The artifact now carries its own refusing callback, a `_RefuseRecompileCallback` bound into its `OptimizeContext` once at load, and touches no global state per call; `_callback_from_stance` keeps that callback under every process-wide stance that would compile.

**Summary.** The installed driver wrapped each call in `torch.compiler.set_stance("fail_on_recompile")`, which mutates the process-global `_stance` that every `torch.compile` in the process reads on entry. That broke concurrent compiles in other threads and could restore the stance out of order when calls overlapped. The stance's per-call `fail_callback` closure is now a small `_FailOnRecompileCallback` class, and `_build_installed_forward` binds a `_RefuseRecompileCallback` subclass of it into the artifact's own `OptimizeContext` before `context(fn)` captures the callback. Because a stance the caller sets still passes through `_callback_from_stance` on every entry, that function recognizes the subclass and, reading the stance once, keeps it under every stance except `"force_eager"` and `"eager_on_recompile"`. Load also refuses two configurations the binding cannot cover, Dynamo disabled and `compiled_autograd`, and the refusal raises its own `_RecompileRefusedError`, which the driver catches by type instead of matching message text.

## Before and after, per call

```python
# parent: _build_installed_forward
compiled = torch._dynamo.optimize(BACKEND, package=package)(fn)

def forward(*args, **kwargs):
    with torch.compiler.set_stance("fail_on_recompile"):   # process-global
        try:
            return compiled(*args, **kwargs)
        except RuntimeError as _e:
            if "stance is 'fail_on_recompile'" not in str(_e):
                raise
            raise _PrecompileError(...) from None

# now: bound once at load, no global state touched per call
context = torch._dynamo.optimize(BACKEND, package=package)
context.callback = _RefuseRecompileCallback(context.callback)  # before context(fn)
compiled = context(fn)

def forward(*args, **kwargs):
    try:
        return compiled(*args, **kwargs)
    except _RecompileRefusedError as _e:
        raise _PrecompileError(...) from None
```

The stance is only consulted when a compiled callable is entered, to turn its callback into fail_on_recompile's callback; that callback then serves cached entries for every frame of the call and raises instead of compiling. Moving it out of `_callback_from_stance` into `_FailOnRecompileCallback` is a move plus closure-to-class, with no behavior change for the stance. The binding has to happen before `context(fn)`, which captures the callback when it wraps.

## What another thread sees

```python
# thread A: inside a served call of the installed artifact
# thread B, at the same moment:
torch.compile(g)(x)
# parent: B reads the global stance "fail_on_recompile" and raises on its first compile
# now:    B compiles normally; the stance is still "default"
```

## Under a process-wide stance

A stance the caller sets still passes through `_callback_from_stance` on every entry, and the compiling ones (`force_backend`, `"eager_then_compile"`, `"aot_eager_then_compile"`) would replace or re-wrap the bound callback and compile what the capture did not cover. So the function checks for the subclass first:

```python
def _callback_from_stance(callback):
    if isinstance(callback, _RefuseRecompileCallback):
        stance = _stance.stance          # read once
        if stance == "force_eager":
            return None                  # every call eager, installed entries bypassed
        return False if stance == "eager_on_recompile" else callback
    ...
```

| Stance the caller sets | Captured call | Uncovered call |
|---|---|---|
| default, `force_backend`, `"eager_then_compile"`, `"aot_eager_then_compile"`, `"fail_on_recompile"` | served compiled | `PrecompileError` |
| `"force_eager"` | eager | eager |
| `"eager_on_recompile"` | served compiled | eager |

Only the driver builds a `_RefuseRecompileCallback`. The per-call `_FailOnRecompileCallback`s that the stance builds, which `__exit__` can hand back as `self.prior`, keep the old path. The decision lives where the stance is read, so a concurrent `set_stance` cannot land between a check and the choice, and a new stance defaults to keeping the refusal. The `load()` docstring and the artifact's serving notes say so.

## Errors the refusal raises

The subclass overrides the message prefix and the exception class. It raises `_RecompileRefusedError` (a `RuntimeError`) with a message that does not claim a stance is set, and the driver's `forward` catches it by type rather than matching the message text.

## Two configurations load now refuses

```python
# TORCHDYNAMO_DISABLE=1 (or the enable_dynamo killswitch)
load(artifact, cache)
# parent: the install-failure message, whose hint blames a source change
# now:    PrecompileError: ... serves through Dynamo, which is disabled in this process ...

torch._dynamo.config.compiled_autograd = True
load(artifact, cache)
# now:    PrecompileError: ... cannot load with torch._dynamo.config.compiled_autograd enabled ...
```

Binding needs an `OptimizeContext`, which `optimize()` does not return when Dynamo is disabled. With `compiled_autograd`, `OptimizeContext` would compile backward graphs through a fresh `rebuild_ctx()` callback that does not refuse.

## Rejected: set the stance once at load

Setting the stance once at load and documenting it would put every other `torch.compile` in the process under fail_on_recompile for as long as the artifact is loaded.

## Tests

| Test | Pins |
|---|---|
| `test_an_installed_artifact_leaves_the_global_stance_alone` | the entry calls a `torch._dynamo.disable`d function mid-call that records the global stance; a fresh process sees `"default"` (it saw `"fail_on_recompile"` before this change); the recorder also runs a plain `torch.compile`, which must still compile |
| `test_an_installed_artifact_under_a_process_wide_stance` | `tags_compiled` (adds 1 only in a compiled frame) captured on one shape, served in a fresh process under each stance in the table above; the refusal's text names no stance, checked twice to get past the delayed-compile warmup |
| `test_an_installed_artifact_refuses_to_load_with_dynamo_disabled` | under `TORCHDYNAMO_DISABLE=1` the refusal names Dynamo being disabled, not the source |
| `test_an_installed_artifact_refuses_to_load_with_compiled_autograd` | with `compiled_autograd` enabled before load, load refuses |

Test Plan:

The new test serves an installed artifact whose entry calls a
`torch._dynamo.disable`d function mid-call that records the global stance; the
fresh process sees "default" (it saw "fail_on_recompile" before this change).
A second test loads an installed artifact under TORCHDYNAMO_DISABLE=1 and
checks the refusal names Dynamo being disabled, not the source; another
enables compiled_autograd before load and checks that refusal. A third
captures `tags_compiled` (which adds 1 only in a compiled frame) on one shape
and serves it in a fresh process under each process-wide stance:
force_backend, "eager_then_compile", "aot_eager_then_compile" and
"fail_on_recompile" serve the captured shape compiled and refuse the uncovered
one with PrecompileError whose text names no stance (twice, past the
delayed-compile warmup);
"force_eager" runs both eagerly; "eager_on_recompile" serves the captured one
compiled and the uncovered one eagerly. The stance recorder also runs a plain
`torch.compile` mid-call, which must still compile. Dropping the
`_FailOnRecompileCallback` branch in `_callback_from_stance` fails the third
test ("compiled under default"); raising a plain RuntimeError from the subclass
callback fails it too, and dropping the compiled_autograd check fails its test.

```
python test/test_precompile.py -k stance -k served_installed -k changed_source -k dynamo_disabled -k compiled_autograd -k own_errors
python test/test_precompile.py
cd test && python -m pytest -q dynamo/test_recompiles.py dynamo/test_decorators.py -k "stance or recompile"
```

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

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

Pull Request resolved: #198557
Approved by: https://github.com/Mingming-Ding
ghstack dependencies: #198523, #198556
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
pytorchmergebot pushed a commit that referenced this pull request Oct 12, 2026
… captured it (#198558)

**Problem.** Loading an installed artifact in a process that has already compiled any of its functions (the process that captured it, or one that ran `torch.compile` first) quietly lets those live compiles serve every call the artifact does not cover, so the load looks like it works while testing nothing about the artifact.

**Fix.** `load()` now refuses such an artifact with a `PrecompileError` that names the already-compiled frames and says to load it in a fresh process.

**Summary.** An installed artifact serves by attaching its captured Dynamo entries to the real code objects of the entry and every frame it compiled, and Dynamo's lookup checks those precompile entries first but falls back to any ordinary cache entries already on the same code object. In a process that already compiled one of those frames, a call the artifact does not cover is therefore served by the live compile instead of raising, which defeats the most natural check (capture, then load in the same script) and lets install() rebind the resume and compiled-fn globals the live entries call. `_build_installed_forward` now refuses before installing when any code object `CompilePackage.install` targets already has live cache entries, found the same way install finds them. Refusing is the smaller and safer contract than evicting the live entries, which belong to the caller's own compile, and it matches the standalone graph-break artifact, which already refuses the same situation. The check runs only at load, so compiling those frames after load brings the fallback back, and the `load()` docstring says so.

## Why it is needed

The installed artifact (#198523) puts its entries onto `calls_breaking_helper` and `breaking_helper`. In a fresh process those code objects carry nothing else, so a miss raises and tells you the artifact does not cover the call. In a process that already compiled them, the leftover entries answer instead:

```python
with capture(calls_breaking_helper, ...) as cap:
    cap(model, x2)                # leaves live compiled entries behind

f = load(artifact, cache)         # same process
f(model, x3)                      # a shape the artifact never saw
# parent: works, served by the leftover live compile -> false confidence
# now:    PrecompileError: frames this artifact installs onto
#         (calls_breaking_helper, breaking_helper, ...) already have live
#         Dynamo cache entries ... load this artifact in a fresh process.
```

The same happens in a fresh process that ran `torch.compile` on the entry, or only on a function the entry calls (`breaking_helper`), before loading.

## The check, in `_build_installed_forward`

It runs after the compiled_autograd refusal and before `optimize`/`install`:

```python
entries = package._codes.items()
targets = [_lookup_code(e) if e.code_source else c for c, e in entries]
live = [c.co_name for c in targets if _debug_get_cache_entry_list(c)]
if live:
    raise PrecompileError(...)   # names the frames, points at a fresh process
```

`targets` is exactly the set of codes `CompilePackage.install` writes to. The entry's code is the package key, resolved through `innermost_fn`, so a `torch.compile`-wrapped attribute is seen through. Every child frame is resolved from its recorded `code_source` through `_lookup_code`, the same resolution install uses, so the check and the install cannot disagree about which codes are involved. Checking only the entry's code would miss a process that compiled only a child frame.

## Why refuse, not evict

Making the in-process load work would mean evicting the live entries first. Those belong to the caller's compile, and deleting them behind the caller's back is surprising, so refusing is the smaller and safer contract. The standalone graph-break artifact already refuses to load beside the live compile that captured it (the continuation names collide).

## Left as documented, not checked

The check runs only at load. Compiling those frames after load adds live entries that again serve the calls the installed ones miss. The `load()` docstring now states this, instead of paying for a check on every call.

## Tests

| Test | Pins |
|---|---|
| `test_a_frame_the_entry_cannot_reach_is_served_installed` (extended) | loading in the capturing process raises `PrecompileError` mentioning "fresh process"; the artifact still serves in a fresh process |
| `test_an_installed_artifact_refuses_frames_compiled_before_load[calls_breaking_helper]` / `[breaking_helper]` | a fresh process `torch.compile`s the entry, or only the child `breaking_helper`, then loads; the refusal's frame list (`onto (...)`) must name the compiled frame as a whole word, so `breaking_helper` cannot match inside `calls_breaking_helper`; checking only the entry's code fails the child case |

Test Plan:

The installed round-trip test now also loads the artifact in the capturing
process and expects the refusal. A parametrized fresh-process test
torch.compile's either the entry or only `breaking_helper` (a child frame)
before `load` and expects the refusal's frame list to name the compiled frame
as a whole word; checking only the entry's code fails the child case. The
load() docstring notes the check runs only at load, so compiling those frames
afterwards reintroduces the fallback.

```
python test/test_precompile.py -k served_installed -k before_load
python test/test_precompile.py
```

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

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

Pull Request resolved: #198558
Approved by: https://github.com/MengjiaoZhou
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: dynamo topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants