Repository navigation
[precompile] Serve a capture whose child frame graph-broke by installing it - #198523
bobrenjc93 wants to merge 10 commits into
Conversation
[ghstack-poisoned]
🔗 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 FailureAs of commit fbabae5 with merge base a4849a9 ( 🟡 GREEN LIGHT - PR requires human review:
reason: 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. |
|
Claude finished @bobrenjc93's task in 2m 26s —— View job The installed path works, but some state is now out of date: PR Review: #198523SummaryCaptures that have a frame the entry can't reach are now rendered as Thread Safety
API Design
Code Quality
Testing
RecommendationRequest Changes: the |
[ghstack-poisoned]
…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
|
@claude review this PR. Earlier bot reviews and my replies are in this thread; please verify the fixes and dispositions. |
|
Claude finished @bobrenjc93's task in 1m 10s —— View job None of the earlier review's findings have been addressed in the current head ( PR Review: #198523SummaryThe PR serves a capture that has a frame the entry can't reach by emitting Status of earlier findings: the thread contains no replies from the author, only the Thread Safety
API Design
Code Quality
Testing
RecommendationRequest Changes: all of the earlier findings are still unaddressed. The main blockers are the wrong |
[ghstack-poisoned]
…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
|
@claude review this PR. Earlier bot reviews and my replies are in this thread; please verify the fixes and dispositions. |
|
Claude finished @bobrenjc93's task in 46s —— View job All of the earlier findings are still open at the current head ( PR Review: #198523SummaryThe PR serves a capture that has a frame the entry can't reach by emitting What changed since the last review: the thread still has only
None of the code or tests named in the earlier reviews changed. I re-checked every finding against HEAD.
The full reasoning for each item is in the first review above and still applies as written. RecommendationRequest 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]
…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
|
@claude review this PR. Earlier bot reviews and my replies are in this thread; please verify the fixes and dispositions. |
|
Claude finished @bobrenjc93's task in 47s —— View job All 10 earlier findings are still open at the current head ( PR Review: #198523SummaryThe PR serves a capture that has a frame the entry can't reach by emitting What changed since the last review ( I re-checked each finding against HEAD:
The first review in this thread has the full reasoning for each item, and it still applies as written. RecommendationRequest Changes: nothing from the earlier reviews has been addressed. The blockers are still #1 (the global-stance thread-safety decision), #2 (the wrong 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 |
[ghstack-poisoned]
|
/easycla |
…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
|
Claude finished @bobrenjc93's task in 1m 16s —— View job The new PR Review: #198523SummaryThe PR serves a capture with a frame the entry can't reach by rendering it as How I checked that only the base moved:
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 |
[ghstack-poisoned]
|
@claude review |
|
Claude finished @bobrenjc93's task in 39s —— View job The new PR Review: #198523SummaryCaptures with a frame the entry can't reach are now rendered as I compared the PR's patch before the update (
The earlier items are still deferred to the stacked PRs. This job can't see those branches, so I haven't checked them:
RecommendationApprove, provided #198556 to #198558 land in the same stack. |
…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
…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
…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
…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
…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
…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
…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]
|
@claude review |
|
Claude finished @bobrenjc93's task in 52s —— View job The new PR Review: #198523SummaryCaptures that have a frame the entry can't reach are now rendered as How I checked that only the base moved:
These earlier items are still deferred to the stacked PRs. This job can't see those branches, so I haven't checked them:
RecommendationApprove, provided #198556 to #198558 land in the same stack. |
|
Starting merge as part of PR stack under #198557 |
…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
…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
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
… 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
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_artifactrefused the capture ("cannot reach from the entry"). This PR renders those captures asSERVING_MODE = "installed", carrying the whole Dynamo package in one_PACKAGEblob, and their driver_build_installed_forwardinstalls it withCompilePackage.install, exactly as a warm torch.compile package load does. Every call is served underfail_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:
The break is inside
breaking_helper, not in the entry. Dynamo compilesbreaking_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_helperwould silently run eager.Render side (
torch/_precompile.py): a mode choice instead of a refusalAn installed artifact writes the following instead of
_FRAMES,_BACKENDSand_ENTRY_BINDING:_parse_artifact_metadataalready readsSERVING_MODE, so the format needs no new concept, andload()now sets the handle'sinstalledflag 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 DynamoCompilePackage.installputs the captured entries onto the real code objects ofcalls_breaking_helperandbreaking_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 aPrecompileErrorwhen 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 alternativeServing under
fail_on_recompilekeeps 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_multigraph_artifact_installs_a_frame_the_entry_cannot_reachSERVING_MODE = "installed", anUNREACHABLE_WITHOUT_INSTALLlist,forward = _build_installed_forward(), and no_FRAMESblobtest_a_frame_the_entry_cannot_reach_is_served_installed(both backends)calls_breaking_helperon two shapes, checks the unreachable list names the helper and its continuation, and serves it in a fresh process; since that process serves underfail_on_recompile, a correct result proves every frame, the helper's included, hit an installed entry instead of compiling, and an uncovered dtype must raiseLeft to the PRs above
This PR is kept to the minimum that serves; each gap is its own draft on top.
RuntimeError, not aPrecompileError, and a failed install is not wrappedset_stance(...)per call flips the process-global stance, so another thread'storch.compileraises while a call is being servedunload()/__exit__do not take the install back out (CompilePackage.uninstallresets only the entry's code object)Test Plan:
The new end-to-end test captures
calls_breaking_helper(whose helper graphbreaks) 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.
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