AI Infra · TPU v7
95 Minutes to 14: Cold Compile Optimization for Hy4 on TPU v7
TPU programs are compiled per input shape, and with an empty cache Hy4 took 95 minutes to start on TPU v7. Our analysis found that most of the cost was not in the compiler but in the computation graphs fed to it: one grew linearly with the bucket, the other with the number of ranks. After removing both multipliers and letting ranks replay each other's compiled artifacts, cold compile dropped to about 14 minutes. This post covers the analysis, the changes, the gains, the validation before production, and where these methods apply.
TL;DR
- Problem: TPU programs are compiled per input shape, and the compile cache is often invalidated by changes to config, image or version. Each Hy4 cold compile took 95.1 minutes, during which nothing could be served.
- Cause: the chunk loop in the sparse MLA kernel was unrolled at trace time, so program length grew linearly with the token bucket; the attention sink was written into the program as a closure constant, so the same shape was compiled into a separate program per rank.
- Solution: switch the chunk loop to
fori_loop, make the attention sink a runtime input, replay compiled artifacts between ranks, and add several compile-time optimizations. - Gain: cold compile went from 95.1 minutes to about 14 (mnbt 2048, two measurements at 819 s and 842 s). On GLM-5.3, toggling only the same "bucket splitting + replay" switch (the two contributions cannot be separated) cut the time from weights loaded to service ready from 959 s to 409 s. All three rounds of accuracy evaluation were above the release threshold.
Background#
Hy4-preview is a MoE model from Tencent Hunyuan. Its attention is DSA sparse attention (sparse MLA), and decoding uses MTP speculative decoding. We deploy it on TPU v7 with vLLM + vllm-torchtpu: TP16 across two hosts with 8 ranks each, and max_num_batched_tokens (mnbt below) set to 2048.
TPU programs are compiled per input shape. vLLM divides inputs into several buckets by token count. At startup it has to compile the main model for every bucket, then the sampling, draft model and speculative decoding warmup programs, and it only opens the service once all of these are done. Compiled results are cached on shared storage, and startup is fast when the cache is complete (warm start). The problem is that the cache is invalidated often: a change to config that enters the cache key, a new image, or a version rollback all force a compile from scratch (cold compile). During tuning this happened several times a day, and each Hy4 cold compile took 95.1 minutes, during which nothing could be served.
Our goal was to bring cold compile under 20 minutes. Throughout this post, cold compile time means the time from pod creation to service ready in the rank 0 log, with an empty cache. Numbers without a run count are single measurements, and conclusions drawn from reading code or from extrapolation are marked "inference".
Problem analysis: where the time goes#
Measuring directly on the production configuration costs an hour and a half per compile, which is too slow to iterate. We built a 4-layer proxy model with fake weights on a spot node: three cold compiles of the same configuration averaged 1728 s with a 1.8% standard deviation, which served as our noise baseline. We then measured 8 and 16 layers, extrapolated to 78 layers and compared with production logs; the error was around ±30%.
| Cost item | Mechanism | Magnitude | Evidence |
|---|---|---|---|
| Unrolled sparse MLA chunk loop | The Python loop in the kernel that chunks by 64 tokens is unrolled as-is at trace time, so program length grows linearly with the bucket | 74–93% of each worker's compile work (78 layers, mnbt 8192) | Extrapolation; causal experiment: raising the chunk size from 64 to 512 cut main-model precompile time on the proxy model by 66%, about 75–85% of the predicted reduction |
| Attention sink as a closure constant | The kernel writes this rank's attention sink into the program as a closure constant, so the program fingerprint differs by rank | 12–14 programs under the same shape key; on each host, 7 of the 8 are redundant | Counting program files in the cache directory and comparing their contents with strings |
| Critical path outside compilation | Weight loading, profile run, KV initialization, draft model, speculative decoding warmup | 6–7 minutes | Production logs |
Neither of the two main costs comes from the compiler itself being slow. In both cases the computation graph sent to the compiler was multiplied: one by bucket, the other by rank count. With both removed, wall time is roughly one compile of the largest bucket plus the six or seven minutes outside compilation, for a theoretical floor of about 11 minutes (inference).
Solution#
Most changes are implemented as switches in vllm-torchtpu that are off by default. Our deployment recipe turns them on through environment variables, so other deployments are unaffected. Every change went through two checks: bitwise comparison at the kernel level (fori, unroll, bitwise indexing and the single-switch dispatcher are all bitwise equal to the original implementation), and measurement of runtime overhead.
1. Switch the chunk loop to fori_loop#
Problem. The unrolled Python loop makes program length proportional to T/64, so compile work balloons for large buckets.
Approach. Switch to fori_loop, so the loop stays a loop in the compiled program. Plain fori (unroll factor 1) has a runtime cost: in kernel-level microbenchmarks the decode kernel is 10–18% slower and mixed steps are 30–34% slower. With an unroll factor of 16, the mixed-step cost drops to 1.1–2.1%, but part of the compile work for large buckets comes back. We prioritized runtime performance and chose an unroll factor of 16.
2. Make the attention sink a runtime input#
Problem. Each rank has a different attention sink value. Once it is written into the program, every shape has to be compiled 8 times per host, and the two hosts cannot reuse each other's programs either.
Approach. Pass the attention sink into the kernel as a tensor input.
Effect. One program per shape, shared by all 16 ranks. With items 1 and 2 shipped together, the first cold compile on the production topology (mnbt 8192) took 52.3 minutes.
This item applies broadly to anyone writing custom kernels: whenever a per-rank value (attention sink, offsets derived from the rank id, sharding-dependent constants) ends up in a closure, compile work scales with the rank count. The simplest check is to count how many programs sit under the same shape key in the cache directory.
3. Replay compiled artifacts between ranks#
Problem. vllm-torchtpu's parallel precompile assigns buckets to different ranks to compile, while the other ranks wait to hit the shared XLA cache. But even after a hit, each bucket still takes about 40 seconds.
Approach. We adopted the peer-artifact replay scheme from upstream vllm-torchtpu: the full compiled artifact produced by one rank is checked against the graph fingerprint, and other ranks then load it directly (replay). The cache lives on Lustre shared by both hosts. We later switched to the upstream claim-file mechanism (exclusive create, heartbeat and takeover on expiry), which no longer depends on a barrier where all ranks wait at the same time.
Two points need attention when using replay:
- The graph fingerprint does not cover closure constants. From the code, this scheme's fingerprint covers only the FX graph code and small constants, not the constants inside custom-op closures (from reading code, not directly observed at runtime). If the graph still holds per-rank constants such as the attention sink, replay could load another rank's program. On Hy4 we ran a control with replay off and a full cold compile (1812 s): outputs on 40 long prompts were identical to the replay-on run, 40/40, and GSM8K was 94.84; the same control on GLM-5.3 was also 40/40. When applying this to other models, either check closure constants first or run the same control.
- Change the cache root when rolling back. Turning off the switch is not enough: replayed artifacts remain in the cache as hard links, and the cache key is not sensitive to this switch. We tested it: under the same cache root, with only the parallel precompile switch turned off, all 16 ranks still loaded the existing compiled artifacts directly, with 0 compiles.
4. Other compile-time optimizations#
- Compute indices with bitwise operations instead of division and modulo; share the sparse MLA op across the 78 layers instead of tracing it layer by layer. These two took cold compile from 52.3 to 28.7 minutes.
- Share the streamidx op across layers as well; remove shapes the rejection sampler never uses; use
--kv-cache-memory-bytesto skip the profile run (the profile run itself takes about 150 seconds). These shipped in the same round as the unroll factor of 16, and together cold compile rose from 28.7 to 30.7 minutes; the increase came from the unroll factor. - Change the dispatcher to a single
switch; skip the local save of the AOTAutograd cache; raise the container CPU limit from 100 to 223 cores, because the compile peak was already saturating 100 cores. - Rotate the rejection sampler's precompile order by rank, so different ranks compile different shapes first. Rotation can only be used on graphs without collectives: we once rotated
compute_selected_logits, which contains an all-gather, by rank as well, and it deadlocked for three hours. Judging from the code and the timeline, the rotation scrambled the order of the all-gathers (inference, no stack captured).
One direction was abandoned: removing the two intermediate buckets 1024 and 4096 would cut about 3 more minutes from cold compile, but at concurrency 32 throughput dropped 17.8% and 7.7% for the 3000-token-input and 800-token-input workloads respectively (single measurement; we have seen 8.9% variation across restarts with the same configuration), so the cost outweighed the gain.
Gains#
Hy4#
Cold compile went from 95.1 minutes to about 14. The final version was measured twice at mnbt 2048, at 819 s and 842 s. In configurations without sequence parallelism, replay also makes the number of buckets matter less for cold compile time: 856, 878 and 921 s at mnbt 2048, 4096 and 8192 respectively.
The remaining 14 minutes break down as follows:
Comparison across three models#
We also tested the same approach on GLM-5.3 and Qwen3.5. Two caveats. First, besides the compile-related changes, the "original recipe" and "optimized" configurations also differ in image, vLLM version and KV settings, so the chart below reflects the overall difference between two configurations. Second, Hy4 and Qwen3.5 are timed from pod creation, while GLM-5.3's weight loading takes 14 to 42 minutes and would mask the compile difference, so it is timed from when weight loading finishes.
- None of the three original recipes could start at large mnbt: Hy4 hit HBM OOM when loading programs at runtime at 4096, and 8192 was not tested; GLM-5.3 hit OOM at compile time at 8192, with HLO temporary buffers needing 96.58G; Qwen3.5 hit OOM when loading programs at 8192, reproduced twice. The new recipes start at all three settings.
- The only comparison that can be attributed on its own is one pair on GLM-5.3: same image, same node distribution, differing only in the parallel precompile switch. Time from weights loaded to service ready dropped from 959 s to 409 s. This switch controls both bucket splitting and replay, so their contributions cannot be separated. Outputs on the 40 long prompts were identical on both sides, and GSM8K was 97.50 and 97.27 respectively (the 97.27 run was a warm start).
- Qwen3.5 improved by only 24–26%. It uses DP8, so 8 inference engines each compile on their own, and replay only looks for replayable artifacts within the same DP index, so the replay count was 0. The two main costs identified earlier are both in sparse MLA, a path Qwen3.5 does not take in the first place (inference).
Accuracy and performance#
The final version ran three rounds of each accuracy evaluation: GSM8K 94.54 / 94.84 / 94.24 (mean 94.54), MMLU 90.19 / 90.07 / 90.44 (mean 90.23). The release threshold is the reference version's three-round mean minus 1 percentage point, i.e. 93.62 / 89.74. A question-by-question paired comparison with the previous version showed no regression. On performance, two versions from the pre-release hardening stage each ran one round of regression benchmarks: one had 14 of 16 benchmark points within ±5% of the control version; for the other, the two concurrency-1 points were each re-run four times, with means of −2.0% and −3.9%.
Validation before production#
Once cold compile was fast, we still had to make sure it would not cause problems in production. We ran four rounds of adversarial review: independent review agents looked for problems along five directions, the verifier rejected findings by default, and every finding had to come with reproducible evidence. The first three rounds produced 113 findings, grouped into 13 root-cause groups; the fourth round produced 30, with no new root-cause groups. Below are a few representative issues. All fixes are in the image and were verified on hardware.
| Issue | Consequence | Fix | Verification |
|---|---|---|---|
| Some ranks missing compiled artifacts | These ranks fell back to recompiling and got out of step with the other ranks during warmup that contains collectives, triggering a SparseCore CoreHalt (the causal chain is inferred) | Each rank's artifact load result is first put to an all_reduce vote on CPU: either all ranks load, or all ranks recompile | CoreHalt 1 → 0, ready in 445 s |
| First failure in speculative decoding warmup | Only on cold compile, once per rank, with the error does not support dynamic shape, taking the single-rank retry path | The draft model's positions tensor was passed into a statically compiled function while carrying a dynamic-dim mark; it now passes positions.view_as(positions) | First failures 16 → 0 |
| Speculative decoding combined with logprobs / seed / prompt_logprobs | logprobs crashed EngineCore; seed returned an empty 500; prompt_logprobs silently returned [None] | Rejected at the request entry point with a 400 | — |
| Compile cache grew by about 3.8 GB per restart | AOTAutogradCache entries for small graphs were written every time but never read (from reading code) | Skip the local save for small graphs in all processes | New files in the aotautograd cache directory during cold compile, warm start and serving: 3000+ → 0 |
| "No compiles while serving" could not be verified | Runtime recompiles are not logged by default | Count newly written programs in the cache directory instead | First pass of traffic: 1537 new programs; second pass: 17 new |
Another phenomenon that is easy to misread: verbatim output depends on how ranks are distributed across nodes. Under the same distribution, outputs on the 40 long prompts were essentially identical, 40/40; with a different distribution it was 37/40, and the 3 that differed had the same final answers, only worded differently. So align the node distribution before any verbatim consistency check, otherwise a difference in distribution will be misread as a regression.
Later developments#
The main data in this post is as of October 1. Since then there have been two changes related to cold compile:
Sequence parallelism in mixed steps pushed cold compile back up. To raise throughput at high concurrency, later versions enabled sequence parallelism in mixed steps; to lower time to first token, mnbt was also changed to 8192. Cold compile rose to about 47–50 minutes as a result. At the time, rank 0's logs suggested the main reason was that several sequence-parallel mixed-step buckets were compiled serially on rank 0. The actual root cause turned out to be that the sequence-parallel slice wrote the rank index into the traced graph, so cross-rank replay rejected every one of these buckets and every rank compiled them all itself; reading the rank at run time brought cold compile down to 17.7 minutes. Details are in the follow-up post:
Cold compile for data-parallel deployments. The replay in this post only looks for reusable compiled artifacts within the same DP index. XLA-level programs can already be shared across DP groups, but vLLM-level compiled artifacts cannot be replayed across DP groups, so in a pure data-parallel deployment every engine still has to go through the full compile flow on its own. We then relaxed replay to search across DP, and on Qwen3.5 DP8 the time from weights loaded to service ready dropped from 741 s (single run) to 270 s (mean of three runs). Details are in the follow-up post in this series:
Cold Compile Optimization, Part 2: Cross-DP Compile Reuse for Data-Parallel Deployments on TPU
About 6 of the changes covered in this post have been submitted upstream, together with several fixes from the pre-production validation, and are currently under review.
Where this applies#
The methods in this post apply to deploying models with custom Pallas kernels on TPU with vllm-torchtpu, especially:
- Models with custom attention kernels such as sparse MLA: check the kernels for Python loops that are unrolled at trace time, and for per-rank values that have ended up in closures. Counting the programs under the same shape key in the cache directory is the fastest way to check.
- Tensor-parallel deployments: replaying compiled artifacts between ranks saves most of the duplicated compilation. Before using it, confirm that the graph fingerprint covers every input that affects program semantics, and change the cache root when rolling back.
- Multi-rank startup flows: any rank-local decision (whether compiled artifacts loaded successfully, whether to retry after a failure) must be voted on across all ranks before reaching a collective, otherwise ranks easily fall out of step.
Limitations#
- Most cold compile times were measured only once; the final version was measured twice.
- The first time a request shape appears (for example, non-greedy sampling), that batch gets an extra 5–18 s stall; from the second occurrence of the same shape onward, it no longer appears. The exact mechanism has not been identified.
- The replay-off control was run only once each on Hy4 and GLM-5.3.
- Bitwise equality between fori and the original unrolled implementation was verified only at the kernel level. On a GLM model reduced to 6 layers, the whole-model output differs from the unrolled version by one bf16 rounding step; the cause has not yet been located.
Series#
Overview: Beating B200 from Scratch: Porting and Optimizing Hy4 Inference on TPU v7
- From 2 tok/s to Beating B200: Optimizing Hy4 Inference on TPU v7
- Hy4 Weight Loading on TPU v7: From 857 Seconds to 68
- 95 Minutes to 14: Cold Compile Optimization for Hy4 on TPU v7
- Cold Compile Optimization, Part 2: Cross-DP Compile Reuse for Data-Parallel Deployments on TPU
- Cold Compile Optimization, Part 3: Cross-Rank Reuse for Sequence-Parallel Buckets, 48 Minutes to 17.7
Data comes from the records of the cold compile optimization and pre-production validation, 2026-09-28 to 10-08. This post was first published on October 1 and rewritten on October 9 with a new structure and the later developments added; the sequence-parallel cold compile finding was updated on October 13.