<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
  <title>Roofline · AI Infra Field Notes by Forrest Xi</title>
  <subtitle>Everything AI infrastructure: chips, interconnects, compilers, frameworks, training and inference — hands-on notes from hardware to software</subtitle>
  <link href="https://blog.maxwell-x.dev/en/"/>
  <link rel="self" href="https://blog.maxwell-x.dev/en/feed.xml"/>
  <id>https://blog.maxwell-x.dev/en/</id>
  <updated>2026-10-28T00:00:00Z</updated>
  <author><name>Forrest Xi</name></author>
  <entry>
    <title>Porting and Tuning FastH3 on TPU v6e: a 148 GB Video Model at 1.55x the Performance per Dollar of 4x B200</title>
    <link href="https://blog.maxwell-x.dev/en/fasth3-on-tpu-v6e/"/>
    <id>https://blog.maxwell-x.dev/en/fasth3-on-tpu-v6e/</id>
    <published>2026-10-28T00:00:00Z</published>
    <updated>2026-10-28T00:00:00Z</updated>
    <summary>FastH3 is FastVideo's few-step audio-video model distilled from MiniMax H3. Its weights total about 148 GB, while a TPU v6e chip has 32 GB of HBM. We first got it running on 4 v6e chips (72.4 s per 5-second clip), then moved to 8 chips and brought it down to 18.9 s. At GCP DWS Calendar prices that is 1.55x the performance per dollar of FastVideo's fastest official 4x B200 setup. This is our first post on optimizing the MiniMax H3 family on TPU; the second half covers how the same approach carried over to 15-second clips and a resident service, and where we go next.</summary>
    <content type="html" xml:base="https://blog.maxwell-x.dev/en/fasth3-on-tpu-v6e/">&lt;div class="tldr" role="note"&gt;
&lt;p&gt;&lt;strong&gt;TL;DR&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;5-second clips&lt;/strong&gt;: audio-video generation at 1344×768, 124 frames (about 5 s), 8 steps takes 18.9 s end to end on 8 TPU v6e chips. At DWS Calendar prices that is 1.55x the performance per dollar of 4 B200 GPUs running FastVideo's fastest official configuration (9.843 s).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Fitting it in&lt;/strong&gt;: one copy of the DiT is 70 GB and does not fit on a v6e chip, so the DiT, the text encoder and the VAE all have to be sharded. The hard part was not total capacity but the fact that a TPU needs a contiguous block of HBM to load a program. It ran reliably only after every FSDP all-gather program was kept under a few hundred MB.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;4 chips hit a ceiling&lt;/strong&gt;: tuning 5-second clips on 4 v6e chips went from 72.4 s to 52.0 s (1.13x per dollar). Adding up the paper upper bounds of the candidates we had at the time still did not reach 1.5x, so we moved to 8 chips.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;8-chip tuning&lt;/strong&gt;: 5-second clips went from 31.5 s to 18.9 s. The biggest items were keeping the whole text encoder resident, keeping the whole VAE resident and compiling the full decoder, fixing thread contention on 180 vCPUs, replacing the row max in the block-sparse attention kernel with a fixed bound, and splitting FSDP units by the model's real module names.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;15-second clips&lt;/strong&gt;: with the 4-step checkpoint on the same 8 v6e chips, 41.2 s came down to 25.8 s, mostly from moving the VAE out of HBM during denoising, selecting a fixed 64 blocks per row (lossy), and four changes to decoding (two byte-identical, two near-lossless).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Resident service&lt;/strong&gt;: 4 requests arriving at once at one resident process exposed 3 problems that single-prompt tests never show; after fixing them, for prompts in the 128 bucket whose text fits in one tile, the first request at a new length went from 110–125 s to 25.7–27.0 s.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Next&lt;/strong&gt;: most of the remaining time is in denoising, so the next work is structural changes there (compilation granularity, attention implementation), plus streaming encoding at the end of decoding.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="background"&gt;Background&lt;a class="hd-a" href="#background" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;h3 id="the-model"&gt;The model&lt;a class="hd-a" href="#the-model" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;&lt;a href="https://huggingface.co/MiniMaxAI/MiniMax-H3"&gt;MiniMax H3&lt;/a&gt; is MiniMax's joint audio-video generation model; it produces video with stereo sound in one pass. &lt;a href="https://haoailab.com/blogs/fasth3-preview/"&gt;FastH3&lt;/a&gt; is a few-step version distilled from it by the FastVideo team. This post uses two checkpoints:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://huggingface.co/FastVideo/FastVideo-FastH3-8-Step-V2"&gt;FastVideo-FastH3-8-Step-V2&lt;/a&gt;: 8 DiT forwards, used for 5-second clips (Steps 1–3 below).&lt;/li&gt;
&lt;li&gt;&lt;a href="https://huggingface.co/FastVideo/FastVideo-Minimax-FastH3-Preview-v0.2"&gt;FastVideo-Minimax-FastH3-Preview-v0.2&lt;/a&gt;: 4 DiT forwards, used in the 15-second and resident-service sections.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The size and structure of four components drive the deployment:&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Component&lt;/th&gt;
&lt;th style="text-align:right"&gt;Weights&lt;/th&gt;
&lt;th&gt;Structure&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;DiT&lt;/td&gt;
&lt;td style="text-align:right"&gt;70.1 GB&lt;/td&gt;
&lt;td&gt;50 layers, hidden 5376, 56 attention heads; VSA-H3 block-sparse attention (64-token tiles, about 80% sparse in the 8-step checkpoint)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Text encoder&lt;/td&gt;
&lt;td style="text-align:right"&gt;66.7 GB&lt;/td&gt;
&lt;td&gt;Full Qwen3-VL-32B weights, hidden states taken from layer 50&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Video VAE&lt;/td&gt;
&lt;td style="text-align:right"&gt;10.4 GB&lt;/td&gt;
&lt;td&gt;Decodes by spatial tiles&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Audio VAE&lt;/td&gt;
&lt;td style="text-align:right"&gt;0.6 GB&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;That is about 148 GB in total. A 5-second clip is 42,752 tokens in the DiT; a 15-second clip is about 109,000.&lt;/p&gt;
&lt;h3 id="hardware-and-pricing"&gt;Hardware and pricing&lt;a class="hd-a" href="#hardware-and-pricing" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;A TPU v6e (Trillium) chip has a bf16 peak of 918 TFLOPs, 32 GB of HBM (about 33.5 GB allocatable at runtime), 1638 GB/s of HBM bandwidth and one TensorCore. We used &lt;code&gt;ct6e-standard-8t&lt;/code&gt;: 8 chips per machine, 2x4 topology, 180 vCPUs.&lt;/p&gt;
&lt;p&gt;Both sides are priced at GCP DWS Calendar rates (read from the official pricing pages on 2026-10-05): B200 at $11.2775 per GPU-hour (&lt;code&gt;a4-highgpu-8g&lt;/code&gt; at $90.22 ÷ 8) and v6e at $1.89 per chip-hour, a ratio of 5.967. Performance per dollar counts the accelerators actually occupied:&lt;/p&gt;
&lt;div class="code-block"&gt;&lt;div class="code-head"&gt;&lt;span class="code-lang"&gt;text&lt;/span&gt;&lt;button type="button" class="copy-btn"&gt;&lt;/button&gt;&lt;/div&gt;&lt;div class="hl"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;perf per dollar (vs B200) = B200 time × B200 GPUs × 11.2775 ÷ (TPU time × TPU chips × 1.89)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;The B200 side is 4 GPUs running FastVideo's fastest official configuration, which we measured at 9.843 s (3 prompts × 3 runs). On that basis the break-even point for 8 v6e chips is 29.37 s, and the 1.5x target is 19.57 s. This baseline is the latency-optimal 4-GPU setup; B200 may do better per dollar with fewer GPUs, which we did not measure for 5-second clips, so the ratios in this post hold only against 4x B200.&lt;/p&gt;
&lt;h3 id="measurement-and-accuracy"&gt;Measurement and accuracy&lt;a class="hd-a" href="#measurement-and-accuracy" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Timing&lt;/strong&gt;: one process per prompt, one untimed warm-up, then 3 timed runs; 3 prompts give 9 samples, and we report the mean. The clock runs from request entry to the MP4 being written, covering text encoding, denoising, video and audio decoding, and saving.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Accuracy gate&lt;/strong&gt;: video generation has no GSM8K-style accuracy score. We generated a full-fp32 reference on B200 and compare 12 intermediate tensors (the step-0 velocities, the final latents and so on). For each tensor, the TPU's relative L2 error against the reference, divided by the error of B200's official configuration against the same reference, must be ≤ 1.5. In other words, the TPU error may be at most 1.5x B200's own error. The gate only covers the DiT; for changes to VAE decoding we also compare the PSNR of decoded frames and watch the output.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Software&lt;/strong&gt;: torch 2.13.0 (CPU build) + torch_tpu 0.1.1.dev20260912 + FastVideo, deployed on GKE.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="results-for-5-second-clips"&gt;Results for 5-second clips&lt;a class="hd-a" href="#results-for-5-second-clips" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;figure&gt;
  &lt;div class="chart" role="img" aria-label="End-to-end time for a 5-second clip: 72.4, 52.0, 31.5, 18.9 s"&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;4 chips · running&lt;small&gt;0.81x per $&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill base" style="width:calc((100% - 5.5em) * 1.0000)"&gt;&lt;/span&gt;&lt;span class="val"&gt;72.4&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;4 chips · tuned&lt;small&gt;1.13x per $&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.7189)"&gt;&lt;/span&gt;&lt;span class="val"&gt;52.0&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;8 chips · start&lt;small&gt;0.93x per $&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.4353)"&gt;&lt;/span&gt;&lt;span class="val"&gt;31.5&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;8 chips · tuned&lt;small&gt;1.55x per $&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill" style="width:calc((100% - 5.5em) * 0.2613)"&gt;&lt;/span&gt;&lt;span class="val"&gt;18.9&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;figcaption&gt;End-to-end time (seconds) at 1344×768 / 124 frames / 8 steps, n=9 per row. Per-dollar ratios are priced by chips actually occupied, against 9.843 s on 4 B200 GPUs. The two 4-chip rows were measured using 4 chips of an 8-chip machine and priced as 4 chips. "8 chips · start" is the tuned 4-chip configuration run with 8 processes.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Stage&lt;/th&gt;
&lt;th style="text-align:right"&gt;4 chips tuned&lt;/th&gt;
&lt;th style="text-align:right"&gt;8 chips tuned&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Text encoding&lt;/td&gt;
&lt;td style="text-align:right"&gt;3.16 s&lt;/td&gt;
&lt;td style="text-align:right"&gt;0.24 s&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Denoising (8 steps)&lt;/td&gt;
&lt;td style="text-align:right"&gt;33.57 s&lt;/td&gt;
&lt;td style="text-align:right"&gt;14.99 s&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Video decoding&lt;/td&gt;
&lt;td style="text-align:right"&gt;13.54 s&lt;/td&gt;
&lt;td style="text-align:right"&gt;2.83 s&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;End to end&lt;/td&gt;
&lt;td style="text-align:right"&gt;52.01 s&lt;/td&gt;
&lt;td style="text-align:right"&gt;18.91 s&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;The final configuration passes the accuracy gate: all 12 items in 3 rounds, maximum ratio 1.119, identical across rounds. Two caveats: decoded frames were compared only against the previous TPU configuration (PSNR ≥ 68 dB), not frame by frame against B200 or the fp32 reference, and image quality was judged by watching the output. All numbers come from a single node.&lt;/p&gt;
&lt;h2 id="step-1-fitting-148-gb-into-32-gb-chips"&gt;Step 1: fitting 148 GB into 32 GB chips&lt;a class="hd-a" href="#step-1-fitting-148-gb-into-32-gb-chips" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;h3 id="problem"&gt;Problem&lt;a class="hd-a" href="#problem" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;On v5p (95 GB per chip), FastVideo keeps a full DiT on every chip and shards the text encoder across 4. A v6e chip has 32 GB, so a single DiT copy already overflows it: &lt;strong&gt;the DiT must be sharded no matter how many chips we use&lt;/strong&gt;. The arithmetic first:&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Layout (4 v6e chips)&lt;/th&gt;
&lt;th style="text-align:right"&gt;Resident per chip&lt;/th&gt;
&lt;th&gt;Verdict&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;DiT sharded 4 ways + text encoder sharded and resident + one VAE per chip&lt;/td&gt;
&lt;td style="text-align:right"&gt;44.6 GB&lt;/td&gt;
&lt;td&gt;does not fit&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;DiT sharded 4 ways + text encoder loaded on demand + one VAE per chip&lt;/td&gt;
&lt;td style="text-align:right"&gt;27.9 GB + activations&lt;/td&gt;
&lt;td&gt;might fit&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Everything sharded and resident on 8 chips&lt;/td&gt;
&lt;td style="text-align:right"&gt;27.5 GB&lt;/td&gt;
&lt;td&gt;fits, at twice the cost&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;We started with the second layout: the DiT sharded 4 ways with FSDP and kept resident, the text encoder sharded with FSDP plus CPU offload, streamed onto the chips layer by layer.&lt;/p&gt;
&lt;h3 id="approach"&gt;Approach&lt;a class="hd-a" href="#approach" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;&lt;b&gt;Build the text encoder on the meta device.&lt;/b&gt; Building it on CPU and then calling &lt;code&gt;fully_shard&lt;/code&gt; with offload made all 4 ranks fail with an incompatible tensor type in &lt;code&gt;set_data&lt;/code&gt;. Building the model on the meta device and loading shards straight to host memory made CPU offload work.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;E0101 is about contiguity, not a leak.&lt;/b&gt; After the DiT loaded, the first request kept failing with E0101, &amp;quot;reserve at the bottom of memory&amp;quot;. Our first three attempts looked for whatever was holding 15 GB (reshard not freeing memory, large parameter units), and none of them was it. The XLA documentation for this error code explains it: loading a program needs a &lt;strong&gt;contiguous&lt;/strong&gt; block of HBM, and with enough fragmentation it fails even when total free memory is sufficient. In one measurement, 15.95 GB was free but only 0.63 GB could be reserved contiguously. The same code also passed on some runs and failed on others, so the memory layout cannot be relied on.&lt;/p&gt;
&lt;p&gt;In torch_tpu, each FSDP2 all-gather is itself a program, and its input plus output count toward the program reservation (inferred from matching sizes). The fix was therefore to &lt;strong&gt;keep each all-gather program small&lt;/strong&gt;: split FSDP units down to the attention block and each projection, keeping every unit's full parameters around 0.33 GB, and look up the large embedding on the host. After that both requests passed reliably.&lt;/p&gt;
&lt;h3 id="gain"&gt;Gain&lt;a class="hd-a" href="#gain" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;The model ran on 4 v6e chips at 72.4 s per 5-second clip, passing all 12 items of the accuracy gate (maximum 1.093). Priced as 4 chips, that is 0.81x B200's performance per dollar.&lt;/p&gt;
&lt;h3 id="where-it-applies"&gt;Where it applies&lt;a class="hd-a" href="#where-it-applies" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;When running large models on TPUs with tight HBM, first tell E0100 from E0101: E0100 means buffers really do not fit, E0101 means a program load could not find contiguous space. For E0101, make individual programs smaller instead of hunting for whoever is using memory.&lt;/p&gt;
&lt;h2 id="step-2-5-second-clips-at-52-s-on-4-chips-then-a-move-to-8"&gt;Step 2: 5-second clips at 52 s on 4 chips, then a move to 8&lt;a class="hd-a" href="#step-2-5-second-clips-at-52-s-on-4-chips-then-a-move-to-8" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;This step and the next are both about 5-second clips (8-step checkpoint). Four main changes went into the 4-chip tuning:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Cache the AdaLN modulation table by timestep.&lt;/b&gt; The DiT's AdaLN projection only takes the timestep embedding as input, and the 8-step distilled model uses the same timesteps for every request, so the output is identical every time. These weights are 26.0 GB, 37% of the DiT. Moving them to host memory and caching the modulation table per timestep frees those 26 GB of HBM and removes their all-gather from every step; a cache hit reuses the same tensor, so results are bit-identical.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Split FSDP units down to linear layers&lt;/b&gt;, so each all-gather program is smaller and starts earlier.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Compile the DiT and VAE per block&lt;/b&gt;, leaving collectives and the Pallas kernel outside the compiled graph (putting them inside either hung or ran slower).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Keep the first 24 text-encoder layers resident&lt;/b&gt; and stream the rest; keep the audio VAE resident.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That took 72.4 s down to 52.0 s (-28%), or 1.13x per dollar, still 1.33x short of the 1.5x target. At this point we stopped and did the arithmetic. With 4 chips, Ulysses can only split 4 ways, and the block-sparse kernel took 26.5 ms per layer (14.3 ms on 4 v5p chips). Adding up the paper upper bounds of the candidates registered at the time gave about 45–47 s (an estimate), short of 39.15 s, so we decided to move to 8 chips instead of running more small experiments on 4. How much of the later 8-chip gains (thread count, single-parameter FSDP gathers, the fixed-bound kernel) would carry back to 4 chips, we did not measure.&lt;/p&gt;
&lt;p&gt;On 8 v6e chips the cost doubles and the target becomes 19.57 s. Running the tuned 4-chip configuration with 8 processes gave 31.5 s, 0.93x per dollar; that was the 8-chip starting point.&lt;/p&gt;
&lt;h2 id="step-3-5-second-clips-from-315-s-to-189-s-on-8-chips"&gt;Step 3: 5-second clips from 31.5 s to 18.9 s on 8 chips&lt;a class="hd-a" href="#step-3-5-second-clips-from-315-s-to-189-s-on-8-chips" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;h3 id="where-the-time-goes"&gt;Where the time goes&lt;a class="hd-a" href="#where-the-time-goes" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;At the starting point one DiT step took 2.36 s (rank 0, 8-way Ulysses). Broken down from the profile:&lt;/p&gt;
&lt;figure&gt;
  &lt;div class="chart" role="img" aria-label="Breakdown of a 2363 ms DiT step"&gt;
    &lt;div class="stack"&gt;&lt;span class="seg c1" style="flex:700" title="Block-sparse attention kernel: 700 ms"&gt;700&lt;/span&gt;&lt;span class="seg c2" style="flex:526" title="Data movement: 526 ms"&gt;526&lt;/span&gt;&lt;span class="seg c3" style="flex:452" title="Collectives and block selection: 452 ms"&gt;452&lt;/span&gt;&lt;span class="seg c4" style="flex:280" title="Linear-layer GEMM: 280 ms"&gt;280&lt;/span&gt;&lt;span class="seg c5" style="flex:405" title="Elementwise, idle and other: 405 ms"&gt;405&lt;/span&gt;&lt;/div&gt;
    &lt;div class="legend"&gt;&lt;span&gt;&lt;i class="c1"&gt;&lt;/i&gt;Block-sparse kernel 29.6%&lt;/span&gt;&lt;span&gt;&lt;i class="c2"&gt;&lt;/i&gt;Data movement 22.3%&lt;/span&gt;&lt;span&gt;&lt;i class="c3"&gt;&lt;/i&gt;Collectives + block selection 19.1%&lt;/span&gt;&lt;span&gt;&lt;i class="c4"&gt;&lt;/i&gt;GEMM 11.8%&lt;/span&gt;&lt;span&gt;&lt;i class="c5"&gt;&lt;/i&gt;Elementwise, idle and other 17.1%&lt;/span&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;figcaption&gt;Device time (ms) of the DiT forward at denoising step 3, 8 v6e chips, starting configuration; the categories sum to about 2363 ms. Data movement covers copy / as_strided / pad and tile reordering; collectives are FSDP all-gather and Ulysses all-to-all; the last segment is 214 ms of elementwise ops, 180 ms idle between programs and 12 ms other.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;The linear-layer GEMMs were already at 78% of peak, leaving little room. Most of the time went to the block-sparse kernel, data movement and collectives. Outside the DiT, text encoding (3.0 s) and video decoding (6.4 s) were also well over budget.&lt;/p&gt;
&lt;h3 id="change-by-change"&gt;Change by change&lt;a class="hd-a" href="#change-by-change" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;figure&gt;
  &lt;div class="chart" role="img" aria-label="End-to-end time after each 8-chip change"&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Start&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill base" style="width:calc((100% - 5.5em) * 1.0000)"&gt;&lt;/span&gt;&lt;span class="val"&gt;31.50&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Text encoder resident&lt;small&gt;+ VAE kept gathered&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.8539)"&gt;&lt;/span&gt;&lt;span class="val"&gt;26.89&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;ffmpeg / single-thread layout&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.8247)"&gt;&lt;/span&gt;&lt;span class="val"&gt;25.97&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Threads + full VAE compile&lt;small&gt;+ RoPE / a2a sync&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.7006)"&gt;&lt;/span&gt;&lt;span class="val"&gt;22.07&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;FSDP gather into param buffer&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.6821)"&gt;&lt;/span&gt;&lt;span class="val"&gt;21.48&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Kernel fixed bound&lt;small&gt;+ text encoder TP8&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.6321)"&gt;&lt;/span&gt;&lt;span class="val"&gt;19.91&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;FSDP split by real names&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill" style="width:calc((100% - 5.5em) * 0.6003)"&gt;&lt;/span&gt;&lt;span class="val"&gt;18.91&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;figcaption&gt;5-second clips (124 frames / 8 steps). Each row is a re-measurement on a fresh pod built exactly from the recipe (n=9, seconds), stacked on the row above. Some items were below the noise threshold on their own and could only be validated bundled with others, hence several items per row.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Five of these carry over to other models.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;1. When the chip count doubles, re-decide what stays resident.&lt;/b&gt; On 4 chips the text encoder shard was about 12.4 GB per chip; keeping it next to the DiT slowed each denoising step by 1.25 s, so it had to be streamed. On 8 chips the shard halves and there is room: the text encoder became fully resident, later 8-way tensor parallel, and text encoding dropped from 3.0 s to 0.24 s. The VAE is similar. On 4 chips it was sharded, and every decode tile re-gathered all 36 blocks; carried over to the 8-chip starting point, that layout measured 1036 all-gathers per decode, 1.29 s in total. On 8 chips we first kept it gathered for the whole decode, then made it fully resident and compiled the entire decoder; video decoding went from 6.4 s to 2.9 s. The cost is about 27 s of extra compilation on the first request, and decoded frames are no longer bit-identical (PSNR 68–70 dB). When changing chip count or chip generation, every component that the old layout offloaded only because HBM was short should be re-evaluated against the new headroom.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;2. Thread contention on 180 vCPUs.&lt;/b&gt; Each of the 8 worker processes defaulted to 180 intra-op threads, and host-side torch ops fought over cores. The first symptom was a layout function taking 509 ms, versus 1 ms single-threaded (-0.92 s together with an ffmpeg pipe, re-measured from the recipe). Setting &lt;code&gt;OMP_NUM_THREADS=22&lt;/code&gt; globally (180 ÷ 8, rounded down) then took another spot, row_plan, from 610 ms to 2 ms, and that step saved a further 1.21 s end to end. When several processes share one large machine, this default almost always needs changing.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;3. Block-sparse attention kernel: a fixed bound instead of the row max.&lt;/b&gt; On v6e each iteration of this Pallas kernel takes about 1 µs; softmax elementwise work is about 37% of it, matmul only about 28%. The most expensive part of the softmax is the row-max reduction over 2048 lanes and the rescaling that follows. Following maxdiffusion, we use the Cauchy–Schwarz inequality to give a fixed upper bound on the logits (‖q‖·max‖k‖) instead of tracking the row max online, switch exp to exp2, and fold the scale into q. Program blocks where the bound is not safe enough fall back to the original path via a flag. Block-sparse attention only computes the selected subset, so maxdiffusion's guarantee that the row max is ≥ 0 does not hold here; the check is per program block rather than per head. A single layer got 23% faster, and together with text-encoder tensor parallelism the gain was -1.57 s. The change only alters rounding, and the accuracy gate still passes.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;4. Partial RoPE as a signed permutation matmul.&lt;/b&gt; H3's RoPE rotates 96 of the 128 channels, and the cut point is not aligned to the 128-lane width. The slicing version became about 16 small ops on TPU, each reading and writing q / k once. Multiplying by a signed permutation matrix, with cos / sin padded with 1 and 0 for the unrotated channels, gives bit-identical results for bf16 inputs, and the RoPE program went from 131.6 ms to 86.7 ms per step. It is not bit-identical for f32 inputs: the same trick applied to the f32 VAE gave frames at 67.86 dB PSNR.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;5. Write FSDP split rules against the model's real module names.&lt;/b&gt; Each FSDP2 unshard does two copies: shards into a flat buffer, and after the all-gather, back out into the individual parameters. If a unit holds only one parameter, the flat input is the shard itself and the flat output is the full parameter, so both copies can be skipped with bit-identical results (-0.55 s). But our first split rules followed diffusers naming (&lt;code&gt;to_out.0&lt;/code&gt; / &lt;code&gt;net.0.proj&lt;/code&gt; / &lt;code&gt;net.2&lt;/code&gt;), while the H3 DiT calls them &lt;code&gt;attn.to_out&lt;/code&gt; / &lt;code&gt;ff.fc_in&lt;/code&gt; / &lt;code&gt;ff.fc_out&lt;/code&gt;. The three largest matrices were never split out, and &lt;strong&gt;a name mismatch raises no error&lt;/strong&gt;. Fixing it saved another 0.98 s, of which about 0.2–0.5 s exceeds what the skipped copies can account for; that part has not been broken down (presumably related to all-gather granularity). After enabling any optimization that only applies to single-parameter units, count the modules that actually became single-parameter units.&lt;/p&gt;
&lt;h3 id="what-is-left"&gt;What is left&lt;a class="hd-a" href="#what-is-left" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;In the final 5-second configuration a DiT step takes 1.84 s. A serial floor from compute plus ICI traffic is about 0.48 s (in this stack, all-gather and matmul inside the same graph were measured not to overlap), so 3.8x remains. Video decoding takes 2.83 s against a floor of about 0.84 s. After the fixed-bound change we also tried a two-pass variant and register tiling for the block-sparse kernel; neither beat the noise threshold.&lt;/p&gt;
&lt;h2 id="15-second-clips-from-412-s-to-258-s"&gt;15-second clips: from 41.2 s to 25.8 s&lt;a class="hd-a" href="#15-second-clips-from-412-s-to-258-s" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Steps 1–3 were all about 5-second clips. This section moves to 15-second clips (362 frames) on the same 8 v6e chips, timed the same way, from request entry to MP4 written. Real-time 15-second generation already exists on GPUs: vLLM-Omni, for example, reports about 14.1 s client-side end to end on 8 B300 GPUs with 4 dense-attention steps (self-reported by the authors; hardware, step count and timing boundary all differ from ours). Real time is the long-term direction for this line of work too.&lt;/p&gt;
&lt;h3 id="8-steps-would-not-get-there-so-4-steps"&gt;8 steps would not get there, so 4 steps&lt;a class="hd-a" href="#8-steps-would-not-get-there-so-4-steps" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;Running 15-second clips with the 5-second recipe took 76.6 s with the 8-step checkpoint. Extrapolating from compute, the lossless floor for 8 steps is about 12 s, and getting close to real time would need the whole pipeline above 80% of peak; that is not realistic. So we switched to the 4-step Preview-v0.2 checkpoint. Side-by-side clips showed the 8-step model clearly better in sharpness, detail and storytelling; the 4-step gap was expected, and we went after speed first.&lt;/p&gt;
&lt;h3 id="changes-and-result"&gt;Changes and result&lt;a class="hd-a" href="#changes-and-result" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;figure&gt;
  &lt;div class="chart" role="img" aria-label="End-to-end time for 4-step 15-second clips"&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;4 steps + 5 s recipe&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill base" style="width:calc((100% - 5.5em) * 1.0000)"&gt;&lt;/span&gt;&lt;span class="val"&gt;41.17&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;VAE out of HBM while denoising&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.8778)"&gt;&lt;/span&gt;&lt;span class="val"&gt;36.14&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Fixed 64 blocks per row&lt;small&gt;lossy&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.7741)"&gt;&lt;/span&gt;&lt;span class="val"&gt;31.87&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Output rank writes MP4&lt;small&gt;+ three small DiT changes&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.7385)"&gt;&lt;/span&gt;&lt;span class="val"&gt;30.40&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;uint8 on device&lt;small&gt;+ last-round tile balance&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.6909)"&gt;&lt;/span&gt;&lt;span class="val"&gt;28.45&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Whole decoder compiled&lt;small&gt;+ VAE RoPE matmul&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill" style="width:calc((100% - 5.5em) * 0.6202)"&gt;&lt;/span&gt;&lt;span class="val"&gt;25.53&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;figcaption&gt;End-to-end time (seconds) at 1344×768 / 362 frames / 4 steps, development pod, n=9. Re-measured on a fresh pod built exactly from the final recipe: 25.77 s (slowest 26.21 s).&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Two of these deserve a closer look:&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Under HBM pressure the runtime evicts loaded programs.&lt;/b&gt; Activations and attention tables are much larger for a 15-second clip. During denoising only about 10 GB of HBM was left, so every layer the runtime evicted and reloaded attention programs and defragmented memory, adding a 917 ms gap per step. Moving the video VAE back to the host during denoising freed about 9 GB, and the gap dropped to 0.1 ms. In a profile this overhead shows up as blank space between programs and looks like synchronization waits.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Four changes in the second half of decoding.&lt;/b&gt; Frames are quantized to uint8 on the TPU before the transfer to host (4.48 → 1.12 GB, -1.11 s); the last round of tiles is split evenly across the 8 chips (-1.14 s); the full decoder is gathered and compiled as one graph at the start of decoding (-1.96 s); the VAE RoPE becomes a matmul (-0.98 s). The first two leave the MP4 byte-identical; the last two are near-lossless, with frames at about 67.7 dB PSNR.&lt;/p&gt;
&lt;h3 id="options-we-tried-but-did-not-adopt"&gt;Options we tried but did not adopt&lt;a class="hd-a" href="#options-we-tried-but-did-not-adopt" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;The first two rows were measured on the configuration that used the taeh3 decoder at the time, not on the same baseline as the final 25.77 s above.&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Option&lt;/th&gt;
&lt;th style="text-align:right"&gt;End to end&lt;/th&gt;
&lt;th&gt;Verdict&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Lightweight VAE decoder taeh3&lt;/td&gt;
&lt;td style="text-align:right"&gt;20.65 s&lt;/td&gt;
&lt;td&gt;Frames at only 29.68 dB vs the full VAE; rejected after watching&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Blocks selected per row cut from 64 to 32&lt;/td&gt;
&lt;td style="text-align:right"&gt;19.52 s&lt;/td&gt;
&lt;td&gt;A further -1.1 s on the taeh3 configuration, clearly worse image; rejected&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;int8 / fp8 weights and activations&lt;/td&gt;
&lt;td style="text-align:right"&gt;—&lt;/td&gt;
&lt;td&gt;int8 matmul 0.97–0.98x on v6e, no speedup from fp8&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;int8 all-to-all&lt;/td&gt;
&lt;td style="text-align:right"&gt;—&lt;/td&gt;
&lt;td&gt;Inbound communication time down only 24%, below the preset 25% bar&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;The final recipe runs at 25.77 s, 37% less time than the starting point. Denoising takes about 17.7 s of that and is the largest remaining piece. Small item-by-item changes to denoising had stopped paying off, so the next step is structural (a different attention implementation, a different compilation granularity).&lt;/p&gt;
&lt;h2 id="a-resident-service-4-requests-at-once"&gt;A resident service: 4 requests at once&lt;a class="hd-a" href="#a-resident-service-4-requests-at-once" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;This section is still 15-second clips with the 4-step checkpoint, now in a serving scenario: 4 different prompts arrive at the same time at one resident process. Keeping the model in a resident process and feeding it varied prompts exposed three problems that single-prompt tests never show:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Unreachable Python garbage holding device buffers.&lt;/b&gt; By the third distinct prompt in one process, about 4.1 GB of extra memory was held after denoising, and video decoding then ran out of memory. With one &lt;code&gt;gc.collect()&lt;/code&gt; per request, the scenarios that had reproduced the OOM no longer hit it; calling &lt;code&gt;gc.freeze()&lt;/code&gt; first cut each collection from 530–785 ms to 18–45 ms. One resident process with gc still showed the same +4.6 GB once (not reproduced since, mechanism not found), and rank 0 has only about 0.1–0.3 GB of HBM headroom during decoding, so this needs watching.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;A recompile limit that silently drops the DiT to eager.&lt;/b&gt; FastVideo's LoRA layer sets dynamo's &lt;code&gt;recompile_limit&lt;/code&gt; to 16, and each new sequence length triggers 4 recompiles. From the fifth length on, the DiT stops compiling and runs eagerly, and &lt;strong&gt;its output differs visibly from the compiled path&lt;/strong&gt; (PSNR 17–19 dB) with no error raised. Raising the limit to 1024 fixed it.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;About 90 extra seconds on the first request of a new length.&lt;/b&gt; We first blamed DiT recompilation; per-step timing showed it was VSA-H3's tile-geometry metadata, computed on the TPU as a chain of small eager ops that compile once per shape. Computing it on the host cut that step from 91.8 s to 6–9 ms. Combined with padding text to four buckets (128 / 256 / 512 / 1024) so that prompts with the same number of text tiles within a bucket share one DiT compilation (4 buckets, 4 packed lengths), the first request at a new length went from 110–125 s to 25.7–27.0 s. That figure was measured only for prompts in the 128 bucket whose text fits in one tile; when the number of text tiles changes within a bucket, the first request is still about 1.26x the steady state (one measurement), and the first request to enter any other bucket is 1.4–2.7x, for reasons not yet found.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;After these fixes (this configuration adds a few more changes on top of the 15-second section), the 4-way burst, 3 rounds of 4 requests, gave a P95 of 97.6 s, 24.2–24.6 s per request and 2.47 clips per minute. With one model copy processing 4 requests serially, P95 is essentially 4 times the single-request time, so lowering P95 mostly means lowering single-request time. Splitting into two 4-chip replicas does not help either: we measured roughly equal chip-seconds per request on 4 and 8 chips (about 206–211 for 4 steps), and v6e has no 6-chip machine type.&lt;/p&gt;
&lt;h2 id="takeaways"&gt;Takeaways&lt;a class="hd-a" href="#takeaways" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Lesson&lt;/th&gt;
&lt;th&gt;Where it applies&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;E0101 means a program load needs contiguous HBM; keep each all-gather program to a few hundred MB&lt;/td&gt;
&lt;td&gt;FSDP on TPUs with tight HBM&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;An AdaLN projection that depends only on the timestep can live on host and be cached&lt;/td&gt;
&lt;td&gt;Few-step distilled DiTs&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;After doubling chip count, re-decide resident vs offloaded for each component&lt;/td&gt;
&lt;td&gt;Any move to a new chip count or generation&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Set &lt;code&gt;OMP_NUM_THREADS&lt;/code&gt; explicitly when processes share a large machine&lt;/td&gt;
&lt;td&gt;Multi-rank inference with host-side torch ops&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Replace the row max with a fixed bound in block-sparse attention, falling back per program block&lt;/td&gt;
&lt;td&gt;TPU kernels where softmax elementwise work dominates&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Gather FSDP single-parameter units straight into the parameter buffer; write split rules by real module names and count the result&lt;/td&gt;
&lt;td&gt;torch FSDP2 inference&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;In a resident process, check gc, dynamo's recompile limit and small ops compiled per shape&lt;/td&gt;
&lt;td&gt;Turning an offline script into a resident service&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;Next directions: a 5-second DiT step is still about 3.8x from its serial floor; denoising for 15-second clips needs structural changes; and resident-service P95 follows single-request time. The whole effort followed the &lt;a href="https://rsi.maxwell-x.dev"&gt;Curvature Drive&lt;/a&gt; workflow: turn the target into an absolute number, account for time from profiles, judge each path by its upper bound, and re-measure every adopted change on a fresh pod built exactly from the recipe. The decision to move from 4 chips to 8 also came from an upper-bound estimate of this kind.&lt;/p&gt;
</content>
    <category term="TPU"/>
    <category term="v6e"/>
    <category term="FastVideo"/>
    <category term="Video Generation"/>
    <category term="Performance Tuning"/>
    <category term="B200"/>
  </entry>
  <entry>
    <title>Cold Compile Optimization, Part 3: Cross-Rank Reuse for Sequence-Parallel Buckets, 48 Minutes to 17.7</title>
    <link href="https://blog.maxwell-x.dev/en/hy4-cold-compile-sp/"/>
    <id>https://blog.maxwell-x.dev/en/hy4-cold-compile-sp/</id>
    <published>2026-10-12T00:00:00Z</published>
    <updated>2026-10-12T00:00:00Z</updated>
    <summary>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.</summary>
    <content type="html" xml:base="https://blog.maxwell-x.dev/en/hy4-cold-compile-sp/">&lt;div class="tldr" role="note"&gt;
&lt;p&gt;&lt;strong&gt;TL;DR&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Problem&lt;/strong&gt;: 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 &lt;code&gt;reshape(W, -1, d)[rank]&lt;/code&gt; with &lt;code&gt;rank&lt;/code&gt; 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.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Solution&lt;/strong&gt;: a new sharded op runs one all_to_all of &lt;code&gt;arange(W)&lt;/code&gt; 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.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Gain&lt;/strong&gt;: 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.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;figure&gt;
  &lt;div class="chart" role="img" aria-label="Cold compile time from 48.2 minutes down to 17.7 minutes"&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Original recipe&lt;small&gt;SP on · 3 runs&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill base" style="width:calc((100% - 5.5em) * 1.0000)"&gt;&lt;/span&gt;&lt;span class="val"&gt;48.2&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;+ rank at run time&lt;small&gt;3 runs&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.3885)"&gt;&lt;/span&gt;&lt;span class="val"&gt;18.7&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;+ background save + staggered small graphs&lt;small&gt;3 runs&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill" style="width:calc((100% - 5.5em) * 0.3663)"&gt;&lt;/span&gt;&lt;span class="val"&gt;17.7&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Reference: SP off&lt;small&gt;same image · 1 run&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill base" style="width:calc((100% - 5.5em) * 0.3671)"&gt;&lt;/span&gt;&lt;span class="val"&gt;17.7&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="legend"&gt;&lt;span&gt;&lt;i style="background:var(--ink-2)"&gt;&lt;/i&gt;Original / reference&lt;/span&gt;&lt;span&gt;&lt;i style="background:repeating-linear-gradient(135deg,var(--accent-2) 0 4px,transparent 4px 7px);border:1px solid var(--accent-2)"&gt;&lt;/i&gt;Intermediate&lt;/span&gt;&lt;span&gt;&lt;i style="background:var(--accent)"&gt;&lt;/i&gt;Optimized&lt;/span&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;figcaption&gt;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.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;h2 id="background"&gt;Background&lt;a class="hd-a" href="#background" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;&lt;a href="/en/hy4-cold-compile/"&gt;Part 1 of this series&lt;/a&gt; cut Hy4-preview's cold compile on TPU v7 from 95 minutes to about 14, and &lt;a href="/en/hy4-cold-compile-dp/"&gt;Part 2&lt;/a&gt; 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.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;h2 id="problem-every-rank-compiled-the-sequence-parallel-buckets"&gt;Problem: every rank compiled the sequence-parallel buckets&lt;a class="hd-a" href="#problem-every-rank-compiled-the-sequence-parallel-buckets" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;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:&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
    &lt;tr&gt;&lt;th&gt;Phase&lt;/th&gt;&lt;th&gt;SP on (mean of 3)&lt;/th&gt;&lt;th&gt;SP off (1 run)&lt;/th&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td&gt;Pod start to first round (incl. weight loading)&lt;/td&gt;&lt;td&gt;171 s&lt;/td&gt;&lt;td&gt;165 s&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td&gt;Round 1: the 6 buckets below 512 (incl. the gap after it)&lt;/td&gt;&lt;td&gt;243 s&lt;/td&gt;&lt;td&gt;244 s&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td&gt;&lt;b&gt;Round 2: the 5 buckets from 512 up&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;2114 s&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;412 s&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td&gt;After round 2, before round 3&lt;/td&gt;&lt;td&gt;214 s&lt;/td&gt;&lt;td&gt;130 s&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td&gt;Round 3 (speculative decoding) and on to ready&lt;/td&gt;&lt;td&gt;125 s&lt;/td&gt;&lt;td&gt;111 s&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td&gt;Total (ready time in the server log)&lt;/td&gt;&lt;td&gt;2866 s&lt;/td&gt;&lt;td&gt;1062 s&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;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:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Cross-rank replay was rejected for every sequence-parallel bucket with the reason &lt;code&gt;different code or constants&lt;/code&gt;. About 180 artifacts were rejected per cold compile; with sequence parallelism off, 0.&lt;/li&gt;
&lt;li&gt;The replay fingerprint covers the FX graph code plus small constants hashed by value. The sequence-parallel slice is &lt;code&gt;hidden_states.reshape(W, -1, d)[rank]&lt;/code&gt; with &lt;code&gt;rank&lt;/code&gt; a Python integer, which tracing writes into the graph as a constant, so each rank's fingerprint differs.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Bucketed by nature, &amp;quot;every rank recompiling buckets it could have replayed&amp;quot; is 1588 s (55.4%) and &amp;quot;rank 0 idling for the other ranks after its own compile&amp;quot; is 84 s (2.9%): 58.3% together, from one source. Part 1's &amp;quot;serial compile on rank 0&amp;quot; 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).&lt;/p&gt;
&lt;h2 id="solution"&gt;Solution&lt;a class="hd-a" href="#solution" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;h3 id="1-read-the-rank-at-run-time"&gt;1. Read the rank at run time&lt;a class="hd-a" href="#1-read-the-rank-at-run-time" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;&lt;b&gt;Goal.&lt;/b&gt; All 16 ranks trace a byte-identical graph, and each rank still gets its own block of rows.&lt;/p&gt;
&lt;p&gt;We went through three versions; the first two were dropped:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Index with the rank stored in a buffer tensor.&lt;/b&gt; 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).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Take the device position with &lt;code&gt;lax.axis_index&lt;/code&gt; inside a sharded JAX op, then map it to the TP rank through a table.&lt;/b&gt; The CPU unit test passes, but &lt;code&gt;axis_index&lt;/code&gt; lowers to &lt;code&gt;partition-id&lt;/code&gt;, 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).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;An in-group all_to_all.&lt;/b&gt; In the axis group ordered by TP rank, all_to_all &lt;code&gt;arange(W)&lt;/code&gt;: 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 &lt;code&gt;dynamic_slice&lt;/code&gt; with that run-time value cuts this rank's &lt;code&gt;T/W&lt;/code&gt; 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 &lt;code&gt;partition-id&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;b&gt;Tests.&lt;/b&gt; Three new unit tests, each with a negative control: with a scrambled device-to-rank mapping, every shard equals &lt;code&gt;x.reshape(W, -1, d)[owner]&lt;/code&gt; (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 &lt;code&gt;partition-id&lt;/code&gt; (the &lt;code&gt;axis_index&lt;/code&gt; version fails).&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Effect.&lt;/b&gt; 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.&lt;/p&gt;
&lt;p&gt;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).&lt;/p&gt;
&lt;h3 id="2-stagger-the-sampler-side-precompile-across-ranks"&gt;2. Stagger the sampler-side precompile across ranks&lt;a class="hd-a" href="#2-stagger-the-sampler-side-precompile-across-ranks" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;&lt;b&gt;Problem.&lt;/b&gt; 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.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Approach.&lt;/b&gt; 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.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Effect.&lt;/b&gt; 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.&lt;/p&gt;
&lt;h3 id="3-save-compiled-artifacts-in-the-background"&gt;3. Save compiled artifacts in the background&lt;a class="hd-a" href="#3-save-compiled-artifacts-in-the-background" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;&lt;b&gt;Problem.&lt;/b&gt; 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 &amp;quot;round done&amp;quot; and &amp;quot;next round's tracing starts&amp;quot;.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Approach.&lt;/b&gt; A switch, off by default, moves the save to a background thread.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Effect.&lt;/b&gt; 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).&lt;/p&gt;
&lt;p&gt;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 &amp;quot;intermediate version&amp;quot; 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.&lt;/p&gt;
&lt;h2 id="an-idea-that-was-refuted-removing-the-512-guard"&gt;An idea that was refuted: removing the 512 guard&lt;a class="hd-a" href="#an-idea-that-was-refuted-removing-the-512-guard" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;&lt;b&gt;The idea.&lt;/b&gt; 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: &lt;code&gt;s72 &amp;lt;= 511&lt;/code&gt;. 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.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;The refutation.&lt;/b&gt; Before spending machine time, an independent reviewer was asked, as usual, to look for reasons it would fail, and it did not hold:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The sequence-parallel branch is enabled on &lt;code&gt;num_tokens % 512 == 0&lt;/code&gt;. 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.&lt;/li&gt;
&lt;li&gt;The log shows only &lt;code&gt;s72 &amp;lt;= 511&lt;/code&gt; 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.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;The lesson is worth stating on its own: &lt;b&gt;one guard text in the log does not mean one guard is at work.&lt;/b&gt; To decide that a split is gone, check that the total number of &amp;quot;left to a later trace&amp;quot; lines drops to zero and that the Dynamo trace count goes down, not that a particular string disappears. Checking only that &lt;code&gt;s72 &amp;lt;= 511&lt;/code&gt; disappears would give a false positive: after the change it would be replaced by the divisibility guard's text, with the same line count.&lt;/p&gt;
&lt;h2 id="results"&gt;Results&lt;a class="hd-a" href="#results" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;div class="tw"&gt;&lt;table&gt;
    &lt;tr&gt;&lt;th&gt;Configuration&lt;/th&gt;&lt;th&gt;Cold compile (polling)&lt;/th&gt;&lt;th&gt;Ready time in server log&lt;/th&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td&gt;Original recipe, SP on&lt;/td&gt;&lt;td&gt;48.2 min (2869 / 2938 / 2871 s)&lt;/td&gt;&lt;td&gt;2866 s&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td&gt;+ rank at run time (intermediate version)&lt;/td&gt;&lt;td&gt;18.7 min (1125 / 1124 / 1123 s)&lt;/td&gt;&lt;td&gt;1096 s&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td&gt;+ background save (alone)&lt;/td&gt;&lt;td&gt;18.3 min (1123 / 1059 / 1119 s), under the bar&lt;/td&gt;&lt;td&gt;1067 s&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td&gt;+ background save + staggered small graphs (final)&lt;/td&gt;&lt;td&gt;17.7 min (1059 / 1059 / 1060 s)&lt;/td&gt;&lt;td&gt;1023 s&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td&gt;Reference: same image, SP off&lt;/td&gt;&lt;td&gt;17.7 min (1 run)&lt;/td&gt;&lt;td&gt;1062 s&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Accuracy.&lt;/b&gt; 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).&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Performance.&lt;/b&gt; 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.&lt;/p&gt;
&lt;h2 id="is-the-replayed-program-the-same-as-one-compiled-locally"&gt;Is the replayed program the same as one compiled locally?&lt;a class="hd-a" href="#is-the-replayed-program-the-same-as-one-compiled-locally" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;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:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Outputs.&lt;/b&gt; 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.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Programs.&lt;/b&gt; 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.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;h2 id="limitations"&gt;Limitations&lt;a class="hd-a" href="#limitations" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;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.&lt;/li&gt;
&lt;li&gt;The paired GSM8K comparison with production leans negative (13 worse / 6 better, p≈0.084), not significant; the cause has not been investigated.&lt;/li&gt;
&lt;li&gt;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.&lt;/li&gt;
&lt;li&gt;Background saving alone did not clear the significance bar, and about 35 s of the combined 73 s is unattributed.&lt;/li&gt;
&lt;li&gt;The replay correctness comparison was done once; node placement is part of the compile cache key, so a different placement still recompiles.&lt;/li&gt;
&lt;li&gt;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.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="where-this-applies"&gt;Where this applies&lt;a class="hd-a" href="#where-this-applies" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Model code that slices data along the TP dimension.&lt;/b&gt; 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 &lt;code&gt;different code or constants&lt;/code&gt; rejections in the replay log, or trace one shape as two different ranks and compare the graph code. Upstream vllm-torchtpu &lt;a href="https://github.com/vllm-project/vllm-torchtpu/pull/1457"&gt;#1457&lt;/a&gt; fixed the same class of problem (the DCP LSE merge indexed by rank).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Sharded ops that need this rank's index.&lt;/b&gt; On torch_tpu, avoid &lt;code&gt;lax.axis_index&lt;/code&gt; and pass the index in as data through an in-group all_to_all.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Small graphs in precompile.&lt;/b&gt; 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.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Reading compile splits from logs.&lt;/b&gt; Count the rejection lines and the trace count; do not go by one guard text.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="series"&gt;Series&lt;a class="hd-a" href="#series" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Overview: &lt;a href="/en/hy4-on-tpu-v7/"&gt;Beating B200 from Scratch: Porting and Optimizing Hy4 Inference on TPU v7&lt;/a&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href="/en/hy4-tpu-vs-b200/"&gt;From 2 tok/s to Beating B200: Optimizing Hy4 Inference on TPU v7&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-weight-loading/"&gt;Hy4 Weight Loading on TPU v7: From 857 Seconds to 68&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-cold-compile/"&gt;95 Minutes to 14: Cold Compile Optimization for Hy4 on TPU v7&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-cold-compile-dp/"&gt;Cold Compile Optimization, Part 2: Cross-DP Compile Reuse for Data-Parallel Deployments on TPU&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-cold-compile-sp/"&gt;Cold Compile Optimization, Part 3: Cross-Rank Reuse for Sequence-Parallel Buckets, 48 Minutes to 17.7&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="postscript" role="note"&gt;
&lt;p&gt;Data from the sequence-parallel cold compile optimization records of 2026-10-11 to 10-12.&lt;/p&gt;
&lt;/div&gt;
</content>
    <category term="TPU"/>
    <category term="vLLM"/>
    <category term="XLA"/>
    <category term="Compilation"/>
    <category term="Sequence Parallelism"/>
  </entry>
  <entry>
    <title>Cold Compile Optimization, Part 2: Cross-DP Compile Reuse for Data-Parallel Deployments on TPU</title>
    <link href="https://blog.maxwell-x.dev/en/hy4-cold-compile-dp/"/>
    <id>https://blog.maxwell-x.dev/en/hy4-cold-compile-dp/</id>
    <published>2026-10-09T00:00:00Z</published>
    <updated>2026-10-09T00:00:00Z</updated>
    <summary>The cross-rank replay described in the previous post only looks for reusable compiled artifacts within the same DP index. In a pure data-parallel deployment each inference engine has a DP index of its own, so replay never happens. We widened replay to search across DP indices, and for layouts that mix tensor and data parallelism we normalized the process group names in the graph fingerprint. On our self-maintained branch with the same image, the time from weights loaded to service ready dropped from 741 s to 270 s for Qwen3.5 DP8, and from 703 s to 251 s for TP2×DP4.</summary>
    <content type="html" xml:base="https://blog.maxwell-x.dev/en/hy4-cold-compile-dp/">&lt;div class="tldr" role="note"&gt;
&lt;p&gt;&lt;strong&gt;TL;DR&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Problem&lt;/strong&gt;: the cross-rank replay proposed upstream in vllm-torchtpu (not yet merged into main) only looks for reusable compiled artifacts within the same DP index. Under pure data parallelism each engine owns one DP index, so the replay count is 0, and for every bucket all 8 engines go through tracing, conversion, loading and saving on their own.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Solution&lt;/strong&gt;: with tensor parallel size 1, widen the replay search to all DP indices. With tensor parallel size greater than 1, the graphs of different DP groups differ only in the process group names of collective calls, so we first normalize the group names in the graph fingerprint and then replay across DP.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Gain&lt;/strong&gt;: on our self-maintained branch with the same image, the time from weights loaded to service ready dropped from 741 s to 270 s for Qwen3.5 DP8, from 703 s to 251 s for TP2×DP4, and from 606 s to 241 s for TP4×DP2. All of them passed the accuracy evaluation.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="background"&gt;Background&lt;a class="hd-a" href="#background" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;&lt;a href="/en/hy4-cold-compile/"&gt;The previous post&lt;/a&gt; covered cold compile optimization for Hy4 on TPU v7. One of the key changes was replaying compiled artifacts between ranks: vllm-torchtpu assigns token buckets to different ranks for compilation, and once one rank has finished a complete artifact and it passes the graph fingerprint check, the other ranks load it directly instead of tracing and compiling again. Hy4's production deployment is TP16 with a single DP group, so all 16 ranks can replay from each other, and the change brought a significant gain.&lt;/p&gt;
&lt;p&gt;Data-parallel (DP) deployments are different. For a model like Qwen3.5-397B we deploy DP8 on a single TPU v7 host: each of the 8 inference engines holds a full copy of the attention weights and serves its own requests, while expert parallelism shards the MoE experts across the 8 engines. Yet replay barely shortened cold compile for this layout. This post explains why, and how we made replay work under data parallelism.&lt;/p&gt;
&lt;p&gt;Unless noted otherwise, cold compile time in this post means the time from the last &lt;code&gt;Loading weights took&lt;/code&gt; log line to service ready, starting from an empty cache. It excludes pod startup and weight loading. The previous post measured from pod creation, so the two sets of numbers are not directly comparable.&lt;/p&gt;
&lt;h2 id="problem-why-replay-fails-under-data-parallelism"&gt;Problem: why replay fails under data parallelism&lt;a class="hd-a" href="#problem-why-replay-fails-under-data-parallelism" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;h3 id="replay-only-searches-within-the-same-dp-index"&gt;Replay only searches within the same DP index&lt;a class="hd-a" href="#replay-only-searches-within-the-same-dp-index" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;In the code, when cross-rank replay looks for artifacts to replay, it only matches other ranks under the same DP index, and the lock file name used to claim a compile task also contains the DP index. With tensor parallel size 1, each DP index has only one rank, so there is no peer to find. In a controlled experiment with the same image and parallel precompile enabled, Qwen3.5 DP8 recorded 0 replays; the same setup with the cross-DP replay patch recorded 70 (10 buckets × 7 engines).&lt;/p&gt;
&lt;h3 id="what-gets-repeated-is-the-vllm-layer-compile-pipeline"&gt;What gets repeated is the vLLM-layer compile pipeline&lt;a class="hd-a" href="#what-gets-repeated-is-the-vllm-layer-compile-pipeline" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;This does not mean the 8 engines compile the same XLA program 8 times. Judging by the cache directory, in each of three cold compiles every bucket has only 1 copy of the XLA cache, the graphs exported by the 8 engines have identical md5, and the vLLM-layer artifacts of all engines have the same byte size, differing only in timing metadata. What is not shared is the vLLM-layer pipeline: AOTAutograd, conversion from FX graph to MLIR, and loading and serializing the compiled artifact. Every engine runs these steps itself, all 8 engines work on the same bucket at the same time, and buckets advance one after another.&lt;/p&gt;
&lt;h3 id="where-the-time-goes"&gt;Where the time goes&lt;a class="hd-a" href="#where-the-time-goes" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;Take the original Qwen3.5 DP8 recipe as an example (an older image, without parallel precompile). Three cold compiles averaged 1008.1 s. Cross-checking the log timeline against the modification times of the cache files gives the following breakdown:&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Item&lt;/th&gt;
&lt;th style="text-align:right"&gt;s&lt;/th&gt;
&lt;th style="text-align:right"&gt;Share&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;The 9 main-model buckets other than the slowest of the 10: 8 engines compile the same bucket in lockstep, buckets run serially&lt;/td&gt;
&lt;td style="text-align:right"&gt;646.3&lt;/td&gt;
&lt;td style="text-align:right"&gt;64.1%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Necessary compile (the slowest bucket, 1024)&lt;/td&gt;
&lt;td style="text-align:right"&gt;93.2&lt;/td&gt;
&lt;td style="text-align:right"&gt;9.2%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Disk writes and serialization&lt;/td&gt;
&lt;td style="text-align:right"&gt;87.6&lt;/td&gt;
&lt;td style="text-align:right"&gt;8.7%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Sampler and other small graphs&lt;/td&gt;
&lt;td style="text-align:right"&gt;62.3&lt;/td&gt;
&lt;td style="text-align:right"&gt;6.2%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Dynamo tracing&lt;/td&gt;
&lt;td style="text-align:right"&gt;54.8&lt;/td&gt;
&lt;td style="text-align:right"&gt;5.4%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Compilation during the profile run&lt;/td&gt;
&lt;td style="text-align:right"&gt;50.0&lt;/td&gt;
&lt;td style="text-align:right"&gt;5.0%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Other&lt;/td&gt;
&lt;td style="text-align:right"&gt;14.0&lt;/td&gt;
&lt;td style="text-align:right"&gt;1.4%&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;The compile window of the 9 main-model buckets takes nearly two thirds of the total, and the logs cannot separate how much of it is XLA compilation and how much is the vLLM-layer pipeline. If each bucket went through the full pipeline on only one engine, with the other engines replaying at zero cost, and the profile run were skipped, the theoretical floor would be about 223 s.&lt;/p&gt;
&lt;h2 id="solution"&gt;Solution&lt;a class="hd-a" href="#solution" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;h3 id="tensor-parallel-size-1-cross-dp-replay"&gt;Tensor parallel size 1: cross-DP replay&lt;a class="hd-a" href="#tensor-parallel-size-1-cross-dp-replay" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;The change itself is small: widen the search for peer artifacts from the same DP index to all DP indices. The graph fingerprint is kept and checked on every replay. Each bucket then goes through the full pipeline on one engine, and the other 7 replay directly.&lt;/p&gt;
&lt;p&gt;There are two versions of this change. All Qwen3.5 data in this post comes from the implementation on our self-maintained branch: besides widening the search, it replaces the DP index in the claim lock file name with a uniform marker, which, together with the claim file mechanism mentioned in the previous post, ensures that only one engine compiles each bucket. The version submitted upstream only widens the search. Its switch does not enter the compile cache key, so toggling it does not trigger recompilation. Its effect is measured separately on the reduced-layer GLM-5.2 testbed below.&lt;/p&gt;
&lt;p&gt;On the deployments we tested, none of the following evidence found replay changing the output:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Program level&lt;/strong&gt;: the graphs exported by the 8 engines have identical md5, and the vLLM-layer artifacts have the same byte size, differing only in timing metadata. The expert start index used by expert parallelism is a graph input, not a constant.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Accuracy evaluation&lt;/strong&gt;: Qwen3.5 DP8 with cross-DP replay enabled averaged 96.82 on GSM8K and 89.21 on MMLU over three rounds. On the finalized image, three rounds gave GSM8K 96.89 and MMLU 89.26, with no significant difference from the original recipe in a per-question paired comparison.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Per-logprob comparison with real weights&lt;/strong&gt;: on upstream code and a newer torch_tpu version, we deployed DP8 with the real weights of the first 6 layers of DeepSeek-V3.2. Each DP rank sent the same fixed 5 prompts, and every rank ran replayed artifacts for at least 4 buckets. For all 40 outputs, the text and the top-5 logprobs at every position were identical to runs without replay. In the positive control (changing the MoE quantization block size), all 40 differed.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;All of this evidence is at the output level. The graph fingerprint cannot see closure constants outside the graph, so on other models or layouts you still need to first confirm that no per-rank values enter closures, or run the same output comparison.&lt;/p&gt;
&lt;h3 id="tensor-parallel-size-greater-than-1-normalizing-process-group-names"&gt;Tensor parallel size greater than 1: normalizing process group names&lt;a class="hd-a" href="#tensor-parallel-size-greater-than-1-normalizing-process-group-names" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;When tensor parallel size is greater than 1, the TP ranks within each DP group form their own process group. The last argument of a collective call in the graph (such as &lt;code&gt;_c10d_functional.all_reduce(..., 'sum', '3')&lt;/code&gt;) is the process group name. Different DP groups have different group names, so their graph fingerprints differ and every replay is rejected. In Qwen3.5 TP2×DP4, the two graphs of the same TP rank in different DP groups differ in 242 lines, all of them group names.&lt;/p&gt;
&lt;p&gt;Before computing the graph fingerprint, we replace the group names in collective calls with a uniform placeholder and leave everything else unchanged (a unit test pins down that only group names are normalized). On real graphs, all 361 calls were rewritten, after which the graphs of different DP groups no longer differed at all. With the patch, Qwen3.5 TP2×DP4 went from 0 replays (262 rejected) to 70 replays (0 rejected). On the vLLM 0.29 self-maintained branch we use, the start and end positions of the vocabulary shards are already tensors rather than constants, so after group name normalization the graphs of all 8 workers are identical. Replay then spans both DP groups and TP ranks, and each bucket needs to be compiled only once.&lt;/p&gt;
&lt;p&gt;Whether this is safe depends on how the underlying runtime compiles collectives for subgroups: cross-group replay is correct only if the subgroup programs of different DP groups are themselves identical. We confirmed that the runtime version we used at the time satisfies this, but a newer version that upstream pinned later changed the device-assignment-related part of the compile cache, so cross-DP-group replay could load a program with a different device assignment (inference, not verified on hardware). For this reason we did not submit this part upstream, and on our self-maintained branch we added a version check that refuses to normalize and prints a warning when the runtime version is newer or unknown.&lt;/p&gt;
&lt;h3 id="skipping-the-profile-run"&gt;Skipping the profile run&lt;a class="hd-a" href="#skipping-the-profile-run" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;Data-parallel deployments can also set the KV cache size directly with &lt;code&gt;--kv-cache-memory-bytes&lt;/code&gt; and skip the profile run at startup, with the number of KV blocks still fixed by &lt;code&gt;--num-gpu-blocks-override&lt;/code&gt;. On Qwen3.5 DP8 the profile run takes about 100 s, and skipping it is necessary to reach the theoretical floor above.&lt;/p&gt;
&lt;h2 id="gains"&gt;Gains&lt;a class="hd-a" href="#gains" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;In the comparison below, both arms use the same image, and both have parallel precompile enabled and skip the local AOTAutograd save and the profile run. The only difference is whether cross-DP replay takes effect.&lt;/p&gt;
&lt;figure&gt;
  &lt;div class="chart" role="img" aria-label="Cold compile time for three Qwen3.5 layouts before and after cross-DP replay takes effect"&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;DP8&lt;small&gt;TP1&lt;/small&gt;&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 1.0000)"&gt;&lt;/span&gt;&lt;span class="val"&gt;741&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.3647)"&gt;&lt;/span&gt;&lt;span class="val"&gt;270&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;TP2×DP4&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.9483)"&gt;&lt;/span&gt;&lt;span class="val"&gt;703&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.3390)"&gt;&lt;/span&gt;&lt;span class="val"&gt;251&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;TP4×DP2&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.8182)"&gt;&lt;/span&gt;&lt;span class="val"&gt;606&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.3256)"&gt;&lt;/span&gt;&lt;span class="val"&gt;241&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="legend"&gt;&lt;span&gt;&lt;i style="background:var(--ink-2)"&gt;&lt;/i&gt;0 replays&lt;/span&gt;&lt;span&gt;&lt;i style="background:var(--accent)"&gt;&lt;/i&gt;Cross-DP replay active&lt;/span&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;figcaption&gt;Cold compile time (seconds) of Qwen3.5-397B on a single TPU v7 host, from weights loaded to service ready, empty cache, with both arms of each layout on the same image. The 0-replay arms were measured once each. Of the arms with replay active, DP8 and TP2×DP4 were each measured three times and averaged, and TP4×DP2 was measured once. The TP2×DP4 control arm had the cross-DP switch on but group names not normalized, so every replay was rejected.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Layout&lt;/th&gt;
&lt;th style="text-align:right"&gt;0 replays&lt;/th&gt;
&lt;th style="text-align:right"&gt;Cross-DP replay active&lt;/th&gt;
&lt;th&gt;Accuracy evaluation&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Qwen3.5 DP8&lt;/td&gt;
&lt;td style="text-align:right"&gt;741.1 s (1 run)&lt;/td&gt;
&lt;td style="text-align:right"&gt;270.3 s (3 runs: 273.4 / 268.7 / 268.7)&lt;/td&gt;
&lt;td&gt;Same arm, three rounds: GSM8K 96.82, MMLU 89.21&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Qwen3.5 TP2×DP4&lt;/td&gt;
&lt;td style="text-align:right"&gt;702.8 s (1 run)&lt;/td&gt;
&lt;td style="text-align:right"&gt;251.2 s (3 runs: 249.1 / 246.8 / 257.8)&lt;/td&gt;
&lt;td&gt;Finalized image, three rounds: GSM8K 96.79, MMLU 89.30&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Qwen3.5 TP4×DP2&lt;/td&gt;
&lt;td style="text-align:right"&gt;606.4 s (1 run)&lt;/td&gt;
&lt;td style="text-align:right"&gt;241.3 s (1 run)&lt;/td&gt;
&lt;td&gt;One round: GSM8K 97.04, MMLU 89.18&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;With cross-DP replay enabled, cold compile time depends little on how tensor parallelism is split: TP2×DP4 takes 251 s and TP4×DP2 takes 241 s, while with 0 replays the two differ by nearly 100 s (different images, one run each). This matches the expectation that each bucket is really compiled only once. Replay itself is cheap: in one DP8 measurement, the time for each engine from entering a bucket to finishing its replay had a median of 1.5 s, and the longest, 61.5 s, occurred when several engines were waiting on a claim at the same time.&lt;/p&gt;
&lt;p&gt;Compared with the very first original recipe, Qwen3.5 DP8 went from 1008.1 s (mean of three runs) to about 270 s. In between, however, we also changed the image and vLLM version, turned on several compile-time switches covered in the previous post, and skipped the profile run, so the whole gain cannot be attributed to cross-DP replay.&lt;/p&gt;
&lt;p&gt;On throughput, replay changes only where the program comes from, not the program itself. The formal benchmark of Qwen3.5 DP8 with cross-DP replay enabled showed no drop against historical benchmark results of the original recipe, but the two measurements were taken on different dates and nodes, so they only show that it is no worse.&lt;/p&gt;
&lt;h2 id="trying-it-on-hy4"&gt;Trying it on Hy4&lt;a class="hd-a" href="#trying-it-on-hy4" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;We also tried a layout mixing tensor and data parallelism on Hy4. TP8×DP2 is deployed across two hosts. The original recipe averaged 1520.0 s of cold compile over three runs. With both cross-DP replay (with group name normalization) and the profile-run skip enabled, one run measured 931.3 s. After group name normalization, the graphs of all 16 ranks were identical line by line, and rejected replays fell from more than 330 to 0. This comparison also changed the image and combined the two changes, so it is for reference only.&lt;/p&gt;
&lt;p&gt;In the end TP8×DP2 was not used for Hy4's production deployment. The main reason is that the mixed-step sequence parallelism in Hy4's production config requires a single DP group, which is structurally incompatible with TP8×DP2. On performance, under the first-round default config (one run each at concurrency 8 and 64), the extra communication from data parallelism added 81–90 ms to each mixed step. With 8K input and 1K output, throughput was 21% lower than TP16 at concurrency 8, 9% lower at concurrency 32, and roughly on par at concurrency 64. TP16 has a single DP group, where the same-DP replay from the previous post already takes full effect, so it does not need the changes in this post.&lt;/p&gt;
&lt;h2 id="upstream-validation"&gt;Upstream validation&lt;a class="hd-a" href="#upstream-validation" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;To confirm that cross-DP replay is equally effective on upstream code, we deployed DP8 on TPU v7x with a GLM-5.2 config reduced to 6 layers and dummy weights, and compared three versions of the code: the upstream baseline, the baseline plus cross-rank replay, and that plus cross-DP replay. Each was measured three times, from serve start to the health check passing:&lt;/p&gt;
&lt;figure&gt;
  &lt;div class="chart" role="img" aria-label="Ready time of three implementations on upstream code"&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Upstream baseline&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill base" style="width:calc((100% - 5.5em) * 0.9003)"&gt;&lt;/span&gt;&lt;span class="val"&gt;180.7&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;+ Cross-rank replay&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 1.0000)"&gt;&lt;/span&gt;&lt;span class="val"&gt;200.7&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;+ Cross-DP replay&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill" style="width:calc((100% - 5.5em) * 0.6827)"&gt;&lt;/span&gt;&lt;span class="val"&gt;137.0&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;figcaption&gt;Time (seconds) from serve start to the health check passing, GLM-5.2 reduced to 6 layers, dummy weights, DP8, mean of three runs each, same image.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Cross-DP replay is 63.7 s faster than cross-rank replay alone (the three paired runs on the same pod were −61, −70 and −60 s), and 43.7 s faster than the upstream baseline (−24%). Note also that on this reduced-layer testbed, cross-rank replay on its own, in a deployment with tensor parallel size 1, was 20 s slower than the baseline. The gap falls in the main-model compile phase, and we have not yet found the cause.&lt;/p&gt;
&lt;p&gt;Because model outputs carry no signal with dummy weights, correctness was instead validated with the real weights of the first 6 layers of DeepSeek-V3.2; the results are given above. Cross-DP replay stacks on top of cross-rank replay and has been submitted upstream, where it is pending review.&lt;/p&gt;
&lt;h2 id="scope-and-limitations"&gt;Scope and limitations&lt;a class="hd-a" href="#scope-and-limitations" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Cross-DP replay applies to data-parallel deployments with tensor parallel size 1 on vllm-torchtpu. It requires all engines to share the same compile cache root, parallel precompile to be enabled, and the main-model programs traced by every engine to be identical. In such deployments, once replay is on, cold compile is essentially reduced to compiling the slowest bucket once plus the serial segments that cannot be parallelized.&lt;/p&gt;
&lt;p&gt;A few points to keep in mind:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;With tensor parallel size greater than 1, process group names must be normalized before replaying across DP, and the safety of this approach has so far only been confirmed on an older runtime version.&lt;/li&gt;
&lt;li&gt;The graph fingerprint cannot see closure constants outside the graph, such as per-device values captured in a Pallas kernel closure. Letting more ranks share the same artifact amplifies the risk from such constants. All current correctness evidence is at the output level (accuracy evaluation and per-logprob comparison).&lt;/li&gt;
&lt;li&gt;For deployments with a single DP group (such as Hy4's TP16), the changes in this post bring no additional gain.&lt;/li&gt;
&lt;li&gt;Pure data-parallel deployments spanning multiple hosts have not been tested.&lt;/li&gt;
&lt;li&gt;Most control arms in this post were measured only once, and the contribution of skipping the profile run was not isolated.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="series"&gt;Series&lt;a class="hd-a" href="#series" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Overview: &lt;a href="/en/hy4-on-tpu-v7/"&gt;Beating B200 from Scratch: Porting and Optimizing Hy4 Inference on TPU v7&lt;/a&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href="/en/hy4-tpu-vs-b200/"&gt;From 2 tok/s to Beating B200: Optimizing Hy4 Inference on TPU v7&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-weight-loading/"&gt;Hy4 Weight Loading on TPU v7: From 857 Seconds to 68&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-cold-compile/"&gt;95 Minutes to 14: Cold Compile Optimization for Hy4 on TPU v7&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-cold-compile-dp/"&gt;Cold Compile Optimization, Part 2: Cross-DP Compile Reuse for Data-Parallel Deployments on TPU&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-cold-compile-sp/"&gt;Cold Compile Optimization, Part 3: Cross-Rank Reuse for Sequence-Parallel Buckets, 48 Minutes to 17.7&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="postscript" role="note"&gt;
&lt;p&gt;Data comes from our data-parallel cold compile optimization records and upstream validation from 2026-10-02 to 10-08.&lt;/p&gt;
&lt;/div&gt;
</content>
    <category term="TPU"/>
    <category term="vLLM"/>
    <category term="XLA"/>
    <category term="Compilation"/>
    <category term="Data Parallelism"/>
  </entry>
  <entry>
    <title>Hy4 Weight Loading on TPU v7: From 857 Seconds to 68</title>
    <link href="https://blog.maxwell-x.dev/en/hy4-weight-loading/"/>
    <id>https://blog.maxwell-x.dev/en/hy4-weight-loading/</id>
    <published>2026-10-08T00:00:00Z</published>
    <updated>2026-10-09T00:00:00Z</updated>
    <summary>The official Hy4-preview weights are 757.88 GiB. Deployed across two TPU v7 hosts, loading straight from the original checkpoint took 857 seconds. We analyzed why it was slow: every rank reads the full checkpoint, vLLM skips prefetch for large models, and with multiple hosts prefetch covers only half the files. After switching to a per-rank pre-sharded weight cache and closing two gaps in the upstream loader, load time dropped to 68.5 seconds. This post covers the analysis, the approach and the gains, as well as where this kind of cache fits and what it costs.</summary>
    <content type="html" xml:base="https://blog.maxwell-x.dev/en/hy4-weight-loading/">&lt;div class="tldr" role="note"&gt;
&lt;p&gt;&lt;strong&gt;TL;DR&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Problem&lt;/strong&gt;: The Hy4-preview checkpoint is 757.88 GiB. In a deployment with two hosts and 16 ranks, the default loading path has every rank read the full checkpoint, and vLLM's prefetch for network file systems has a memory threshold that large models easily miss. On the same software stack, one load straight from the original checkpoint took 857 seconds.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Approach&lt;/strong&gt;: Write the weights to disk after quantization conversion, already split per rank, so that each rank reads only its own ~47 GiB (vLLM's &lt;code&gt;sharded_state&lt;/code&gt; format). Add prefetch to the upstream ShardedStateLoader and fix 8 read-back issues it has on MXFP8-quantized models.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Gains&lt;/strong&gt;: Load time dropped from 857 seconds to 68.5 seconds, about 12.5×, and later measurements ranged over 65–71 seconds. Accuracy evaluations with the cache were normal.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;When to use it&lt;/strong&gt;: multi-host tensor parallelism, checkpoints close to or larger than a single host's memory, and deployments that restart often. The cost is that the cache is tied to the parallel configuration and the code version, and has to be rebuilt when the configuration changes.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="background"&gt;Background&lt;a class="hd-a" href="#background" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Hy4-preview is an MoE model released by Tencent Hunyuan, with 770B total parameters. The official checkpoint is quantized with modelopt MXFP8 and consists of 130 shards totaling 757.88 GiB.&lt;/p&gt;
&lt;p&gt;Our deployment on TPU v7 is two &lt;code&gt;tpu7x-standard-4t&lt;/code&gt; hosts, 8 chips and 16 devices in total, running TP16 plus expert parallelism. Each device maps to one rank, so each host runs 8 ranks. The weights sit on Google Cloud Managed Lustre, and both hosts read them from there.&lt;/p&gt;
&lt;p&gt;The service loads its weights on every start, and version switches, configuration changes and failure recovery all trigger one. During tuning we restarted several times a day, so load time directly limits iteration speed. On the vLLM 0.29 stack, one load straight from the original checkpoint took 857 seconds (this measurement did not record whether prefetch was enabled).&lt;/p&gt;
&lt;p&gt;All load times in this post are the &lt;code&gt;Loading weights took&lt;/code&gt; value from the vLLM log, taken from the slowest rank. It covers only &lt;code&gt;model.load_weights&lt;/code&gt; itself, not the post-processing that follows.&lt;/p&gt;
&lt;h2 id="problem-analysis-where-the-time-goes"&gt;Problem analysis: where the time goes&lt;a class="hd-a" href="#problem-analysis-where-the-time-goes" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;h3 id="every-rank-reads-the-full-checkpoint"&gt;Every rank reads the full checkpoint&lt;a class="hd-a" href="#every-rank-reads-the-full-checkpoint" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;vLLM's default loading path has every rank read the full checkpoint and then cut out its own slice online according to tensor parallelism. Hy4 has 16 ranks, each reading 757.88 GiB, for a combined logical read of about 11.8 TiB across the 16 ranks. Ranks on the same host can share the OS page cache, so the actual physical reads are somewhat lower, but each host still has to read the full 757.88 GiB into memory.&lt;/p&gt;
&lt;h3 id="prefetch-has-a-memory-threshold"&gt;Prefetch has a memory threshold&lt;a class="hd-a" href="#prefetch-has-a-memory-threshold" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;On network file systems such as Lustre and NFS, vLLM pre-reads the checkpoint files into the page cache before loading (prefetch), turning many small random reads into large sequential ones. This step is gated by a condition:&lt;/p&gt;
&lt;div class="code-block"&gt;&lt;div class="code-head"&gt;&lt;span class="code-lang"&gt;python&lt;/span&gt;&lt;button type="button" class="copy-btn"&gt;&lt;/button&gt;&lt;/div&gt;&lt;div class="hl"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="n"&gt;fits_in_ram&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;total_bytes&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="mf"&gt;0.9&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;avail&lt;/span&gt;
&lt;span class="c1"&gt;# avail = min(host_available, cgroup_limit - cgroup_usage)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;When the condition fails, vLLM prints a &lt;code&gt;Skipping auto-prefetch&lt;/code&gt; line and falls back to on-demand reads (mmap page faults). Two points are easy to miss here. The numerator is the size of the whole checkpoint and is not divided by the number of ranks. The denominator is the available memory as seen by the container (cgroup), which is bounded by the pod's memory limit rather than the node's physical memory.&lt;/p&gt;
&lt;p&gt;The Hy4 checkpoint sits right around this line, and we ran into it twice:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The pod memory limit was initially set to 400Gi, leaving only 382.78 GiB available, and prefetch was skipped. The loading progress bar showed 25.97 seconds per shard, which projects to about 56 minutes for the full load. After we raised the memory limit to 880Gi, available memory was 862.90 GiB, prefetch turned on, and each shard dropped to 4.84 seconds (the two rates were taken at different points in the load).&lt;/li&gt;
&lt;li&gt;Another time, available memory was only 781.44 GiB, giving a threshold of 703 GiB, which is below the checkpoint size. Prefetch was skipped again, and loading took 913–1018 seconds. In the same hour, on the same Lustre, GLM-5.3 Flash (305.79 GiB, within the threshold, single-host deployment) loaded in only 52 seconds. The two differ in both model and deployment, so the gap does not come entirely from the threshold, but it shows how much prefetch affects load speed.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Passing the threshold needs at least 842 GiB of available memory, while the available memory we measured fluctuated within 781–869 GiB. Raising the pod memory limit alone therefore cannot guarantee that prefetch takes effect reliably.&lt;/p&gt;
&lt;h3 id="with-multiple-hosts-prefetch-covers-only-half-the-files"&gt;With multiple hosts, prefetch covers only half the files&lt;a class="hd-a" href="#with-multiple-hosts-prefetch-covers-only-half-the-files" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;Even with prefetch on, vLLM assigns the files to prefetch by global rank (&lt;code&gt;sorted_files[rank::world_size]&lt;/code&gt;). Hy4's 16 ranks span two hosts, so the 8 ranks on each host prefetch only half the files. The other half goes into the peer host's page cache, which does nothing for the local host. With prefetch on, the default loader still took 497 seconds (host A) and 634 seconds (host B).&lt;/p&gt;
&lt;h3 id="quantization-conversion-is-not-the-bottleneck"&gt;Quantization conversion is not the bottleneck&lt;a class="hd-a" href="#quantization-conversion-is-not-the-bottleneck" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;We first assumed the slowness came from dequantizing and requantizing the MXFP8 weights after loading. Measurements ruled this out: the quantization conversion log and &lt;code&gt;Loading weights took&lt;/code&gt; finished within the same second, and the conversion itself takes only 2–3 seconds. Most of the time goes to reading the full checkpoint and slicing it tensor by tensor (we did not measure how the time splits between the two).&lt;/p&gt;
&lt;h2 id="approach-a-per-rank-pre-sharded-weight-cache"&gt;Approach: a per-rank pre-sharded weight cache&lt;a class="hd-a" href="#approach-a-per-rank-pre-sharded-weight-cache" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;h3 id="idea"&gt;Idea&lt;a class="hd-a" href="#idea" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;vLLM supports the &lt;code&gt;sharded_state&lt;/code&gt; load format: load the model fully once and write each rank's sliced weights to disk separately; on later starts, each rank reads only its own files. What we write to disk is the state &lt;strong&gt;after post-processing&lt;/strong&gt;: MXFP8 has been converted to the runtime format, MLA's &lt;code&gt;kv_b_proj&lt;/code&gt; has been folded into &lt;code&gt;W_UK_T / W_UV&lt;/code&gt;, and the quantization scales are already floating point.&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;Default loading&lt;/th&gt;
&lt;th&gt;Pre-sharded cache&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Read per rank&lt;/td&gt;
&lt;td&gt;757.88 GiB, sliced online&lt;/td&gt;
&lt;td&gt;about 47 GiB&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Read per host&lt;/td&gt;
&lt;td&gt;757.88 GiB, above the prefetch threshold&lt;/td&gt;
&lt;td&gt;about 379 GiB&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Quantization conversion&lt;/td&gt;
&lt;td&gt;Done on every start&lt;/td&gt;
&lt;td&gt;Done before writing to disk&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;The cache for each configuration only has to be built once, and the output totals 757.2 GiB. On vLLM 0.27 the build took about 36 minutes. On vLLM 0.29, offline saving also runs the whole compilation again, so it takes about 45–85 minutes.&lt;/p&gt;
&lt;h3 id="closing-two-gaps-in-the-upstream-loader"&gt;Closing two gaps in the upstream loader&lt;a class="hd-a" href="#closing-two-gaps-in-the-upstream-loader" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;Using the upstream ShardedStateLoader as is runs into two problems.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;First, it has no prefetch.&lt;/strong&gt; The upstream implementation is just &lt;code&gt;safe_open&lt;/code&gt; plus &lt;code&gt;get_tensor()&lt;/code&gt; and relies entirely on mmap page faults; vLLM's prefetch logic exists only in the default loader. On the first read-back from the cache, each rank's physical read rate was only about 30 MB/s, about 480 MB/s across all 16 ranks. We added a background thread pool (8 threads by default) that reads &lt;strong&gt;each rank's own&lt;/strong&gt; files sequentially in 16 MiB blocks. We deliberately did not reuse vLLM's &lt;code&gt;_prefetch_all_checkpoints&lt;/code&gt;, because it splits the files by rank once more, and each rank would end up prefetching only 1/16 of them.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Second, it assumes that saving and loading see the same set of tensors.&lt;/strong&gt; On load, upstream does only &lt;code&gt;param.copy_(tensor)&lt;/code&gt;. But the cache holds the post-processed model, while model initialization (&lt;code&gt;create_weights&lt;/code&gt;) allocates the checkpoint layout, and the two disagree in four respects: key set, shapes and dtypes, quantization state, and device. We fixed 8 places in total, mainly:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;kv_b_proj&lt;/code&gt;, which MLA folds away, does not exist in the cache, so a missing key is now downgraded to a warning;&lt;/li&gt;
&lt;li&gt;MXFP8 weights that are already in the runtime format skip repeated quantization;&lt;/li&gt;
&lt;li&gt;after a parameter is renamed, the old attribute is cleaned up by setting it to None rather than deleting it, so the alias of the shared expert is not removed by mistake;&lt;/li&gt;
&lt;li&gt;newly created parameters are placed on the model's device instead of being left on the CPU;&lt;/li&gt;
&lt;li&gt;the step in which MLA rebuilds &lt;code&gt;W_UK_T / W_UV&lt;/code&gt; from &lt;code&gt;kv_b_proj&lt;/code&gt; is skipped.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Of these, 3 are design gaps in upstream: any quantization scheme that changes the structure of the state_dict during post-processing will run into them.&lt;/p&gt;
&lt;h3 id="two-side-issues"&gt;Two side issues&lt;a class="hd-a" href="#two-side-issues" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;MTP draft model.&lt;/strong&gt; The cache holds only the main model's weights. By default the draft model inherits the main model's load format and path, so it looks for the MTP weights in the cache directory and fails. We force the draft model to use the default loading path and point it back at the original checkpoint. Loading the draft model on its own takes 11–15 seconds.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Compile cache.&lt;/strong&gt; The vllm-torchtpu compile cache key includes &lt;code&gt;spec.model&lt;/code&gt; from the speculative decoding config, which under MTP defaults to the main model path. So the first time the model path points at the cache directory, it triggers a full recompile (about 25 minutes on vLLM 0.27); after that the cache hits normally.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="gains"&gt;Gains&lt;a class="hd-a" href="#gains" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;figure&gt;
  &lt;div class="chart" role="img" aria-label="Weight load time falling from 857 seconds to 68.5 seconds"&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Original checkpoint&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill base" style="width:calc((100% - 5.5em) * 1.0000)"&gt;&lt;/span&gt;&lt;span class="val"&gt;857&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Pre-sharded cache&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill" style="width:calc((100% - 5.5em) * 0.0799)"&gt;&lt;/span&gt;&lt;span class="val"&gt;68.5&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;figcaption&gt;Weight load time (seconds) on the vLLM 0.29 stack, taken from &lt;code&gt;Loading weights took&lt;/code&gt; in the vLLM log.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;On the vLLM 0.29 stack, load time dropped from 857 seconds to 68.5 seconds, about 12.5×, and later measurements ranged over 65–71 seconds.&lt;/p&gt;
&lt;p&gt;The measurements from each stage are summarized below:&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Configuration&lt;/th&gt;
&lt;th&gt;Software stack&lt;/th&gt;
&lt;th style="text-align:right"&gt;Load time&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Default loading, prefetch skipped by the memory threshold&lt;/td&gt;
&lt;td&gt;vLLM 0.27&lt;/td&gt;
&lt;td style="text-align:right"&gt;913–1018 s&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Default loading, prefetch on&lt;/td&gt;
&lt;td&gt;vLLM 0.27&lt;/td&gt;
&lt;td style="text-align:right"&gt;497 / 634 s (two hosts)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Pre-sharded cache + prefetch&lt;/td&gt;
&lt;td&gt;vLLM 0.27&lt;/td&gt;
&lt;td style="text-align:right"&gt;124.79 s&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Default loading&lt;/td&gt;
&lt;td&gt;vLLM 0.29&lt;/td&gt;
&lt;td style="text-align:right"&gt;857 s&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Pre-sharded cache + prefetch&lt;/td&gt;
&lt;td&gt;vLLM 0.29&lt;/td&gt;
&lt;td style="text-align:right"&gt;68.5 s&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;A few notes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The 124.79 seconds on vLLM 0.27 was measured with a fairly warm page cache (the cache had been written just an hour earlier), and only 2 of the 16 ranks printed a time, so it should be read as an optimistic figure; the real time may be longer. The vLLM 0.29 measurement did not record the page cache state. A cold start with the page cache cleared was not measured.&lt;/li&gt;
&lt;li&gt;On vLLM 0.27, single-stream inference throughput did not change after switching to the cache (111.99 vs 112.29 tok/s, within the ±5% noise range). On vLLM 0.29, accuracy evaluations with the cache gave a three-round GSM8K average of 94.89 and MMLU 90.40, both above the release bar.&lt;/li&gt;
&lt;li&gt;The 857-second measurement did not record whether prefetch was enabled, so the baseline behind the 12.5× figure is not fully certain.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="addendum-lustre-striping"&gt;Addendum: Lustre striping&lt;a class="hd-a" href="#addendum-lustre-striping" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Managed Lustre throughput is purchased as capacity × throughput per TiB. This is a guaranteed floor, and measured throughput can exceed it by about 22%. Stripes are allocated when a file is created, and expanding capacity does not redistribute existing files: after we expanded Lustre from 8 OSTs to 16, all 1742 of Hy4's objects still sat on the original 8 OSTs.&lt;/p&gt;
&lt;p&gt;To let existing files use the new OSTs, you have to redistribute them with &lt;code&gt;lfs migrate&lt;/code&gt;, and you must pass the full PFL layout template: running it without arguments has no effect on existing PFL files, while specifying only &lt;code&gt;-c 16&lt;/code&gt; flattens the PFL layout. In a controlled comparison on DeepSeek-V3.2 (642 GiB, cold cache, 8-way parallel reads from a single client), read speed was 3.00 GiB/s with 8 stripes and 5.63 GiB/s with 16, a 1.88× improvement. Hy4 load time before and after redistribution was not compared separately.&lt;/p&gt;
&lt;h2 id="when-to-use-it-and-what-it-costs"&gt;When to use it and what it costs&lt;a class="hd-a" href="#when-to-use-it-and-what-it-costs" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;When to use it.&lt;/strong&gt; The pre-sharded cache suits these deployments:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;multi-host tensor parallelism, where each rank needs only a small part of the checkpoint;&lt;/li&gt;
&lt;li&gt;checkpoints close to or larger than a single host's available memory, where the default prefetch is unreliable;&lt;/li&gt;
&lt;li&gt;frequent restarts, for example during tuning, canary switchovers and failure recovery;&lt;/li&gt;
&lt;li&gt;quantization formats that need heavy post-processing after loading, where the post-processed result can be cached along with the weights.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;What it costs.&lt;/strong&gt; The cache moves part of the load-time computation to before deployment, and in return brings a set of invalidation conditions:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The cache is tied to TP, EP, max-model-len, the KV dtype, the speculative decoding config and the code version. Any change requires a rebuild, and the rebuild occupies all 16 devices. A manifest containing module hashes, environment variables and engine arguments is written alongside the cache, but apart from the layout field described below, it is not yet checked automatically at startup.&lt;/li&gt;
&lt;li&gt;Layout changes can cause silently wrong results. When moving to vLLM 0.29, vllm-torchtpu followed upstream in changing the runtime layout of FP8 linear layers to (k, n). Square matrices have the same shape under the old and new layouts, so an old cache would be treated as already processed and loaded directly. The new loader therefore requires the manifest to declare &lt;code&gt;runtime_linear_layout == &amp;quot;kn&amp;quot;&lt;/code&gt; explicitly, and errors out otherwise.&lt;/li&gt;
&lt;li&gt;Forgetting to turn on the cache switch raises no error. Loading just falls back to the original checkpoint and startup takes more than ten minutes longer (over 900 seconds on vLLM 0.27, about 790 seconds on 0.29). We therefore made it the default in the deployment script.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="series"&gt;Series&lt;a class="hd-a" href="#series" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Overview: &lt;a href="/en/hy4-on-tpu-v7/"&gt;Beating B200 from Scratch: Porting and Optimizing Hy4 Inference on TPU v7&lt;/a&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href="/en/hy4-tpu-vs-b200/"&gt;From 2 tok/s to Beating B200: Optimizing Hy4 Inference on TPU v7&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-weight-loading/"&gt;Hy4 Weight Loading on TPU v7: From 857 Seconds to 68&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-cold-compile/"&gt;95 Minutes to 14: Cold Compile Optimization for Hy4 on TPU v7&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-cold-compile-dp/"&gt;Cold Compile Optimization, Part 2: Cross-DP Compile Reuse for Data-Parallel Deployments on TPU&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-cold-compile-sp/"&gt;Cold Compile Optimization, Part 3: Cross-Rank Reuse for Sequence-Parallel Buckets, 48 Minutes to 17.7&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="postscript" role="note"&gt;
&lt;p&gt;Data comes from deployment records between 2026-08-28 and 10-08.&lt;/p&gt;
&lt;/div&gt;
</content>
    <category term="TPU"/>
    <category term="vLLM"/>
    <category term="Hy4"/>
    <category term="Weight Loading"/>
    <category term="Lustre"/>
  </entry>
  <entry>
    <title>From 2 tok/s to Beating B200: Optimizing Hy4 Inference on TPU v7</title>
    <link href="https://blog.maxwell-x.dev/en/hy4-tpu-vs-b200/"/>
    <id>https://blog.maxwell-x.dev/en/hy4-tpu-vs-b200/</id>
    <published>2026-10-08T00:00:00Z</published>
    <updated>2026-10-09T00:00:00Z</updated>
    <summary>Hy4-preview is a 770B-parameter MoE model with DSA sparse attention and MTP speculative decoding. When first ported to TPU v7, single-stream decoding ran at only 2 tok/s. In the end, across a ten-level benchmark with 8K input / 1K output at concurrency 1–64, 8 TPU v7 chips delivered 3%–19% higher output throughput than 8 B200 GPUs. This post follows the four classes of bottlenecks in the order we hit them: porting the model and getting it correct, getting the model compiled, speeding up sparse-attention prefill with masked-dense, and optimizing mixed steps under high concurrency.</summary>
    <content type="html" xml:base="https://blog.maxwell-x.dev/en/hy4-tpu-vs-b200/">&lt;div class="tldr" role="note"&gt;
&lt;p&gt;&lt;strong&gt;TL;DR&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Result&lt;/strong&gt;: in a ten-level benchmark with 8000 input / 1000 output tokens at concurrency 1–64, 8 TPU v7 chips delivered 3%–19% higher output throughput than 8 B200 GPUs, 11%–28% lower time to first token, and lower time per output token at every level (B200 measured once per level).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Getting the model to run correctly&lt;/strong&gt;: we added MXFP8 quantization support, fixed 6 faults caused by bypassing the MLA wrapper layer, and wired in the learnable attention sink. Output went from garbage back to normal, and GSM8K is in the same range as the B200 side.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Getting the model compiled&lt;/strong&gt;: Hy4's model class lacked &lt;code&gt;@support_torch_compile&lt;/code&gt;. Adding it raised single-stream throughput from 2.14 to 48.57 tok/s, and compiling the MTP draft model as well brought it to 100.11 tok/s.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Speeding up sparse-attention prefill&lt;/strong&gt;: replacing sparse gather with masked-dense cut TTFT at 4K input from 1338.81 ms to 729.04 ms.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Optimizing mixed steps under high concurrency&lt;/strong&gt;: raising the masked-dense KV length cap, splitting out the speculative verification window, eliminating XLA whole-buffer copies, switching to contiguous DMA writeback and more took concurrency-32 throughput from 0.365 times B200's to 1.046 times.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="background"&gt;Background&lt;a class="hd-a" href="#background" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;h3 id="model"&gt;Model&lt;a class="hd-a" href="#model" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;Hy4-preview is an MoE model released by Tencent Hunyuan, with 770B total parameters, 49B active parameters and 78 layers. Two of its structural features have a large impact on the inference system:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;DSA sparse attention&lt;/strong&gt;: for each query, a lightweight indexer first selects the top-2048 from all KV entries, and attention is then computed over those entries (sparse MLA).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;MTP speculative decoding&lt;/strong&gt;: at each decode step the model predicts 3 extra draft tokens, which the main model verifies together; accepted draft tokens are emitted along with the normally generated token.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The official weights use MXFP8 quantization and are 757.88 GiB.&lt;/p&gt;
&lt;h3 id="experimental-setup"&gt;Experimental setup&lt;a class="hd-a" href="#experimental-setup" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;TPU side&lt;/th&gt;
&lt;th&gt;GPU side&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Hardware&lt;/td&gt;
&lt;td&gt;2 × &lt;code&gt;tpu7x-standard-4t&lt;/code&gt;, topology 2x2x2, 8 TPU v7 chips in total (16 TensorCores)&lt;/td&gt;
&lt;td&gt;1 × &lt;code&gt;a4-highgpu-8g&lt;/code&gt;, 8 × NVIDIA B200&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Parallelism&lt;/td&gt;
&lt;td&gt;TP16 + expert parallelism&lt;/td&gt;
&lt;td&gt;TP8 + expert parallelism&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Inference framework&lt;/td&gt;
&lt;td&gt;vLLM 0.29.0 + vllm-torchtpu (our own maintained branch)&lt;/td&gt;
&lt;td&gt;Official vLLM hy4-preview image (0.1.dev20485+g0fd2e8d50)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Libraries&lt;/td&gt;
&lt;td&gt;torch 2.13.0, torch_tpu 0.1.1.dev20260912, JAX 0.10.2, libtpu 0.0.47&lt;/td&gt;
&lt;td&gt;torch 2.13.0+cu130, CUDA 13.0, FlashInfer 0.6.17, driver 590.48.01&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Attention implementation&lt;/td&gt;
&lt;td&gt;masked-dense (when KV ≤ 9216), otherwise sparse&lt;/td&gt;
&lt;td&gt;&lt;code&gt;FLASHMLA_SPARSE&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Common settings&lt;/td&gt;
&lt;td&gt;MXFP8 weights, fp8 KV cache, MTP k=3&lt;/td&gt;
&lt;td&gt;Same&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;Each TPU v7 chip has two TensorCores, each exposed as its own device, so 8 chips give 16 devices and a tensor parallel degree of 16.&lt;/p&gt;
&lt;h3 id="goal-and-benchmark-method"&gt;Goal and benchmark method&lt;a class="hd-a" href="#goal-and-benchmark-method" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;The final target workload is fixed-length requests with 8000 input / 1000 output tokens, covering ten concurrency levels: 1, 2, 4, 6, 8, 16, 24, 32, 48 and 64. We benchmark the &lt;code&gt;/v1/chat/completions&lt;/code&gt; endpoint with evalscope, and the metric is output throughput (output tok/s). On the TPU side each level is measured at least twice and averaged (three times at concurrency 32), with B200's formal benchmark results as the reference.&lt;/p&gt;
&lt;h2 id="results"&gt;Results&lt;a class="hd-a" href="#results" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;figure&gt;
  &lt;div class="chart" role="img" aria-label="Output throughput of TPU v7 and B200 across ten concurrency levels"&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;c1&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.1079)"&gt;&lt;/span&gt;&lt;span class="val"&gt;122&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.1226)"&gt;&lt;/span&gt;&lt;span class="val"&gt;138&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;c2&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.1883)"&gt;&lt;/span&gt;&lt;span class="val"&gt;212&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.2240)"&gt;&lt;/span&gt;&lt;span class="val"&gt;252&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;c4&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.3120)"&gt;&lt;/span&gt;&lt;span class="val"&gt;352&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.3356)"&gt;&lt;/span&gt;&lt;span class="val"&gt;378&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;c6&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.3852)"&gt;&lt;/span&gt;&lt;span class="val"&gt;434&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.4292)"&gt;&lt;/span&gt;&lt;span class="val"&gt;484&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;c8&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.4524)"&gt;&lt;/span&gt;&lt;span class="val"&gt;510&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.5078)"&gt;&lt;/span&gt;&lt;span class="val"&gt;572&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;c16&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.6121)"&gt;&lt;/span&gt;&lt;span class="val"&gt;690&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.6821)"&gt;&lt;/span&gt;&lt;span class="val"&gt;768&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;c24&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.7036)"&gt;&lt;/span&gt;&lt;span class="val"&gt;793&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.7483)"&gt;&lt;/span&gt;&lt;span class="val"&gt;843&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;c32&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.8127)"&gt;&lt;/span&gt;&lt;span class="val"&gt;916&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.8501)"&gt;&lt;/span&gt;&lt;span class="val"&gt;958&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;c48&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.8874)"&gt;&lt;/span&gt;&lt;span class="val"&gt;1000&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.9379)"&gt;&lt;/span&gt;&lt;span class="val"&gt;1057&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;c64&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.9735)"&gt;&lt;/span&gt;&lt;span class="val"&gt;1097&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 1.0000)"&gt;&lt;/span&gt;&lt;span class="val"&gt;1127&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="legend"&gt;&lt;span&gt;&lt;i style="background:var(--ink-2)"&gt;&lt;/i&gt;8 × B200&lt;/span&gt;&lt;span&gt;&lt;i style="background:var(--accent)"&gt;&lt;/i&gt;8 × TPU v7&lt;/span&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;figcaption&gt;Output throughput (tok/s), 8000 input / 1000 output; the labels on the left are the concurrency. TPU is the final version v2.14, the mean of two measurements per level (three at c32); B200 is one measurement per level.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;div class="tw"&gt;&lt;table&gt;
  &lt;tr&gt;&lt;th&gt;Concurrency&lt;/th&gt;&lt;th&gt;TPU throughput&lt;/th&gt;&lt;th&gt;B200 throughput&lt;/th&gt;&lt;th&gt;TPU / B200&lt;/th&gt;&lt;th&gt;TTFT (ms)&lt;br&gt;TPU / B200&lt;/th&gt;&lt;th&gt;TPOT (ms)&lt;br&gt;TPU / B200&lt;/th&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td class="num"&gt;1&lt;/td&gt;&lt;td class="num"&gt;138.10&lt;/td&gt;&lt;td class="num"&gt;121.58&lt;/td&gt;&lt;td class="num"&gt;1.136&lt;/td&gt;&lt;td class="num"&gt;541 / 701&lt;/td&gt;&lt;td class="num"&gt;6.7 / 7.5&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td class="num"&gt;2&lt;/td&gt;&lt;td class="num"&gt;252.34&lt;/td&gt;&lt;td class="num"&gt;212.09&lt;/td&gt;&lt;td class="num"&gt;1.190&lt;/td&gt;&lt;td class="num"&gt;569 / 738&lt;/td&gt;&lt;td class="num"&gt;7.5 / 8.7&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td class="num"&gt;4&lt;/td&gt;&lt;td class="num"&gt;378.09&lt;/td&gt;&lt;td class="num"&gt;351.52&lt;/td&gt;&lt;td class="num"&gt;1.076&lt;/td&gt;&lt;td class="num"&gt;641 / 806&lt;/td&gt;&lt;td class="num"&gt;9.9 / 10.4&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td class="num"&gt;6&lt;/td&gt;&lt;td class="num"&gt;483.52&lt;/td&gt;&lt;td class="num"&gt;433.95&lt;/td&gt;&lt;td class="num"&gt;1.114&lt;/td&gt;&lt;td class="num"&gt;719 / 908&lt;/td&gt;&lt;td class="num"&gt;11.3 / 12.6&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td class="num"&gt;8&lt;/td&gt;&lt;td class="num"&gt;572.09&lt;/td&gt;&lt;td class="num"&gt;509.61&lt;/td&gt;&lt;td class="num"&gt;1.123&lt;/td&gt;&lt;td class="num"&gt;731 / 1010&lt;/td&gt;&lt;td class="num"&gt;13.1 / 14.4&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td class="num"&gt;16&lt;/td&gt;&lt;td class="num"&gt;768.48&lt;/td&gt;&lt;td class="num"&gt;689.56&lt;/td&gt;&lt;td class="num"&gt;1.114&lt;/td&gt;&lt;td class="num"&gt;1052 / 1361&lt;/td&gt;&lt;td class="num"&gt;19.4 / 21.3&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td class="num"&gt;24&lt;/td&gt;&lt;td class="num"&gt;842.96&lt;/td&gt;&lt;td class="num"&gt;792.66&lt;/td&gt;&lt;td class="num"&gt;1.063&lt;/td&gt;&lt;td class="num"&gt;1286 / 1727&lt;/td&gt;&lt;td class="num"&gt;26.6 / 27.9&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td class="num"&gt;32&lt;/td&gt;&lt;td class="num"&gt;957.73&lt;/td&gt;&lt;td class="num"&gt;915.57&lt;/td&gt;&lt;td class="num"&gt;1.046&lt;/td&gt;&lt;td class="num"&gt;1556 / 2040&lt;/td&gt;&lt;td class="num"&gt;31.4 / 32.4&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td class="num"&gt;48&lt;/td&gt;&lt;td class="num"&gt;1056.60&lt;/td&gt;&lt;td class="num"&gt;999.72&lt;/td&gt;&lt;td class="num"&gt;1.057&lt;/td&gt;&lt;td class="num"&gt;2057 / 2587&lt;/td&gt;&lt;td class="num"&gt;42.8 / 44.8&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td class="num"&gt;64&lt;/td&gt;&lt;td class="num"&gt;1126.56&lt;/td&gt;&lt;td class="num"&gt;1096.72&lt;/td&gt;&lt;td class="num"&gt;1.027&lt;/td&gt;&lt;td class="num"&gt;2862 / 3213&lt;/td&gt;&lt;td class="num"&gt;53.1 / 54.5&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;At all ten concurrency levels, TPU output throughput is higher than B200's, by 3% (c64) to 19% (c2); time to first token (TTFT) is 11%–28% lower, and time per output token (TPOT) is lower at every level. All 2353 requests in this TPU round succeeded. Some caveats: B200 was measured only once per level; the lead at c4 (7.6%) is within the variation between TPU's own two measurements; the lead at c64 is the smallest, and the lowest of the four TPU samples is only 1.7% above B200.&lt;/p&gt;
&lt;p&gt;The comparison was made under the following conditions; please state them when citing these numbers:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The workload is fixed-length requests with 8000 input / 1000 output tokens at concurrency 1–64. The TPU recipe's maximum context is 10240 and B200's is 262144; when any request in a batch has KV over 9216, TPU's mixed step falls back to the sparse path, and that cost was not measured.&lt;/li&gt;
&lt;li&gt;Both sides use fp8 KV cache, which the TPU sparse attention kernel requires. Its effect on B200 cuts both ways: at 4K input and concurrency 1, fp8 KV on B200 gives 13.3% lower throughput and 10.7% higher TTFT than bf16 KV (fp8 side measured once); but with bf16 KV, B200 holds only about 570,000 tokens, so at high concurrency the extra capacity from fp8 works in its favor. The net effect on this post's workload was not measured.&lt;/li&gt;
&lt;li&gt;The two sides produce different numbers of tokens per decode step. By engine statistics, TPU emits an average of 3.03 tokens per step, while B200 emits 2.59 and 2.54 at concurrency 32 and 64 respectively, so TPU produces 17–19% more. This affects how the throughput comparison should be read, and there are two possibilities. If the difference comes from a genuinely higher acceptance rate, it is a real TPU advantage in this configuration and the lead in the table holds. If part of it comes from the two sides handling the end-of-sequence (EOS) token differently, the lead in the table is overstated. The source of the second case: TPU's sampler does not mask EOS, and &lt;code&gt;ignore_eos&lt;/code&gt; only keeps generating after EOS is sampled, while B200 masks EOS at the sampler, so the tail content generated on the two sides differs. By a rough estimate this effect is on the order of 1 percentage point (inference); the split between the two causes has not been checked token by token.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The sections below follow the four classes of bottlenecks in the order we encountered them.&lt;/p&gt;
&lt;h2 id="porting-the-model-and-getting-it-correct"&gt;Porting the model and getting it correct&lt;a class="hd-a" href="#porting-the-model-and-getting-it-correct" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;At the start, Hy4 was not in vllm-torchtpu's model list. We extracted the &lt;code&gt;hy_v4&lt;/code&gt; model code (11 files) from the official GPU image and ported it to vllm-torchtpu. The first obstacle was the quantization format: the weight repository is named FP8, but the actual scheme is modelopt MXFP8, which is not on the TPU platform's quantization allowlist. Following the existing MXFP4 implementation, we added an MXFP8 quantization method that dequantizes at load time and requantizes to the FP8 format used at runtime.&lt;/p&gt;
&lt;p&gt;The next problem was subtler: the patches were applied but had no effect. The image contained 3 copies of vllm_torchtpu, and the one patched at build time was not the one imported at runtime. In addition, &lt;code&gt;current_platform.is_tpu()&lt;/code&gt; is always False on out-of-tree platforms like torchtpu, so patches that depended on it had been taking the else branch all along. We changed the platform check to &lt;code&gt;device_type == &amp;quot;tpu&amp;quot;&lt;/code&gt;, patched every copy in the image, and added a build-time AST comparison to confirm the patches actually land in the code imported at runtime.&lt;/p&gt;
&lt;p&gt;Hy4 also instantiates &lt;code&gt;MLAAttention&lt;/code&gt; directly instead of going through &lt;code&gt;MultiHeadLatentAttentionWrapper&lt;/code&gt;. Everything the wrapper normally does had to be filled in by hand, which led to 6 separate faults, ranging from a CUDA FlashAttention import error to top-k indices not being truncated to the current step's token count. Among these, fp8 KV cache is a hard prerequisite of the sparse attention kernel and must be enabled.&lt;/p&gt;
&lt;p&gt;The first time the service passed its health check, the output was a repeated &lt;code&gt;&amp;quot; is is is…&amp;quot;&lt;/code&gt;. During debugging we suspected out-of-bounds top-k indices for a while and spent about 10 rounds verifying it, ruling it out only after re-checking each worker separately. The real problem was that the learnable attention sink had not been wired into the sparse kernel's softmax; once it was connected, output returned to normal (we did not run the reverse experiment of zeroing the sink to reproduce the bad output). In the accuracy evaluation that followed, GSM8K scored only 19.67%. Breaking it down, 79% of the answers were empty: the GSM8K 8-shot stop sequence &lt;code&gt;Q:&lt;/code&gt; was being triggered inside the model's thinking section. After switching to no_think and re-extracting answers offline, full runs landed between 94.3% and 95.4%, in the same range as the 95.60% from the independent port on the B200 side.&lt;/p&gt;
&lt;h2 id="a-missing-decorator-getting-the-model-compiled"&gt;A missing decorator: getting the model compiled&lt;a class="hd-a" href="#a-missing-decorator-getting-the-model-compiled" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Once the output was correct, single-stream decoding ran at only 1.9–2.3 tok/s, so generating 1000 tokens took more than 8 minutes. The profile showed TPU utilization of only 7.8%, with 94% of the time spent waiting on the host.&lt;/p&gt;
&lt;p&gt;The cause was simple: Hy4's model class &lt;code&gt;HYV4Model&lt;/code&gt; lacked the &lt;code&gt;@support_torch_compile&lt;/code&gt; decorator, so all 78 layers ran on TPU with op-by-op dispatch and were never compiled into a whole graph. The serve log had in fact been printing &lt;code&gt;torch.compile is turned on, but the model … does not support it&lt;/code&gt; the whole time. After adding the decorator and removing three patterns that blocked whole-graph compilation (&lt;code&gt;fp8_dtype()&lt;/code&gt; scanning &lt;code&gt;/sys/bus/pci&lt;/code&gt; on every call, leftover debug code, and lazy initialization inside forward), single-stream throughput on short prompts rose from 2.14 to 48.57 tok/s; under the 4000 input / 1000 output setting we used from then on, it was 45.82 tok/s.&lt;/p&gt;
&lt;p&gt;The B200 side runs with MTP speculative decoding enabled. To match it, we added the 3 registrations missing from Hy4 MTP in vLLM 0.27, and with MTP enabled throughput reached 72.84 tok/s. The profile showed the draft model taking 35.6% of each step's time, again because it was not compiled. From the profile we predicted that adding the decorator to the draft model &lt;code&gt;HYV4MTP&lt;/code&gt; would cut TPOT by about 30%. Measured TPOT went from 12.38 to 8.66 ms (−30%), matching the prediction, and throughput reached 100.11 tok/s.&lt;/p&gt;
&lt;p&gt;With speculative decoding, a single request has only 1+K tokens per step, which used to be padded up to the smallest bucket of 16. Adding a bucket of 8 tokens raised throughput from 112.29 to 126.33 tok/s (+12.5%, with 5 MTP draft tokens at the time; after switching back to 3 to match B200 it was 117.70 tok/s). This gain is measured and reproducible, but the causal chain &amp;quot;half the padding, therefore faster&amp;quot; was not verified on its own.&lt;/p&gt;
&lt;h2 id="replacing-sparse-gather-with-masked-dense"&gt;Replacing sparse gather with masked-dense&lt;a class="hd-a" href="#replacing-sparse-gather-with-masked-dense" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;With decoding faster, the bottleneck moved to prefill: at 4K input and concurrency 1, TTFT was 4.37× B200's. TTFT versus input length is almost a straight line through the origin, with the intercept accounting for only 7.6%, which indicates the limit is device compute rather than the host; the per-token slope was 4.80× B200's. Breaking it down further, each of the 16 devices held a full copy of the KV latent, and to fetch at most 2048 distinct rows, the sparse MLA gather materialized about 4.19 million rows, 2048× redundant. 96.3% of the sparse path's device time went into the gather.&lt;/p&gt;
&lt;p&gt;Our first attempt was to use dense attention directly when the KV length did not exceed top-k, but the routing flag was constant-folded into the compiled graph during dynamo tracing, so values written at runtime had no effect, and we had to abandon it. What we finally adopted was the masked-dense method from upstream vllm-torchtpu: instead of gathering, it writes the top-k result as a bitmap (done on SparseCore) and computes masked dense attention, which is semantically equivalent to sparse attention. The upstream implementation did not work as-is, and we added three things: wiring in the learnable attention sink; changing the enabling condition, which upstream only fit deployments with 64 attention heads (under TP16 each device has only 4 heads, so the condition was never met), to check the head count after sharding; and refitting the cost model that chooses between masked-dense and sparse for 4 heads per device, with the path selected on device via &lt;code&gt;lax.cond&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;After masked-dense went live, TTFT at 4K input dropped from 1338.81 ms to 729.04 ms (−45.55%), with 0.19% dispersion across three measurements, GSM8K 94.69% and MMLU 90.14%. On top of that, we made a series of prefill optimizations:&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Change&lt;/th&gt;
&lt;th&gt;Mechanism&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Block-wise indexer KV writes&lt;/td&gt;
&lt;td&gt;Writing 524 KB used to trigger a 377 MB reshuffle of the whole pool&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Page-wise main KV writes&lt;/td&gt;
&lt;td&gt;Replaces per-token scatter&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;top-k sort width follows the actual KV length&lt;/td&gt;
&lt;td&gt;Previously fixed by max-model-len&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;KV blocks 720 → 192&lt;/td&gt;
&lt;td&gt;The per-layer whole-pool copy cost scales with pool size; the trade-off is that KV capacity drops from 737,280 to 196,608 tokens, so the later production configuration did not keep this change&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Indexer early exit (from upstream)&lt;/td&gt;
&lt;td&gt;When the first chunk's KV length does not exceed top-k, the sort is an identity operation and can be skipped&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;masked-dense query block 32 → 256&lt;/td&gt;
&lt;td&gt;32 was set for 64-head deployments; with 4 heads per device, 256 uses only 10.9% of VMEM, and results are bit-identical&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Fused iHC kernel&lt;/td&gt;
&lt;td&gt;Hy4's iHC had always taken an fp32 eager fallback on TPU, accounting for 14.4% of device time; rewritten as a Pallas kernel&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;--xla_tpu_dvfs_p_state=7&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Chip frequency state setting; mechanism not identified&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;These changes brought TTFT further down to 419.73 ms (the later part switched to probe measurements on the completions endpoint, which differ from the earlier chat-endpoint method by about 55 ms, so the overall reduction cannot be computed on a single basis). Compared with B200 at 4K input and concurrency 1 at this point: TTFT was 419.73 vs 340.19 ms, still 23% slower (this is the 192-KV-block configuration; the production configuration that keeps 720 blocks is estimated at about 455 ms, not measured); throughput was 147.23 vs 137.45 tok/s, slightly higher, but the difference is only 1.7–2.5 standard deviations. Around the same time we measured the 8K/1K concurrency curve for the first time: single-concurrency throughput was on par, but at high concurrency it was only 23%–42% of B200's, so the focus of the next stage shifted to high concurrency.&lt;/p&gt;
&lt;h2 id="mixed-steps-under-high-concurrency"&gt;Mixed steps under high concurrency&lt;a class="hd-a" href="#mixed-steps-under-high-concurrency" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;After migrating to vLLM 0.29, we continued optimizing against the ten levels at concurrency 64 and below from B200's formal benchmark. The starting point: throughput at concurrency 8 was only 53% of B200's, at concurrency 32 only 37%, and TTFT was 3.51× B200's.&lt;/p&gt;
&lt;p&gt;Under high concurrency, the main cost is in the &amp;quot;mixed step&amp;quot;, a scheduling step that contains several speculative decoding requests and a chunk of prefill at once; at concurrency 32 a mixed step contains 32 speculative decoding requests. Breaking down mixed steps with production profiles, the problems fell into four areas: at 8K input, decode requests have KV lengths of 8000–9000, above the masked-dense default cap of 6144, so the whole mixed step fell back to sparse gather; the speculative verification window (4 tokens per request) was treated as prefill, with each window occupying its own 256-row query block; several pieces of intermediate data were passed through persistent buffers or program inputs, which XLA turned into whole-buffer copies; and KV writeback used per-token scatter.&lt;/p&gt;
&lt;p&gt;The single largest gain came from changing one parameter: raising the masked-dense KV length cap from 6144 to 9216. Mixed steps at 8K input no longer fell back to sparse, mixed-step time dropped from about 600 ms to 345 ms, and concurrency-32 throughput rose 40.6%. The later changes are grouped by category below; each was measured on hardware on its own before being merged:&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Category&lt;/th&gt;
&lt;th&gt;Change&lt;/th&gt;
&lt;th style="text-align:right"&gt;Concurrency-32 throughput change&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Attention path&lt;/td&gt;
&lt;td&gt;masked-dense KV length cap 6144 → 9216&lt;/td&gt;
&lt;td style="text-align:right"&gt;+40.6%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Speculative verification window&lt;/td&gt;
&lt;td&gt;Split the verification window into its own segment in masked-dense (q_len=4)&lt;/td&gt;
&lt;td style="text-align:right"&gt;+21.0%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;Give the verification window its own pass in indexer top-k as well&lt;/td&gt;
&lt;td style="text-align:right"&gt;+7.8%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Eliminating whole-buffer copies&lt;/td&gt;
&lt;td&gt;Replace &lt;code&gt;jnp.searchsorted&lt;/code&gt; in indexer writes with a single broadcast compare-and-sum&lt;/td&gt;
&lt;td style="text-align:right"&gt;+3.8%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;Reuse the bitmap across layers: only 21 of the 78 layers compute top-k, the rest share it&lt;/td&gt;
&lt;td style="text-align:right"&gt;+5.6%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;Hand the bitmap off directly along with top-k instead of passing it through a 75 MB persistent buffer; decode steps also use masked-dense&lt;/td&gt;
&lt;td style="text-align:right"&gt;+6.3%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Kernel optimization&lt;/td&gt;
&lt;td&gt;Remove a 4×4 byte transpose in the kernel caused by a reshape&lt;/td&gt;
&lt;td style="text-align:right"&gt;+6.7% (concurrency 64: +17.0%)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;Truncate the prefill attention KV loop at the causal position; one 8000-token prompt goes from 256 to 144 block iterations&lt;/td&gt;
&lt;td style="text-align:right"&gt;+3.9%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;KV pages per block in the decode window kernel 3 → 9&lt;/td&gt;
&lt;td style="text-align:right"&gt;Concurrency-64 decode attention 21.54 → 16.92 ms/step&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Parallelism&lt;/td&gt;
&lt;td&gt;Enable sequence parallelism for mixed steps: all-reduce split into reduce-scatter + all-gather, iHC computes only this rank's 1/16&lt;/td&gt;
&lt;td style="text-align:right"&gt;+6.1% (mnbt 2048 recipe; +4.1% on the 8192 recipe)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Writeback&lt;/td&gt;
&lt;td&gt;rope KV writeback becomes one contiguous DMA per page per sequence, with written bytes identical byte for byte&lt;/td&gt;
&lt;td style="text-align:right"&gt;+7.2%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;Indexer K writeback also switched to contiguous DMA; scoring and SparseCore top-k interleaved in 2048-token chunks&lt;/td&gt;
&lt;td style="text-align:right"&gt;Concurrency 64: +2.9%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Scheduling parameters&lt;/td&gt;
&lt;td&gt;mnbt 2048 → 8192, taking in the whole prompt at once; TTFT down 6.7%–27.1%, concurrency-64 throughput −5.5%&lt;/td&gt;
&lt;td style="text-align:right"&gt;—&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;During optimization we also found and fixed two correctness problems. The indexer K cache wrote unaligned MTP windows to the wrong position; after the fix, mid-generation divergence in long-context generation went from 3 questions to 0. &lt;code&gt;swiglu_limit=10&lt;/code&gt; in the Hy4 config was silently dropped by the TPU adaptation layer; after restoring it, the setting took effect as configured, performance was unchanged and accuracy evaluation passed.&lt;/p&gt;
&lt;figure&gt;
  &lt;div class="chart" role="img" aria-label="Concurrency-32 throughput rising from 334 to 954 tok/s, versus 916 for B200"&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Start&lt;small&gt;×0.365&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill base" style="width:calc((100% - 5.5em) * 0.3507)"&gt;&lt;/span&gt;&lt;span class="val"&gt;334&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;KV cap 9216&lt;small&gt;×0.513&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.4929)"&gt;&lt;/span&gt;&lt;span class="val"&gt;470&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Separate verify window&lt;small&gt;×0.621&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.5965)"&gt;&lt;/span&gt;&lt;span class="val"&gt;569&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Indexer opts and fix&lt;small&gt;×0.679&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.6517)"&gt;&lt;/span&gt;&lt;span class="val"&gt;622&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Cross-layer bitmap reuse&lt;small&gt;×0.752&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.7218)"&gt;&lt;/span&gt;&lt;span class="val"&gt;688&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Sequence parallelism&lt;small&gt;×0.797&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.7649)"&gt;&lt;/span&gt;&lt;span class="val"&gt;730&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;No byte transpose&lt;small&gt;×0.850&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.8163)"&gt;&lt;/span&gt;&lt;span class="val"&gt;779&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Direct bitmap handoff&lt;small&gt;×0.905&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.8689)"&gt;&lt;/span&gt;&lt;span class="val"&gt;829&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Contiguous rope writeback&lt;small&gt;×0.971&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.9316)"&gt;&lt;/span&gt;&lt;span class="val"&gt;889&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Causal cutoff + 9 pages&lt;small&gt;×1.029&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.9873)"&gt;&lt;/span&gt;&lt;span class="val"&gt;942&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Contiguous indexer writeback&lt;small&gt;×1.042&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill" style="width:calc((100% - 5.5em) * 1.0000)"&gt;&lt;/span&gt;&lt;span class="val"&gt;954&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;B200&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.9599)"&gt;&lt;/span&gt;&lt;span class="val"&gt;916&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="legend"&gt;&lt;span&gt;&lt;i style="background:var(--ink-2)"&gt;&lt;/i&gt;Start / B200&lt;/span&gt;&lt;span&gt;&lt;i style="background:repeating-linear-gradient(135deg,var(--accent-2) 0 4px,transparent 4px 7px);border:1px solid var(--accent-2)"&gt;&lt;/i&gt;Intermediate&lt;/span&gt;&lt;span&gt;&lt;i style="background:var(--accent)"&gt;&lt;/i&gt;Final&lt;/span&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;figcaption&gt;Concurrency-32 output throughput (tok/s), 8000 input / 1000 output; the figure in parentheses is the multiple of B200. Intermediate versions are mostly the mean of 3 measurements within the same serve; the last two rows take one pass from the formal benchmark (their three-pass means are 938.42 and 957.73). The first nine rows use the mnbt 2048 recipe and the last two use mnbt 8192. Between the fourth and fifth rows there were also three versions that only touched cold compile and stability; together with a change in measurement method, this means the 622 → 688 increase in that segment cannot all be attributed to bitmap reuse (its isolated gain is +5.6%).&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Cumulatively, concurrency-32 throughput went from 334.47 to 957.73 tok/s (three-pass mean), from 37% of B200's to 5% above B200; final results at every concurrency level are in the &amp;quot;Results&amp;quot; section at the start of this post. Several directions were tried and not adopted:&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Direction&lt;/th&gt;
&lt;th&gt;Outcome&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;TP8 × DP2&lt;/td&gt;
&lt;td&gt;The extra communication from data parallelism costs 81–90 ms per mixed step; the best configuration was only 2% higher at concurrency 64 (within noise) and 8.8% lower at concurrency 32&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Dual micro-batch interleaving + offloading collectives to SparseCore&lt;/td&gt;
&lt;td&gt;The offload itself works, but the two batches did not actually interleave; &lt;code&gt;optimization_barrier&lt;/code&gt; was removed by XLA&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;MTP draft count 3 → 2 at high concurrency&lt;/td&gt;
&lt;td&gt;Estimated device time almost unchanged and output about 20% lower; not run on hardware&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;mnbt 16384 (matching B200's default)&lt;/td&gt;
&lt;td&gt;HBM OOM at compile time&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;MLA layout fusion&lt;/td&gt;
&lt;td&gt;In production it introduced an &lt;code&gt;as_strided_inverse&lt;/code&gt; costing 185 ms per mixed step, and throughput at the four levels tested dropped 4.3%–16.2%; mechanism not identified&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;h2 id="curvature-drive-the-tuning-workflow-behind-the-second-half"&gt;Curvature Drive: the tuning workflow behind the second half&lt;a class="hd-a" href="#curvature-drive-the-tuning-workflow-behind-the-second-half" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;The fourth stage of optimization was driven by Curvature Drive, an engine we built. It is an agent engine for TPU inference tuning that is capable of Recursive Self-Improvement (RSI): beyond running the tuning, it improves its own process, evaluation methods and knowledge base at the end of each round, so the next round starts from a better position.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;It integrates TPU domain knowledge.&lt;/strong&gt; Curvature Drive has a built-in, continually growing TPU inference knowledge base, currently 280 experience cards. They cover TPU hardware specs (the chip-to-TensorCore mapping, HBM and VMEM capacity, ICI topology and so on), Pallas kernel development techniques, XLA compilation and caching behavior, how to capture and read profiles, methods for breaking device time down by bottleneck type, and known pitfalls of each model on TPU. Each card records the software environment it was validated in; when the environment changes, the card is flagged for re-review and serves only as a prior reference, and cannot by itself rule out a direction.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;It explores.&lt;/strong&gt; Before proposing each optimization hypothesis, the engine first runs a frontier scan: it checks upstream code and issues / PRs, official documentation, the source of strong kernels and related papers, to first answer &amp;quot;how have others solved this bottleneck&amp;quot;, and it periodically summarizes new developments in the outside community. The experiment queue also has an exploration quota: at least 1 in every 5 experiments is exploratory, dedicated to re-examining directions that experience says are not worthwhile or that were rejected under an older environment.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Every step has gates and evaluation.&lt;/strong&gt; An optimization is split into fixed stages: freeze the goal and the comparison basis, measure the noise across repeated measurements, and attribute time using production profiles. Before going on hardware, each hypothesis gets an upper-bound estimate of its gain and written falsification conditions. Predictions must be registered before the data arrives. A change must first be proven to have actually taken effect before its effect is evaluated. Adopted changes must pass three rounds of accuracy evaluation and a long-context verbatim comparison, and are baked into the image and the deployment recipe. A separate reviewer agent checks the direction and looks for counterexamples at key points, and the author has to respond to each item.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;It evolves itself.&lt;/strong&gt; At the end of each round, the engine writes reusable lessons into new experience cards, and conclusions later overturned by evidence are registered as retracted rather than deleted. Changes to the procedure itself are submitted as proposals, merged after human review, and evaluated by replaying a fixed set of historical decision questions to confirm the change makes it stronger rather than weaker. On 12 historical decision questions, the group using Curvature Drive scored 93.3% and the group without it scored 82.5%. After the Hy4 round, 23 new experience cards entered the knowledge base.&lt;/p&gt;
&lt;p&gt;On Hy4, this stage covered 14 versions, 38 experiments and 41 optimization hypotheses. A few examples:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;A hypothesis retracted and reopened&lt;/strong&gt;: &amp;quot;raise the masked-dense KV cap&amp;quot; was first rejected on paper on the grounds that &amp;quot;the decode branch would take the mixed batch first&amp;quot;. It later turned out that because of &lt;code&gt;reorder_batch_threshold=1&lt;/code&gt; the speculative windows are not counted as decode, so the premise was wrong. After the rejection was retracted and the hypothesis reopened, it became the largest single gain of this stage (+40.6%).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A change stopped by the accuracy gate&lt;/strong&gt;: the indexer verification window change gave a 7.8% speedup, but MMLU came in low in two rounds and a rollback was required. It was re-adopted only after alternating restarts with three rounds each (5700 questions) confirmed there was no regression. The long-context verbatim comparison in the same period caught the indexer K cache writing to the wrong position.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A version stopped by the formal benchmark&lt;/strong&gt;: after the version enabling sequence parallelism was first baked in, the speculative acceptance rate readings in the formal benchmark were abnormal (0.76 at concurrency 1 and 0.565 at concurrency 64, versus about 0.68 normally), and the decoded output was garbage. The cause was a warm start after a change in pod placement, which loaded a cache compiled under a different placement. This version was withdrawn, and the fix was to add the rank-to-device placement to the compile cache key. In a later isolation experiment, however, garbage output showed an acceptance rate of 0.680, which looks completely normal, so acceptance rate is not a reliable correctness metric; since then every formal benchmark has included checks on the output content.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;An introduction to Curvature Drive and live progress on its tasks are at &lt;a href="https://rsi.maxwell-x.dev"&gt;https://rsi.maxwell-x.dev&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id="accuracy"&gt;Accuracy&lt;a class="hd-a" href="#accuracy" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;The final version scores GSM8K 95.00 / 94.77 / 95.07 over three rounds, MMLU 90.04, and 100% on RULER niah_single_1@8192; on 40 long-context questions its output is verbatim identical to the previous version.&lt;/p&gt;
&lt;p&gt;The only truly like-for-like accuracy comparison between the two sides is RULER (100% on both). GSM8K is close to B200's 95.60%, but the KV data type, parallelism and answer extraction differ, so this cannot be taken to mean accuracy is on par. Long-chain reasoning tasks such as GPQA and AIME get truncated under the 10240 context cap and can only be evaluated in no_think mode, which is not comparable with B200. Two numeric paths also have lower precision than the CUDA reference implementation and have not been specifically validated: the rope part of the KV (k_pe) is stored as per-tensor fp8, versus bf16 on CUDA; and iHC's hc_fn weights are rounded to bf16, with a relative error of 1.7e-3 measured in isolation.&lt;/p&gt;
&lt;h2 id="lessons-and-where-they-apply"&gt;Lessons and where they apply&lt;a class="hd-a" href="#lessons-and-where-they-apply" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Looking back at the four stages, several lessons carry over to other models:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;When porting a GPU-only model&lt;/strong&gt;, check three things first: whether the quantization format is on the platform allowlist; whether the image contains multiple packages with the same name and whether patches land on the copy imported at runtime; and whether the model bypasses the framework's wrapper layers.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;When a model on TPU is &amp;quot;one or two orders of magnitude slower&amp;quot;&lt;/strong&gt;, the most common cause is not a particular op but that the model never entered compilation and is running in eager mode with op-by-op dispatch. Check the torch.compile message in the serve log first, then the share of host wait time in the profile.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;masked-dense suits DSA / sparse MLA models deployed with tensor parallelism&lt;/strong&gt;, especially when each device gets few attention heads and the upstream default condition will not trigger. Parameters inherited from GPU deployments (enabling conditions, block sizes) often carry implicit assumptions such as the head count, and need to be rechecked when the sharding changes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Mixed-step optimization pays off most for workloads with &amp;quot;long input + speculative decoding + medium-to-high concurrency&amp;quot;.&lt;/strong&gt; When investigating, rely on op-level data from production profiles: writing a single element to a persistent buffer or passing a large tensor as a program input can each be turned into a whole-buffer copy by XLA, and this kind of overhead often does not show up in isolated tests. The speculative verification window is also easily treated as prefill by the scheduler and needs separate handling.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="series"&gt;Series&lt;a class="hd-a" href="#series" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Overview: &lt;a href="/en/hy4-on-tpu-v7/"&gt;Beating B200 from Scratch: Porting and Optimizing Hy4 Inference on TPU v7&lt;/a&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href="/en/hy4-tpu-vs-b200/"&gt;From 2 tok/s to Beating B200: Optimizing Hy4 Inference on TPU v7&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-weight-loading/"&gt;Hy4 Weight Loading on TPU v7: From 857 Seconds to 68&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-cold-compile/"&gt;95 Minutes to 14: Cold Compile Optimization for Hy4 on TPU v7&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-cold-compile-dp/"&gt;Cold Compile Optimization, Part 2: Cross-DP Compile Reuse for Data-Parallel Deployments on TPU&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-cold-compile-sp/"&gt;Cold Compile Optimization, Part 3: Cross-Rank Reuse for Sequence-Parallel Buckets, 48 Minutes to 17.7&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="postscript" role="note"&gt;
&lt;p&gt;Data comes from the porting log from 2026-08-28 to 2026-10-08, the experiment records of the tuning workflow, TPU-side formal benchmarks #147 and #153–#160, and B200-side formal benchmark #926.&lt;/p&gt;
&lt;/div&gt;
</content>
    <category term="TPU"/>
    <category term="vLLM"/>
    <category term="Hy4"/>
    <category term="Performance Tuning"/>
    <category term="B200"/>
  </entry>
  <entry>
    <title>Beating B200 from Scratch: Porting and Optimizing Hy4 Inference on TPU v7</title>
    <link href="https://blog.maxwell-x.dev/en/hy4-on-tpu-v7/"/>
    <id>https://blog.maxwell-x.dev/en/hy4-on-tpu-v7/</id>
    <published>2026-10-08T00:00:00Z</published>
    <updated>2026-10-09T00:00:00Z</updated>
    <summary>Hy4-preview is a 770B-parameter MoE model with sparse attention and MTP speculative decoding. We ported it from GPU to TPU v7. In benchmarks with 8K input / 1K output at concurrency 1–64, 8 TPU v7 chips delivered 3%–19% higher output throughput than 8 B200 GPUs. Weight loading dropped from 857 seconds to 68, and cold compile from 95 minutes to about 14. This post summarizes the work on all three fronts, and the tuning engine behind it, Curvature Drive.</summary>
    <content type="html" xml:base="https://blog.maxwell-x.dev/en/hy4-on-tpu-v7/">&lt;div class="tldr" role="note"&gt;
&lt;p&gt;&lt;strong&gt;TL;DR&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Inference performance&lt;/strong&gt;: across ten concurrency levels from 1 to 64 with 8000 input / 1000 output tokens, 8 TPU v7 chips delivered 3%–19% higher output throughput than 8 B200 GPUs, with 11%–28% lower time to first token (TTFT).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Weight loading&lt;/strong&gt;: for the 757.88 GiB checkpoint, load time on the same software stack dropped from 857 seconds to 68.5 seconds.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cold compile&lt;/strong&gt;: startup time with an empty cache dropped from 95.1 minutes to about 14 minutes (mnbt 2048 configuration).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Method&lt;/strong&gt;: the second half of the tuning was driven by Curvature Drive, a recursively self-improving tuning engine. In two weeks it raised throughput at concurrency 32 from 0.365× that of B200 to 1.046×.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="background"&gt;Background&lt;a class="hd-a" href="#background" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Hy4-preview is an MoE model released by Tencent Hunyuan, with 770B total parameters, 49B activated parameters and 78 layers. The official weights are MXFP8-quantized and total 757.88 GiB. Its attention is DSA sparse attention: for each query, a lightweight indexer first selects the top-2048 KV entries, and attention is then computed over those entries (sparse MLA). Decoding uses MTP speculative decoding, which predicts 3 extra draft tokens per step for the main model to verify together. These two features account for most of the difficulty on the inference system side.&lt;/p&gt;
&lt;p&gt;Our goal was to deploy this model on TPU v7 and outperform B200 at the same chip count. At the start, Hy4 was not on the supported list of the TPU inference stack (vLLM + vllm-torchtpu), so we had to begin with the port. Once the model ran, single-stream decoding reached only 1.9–2.3 tok/s, and throughput at concurrency 32 with 8K input was only 0.365× that of B200. On top of that, every startup spent 857 seconds loading weights, plus another 95 minutes compiling whenever the cache was invalidated. Inference performance, weight loading and cold compile are the three problems this work set out to solve.&lt;/p&gt;
&lt;h2 id="test-environment"&gt;Test environment&lt;a class="hd-a" href="#test-environment" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;TPU side&lt;/th&gt;
&lt;th&gt;GPU side&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Hardware&lt;/td&gt;
&lt;td&gt;2 × &lt;code&gt;tpu7x-standard-4t&lt;/code&gt;, topology 2x2x2, 8 TPU v7 chips in total (16 TensorCores)&lt;/td&gt;
&lt;td&gt;1 × &lt;code&gt;a4-highgpu-8g&lt;/code&gt;, 8 × NVIDIA B200&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Parallelism&lt;/td&gt;
&lt;td&gt;TP16 + expert parallelism&lt;/td&gt;
&lt;td&gt;TP8 + expert parallelism&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Inference framework&lt;/td&gt;
&lt;td&gt;vLLM 0.29.0 + vllm-torchtpu (self-maintained branch)&lt;/td&gt;
&lt;td&gt;Official vLLM hy4-preview image (0.1.dev20485+g0fd2e8d50)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Libraries&lt;/td&gt;
&lt;td&gt;torch 2.13.0, torch_tpu 0.1.1.dev20260912, JAX 0.10.2, libtpu 0.0.47&lt;/td&gt;
&lt;td&gt;torch 2.13.0+cu130, CUDA 13.0, FlashInfer 0.6.17, driver 590.48.01&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Attention implementation&lt;/td&gt;
&lt;td&gt;masked-dense (when KV ≤ 9216), otherwise sparse&lt;/td&gt;
&lt;td&gt;&lt;code&gt;FLASHMLA_SPARSE&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Common settings&lt;/td&gt;
&lt;td&gt;MXFP8 weights, fp8 KV cache, MTP k=3&lt;/td&gt;
&lt;td&gt;Same as left&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;Each TPU v7 chip has two TensorCores, and each one is a separate device, so 8 chips give 16 devices and a tensor parallel degree of 16.&lt;/p&gt;
&lt;h2 id="inference-performance-from-2-toks-to-beating-b200"&gt;Inference performance: from 2 tok/s to beating B200&lt;a class="hd-a" href="#inference-performance-from-2-toks-to-beating-b200" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;The gains in inference performance came in roughly three stages, each with a different bottleneck.&lt;/p&gt;
&lt;p&gt;The first bottleneck was that the model was not being compiled at all. Hy4's model class lacked the &lt;code&gt;@support_torch_compile&lt;/code&gt; decorator, so all 78 layers ran on TPU with op-by-op dispatch, and the device spent 94% of its time waiting on the host. After we added the decorator to both the main model and the MTP draft model and removed several constructs that blocked whole-graph compilation, single-stream throughput on short prompts rose from 2.14 to 48.57 tok/s. With 4000 input / 1000 output, enabling MTP and compiling the draft model brought it to 100.11 tok/s.&lt;/p&gt;
&lt;p&gt;Next, the bottleneck moved to the prefill of sparse attention. Each of the 16 devices held a full copy of the KV, and to fetch at most 2048 distinct rows, the sparse MLA gather materialized 4.19 million rows. TTFT at 4K input was 4.37× that of B200. We solved this with the masked-dense method from upstream vllm-torchtpu: write the top-k result into a bitmap and compute masked dense attention, which is semantically equivalent to sparse attention. The upstream implementation only targeted deployments with 64 attention heads and does not activate under TP16 with 4 heads per device. We added attention sink support, made the enablement check use the head count after sharding, and refit the cost model used for path selection. After these changes, TTFT at 4K input dropped from 1338.81 ms to 729.04 ms.&lt;/p&gt;
&lt;p&gt;Last came high concurrency. At higher concurrency, a single scheduler step contains several speculative decoding requests and a chunk of prefill at the same time; we call this a mixed step. At concurrency 32, one mixed step holds 32 speculative decoding requests. With 8K input, many of these mixed steps fell back to the sparse path, along with several data handoffs that XLA lowered into whole-block copies. The optimizations in this stage were: raising the masked-dense KV length cap from 6144 to 9216 so that mixed steps with 8K input no longer fall back to sparse, which alone raised throughput at concurrency 32 by 40.6%; computing the speculative decoding verification window as a separate segment; reusing the attention bitmap across layers and handing it off directly from top-k; enabling sequence parallelism in mixed steps; turning KV writeback into DMA that is contiguous per sequence; and having prefill attention truncate the KV loop at the causal position. Within two weeks, throughput at concurrency 32 went from 0.365× that of B200 to 1.046×.&lt;/p&gt;
&lt;figure&gt;
  &lt;div class="chart" role="img" aria-label="Output throughput of TPU v7 and B200 at ten concurrency levels"&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;c1&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.1079)"&gt;&lt;/span&gt;&lt;span class="val"&gt;122&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.1226)"&gt;&lt;/span&gt;&lt;span class="val"&gt;138&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;c2&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.1883)"&gt;&lt;/span&gt;&lt;span class="val"&gt;212&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.2240)"&gt;&lt;/span&gt;&lt;span class="val"&gt;252&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;c4&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.3120)"&gt;&lt;/span&gt;&lt;span class="val"&gt;352&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.3356)"&gt;&lt;/span&gt;&lt;span class="val"&gt;378&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;c6&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.3852)"&gt;&lt;/span&gt;&lt;span class="val"&gt;434&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.4292)"&gt;&lt;/span&gt;&lt;span class="val"&gt;484&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;c8&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.4524)"&gt;&lt;/span&gt;&lt;span class="val"&gt;510&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.5078)"&gt;&lt;/span&gt;&lt;span class="val"&gt;572&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;c16&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.6121)"&gt;&lt;/span&gt;&lt;span class="val"&gt;690&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.6821)"&gt;&lt;/span&gt;&lt;span class="val"&gt;768&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;c24&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.7036)"&gt;&lt;/span&gt;&lt;span class="val"&gt;793&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.7483)"&gt;&lt;/span&gt;&lt;span class="val"&gt;843&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;c32&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.8127)"&gt;&lt;/span&gt;&lt;span class="val"&gt;916&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.8501)"&gt;&lt;/span&gt;&lt;span class="val"&gt;958&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;c48&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.8874)"&gt;&lt;/span&gt;&lt;span class="val"&gt;1000&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.9379)"&gt;&lt;/span&gt;&lt;span class="val"&gt;1057&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;c64&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.9735)"&gt;&lt;/span&gt;&lt;span class="val"&gt;1097&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 1.0000)"&gt;&lt;/span&gt;&lt;span class="val"&gt;1127&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="legend"&gt;&lt;span&gt;&lt;i style="background:var(--ink-2)"&gt;&lt;/i&gt;8 × B200&lt;/span&gt;&lt;span&gt;&lt;i style="background:var(--accent)"&gt;&lt;/i&gt;8 × TPU v7&lt;/span&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;figcaption&gt;Output throughput (tok/s), 8000 input / 1000 output; labels on the left are the concurrency. TPU numbers are from the final version, averaged over two runs per level (three at c32); B200 is one run per level.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;At all ten concurrency levels, TPU output throughput is higher than B200, by 3% (c64) to 19% (c2). TTFT is 11%–28% lower, and time per output token is lower at every level as well. When citing these numbers, keep several conditions in mind: the load is fixed-length requests of 8000 input / 1000 output; the TPU recipe's maximum context is 10240 (262144 on B200), and when any request in a batch has KV beyond 9216, TPU mixed steps fall back to the sparse path; both sides use fp8 KV cache, which the TPU sparse attention kernel requires; B200 was measured only once per level. In addition, by engine statistics, TPU emits an average of 3.03 tokens per decode step versus 2.54–2.59 on B200. If this comes from a real difference in acceptance rate, the lead shown above holds. If part of it comes from the two sides handling the end-of-sequence token (EOS) differently, the lead is overstated; a rough estimate puts that part on the order of 1 percentage point (inference).&lt;/p&gt;
&lt;p&gt;This set of methods suits DSA / sparse MLA models deployed with tensor parallelism on TPU, and pays off most for workloads that combine long inputs, speculative decoding and medium-to-high concurrency. The full story is in the first post of this series:&lt;/p&gt;
&lt;p&gt;&lt;a href="/en/hy4-tpu-vs-b200/"&gt;From 2 tok/s to Beating B200: Optimizing Hy4 Inference on TPU v7&lt;/a&gt;&lt;/p&gt;
&lt;h2 id="weight-loading-from-857-seconds-to-68"&gt;Weight loading: from 857 seconds to 68&lt;a class="hd-a" href="#weight-loading-from-857-seconds-to-68" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Hy4 is deployed on two hosts with 16 ranks. With vLLM's default loading path, every rank reads the full 757.88 GiB checkpoint and then slices out its own share online. The weights sit on Lustre shared by both hosts, and two factors slow the reads further. First, vLLM only prefetches from network file systems when the whole checkpoint fits within 90% of available memory; Hy4 sits right around that line, and at one point our pods skipped prefetching because of it. Second, even with prefetch enabled, files are assigned by global rank, so with two hosts each host prefetches only half.&lt;/p&gt;
&lt;p&gt;Our approach is to write the weights to disk after quantization conversion, already sliced per rank, producing one cache per rank (vLLM's &lt;code&gt;sharded_state&lt;/code&gt; format), so that each rank reads only its own ~47 GiB. Upstream's ShardedStateLoader has no prefetching and does not account for quantization post-processing changing the model structure. We added prefetching to it and fixed 8 read-back issues.&lt;/p&gt;
&lt;figure&gt;
  &lt;div class="chart" role="img" aria-label="Weight loading time dropping from 857 seconds to 68.5 seconds"&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Original checkpoint&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill base" style="width:calc((100% - 5.5em) * 1.0000)"&gt;&lt;/span&gt;&lt;span class="val"&gt;857&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Pre-sharded cache&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill" style="width:calc((100% - 5.5em) * 0.0799)"&gt;&lt;/span&gt;&lt;span class="val"&gt;68.5&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;figcaption&gt;Weight loading time (seconds), vLLM 0.29 software stack, taken from &lt;code&gt;Loading weights took&lt;/code&gt; in the vLLM log. Later runs measured between 65 and 71 seconds.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;On the same software stack, load time dropped from 857 seconds to 68.5 seconds, about 12.5× faster. This cache suits deployments with multi-host tensor parallelism, checkpoints close to or larger than single-host memory, and frequent restarts. The cost is that the cache is tied to the parallel configuration, max-model-len, KV data type, speculative decoding configuration and code version, and a change in any of them requires a rebuild. The full story is in the second post of this series:&lt;/p&gt;
&lt;p&gt;&lt;a href="/en/hy4-weight-loading/"&gt;Hy4 Weight Loading on TPU v7: From 857 Seconds to 68&lt;/a&gt;&lt;/p&gt;
&lt;h2 id="cold-compile-from-95-minutes-to-14"&gt;Cold compile: from 95 minutes to 14&lt;a class="hd-a" href="#cold-compile-from-95-minutes-to-14" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;TPU programs are compiled per input shape. At startup, vLLM compiles the main model for every token bucket, then the sampling, draft model and speculative decoding warmup programs, and only opens the service once all of them are done. Compiled results are cached, but the cache is invalidated whenever the configuration, image or version changes. One Hy4 cold compile takes 95.1 minutes.&lt;/p&gt;
&lt;p&gt;We measured compile volume on a 4-layer proxy model and extrapolated to 78 layers, and found that the main cost was not in the compiler itself but in the graphs fed into it. In the sparse MLA kernel, a Python loop over 64-token chunks was unrolled verbatim during tracing, so program length grew linearly with the bucket; by extrapolation this accounts for 74–93% of each worker's compile volume. The attention sink was written into the program as a closure constant, so the same shape was compiled into multiple copies, one per rank. To address these two points, we changed the chunk loop to &lt;code&gt;fori_loop&lt;/code&gt; and made the attention sink a runtime input, then adopted the upstream approach of replaying compiled artifacts across ranks, along with several compile-time optimizations.&lt;/p&gt;
&lt;figure&gt;
  &lt;div class="chart" role="img" aria-label="Cold compile time dropping from 95.1 minutes to about 14 minutes"&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Before&lt;small&gt;mnbt 2048&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill base" style="width:calc((100% - 5.5em) * 1.0000)"&gt;&lt;/span&gt;&lt;span class="val"&gt;95.1&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;fori + sink as input&lt;small&gt;mnbt 8192&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.5499)"&gt;&lt;/span&gt;&lt;span class="val"&gt;52.3&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;+ bitwise indexing / shared ops&lt;small&gt;mnbt 8192&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.3018)"&gt;&lt;/span&gt;&lt;span class="val"&gt;28.7&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;+ dispatcher / rotation, etc.&lt;small&gt;mnbt 8192&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.2250)"&gt;&lt;/span&gt;&lt;span class="val"&gt;21.4&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;+ cross-rank replay&lt;small&gt;mnbt 8192&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.1614)"&gt;&lt;/span&gt;&lt;span class="val"&gt;15.35&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;After&lt;small&gt;mnbt 2048&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill" style="width:calc((100% - 5.5em) * 0.1456)"&gt;&lt;/span&gt;&lt;span class="val"&gt;13.7–14.0&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;figcaption&gt;Cold compile time (minutes), empty cache, from pod creation to service ready. The intermediate steps were measured at mnbt 8192 and the first and last rows at mnbt 2048, so the rows cannot be subtracted from one another directly.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Cold compile dropped from 95.1 minutes to about 14 minutes (two runs with mnbt 2048, at 819 seconds and 842 seconds). On GLM-5.3, toggling only the same &amp;quot;bucket splitting + replay&amp;quot; switch (the two contributions cannot be separated) cut the time from weights loaded to service ready from 959 seconds to 409 seconds. These problems are common when deploying models with custom Pallas kernels on vllm-torchtpu. A simple check is to count how many programs in the compile cache directory correspond to the same shape. The full story is in the third post of this series:&lt;/p&gt;
&lt;p&gt;&lt;a href="/en/hy4-cold-compile/"&gt;95 Minutes to 14: Cold Compile Optimization for Hy4 on TPU v7&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The replay above can only reuse compiled artifacts within the same DP index. For pure data parallel deployments, or mixed tensor and data parallel deployments, we went further and relaxed replay to look up artifacts across DP ranks. On Qwen3.5 DP8, the time from weights loaded to service ready dropped from 741 seconds (single run) to 270 seconds (mean of three runs). See the fourth post of this series:&lt;/p&gt;
&lt;p&gt;&lt;a href="/en/hy4-cold-compile-dp/"&gt;Cold Compile Optimization, Part 2: Cross-DP Compile Reuse for Data-Parallel Deployments on TPU&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Later, after mixed-step sequence parallelism was turned on and mnbt raised to 8192 to cut time to first token, cold compile climbed back to 48 minutes. The root cause was that the sequence-parallel slice wrote the rank index into the traced graph, which disabled cross-rank replay; reading the rank at run time brought it down to 17.7 minutes. See the fifth post of this series:&lt;/p&gt;
&lt;p&gt;&lt;a href="/en/hy4-cold-compile-sp/"&gt;Cold Compile Optimization, Part 3: Cross-Rank Reuse for Sequence-Parallel Buckets, 48 Minutes to 17.7&lt;/a&gt;&lt;/p&gt;
&lt;h2 id="curvature-drive-a-recursively-self-improving-tuning-engine"&gt;Curvature Drive: a recursively self-improving tuning engine&lt;a class="hd-a" href="#curvature-drive-a-recursively-self-improving-tuning-engine" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;The second half of the performance work (September 24 to October 8) was driven by Curvature Drive, a tuning engine we built. It is an agent engine for TPU inference tuning that can recursively self-improve (Recursive Self-Improvement, RSI): besides running the tuning, it improves its own process, evaluation methods and knowledge base at the end of each round, so the next round starts from a better position.&lt;/p&gt;
&lt;p&gt;Curvature Drive brings together domain expertise on TPU. It has a built-in, continuously growing knowledge base, currently 280 experience cards, covering TPU hardware specs (the mapping between chips and TensorCores, HBM and VMEM capacity, ICI topology, and so on), Pallas kernel development techniques, XLA compilation and caching behavior, how to capture and read profiles, methods for breaking down device time by the nature of the bottleneck, and known pitfalls of individual models on TPU. Each card records the software environment it was validated in. When the environment changes, the card is flagged for re-review and serves only as a prior; it cannot by itself rule out a direction.&lt;/p&gt;
&lt;p&gt;It also has an explicit exploration process. Before proposing any optimization hypothesis, the engine runs a frontier scan: it checks upstream code and issues / PRs, official documentation, and the source code and papers behind strong kernels, to first answer &amp;quot;how have others solved this bottleneck&amp;quot;. It also periodically summarizes new developments in the external community. The experiment queue has an exploration quota: at least 1 in every 5 experiments is exploratory, dedicated to revisiting directions that experience says are not worth pursuing, or that were rejected under an older environment.&lt;/p&gt;
&lt;p&gt;In execution, each optimization is split into fixed phases, and every phase has a machine-checked gate. The goal and comparison methodology are frozen first, and the noise of repeated measurements is measured; production profiles then break down the time of each scheduler step to the operator level. Before any hypothesis goes on hardware, its upper bound on gains is estimated and its falsification condition written down. Predictions must be registered before the data arrives, and a change must first be shown to actually take effect before its effect is evaluated. Adopted changes must pass three rounds of accuracy evaluation and a long-context verbatim comparison, and are baked into the image and the deployment recipe. Independent reviewer agents check the direction and look for counterexamples at key points, and the author has to respond to each item.&lt;/p&gt;
&lt;p&gt;At the end of each round, the engine writes reusable lessons into new experience cards, and conclusions overturned by later evidence are registered as retracted rather than deleted. Changes to the procedure itself are submitted as proposals and merged after human review, then evaluated by replaying a fixed set of historical decision questions to confirm that the change makes the engine stronger rather than weaker. On 12 historical decision questions, the group using Curvature Drive scored 93.3%, against 82.5% for the group without it.&lt;/p&gt;
&lt;p&gt;On Hy4, over two weeks, 14 versions and 38 experiments, Curvature Drive raised throughput at 8K/1K and concurrency 32 from 0.365× that of B200 to 1.046×, and 23 new experience cards entered the knowledge base at the end of this round. It also caught several problems that &amp;quot;looked faster&amp;quot;. A change that gave a 7.8% speedup came in low on MMLU in two rounds; it was rolled back, re-measured over three rounds with alternating restarts, and re-adopted only after no regression was confirmed, and the long-context verbatim comparison in the same period also uncovered an indexer KV write error. A version that had already been baked in gave abnormal readings in the formal benchmark; the cause turned out to be a mismatched compile cache loaded after the pod placement changed, and the version was retracted right away.&lt;/p&gt;
&lt;p&gt;An introduction to Curvature Drive and live progress on each task are at &lt;a href="https://rsi.maxwell-x.dev"&gt;https://rsi.maxwell-x.dev&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id="series"&gt;Series&lt;a class="hd-a" href="#series" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href="/en/hy4-tpu-vs-b200/"&gt;From 2 tok/s to Beating B200: Optimizing Hy4 Inference on TPU v7&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-weight-loading/"&gt;Hy4 Weight Loading on TPU v7: From 857 Seconds to 68&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-cold-compile/"&gt;95 Minutes to 14: Cold Compile Optimization for Hy4 on TPU v7&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-cold-compile-dp/"&gt;Cold Compile Optimization, Part 2: Cross-DP Compile Reuse for Data-Parallel Deployments on TPU&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-cold-compile-sp/"&gt;Cold Compile Optimization, Part 3: Cross-Rank Reuse for Sequence-Parallel Buckets, 48 Minutes to 17.7&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="postscript" role="note"&gt;
&lt;p&gt;Data as of 2026-10-08; the cold compile part was updated on October 13 with the fifth post.&lt;/p&gt;
&lt;/div&gt;
</content>
    <category term="TPU"/>
    <category term="vLLM"/>
    <category term="Hy4"/>
    <category term="B200"/>
  </entry>
  <entry>
    <title>Natural Cantonese Voiceover with Gemini 3.8 Flash TTS: Step by Step, and the Pitfalls</title>
    <link href="https://blog.maxwell-x.dev/en/gemini-tts-cantonese/"/>
    <id>https://blog.maxwell-x.dev/en/gemini-tts-cantonese/</id>
    <published>2026-10-02T00:00:00Z</published>
    <updated>2026-10-02T00:00:00Z</updated>
    <summary>We voiced a 30-second tech promo in Cantonese and fixed it one problem at a time: the model read the directions aloud, slipped into Mandarin, spoke its English with an American accent, and said "14 seconds" instead of "14 minutes". This post gives runnable requests for each step, why each step is there, and before/after audio for every pitfall.</summary>
    <content type="html" xml:base="https://blog.maxwell-x.dev/en/gemini-tts-cantonese/">&lt;div class="tldr" role="note"&gt;
&lt;p&gt;&lt;strong&gt;TL;DR&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Put only the words to be spoken in the text.&lt;/strong&gt; Gemini 3.8 TTS treats &lt;code&gt;text&lt;/code&gt; as a verbatim transcript. With directions written into the text, 6 of 10 takes read the directions aloud. Put style in &lt;code&gt;speechMetadata.style&lt;/code&gt;, as one short phrase.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Get the accent from the voice, not the prompt.&lt;/strong&gt; We went through all 2,089 prebuilt and Extended Voice Library voices: none is Cantonese or Chinese, and the English comes out in a standard American or British accent. A voice built with voice design from a text description gave us Hong Kong-accented English.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Write the script in traditional Cantonese characters, not simplified.&lt;/strong&gt; The model detects the language itself. The same line in simplified characters came out in Mandarin 2 times out of 4; in traditional Cantonese characters with &amp;quot;Hong Kong Cantonese&amp;quot; in the style, 10 of 10 were Cantonese.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;It is cheap.&lt;/strong&gt; We measured 25 tokens per second of audio, so a minute of speech costs about $0.027 at the 2027 list price, half that during the promotion.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Check every take word by word.&lt;/strong&gt; &amp;quot;14 分鐘&amp;quot; (14 minutes) came out as &amp;quot;14 秒&amp;quot; (14 seconds) once and as &amp;quot;1.4 分鐘&amp;quot; once; after we wrote the number in Chinese characters (十四), it did not happen again. There is no reliable automatic check for accent; you have to listen.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="the-example-a-30-second-cantonese-promo"&gt;The example: a 30-second Cantonese promo&lt;a class="hd-a" href="#the-example-a-30-second-cantonese-promo" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;This is the finished video. It is about &lt;a href="/en/hy4-cold-compile/"&gt;cutting Hy4's cold compile on TPU v7 from 95 minutes to 14&lt;/a&gt;. The narration is colloquial Cantonese mixed with English, the way Hong Kong engineers talk, and all of it was generated by &lt;code&gt;gemini-3.8-flash-tts&lt;/code&gt;; there is no human recording.&lt;/p&gt;
&lt;figure&gt;
&lt;video controls playsinline preload="metadata" poster="/gemini-tts-cantonese/video-poster.jpg" src="/gemini-tts-cantonese/hy4-promo-yue.mp4" style="display:block;width:100%;max-width:360px;margin:0 auto;border-radius:8px"&gt;&lt;/video&gt;
&lt;figcaption&gt;Cantonese promo, 30.5 s. Five lines of narration, each generated separately and placed to the picture.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;The five lines:&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Beat&lt;/th&gt;
&lt;th&gt;Cantonese script (as sent to TTS)&lt;/th&gt;
&lt;th&gt;Meaning&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Problem&lt;/td&gt;
&lt;td&gt;混元 4 喺 TPU v7 度 cold start，淨係 compile 就要 95 分鐘；cache 一 invalidate 咗，就要由頭嚟過。&lt;/td&gt;
&lt;td&gt;Hy4's cold start on TPU v7 spends 95 minutes just compiling; once the cache is invalidated, you start over.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Turn&lt;/td&gt;
&lt;td&gt;Bottleneck 唔喺 compiler 度，係個 graph 畀人放大咗。&lt;/td&gt;
&lt;td&gt;The bottleneck isn't the compiler; the graph got blown up.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Fix&lt;/td&gt;
&lt;td&gt;Loop 改用 for i，constant 改做 parameter，compile 出嚟嘅嘢喺唔同 rank 之間 share。&lt;/td&gt;
&lt;td&gt;Loops use fori, constants become parameters, compiled artifacts are shared across ranks.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Result&lt;/td&gt;
&lt;td&gt;Cold start，直接壓到得返十四分鐘！&lt;/td&gt;
&lt;td&gt;Cold start, cut straight down to fourteen minutes!&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Payoff&lt;/td&gt;
&lt;td&gt;每日嘅優化實驗由 12 組變 80 組，i-te-rate 快咗好多！&lt;/td&gt;
&lt;td&gt;Daily optimization experiments went from 12 to 80; we iterate much faster!&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;The way the last two lines are written (十四 in characters, a hyphenated &amp;quot;i-te-rate&amp;quot;) came from fixing pitfalls, explained below.&lt;/p&gt;
&lt;h2 id="meet-gemini-38-flash-tts"&gt;Meet Gemini 3.8 Flash TTS&lt;a class="hd-a" href="#meet-gemini-38-flash-tts" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;&lt;a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/gemini/3-8-flash-tts"&gt;Gemini 3.8 Flash TTS&lt;/a&gt; (&lt;code&gt;gemini-3.8-flash-tts&lt;/code&gt;) is Google's flagship text-to-speech model, released on September 28, 2026 and currently in Preview. You call it through the Gemini Enterprise (Vertex AI) &lt;code&gt;generateContent&lt;/code&gt; / &lt;code&gt;streamGenerateContent&lt;/code&gt; methods. Google positions it around four things:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Expressiveness&lt;/strong&gt;: a wide emotional range and natural cadence, following turn-level &lt;code&gt;style&lt;/code&gt; directions and inline vocal tags such as &lt;code&gt;&amp;lt;laugh&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;sigh&amp;gt;&lt;/code&gt; and &lt;code&gt;&amp;lt;short pause&amp;gt;&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Long-form stability&lt;/strong&gt;: voice identity, timbre, volume and room tone stay consistent across long dialogues and multi-minute narration.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Regional accents&lt;/strong&gt;: 130 languages, including regional accents and minority dialects. You don't specify the language; the model &lt;a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/text-to-speech/overview"&gt;detects it from the input&lt;/a&gt;. Cantonese is on the supported list, and Chinese is listed separately as Hans and Hant script.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Voices&lt;/strong&gt;: 30 prebuilt voices, more than 2,000 voices in the Extended Voice Library, voices you create from a text description with &lt;a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/text-to-speech/voice-design"&gt;voice design&lt;/a&gt;, and voices replicated from a recording with voice replication.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;There is also a Flash-Lite model in the same generation. Both use the same request schema, so switching is a change of model ID:&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;Flash TTS&lt;/th&gt;
&lt;th&gt;Flash-Lite TTS&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Model ID&lt;/td&gt;
&lt;td&gt;&lt;code&gt;gemini-3.8-flash-tts&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;gemini-3.8-flash-lite-tts&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Strength&lt;/td&gt;
&lt;td&gt;Voice fidelity, acting nuance, dialect coverage&lt;/td&gt;
&lt;td&gt;Throughput, low latency, cost&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Recommended for&lt;/td&gt;
&lt;td&gt;Audiobooks, studio narration, complex multi-speaker dialogue, frequent vocal tags, difficult pronunciation, regional dialects&lt;/td&gt;
&lt;td&gt;High-volume production, real-time voice agents, read-aloud features, voice replication, everyday single-speaker speech&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Languages&lt;/td&gt;
&lt;td&gt;130&lt;/td&gt;
&lt;td&gt;101&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;We wanted natural Cantonese, which falls under regional dialects, so we used Flash. We did not test Flash-Lite.&lt;/p&gt;
&lt;p&gt;A few specs worth knowing before you integrate:&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Item&lt;/th&gt;
&lt;th&gt;Spec&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Input / output&lt;/td&gt;
&lt;td&gt;Text in, audio out only&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Token limits&lt;/td&gt;
&lt;td&gt;8,192 input, 16,384 output&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Region&lt;/td&gt;
&lt;td&gt;&lt;code&gt;global&lt;/code&gt; only&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Speakers&lt;/td&gt;
&lt;td&gt;One or two. For more than two, or to mix in designed voices, synthesize each turn and concatenate the audio yourself&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Output format&lt;/td&gt;
&lt;td&gt;Unary requests default to a complete WAV file (16-bit PCM, 24 kHz, mono); streaming defaults to raw PCM; μ-law / A-law are also available. No MP3 or Ogg Opus, and the sample rate can't be set&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Billing&lt;/td&gt;
&lt;td&gt;Pay-as-you-go&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;If you have used an earlier Gemini TTS model (such as &lt;code&gt;gemini-3.1-flash-tts-preview&lt;/code&gt;), three of the changes in the &lt;a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/text-to-speech/migration-guide"&gt;migration guide&lt;/a&gt; matter most for prompting: &lt;code&gt;text&lt;/code&gt; is a verbatim transcript and style moves to &lt;code&gt;speechMetadata.style&lt;/code&gt;; vocal tags change from square brackets &lt;code&gt;[sigh]&lt;/code&gt; to angle brackets &lt;code&gt;&amp;lt;sigh&amp;gt;&lt;/code&gt;; and &lt;code&gt;systemInstruction&lt;/code&gt; is gone, while sampling parameters such as &lt;code&gt;temperature&lt;/code&gt; are rejected. Step 2 below covers the first of these, which was also the first pitfall we hit.&lt;/p&gt;
&lt;h3 id="strengths-why-it-is-worth-using"&gt;Strengths: why it is worth using&lt;a class="hd-a" href="#strengths-why-it-is-worth-using" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;Google's stated strengths, plus what we saw in practice:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Dialects actually work.&lt;/strong&gt; It supports 130 languages and says explicitly that this includes regional accents and minority dialects. We produced Hong Kong engineer-style Cantonese with English terms mixed into Cantonese sentences, and the switches sound natural rather than stitched together.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Fine-grained control.&lt;/strong&gt; Each line can have its own style, and lines can carry vocal tags such as &lt;code&gt;&amp;lt;laugh&amp;gt;&lt;/code&gt; and &lt;code&gt;&amp;lt;sigh&amp;gt;&lt;/code&gt;. Text is treated as a verbatim transcript, so it reads what you wrote instead of rewording it. The flip side is in Step 2: directions written into the text get read too.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Customizable voices.&lt;/strong&gt; Besides 30 prebuilt voices and more than 2,000 in the Extended Voice Library, you can design a voice from a sentence or two (ours took a few seconds) or replicate one from a recording. Accent, age and timbre are all yours to set, which is what got us Hong Kong-accented English.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Long-form stability&lt;/strong&gt; (per Google). Voice, volume and room tone stay consistent over long dialogues and multi-minute narration. Our video is 30 seconds, so we did not verify this.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;One API, two tiers.&lt;/strong&gt; Flash and Flash-Lite share the request schema: Flash for quality, Flash-Lite for latency and cost, switched by changing the model ID.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cheap&lt;/strong&gt;, see the next section.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="pricing-roughly-one-to-three-us-cents-per-minute-of-speech"&gt;Pricing: roughly one to three US cents per minute of speech&lt;a class="hd-a" href="#pricing-roughly-one-to-three-us-cents-per-minute-of-speech" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;From the &lt;a href="https://cloud.google.com/gemini-enterprise-agent-platform/generative-ai/pricing"&gt;official Gemini Enterprise pricing&lt;/a&gt; (USD per 1M tokens):&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Model&lt;/th&gt;
&lt;th&gt;Period&lt;/th&gt;
&lt;th style="text-align:right"&gt;Text input&lt;/th&gt;
&lt;th style="text-align:right"&gt;Audio output&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Flash TTS&lt;/td&gt;
&lt;td&gt;Through 2026-12-31 (promotional)&lt;/td&gt;
&lt;td style="text-align:right"&gt;0.50&lt;/td&gt;
&lt;td style="text-align:right"&gt;9.00&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Flash TTS&lt;/td&gt;
&lt;td&gt;From 2027-01-01&lt;/td&gt;
&lt;td style="text-align:right"&gt;1.00&lt;/td&gt;
&lt;td style="text-align:right"&gt;18.00&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Flash-Lite TTS&lt;/td&gt;
&lt;td&gt;Through 2026-12-31 (promotional)&lt;/td&gt;
&lt;td style="text-align:right"&gt;0.50&lt;/td&gt;
&lt;td style="text-align:right"&gt;6.00&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Flash-Lite TTS&lt;/td&gt;
&lt;td&gt;From 2027-01-01&lt;/td&gt;
&lt;td style="text-align:right"&gt;1.00&lt;/td&gt;
&lt;td style="text-align:right"&gt;12.00&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;The promotional price takes the form of 50% credits back on net spend on the same model, not a direct discount.&lt;/p&gt;
&lt;p&gt;Almost all of the cost is audio output. We read &lt;code&gt;usageMetadata&lt;/code&gt; from the responses: both measurements came to &lt;strong&gt;25 tokens per second of audio&lt;/strong&gt; (99 tokens for 3.96 s, 130 for 5.2 s). For Flash TTS that works out to:&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th style="text-align:right"&gt;Promotional&lt;/th&gt;
&lt;th style="text-align:right"&gt;From 2027&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Per minute of speech (1,500 tokens)&lt;/td&gt;
&lt;td style="text-align:right"&gt;$0.0135&lt;/td&gt;
&lt;td style="text-align:right"&gt;$0.027&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Per hour of speech (90,000 tokens)&lt;/td&gt;
&lt;td style="text-align:right"&gt;$0.81&lt;/td&gt;
&lt;td style="text-align:right"&gt;$1.62&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;Text input is a few dozen tokens per line and can be ignored. The five lines of our video, including the takes our checks sent back, came to 1,118 audio tokens, or $0.02 at the 2027 list price; designing a voice took about 220 input and 560 output tokens, about $0.01. The transcription calls used for checking are billed separately at the transcription model's rates and are not included.&lt;/p&gt;
&lt;h2 id="step-1-write-a-colloquial-cantonese-script-not-a-mandarin-script-read-in-cantonese"&gt;Step 1: Write a colloquial Cantonese script, not a Mandarin script read in Cantonese&lt;a class="hd-a" href="#step-1-write-a-colloquial-cantonese-script-not-a-mandarin-script-read-in-cantonese" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Hand a Mandarin script to TTS and ask for Cantonese, and you get written Chinese read aloud in Cantonese, which any Hong Konger can tell at once. Rewrite the script as speech first:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Use spoken Cantonese words&lt;/strong&gt;: 在 → 喺 (at), 是 → 係 (is), 了 → 咗 (perfective), 重来 → 由頭嚟過 (start over), 只剩 → 得返 (only ... left).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Keep technical terms in English&lt;/strong&gt;: Hong Kong engineers say cold start, compile, cache and bottleneck in everyday speech. Translating them all into Chinese sounds less natural, not more.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Keep the takeaway in Chinese for non-technical viewers&lt;/strong&gt;, for example 優化實驗 (optimization experiments).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This step decides whether it sounds like a Hong Konger talking, and the model can't do it for you.&lt;/p&gt;
&lt;h2 id="step-2-only-the-spoken-words-go-in-the-text-style-goes-in-speechmetadatastyle"&gt;Step 2: Only the spoken words go in the text; style goes in &lt;code&gt;speechMetadata.style&lt;/code&gt;&lt;a class="hd-a" href="#step-2-only-the-spoken-words-go-in-the-text-style-goes-in-speechmetadatastyle" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;This is the easiest trap when moving from older TTS models. With older models such as &lt;code&gt;gemini-3.1-flash-tts-preview&lt;/code&gt;, the usual practice was to write the style into the text: &amp;quot;Read this in an excited tone: …&amp;quot;. For 3.8, the &lt;a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/text-to-speech/migration-guide"&gt;official migration guide&lt;/a&gt; says &lt;code&gt;text&lt;/code&gt; is read as a verbatim transcript, and directions written into it &amp;quot;might be spoken aloud&amp;quot;.&lt;/p&gt;
&lt;p&gt;What we measured: keeping the old style of prompt (directions in the text, script fenced in quotes), two takes for each of the five lines, &lt;strong&gt;6 takes read the whole direction aloud&lt;/strong&gt;, and lines that should run 3–8 s ran 17–40 s.&lt;/p&gt;
&lt;figure&gt;
&lt;audio controls preload="none" style="width:100%" src="/gemini-tts-cantonese/01-leak.mp3"&gt;&lt;/audio&gt;
&lt;figcaption&gt;Counter-example (first 13 s): the model starts with "Read only the text inside the quotes, do not read this instruction…", in Cantonese.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;The correct request looks like this. Style goes in &lt;code&gt;speechMetadata.style&lt;/code&gt; as one short phrase; &lt;code&gt;text&lt;/code&gt; holds only the lines:&lt;/p&gt;
&lt;div class="code-block"&gt;&lt;div class="code-head"&gt;&lt;span class="code-lang"&gt;python&lt;/span&gt;&lt;button type="button" class="copy-btn"&gt;&lt;/button&gt;&lt;/div&gt;&lt;div class="hl"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;base64&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;subprocess&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;requests&lt;/span&gt;

&lt;span class="n"&gt;URL&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/&amp;quot;&lt;/span&gt;
       &lt;span class="s2"&gt;&amp;quot;publishers/google/models/gemini-3.8-flash-tts:generateContent&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;TOKEN&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;subprocess&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;check_output&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;gcloud&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;auth&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;print-access-token&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;tts&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;style&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;voice&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;out_path&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;body&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="s2"&gt;&amp;quot;contents&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;role&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;user&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;parts&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[{&lt;/span&gt;
            &lt;span class="s2"&gt;&amp;quot;text&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;                                  &lt;span class="c1"&gt;# only the words to be spoken&lt;/span&gt;
            &lt;span class="s2"&gt;&amp;quot;speechMetadata&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;style&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;style&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;            &lt;span class="c1"&gt;# style: one short phrase&lt;/span&gt;
        &lt;span class="p"&gt;}]}],&lt;/span&gt;
        &lt;span class="s2"&gt;&amp;quot;generationConfig&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="s2"&gt;&amp;quot;responseModalities&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;AUDIO&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
            &lt;span class="s2"&gt;&amp;quot;speechConfig&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;languageCode&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;yue-HK&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;voiceConfig&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;voice&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;voice&lt;/span&gt;&lt;span class="p"&gt;}},&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;requests&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;post&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;URL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;headers&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Authorization&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Bearer &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;TOKEN&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;body&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;180&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;raise_for_status&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;()[&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;candidates&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;content&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;parts&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;inlineData&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;data&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;out_path&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;wb&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;write&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;base64&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;b64decode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;                    &lt;span class="c1"&gt;# unary requests return a complete WAV file&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;The styles we ended up with: one shared base, plus one mood per line.&lt;/p&gt;
&lt;div class="code-block"&gt;&lt;div class="code-head"&gt;&lt;span class="code-lang"&gt;python&lt;/span&gt;&lt;button type="button" class="copy-btn"&gt;&lt;/button&gt;&lt;/div&gt;&lt;div class="hl"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="n"&gt;BASE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;Hong Kong Cantonese, tech keynote narrator, steady pace, crisp endings&amp;quot;&lt;/span&gt;
&lt;span class="n"&gt;STYLE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;problem&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;BASE&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;, heavy and urgent&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;    &lt;span class="s2"&gt;&amp;quot;turn&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;BASE&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;, calm and assured&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
         &lt;span class="s2"&gt;&amp;quot;fix&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;BASE&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;, confident and upbeat&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;     &lt;span class="s2"&gt;&amp;quot;result&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;BASE&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;, energetic, pleasantly surprised&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
         &lt;span class="s2"&gt;&amp;quot;payoff&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;BASE&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;, rising excitement, strong finish&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;Related changes to watch for:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;systemInstruction&lt;/code&gt; is no longer supported.&lt;/strong&gt; Moving the directions into a system message is not a way around this.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;temperature&lt;/code&gt; / &lt;code&gt;topP&lt;/code&gt; / &lt;code&gt;topK&lt;/code&gt; are rejected with &lt;code&gt;INVALID_ARGUMENT&lt;/code&gt;&lt;/strong&gt;; remove them from the request.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Unary requests return a complete WAV file&lt;/strong&gt; that starts with a &lt;code&gt;RIFF&lt;/code&gt; header. If your old code treats the response as raw PCM and wraps its own WAV header around it, the header bytes get played as audio: a very short click at the start.&lt;/li&gt;
&lt;li&gt;If you call the model through an OpenAI-compatible middle layer, &lt;strong&gt;first check that it passes &lt;code&gt;speechMetadata&lt;/code&gt; through.&lt;/strong&gt; How to check is in Step 6: set the style to &amp;quot;extremely slow, one syllable at a time&amp;quot; and see whether the duration grows.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="step-3-let-the-voice-carry-the-accent-build-a-hong-kong-voice-with-voice-design"&gt;Step 3: Let the voice carry the accent; build a Hong Kong voice with voice design&lt;a class="hd-a" href="#step-3-let-the-voice-carry-the-accent-build-a-hong-kong-voice-with-voice-design" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;With the prebuilt voice Puck, the Cantonese itself was fine, but the English in each line had a standard American or British accent, which is not how Hong Kongers talk. The &lt;a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/text-to-speech/prompting-guide"&gt;prompting guide&lt;/a&gt; says fixed traits such as age, gender and regional accent belong to the voice, not to &lt;code&gt;style&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The catch is that the voice library has no such voice. We paged through the whole Voices API list: 30 prebuilt voices plus the Extended Voice Library, 2,089 in all, with language codes concentrated in en / ko / ja / hi / pt / ar / de and similar, and &lt;strong&gt;not one Cantonese or Chinese voice&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;So the only option is &lt;a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/text-to-speech/voice-design"&gt;voice design&lt;/a&gt;: describe the voice in a sentence or two, and the API generates it, stores it in your project and returns a &lt;code&gt;voice_…&lt;/code&gt; ID that you use like a prebuilt voice.&lt;/p&gt;
&lt;div class="code-block"&gt;&lt;div class="code-head"&gt;&lt;span class="code-lang"&gt;python&lt;/span&gt;&lt;button type="button" class="copy-btn"&gt;&lt;/button&gt;&lt;/div&gt;&lt;div class="hl"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="n"&gt;VOICES&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/voices&amp;quot;&lt;/span&gt;
&lt;span class="n"&gt;body&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;store&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;voice&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="s2"&gt;&amp;quot;type&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;VOICE_TYPE_PROMPTED&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;&amp;quot;displayName&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;hk-engineer&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;&amp;quot;gender&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;male&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;&amp;quot;languageCode&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;yue-HK&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="c1"&gt;# &amp;quot;A Hong Kong male engineer in his thirties, speaking natural colloquial Hong Kong Cantonese; the English terms&lt;/span&gt;
    &lt;span class="c1"&gt;#  in his sentences carry a clear Hong Kong accent (not standard American or British); clear, confident,&lt;/span&gt;
    &lt;span class="c1"&gt;#  like a tech keynote narrator.&amp;quot;&lt;/span&gt;
    &lt;span class="s2"&gt;&amp;quot;prompted&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;input&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;三十多岁的香港男工程师，讲地道香港粤语口语，句中夹杂的英文术语带明显港式口音&amp;quot;&lt;/span&gt;
                          &lt;span class="s2"&gt;&amp;quot;（唔系标准英美音），声音清晰、自信，似科技发布会旁白。&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="p"&gt;}}&lt;/span&gt;
&lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;requests&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;post&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;VOICES&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;headers&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Authorization&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Bearer &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;TOKEN&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;body&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;120&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;voice_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;()[&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;id&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;                 &lt;span class="c1"&gt;# like voice_xxxxxxxx-...; pass it as voiceConfig.voice&lt;/span&gt;
&lt;span class="c1"&gt;# r.json()[&amp;quot;sample_audio&amp;quot;] is a preview: audio/l16, 24 kHz mono raw PCM; add a WAV header yourself&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;We built two, one from an English description and one from the Chinese description above, generated the full narration with each, and a listener picked the one built from the Chinese description.&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;tr&gt;&lt;td&gt;Prebuilt voice Puck&lt;/td&gt;&lt;td&gt;&lt;audio controls preload="none" style="width:240px;max-width:100%" src="/gemini-tts-cantonese/03-puck.mp3"&gt;&lt;/audio&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Designed voice (Hong Kong engineer)&lt;/td&gt;&lt;td&gt;&lt;audio controls preload="none" style="width:240px;max-width:100%" src="/gemini-tts-cantonese/03-designed.mp3"&gt;&lt;/audio&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;Two things to note:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Creating a voice is billed&lt;/strong&gt; (as text input plus audio output tokens; about 220 in and 560 out for ours). Speech generated with it is billed at the normal rate.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Stored voices expire after a year without use&lt;/strong&gt;; each use resets the clock. For a long-running project, keep the description so you can recreate the voice if it expires.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="step-4-traditional-cantonese-characters-keep-mandarin-out"&gt;Step 4: Traditional Cantonese characters keep Mandarin out&lt;a class="hd-a" href="#step-4-traditional-cantonese-characters-keep-mandarin-out" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;The documentation says 3.8 &lt;a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/text-to-speech/overview"&gt;detects the input language automatically&lt;/a&gt;. We set &lt;code&gt;languageCode: yue-HK&lt;/code&gt; in the request, but while the Cantonese script was written in simplified characters (系, 个, 钟), the result line still came out entirely in Mandarin from time to time.&lt;/p&gt;
&lt;p&gt;For the result line, &amp;quot;Cold start，直接压到得返 14 分钟！&amp;quot;, same voice, several takes per variant:&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Script&lt;/th&gt;
&lt;th style="text-align:right"&gt;Takes read in Mandarin&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Simplified-character Cantonese&lt;/td&gt;
&lt;td style="text-align:right"&gt;2 / 4&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Traditional Cantonese characters&lt;/td&gt;
&lt;td style="text-align:right"&gt;1 / 4&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Traditional Cantonese characters + &lt;code&gt;Hong Kong Cantonese&lt;/code&gt; in the style&lt;/td&gt;
&lt;td style="text-align:right"&gt;0 / 10&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;The other four lines never came out in Mandarin with any variant. The one that did is the shortest line, and the only one that starts in English. We have not verified why it is more likely to be taken as Mandarin; we only observed it.&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;tr&gt;&lt;td&gt;Simplified script: whole line in Mandarin&lt;/td&gt;&lt;td&gt;&lt;audio controls preload="none" style="width:240px;max-width:100%" src="/gemini-tts-cantonese/02-mandarin.mp3"&gt;&lt;/audio&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Traditional characters + Hong Kong Cantonese&lt;/td&gt;&lt;td&gt;&lt;audio controls preload="none" style="width:240px;max-width:100%" src="/gemini-tts-cantonese/02-cantonese.mp3"&gt;&lt;/audio&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;We use &amp;quot;Hong Kong Cantonese&amp;quot; in the style to steer the &lt;strong&gt;language&lt;/strong&gt;, not the accent: with the same phrase, the prebuilt voice still spoke standard English. The accent comes from the voice in Step 3.&lt;/p&gt;
&lt;h2 id="step-5-dont-stack-speed-ups-and-dont-rely-on-tags-for-pauses"&gt;Step 5: Don't stack speed-ups, and don't rely on tags for pauses&lt;a class="hd-a" href="#step-5-dont-stack-speed-ups-and-dont-rely-on-tags-for-pauses" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Two habits from our old pipeline made the pacing worse:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Stacked speed-ups.&lt;/strong&gt; To fit 30 seconds, the old pipeline put &amp;quot;speaking rapidly&amp;quot; in the style and then sped the audio up again with ffmpeg &lt;code&gt;atempo=1.07&lt;/code&gt;. On 3.8 it was clearly too fast. With both removed, the full Cantonese narration went from 22.1 s to 27.7 s (same voice). The final video grew from 30 s to 30.5 s, with a voice change and two re-recorded lines in between.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A pause tag that is too long.&lt;/strong&gt; For a short pause after &amp;quot;Cold start&amp;quot; we used the official &lt;code&gt;&amp;lt;short pause&amp;gt;&lt;/code&gt; tag, and measured a 0.86 s gap, which sounds like a break. With the tag removed and only the comma left, the pause is about 0.3 s and sounds natural.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;code&gt;&amp;lt;short pause&amp;gt;&lt;/code&gt; / &lt;code&gt;&amp;lt;long pause&amp;gt;&lt;/code&gt; from the guide are for places that need real silence. For phrasing, punctuation is enough.&lt;/p&gt;
&lt;h2 id="step-6-check-every-take-word-by-word"&gt;Step 6: Check every take word by word&lt;a class="hd-a" href="#step-6-check-every-take-word-by-word" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;The same line comes out differently on every take, and if you generate enough, some will be wrong. What we ran into:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&amp;quot;14 分鐘&amp;quot; (14 minutes) came out as &amp;quot;&lt;strong&gt;14 秒&lt;/strong&gt;&amp;quot; (14 seconds), and that take was already in the video before a listener caught it;&lt;/li&gt;
&lt;li&gt;another take said &amp;quot;&lt;strong&gt;1.4 分鐘&lt;/strong&gt;&amp;quot; (1.4 minutes);&lt;/li&gt;
&lt;li&gt;and the whole-line Mandarin takes described above.&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;tr&gt;&lt;td&gt;"14 seconds", and a 0.86 s gap after Cold start&lt;/td&gt;&lt;td&gt;&lt;audio controls preload="none" style="width:240px;max-width:100%" src="/gemini-tts-cantonese/04-14sec.mp3"&gt;&lt;/audio&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Fixed: number written as 十四, pause tag removed&lt;/td&gt;&lt;td&gt;&lt;audio controls preload="none" style="width:240px;max-width:100%" src="/gemini-tts-cantonese/04-fixed.mp3"&gt;&lt;/audio&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;With the number written in digits, 2 of 5 takes were wrong (&amp;quot;14 秒&amp;quot;, &amp;quot;1.4 分鐘&amp;quot;); written as 十四, all 4 takes were right. The samples are small, but rewriting costs nothing, so we recommend writing numbers in characters.&lt;/p&gt;
&lt;p&gt;The acceptance checks we settled on, run on every take:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Two transcription models, word by word&lt;/strong&gt; (we used Gemini 3.5 Flash and 3.7 Flash). A take passes only if both match the script. A single transcription model mishears too (it turned 混元 into other words), so don't trust just one.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cut long audio into short chunks before transcribing.&lt;/strong&gt; On a whole take, the model summarized away the direction that had been read aloud and returned a clean-looking transcript; we were fooled by this once. Cut at the pauses into chunks a few seconds long, and transcribe those.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Look at the duration.&lt;/strong&gt; A take several times longer than the normal length of the same line almost always means the directions were read aloud. This check is the cheapest and the most reliable.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Measure the longest pause inside the line&lt;/strong&gt; (&lt;code&gt;ffmpeg -af silencedetect&lt;/code&gt;); listen to anything over about 0.5 s.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Check the language.&lt;/strong&gt; Have a transcription model report the share of characters pronounced in Cantonese. Before relying on it, run it on a known Cantonese sample and a known Mandarin sample and confirm it tells them apart (we got 100 and 0).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;There is no reliable automatic check for accent.&lt;/strong&gt; We asked a model to rate the Hong Kong accent of the English words from 1 to 5, and every sample got 3, including Puck with its standard American accent, so the rating could not tell anything apart. Accent has to be judged by ear.&lt;/p&gt;
&lt;h2 id="step-7-if-a-single-english-word-still-sounds-american-change-its-spelling"&gt;Step 7: If a single English word still sounds American, change its spelling&lt;a class="hd-a" href="#step-7-if-a-single-english-word-still-sounds-american-change-its-spelling" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;With the designed voice, most of the English already sounded like Hong Kong, but a listener still flagged &amp;quot;iterate&amp;quot; in the payoff line as too American. We made three candidates to choose from by ear:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the same script, generated again;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;English words in a Hong Kong accent&lt;/code&gt; added to the style;&lt;/li&gt;
&lt;li&gt;the spelling changed to &lt;strong&gt;&lt;code&gt;i-te-rate&lt;/code&gt;&lt;/strong&gt;, so the three syllables get even weight.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The respelling won. That was a listener's choice, not a measurement, and it may not work as well for other words. But respelling costs almost nothing, so it is worth trying first.&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;tr&gt;&lt;td&gt;Original spelling: iterate&lt;/td&gt;&lt;td&gt;&lt;audio controls preload="none" style="width:240px;max-width:100%" src="/gemini-tts-cantonese/05-iterate-us.mp3"&gt;&lt;/audio&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Respelled: i-te-rate&lt;/td&gt;&lt;td&gt;&lt;audio controls preload="none" style="width:240px;max-width:100%" src="/gemini-tts-cantonese/05-iterate-hk.mp3"&gt;&lt;/audio&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;h2 id="a-small-trap-when-cutting-it-into-the-video"&gt;A small trap when cutting it into the video&lt;a class="hd-a" href="#a-small-trap-when-cutting-it-into-the-video" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;The narration is generated line by line, and the on-screen cards and number hits have to land with the speech. We locate them by the pauses in each line's audio; the hit on &amp;quot;80 組&amp;quot; (80 runs), for example, was placed at the &lt;strong&gt;longest pause&lt;/strong&gt; in the payoff line.&lt;/p&gt;
&lt;p&gt;With the new voiceover, the two longest pauses differed by 2 ms (0.351 s vs 0.349 s), the code picked the earlier one, and the hit landed about 2.6 s early. We changed the rule to &amp;quot;the pause nearest 60% of the line&amp;quot; and re-ran it on the old voiceovers to confirm it picks the same positions there.&lt;/p&gt;
&lt;p&gt;This has nothing to do with TTS, but it can trigger every time the voiceover is regenerated: &lt;strong&gt;an anchor chosen by &amp;quot;the maximum&amp;quot; fails at random when values are nearly tied.&lt;/strong&gt;&lt;/p&gt;
&lt;h2 id="the-complete-prompts-and-script"&gt;The complete prompts and script&lt;a class="hd-a" href="#the-complete-prompts-and-script" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Put the seven steps together and you get the script below. It does four things: creates a voice from the description if you don't pass one; synthesizes each line; runs the Step 6 checks on every take (duration, longest pause, keywords in two transcriptions, Cantonese share) and regenerates a line that fails, up to 4 times; and finally trims the silence, joins the lines into one narration, and reports token usage and cost.&lt;/p&gt;
&lt;p&gt;All the prompts it uses:&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Purpose&lt;/th&gt;
&lt;th&gt;Content&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Voice description (used once, to create the voice)&lt;/td&gt;
&lt;td&gt;三十多岁的香港男工程师，讲地道香港粤语口语，句中夹杂的英文术语带明显港式口音（唔系标准英美音），声音清晰、自信，似科技发布会旁白。 (&amp;quot;A Hong Kong male engineer in his thirties … like a tech keynote narrator&amp;quot;, see Step 3)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Style base (on every line)&lt;/td&gt;
&lt;td&gt;&lt;code&gt;Hong Kong Cantonese, tech keynote narrator, steady pace, crisp endings&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Per-line mood&lt;/td&gt;
&lt;td&gt;heavy and urgent / calm and assured / confident and upbeat / energetic, pleasantly surprised / rising excitement, strong finish&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Lines&lt;/td&gt;
&lt;td&gt;The five lines at the top of this post, in traditional Cantonese characters&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="/gemini-tts-cantonese/make_voiceover.py"&gt;Download make_voiceover.py&lt;/a&gt;. Requirements: Python 3 with &lt;code&gt;requests&lt;/code&gt;, and &lt;code&gt;ffmpeg&lt;/code&gt; / &lt;code&gt;ffprobe&lt;/code&gt; on PATH; run &lt;code&gt;gcloud auth login&lt;/code&gt; first, and the project needs Vertex AI enabled.&lt;/p&gt;
&lt;div class="code-block"&gt;&lt;div class="code-head"&gt;&lt;span class="code-lang"&gt;bash&lt;/span&gt;&lt;button type="button" class="copy-btn"&gt;&lt;/button&gt;&lt;/div&gt;&lt;div class="hl"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="nb"&gt;export&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nv"&gt;PROJECT_ID&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;your-project
&lt;span class="nb"&gt;export&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nv"&gt;VOICE_ID&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;voice_...&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;# optional: reuse a designed voice; if unset, one is created and its ID printed&lt;/span&gt;
python3&lt;span class="w"&gt; &lt;/span&gt;make_voiceover.py
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div class="code-block"&gt;&lt;div class="code-head"&gt;&lt;span class="code-lang"&gt;python&lt;/span&gt;&lt;button type="button" class="copy-btn"&gt;&lt;/button&gt;&lt;/div&gt;&lt;div class="hl"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="ch"&gt;#!/usr/bin/env python3&lt;/span&gt;
&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;Cantonese voiceover with Gemini 3.8 Flash TTS: one take per line, checked, then joined.&lt;/span&gt;

&lt;span class="sd"&gt;    export PROJECT_ID=your-project        # Vertex AI enabled; `gcloud auth login` done&lt;/span&gt;
&lt;span class="sd"&gt;    export VOICE_ID=voice_...             # optional: reuse a designed voice; omitted -&amp;gt; one is created&lt;/span&gt;
&lt;span class="sd"&gt;    python3 make_voiceover.py             # -&amp;gt; out/line*.wav, out/narration.wav&lt;/span&gt;

&lt;span class="sd"&gt;Needs: python3 + requests, ffmpeg/ffprobe on PATH.&lt;/span&gt;
&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;base64&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;io&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;json&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;os&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;re&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;subprocess&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;tempfile&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;time&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;wave&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;requests&lt;/span&gt;

&lt;span class="n"&gt;PROJECT&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;environ&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;PROJECT_ID&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="n"&gt;API&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;https://aiplatform.googleapis.com/v1beta1/projects/&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;PROJECT&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;/locations/global&amp;quot;&lt;/span&gt;
&lt;span class="n"&gt;TOKEN&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;subprocess&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;check_output&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;gcloud&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;auth&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;print-access-token&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="n"&gt;HDR&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Authorization&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Bearer &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;TOKEN&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="n"&gt;OUT&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;out&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;GAP&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;0.4&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;MAX_TAKES&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;
&lt;span class="n"&gt;PRICE_PER_M&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;text_in&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;1.00&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;audio_out&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;18.00&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;   &lt;span class="c1"&gt;# USD per 1M tokens from 2027-01-01 (half that through 2026)&lt;/span&gt;

&lt;span class="c1"&gt;# --- the voice: accent, age and timbre live here, not in the style ---------------------------&lt;/span&gt;
&lt;span class="n"&gt;VOICE_PROMPT&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;三十多岁的香港男工程师，讲地道香港粤语口语，句中夹杂的英文术语带明显港式口音&amp;quot;&lt;/span&gt;
                &lt;span class="s2"&gt;&amp;quot;（唔系标准英美音），声音清晰、自信，似科技发布会旁白。&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# --- the script: text is read verbatim; style is one short phrase per line --------------------&lt;/span&gt;
&lt;span class="n"&gt;BASE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;Hong Kong Cantonese, tech keynote narrator, steady pace, crisp endings&amp;quot;&lt;/span&gt;
&lt;span class="n"&gt;LINES&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;  &lt;span class="c1"&gt;# (text in traditional Cantonese characters, mood, must appear in transcript, must not appear)&lt;/span&gt;
    &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;混元 4 喺 TPU v7 度 cold start，淨係 compile 就要 95 分鐘；cache 一 invalidate 咗，就要由頭嚟過。&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
     &lt;span class="s2"&gt;&amp;quot;heavy and urgent&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sa"&gt;r&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;95&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sa"&gt;r&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;分[鐘钟]&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="p"&gt;[]),&lt;/span&gt;
    &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Bottleneck 唔喺 compiler 度，係個 graph 畀人放大咗。&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;calm and assured&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sa"&gt;r&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;(?i)compiler&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sa"&gt;r&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;(?i)graph&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="p"&gt;[]),&lt;/span&gt;
    &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Loop 改用 for i，constant 改做 parameter，compile 出嚟嘅嘢喺唔同 rank 之間 share。&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
     &lt;span class="s2"&gt;&amp;quot;confident and upbeat&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sa"&gt;r&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;(?i)constant&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sa"&gt;r&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;(?i)parameter&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="p"&gt;[]),&lt;/span&gt;
    &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Cold start，直接壓到得返十四分鐘！&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;energetic, pleasantly surprised&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sa"&gt;r&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;14|十四&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sa"&gt;r&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;分[鐘钟]&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
     &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sa"&gt;r&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;秒&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sa"&gt;r&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;1\.4&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]),&lt;/span&gt;                                             &lt;span class="c1"&gt;# misreadings we actually heard&lt;/span&gt;
    &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;每日嘅優化實驗由 12 組變 80 組，i-te-rate 快咗好多！&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;rising excitement, strong finish&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sa"&gt;r&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;12|十二&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sa"&gt;r&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;80|八十&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="p"&gt;[]),&lt;/span&gt;
&lt;span class="p"&gt;]&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;post&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;body&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;180&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;requests&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;post&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;API&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;/&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;headers&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;HDR&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;body&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;raise_for_status&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;create_voice&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;post&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;voices&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;store&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;voice&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="s2"&gt;&amp;quot;type&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;VOICE_TYPE_PROMPTED&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;displayName&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;hk-engineer&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;gender&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;male&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;&amp;quot;languageCode&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;yue-HK&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;prompted&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;input&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;VOICE_PROMPT&lt;/span&gt;&lt;span class="p"&gt;}}},&lt;/span&gt; &lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;120&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;created voice&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;id&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;- export VOICE_ID to reuse it&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;id&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;synth&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;style&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;voice&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;post&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;publishers/google/models/gemini-3.8-flash-tts:generateContent&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="s2"&gt;&amp;quot;contents&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;role&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;user&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;parts&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;text&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;speechMetadata&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;style&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;style&lt;/span&gt;&lt;span class="p"&gt;}}]}],&lt;/span&gt;
        &lt;span class="s2"&gt;&amp;quot;generationConfig&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;responseModalities&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;AUDIO&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
                             &lt;span class="s2"&gt;&amp;quot;speechConfig&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;languageCode&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;yue-HK&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;voiceConfig&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;voice&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;voice&lt;/span&gt;&lt;span class="p"&gt;}}}})&lt;/span&gt;
    &lt;span class="n"&gt;wav&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;base64&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;b64decode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;candidates&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;content&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;parts&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;inlineData&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;data&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;  &lt;span class="c1"&gt;# complete WAV&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;wav&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;usageMetadata&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{})&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;ffmpeg&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;subprocess&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;run&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;ffmpeg&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;-nostdin&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;-v&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;error&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;-y&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="nb"&gt;input&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                          &lt;span class="n"&gt;capture_output&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;check&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stdout&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;trim&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;wav&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;  &lt;span class="c1"&gt;# cut leading/trailing silence, short fades against clicks&lt;/span&gt;
    &lt;span class="n"&gt;edge&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;silenceremove=start_periods=1:start_threshold=-42dB&amp;quot;&lt;/span&gt;
    &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="n"&gt;tempfile&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;NamedTemporaryFile&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;suffix&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;.wav&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;   &lt;span class="c1"&gt;# a file, not a pipe, so the WAV header gets real sizes&lt;/span&gt;
        &lt;span class="n"&gt;ffmpeg&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;-i&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;pipe:0&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;-af&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;,areverse,&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;,areverse,afade=t=in:d=0.01,areverse,&amp;quot;&lt;/span&gt;
               &lt;span class="s2"&gt;&amp;quot;afade=t=in:d=0.04,areverse&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;wav&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;rb&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;read&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;duration&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;wav&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;wave&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;io&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;BytesIO&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;wav&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getnframes&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getframerate&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;longest_pause&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;wav&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;log&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;subprocess&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;run&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;ffmpeg&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;-nostdin&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;-i&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;pipe:0&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;-af&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;silencedetect=n=-38dB:d=0.12&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;-f&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;null&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;-&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
                         &lt;span class="nb"&gt;input&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;wav&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;capture_output&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stderr&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;decode&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="n"&gt;st&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;float&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;re&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;findall&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;r&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;silence_start: ([\d.]+)&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;
    &lt;span class="n"&gt;en&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;float&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;re&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;findall&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;r&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;silence_end: ([\d.]+)&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;max&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;zip&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;en&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mf"&gt;0.0&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;ask&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;prompt&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;wav&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;body&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;contents&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;role&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;user&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;parts&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;text&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;prompt&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;inlineData&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;mimeType&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;audio/wav&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;data&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;base64&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;b64encode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;wav&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;decode&lt;/span&gt;&lt;span class="p"&gt;()}}]}]}&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;attempt&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;         &lt;span class="c1"&gt;# now and then a response comes back with no text&lt;/span&gt;
        &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;post&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;publishers/google/models/&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;:generateContent&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;body&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;parts&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;candidates&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="p"&gt;[{}])[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;content&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{})&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;parts&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[])&lt;/span&gt;
        &lt;span class="n"&gt;text&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;&amp;quot;&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;text&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;parts&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;
        &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;attempt&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;&amp;quot;&lt;/span&gt;                        &lt;span class="c1"&gt;# an empty transcript fails the check, so the line is generated again&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;check&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;wav&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;must&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;forbid&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;Return a list of problems; empty means the take passes.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
    &lt;span class="n"&gt;problems&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dur&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[],&lt;/span&gt; &lt;span class="n"&gt;duration&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;wav&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;units&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;re&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;findall&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;r&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;[\u4e00-\u9fff]&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;re&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;findall&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;r&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;[A-Za-z]+(?:-[A-Za-z]+)*&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
             &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;re&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;findall&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;r&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;\d+&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;)))&lt;/span&gt;                      &lt;span class="c1"&gt;# Chinese characters + English words + numbers&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;dur&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mf"&gt;1.5&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mf"&gt;0.3&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;units&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;     &lt;span class="c1"&gt;# normal takes ran 0.23-0.29 s/unit; takes that read the directions ran 3-12x&lt;/span&gt;
        &lt;span class="n"&gt;problems&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;too long (&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;dur&lt;/span&gt;&lt;span class="si"&gt;:&lt;/span&gt;&lt;span class="s2"&gt;.1f&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;s)&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;pause&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;longest_pause&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;wav&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;pause&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mf"&gt;0.6&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;                                                 &lt;span class="c1"&gt;# 0.86 s read as a break; commas give ~0.3 s&lt;/span&gt;
        &lt;span class="n"&gt;problems&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;pause &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;pause&lt;/span&gt;&lt;span class="si"&gt;:&lt;/span&gt;&lt;span class="s2"&gt;.2f&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;s&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;model&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;gemini-3.5-flash&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;gemini-3.7-flash&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;          &lt;span class="c1"&gt;# two transcribers must both agree&lt;/span&gt;
        &lt;span class="n"&gt;heard&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ask&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;逐字转写这段粤语音频，数字用阿拉伯数字，只输出转写。&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;wav&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;miss&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;must&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;re&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;search&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;heard&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;forbid&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;re&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;search&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;heard&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;miss&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;problems&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt; heard &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;heard&lt;/span&gt;&lt;span class="si"&gt;!r}&lt;/span&gt;&lt;span class="s2"&gt; (check &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;miss&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;)&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;js&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ask&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;gemini-3.5-flash&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;判断音频里每个中文字是粤语还是普通话发音（英文词忽略）。&amp;#39;&lt;/span&gt;
             &lt;span class="s1"&gt;&amp;#39;只输出 JSON：{&amp;quot;cantonese_pct&amp;quot;: 0-100}&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;wav&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;re&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;search&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;r&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;\{.*\}&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;js&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;re&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;S&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;pct&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;loads&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;group&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;cantonese_pct&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;pct&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;90&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;problems&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Mandarin drift (cantonese_pct=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;pct&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;)&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;problems&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;makedirs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;OUT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;exist_ok&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;voice&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;environ&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;VOICE_ID&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="n"&gt;create_voice&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="n"&gt;tokens&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;text_in&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;audio_out&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="n"&gt;takes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;mood&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;must&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;forbid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;enumerate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;LINES&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;MAX_TAKES&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="n"&gt;wav&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;usage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;synth&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;BASE&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;, &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;mood&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;voice&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;tokens&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;text_in&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;promptTokenCount&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;tokens&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;audio_out&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;candidatesTokenCount&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;wav&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;trim&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;wav&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;problems&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;check&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;wav&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;must&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;forbid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;line &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt; take &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;duration&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;wav&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;:&lt;/span&gt;&lt;span class="s2"&gt;.2f&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;s&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;OK&amp;quot;&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;problems&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="n"&gt;problems&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;problems&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;break&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="ne"&gt;SystemExit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;line &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;: no clean take in &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;MAX_TAKES&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt; tries; listen to out/line&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;.wav&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;path&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;OUT&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;/line&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;.wav&amp;quot;&lt;/span&gt;
        &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;wb&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;write&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;wav&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="n"&gt;takes&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;gap&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;OUT&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;/gap.wav&amp;quot;&lt;/span&gt;
    &lt;span class="n"&gt;ffmpeg&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;-f&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;lavfi&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;-i&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;anullsrc=r=24000:cl=mono&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;-t&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;GAP&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="n"&gt;gap&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;OUT&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;/list.txt&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;w&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;write&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&amp;quot;&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;file &amp;#39;&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;abspath&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;#39;&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;file &amp;#39;&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;abspath&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;gap&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;#39;&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;takes&lt;/span&gt;&lt;span class="p"&gt;[:&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
                &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;file &amp;#39;&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;abspath&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;takes&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;#39;&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;ffmpeg&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;-f&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;concat&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;-safe&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;0&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;-i&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;OUT&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;/list.txt&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;-ar&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;24000&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;-ac&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;1&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;OUT&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;/narration.wav&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;cost&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;tokens&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;PRICE_PER_M&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mf"&gt;1e6&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;tokens&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;narration: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;OUT&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;/narration.wav  tokens &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;tokens&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;  TTS cost $&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;cost&lt;/span&gt;&lt;span class="si"&gt;:&lt;/span&gt;&lt;span class="s2"&gt;.4f&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt; (list price from 2027; &amp;quot;&lt;/span&gt;
          &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;half through 2026; transcription calls billed separately)&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="vm"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;__main__&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;One real run produced the output below. Line 1's first take was sent back for a 0.72 s pause plus one transcriber returning no text, and line 3's first take for a 0.63 s pause; everything else passed first time:&lt;/p&gt;
&lt;div class="code-block"&gt;&lt;div class="code-head"&gt;&lt;span class="code-lang"&gt;text&lt;/span&gt;&lt;button type="button" class="copy-btn"&gt;&lt;/button&gt;&lt;/div&gt;&lt;div class="hl"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;line 1 take 1: 8.10s [&amp;#39;pause 0.72s&amp;#39;, &amp;quot;gemini-3.7-flash heard &amp;#39;&amp;#39; (check [&amp;#39;95&amp;#39;, &amp;#39;分[鐘钟]&amp;#39;])&amp;quot;]
line 1 take 2: 7.66s OK
line 2 take 1: 3.93s OK
line 3 take 1: 7.24s [&amp;#39;pause 0.63s&amp;#39;]
line 3 take 2: 5.97s OK
line 4 take 1: 2.72s OK
line 5 take 1: 4.76s OK
narration: out/narration.wav  tokens {&amp;#39;text_in&amp;#39;: 295, &amp;#39;audio_out&amp;#39;: 1118}  TTS cost $0.0204 (list price from 2027; half through 2026; transcription calls billed separately)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;The narration the script produced (26.6 s, no music):&lt;/p&gt;
&lt;figure&gt;
&lt;audio controls preload="none" style="width:100%" src="/gemini-tts-cantonese/06-script-output.mp3"&gt;&lt;/audio&gt;
&lt;figcaption&gt;Output of make_voiceover.py, out/narration.wav. Every run comes out slightly different.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Two notes: the cost line uses the list price from 2027, which is halved during the promotion; the Gemini 3.5 / 3.7 Flash calls made by the checks are billed separately.&lt;/p&gt;
&lt;h2 id="pitfall-checklist"&gt;Pitfall checklist&lt;a class="hd-a" href="#pitfall-checklist" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;div class="tw"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Pitfall&lt;/th&gt;
&lt;th&gt;Symptom&lt;/th&gt;
&lt;th&gt;What to do&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Style written into the text&lt;/td&gt;
&lt;td&gt;Directions read aloud; seconds become tens of seconds (6/10)&lt;/td&gt;
&lt;td&gt;Style in &lt;code&gt;speechMetadata.style&lt;/code&gt;; text holds only the lines&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Middle layer drops the field&lt;/td&gt;
&lt;td&gt;Style has no effect at all&lt;/td&gt;
&lt;td&gt;Use an &amp;quot;extremely slow&amp;quot; style and check the duration, to confirm &lt;code&gt;speechMetadata&lt;/code&gt; is passed through&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Prebuilt voice reads English&lt;/td&gt;
&lt;td&gt;Standard American or British accent&lt;/td&gt;
&lt;td&gt;No Cantonese voice among prebuilt or Extended Library voices; build a Hong Kong voice with voice design&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Cantonese in simplified characters&lt;/td&gt;
&lt;td&gt;Short line comes out entirely in Mandarin (2/4)&lt;/td&gt;
&lt;td&gt;Traditional Cantonese characters + Hong Kong Cantonese in the style (0/10)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Stacked speed-ups&lt;/td&gt;
&lt;td&gt;Too fast&lt;/td&gt;
&lt;td&gt;Drop &amp;quot;speaking rapidly&amp;quot; and atempo&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;&amp;lt;short pause&amp;gt;&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;A clear 0.86 s break&lt;/td&gt;
&lt;td&gt;Phrase with punctuation; keep tags for real silence&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Numbers in digits&lt;/td&gt;
&lt;td&gt;&amp;quot;14 秒&amp;quot;, &amp;quot;1.4 分鐘&amp;quot;&lt;/td&gt;
&lt;td&gt;Write numbers in characters&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Checking one thing only&lt;/td&gt;
&lt;td&gt;Misread words slip through&lt;/td&gt;
&lt;td&gt;Two transcription models word by word + duration + pauses + language&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Transcribing the whole take&lt;/td&gt;
&lt;td&gt;Directions read aloud get summarized away&lt;/td&gt;
&lt;td&gt;Cut into chunks of a few seconds, then transcribe&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;One English word sounds American&lt;/td&gt;
&lt;td&gt;e.g. iterate&lt;/td&gt;
&lt;td&gt;Respell it (i-te-rate) and pick by ear&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;WAV header&lt;/td&gt;
&lt;td&gt;A click at the start&lt;/td&gt;
&lt;td&gt;Unary responses are complete WAV files; don't add another header&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;div class="postscript" role="note"&gt;
&lt;p&gt;All numbers in this post come from this one voiceover. Each variant was generated only 4–10 times, so these are directional observations, not statistics. &amp;quot;Read in Mandarin&amp;quot; was judged by a transcription model that we first checked on known Cantonese and known Mandarin samples; accent was judged by ear.&lt;/p&gt;
&lt;/div&gt;
</content>
    <category term="TTS"/>
    <category term="Gemini"/>
    <category term="Cantonese"/>
  </entry>
  <entry>
    <title>95 Minutes to 14: Cold Compile Optimization for Hy4 on TPU v7</title>
    <link href="https://blog.maxwell-x.dev/en/hy4-cold-compile/"/>
    <id>https://blog.maxwell-x.dev/en/hy4-cold-compile/</id>
    <published>2026-10-01T00:00:00Z</published>
    <updated>2026-10-09T00:00:00Z</updated>
    <summary>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.</summary>
    <content type="html" xml:base="https://blog.maxwell-x.dev/en/hy4-cold-compile/">&lt;div class="tldr" role="note"&gt;
&lt;p&gt;&lt;strong&gt;TL;DR&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Problem&lt;/strong&gt;: 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.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cause&lt;/strong&gt;: 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.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Solution&lt;/strong&gt;: switch the chunk loop to &lt;code&gt;fori_loop&lt;/code&gt;, make the attention sink a runtime input, replay compiled artifacts between ranks, and add several compile-time optimizations.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Gain&lt;/strong&gt;: 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 &amp;quot;bucket splitting + replay&amp;quot; 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.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;figure&gt;
  &lt;div class="chart" role="img" aria-label="Cold compile time falling from 95.1 minutes to about 14 minutes"&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Before&lt;small&gt;mnbt 2048&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill base" style="width:calc((100% - 5.5em) * 1.0000)"&gt;&lt;/span&gt;&lt;span class="val"&gt;95.1&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;fori + sink as input&lt;small&gt;mnbt 8192&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.5499)"&gt;&lt;/span&gt;&lt;span class="val"&gt;52.3&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;+ bitwise index / shared ops&lt;small&gt;mnbt 8192&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.3018)"&gt;&lt;/span&gt;&lt;span class="val"&gt;28.7&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;+ dispatcher / CPU / rotation&lt;small&gt;mnbt 8192 · 3 runs&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.2250)"&gt;&lt;/span&gt;&lt;span class="val"&gt;21.4&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;+ cross-rank replay&lt;small&gt;mnbt 8192 · 3 runs&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.1614)"&gt;&lt;/span&gt;&lt;span class="val"&gt;15.35&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;After&lt;small&gt;mnbt 2048 · 2 runs&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill" style="width:calc((100% - 5.5em) * 0.1441)"&gt;&lt;/span&gt;&lt;span class="val"&gt;13.7–14.0&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="legend"&gt;&lt;span&gt;&lt;i style="background:var(--ink-2)"&gt;&lt;/i&gt;Before&lt;/span&gt;&lt;span&gt;&lt;i style="background:repeating-linear-gradient(135deg,var(--accent-2) 0 4px,transparent 4px 7px);border:1px solid var(--accent-2)"&gt;&lt;/i&gt;Intermediate steps&lt;/span&gt;&lt;span&gt;&lt;i style="background:var(--accent)"&gt;&lt;/i&gt;After&lt;/span&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;figcaption&gt;Cold compile time in minutes with an empty cache, from pod creation to service ready; single measurement unless noted. The intermediate steps were measured at mnbt 8192 and the first and last rows at mnbt 2048, so rows cannot be subtracted from each other directly: the same image went from 21.4 minutes at 8192 to 18.3 minutes at 2048. The 52.3 run was timed by /health and the others by the service-ready time in the logs, a slightly different method.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;h2 id="background"&gt;Background&lt;a class="hd-a" href="#background" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;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 &amp;quot;inference&amp;quot;.&lt;/p&gt;
&lt;h2 id="problem-analysis-where-the-time-goes"&gt;Problem analysis: where the time goes&lt;a class="hd-a" href="#problem-analysis-where-the-time-goes" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;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%.&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
    &lt;tr&gt;&lt;th&gt;Cost item&lt;/th&gt;&lt;th&gt;Mechanism&lt;/th&gt;&lt;th&gt;Magnitude&lt;/th&gt;&lt;th&gt;Evidence&lt;/th&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td&gt;Unrolled sparse MLA chunk loop&lt;/td&gt;&lt;td&gt;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&lt;/td&gt;&lt;td&gt;74–93% of each worker's compile work (78 layers, mnbt 8192)&lt;/td&gt;&lt;td&gt;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&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td&gt;Attention sink as a closure constant&lt;/td&gt;&lt;td&gt;The kernel writes this rank's attention sink into the program as a closure constant, so the program fingerprint differs by rank&lt;/td&gt;&lt;td&gt;12–14 programs under the same shape key; on each host, 7 of the 8 are redundant&lt;/td&gt;&lt;td&gt;Counting program files in the cache directory and comparing their contents with strings&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td&gt;Critical path outside compilation&lt;/td&gt;&lt;td&gt;Weight loading, profile run, KV initialization, draft model, speculative decoding warmup&lt;/td&gt;&lt;td&gt;6–7 minutes&lt;/td&gt;&lt;td&gt;Production logs&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;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).&lt;/p&gt;
&lt;h2 id="solution"&gt;Solution&lt;a class="hd-a" href="#solution" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;h3 id="1-switch-the-chunk-loop-to-fori_loop"&gt;1. Switch the chunk loop to fori_loop&lt;a class="hd-a" href="#1-switch-the-chunk-loop-to-fori_loop" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;&lt;b&gt;Problem.&lt;/b&gt; The unrolled Python loop makes program length proportional to T/64, so compile work balloons for large buckets.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Approach.&lt;/b&gt; Switch to &lt;code&gt;fori_loop&lt;/code&gt;, 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.&lt;/p&gt;
&lt;h3 id="2-make-the-attention-sink-a-runtime-input"&gt;2. Make the attention sink a runtime input&lt;a class="hd-a" href="#2-make-the-attention-sink-a-runtime-input" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;&lt;b&gt;Problem.&lt;/b&gt; 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.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Approach.&lt;/b&gt; Pass the attention sink into the kernel as a tensor input.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Effect.&lt;/b&gt; 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.&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;h3 id="3-replay-compiled-artifacts-between-ranks"&gt;3. Replay compiled artifacts between ranks&lt;a class="hd-a" href="#3-replay-compiled-artifacts-between-ranks" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;&lt;b&gt;Problem.&lt;/b&gt; 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.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Approach.&lt;/b&gt; 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.&lt;/p&gt;
&lt;figure&gt;
  &lt;div class="chart" role="img" aria-label="Effect of bucket splitting and replay: 30.2, 18.3 and 14.3 minutes"&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Splitting / replay all off&lt;small&gt;parallel precompile off&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill base" style="width:calc((100% - 5.5em) * 1.0000)"&gt;&lt;/span&gt;&lt;span class="val"&gt;30.2&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Splitting only&lt;small&gt;no replay&lt;/small&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill alt" style="width:calc((100% - 5.5em) * 0.6060)"&gt;&lt;/span&gt;&lt;span class="val"&gt;18.3&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row"&gt;&lt;div class="lab"&gt;Splitting + replay&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill" style="width:calc((100% - 5.5em) * 0.4735)"&gt;&lt;/span&gt;&lt;span class="val"&gt;14.3&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;figcaption&gt;Hy4 cold compile time in minutes, mnbt 2048, one run each. The three rows are not the same image, so read only the magnitude and avoid computing exact differences. The first row turns off the parallel precompile switch, which disables bucket splitting, rotation and replay together, and every rank compiles every bucket on its own.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Two points need attention when using replay:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;b&gt;The graph fingerprint does not cover closure constants.&lt;/b&gt; 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.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Change the cache root when rolling back.&lt;/b&gt; 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.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="4-other-compile-time-optimizations"&gt;4. Other compile-time optimizations&lt;a class="hd-a" href="#4-other-compile-time-optimizations" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;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.&lt;/li&gt;
&lt;li&gt;Share the streamidx op across layers as well; remove shapes the rejection sampler never uses; use &lt;code&gt;--kv-cache-memory-bytes&lt;/code&gt; to 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.&lt;/li&gt;
&lt;li&gt;Change the dispatcher to a single &lt;code&gt;switch&lt;/code&gt;; 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.&lt;/li&gt;
&lt;li&gt;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 &lt;code&gt;compute_selected_logits&lt;/code&gt;, 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).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;h2 id="gains"&gt;Gains&lt;a class="hd-a" href="#gains" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;h3 id="hy4"&gt;Hy4&lt;a class="hd-a" href="#hy4" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;p&gt;The remaining 14 minutes break down as follows:&lt;/p&gt;
&lt;figure&gt;
  &lt;div class="chart" role="img" aria-label="Breakdown of an 856 s cold compile"&gt;
    &lt;div class="stack"&gt;&lt;span class="seg c1" style="flex:143" title="Pod startup + weight loading: 143 s"&gt;143&lt;/span&gt;&lt;span class="seg c2" style="flex:66" title="Dynamo tracing: 66 s"&gt;66&lt;/span&gt;&lt;span class="seg c3" style="flex:313" title="First compile of the largest bucket: 313 s"&gt;313&lt;/span&gt;&lt;span class="seg c4" style="flex:85" title="Replay of remaining buckets + sync: 85 s"&gt;85&lt;/span&gt;&lt;span class="seg c5" style="flex:249" title="Sampling / draft / speculative warmup: 249 s"&gt;249&lt;/span&gt;&lt;/div&gt;
    &lt;div class="legend"&gt;&lt;span&gt;&lt;i class="c1"&gt;&lt;/i&gt;Pod startup + weight loading 143 s&lt;/span&gt;&lt;span&gt;&lt;i class="c2"&gt;&lt;/i&gt;Dynamo tracing 66 s&lt;/span&gt;&lt;span&gt;&lt;i class="c3"&gt;&lt;/i&gt;First compile of the largest bucket 313 s&lt;/span&gt;&lt;span&gt;&lt;i class="c4"&gt;&lt;/i&gt;Replay of remaining buckets + sync 85 s&lt;/span&gt;&lt;span&gt;&lt;i class="c5"&gt;&lt;/i&gt;Sampling / draft / speculative warmup 249 s&lt;/span&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;figcaption&gt;Breakdown of one 856 s cold compile in seconds, single measurement. The first compile of the largest bucket covers the compile time of the other buckets. The last segment is mainly MTP speculative decoding warmup and small sampling-related graphs, and varies a lot by model: about 4 s on Qwen3.5 and about 118 s on GLM-5.3.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;h3 id="comparison-across-three-models"&gt;Comparison across three models&lt;a class="hd-a" href="#comparison-across-three-models" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;We also tested the same approach on GLM-5.3 and Qwen3.5. Two caveats. First, besides the compile-related changes, the &amp;quot;original recipe&amp;quot; and &amp;quot;optimized&amp;quot; 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.&lt;/p&gt;
&lt;figure&gt;
  &lt;div class="chart" role="img" aria-label="Cold compile time for three models at three mnbt values, original recipe vs optimized"&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;Hy4&lt;small&gt;mnbt 2048&lt;/small&gt;&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 1.0000)"&gt;&lt;/span&gt;&lt;span class="val"&gt;95.1&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.1451)"&gt;&lt;/span&gt;&lt;span class="val"&gt;13.8&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;Hy4&lt;small&gt;mnbt 4096&lt;/small&gt;&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="tag oom"&gt;HBM OOM&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.1472)"&gt;&lt;/span&gt;&lt;span class="val"&gt;14.0&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;Hy4&lt;small&gt;mnbt 8192&lt;/small&gt;&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="tag na"&gt;not tested&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.1598)"&gt;&lt;/span&gt;&lt;span class="val"&gt;15.2&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;GLM-5.3&lt;small&gt;mnbt 2048&lt;/small&gt;&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.6151)"&gt;&lt;/span&gt;&lt;span class="val"&gt;58.5&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.0715)"&gt;&lt;/span&gt;&lt;span class="val"&gt;6.8&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;GLM-5.3&lt;small&gt;mnbt 4096&lt;/small&gt;&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.6730)"&gt;&lt;/span&gt;&lt;span class="val"&gt;64.0&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.0768)"&gt;&lt;/span&gt;&lt;span class="val"&gt;7.3&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;GLM-5.3&lt;small&gt;mnbt 8192&lt;/small&gt;&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="tag oom"&gt;HBM OOM&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.0862)"&gt;&lt;/span&gt;&lt;span class="val"&gt;8.2&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;Qwen3.5&lt;small&gt;mnbt 2048&lt;/small&gt;&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.2292)"&gt;&lt;/span&gt;&lt;span class="val"&gt;21.8&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.1735)"&gt;&lt;/span&gt;&lt;span class="val"&gt;16.5&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;Qwen3.5&lt;small&gt;mnbt 4096&lt;/small&gt;&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="fill base thin" style="width:calc((100% - 5.5em) * 0.2534)"&gt;&lt;/span&gt;&lt;span class="val"&gt;24.1&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.1861)"&gt;&lt;/span&gt;&lt;span class="val"&gt;17.7&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="row pair"&gt;&lt;div class="lab"&gt;Qwen3.5&lt;small&gt;mnbt 8192&lt;/small&gt;&lt;/div&gt;&lt;div&gt;&lt;div class="track"&gt;&lt;span class="tag oom"&gt;HBM OOM&lt;/span&gt;&lt;/div&gt;&lt;div class="track"&gt;&lt;span class="fill thin" style="width:calc((100% - 5.5em) * 0.2050)"&gt;&lt;/span&gt;&lt;span class="val"&gt;19.5&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;div class="legend"&gt;&lt;span&gt;&lt;i style="background:var(--ink-2)"&gt;&lt;/i&gt;Original recipe&lt;/span&gt;&lt;span&gt;&lt;i style="background:var(--accent)"&gt;&lt;/i&gt;Optimized&lt;/span&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;figcaption&gt;Cold compile time in minutes, empty cache and a single measurement per cell, on the same scale as the first chart in this post.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;ul&gt;
&lt;li&gt;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.&lt;/li&gt;
&lt;li&gt;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).&lt;/li&gt;
&lt;li&gt;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).&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="accuracy-and-performance"&gt;Accuracy and performance&lt;a class="hd-a" href="#accuracy-and-performance" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;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%.&lt;/p&gt;
&lt;h2 id="validation-before-production"&gt;Validation before production&lt;a class="hd-a" href="#validation-before-production" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;div class="tw"&gt;&lt;table&gt;
    &lt;tr&gt;&lt;th&gt;Issue&lt;/th&gt;&lt;th&gt;Consequence&lt;/th&gt;&lt;th&gt;Fix&lt;/th&gt;&lt;th&gt;Verification&lt;/th&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td&gt;Some ranks missing compiled artifacts&lt;/td&gt;&lt;td&gt;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)&lt;/td&gt;&lt;td&gt;Each rank's artifact load result is first put to an all_reduce vote on CPU: either all ranks load, or all ranks recompile&lt;/td&gt;&lt;td&gt;CoreHalt 1 → 0, ready in 445 s&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td&gt;First failure in speculative decoding warmup&lt;/td&gt;&lt;td&gt;Only on cold compile, once per rank, with the error &lt;code&gt;does not support dynamic shape&lt;/code&gt;, taking the single-rank retry path&lt;/td&gt;&lt;td&gt;The draft model's positions tensor was passed into a statically compiled function while carrying a dynamic-dim mark; it now passes &lt;code&gt;positions.view_as(positions)&lt;/code&gt;&lt;/td&gt;&lt;td&gt;First failures 16 → 0&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td&gt;Speculative decoding combined with logprobs / seed / prompt_logprobs&lt;/td&gt;&lt;td&gt;logprobs crashed EngineCore; seed returned an empty 500; prompt_logprobs silently returned [None]&lt;/td&gt;&lt;td&gt;Rejected at the request entry point with a 400&lt;/td&gt;&lt;td&gt;—&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td&gt;Compile cache grew by about 3.8 GB per restart&lt;/td&gt;&lt;td&gt;AOTAutogradCache entries for small graphs were written every time but never read (from reading code)&lt;/td&gt;&lt;td&gt;Skip the local save for small graphs in all processes&lt;/td&gt;&lt;td&gt;New files in the aotautograd cache directory during cold compile, warm start and serving: 3000+ → 0&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td&gt;"No compiles while serving" could not be verified&lt;/td&gt;&lt;td&gt;Runtime recompiles are not logged by default&lt;/td&gt;&lt;td&gt;Count newly written programs in the cache directory instead&lt;/td&gt;&lt;td&gt;First pass of traffic: 1537 new programs; second pass: 17 new&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;h2 id="later-developments"&gt;Later developments&lt;a class="hd-a" href="#later-developments" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;The main data in this post is as of October 1. Since then there have been two changes related to cold compile:&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Sequence parallelism in mixed steps pushed cold compile back up.&lt;/b&gt; 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:&lt;/p&gt;
&lt;p&gt;&lt;a href="/en/hy4-cold-compile-sp/"&gt;Cold Compile Optimization, Part 3: Cross-Rank Reuse for Sequence-Parallel Buckets, 48 Minutes to 17.7&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Cold compile for data-parallel deployments.&lt;/b&gt; 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:&lt;/p&gt;
&lt;p&gt;&lt;a href="/en/hy4-cold-compile-dp/"&gt;Cold Compile Optimization, Part 2: Cross-DP Compile Reuse for Data-Parallel Deployments on TPU&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;h2 id="where-this-applies"&gt;Where this applies&lt;a class="hd-a" href="#where-this-applies" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;The methods in this post apply to deploying models with custom Pallas kernels on TPU with vllm-torchtpu, especially:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Models with custom attention kernels such as sparse MLA&lt;/strong&gt;: 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.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Tensor-parallel deployments&lt;/strong&gt;: 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.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Multi-rank startup flows&lt;/strong&gt;: 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.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="limitations"&gt;Limitations&lt;a class="hd-a" href="#limitations" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Most cold compile times were measured only once; the final version was measured twice.&lt;/li&gt;
&lt;li&gt;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.&lt;/li&gt;
&lt;li&gt;The replay-off control was run only once each on Hy4 and GLM-5.3.&lt;/li&gt;
&lt;li&gt;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.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="series"&gt;Series&lt;a class="hd-a" href="#series" aria-label="Copy link to this section"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Overview: &lt;a href="/en/hy4-on-tpu-v7/"&gt;Beating B200 from Scratch: Porting and Optimizing Hy4 Inference on TPU v7&lt;/a&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href="/en/hy4-tpu-vs-b200/"&gt;From 2 tok/s to Beating B200: Optimizing Hy4 Inference on TPU v7&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-weight-loading/"&gt;Hy4 Weight Loading on TPU v7: From 857 Seconds to 68&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-cold-compile/"&gt;95 Minutes to 14: Cold Compile Optimization for Hy4 on TPU v7&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-cold-compile-dp/"&gt;Cold Compile Optimization, Part 2: Cross-DP Compile Reuse for Data-Parallel Deployments on TPU&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/en/hy4-cold-compile-sp/"&gt;Cold Compile Optimization, Part 3: Cross-Rank Reuse for Sequence-Parallel Buckets, 48 Minutes to 17.7&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="postscript" role="note"&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;/div&gt;
</content>
    <category term="TPU"/>
    <category term="vLLM"/>
    <category term="XLA"/>
    <category term="Compilation"/>
  </entry>
</feed>
