Repository navigation
[precompile] carry Triton's JIT runtime cache through precompile.capture / load - #198789
bobrenjc93 wants to merge 72 commits into
Conversation
🔗 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 FailuresAs of commit 3da7cbb with merge base d45baa0 ( 🟡 GREEN LIGHT - PR requires human review:
reason: This comment was automatically generated by Dr. CI and updates every 15 minutes. |
…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/)
…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/)
…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/)
|
@claude review this PR |
|
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 reviewPR Review: #198789SummaryThis PR makes What changed since the last round:
No issues found. RecommendationApprove 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]
|
Starting merge as part of PR stack under #200836 |
|
Starting merge as part of PR stack under #200551 |
Stack from ghstack (oldest at bottom):
Problem. A model also launches Triton kernels that Inductor never compiles (
@triton.jit/@triton.autotunefunctions, 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 thatno_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 atriton_runtimeartifact at every write, andprecompile.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 aTRITON_CACHE_DIRthe 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 atriton_runtimeartifact.load()imports the artifact once per cache root and before any graph artifact loads, intoTRITON_CACHE_DIRonly 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 acapture()block. The contract is to run every Triton JIT kernel and autotuner the serving process needs inside thecapture()block and to callload()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.autotunefunctions 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.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_cachepoints Triton at a fresh private directory (knobs.cache.dir), turns Triton's autotuning cache on (knobs.autotuning.cache), and switchescache_resultson for autotuners that already exist, since an autotuner fixes it when it is decorated; an autotuner decorated inside the scope keepscache_resultson afterwards, because Triton does not record whether its decorator asked for it. All of that is held on anExitStackand restored when the last open capture exits, also when the block raises. The stack only becomes the scope's once_own_triton_cachereturns, 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_lockis held, before_captureis 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. Thecapture()docstring now says so: aTRITON_CACHE_DIRthe user set is not used inside the block, and its kernels compile again there.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_cachereturnsNone: the scope leaves Triton's settings alone and exports notriton_runtimeartifact.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.Every write (
save()and block exit) goes throughfreeze_runtime_cache, which checks that Triton's cache directory did not change during the capture, and exports the directory, keyed bytorch_keyand the CUDA version, as atriton_runtimeartifact next toinductor_tritonand the C++ kernels. Because the export happens at the write, an entry Triton writes late in the block still ships.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. Thecapture()docstring states the same contract.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 intoTRITON_CACHE_DIRif 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 pointsTRITON_CACHE_DIRat 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 keepsTRITON_CACHE_DIRacross 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 hydratestriton_runtimebefore the other artifacts (CacheArtifact.populate_first()), because graph artifacts can launch Triton kernels while they load.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 leavesTRITON_CACHE_DIRand the autotuners alone.Validation runs before
_serving_triton_rootrepointsTRITON_CACHE_DIRor 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 aprecompile.captureblock 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_DIRwhile it is active).A missing Triton, a failed root lookup, a SHA-256 mismatch, or the transport rejecting the bundle raises. Under
no_compilation()a strictload()surfaces these as aPrecompileError("strict precompile.load could not hydrate the compiled cache") with the cause chained.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
FileCacheManageralready 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.cacheandtriton.knobs.autotuning, nothing changes from the previous change: the Inductor and C++ kernels are still frozen, and JIT kernels compile on first use.Evidence status
Three end-to-end runs on the same model. They ran with a Triton-side transport that carried the same cache files.
precompile.no_compilation() forbids Triton kernel compilation; the supplied artifact or its kernel/autotune cache does not cover this executionno_compilation()Tests
test_capture_refuses_changed_triton_cache_dirload()places it in the consumer's directorytest_capture_ships_late_native_dependencytest_capture_scope_restores_triton_cache_settingstest_capture_scope_restores_triton_cache_settings_when_opening_failstest_capture_scope_skips_deleted_driver_moduletest_capture_scope_leaves_triton_alone_without_active_backendtest_one_triton_runtime_cache_per_directorytest_triton_root_is_importable_under_the_import_ruletest_repeat_triton_runtime_import_skips_directory_setuptest_triton_runtime_import_refused_inside_capturetriton_runtimehydrates before graph artifactstest_triton_runtime_cache_hydrates_before_graph_artifactstest_triton_runtime_cache_round_trips_once_per_consumerTRITON_CACHE_DIRand the autotuning cache setting unchangedtest_strict_import_rejects_corrupt_triton_runtime_cacheTRITON_CACHE_DIRand the autotuning cache setting unchangedtest_strict_import_rejects_incompatible_triton_runtime_cacheload()raise "could not hydrate", with the reason chainedtest_unimportable_triton_runtime_cachetest_triton_runtime_cache_needs_triton_cache_knobsTRITON_CACHE_DIRnorTRITON_CACHE_AUTOTUNINGsettest_strict_replay_in_fresh_process(_RUNTIME_CACHE_DRIVER)Test Plan:
test_capture_refuses_changed_triton_cache_dirpins the refusal of a moved cache directory,test_capture_ships_late_native_dependencythat an entry written to Triton's cache late in the block ships, andtest_one_triton_runtime_cache_per_directorythat a second, different cache imports into a fresh directory without touching the first.test_triton_root_is_importable_under_the_import_rulepins 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_setuppins that a repeat load of the same cache skips the directory setup,test_triton_runtime_import_refused_inside_capturethe refusal inside a capture block,test_capture_scope_restores_triton_cache_settingsthat the real capture scope restores Triton's cache directory and autotuning cache on exit, also when the block raises, andtest_capture_scope_skips_deleted_driver_modulethat 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_backendpins 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_cacheandtest_strict_import_rejects_incompatible_triton_runtime_cache(both also checking thatTRITON_CACHE_DIRand the autotuning cache setting are unchanged after the rejection),test_unimportable_triton_runtime_cacheandtest_triton_runtime_cache_needs_triton_cache_knobspin the serving side, and the fresh-processtest_strict_replay_in_fresh_processreplays 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