Skip to content

[precompile] carry Triton's JIT runtime cache through precompile.capture / load - #198789

Closed
bobrenjc93 wants to merge 72 commits into
gh/bobrenjc93/1517/basefrom
gh/bobrenjc93/1517/head
Closed

bobrenjc93 wants to merge 72 commits into
gh/bobrenjc93/1517/basefrom
gh/bobrenjc93/1517/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Problem. A model also launches Triton kernels that Inductor never compiles (@triton.jit / @triton.autotune functions, for example in fbgemm or custom ops), and in a fresh serving process each of them is JIT-compiled and autotuned on first call, which is serve-time compilation that no precompile cache entry covers and that no_compilation() refuses.

Fix. precompile.capture() gives Triton a fresh private cache directory with its autotuning cache on for the life of its runtime scope and exports that directory into the precompile cache as a triton_runtime artifact at every write, and precompile.load() imports it, before any graph artifact, as part of loading the cache.

Summary. Before this change the precompile cache carried only what Inductor compiled (the frozen static Inductor Triton kernels and the frozen C++ kernels), so kernels launched directly through Triton's JIT, together with their autotuning decisions, were compiled and benchmarked again on every serving rank. On a large production FSDP2 recommendation model that meant every one of 16 strict replay ranks refused to serve, and without no_compilation() every rank re-benchmarked 2207 autotuning candidates at serve time. capture() owns Triton's cache for the life of its runtime scope, so a TRITON_CACHE_DIR the user set is not used inside the block, and every write (save() and block exit) exports that directory through the torch-side transport from the previous two PRs (torch.compiler._triton_runtime_cache) as a triton_runtime artifact. load() imports the artifact once per cache root and before any graph artifact loads, into TRITON_CACHE_DIR only when the import's own rule accepts that directory (a ready marker carrying this bundle's SHA-256 or, unmarked, nothing but this cache's entries, complete or partial, and staging directories) and otherwise into a fresh directory; it checks the SHA-256 and decodes the bundle before it repoints any Triton setting, so a corrupt or incompatible bundle raises with Triton untouched, and it refuses to import inside a capture() block. The contract is to run every Triton JIT kernel and autotuner the serving process needs inside the capture() block and to call load() before anything else on each serving rank compiles; a different cache loaded later in the same process goes into a fresh directory, so JIT kernels of the earlier cache that have not been launched yet compile on first use, and loading the earlier cache again after that imports it into another fresh directory.

Context

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. The changes below this one added the runtime scope capture() opens, 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 carry kernels launched directly through Triton's JIT (@triton.jit / @triton.autotune functions that Inductor does not compile, for example in fbgemm or custom ops), together with their autotuning results.

Two follow-ups sit above this PR and are not part of it: the non-strict fallback when the runtime cache cannot be imported is in #201001, and leaving Inductor's own kernels out of the exported cache is in #201002.

Why precompile needs this

Inductor's frozen kernels cover what Inductor compiled, and 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 binaries and autotuning decisions live in Triton's cache directory, so the capture exports that directory into the precompile cache and load() imports it before any graph artifact loads.

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

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

The capture side

capture() owns Triton's cache for the life of its runtime scope; nothing has to be set in the environment. When the scope opens, _own_triton_cache points Triton at a fresh private directory (knobs.cache.dir), turns Triton's autotuning cache on (knobs.autotuning.cache), and switches cache_results on for autotuners that already exist, since an autotuner fixes it when it is decorated; an autotuner decorated inside the scope keeps cache_results on afterwards, because Triton does not record whether its decorator asked for it. All of that is held on an ExitStack and restored when the last open capture exits, also when the block raises. The stack only becomes the scope's once _own_triton_cache returns, so a failure partway through opening (such as the live-autotuner walk raising) restores the knobs it already overrode (test_capture_scope_restores_triton_cache_settings_when_opening_fails). The restore runs while _capture_lock is held, before _capture is cleared: closing after the lock was released would let a capture opening on another thread in between save this scope's private directory as the settings to restore. The capture() docstring now says so: a TRITON_CACHE_DIR the user set is not used inside the block, and its kernels compile again there.

# _RuntimeCapture.__init__, when the first capture block opens
with contextlib.ExitStack() as settings:
    self.cache_root = _own_triton_cache(settings)  # None without a usable Triton
    self.triton_settings = settings.pop_all()  # only once opening succeeded

# capture_scope(), when the last capture block exits
with _capture_lock:
    owner.captures -= 1
    if owner.captures == 0:
        ...
        try:
            owner.triton_settings.close()  # knobs.cache / knobs.autotuning / cache_results restored
        finally:
            _capture = None

A capture owns Triton's cache only when one of Triton's backend drivers is active. Without one (a CPU-only host) no JIT kernel runs and the interpreter never uses the cache, so _own_triton_cache returns None: the scope leaves Triton's settings alone and exports no triton_runtime artifact.

# _own_triton_cache
if not any(backend.driver.is_active() for backend in backends.values()):
    return None  # CPU-only capture: knobs.cache / knobs.autotuning untouched, no triton_runtime

Triton builds its driver's utility module (cuda_utils, hip_utils) into the cache directory once per process, so when the producer already loaded it, the scope copies the loaded build into the new directory; otherwise the export would lack it and the serving process would build it again. The copy is skipped when the loaded module's file no longer exists on disk (a process that loaded it from a since-deleted temporary directory crashed here before); a serving host then rebuilds it, as it does when the producer never loaded one.

module = getattr(loaded, "__file__", None)
if module is not None and (module := Path(module)).is_file():
    ...  # copy into the scope's directory

Every write (save() and block exit) goes through freeze_runtime_cache, which checks that Triton's cache directory did not change during the capture, and exports the directory, keyed by torch_key and the CUDA version, as a triton_runtime artifact next to inductor_triton and the C++ kernels. Because the export happens at the write, an entry Triton writes late in the block still ships.

# Triton's cache directory moved inside the block
with precompile.capture(fn, ...) as cap:
    cap(x)
    triton.knobs.cache.dir = some_other_directory
# now: PrecompileError "... could not freeze ...", caused by
#      RuntimeError("Triton's cache directory changed during the capture")

The contract: launch every Triton JIT kernel inside the block, load first on each rank

Only what runs inside the block is carried, so launch every Triton JIT kernel and autotuner the serving process needs inside it. A JIT kernel or autotuner already used before the block reuses what it compiled or tuned then, which lives in the old directory and is not carried. Triton 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 in the serving process. The capture() docstring states the same contract.

_scale_kernel[grid](x, out, n)        # first launch before the block: not carried

with precompile.capture(fn, ...) as cap:
    cap(*inputs)                      # first launch in here: binary and tuning decision carried

On the serving side, load() is the only call: on each rank, call it before anything else in the process compiles, so the imported binaries and decisions are in place before any Triton kernel would compile.

The serving side

load() imports the artifact as it populates the cache (TritonRuntimeCacheArtifact.populate_cache). The import goes into TRITON_CACHE_DIR if the import accepts it, i.e. its ready marker carries this bundle's SHA-256 or, unmarked, it holds nothing but this cache's entries, complete or partial, and the staging directory of an import that is running or was killed, and otherwise into a fresh private directory that Triton uses from then on (Inductor points TRITON_CACHE_DIR at its shared cache once it compiles, so it is often not empty). The check is the import's own acceptance rule, so a directory a killed rank left half-imported is reused rather than abandoned, a directory this cache was already imported into is reused even after other kernels were compiled into it (a restarted process or a later-starting local rank keeps the warm cache, and the extra entries are content-addressed), and an unmarked one with an unrelated entry is never handed to an import that would reject it. A directory with a ready marker counts only when the marker carries this bundle's SHA-256, so a host that keeps TRITON_CACHE_DIR across a model-version rollout imports the new bundle into a fresh directory instead of having it rejected. Triton's autotuning cache is turned on for the rest of the process, for existing autotuners too, so the imported decisions are reused instead of re-benchmarked. Cache loading hydrates triton_runtime before the other artifacts (CacheArtifact.populate_first()), because graph artifacts can launch Triton kernels while they load.

# _importable(root, digest, keys): may the import go into this directory?
# keys are the entry names the decoded bundle holds.
if marker.exists():
    return not marker.is_symlink() and marker.is_file() and marker.read_text() == digest
return all(entry.name in keys or entry.name.startswith(_READY) for entry in root.iterdir())

# CacheArtifactManager.populate_caches
ordered = sorted(chain(*artifacts.values()), key=lambda artifact: not artifact.populate_first())
# TritonRuntimeCacheArtifact.populate_first() -> True; every other artifact -> False

Each artifact is imported once per cache root, and the repeat check runs before any directory setup, so a second load() of the same cache while Triton still uses the directory it was imported into neither imports nor hashes it again and leaves TRITON_CACHE_DIR and the autotuners alone.

# TritonRuntimeCacheArtifact.import_into_triton, in order
if _active_capture() is not None:
    raise RuntimeError("... it cannot be imported inside a precompile.capture block")
if (self.key, str(cache.runtime_cache_root())) in _imported_triton_runtime:
    return                                    # repeat load, same root: no directory setup
# Validate before _serving_triton_root repoints Triton for the process.
if hashlib.sha256(self.content).hexdigest() != self.key:
    raise RuntimeError("Corrupt Triton runtime-cache artifact")
cache._decode(self.content, context)          # format, ABI/build identity, member digests
root = _serving_triton_root(cache, self.key)  # pick or create the directory

Validation runs before _serving_triton_root repoints TRITON_CACHE_DIR or turns the autotuning cache on. load() checks the artifact's SHA-256 and runs the transport's pure _decode, which checks the bundle's format, its ABI and build compatibility, and every member digest without writing anything, so a corrupt or incompatible bundle raises and leaves the process's Triton settings unchanged. The extra decode costs about 3 ms on a 4 MB bundle.

A load() inside a precompile.capture block refuses to import, because the capture owns Triton's cache directory there; Triton's cache directory is left as it was and nothing is imported.

A later, different cache, and strict failures

A different cache loaded later in the same process does not raise: it goes into a fresh directory that Triton uses from then on, and the first import is left untouched. The limitation is that Triton then compiles out of the new directory only, so JIT kernels of the earlier cache that have not been launched yet are not found there and compile on first use. Kernels the earlier cache already launched keep their loaded binaries. Once such a load has repointed Triton, loading the first cache again imports it into a fresh directory, because the earlier directory also holds kernels other caches wrote after the import (Inductor writes its own kernel files into TRITON_CACHE_DIR while it is active).

precompile.load(artifact_path=a1, cache_path=c1)  # imports into TRITON_CACHE_DIR
precompile.load(artifact_path=a2, cache_path=c2)  # different bundle: fresh directory,
                                                  # TRITON_CACHE_DIR now points at it
# a c1 JIT kernel first launched after this point compiles on first use
precompile.load(artifact_path=a1, cache_path=c1)  # c1 again: imported into another fresh directory

A missing Triton, a failed root lookup, a SHA-256 mismatch, or the transport rejecting the bundle raises. Under no_compilation() a strict load() surfaces these as a PrecompileError ("strict precompile.load could not hydrate the compiled cache") with the cause chained.

with precompile.no_compilation():
    precompile.load(artifact_path=a, cache_path=c)
# PrecompileError "strict precompile.load could not hydrate the compiled cache", caused by
#   no usable Triton:   "The precompile cache contains a Triton runtime cache, but
#                        Triton is not installed or too old to import one"
#   inside a capture:   "... but it cannot be imported inside a precompile.capture block"
#   root lookup fails:  "... but Triton has no cache directory to import it into (...)"
#   digest != key:      "Corrupt Triton runtime-cache artifact"
#   other build/ABI:    "Incompatible Triton runtime-cache ABI or build identity"
# after the digest and incompatibility rejections, TRITON_CACHE_DIR and the autotuning cache setting are as they were

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.

No Triton-version dependency, and no Triton

The transport 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 captures in one process and replays strictly in another with no Triton cache writes.

Without Triton, or with one too old to have triton.knobs.cache and triton.knobs.autotuning, nothing changes from the previous change: the Inductor and C++ kernels are still frozen, and JIT kernels compile on first use.

_runtime_cache._triton_runtime_cache()
# Triton with knobs.autotuning and knobs.cache.manager_class -> torch.compiler._triton_runtime_cache
# otherwise -> None: the scope owns no Triton directory and no triton_runtime artifact is written
# the same holds when Triton is usable but no backend driver is active (CPU-only capture)

Evidence status

Three end-to-end runs on the same model. They ran with a Triton-side transport that carried the same cache files.

run outcome
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

Tests

claim test
a moved Triton cache directory is refused at write time test_capture_refuses_changed_triton_cache_dir
an entry written to Triton's cache late in the block ships, and load() places it in the consumer's directory test_capture_ships_late_native_dependency
the real capture scope restores Triton's cache directory and autotuning cache on exit, also when the block raises test_capture_scope_restores_triton_cache_settings
a capture scope that fails while opening restores the Triton knobs it already overrode test_capture_scope_restores_triton_cache_settings_when_opening_fails
a capture does not crash when the driver utility module Triton loaded was since deleted from disk test_capture_scope_skips_deleted_driver_module
a capture with no active Triton backend leaves Triton's settings alone and owns no cache directory test_capture_scope_leaves_triton_alone_without_active_backend
a second, different cache imports into a fresh directory (whose ready marker carries its SHA-256) without touching the first test_one_triton_runtime_cache_per_directory
the directory choice follows the import's acceptance rule: partial, staging-only and already-imported directories are reused, an unmarked one with an unrelated entry or one with another cache's marker is not test_triton_root_is_importable_under_the_import_rule
a repeat load of the same cache, while Triton still uses its directory, skips the directory setup and imports once test_repeat_triton_runtime_import_skips_directory_setup
a load inside a capture block refuses to import and leaves Triton's cache directory alone test_triton_runtime_import_refused_inside_capture
triton_runtime hydrates before graph artifacts test_triton_runtime_cache_hydrates_before_graph_artifacts
the import happens once per consumer root and turns the autotuning cache on test_triton_runtime_cache_round_trips_once_per_consumer
a SHA-256 mismatch is rejected before any import, with TRITON_CACHE_DIR and the autotuning cache setting unchanged test_strict_import_rejects_corrupt_triton_runtime_cache
a bundle exported for another build identity is rejected as incompatible, with TRITON_CACHE_DIR and the autotuning cache setting unchanged test_strict_import_rejects_incompatible_triton_runtime_cache
a missing Triton or a failed root lookup makes a strict load() raise "could not hydrate", with the reason chained test_unimportable_triton_runtime_cache
the transport needs Triton's cache and autotuning knobs test_triton_runtime_cache_needs_triton_cache_knobs
capture, then strict replay in a fresh process with no Triton cache writes and neither TRITON_CACHE_DIR nor TRITON_CACHE_AUTOTUNING set test_strict_replay_in_fresh_process (_RUNTIME_CACHE_DRIVER)

Test Plan:

python test/test_precompile.py
python test/test_precompile.py -k triton -k runtime -k Runtime
lintrunner torch/compiler/_runtime_cache.py torch/_precompile.py test/test_precompile.py

test_capture_refuses_changed_triton_cache_dir pins the refusal of a moved cache directory, test_capture_ships_late_native_dependency that an entry written to Triton's cache late in the block ships, and test_one_triton_runtime_cache_per_directory that a second, different cache imports into a fresh directory without touching the first. test_triton_root_is_importable_under_the_import_rule pins that the directory choice follows the import's own acceptance rule, so a partly imported or staging-only directory is reused, as is one this cache was imported into whatever was compiled into it since, and an unmarked one with an unrelated entry or one with another cache's marker is not. test_repeat_triton_runtime_import_skips_directory_setup pins that a repeat load of the same cache skips the directory setup, test_triton_runtime_import_refused_inside_capture the refusal inside a capture block, test_capture_scope_restores_triton_cache_settings that the real capture scope restores Triton's cache directory and autotuning cache on exit, also when the block raises, and test_capture_scope_skips_deleted_driver_module that a capture does not crash when the driver utility module Triton loaded was since deleted from disk (a capture copies the loaded module into its directory, and a process that loaded it from a temporary directory crashed there before). test_capture_scope_leaves_triton_alone_without_active_backend pins that a capture with no active Triton backend leaves Triton's settings alone. test_triton_runtime_cache_hydrates_before_graph_artifacts, test_triton_runtime_cache_round_trips_once_per_consumer, test_strict_import_rejects_corrupt_triton_runtime_cache and test_strict_import_rejects_incompatible_triton_runtime_cache (both also checking that TRITON_CACHE_DIR and the autotuning cache setting are unchanged after the rejection), test_unimportable_triton_runtime_cache and test_triton_runtime_cache_needs_triton_cache_knobs pin the serving side, and the fresh-process test_strict_replay_in_fresh_process replays strictly with no Triton cache writes.

This change was authored with an AI assistant (Claude Code).

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

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 27, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 3da7cbb with merge base d45baa0 (image):
💚 Looks good so far! There are no failures yet. 💚

🟡 GREEN LIGHT - PR requires human review:

  • Triviality
    • New feature: torch/compiler/_runtime_cache.py adds TritonRuntimeCacheArtifact plus capture-side _own_triton_cache and serve-side _serving_triton_root, which fits no trivial class
    • CacheArtifactManager.populate_caches in torch/compiler/_cache.py now orders every artifact by a new populate_first() hook
  • User-facing expectations
    • capture() docstring in torch/_precompile.py now says a user-set TRITON_CACHE_DIR is ignored inside the block, so kernels compile again there
    • _serving_triton_root rewrites os.environ["TRITON_CACHE_DIR"] and sets knobs.autotuning.cache = True for the rest of the process
  • Scope
    • Process-global Triton state, autotuner cache_results mutation via gc.get_objects(), and atexit temp dirs need a human to judge them
    • Roughly 600 new test lines in test/test_precompile.py, including a subprocess fresh-process replay test

reason: not_trivial
Reviewed commit: 3da7cbb

Inference job

🐛 Report a wrong verdict

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

@bobrenjc93
bobrenjc93 marked this pull request as draft September 27, 2026 13:14
@bobrenjc93 bobrenjc93 changed the title [precompile] runtime cache: capture_runtime / finalize_cache / prepare_runtime [no-ci] [precompile] runtime cache: capture_runtime / finalize_cache / prepare_runtime Sep 27, 2026
@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Sep 27, 2026
@bobrenjc93 bobrenjc93 added the topic: not user facing topic category label Sep 27, 2026
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 27, 2026
…e_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. With the full set, the replay completed on all 16 ranks for 100 batches with zero serve-time compilation. Its losses matched an uncompiled run of the same build: the first step was bit-identical, and after 100 steps the differences were within run-to-run noise.

**What.** Under `no_compilation()`, the serving process must get every kernel it launches from the artifact. Inductor's graph cache alone does not do that. Kernels that were not statically launched, and C++ kernels, are compiled again on first use.

This adds `torch.compiler._runtime_cache` and three APIs in `torch.compiler.precompile`:
- `capture_runtime()` records, during capture, the Triton kernels Inductor launches (including late autotuning winners) and the C++ kernel binaries.
- `finalize_cache()` seals the capture. It freezes the static Triton launchers and C++ binaries into the cache, reports any Triton source it cannot export, and keeps the cache and policy intact on failure.
- `prepare_runtime()` runs in the serving process before graph artifacts load. It streams and verifies the finalized cache and hydrates the kernels, mapping a shared cache to the current device.

Kernels launched directly through Triton's JIT are captured too when Triton exposes `triton.runtime.cache.export_runtime_cache`. Without that, they compile again on first use, and `no_compilation()` reports it.

**Example.**

```python
import torch
from torch.compiler import precompile

# Capture process
with precompile.capture_runtime():
    with precompile.capture(model, artifact_path="model.py",
                            cache_path="model.cache") as cap:
        cap(batch)
    precompile.finalize_cache(artifact_path="model.py", cache_path="model.cache")

# Serving process, before the model is built
precompile.prepare_runtime(artifact_path="model.py", cache_path="model.cache")
runnable = precompile.load("model.py", "model.cache")
with precompile.no_compilation():
    out = runnable(batch)  # every kernel it launches comes from model.cache
```

**Why it's needed.** `no_compilation()`, from the previous change, turns every serve-time kernel compile into an error. At tip, a replay of the model's artifact compiles, misses and autotunes Triton kernels, and compiles C++ kernels (counts below). Under the policy, each of those would raise unless the kernels ship in the artifact, and this change is what ships them.

**Evidence status.** Three end-to-end runs on the same model:
- Full set, including this change: the strict replay completed on all 16 ranks 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 only this change: 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 this change and the previous one: 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. Shipping the capture-time kernels makes the replay run the same kernels as the capture.
ghstack-source-id: 437216894
@exported-using-ghexport

Differential Revision: [D122023198](https://our.internmc.facebook.com/intern/diff/D122023198/)
@bobrenjc93 bobrenjc93 changed the title [no-ci] [precompile] runtime cache: capture_runtime / finalize_cache / prepare_runtime [precompile] runtime cache: capture_runtime / finalize_cache / prepare_runtime Sep 27, 2026
bobrenjc93 added a commit that referenced this pull request Sep 27, 2026
…e_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. With the full set, the replay completed on all 16 ranks for 100 batches with zero serve-time compilation. Its losses matched an uncompiled run of the same build: the first step was bit-identical, and after 100 steps the differences were within run-to-run noise.

**What.** Under `no_compilation()`, the serving process must get every kernel it launches from the artifact. Inductor's graph cache alone does not do that. Kernels that were not statically launched, and C++ kernels, are compiled again on first use.

This adds `torch.compiler._runtime_cache` and three APIs in `torch.compiler.precompile`:
- `capture_runtime()` records, during capture, the Triton kernels Inductor launches (including late autotuning winners) and the C++ kernel binaries.
- `finalize_cache()` seals the capture. It freezes the static Triton launchers and C++ binaries into the cache, reports any Triton source it cannot export, and keeps the cache and policy intact on failure.
- `prepare_runtime()` runs in the serving process before graph artifacts load. It streams and verifies the finalized cache and hydrates the kernels, mapping a shared cache to the current device.

Kernels launched directly through Triton's JIT are captured too when Triton exposes `triton.runtime.cache.export_runtime_cache`. Without that, they compile again on first use, and `no_compilation()` reports it.

**Example.**

```python
import torch
from torch.compiler import precompile

# Capture process
with precompile.capture_runtime():
    with precompile.capture(model, artifact_path="model.py",
                            cache_path="model.cache") as cap:
        cap(batch)
    precompile.finalize_cache(artifact_path="model.py", cache_path="model.cache")

# Serving process, before the model is built
precompile.prepare_runtime(artifact_path="model.py", cache_path="model.cache")
runnable = precompile.load("model.py", "model.cache")
with precompile.no_compilation():
    out = runnable(batch)  # every kernel it launches comes from model.cache
```

**Why it's needed.** `no_compilation()`, from the previous change, turns every serve-time kernel compile into an error. At tip, a replay of the model's artifact compiles, misses and autotunes Triton kernels, and compiles C++ kernels (counts below). Under the policy, each of those would raise unless the kernels ship in the artifact, and this change is what ships them.

**Evidence status.** Three end-to-end runs on the same model:
- Full set, including this change: the strict replay completed on all 16 ranks 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 only this change: 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 this change and the previous one: 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. Shipping the capture-time kernels makes the replay run the same kernels as the capture.
ghstack-source-id: 437216894
@exported-using-ghexport

Differential Revision: [D122023198](https://our.internmc.facebook.com/intern/diff/D122023198/)
@bobrenjc93 bobrenjc93 changed the title [precompile] runtime cache: capture_runtime / finalize_cache / prepare_runtime [no-ci] [precompile] runtime cache: capture_runtime / finalize_cache / prepare_runtime Sep 27, 2026
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 27, 2026
…e_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. With the full set, the replay completed on all 16 ranks for 100 batches with zero serve-time compilation. Its losses matched an uncompiled run of the same build: the first step was bit-identical, and after 100 steps the differences were within run-to-run noise.

**What.** Under `no_compilation()`, the serving process must get every kernel it launches from the artifact. Inductor's graph cache alone does not do that. Kernels that were not statically launched, and C++ kernels, are compiled again on first use.

This adds `torch.compiler._runtime_cache` and three APIs in `torch.compiler.precompile`:
- `capture_runtime()` records, during capture, the Triton kernels Inductor launches (including late autotuning winners) and the C++ kernel binaries.
- `finalize_cache()` seals the capture. It freezes the static Triton launchers and C++ binaries into the cache, reports any Triton source it cannot export, and keeps the cache and policy intact on failure.
- `prepare_runtime()` runs in the serving process before graph artifacts load. It streams and verifies the finalized cache and hydrates the kernels, mapping a shared cache to the current device.

Kernels launched directly through Triton's JIT are captured too when Triton exposes `triton.runtime.cache.export_runtime_cache`. Without that, they compile again on first use, and `no_compilation()` reports it.

**Example.**

```python
import torch
from torch.compiler import precompile

# Capture process
with precompile.capture_runtime():
    with precompile.capture(model, artifact_path="model.py",
                            cache_path="model.cache") as cap:
        cap(batch)
    precompile.finalize_cache(artifact_path="model.py", cache_path="model.cache")

# Serving process, before the model is built
precompile.prepare_runtime(artifact_path="model.py", cache_path="model.cache")
runnable = precompile.load("model.py", "model.cache")
with precompile.no_compilation():
    out = runnable(batch)  # every kernel it launches comes from model.cache
```

**Why it's needed.** `no_compilation()`, from the previous change, turns every serve-time kernel compile into an error. At tip, a replay of the model's artifact compiles, misses and autotunes Triton kernels, and compiles C++ kernels (counts below). Under the policy, each of those would raise unless the kernels ship in the artifact, and this change is what ships them.

**Evidence status.** Three end-to-end runs on the same model:
- Full set, including this change: the strict replay completed on all 16 ranks 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 only this change: 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 this change and the previous one: 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. Shipping the capture-time kernels makes the replay run the same kernels as the capture.
ghstack-source-id: 437241010
@exported-using-ghexport

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

Copy link
Copy Markdown
Contributor Author

@claude review this PR

@claude

claude Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

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


Approve. Both docstring fixes from the last round are in at this head, and a re-read of the diff found no new defects.

Full review

PR Review: #198789

Summary

This PR makes capture() give Triton a private cache directory, with the autotuning cache on, for its runtime scope, and export that directory as a triton_runtime artifact on every write. load() imports the artifact before any graph artifact. It changes 4 files, +907/-19, and no REVIEW.md applies. Triton isn't installed on this runner, so I checked the knob and environment interaction by reading the code and did not run it.

What changed since the last round:

  • _serving_triton_root docstring: it now states the same rule _importable uses. TRITON_CACHE_DIR is accepted if its ready marker carries this bundle's digest, or, if it has no marker, if it holds only this cache's entries and marker-prefixed staging entries.
  • capture() docstring: the Triton paragraph is rewrapped to the width of the surrounding lines.

No issues found.

Recommendation

Approve

Nothing blocks merge. As in earlier rounds, two things depend on the PRs above this one, so land the three together:

[ghstack-poisoned]
[ghstack-poisoned]
This was referenced Oct 14, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #200836

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #200551

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: inductor topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants