Repository navigation
[precompile] Raise PrecompileError when an installed artifact fails to install - #198556
bobrenjc93 wants to merge 6 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/198556
Note: Links to docs will display an error until the docs builds have been completed. ⏳ No Failures, 1 PendingAs of commit ffe4c00 with merge base a4849a9 ( 🟡 GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:
reason: This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
Claude finished @bobrenjc93's task in 1m 38s —— View job The change looks right, and I found only minor issues: an untested pass-through branch, a subprocess call with no timeout, and a docstring narrower than what the code does. PR Review: #198556SummaryThe PR makes an installed artifact raise API Design
Testing
Code Quality
RecommendationApprove: none of the above blocks the change. The docstring fix and the test timeout are one-liners, and the pass-through test is worth adding since it guards the only new broad |
[ghstack-poisoned]
|
Round 40 (tb40, head moved), addressing all four items:
|
|
Claude finished @bobrenjc93's task in 54s —— View job All four items from the last round are fixed. I found one new minor issue: the new install-failure message can point users to the wrong source file. PR Review: #198556SummaryThe PR makes an installed artifact raise
I checked two more things:
Code Quality
RecommendationApprove: nothing blocks the change. The item above is a one-line wording fix. |
|
Claude finished @bobrenjc93's task in 26s —— View job The code at the head commit is the same as in the last review. One minor item is still open: the install-failure message still says "that source", which can point users to the wrong file. PR Review: #198556SummaryThe PR makes an installed artifact raise Code Quality
RecommendationApprove: nothing blocks the change. The item above is a one-line wording fix. |
[ghstack-poisoned]
… artifact fails to install
When `_build_installed_forward` cannot install an artifact, its error says "If that source changed since capture, regenerate the artifact against it." Here "that source" points back at `{module_name}.{FN_NAME}`, the entry function. But the install also resolves every child frame the artifact compiled, and those often live in other modules (inlined helpers, a graph-breaking callee). When one of them changed, the error sends the reader to the wrong file. The message now says "If a source it captured changed since capture (named above), ...". The chained exception text already names the frame that failed, so this points the reader at that frame instead of the entry.
This came up in the review of the commit that introduced the message (#198556). That PR is approved, and its head is frozen to keep the approval and its CI. The wording change goes here at the top of the stack instead of being amended into it.
Test Plan:
No test matches on this sentence. The existing install-failure tests still pass:
```
python test/test_precompile.py
python test/dynamo/test_precompile_package.py
lintrunner -a --skip PYREFLY,CLANGTIDY torch/_precompile_driver.py
```
This PR was authored with an AI assistant (Claude Code).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ghstack-source-id: bf11742
Pull-Request: #200526
|
@claude review |
|
Claude finished @bobrenjc93's task in 21s —— View job The code at head PR Review: #198556SummaryThe PR makes an installed artifact raise
No Code Quality
RecommendationApprove. Nothing blocks the change; the item above is a one-line wording fix. |
…o install
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.
The message says both ways a call can miss: a guard (on the arguments or on a
module global the graph baked in) no longer holds, or the call shape was never
captured. Any other exception, including the served model's own, passes
through unchanged.
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`.
A third test serves a model that raises its own `RuntimeError` from a
`torch._dynamo.disable`'d helper and checks it surfaces unwrapped. Removing the
stance-message match from `forward` fails the round-trip test.
```
python test/test_precompile.py -k served_installed -k changed_source -k own_errors
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: e4813da
Pull-Request: #198556
…o install
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.
The message says both ways a call can miss: a guard (on the arguments or on a
module global the graph baked in) no longer holds, or the call shape was never
captured. Any other exception, including the served model's own, passes
through unchanged.
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`.
A third test serves a model that raises its own `RuntimeError` from a
`torch._dynamo.disable`'d helper and checks it surfaces unwrapped. Removing the
stance-message match from `forward` fails the round-trip test.
```
python test/test_precompile.py -k served_installed -k changed_source -k own_errors
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: e4813da
Pull-Request: #198556
…o install
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.
The message says both ways a call can miss: a guard (on the arguments or on a
module global the graph baked in) no longer holds, or the call shape was never
captured. Any other exception, including the served model's own, passes
through unchanged.
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`.
A third test serves a model that raises its own `RuntimeError` from a
`torch._dynamo.disable`'d helper and checks it surfaces unwrapped. Removing the
stance-message match from `forward` fails the round-trip test.
```
python test/test_precompile.py -k served_installed -k changed_source -k own_errors
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: e4813da
Pull-Request: #198556
…o install
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.
The message says both ways a call can miss: a guard (on the arguments or on a
module global the graph baked in) no longer holds, or the call shape was never
captured. Any other exception, including the served model's own, passes
through unchanged.
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`.
A third test serves a model that raises its own `RuntimeError` from a
`torch._dynamo.disable`'d helper and checks it surfaces unwrapped. Removing the
stance-message match from `forward` fails the round-trip test.
```
python test/test_precompile.py -k served_installed -k changed_source -k own_errors
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: e4813da
Pull-Request: #198556
…o install
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.
The message says both ways a call can miss: a guard (on the arguments or on a
module global the graph baked in) no longer holds, or the call shape was never
captured. Any other exception, including the served model's own, passes
through unchanged.
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`.
A third test serves a model that raises its own `RuntimeError` from a
`torch._dynamo.disable`'d helper and checks it surfaces unwrapped. Removing the
stance-message match from `forward` fails the round-trip test.
```
python test/test_precompile.py -k served_installed -k changed_source -k own_errors
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: e4813da
Pull-Request: #198556
…on a source change
When `_build_installed_forward` cannot rebuild or install an artifact's package, it raises a PrecompileError that appends the cause and ended "If that source changed since capture, regenerate the artifact against it." Here "that source" read as `{module_name}.{FN_NAME}`, the entry function, but the package also checksums every inlined source, and those often live in other modules. The same `except Exception` also catches causes that name no source at all (an AssertionError inside install, say). Only the "Source code changes detected for <module> (line a - line b)" RuntimeError from `CompilePackage` names the source that changed.
The hint is now conditional: "If the cause names a source that changed since capture, regenerate the artifact against it." Giving the regenerate hint only for the source-mismatch RuntimeError would mean matching that error's text, which this driver avoids elsewhere (it catches the refusal by type). So the hint is left to the reader, who can see the cause.
This addresses review comments on the commit that introduced the message (#198556). That PR is approved, so the change goes here at the top of the stack instead of being amended into it.
Test Plan:
`test_an_installed_artifact_names_a_changed_helper_module_at_load` changes a module the entry inlines, not the entry's own module, and checks that the cause names that module and the message carries the conditional hint. The existing install-failure tests still pass:
```
python test/test_precompile.py
python test/dynamo/test_precompile_package.py
lintrunner -a --skip PYREFLY,CLANGTIDY torch/_precompile_driver.py
```
This PR was authored with an AI assistant (Claude Code).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ghstack-source-id: 51ae429
Pull-Request: #200526
…o install
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.
The message says both ways a call can miss: a guard (on the arguments or on a
module global the graph baked in) no longer holds, or the call shape was never
captured. Any other exception, including the served model's own, passes
through unchanged.
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`.
A third test serves a model that raises its own `RuntimeError` from a
`torch._dynamo.disable`'d helper and checks it surfaces unwrapped. Removing the
stance-message match from `forward` fails the round-trip test.
```
python test/test_precompile.py -k served_installed -k changed_source -k own_errors
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: e4813da
Pull-Request: #198556
…o install
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.
The message says both ways a call can miss: a guard (on the arguments or on a
module global the graph baked in) no longer holds, or the call shape was never
captured. Any other exception, including the served model's own, passes
through unchanged.
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`.
A third test serves a model that raises its own `RuntimeError` from a
`torch._dynamo.disable`'d helper and checks it surfaces unwrapped. Removing the
stance-message match from `forward` fails the round-trip test.
```
python test/test_precompile.py -k served_installed -k changed_source -k own_errors
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: e4813da
Pull-Request: #198556
…on a source change
When `_build_installed_forward` cannot rebuild or install an artifact's package, it raises a PrecompileError that appends the cause and ended "If that source changed since capture, regenerate the artifact against it." Here "that source" read as `{module_name}.{FN_NAME}`, the entry function, but the package also checksums every inlined source, and those often live in other modules. The same `except Exception` also catches causes that name no source at all (an AssertionError inside install, say). Only the "Source code changes detected for <module> (line a - line b)" RuntimeError from `CompilePackage` names the source that changed.
The hint is now conditional: "If the cause names a source that changed since capture, regenerate the artifact against it." Giving the regenerate hint only for the source-mismatch RuntimeError would mean matching that error's text, which this driver avoids elsewhere (it catches the refusal by type). So the hint is left to the reader, who can see the cause.
This addresses review comments on the commit that introduced the message (#198556). That PR is approved, so the change goes here at the top of the stack instead of being amended into it.
Test Plan:
`test_an_installed_artifact_names_a_changed_helper_module_at_load` changes a module the entry inlines, not the entry's own module, and checks that the cause names that module and the message carries the conditional hint. The existing install-failure tests still pass:
```
python test/test_precompile.py
python test/dynamo/test_precompile_package.py
lintrunner -a --skip PYREFLY,CLANGTIDY torch/_precompile_driver.py
```
This PR was authored with an AI assistant (Claude Code).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ghstack-source-id: 9df6035
Pull-Request: #200526
[ghstack-poisoned]
…on a source change
When `_build_installed_forward` cannot rebuild or install an artifact's package, it raises a PrecompileError that appends the cause and ended "If that source changed since capture, regenerate the artifact against it." Here "that source" read as `{module_name}.{FN_NAME}`, the entry function, but the package also checksums every inlined source, and those often live in other modules. The same `except Exception` also catches causes that name no source at all (an AssertionError inside install, say). Only the "Source code changes detected for <module> (line a - line b)" RuntimeError from `CompilePackage` names the source that changed.
The hint is now conditional: "If the cause names a source that changed since capture, regenerate the artifact against it." Giving the regenerate hint only for the source-mismatch RuntimeError would mean matching that error's text, which this driver avoids elsewhere (it catches the refusal by type). So the hint is left to the reader, who can see the cause.
This addresses review comments on the commit that introduced the message (#198556). That PR is approved, so the change goes here at the top of the stack instead of being amended into it.
Test Plan:
`test_an_installed_artifact_names_a_changed_helper_module_at_load` changes a module the entry inlines, not the entry's own module, and checks that the cause names that module and the message carries the conditional hint. The existing install-failure tests still pass:
```
python test/test_precompile.py
python test/dynamo/test_precompile_package.py
lintrunner -a --skip PYREFLY,CLANGTIDY torch/_precompile_driver.py
```
This PR was authored with an AI assistant (Claude Code).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ghstack-source-id: 5457a20
Pull-Request: #200526
|
@claude review |
|
Claude finished @bobrenjc93's task in 46s —— View job The new head PR Review: #198556SummaryThe PR makes an installed artifact raise
No Code Quality
RecommendationApprove. Nothing blocks the change; the item above is a one-line wording fix. |
|
/easycla |
|
Starting merge as part of PR stack under #198557 |
…ing it (#198523) **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: ```python 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. ```python # 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 ```python 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`: ```python 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 ```python 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]> Pull Request resolved: #198523 Approved by: https://github.com/Mingming-Ding
…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
…itional on a source change
When `_build_installed_forward` cannot rebuild or install an artifact's package, it raises a PrecompileError that appends the cause and ended "If that source changed since capture, regenerate the artifact against it." Here "that source" read as `{module_name}.{FN_NAME}`, the entry function, but the package also checksums every inlined source, and those often live in other modules. The same `except Exception` also catches causes that name no source at all (an AssertionError inside install, say). Only the "Source code changes detected for <module> (line a - line b)" RuntimeError from `CompilePackage` names the source that changed.
The hint is now conditional: "If the cause names a source that changed since capture, regenerate the artifact against it." Giving the regenerate hint only for the source-mismatch RuntimeError would mean matching that error's text, which this driver avoids elsewhere (it catches the refusal by type). So the hint is left to the reader, who can see the cause.
This addresses review comments on the commit that introduced the message (#198556). That PR is approved, so the change goes here at the top of the stack instead of being amended into it.
Test Plan:
`test_an_installed_artifact_names_a_changed_helper_module_at_load` changes a module the entry inlines, not the entry's own module, and checks that the cause names that module and the message carries the conditional hint. The existing install-failure tests still pass:
```
python test/test_precompile.py -k test_an_installed_artifact_names_a_changed_helper_module_at_load
python test/test_precompile.py
python test/dynamo/test_precompile_package.py
lintrunner -a --skip PYREFLY,CLANGTIDY torch/_precompile_driver.py
```
This PR was authored with an AI assistant (Claude Code).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ghstack-source-id: aaa3a2c
Pull-Request: #200526
…itional on a source change
When `_build_installed_forward` cannot rebuild or install an artifact's package, it raises a PrecompileError that appends the cause and ended "If that source changed since capture, regenerate the artifact against it." Here "that source" read as `{module_name}.{FN_NAME}`, the entry function, but the package also checksums every inlined source, and those often live in other modules. The same `except Exception` also catches causes that name no source at all (an AssertionError inside install, say). Only the "Source code changes detected for <module> (line a - line b)" RuntimeError from `CompilePackage` names the source that changed.
The hint is now conditional: "If the cause names a source that changed since capture, regenerate the artifact against it." Giving the regenerate hint only for the source-mismatch RuntimeError would mean matching that error's text, which this driver avoids elsewhere (it catches the refusal by type). So the hint is left to the reader, who can see the cause.
This addresses review comments on the commit that introduced the message (#198556). That PR is approved, so the change goes here at the top of the stack instead of being amended into it.
Test Plan:
`test_an_installed_artifact_names_a_changed_helper_module_at_load` changes a module the entry inlines, not the entry's own module, and checks that the cause names that module and the message carries the conditional hint. The existing install-failure tests still pass:
```
python test/test_precompile.py -k test_an_installed_artifact_names_a_changed_helper_module_at_load
python test/test_precompile.py
python test/dynamo/test_precompile_package.py
lintrunner -a --skip PYREFLY,CLANGTIDY torch/_precompile_driver.py
```
This PR was authored with an AI assistant (Claude Code).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ghstack-source-id: 3c000d6
Pull-Request: #200526
Stack from ghstack (oldest at bottom):
An installed artifact rebuilds
CompilePackage(fn, dynamo)against the livemodule 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 ofload(), outside thePrecompileErrorcontract; a standalone artifact is never exposed to it._build_installed_forwardnow translates any failure of the package rebuild orinstallinto aPrecompileErrornaming the captured function, the same wayit already does for an unimportable module.
A call no captured variant covers had the same gap: the
fail_on_recompilestance raises a plain
RuntimeError, where a standalone artifact raisesPrecompileError("no captured variant ...").forwardnow re-raises thatstance error, and only that one (matched on its stable message), as a
PrecompileErrorwith the same wording, so both serving modes refuse anuncovered 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
loadraisesPrecompileError.The installed round-trip test's uncovered call now expects
PrecompileError.This PR was authored with the help of an AI assistant (Claude).
Co-Authored-By: Claude Opus 5.5 [email protected]