RooflineAI Infra Field Notes by Forrest Xi

AI Infra · TPU v7

Cold Compile Optimization, Part 3: Cross-Rank Reuse for Sequence-Parallel Buckets, 48 Minutes to 17.7

After Hy4 turned on mixed-step sequence parallelism and raised the per-step token budget (max_num_batched_tokens, mnbt) to 8192 to cut time to first token, its cold compile climbed from about 14 minutes back to 48. The root cause: the sequence-parallel slice wrote the rank index into the traced graph. Each of the 16 ranks traced a different program, every rank rejected the others' compiled artifacts, and each rank compiled all five sequence-parallel buckets one after another. Reading the rank at run time from one in-group all_to_all brought cold compile to 18.7 minutes; staggering the sampler-side precompile across ranks and moving artifact saving to a background thread brought it to 17.7, on par with the same recipe without sequence parallelism.

TL;DR

  • Problem: with mixed-step sequence parallelism on, Hy4's mnbt 8192 recipe took 48.2 minutes to cold compile (mean of three). The sequence-parallel slice is written reshape(W, -1, d)[rank] with rank a Python integer, so it is traced as a constant: 16 ranks trace 16 different programs, cross-rank replay rejects all of them, and every rank compiles all five sequence-parallel buckets serially.
  • Solution: a new sharded op runs one all_to_all of arange(W) inside the group ordered by TP rank. Each rank receives its own position and slices its row block with it, so the graph no longer holds a rank constant. Two smaller changes: sampler-side graphs with no collective precompile in a per-rank staggered order, and artifact saving moves to a background thread.
  • Gain: cold compile went from 48.2 to 17.7 minutes (mean of three, timed by health-check polling), level with 17.7 minutes for the same image without sequence parallelism (one run). Accuracy evaluations passed in all three rounds, and a ten-tier formal benchmark stayed within ±3% throughput of the current recipe. This is a variant recipe; switching production to it still goes through integration validation.
Cold compile time (minutes), mnbt 8192, empty cache, from pod creation until rank 0 passes the health check, timed by a poller that checks about every 60 seconds. Measured at the ready time in the server log instead (the caliber of Part 1), the first three rows are 47.8, 18.3 and 17.05 minutes. The reference row uses the same image as the original recipe with only sequence parallelism turned off.

Background#

Part 1 of this series cut Hy4-preview's cold compile on TPU v7 from 95 minutes to about 14, and Part 2 extended cross-rank replay to data-parallel deployments. Part 1's follow-up section noted that later versions turned on sequence parallelism in mixed steps for high-concurrency throughput and raised max_num_batched_tokens (the most tokens one step processes; mnbt below) to 8192 for time to first token, and that cold compile climbed back to 47–50 minutes, which we then put down to the sequence-parallel buckets compiling serially on rank 0. This post picks up that thread with the actual cause and the fix.

The deployment is unchanged: vLLM + vllm-torchtpu, TP16 across two hosts with 8 ranks each, the compile cache on storage shared by both hosts, parallel precompile and cross-rank replay on. Sequence parallelism only kicks in when the token count is a multiple of 512, so mnbt 8192 has five sequence-parallel buckets: 512, 1024, 2048, 4096 and 8192.

Cold compile time here means the time from pod creation until rank 0 passes the health check, starting from an empty cache. The reading comes from a script that polls about every 60 seconds, so it is quantized; we also recorded the ready time in the server log, and the text says which one each number is. The baseline was measured three times on the same image, recipe and nodes: 2869, 2938 and 2871 s, mean 48.2 minutes, standard deviation 1.36%. Below, twice the standard deviation (2.72%) is the bar for calling a difference significant.

Problem: every rank compiled the sequence-parallel buckets#

We split rank 0's server log into compile phases; for each of the three runs the phases add up to the end-to-end time. The difference is mostly in the second round:

PhaseSP on (mean of 3)SP off (1 run)
Pod start to first round (incl. weight loading)171 s165 s
Round 1: the 6 buckets below 512 (incl. the gap after it)243 s244 s
Round 2: the 5 buckets from 512 up2114 s412 s
After round 2, before round 3214 s130 s
Round 3 (speculative decoding) and on to ready125 s111 s
Total (ready time in the server log)2866 s1062 s

With sequence parallelism off, different ranks compile the five round-2 buckets, rank 0 only waits for the slowest one, the 8192 bucket (291 s), and replays the rest. With it on, rank 0 compiled all five buckets itself, 360–430 s each. The log gives two direct pieces of evidence:

  • Cross-rank replay was rejected for every sequence-parallel bucket with the reason different code or constants. About 180 artifacts were rejected per cold compile; with sequence parallelism off, 0.
  • The replay fingerprint covers the FX graph code plus small constants hashed by value. The sequence-parallel slice is hidden_states.reshape(W, -1, d)[rank] with rank a Python integer, which tracing writes into the graph as a constant, so each rank's fingerprint differs.

Bucketed by nature, "every rank recompiling buckets it could have replayed" is 1588 s (55.4%) and "rank 0 idling for the other ranks after its own compile" is 84 s (2.9%): 58.3% together, from one source. Part 1's "serial compile on rank 0" only saw rank 0; the rejection counts show every rank doing the same duplicate work (only rank 0's timeline was parsed phase by phase).

Solution#

1. Read the rank at run time#

Goal. All 16 ranks trace a byte-identical graph, and each rank still gets its own block of rows.

We went through three versions; the first two were dropped:

  • Index with the rank stored in a buffer tensor. The two ranks' graphs are indeed identical (checked on CPU), but the buffer becomes an input that only the sequence-parallel group of graphs has. When vllm-torchtpu hands a bucket over between the two trace groups it requires matching input signatures, and it refuses (from reading the code).
  • Take the device position with lax.axis_index inside a sharded JAX op, then map it to the TP rank through a table. The CPU unit test passes, but axis_index lowers to partition-id, and when torch_tpu recompiles the module through jax.export the SPMD partitioner does not accept that instruction. Existing comments and workarounds in the codebase record this, and we dropped the version before it reached a TPU (inferred from those source comments; this version was not run on TPU).
  • An in-group all_to_all. In the axis group ordered by TP rank, all_to_all arange(W): all_to_all sends element i to member i of the group, so each rank receives its own position in the group, which is its TP rank. A dynamic_slice with that run-time value cuts this rank's T/W rows. The graph only holds the group structure, identical on all 16 ranks. The cost is one all_to_all of W int32 values per sequence-parallel step. vllm-torchtpu already uses the same pattern elsewhere (passing the rank in as data through an all_to_all to avoid partition-id).

Tests. Three new unit tests, each with a negative control: with a scrambled device-to-rank mapping, every shard equals x.reshape(W, -1, d)[owner] (an identity mapping fails, 256/256 elements wrong); tracing the 512 bucket as rank 3 and as rank 5 gives the same graph code (the original slice fails); neither the lowered StableHLO nor the compiled HLO contains partition-id (the axis_index version fails).

Effect. On TPU, rejections on sequence-parallel buckets dropped from about 180 to 0, and every rank logged replaying sequence-parallel buckets from a peer. Round 2 fell from 2114 s to 428 s, close to the 412 s without sequence parallelism. Cold compile fell to 18.7 minutes (three runs: 1125, 1124, 1123 s, unusually tidy because of the polling quantization; ready time in the server log averaged 1096 s), a 61.1% cut and 22 times the significance bar.

A side observation: rank 0's 8192-bucket compile went from about 400 s (409 / 393 / 396) to about 306 s (318 / 270 / 329). Before the change all 16 ranks were compiling large buckets at once; afterwards far fewer do at any moment, so the compilers contend less for CPU and memory (inferred; contention was not measured separately).

2. Stagger the sampler-side precompile across ranks#

Problem. Besides the main model, startup precompiles a few groups of sampler-related graphs per request-count bucket (sampling from logits, gathering logprobs, structured decoding). Every rank compiled them in the same order, and the speculative-decoding warmup that follows contains collectives, so it waits for the slowest rank.

Approach. As the rejection sampler already does, each rank starts at its own share of the sweep and wraps around. Ranks compile different shapes first and put them in the shared XLA cache, so most later shapes become loads. Staggering is only safe for graphs with no collective; otherwise ranks reach the same collective at different times and deadlock (Part 1 records a real deadlock). We added a test that traces these real graphs and asserts they contain no collective op; its negative control, a deliberately inserted fake all-gather, is caught.

Effect. The slowest of the 16 ranks spent 21.7 s on these three sweeps instead of 31.1 s (three runs each), about a third less rather than the half one might expect. Reading the code suggests three reasons (inferred; not measured one by one): to confirm there is no collective first, all ranks still compile the first shape in the same order, in sync; there are only 4 request-count buckets, so only 3 actually get staggered; and the start formula splits the 8 ranks into a few groups that still duplicate work within each group.

3. Save compiled artifacts in the background#

Problem. After each compile round, vLLM serializes and saves the compiled artifact synchronously before tracing the next round. There is a 46–49 s gap between "round done" and "next round's tracing starts".

Approach. A switch, off by default, moves the save to a background thread.

Effect. First, the cost: per-phase timing shows the save itself is about 19 s of FX graph serialization (the artifact is about 64 MB and the write time is negligible), not the whole gap. With the switch on, both rounds got about 40 s shorter but the gaps between rounds each got about 20 s longer, netting roughly 25–30 s. Measured alone, cold compile went from 18.7 to 18.3 minutes (−2.11%), under the 2.72% bar, so we do not count it as a gain on its own. Our guess for the longer gaps is that the background pickling and the next round's Dynamo tracing are both pure Python and contend for the GIL (inferred, not verified).

Measured together with change 2, cold compile reached 17.7 minutes (three runs: 1059, 1059, 1060 s; ready time in the server log 1014, 1011, 1044 s, mean 1023 s), 5.75% below the version with change 1 only (the "intermediate version" below) and over the bar, so both were adopted together. On the server-log reading the combination saves 73 s over the intermediate version, while the two changes measured separately account for about 38 s; the remaining 35 s or so is unattributed.

An idea that was refuted: removing the 512 guard#

The idea. With sequence parallelism fixed, one suspicious thing remained in the log: the main model is traced in two rounds split at 512, each with one Dynamo trace (about 40 s) and one artifact save. The log gives only one reason text for leaving a bucket to a later trace: s72 <= 511. Following it led to a kernel helper that compares the token count with 512 before checking a switch. Swapping the two conditions gives the same result for any input, but with the switch on it no longer emits that comparison guard, and a CPU test confirmed the helper leaves no guard after the swap. Merging the two rounds into one was estimated to save about 215 s, an upper bound of about ×1.24.

The refutation. Before spending machine time, an independent reviewer was asked, as usual, to look for reasons it would fail, and it did not hold:

  • The sequence-parallel branch is enabled on num_tokens % 512 == 0. No bucket below 512 is a multiple of 512, so this divisibility guard splits the buckets at exactly the same place. And the sequence-parallel graph has collectives that the other one lacks, so the two groups could never be one graph anyway.
  • The log shows only s72 <= 511 because the function that assigns buckets to traces checks each symbol's value range first and returns on a hit, and only then checks guards one by one. The comparison guard is absorbed into the value range; the divisibility guard is not, so the former hides the latter. We found the divisibility guard's text in an earlier log, which confirms it.

So on the recipe with sequence parallelism the change saves nothing; it may help a recipe without sequence parallelism (untested). This paper refutation stopped it before it reached a TPU and saved about 73 minutes of experiment time.

The lesson is worth stating on its own: one guard text in the log does not mean one guard is at work. To decide that a split is gone, check that the total number of "left to a later trace" lines drops to zero and that the Dynamo trace count goes down, not that a particular string disappears. Checking only that s72 <= 511 disappears would give a false positive: after the change it would be replaced by the divisibility guard's text, with the same line count.

Results#

ConfigurationCold compile (polling)Ready time in server log
Original recipe, SP on48.2 min (2869 / 2938 / 2871 s)2866 s
+ rank at run time (intermediate version)18.7 min (1125 / 1124 / 1123 s)1096 s
+ background save (alone)18.3 min (1123 / 1059 / 1119 s), under the bar1067 s
+ background save + staggered small graphs (final)17.7 min (1059 / 1059 / 1060 s)1023 s
Reference: same image, SP off17.7 min (1 run)1062 s

Every row except the reference is three runs, each with a fresh cache directory. Restarting the final version once exactly as the recipe specifies took 1060 s, matching the table; a warm start on the same cache directory and node placement took 374 s with no new compile on either host, so the artifacts written in the background are complete and loadable.

Accuracy. The final version scored GSM8K 94.69 / 94.16 / 94.77 (mean 94.54) and MMLU 90.28 / 90.23 / 90.02 (mean 90.18), above the release bars of 93.72 / 89.74. Paired question by question against the intermediate version (change 1, rank at run time, only): GSM8K 9 worse, 9 better; MMLU 70 worse, 75 better; no regression found. Against the current production version, both the intermediate and the final version score GSM8K 13 worse, 6 better, one-sided p≈0.084: not significant, but leaning negative. The only change both versions share relative to production is change 1 (rank at run time).

Performance. A ten-tier formal benchmark, compared on the same caliber with the production recipe's latest formal benchmark: throughput within ±2.9%, time to first token within ±5.1%, time per output token within ±2.7%, in both directions, one run each. Within that resolution, no run-time cost from the extra all_to_all per step showed up; a smaller cost would not be visible.

Is the replayed program the same as one compiled locally?#

Sequence-parallel buckets had never been replayed before; now only one of 16 ranks actually compiles each and the rest load it, so the replayed program needed checking on its own. Two layers of comparison:

  • Outputs. One arm turns parallel precompile off (every rank compiles every bucket itself; cold compile 2560 s); the other warm-starts from the replayed cache. On 40 long prompts of over 11,000 characters at temperature 0, compared word for word: 40/40 identical across arms, twice. The control, the same serve run twice, gives 39/40; the one prompt that changes does so the same way in both arms depending on which pass it is, independent of replay.
  • Programs. A byte comparison cannot work: two ranks compiling the same graph already produce different artifacts. Comparing the 512-bucket artifacts by pickle structure instead: two locally compiled artifacts from different ranks differ by 170,032 bytes in program-block length with identical string sets; a replayed artifact and this rank's own compile differ by 108 bytes, with one extra 64-character hash among the strings (presumably the fingerprint of the replay source, not checked). The difference between replayed and locally compiled artifacts lies within the normal rank-to-rank difference.

Two more checks: on the intermediate version (change 1, rank at run time, only; no background saving or staggered sweeps yet), swapping the node placement of the two hosts and restarting recompiles but produces correct output (GSM8K 94.69); a warm start on the same placement compiles nothing.

Limitations#

  • This is a variant recipe; the production recipe is unchanged. Switching production over is up to integration validation, and the long-context accuracy gate (RULER and others beyond the 40 long prompts) has not been run.
  • The paired GSM8K comparison with production leans negative (13 worse / 6 better, p≈0.084), not significant; the cause has not been investigated.
  • The main reading is polling-based with about 60 s of quantization, and the final version's three runs land in the same step; the server-log ready time has a standard deviation of about 18 s.
  • Background saving alone did not clear the significance bar, and about 35 s of the combined 73 s is unattributed.
  • The replay correctness comparison was done once; node placement is part of the compile cache key, so a different placement still recompiles.
  • Part 1's 921 s for mnbt 8192 without sequence parallelism (an older image, the main model traced in one round, server-log caliber) is still about 100 s faster. Structurally, with sequence parallelism the main model must be traced in two rounds, each with a trace, a save and a first compile of its largest bucket in series; the one remaining lever is overlapping the two rounds' tracing and compiling, with an estimated upper bound of about 120 s (inferred), not yet tried.

Where this applies#

  • Model code that slices data along the TP dimension. Wherever a Python rank integer indexes, slices or computes an offset, the rank enters the graph as a constant and cross-rank replay stops working. Look for different code or constants rejections in the replay log, or trace one shape as two different ranks and compare the graph code. Upstream vllm-torchtpu #1457 fixed the same class of problem (the DCP LSE merge indexed by rank).
  • Sharded ops that need this rank's index. On torch_tpu, avoid lax.axis_index and pass the index in as data through an in-group all_to_all.
  • Small graphs in precompile. Those without collectives can be staggered across ranks; those with collectives must never be. When estimating the gain, subtract the first shape compiled in sync and the duplication within groups instead of assuming one over the number of ranks.
  • Reading compile splits from logs. Count the rejection lines and the trace count; do not go by one guard text.

Series#

Overview: Beating B200 from Scratch: Porting and Optimizing Hy4 Inference on TPU v7

  1. From 2 tok/s to Beating B200: Optimizing Hy4 Inference on TPU v7
  2. Hy4 Weight Loading on TPU v7: From 857 Seconds to 68
  3. 95 Minutes to 14: Cold Compile Optimization for Hy4 on TPU v7
  4. Cold Compile Optimization, Part 2: Cross-DP Compile Reuse for Data-Parallel Deployments on TPU
  5. Cold Compile Optimization, Part 3: Cross-Rank Reuse for Sequence-Parallel Buckets, 48 Minutes to 17.7

Data from the sequence-parallel cold compile optimization records of 2026-10-11 to 10-12.