Skip to content

[precompile] Refuse loading an installed artifact in the process that captured it - #198558

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

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

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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:

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:

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.compiles 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]

[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/198558

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

✅ No Failures

As of commit 9bf5745 with merge base be4d660 (image):
💚 Looks good so far! There are no failures yet. 💚

🟡 GREEN LIGHT - PR requires human review:

  • User-facing contract change
    • _build_installed_forward in torch/_precompile_driver.py now raises PrecompileError where load() used to succeed, whenever a target frame has live cache entries
    • load() is public as torch.compiler.precompile.load, and its docstring in torch/_precompile.py now states this new refusal
  • Design choice a reviewer could change
    • Refusing rather than evicting, and checking only at load rather than on every call, are contract decisions that the PR body argues for
    • The new check relies on private internals (package._codes, _lookup_code, _debug_get_cache_entry_list) that have to match how CompilePackage.install picks its targets
  • Triviality
    • Not a single-cause bugfix: the fix moves a user-facing expectation, which that class excludes, and no other trivial class fits
    • Tests are present: the test_an_installed_artifact_refuses_frames_compiled_before_load parametrization and the extended capture-process assertion

reason: not_trivial
Reviewed commit: 9bf5745

Inference job

🐛 Report a wrong verdict

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

@bobrenjc93 bobrenjc93 changed the title [precompile] Refuse loading an installed artifact in the process that captured it [no-ci] [precompile] Refuse loading an installed artifact in the process that captured it 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 6s —— View job


The refusal is the right contract, but the check only looks at the entry's bare fn.__code__, so it misses some of the cases the PR description says it covers.

PR Review: #198558

Summary

_build_installed_forward now refuses to load an installed artifact when the captured entry's code object already has live Dynamo cache entries. The design is sound. The check is narrower than the contract stated in the PR description and the load() docstring.

Code Quality

  • torch/_precompile_driver.py:782 checks only the entry frame, not every frame being installed. CompilePackage.install (torch/_dynamo/package.py:1371-1486) loads precompile entries onto every code in dynamo.codes. That includes the child frames entered through ordinary calls (a child module's forward, found via _lookup_code).
    • Failure case: a process ran torch.compile on a submodule the artifact covers, but not on the entry itself. That child code object keeps its live cache entries, and the check passes.
    • For that child, Dynamo tries the precompile entries first and falls back to the live ones. A call the artifact doesn't cover is then served by the live compile, which is the silent false pass this PR is meant to stop.
    • The capturing-process case works only because the entry happens to carry live entries too.
    • Suggested fix: check every installable target code. One way is to iterate package._codes after CompilePackage(fn, dynamo) is built, resolving through _lookup_code when entry.code_source is set, and refuse if any target has live cache entries. The alternative is to narrow the docstring and error message to "the entry".
  • The check reads fn.__code__, but CompilePackage works on innermost_fn(fn) (package.py:1093). If the module attribute FN_NAME is a wrapped callable, for example one with @torch.compile applied, fn.__code__ is the wrapper's code. It has no cache entries, so the check passes, while the precompile entries go onto the inner code, which does have them. That inner code is exactly the "a torch.compile of it" case the error message names. Checking package._innermost_fn.__code__, or the loop above, fixes both points at once.

API Design

  • torch/_precompile.py:3313-3315: the new docstring says an installed artifact "is refused wherever its entry already has live Dynamo cache entries." If the check is widened as suggested above, reword this to "any frame it installs onto". As written, it describes the narrower check, while the PR description promises the wider one.

Testing

  • test/test_precompile.py:4794-4797 only covers refusal in the capturing process. Two cases the check claims to handle have no tests:

    1. A fresh process that has run torch.compile on the entry function before load(). This is the second case in the error message.
    2. Once the check is widened, a process that compiled only a child frame (the helper that graph-breaks). This is the case that currently gets through.

    Both can use the existing _serve_in_fresh_process harness, or a plain subprocess that compiles first and then loads.

Recommendation

Request Changes: widen the check to all installed target codes, resolved through innermost_fn, and add a test for the separately compiled case.

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

In the capturing process the entry and every frame it compiled still carry the
capture's live Dynamo cache entries. Installing the artifact there adds its
precompile entries beside them, and Dynamo's lookup checks precompile entries
first but falls back to the cache entries, so any call the artifact does not
cover is still served by the live compile. The load looks like it works while
testing nothing about the artifact (and install() rebinds the resume and
compiled-fn globals those live entries call).

`_build_installed_forward` now refuses, with a `PrecompileError` pointing at a
fresh process, when any code object the package installs onto already has live
cache entries. Those are the codes `CompilePackage.install` targets: the entry's
(resolved through `innermost_fn`, so a `torch.compile`-wrapped attribute is seen
through) and every child frame, resolved through `_lookup_code`. That also
covers a process that torch.compile'd the entry, or only a function it calls,
before loading. Making
the in-process load work would mean evicting the live entries, which belong to
the caller's compile, so refusing is the smaller and safer contract. The
standalone graph-break artifact already refuses the same situation.

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 naming `breaking_helper`; checking only
the entry's code fails the child case.

```
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]>
ghstack-source-id: 28c050c
Pull-Request: #198558
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Round 40 (tb40, head moved), widening the check as suggested:

  • All install targets: the check now runs after CompilePackage(fn, dynamo) and covers exactly the codes install() targets. It iterates package._codes, resolving through _lookup_code(e) when e.code_source is set, and refuses if any has live cache entries, naming the frames. The entry key is package._innermost_fn.__code__, so a torch.compile-wrapped attribute is seen through as well.
  • Docstring: load() now says "wherever any frame it installs onto already has live Dynamo cache entries".
  • Tests: new parametrized test_an_installed_artifact_refuses_frames_compiled_before_load. A fresh process torch.compiles either the entry (calls_breaking_helper) or only the child breaking_helper before load, and expects the refusal naming breaking_helper. Narrowing the check back to fn.__code__ fails the child case. The capturing-process refusal in the round-trip test is unchanged.

@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 34s —— View job


The widened check does what round 40 described, and I found nothing blocking. There is one weak test assertion to tighten, and one gap outside this PR's scope that you should either document or accept.

PR Review: #198558

Summary

_build_installed_forward now refuses to load when any code that install() targets already has live Dynamo cache entries. It resolves targets the same way install() does: innermost_fn for the entry, and _lookup_code for any code_source entry. Resume and compiled-fn entries with install_to_global resolve to freshly deserialized code objects. Those never carry cache entries and get rebound globals, so skipping them is correct. Bypassed entries are included in the check. That is correct too: install() gives them no precompile entries, so live entries on them would serve every call.

Testing

  • test/test_precompile.py:4846: self.assertIn("breaking_helper", out.stdout) passes trivially in the compiled="calls_breaking_helper" case. "calls_breaking_helper" contains "breaking_helper" as a substring. In that case the assertion doesn't check which frames the error names, so a regression that dropped the child frame from the live list would still pass. Match the frame list itself instead. For example, assert "(breaking_helper)" for the child-only case, and for the entry case assert that calls_breaking_helper is in the parenthesized list.

API Design

  • torch/_precompile.py:3320-3322: the refusal applies at load time only, and the docstring should say so. Suppose a process calls load() first and then runs torch.compile on the entry, or on a child such as breaking_helper, with a normal callback. A miss on the installed precompile entries then compiles and adds live cache entries next to them. Later calls through forward that the artifact doesn't cover are served by those entries instead of raising, which is the same false pass this PR closes. The word "already" in the docstring hints at this. Evicting or blocking later compiles is the kind of change the PR description rules out, so accepting this is reasonable. If you do, say it explicitly: for example, "and compiling those frames after load reintroduces the fallback."

Recommendation

Approve once the test assertion is tightened. The docstring note is a one-line clarification.

jlevy pushed a commit to jlevy/metabrowser that referenced this pull request Sep 24, 2026
… does

Review of #243. A cancelled or stale run, a completed run with no
conclusion, and a run whose status was waiting, requested, or empty were
all counted as neutral. github.com's Checks page names a cancelled run
apart ("This job was cancelled", beside "was skipped", "failed", and "This
check was neutral", read on pytorch/pytorch#198558, whose head has 11
cancelled runs by a read-only gh api GET).

checkRunResult and commitStatusResult now decide each check's tone and
label from two tables: a run not yet completed, whatever its status, is
pending; a completed run is success, failure (failure, timed_out,
action_required, startup_failure), cancelled, skipped, stale, or neutral
by its conclusion, and unknown with no conclusion or an undocumented one;
a commit status is success, failure (failure, error), or pending, and
unknown otherwise. Cancelled, stale, and unknown badges are muted like
neutral.

tests/test_github_check_tones.py runs both functions over every documented
status, conclusion, and state and the undocumented cases, and checks that
every tone has a badge color. The CHANGELOG states exactly what is counted.

Refs: mb-5wqg

Co-Authored-By: Claude Opus 5.5 <[email protected]>
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 24, 2026
… captured it

In the capturing process the entry and every frame it compiled still carry the
capture's live Dynamo cache entries. Installing the artifact there adds its
precompile entries beside them, and Dynamo's lookup checks precompile entries
first but falls back to the cache entries, so any call the artifact does not
cover is still served by the live compile. The load looks like it works while
testing nothing about the artifact (and install() rebinds the resume and
compiled-fn globals those live entries call).

`_build_installed_forward` now refuses, with a `PrecompileError` pointing at a
fresh process, when any code object the package installs onto already has live
cache entries. Those are the codes `CompilePackage.install` targets: the entry's
(resolved through `innermost_fn`, so a `torch.compile`-wrapped attribute is seen
through) and every child frame, resolved through `_lookup_code`. That also
covers a process that torch.compile'd the entry, or only a function it calls,
before loading. Making
the in-process load work would mean evicting the live entries, which belong to
the caller's compile, so refusing is the smaller and safer contract. The
standalone graph-break artifact already refuses the same situation.

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 naming `breaking_helper`; checking only
the entry's code fails the child case.

```
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]>
ghstack-source-id: 4c80924
Pull-Request: #198558
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Round 41: this head moved only because #198557 below it changed. The one conflict was the import block, which now takes _FailOnRecompileCallback from #198557 alongside this PR's _lookup_code / _debug_get_cache_entry_list imports. No change to this PR's own logic.

@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.

bobrenjc93 added a commit that referenced this pull request Sep 30, 2026
…/ prepare_runtime

Pull Request resolved: #198789

Part of the set of changes the two-phase precompile workflow needs at pytorch tip, on top of the open precompile stack that ends in #198558. In that workflow, one GPU captures the model against a fake process group of the serving world size, and then every rank replays the saved artifact with recompilation refused. The set was found by running the workflow end to end at tip on a large production FSDP2 recommendation model. This is the last of the changes that carry a capture's compiled kernels in the precompile cache. Earlier changes added the lifecycle (`capture_runtime`, `finalize_cache`, `prepare_runtime`), the frozen static Inductor Triton kernels, the frozen C++ kernels, and (in the previous two PRs) a torch-side transport for Triton's on-disk cache, `torch.compiler._triton_runtime_cache`. This one uses that transport to add kernels launched directly through Triton's JIT (`@triton.jit` / `@triton.autotune` functions that are not compiled by Inductor, for example in fbgemm or custom ops), together with their autotuning results.

**Why precompile needs this.** Inductor's frozen kernels cover what Inductor compiled. A model also launches Triton kernels that Inductor never sees. In a fresh serving process, each of those is JIT-compiled and autotuned on first call. That is serve-time compilation that no precompile cache entry covers, and it happens before any graph runs. Those compiled binaries and autotuning decisions all live in Triton's cache directory, so the capture exports that directory into the precompile cache with the transport from the previous two PRs, and `prepare_runtime` imports it before the application does.

**What.**
- `capture_runtime()`: when Triton is installed (any version with `triton.knobs.cache` and `triton.knobs.autotuning`) and `TRITON_CACHE_DIR` is set, it requires that directory to be dedicated to this capture (everything in it ships) and Triton's autotuning cache to be on (`TRITON_CACHE_AUTOTUNING=1`), both before application imports, otherwise it raises `PrecompileError`. It records the cache root. Without `TRITON_CACHE_DIR`, the check waits for a GPU: a capture that never starts a CUDA or XPU runtime cannot launch a Triton JIT kernel, so it proceeds and ships no Triton runtime cache. If the GPU runtime has already started, `capture_runtime` raises; if the capture starts it, `finalize_cache` raises.
- `finalize_cache()`:
  - rejects a capture whose cache root changed;
  - drains Inductor's pending compiles (Triton's own async compile mode waits for its compiles when its context exits), then exports the runtime cache, keyed by `torch_key` and the CUDA version, as a `triton_runtime` artifact, leaving out Inductor's own kernels (see Size below).
- `prepare_runtime()`: requires the autotuning cache (so the imported decisions are replayed) and imports the artifact into this process's `TRITON_CACHE_DIR`, which must be empty before the first import or already hold this same artifact. A directory that holds a different Triton runtime cache is rejected (strictly by `prepare_runtime`, with a warning by `load`), so each finalized cache needs its own serving directory. Each artifact is imported once per cache root, so the later `precompile.load` does not import it again. Cache loading hydrates `triton_runtime` before the other artifacts (`CacheArtifact.populate_first()`), because graph artifacts can launch Triton kernels while they load.
- Without Triton, or with one too old to have those knobs, nothing changes from the previous change: the Inductor and C++ kernels are still frozen, and JIT kernels compile on first use.
- Consumer-side checks: every import path applies the same checks. The consumer must have Triton installed and a cache directory to import into (the transport requires an explicit `TRITON_CACHE_DIR` unless Triton's default directory already holds an imported bundle), and its autotuning cache must be on, or the imported decisions are ignored. `prepare_runtime` is the strict serving path, so it raises when any check fails. `load` raises under `no_compilation()`; otherwise it logs a warning and continues, and Triton compiles or autotunes those kernels on first use. The same holds when the import itself fails (a failing root lookup, a SHA-256 mismatch, or the transport rejecting the bundle): outside `no_compilation()` it is a warning, so the artifacts populated after this one (graphs, autotune results, frozen Inductor and C++ kernels) still load. A worker that serves non-strictly can skip `prepare_runtime`, because `load` is what installs the frozen Inductor kernels. The SHA-256 of the blob is verified only when it is actually imported, so `load` after `prepare_runtime` does not hash it again.
- Concurrent ranks on one host: the import stages the bundle inside the cache root and renames each entry into place, and a rank that finds an entry already placed validates it instead, so ranks importing into one shared cache directory never see a partly written entry.
- Size: with the explicit `TRITON_CACHE_DIR`, Inductor's own Triton kernels compile into the same directory as the JIT kernels. `inductor_triton` already ships the ones replay needs, so they must not be exported a second time. `TritonBundler.put` sees the Triton cache key of every binary Inductor compiles, including losing autotune candidates. `TritonBundler.read_and_emit` sees every binary Inductor writes from a loaded artifact's bundle, including candidates the loaded code never compiles. The capture scope records both sets of keys, and `finalize_cache` passes them to `export_runtime_cache(exclude=...)`. Measured on an H100 with a synthetic 4-layer transformer (d=1024, bf16) plus one user `@triton.autotune` kernel (not the production run):

  | mode | `triton_runtime` without the exclusion | with it | what is left |
  |---|---|---|---|
  | default | 2.0 MB (1.2 MB of it Inductor kernels, 10 kernels) | 0.77 MB | user kernel 50 KB, its autotune choice, Triton's two native launcher modules 0.7 MB |
  | `max_autotune` | 39.2 MB (38.3 MB of it Inductor kernels, 104 kernels) | 0.77 MB | the same |

  For example, a `max_autotune` model compiles a pointwise kernel with several candidate configs. All of them land in `TRITON_CACHE_DIR`, and only the winner ships, frozen in `inductor_triton`. The fresh-process test replays strictly with the Inductor kernels excluded, which confirms that nothing reads them from the runtime cache.

**No Triton-version dependency.** An earlier version of this change relied on a runtime-cache export/import API in a newer Triton. The transport now lives in torch (previous two PRs) and reads and writes the layout that the pinned Triton's `FileCacheManager` already uses, so this works with the Triton pinned here. The fresh-process test now runs in this tree and passes: capture in one process, then strict replay in another with no Triton cache writes. One limitation comes from Triton itself: it does not write an autotuning cache entry for an autotuner whose configs have a `pre_hook`, so such a kernel is benchmarked again on first use.

**Behaviour change.** Before, `capture_runtime()` required an explicit `TRITON_CACHE_DIR` and `TRITON_CACHE_AUTOTUNING=1` only with a Triton that had the upstream API. Now the transport is always available when Triton is installed, so a capture that uses the GPU needs both settings whenever Triton is installed. A CPU-only capture without `TRITON_CACHE_DIR` behaves as before.

**Example.**

```python
# producer, launched with TRITON_CACHE_DIR=/tmp/capture-17/triton TRITON_CACHE_AUTOTUNING=1
with precompile.capture_runtime():
    with precompile.capture(model, artifact_path="model.py", cache_path="model.cache") as cap:
        cap(batch)  # model calls a @triton.autotune kernel from a custom op
    precompile.finalize_cache(artifact_path="model.py", cache_path="model.cache")

# each serving rank, before importing the application
precompile.prepare_runtime(artifact_path="model.py", cache_path="model.cache")
with precompile.no_compilation():
    out = precompile.load(artifact_path="model.py", cache_path="model.cache")(batch)
# before: the custom op's kernel JIT-compiles and autotunes on first call, and under
#         no_compilation() that is refused
# after:  its binary and autotuning decision come from model.cache
```

**Evidence status.** Three end-to-end runs on the same model. They used the earlier Triton-side version of the transport, which carried the same cache files:
- Full set: the strict replay completed on all 16 ranks for 100 batches with zero serve-time compilation. The first training step was bit-identical to an uncompiled run of the same build, and after 100 steps the loss differences were within run-to-run noise.
- Full set minus the runtime-cache changes: the capture succeeds, but every one of the 16 replay ranks refuses to serve with `precompile.no_compilation() forbids Triton kernel compilation; the supplied artifact or its kernel/autotune cache does not cover this execution`.
- Without these changes and `no_compilation()`: the replay completes, but every rank re-benchmarks 2207 autotuning candidates at serve time. In that run, which also used an older version of the training harness, the first step already differed from the uncompiled run, and after 100 steps one task's loss was 24% worse, well outside run-to-run noise.
ghstack-source-id: 439160368
@exported-using-ghexport

Differential Revision: [D122023198](https://our.internmc.facebook.com/intern/diff/D122023198/)
bobrenjc93 added a commit that referenced this pull request Sep 30, 2026
…/ prepare_runtime

Pull Request resolved: #198789

Part of the set of changes the two-phase precompile workflow needs at pytorch tip, on top of the open precompile stack that ends in #198558. In that workflow, one GPU captures the model against a fake process group of the serving world size, and then every rank replays the saved artifact with recompilation refused. The set was found by running the workflow end to end at tip on a large production FSDP2 recommendation model. This is the last of the changes that carry a capture's compiled kernels in the precompile cache. Earlier changes added the lifecycle (`capture_runtime`, `finalize_cache`, `prepare_runtime`), the frozen static Inductor Triton kernels, the frozen C++ kernels, and (in the previous two PRs) a torch-side transport for Triton's on-disk cache, `torch.compiler._triton_runtime_cache`. This one uses that transport to add kernels launched directly through Triton's JIT (`@triton.jit` / `@triton.autotune` functions that are not compiled by Inductor, for example in fbgemm or custom ops), together with their autotuning results.

**Why precompile needs this.** Inductor's frozen kernels cover what Inductor compiled. A model also launches Triton kernels that Inductor never sees. In a fresh serving process, each of those is JIT-compiled and autotuned on first call. That is serve-time compilation that no precompile cache entry covers, and it happens before any graph runs. Those compiled binaries and autotuning decisions all live in Triton's cache directory, so the capture exports that directory into the precompile cache with the transport from the previous two PRs, and `prepare_runtime` imports it before the application does.

**What.**
- `capture_runtime()`: when Triton is installed (any version with `triton.knobs.cache` and `triton.knobs.autotuning`) and `TRITON_CACHE_DIR` is set, it requires that directory to be dedicated to this capture (everything in it ships) and Triton's autotuning cache to be on (`TRITON_CACHE_AUTOTUNING=1`), both before application imports, otherwise it raises `PrecompileError`. It records the cache root. Without `TRITON_CACHE_DIR`, the check waits for a GPU: a capture that never starts a CUDA or XPU runtime cannot launch a Triton JIT kernel, so it proceeds and ships no Triton runtime cache. If the GPU runtime has already started, `capture_runtime` raises; if the capture starts it, `finalize_cache` raises.
- `finalize_cache()`:
  - rejects a capture whose cache root changed;
  - drains Inductor's pending compiles (Triton's own async compile mode waits for its compiles when its context exits), then exports the runtime cache, keyed by `torch_key` and the CUDA version, as a `triton_runtime` artifact, leaving out Inductor's own kernels (see Size below).
- `prepare_runtime()`: requires the autotuning cache (so the imported decisions are replayed) and imports the artifact into this process's `TRITON_CACHE_DIR`, which must be empty before the first import or already hold this same artifact. A directory that holds a different Triton runtime cache is rejected (strictly by `prepare_runtime`, with a warning by `load`), so each finalized cache needs its own serving directory. Each artifact is imported once per cache root, so the later `precompile.load` does not import it again. Cache loading hydrates `triton_runtime` before the other artifacts (`CacheArtifact.populate_first()`), because graph artifacts can launch Triton kernels while they load.
- Without Triton, or with one too old to have those knobs, nothing changes from the previous change: the Inductor and C++ kernels are still frozen, and JIT kernels compile on first use.
- Consumer-side checks: every import path applies the same checks. The consumer must have Triton installed and a cache directory to import into (the transport requires an explicit `TRITON_CACHE_DIR` unless Triton's default directory already holds an imported bundle), and its autotuning cache must be on, or the imported decisions are ignored. `prepare_runtime` is the strict serving path, so it raises when any check fails. `load` raises under `no_compilation()`; otherwise it logs a warning and continues, and Triton compiles or autotunes those kernels on first use. The same holds when the import itself fails (a failing root lookup, a SHA-256 mismatch, or the transport rejecting the bundle): outside `no_compilation()` it is a warning, so the artifacts populated after this one (graphs, autotune results, frozen Inductor and C++ kernels) still load. A worker that serves non-strictly can skip `prepare_runtime`, because `load` is what installs the frozen Inductor kernels. The SHA-256 of the blob is verified only when it is actually imported, so `load` after `prepare_runtime` does not hash it again.
- Concurrent ranks on one host: the import stages the bundle inside the cache root and renames each entry into place, and a rank that finds an entry already placed validates it instead, so ranks importing into one shared cache directory never see a partly written entry.
- Size: with the explicit `TRITON_CACHE_DIR`, Inductor's own Triton kernels compile into the same directory as the JIT kernels. `inductor_triton` already ships the ones replay needs, so they must not be exported a second time. `TritonBundler.put` sees the Triton cache key of every binary Inductor compiles, including losing autotune candidates. `TritonBundler.read_and_emit` sees every binary Inductor writes from a loaded artifact's bundle, including candidates the loaded code never compiles. The capture scope records both sets of keys, and `finalize_cache` passes them to `export_runtime_cache(exclude=...)`. Measured on an H100 with a synthetic 4-layer transformer (d=1024, bf16) plus one user `@triton.autotune` kernel (not the production run):

  | mode | `triton_runtime` without the exclusion | with it | what is left |
  |---|---|---|---|
  | default | 2.0 MB (1.2 MB of it Inductor kernels, 10 kernels) | 0.77 MB | user kernel 50 KB, its autotune choice, Triton's two native launcher modules 0.7 MB |
  | `max_autotune` | 39.2 MB (38.3 MB of it Inductor kernels, 104 kernels) | 0.77 MB | the same |

  For example, a `max_autotune` model compiles a pointwise kernel with several candidate configs. All of them land in `TRITON_CACHE_DIR`, and only the winner ships, frozen in `inductor_triton`. The fresh-process test replays strictly with the Inductor kernels excluded, which confirms that nothing reads them from the runtime cache.

**No Triton-version dependency.** An earlier version of this change relied on a runtime-cache export/import API in a newer Triton. The transport now lives in torch (previous two PRs) and reads and writes the layout that the pinned Triton's `FileCacheManager` already uses, so this works with the Triton pinned here. The fresh-process test now runs in this tree and passes: capture in one process, then strict replay in another with no Triton cache writes. One limitation comes from Triton itself: it does not write an autotuning cache entry for an autotuner whose configs have a `pre_hook`, so such a kernel is benchmarked again on first use.

**Behaviour change.** Before, `capture_runtime()` required an explicit `TRITON_CACHE_DIR` and `TRITON_CACHE_AUTOTUNING=1` only with a Triton that had the upstream API. Now the transport is always available when Triton is installed, so a capture that uses the GPU needs both settings whenever Triton is installed. A CPU-only capture without `TRITON_CACHE_DIR` behaves as before.

**Example.**

```python
# producer, launched with TRITON_CACHE_DIR=/tmp/capture-17/triton TRITON_CACHE_AUTOTUNING=1
with precompile.capture_runtime():
    with precompile.capture(model, artifact_path="model.py", cache_path="model.cache") as cap:
        cap(batch)  # model calls a @triton.autotune kernel from a custom op
    precompile.finalize_cache(artifact_path="model.py", cache_path="model.cache")

# each serving rank, before importing the application
precompile.prepare_runtime(artifact_path="model.py", cache_path="model.cache")
with precompile.no_compilation():
    out = precompile.load(artifact_path="model.py", cache_path="model.cache")(batch)
# before: the custom op's kernel JIT-compiles and autotunes on first call, and under
#         no_compilation() that is refused
# after:  its binary and autotuning decision come from model.cache
```

**Evidence status.** Three end-to-end runs on the same model. They used the earlier Triton-side version of the transport, which carried the same cache files:
- Full set: the strict replay completed on all 16 ranks for 100 batches with zero serve-time compilation. The first training step was bit-identical to an uncompiled run of the same build, and after 100 steps the loss differences were within run-to-run noise.
- Full set minus the runtime-cache changes: the capture succeeds, but every one of the 16 replay ranks refuses to serve with `precompile.no_compilation() forbids Triton kernel compilation; the supplied artifact or its kernel/autotune cache does not cover this execution`.
- Without these changes and `no_compilation()`: the replay completes, but every rank re-benchmarks 2207 autotuning candidates at serve time. In that run, which also used an older version of the training harness, the first step already differed from the uncompiled run, and after 100 steps one task's loss was 24% worse, well outside run-to-run noise.
ghstack-source-id: 439176828
@exported-using-ghexport

Differential Revision: [D122023198](https://our.internmc.facebook.com/intern/diff/D122023198/)
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

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


I found no issues; the diff hasn't changed since the round-43 review, which was approved.

PR Review: #198558

Summary

When any code that CompilePackage.install targets already has live Dynamo cache entries, _build_installed_forward now refuses the load with a PrecompileError. I found no issues.

I re-checked the diff against origin/gh/bobrenjc93/1490/base. The new commits only bring in base updates. The driver check, the load() docstring and the parametrized test are the same as in tb43.

  • Target list (torch/_precompile_driver.py:797-799). It still matches install() (torch/_dynamo/package.py:1371-1420). It iterates the same self._codes, the entry key comes from innermost_fn, and code_source entries resolve through _lookup_code.
  • Bypassed entries. These are still included in the check, which is correct: install() gives them no precompile entries, so live entries on them would serve every call.
  • Test regex (rf"onto \([^)]*\b{compiled}\b"). It still stops breaking_helper from matching inside calls_breaking_helper.

Recommendation

Approve

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

/easycla

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

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


I found no issues. The PR's own diff is the same as the round-43 version that was already approved; the new commits are base updates.

PR Review: #198558

Summary

If any code that CompilePackage.install targets already has live Dynamo cache entries, _build_installed_forward now refuses the load with a PrecompileError. I compared the diff against origin/gh/bobrenjc93/1490/base. The driver check (torch/_precompile_driver.py:797-808), the load() docstring and the parametrized test match tb43. I found no issues.

Recommendation

Approve

[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 18s —— View job


I found no issues. The PR's own diff matches the round-43 version that was already approved; the new commits only bring in base updates.

PR Review: #198558

Summary

If any code that CompilePackage.install targets already has live Dynamo cache entries, _build_installed_forward now refuses the load with a PrecompileError. I compared the diff against origin/gh/bobrenjc93/1490/base. The driver check (torch/_precompile_driver.py:799-810), the load() docstring and the parametrized test with the whole-word regex all match tb43. I found no issues.

Recommendation

Approve

[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 17s —— View job


I found no issues. The PR's own diff is the same as the round-43 version that was already approved; the new commits only bring in base updates.

PR Review: #198558

Summary

If any code that CompilePackage.install targets already has live Dynamo cache entries, _build_installed_forward now refuses the load with a PrecompileError. I re-read the diff against origin/gh/bobrenjc93/1490/base. The driver check (torch/_precompile_driver.py:800-811), the load() docstring and the parametrized test with the whole-word regex are the same as in tb43. I found no issues.

Recommendation

Approve

[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 19s —— View job


I found no issues. The PR's own diff is the same as the round-43 version that was already approved; the new commits only bring in base updates.

PR Review: #198558

Summary

If any code that CompilePackage.install targets already has live Dynamo cache entries, _build_installed_forward now refuses the load with a PrecompileError. I re-read the diff against origin/gh/bobrenjc93/1490/base. The driver check (torch/_precompile_driver.py:800-811), the load() docstring and the parametrized test with the whole-word regex are all the same as in tb43. I found no issues.

Recommendation

Approve

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

/easycla

[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #198920

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants