Skip to content

[precompile] Refuse recompiles in an installed artifact without the global stance - #198557

Closed
bobrenjc93 wants to merge 11 commits into
gh/bobrenjc93/1489/basefrom
gh/bobrenjc93/1489/head
Closed

bobrenjc93 wants to merge 11 commits into
gh/bobrenjc93/1489/basefrom
gh/bobrenjc93/1489/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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

# 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

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

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 _FailOnRecompileCallbacks 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

# 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.disabled 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.disabled 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]

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (1 Unrelated Failure)

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

🟡 GREEN LIGHT - PR requires human review:

  • Triviality
    • Changes core Dynamo stance dispatch: new _RefuseRecompileCallback branch at the top of _callback_from_stance in torch/_dynamo/eval_frame.py
    • Converts the fail_on_recompile closure into _FailOnRecompileCallback, a refactor plus new semantics, not a single trivial class
  • User-facing behavior
    • Installed artifacts now behave differently per stance (force_eager bypasses entries, eager_on_recompile runs uncovered calls eagerly)
    • _build_installed_forward in torch/_precompile_driver.py adds two new load-time refusals: compiled_autograd enabled and Dynamo disabled
  • Concurrency and design
    • Replaces per-call global set_stance with a post-construction context.callback rebinding whose ordering before context(fn) is load-bearing
    • Thread-safety and stance-interaction design merits a human Dynamo reviewer despite tests in test/test_precompile.py

reason: not_trivial
Reviewed commit: e3b2f5e

Inference job

🐛 Report a wrong verdict

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

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

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

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 24, 2026
@bobrenjc93 bobrenjc93 changed the title [precompile] Refuse recompiles in an installed artifact without the global stance [no-ci] [precompile] Refuse recompiles in an installed artifact without the global stance Sep 24, 2026
@bobrenjc93 bobrenjc93 removed ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests labels Sep 24, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude review this PR. It carries one of the review items split out of #198523; the dispositions are in that PR's thread.

@claude

claude Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

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


One blocking issue: with this PR, a user-set eager_then_compile, aot_eager_then_compile or force_backend stance undoes an installed artifact's refusal to recompile, and that case has no test.

PR Review: #198557

Summary

The PR binds fail_on_recompile's callback into the installed artifact's own OptimizeContext when the artifact loads, so a served call no longer sets the process-global stance. The move of _fail_on_recompile_callback is behavior-neutral. But the new "a process-wide stance you set still wins" behavior brings a regression: some stances now defeat the artifact's refusal to recompile. Before this PR, set_stance("fail_on_recompile") inside forward replaced any stance the user had set, so this could not happen.

API Design

  • Some stances still compile, or crash, inside an installed artifact (torch/_precompile_driver.py:792, and the docs at torch/_precompile.py:2039-2042 and :3309-3311). Every call still goes through _callback_from_stance(self.callback) (eval_frame.py:1251), which gets the wrapped fail_callback:

    • set_stance("default", force_backend=...): eval_frame.py:331-332 swaps the callback for a new _create_wrapped_callback(...). That drops fail_callback, so a call no captured variant covers compiles a new graph instead of raising PrecompileError. The backend also differs from the captured one, so installed entries may miss on every call.
    • eager_then_compile / aot_eager_then_compile: _create_delayed_compile_callback wraps fail_callback. On the second example it reads callback._torchdynamo_orig_backend._torchdynamo_orig_backend (eval_frame.py:401) and assumes that is the compiler fn. The wrapper adds one more level: fail_callback → CatchErrorsWrapper → ConvertFrame (convert_frame.py:2581, :2364). So _create_wrapped_callback gets a ConvertFrame as its compiler_fn and compiles with the wrong object. The user sees a confusing internal failure, not the "no captured variant" PrecompileError.
    • force_eager / eager_on_recompile: on a miss these silently run eager. That fits the new docs, but it means "Its calls refuse to compile" is not the contract either.

    Fix: either apply the fail wrapper after the stance (for example, forward builds the callback as _fail_on_recompile_callback(_callback_from_stance(...)), or the artifact skips _callback_from_stance), or state exactly which stances override the refusal. Whichever you pick, eager_then_compile must not reach eval_frame.py:401 with the extra wrapper level. The docstring's "force_eager" example also implies every stance behaves as cleanly, which isn't true.

Testing

  • The stance behavior the docs describe has no test (test/test_precompile.py:4797). test_an_installed_artifact_leaves_the_global_stance_alone only checks that _stance.stance == "default" during a served call. Two tests are missing:
    • One that serves an uncovered call under set_stance("eager_then_compile") and under set_stance(force_backend="eager"), and asserts the result. This would have caught the issue above.
    • One that serves a covered call under force_eager and checks it runs eager, since the docs now promise that behavior.
  • The concurrency motivation is not exercised. No test runs a plain torch.compile while a served call is in flight, for example from inside record_stance, and checks that the plain compile still succeeds. That is the bug this PR fixes. The current test only checks a proxy for it: the value of the global stance.

Code Quality

  • Setting context.callback after construction is a side channel (torch/_precompile_driver.py:792). OptimizeContext.__reduce__ (eval_frame.py:1468) now pickles a local closure, and nothing in _TorchDynamoContext expects callback to change after __init__. Passing the wrapped callback in at construction would state this explicitly, for example through a small optimize/_optimize_catch_errors parameter. That would also remove the need for the isinstance(context, OptimizeContext) probe.

Recommendation

Request Changes. The force_backend and *_then_compile interactions break the artifact's "serves only what capture exercised" contract. The PR needs a test that covers them.

[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests labels Sep 24, 2026
@bobrenjc93 bobrenjc93 removed ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests labels Sep 24, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

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


The only code change since my last review fixes the _build_installed_forward docstring, and I found no code issues. One thing is still open: the PR description describes an earlier design and should be updated before landing.

PR Review: #198557

Summary

When an installed artifact loads, the PR binds a _RefuseRecompileCallback into the artifact's own OptimizeContext, so served calls no longer set the process-global fail_on_recompile stance. The new head (7ea0c2fb) differs from the version I reviewed last (db53d5a0) only in the _build_installed_forward docstring (torch/_precompile_driver.py:736-740). The docstring now names _RefuseRecompileCallback and says that _callback_from_stance keeps it under compiling stances, which fixes that finding. I re-read the full eval_frame.py and _precompile_driver.py diff against gh/bobrenjc93/1489/base and found no new code defects.

Code Quality

  • The PR description still describes an earlier design. The commit message becomes the landed history, so it needs to match the code:
    • The described move no longer exists. The description says the callback moved "into _fail_on_recompile_callback (a pure move, no behavior change)". That function is not in the code. The PR actually adds three classes, _FailOnRecompileCallback, _RefuseRecompileCallback and _RecompileRefusedError (torch/_dynamo/eval_frame.py:279-351). It also adds an early branch to _callback_from_stance (:354-360).
    • The stance behaviour is described wrongly. The description says "a process-wide stance the caller sets still applies on top". In fact the bound callback is kept under force_backend, *_then_compile and fail_on_recompile. Only force_eager and eager_on_recompile change how calls are served.
    • Two changes are not mentioned:
      • the refusal to load with compiled_autograd enabled;
      • forward now catches _RecompileRefusedError by type instead of matching the message text.
    • The Test Plan is incomplete. It lists two tests, but the PR adds four. under_a_process_wide_stance and refuses_to_load_with_compiled_autograd are missing, and the Test Plan's -k filters don't select them.
    • Since this is a ghstack PR, update the description on GitHub, or amend the commit message and run ghstack -u.

Recommendation

Approve once the PR description is updated. Nothing in the code blocks.

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

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


The code is unchanged since the round-43 version I approved, and the PR description now matches it. One small doc gap is left: load() doesn't mention the Dynamo-disabled refusal.

PR Review: #198557

Summary

When an installed artifact loads, the PR binds a _RefuseRecompileCallback into the artifact's own OptimizeContext, so served calls no longer set the process-global fail_on_recompile stance. _callback_from_stance keeps that callback under every stance that would compile, returns None under force_eager and returns False under eager_on_recompile.

I re-read the full diff against gh/bobrenjc93/1489/base. The updated PR description now matches the code:

  • It describes the _FailOnRecompileCallback / _RefuseRecompileCallback / _RecompileRefusedError design and the stance table.
  • It covers both load refusals.
  • Its Test Plan names all four new tests, and the -k stance and -k compiled_autograd filters select the two tests the earlier description left out.

I found no new code defects.

API Design

  • load() documents only one of the two new load refusals (torch/_precompile.py:3320-3322). The docstring now says an installed artifact refuses to load with compiled_autograd enabled. It doesn't say that it also refuses under TORCHDYNAMO_DISABLE=1 or the enable_dynamo killswitch (torch/_precompile_driver.py:800-805). Before this PR, that case failed with the install-failure error, so it's a new documented behavior and the docstring should list it next to the compiled_autograd sentence.

Recommendation

Approve after the one-line docstring addition. Nothing else blocks.

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Oct 10, 2026
…lobal stance

An installed artifact served every call under
`torch.compiler.set_stance("fail_on_recompile")`, which sets the process-global
`_stance`. While one thread was inside a served call, any other thread's
`torch.compile` read that stance and raised on its first compile, and two
overlapping calls could restore the stance out of order.

The stance is only consulted when a compiled callable is entered, to turn its
callback into fail_on_recompile's `fail_callback`; that callback then serves
cached entries for every frame of the call and raises instead of compiling.
This moves that callback out of `_callback_from_stance` into a small
`_FailOnRecompileCallback` class (a move plus closure-to-class, no behavior
change for the stance), and `_build_installed_forward` binds one into the
artifact's own `OptimizeContext` once at load, before `context(fn)` captures
the callback. No global state is touched per call.

A process-wide 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
`_callback_from_stance` now recognizes a `_RefuseRecompileCallback`, a
subclass only the driver builds (the per-call `_FailOnRecompileCallback`s the
stance builds, which `__exit__` can hand back as `self.prior`, keep the old
path), and,
reading the stance once, keeps it under every stance except "force_eager"
(every call runs eagerly, bypassing the installed entries) and
"eager_on_recompile" (captured variants serve, other calls run eagerly). 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.

Binding needs an `OptimizeContext`, which `optimize()` does not return when
Dynamo is disabled (TORCHDYNAMO_DISABLE=1 or the enable_dynamo killswitch);
load now refuses that case with its own PrecompileError instead of the
install-failure message, whose hint blames a source change. It also refuses
`torch._dynamo.config.compiled_autograd`: `OptimizeContext` would compile
backward graphs through a fresh `rebuild_ctx()` callback that does not refuse.

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.

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

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]>
ghstack-source-id: 38e3f46
Pull-Request: #198557
bobrenjc93 added a commit that referenced this pull request Oct 10, 2026
…lobal stance

An installed artifact served every call under
`torch.compiler.set_stance("fail_on_recompile")`, which sets the process-global
`_stance`. While one thread was inside a served call, any other thread's
`torch.compile` read that stance and raised on its first compile, and two
overlapping calls could restore the stance out of order.

The stance is only consulted when a compiled callable is entered, to turn its
callback into fail_on_recompile's `fail_callback`; that callback then serves
cached entries for every frame of the call and raises instead of compiling.
This moves that callback out of `_callback_from_stance` into a small
`_FailOnRecompileCallback` class (a move plus closure-to-class, no behavior
change for the stance), and `_build_installed_forward` binds one into the
artifact's own `OptimizeContext` once at load, before `context(fn)` captures
the callback. No global state is touched per call.

A process-wide 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
`_callback_from_stance` now recognizes a `_RefuseRecompileCallback`, a
subclass only the driver builds (the per-call `_FailOnRecompileCallback`s the
stance builds, which `__exit__` can hand back as `self.prior`, keep the old
path), and,
reading the stance once, keeps it under every stance except "force_eager"
(every call runs eagerly, bypassing the installed entries) and
"eager_on_recompile" (captured variants serve, other calls run eagerly). 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.

Binding needs an `OptimizeContext`, which `optimize()` does not return when
Dynamo is disabled (TORCHDYNAMO_DISABLE=1 or the enable_dynamo killswitch);
load now refuses that case with its own PrecompileError instead of the
install-failure message, whose hint blames a source change. It also refuses
`torch._dynamo.config.compiled_autograd`: `OptimizeContext` would compile
backward graphs through a fresh `rebuild_ctx()` callback that does not refuse.

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.

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

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]>
ghstack-source-id: 38e3f46
Pull-Request: #198557
bobrenjc93 added a commit that referenced this pull request Oct 10, 2026
…lobal stance

An installed artifact served every call under
`torch.compiler.set_stance("fail_on_recompile")`, which sets the process-global
`_stance`. While one thread was inside a served call, any other thread's
`torch.compile` read that stance and raised on its first compile, and two
overlapping calls could restore the stance out of order.

The stance is only consulted when a compiled callable is entered, to turn its
callback into fail_on_recompile's `fail_callback`; that callback then serves
cached entries for every frame of the call and raises instead of compiling.
This moves that callback out of `_callback_from_stance` into a small
`_FailOnRecompileCallback` class (a move plus closure-to-class, no behavior
change for the stance), and `_build_installed_forward` binds one into the
artifact's own `OptimizeContext` once at load, before `context(fn)` captures
the callback. No global state is touched per call.

A process-wide 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
`_callback_from_stance` now recognizes a `_RefuseRecompileCallback`, a
subclass only the driver builds (the per-call `_FailOnRecompileCallback`s the
stance builds, which `__exit__` can hand back as `self.prior`, keep the old
path), and,
reading the stance once, keeps it under every stance except "force_eager"
(every call runs eagerly, bypassing the installed entries) and
"eager_on_recompile" (captured variants serve, other calls run eagerly). 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.

Binding needs an `OptimizeContext`, which `optimize()` does not return when
Dynamo is disabled (TORCHDYNAMO_DISABLE=1 or the enable_dynamo killswitch);
load now refuses that case with its own PrecompileError instead of the
install-failure message, whose hint blames a source change. It also refuses
`torch._dynamo.config.compiled_autograd`: `OptimizeContext` would compile
backward graphs through a fresh `rebuild_ctx()` callback that does not refuse.

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.

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

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]>
ghstack-source-id: 38e3f46
Pull-Request: #198557
bobrenjc93 added a commit that referenced this pull request Oct 10, 2026
…lobal stance

An installed artifact served every call under
`torch.compiler.set_stance("fail_on_recompile")`, which sets the process-global
`_stance`. While one thread was inside a served call, any other thread's
`torch.compile` read that stance and raised on its first compile, and two
overlapping calls could restore the stance out of order.

The stance is only consulted when a compiled callable is entered, to turn its
callback into fail_on_recompile's `fail_callback`; that callback then serves
cached entries for every frame of the call and raises instead of compiling.
This moves that callback out of `_callback_from_stance` into a small
`_FailOnRecompileCallback` class (a move plus closure-to-class, no behavior
change for the stance), and `_build_installed_forward` binds one into the
artifact's own `OptimizeContext` once at load, before `context(fn)` captures
the callback. No global state is touched per call.

A process-wide 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
`_callback_from_stance` now recognizes a `_RefuseRecompileCallback`, a
subclass only the driver builds (the per-call `_FailOnRecompileCallback`s the
stance builds, which `__exit__` can hand back as `self.prior`, keep the old
path), and,
reading the stance once, keeps it under every stance except "force_eager"
(every call runs eagerly, bypassing the installed entries) and
"eager_on_recompile" (captured variants serve, other calls run eagerly). 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.

Binding needs an `OptimizeContext`, which `optimize()` does not return when
Dynamo is disabled (TORCHDYNAMO_DISABLE=1 or the enable_dynamo killswitch);
load now refuses that case with its own PrecompileError instead of the
install-failure message, whose hint blames a source change. It also refuses
`torch._dynamo.config.compiled_autograd`: `OptimizeContext` would compile
backward graphs through a fresh `rebuild_ctx()` callback that does not refuse.

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.

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

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]>
ghstack-source-id: 38e3f46
Pull-Request: #198557
bobrenjc93 added a commit that referenced this pull request Oct 10, 2026
…lobal stance

An installed artifact served every call under
`torch.compiler.set_stance("fail_on_recompile")`, which sets the process-global
`_stance`. While one thread was inside a served call, any other thread's
`torch.compile` read that stance and raised on its first compile, and two
overlapping calls could restore the stance out of order.

The stance is only consulted when a compiled callable is entered, to turn its
callback into fail_on_recompile's `fail_callback`; that callback then serves
cached entries for every frame of the call and raises instead of compiling.
This moves that callback out of `_callback_from_stance` into a small
`_FailOnRecompileCallback` class (a move plus closure-to-class, no behavior
change for the stance), and `_build_installed_forward` binds one into the
artifact's own `OptimizeContext` once at load, before `context(fn)` captures
the callback. No global state is touched per call.

A process-wide 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
`_callback_from_stance` now recognizes a `_RefuseRecompileCallback`, a
subclass only the driver builds (the per-call `_FailOnRecompileCallback`s the
stance builds, which `__exit__` can hand back as `self.prior`, keep the old
path), and,
reading the stance once, keeps it under every stance except "force_eager"
(every call runs eagerly, bypassing the installed entries) and
"eager_on_recompile" (captured variants serve, other calls run eagerly). 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.

Binding needs an `OptimizeContext`, which `optimize()` does not return when
Dynamo is disabled (TORCHDYNAMO_DISABLE=1 or the enable_dynamo killswitch);
load now refuses that case with its own PrecompileError instead of the
install-failure message, whose hint blames a source change. It also refuses
`torch._dynamo.config.compiled_autograd`: `OptimizeContext` would compile
backward graphs through a fresh `rebuild_ctx()` callback that does not refuse.

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.

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

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]>
ghstack-source-id: 38e3f46
Pull-Request: #198557
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

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


I found no blocking issues. The only change since my last review adds the Dynamo-disabled refusal to the load() docstring, which closes the last open item.

PR Review: #198557

Summary

When an installed artifact loads, the PR binds a _RefuseRecompileCallback into the artifact's own OptimizeContext, so served calls no longer set the process-global fail_on_recompile stance.

At the new head (3ca4e755), the load() docstring (torch/_precompile.py:3321-3324) lists both load-time refusals: compiled_autograd enabled, and Dynamo disabled (TORCHDYNAMO_DISABLE=1 or the enable_dynamo killswitch). That fixes the only finding from the previous review.

I re-read the eval_frame.py and _precompile_driver.py diffs against gh/bobrenjc93/1489/base. They match the round-43 version I approved, and I found no new defects.

Recommendation

Approve. Nothing blocks.

bobrenjc93 added a commit that referenced this pull request Oct 10, 2026
…lobal stance

An installed artifact served every call under
`torch.compiler.set_stance("fail_on_recompile")`, which sets the process-global
`_stance`. While one thread was inside a served call, any other thread's
`torch.compile` read that stance and raised on its first compile, and two
overlapping calls could restore the stance out of order.

The stance is only consulted when a compiled callable is entered, to turn its
callback into fail_on_recompile's `fail_callback`; that callback then serves
cached entries for every frame of the call and raises instead of compiling.
This moves that callback out of `_callback_from_stance` into a small
`_FailOnRecompileCallback` class (a move plus closure-to-class, no behavior
change for the stance), and `_build_installed_forward` binds one into the
artifact's own `OptimizeContext` once at load, before `context(fn)` captures
the callback. No global state is touched per call.

A process-wide 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
`_callback_from_stance` now recognizes a `_RefuseRecompileCallback`, a
subclass only the driver builds (the per-call `_FailOnRecompileCallback`s the
stance builds, which `__exit__` can hand back as `self.prior`, keep the old
path), and,
reading the stance once, keeps it under every stance except "force_eager"
(every call runs eagerly, bypassing the installed entries) and
"eager_on_recompile" (captured variants serve, other calls run eagerly). 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.

Binding needs an `OptimizeContext`, which `optimize()` does not return when
Dynamo is disabled (TORCHDYNAMO_DISABLE=1 or the enable_dynamo killswitch);
load now refuses that case with its own PrecompileError instead of the
install-failure message, whose hint blames a source change. It also refuses
`torch._dynamo.config.compiled_autograd`: `OptimizeContext` would compile
backward graphs through a fresh `rebuild_ctx()` callback that does not refuse.

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.

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

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]>
ghstack-source-id: 38e3f46
Pull-Request: #198557
bobrenjc93 added a commit that referenced this pull request Oct 10, 2026
…lobal stance

An installed artifact served every call under
`torch.compiler.set_stance("fail_on_recompile")`, which sets the process-global
`_stance`. While one thread was inside a served call, any other thread's
`torch.compile` read that stance and raised on its first compile, and two
overlapping calls could restore the stance out of order.

The stance is only consulted when a compiled callable is entered, to turn its
callback into fail_on_recompile's `fail_callback`; that callback then serves
cached entries for every frame of the call and raises instead of compiling.
This moves that callback out of `_callback_from_stance` into a small
`_FailOnRecompileCallback` class (a move plus closure-to-class, no behavior
change for the stance), and `_build_installed_forward` binds one into the
artifact's own `OptimizeContext` once at load, before `context(fn)` captures
the callback. No global state is touched per call.

A process-wide 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
`_callback_from_stance` now recognizes a `_RefuseRecompileCallback`, a
subclass only the driver builds (the per-call `_FailOnRecompileCallback`s the
stance builds, which `__exit__` can hand back as `self.prior`, keep the old
path), and,
reading the stance once, keeps it under every stance except "force_eager"
(every call runs eagerly, bypassing the installed entries) and
"eager_on_recompile" (captured variants serve, other calls run eagerly). 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.

Binding needs an `OptimizeContext`, which `optimize()` does not return when
Dynamo is disabled (TORCHDYNAMO_DISABLE=1 or the enable_dynamo killswitch);
load now refuses that case with its own PrecompileError instead of the
install-failure message, whose hint blames a source change. It also refuses
`torch._dynamo.config.compiled_autograd`: `OptimizeContext` would compile
backward graphs through a fresh `rebuild_ctx()` callback that does not refuse.

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.

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

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]>
ghstack-source-id: 38e3f46
Pull-Request: #198557
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

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


No blocking issues: since my last approval at 3ca4e755, only the base has moved, and the PR's own changes are byte-identical.

PR Review: #198557

Summary

When an installed artifact loads, the PR binds a _RefuseRecompileCallback into the artifact's own OptimizeContext. Served calls therefore no longer set the process-global fail_on_recompile stance.

The new head e3b2f5e7 sits on base update e3ccce78. For the four files the PR touches, git diff 3ca4e755 e3b2f5e7 is empty:

  • test/test_precompile.py
  • torch/_dynamo/eval_frame.py
  • torch/_precompile.py
  • torch/_precompile_driver.py

The base update doesn't touch eval_frame.py, _precompile.py or _precompile_driver.py. Its Dynamo-side changes are:

  • the substitute_in_graph / PolyfilledFunctionVariable method dispatch
  • removal of the assert_*_equal polyfills
  • a new test_decorators.py test

None of these touch the stance, _callback_from_stance or the OptimizeContext callback paths this PR relies on. I found no new issues.

Recommendation

Approve. Nothing blocks.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

/easycla

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

pytorchmergebot pushed a commit that referenced this pull request Oct 11, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants