DEV Community

Cover image for vLLM and SGLang on TPU: Production Serving with llm-d 1.0
Omotayo Aina for Google Developer Experts

Posted on Edited on

vLLM and SGLang on TPU: Production Serving with llm-d 1.0

Multi-chip parallelism, KV layouts, speculative decoding and disaggregated KV transfer with vLLM-TorchTPU, SGLang-TorchTPU, TPU Sync and llm-d 1.0

Series: A five-part, hands-on series for PyTorch engineers moving real workloads onto Cloud TPU v6e (Trillium) and v7x (Ironwood) with TorchTPU. Part 1 builds the mental model (execution modes, memory, profiling, kernels). Part 2 runs Hugging Face Transformers v5 and Diffusers natively. Part 3 serves models in production with vLLM-TorchTPU, SGLang-TorchTPU and llm-d. Part 4 trains and post-trains at pod scale with TorchTitan, Ray and GRPO. Part 5 hands the whole workflow to the TPU Agent Suite. This is Part 3. Other parts: Part 1: TorchTPU Performance: Execution Modes, XProf and Pallas Kernels, Part 2: Hugging Face on TPU: Transformers v5, MoE Kernels and Diffusers, Part 4: TorchTitan on Cloud TPU: SimpleFSDP, Graph Trainer, Ray and GRPO, Part 5: TPU Agent Suite: Onboard, Profile and Tune PyTorch on Cloud TPU.

The problem: an agent fleet on one endpoint

You have vllm serve answering on a TPU v7x host and a coding agent hammering it. The first request of each session takes seconds, because it carries a 3,000-token system prompt, tool schemas and a repository index. Every later turn resends all of that plus the last tool output. When a 100k-token prompt lands, every decoding stream on that engine stutters while the prefill runs. A restart costs you a long compile. And the KV cache fills HBM long before the weights do.

None of these are TPU bugs. They are the four questions every production serving deployment answers, on any accelerator: how to lay the model out across chips, where the KV cache lives and in what shape, how to keep prefill from stalling decode, and how to route traffic so cached prefixes get reused. This post answers them for TPU with the two PyTorch-native engines released on October 20, 2026 (vLLM-TorchTPU and SGLang-TorchTPU), the C++ transfer library TPU Sync (Raiden in the code), and llm-d 1.0 on GKE.

What you'll be able to do after this post:

  • Explain where the TPU plugin sits under an unmodified vLLM or SGLang engine, and why every step is padded to a static bucket.
  • Configure cold-start compilation (TPU_PARALLEL_PRECOMPILE, TPU_PRECOMPILE_PEER_REPLAY, the Tier-3 cache) and predict how many graphs a given --max-num-batched-tokens compiles.
  • Decide between TP, DP + EP, PCP and DCP for a model and slice, and diagnose whether a phase is compute-bound or bandwidth-bound.
  • Compare the token-major, block-major and SEQ_ALONG_LANE KV layouts and pick one from the head count and dtype.
  • Build an asymmetric prefill/decode deployment over TPU Sync and package it on GKE with DisaggregatedSet, InferencePool, InferenceObjective and an EndpointPickerConfig.
  • Measure TTFT, TPOT and prefix-cache reuse from a multi-turn tool-calling client, and gate a rollout on CPU-vs-TPU numerical parity.

Everything below has a runnable counterpart in code/sample_02_vllm_sglang_agentic_serving_and_raiden.py. Its CPU path needs no TPU:

python code/sample_02_vllm_sglang_agentic_serving_and_raiden.py --cpu-smoke
python -m pytest tests/test_sample_02.py -q        # 33 passed
Enter fullscreen mode Exit fullscreen mode

The smoke run reimplements the engines' bucket and KV-layout arithmetic, builds and validates every launch profile, emits and parses the GKE manifests, starts a small OpenAI-compatible mock server with a simulated prefix cache, runs the agent client against it, and runs the parity gate. On a TPU VM the same client and parity gate point at the real server.

Mental model: a TPU plugin under an unmodified engine

Both engines are out-of-tree platform plugins. The scheduler, the KV cache manager, the OpenAI-compatible API server and the model definitions are upstream code. The plugin supplies what each engine asks every hardware platform for: an attention backend, KV cache pools, MoE kernels and a way to run the compiled model.

Stack diagram: the upstream engine's OpenAI API and Scheduler feed the TPU Plugin, which pads each step to a bucket, runs a compiled graph and Pallas kernels, and reads and writes the KV cache in TPU HBM.
Only the bottom half is TPU-specific: bucket padding, the compiled graph, Pallas kernels and the KV pools.

vLLM-TorchTPU. pip install vllm-torchtpu registers TpuPlatform through the vllm.platform_plugins entry point (Python 3.12 on a Cloud TPU VM). Each TPU device gets its own worker process, exactly as each GPU does, and collectives go through torch.distributed. The model runs under torch.compile(backend="tpu"), which lowers to XLA. Attention, MoE and quantized matmuls are JAX/Pallas kernels registered as custom ops that Dynamo treats as opaque calls. TPU-specific behavior is installed by src/vllm_torchtpu/patch_registry.py, which applies ordered, process-local patches at five lifecycle stages: import, platform_activation, engine_core, worker_init and model_load. Spawned processes start with an empty registry, which is why most patches are registered for both platform_activation and worker_init.

SGLang-TorchTPU. Installing sglang-tpu registers a platform through the sglang.srt.platforms entry point named tpu_oot, and SGLANG_PLATFORM=tpu_oot selects it. The class behind it, TpuOOTPlatform in sglang_tpu/platform.py, subclasses the in-tree TpuSRTPlatform and defers backend initialization until the worker bootstrap. Three SGLang details matter in production:

  • Host-side page bookkeeping. TpuPagedTokenToKVPoolAllocator keeps free pages on the CPU. Under overlap scheduling, forward N can still be writing pages that a request finished at N-1 just freed, and a DMA (a HiCache load, or KV arriving on a P/D decode server) is not ordered against device compute. KVFreeFence (sglang_tpu/kv_free_fence.py) holds every freed page until the in-flight forwards that might write it are processed, so a missed case costs a device sync instead of corrupted KV.
  • Kernels lowered on the CPU. cpu_export_jax_op in sglang_tpu/pallas_jax_op.py exports a jax.jit Pallas kernel to StableHLO with JAX initialized CPU-only, then registers it as a torch.library custom op, so JAX never competes with TorchTPU for the TPU client.
  • Frozen after warmup. Once warmup finishes, TpuSRTPlatform calls torch.compiler.set_stance("fail_on_recompile"). A shape you did not warm up becomes an error instead of a silent stall (it leaves recompiles on for speculative decoding when SGLANG_TPU_ALLOW_SPEC_RECOMPILE is set).

Static buckets: why the first startup is slow, and how to make the second one fast

There is no CUDA-graph capture on TPU. Instead the runner pads every step to one of a fixed set of shapes, compiles each shape once, and dispatches later steps to the cached program. In vLLM-TorchTPU the token buckets come from _get_token_paddings in platforms/tpu_platform.py: sizes double from 16, and the last bucket is exactly --max-num-batched-tokens rather than the next power of two.

Predict, then check. The Qwen3.5-397B-A17B-FP8 recipe on a v7x host passes --max-num-batched-tokens 1024. How many token buckets does that compile? Write your guess down, then:

from sample_02_vllm_sglang_agentic_serving_and_raiden import token_buckets, padded_len, request_buckets

b = token_buckets(1024)          # mirrors _get_token_paddings (min 16, capped at the budget)
print(len(b), b)                 # 7 [16, 32, 64, 128, 256, 512, 1024]
print(padded_len(b, 300))        # 512: a 300-token step runs the 512 program
print(request_buckets(64))       # [8, 16, 32, 64]: request-count paddings (MIN_NUM_SEQS = 8)
Enter fullscreen mode Exit fullscreen mode

Step chart of the padded step size against tokens scheduled, log scale, with seven buckets from 16 to 1024 and the padding area shaded.
Each step jumps to the next compiled bucket. The shaded area is padding work the TPU does for nothing, worst just above a power of two.

Two consequences. A bigger token budget adds buckets and compile time, and each compiled program stays resident in HBM. And padding waste is worst just past a boundary: 257 tokens run the 512 program. TPU_TOKEN_BUCKET_EXTRA adds specific sizes and TPU_TOKEN_BUCKET_LINEAR adds linearly spaced buckets for long prompts. In CI, set VLLM_XLA_CHECK_RECOMPILATION=1: it watermarks torch.tpu._get_cache_stats() at every precompiled bucket and step and logs any graph compiled during serving. Keep it at 0 in production.

Cold start on a multi-rank host. With TPU_PARALLEL_PRECOMPILE=1, ranks compile buckets in parallel. Add TPU_PRECOMPILE_PEER_REPLAY=1 and each bucket is compiled by exactly one rank of the host and replayed by the others from vLLM's compile cache. The owner assignment in _patch_vllm_compile_all_ranges (src/vllm_torchtpu/__init__.py) sorts buckets biggest first and deals them in a snake, so rank 0 starts on the longest compile and a rank whose first bucket was small gets the next one:

from sample_02_vllm_sglang_agentic_serving_and_raiden import snake_deal
snake_deal(token_buckets(8192), ranks=8)
# {0: [8192], 1: [4096], 2: [2048], 3: [1024], 4: [512], 5: [256], 6: [128, 16], 7: [64, 32]}
Enter fullscreen mode Exit fullscreen mode

Grid of 8 ranks by 10 token buckets, each bucket compiled by exactly one rank and replayed by the other seven.
Eight ranks, ten buckets, ten compiles instead of eighty. The snake hands ranks 6 and 7 two small buckets each.

Peer replay needs the compile cache: startup fails if VLLM_DISABLE_COMPILE_CACHE=1. A waiting rank gives up after TPU_PRECOMPILE_PEER_WAIT_S (default 600 s) and compiles the bucket itself. The envs.py comment sizes that default against the biggest Qwen3.5-397B range at DP8, about 165 s with every rank of the host compiling. Persist both caches across restarts: TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT holds the native PJRT executables and VLLM_CACHE_ROOT holds vLLM's Dynamo and AOT artifacts. They are independent roots. On GKE, mount them on persistent storage, but keep /cache/jax/vllm/profile_cache on an in-memory emptyDir, as the repo's JobSet manifest does, so the free-HBM probe runs fresh at every start.

SGLang takes the ladders explicitly: --tpu-compile-tokens 128 256 512 1024 2048 4096 and --tpu-compile-bs 1 2 4 8 16 32 64, with --enable-torch-compile.

Choosing a parallelism layout

vLLM-TorchTPU supports all six of vLLM's parallelism dimensions, single-host and multi-host, and they compose:

Dimension Flag What it splits Collective it adds
TP --tensor-parallel-size attention heads, dense MLP all-reduce or reduce-scatter per layer
DP --data-parallel-size requests; attention replicated per rank none for attention at TP=1
EP --enable-expert-parallel MoE experts over the TP * DP mesh all-to-all dispatch and combine
PP --pipeline-parallel-size layers into stages point-to-point activations (TPU_PP_HANDOFF=wave or ring)
PCP --prefill-context-parallel-size each prefill chunk's tokens ring attention between adjacent chips
DCP --decode-context-parallel-size KV pages along the sequence LSE merge (TPU_DCP_LSE_MERGE_A2A for small steps)

Count devices first. An engine group consumes DP * TP * PP * PCP logical devices. On v7x every chip exposes two TensorCore devices of 96 GB each, so a tpu7x 2x2x1 host (4 chips) has 8 devices and 768 GB of HBM. A v6e chip is one device with 32 GB, so v6e-8 has 256 GB.

Then decide where the collectives go. For large MoE models the vLLM team reports the best throughput from data-parallel attention plus expert parallelism, for example DP=8, TP=1 with EP on one v7x host:

Two panels. TP=8: Attention TP=8, then All-Reduce, then MoE TP=8. DP=8 + EP: Local Attention, then All-to-All, then Experts per Device.
Under TP=8 every attention layer ends in an 8-way all-reduce. Under DP=8 + EP attention stays on its device and only the MoE layer crosses chips.

Attention stays chip-local, and every device holds num_experts / (TP * DP) experts, so HBM goes to weights and KV instead of replicated expert slices. When per-request latency matters more than aggregate throughput, TP=2, DP=4 puts the two halves of each tensor-parallel group on the two cores of one physical chip: llm-d's GKE TPU provider page notes the die-to-die link inside a v7x chip is about 6x faster than the ICI between neighboring chips.

The sample encodes these rules in recommend_layout(). A worked example:

from sample_02_vllm_sglang_agentic_serving_and_raiden import MODELS, recommend_layout

m = MODELS["qwen3.5-397b-a17b-fp8"]            # 397B total, 17B active, ~397 GB in FP8
for wl in ("throughput", "interactive", "prefill_pool"):
    d = recommend_layout(m, "v7x-8", wl)
    print(wl, d.layout.short(), d.layout.vllm_args())
# throughput   TP=1, DP=8, EP    ['--tensor-parallel-size', '1', '--data-parallel-size', '8', '--enable-expert-parallel']
# interactive  TP=2, DP=4, EP    [...]
# prefill_pool TP=2, PCP=4, EP   ['--tensor-parallel-size', '2', '--prefill-context-parallel-size', '4', '--enable-expert-parallel']
recommend_layout(m, "v6e-8")   # ValueError: 397 GB of fp8 weights does not fit v6e-8 (256 GB HBM ...)
Enter fullscreen mode Exit fullscreen mode

The three outputs match the repo's validated configurations: qwen3.5-397b-fp8-tp1-dp8-ep.sh for throughput, the --tensor-parallel-size 2 --data-parallel-size 4 alternative "for lower per-request latency at smaller concurrencies", and the PCP=4, TP=2 prefill layout the launch post uses for disaggregation. The v6e-8 failure matches the v6e recipe table, which puts this model on v6e-16 (512 GB) with TP=16 or DP=2, TP=8 + EP.

Use X when:

Use When Watch out for
TP=N dense model, one stream must be fast, weights need several devices an all-reduce per layer; cap TP at the KV head count or heads get replicated
DP=N, TP=1 + EP large MoE, throughput first (v7x recipes for Qwen3.5-397B, DeepSeek-V4-Flash, GLM-5.2) each rank holds the dense layers; every DP rank steps in EP lockstep
TP=2, DP=N/2 + EP MoE on v7x, lower latency at low concurrency TP=2 should be the two cores of one chip
PCP long prompts where TTFT matters, and prefill pools MoE with PCP requires EP; TPU_PCP_TOPOLOGY_AWARE_MESH=1 (default) keeps ring neighbors adjacent
DCP long-context decode where one rank's KV does not fit an LSE merge per attention layer
PP model too large for one slice's TP group bubbles; TPU_PP_HANDOFF=ring (libtpu 0.0.50+, torch_tpu 0.2.0+) helps mixed prompt lengths; on v7x set VLLM_TPU_DEVICE_ORDER so a two-core stage does not bind both cores of one chip

MoE layers have their own knobs in src/vllm_torchtpu/envs.py: USE_MOE_SPARSE_CORE=1 (default) moves token permutation and the ragged gather/reduce (ragged_gather_reduce_v2) onto the SparseCores. USE_MOE_FUSED_EP_KERNEL=1 with MOE_FUSED_EP_KERNEL_IMPL=v2 runs top-k, dispatch, both grouped matmuls, combine and the cross-rank transport as one SPMD Pallas program. TPU_MOE_HIERARCHICAL_EP=1 runs EP between chips and TP between the two cores of a chip. When you A/B two layouts, follow the repo's own rule P-4 in the optimization guide: compare at matched global token budget, because DP with a per-rank budget times N ranks is a different experiment from TP at the same total.

Prefill or decode: which one is your bottleneck?

llm-d's disaggregation docs state it plainly: prefill is FLOPs-bound and decode is memory-bandwidth-bound. That is true for the usual shapes, and it is worth checking the arithmetic for your model, because a sparse MoE moves the boundary a long way.

A step reads every weight byte on the device at least once and does 2 * active_params * tokens / TP FLOPs. Divide the two and compare with the chip's ridge point. With TPU v7x at 2,307 FP8 TFLOPS and a practical 3,207 GB/s per device (the TPU Agent Suite's hardware-facts.md tells you to build rooflines on the practical figure, not the 3,686 GB/s theoretical one), the ridge is about 719 FLOPs per byte. For v6e at 1,836 FP8 TFLOPS and 1,638 GB/s it is about 1,121.

Log-log plot of FLOPs per weight byte against tokens per device per step for a dense 70B model on v6e-8 and a 397B-A17B MoE on v7x-8, with ridge lines at 1121 and 719 and the decode region shaded.
Decode steps (shaded) sit two to three orders of magnitude below either ridge. The sparse MoE needs roughly 4x more tokens per device than the dense model before a step stops waiting on HBM.

$ python code/sample_02_vllm_sglang_agentic_serving_and_raiden.py --cpu-smoke   (excerpt)
  roofline prefill TP=2, PCP=4, EP    intensity    175.3 FLOP/B (ridge 719) -> memory-bound
  roofline decode  TP=1, DP=8, EP     intensity      4.1 FLOP/B (ridge 719) -> memory-bound
  qwen3.5-397b-a17b-fp8  v7x-8: a step is compute-bound above ~2,100 tokens per device
  llama-3.3-70b          v6e-8: a step is compute-bound above ~560 tokens per device
Enter fullscreen mode Exit fullscreen mode

Read that output as an analyst. The decode step for 64 requests over 8 DP ranks is 8 tokens per device: intensity around 4, so decode time is the time to stream about 50 GB of expert weights plus the KV, and the MXUs mostly wait. More concurrent sequences per rank, an FP8 KV cache, and speculative decoding (more tokens verified per weight read) are the levers. A 2,048-token prefill chunk split over PCP=4 is 512 tokens per device: still weight-bound for this MoE, even though the same chunk would be compute-bound for a dense 70B. Prefill wants large chunks per device, so for a sparse MoE give the prefill pool fewer, bigger chunks and do not shrink them to protect decode latency. Separate the phases instead. That is what disaggregation buys you, and it is why the phase_roofline() and crossover_tokens() helpers are in the sample. They are a whiteboard model (weights plus KV bytes, no overlap, no collectives), not a benchmark: treat them as a way to ask the right question before you open an XProf trace.

KV cache layouts on (8, 128) tiles

A TPU vector register is 8 sublanes by 128 lanes, and the KV pool's shape decides how much of each tile is padding and how many DMAs a page transfer costs. Three layouts ship today.

Token-major (default). SGLang's TpuFusedMHATokenToKVPool (the pallas_tpu_rpa_v3 backend, Ragged Paged Attention v3) stores [num_blocks, page_size, num_kv_heads*2 // kv_packing, kv_packing, head_dim_padded]. K and V of each head are fused on one axis, packed 32 bits per lane (kv_packing is 4 for FP8 and 2 for BF16), and that axis is padded up to kv_packing. With one KV head per rank in FP8, the 2 real rows pad to 4.

Block-major. vLLM's BlockMajorPoolLayout (VLLM_TPU_BLOCK_MAJOR_KV=1) and SGLang's TpuBlockMajorMHATokenToKVPool (SGLANG_TPU_USE_BLOCK_MAJOR_KV=1) move the layer axis inside the block: [num_blocks, layer_num, page_size, ...]. All layers of one page form one contiguous HBM row, so a Raiden P/D transfer or offload moves a page in one DMA instead of one per layer. SGLang refuses it unless the backend is pallas_tpu_rpa_v3, there is no speculative decoding, P/D runs over raiden, HiCache uses the raiden I/O backend, and the model is not a hybrid linear-attention model. Both P/D servers must agree on it.

SEQ_ALONG_LANE. SGLANG_TPU_USE_SEQ_ALONG_LANE_KV=1 with --attention-backend pallas_tpu_rpa_batched allocates TpuSeqAlongLaneKVPool, which puts the token index on the 128-lane axis. The num_kv_heads * 2 axis is then a plain axis and is never padded. The env var's own comment in sglang_tpu/envs.py gives the result: at one KV head per rank with FP8 KV, 256 bytes per token per layer against 512. The kernel needs --page-size of at least 256. vLLM's --attention-backend CUSTOM (the batched RPA backend) reads both layouts too.

kv_bytes_per_token_per_layer() in the sample mirrors both pools' sizing methods, so you can check any shape before allocating:

Grouped bars of KV bytes per token per layer for token-major and SEQ_ALONG_LANE at 1, 2 and 4 KV heads per rank in FP8 and BF16; only 1 head in FP8 differs (512 vs 256). A second panel shows 1.30M vs 2.60M tokens of KV per device for a 40 GB budget and 60 layers.
The halving only happens where the fused layout pads: one KV head per rank in FP8. Right: what that means for an illustrative 60-layer model with 40 GB of KV budget per device.

This is an Analyze moment: the layout choice depends on heads per rank, which depends on your TP degree. A model with 8 KV heads at TP=8 has one head per rank and gains 2x. The same model at TP=1, DP=8 has 8 heads per rank and gains nothing. SGLang's Muse Spark AgentX recipe (benchmark/tpu/recipe/configs/muse_spark/agentic.py) uses exactly this pool, kv_cache_dtype="fp8_e4m3", page_size=256, pallas_tpu_rpa_batched, for its 1M-token context configuration, and switches to BF16 token-major KV at low concurrency.

KV layout Use when Not when
Token-major (RPA v3) default; any head count; speculative decoding; hybrid models you need one-DMA page transfers
Block-major P/D or offload over Raiden dominates; dense or MoE attention speculative decoding (SGLang), hybrid linear-attention models (SGLang)
SEQ_ALONG_LANE 1 KV head per rank and FP8 KV; long context or large batch page size under 256; BF16 at 1 head (no gain)

Quantization compounds with layout. On v6e, the recipes say to always pass --kv-cache-dtype fp8, which halves KV blocks per token on 32 GB chips. Weights use the --quantization path in layers/adapter/quantization/: FP8 (W8A8, with TPU_FP8_LINEAR_W8A16_MAX_ROWS keeping BF16 activations for small decode buckets on v7x), MXFP4 for gpt-oss, NVFP4 (loaded once into K-major float4_e2m1fn_x2 through the pallas::nvfp4_load_kmajor op), and W4A8 MoE via load-time requantization (MOE_REQUANTIZE_WEIGHT_DTYPE=fp4, MOE_FUSED_EP_ENABLE_W4A8=1).

Agentic traffic: prefix reuse, tool calls and structured output

Agents resend an ever-growing conversation. The cheapest token is the one you never prefill again. vLLM's automatic prefix caching and SGLang's RadixAttention keep reusable prefixes in HBM, and both engines extend this to hybrid models: vLLM caches linear-attention state along with the KV cache for Qwen3.5 and Kimi K3, and SGLang keeps Gated DeltaNet and Kimi Delta Attention state in TpuMambaPool so a radix hit restores the recurrent state too. In the llm-d TPU7x guides, the hybrid Qwen3.5 model runs with --mamba-cache-mode=align, TPU_VLLM_ENABLE_UNIFIED_BLOCK_POOL=1 and PYTHONHASHSEED=0 so block hashes match across engines.

MultiTurnAgenticClient drives /v1/chat/completions the way an agent does. Every request streams, so it measures TTFT (time to the first content or tool-call delta) and TPOT (time between the first and last token divided by tokens minus one), and it reads usage.prompt_tokens_details.cached_tokens (vLLM reports it with --enable-prompt-tokens-details). It also sends the llm-d routing headers on every request, which we will use on GKE:

from sample_02_vllm_sglang_agentic_serving_and_raiden import MultiTurnAgenticClient

client = MultiTurnAgenticClient("http://localhost:8000", "Qwen/Qwen3.5-35B-A3B-FP8",
                                objective="interactive-agent", fairness_id="agent-session-1",
                                slo_ttft_ms=2000, slo_tpot_ms=50)
report = client.run_planning_workflow(slice_name="v7x-8")
print(MultiTurnAgenticClient.format_metrics(report["metrics"]))
Enter fullscreen mode Exit fullscreen mode

The workflow is a TPU serving planner: three turns call tools that are real functions from the same module (lookup_tpu_slice, recommend_parallelism, kv_bytes_per_token), one turn is a plain follow-up, and the last asks for a plan under a JSON Schema response_format, validated client-side. Against the mock server in the smoke run:

turn  kind        TTFT ms  TPOT ms   E2E ms  prompt  cached  hit%
----  ----------  -------  -------  -------  ------  ------  ----
   1  tool_call      49.4     1.22     53.4     616       0     0
   1  answer          8.7     1.41     28.7     696     640    92
   2  tool_call       6.9     1.30     20.3     765     736    96
   2  answer         10.6     1.45     48.3     917     816    89
   3  tool_call       5.2     1.41     22.2     992     976    98
   3  answer          7.0     1.30     15.0    1068    1040    97
   4  answer          6.3     1.46     37.3    1102    1072    97
   5  json            6.4     1.36     23.0    1138    1120    98
final JSON plan: {"slice": "v7x-8", "layout": "TP=1, DP=8, EP", "kv_layout": "seq_along_lane", "bytes_per_token_per_layer": 256, "speculative_method": "mtp"}
first-request TTFT speedup vs turn 1: t1=1.0x, t2=7.1x, t3=9.4x, t4=7.9x, t5=7.7x
llm-d headers seen by server: ['x-llm-d-inference-fairness-id', 'x-llm-d-inference-objective', 'x-llm-d-slo-tpot-ms', 'x-llm-d-slo-ttft-ms']
Enter fullscreen mode Exit fullscreen mode

The mock charges prefill time only for the uncached suffix (16-token block hashes, the RadixAttention idea in miniature) and inserts each finished turn back into the cache, so the numbers are illustrative. The shape is what a real engine shows. Only the first request pays for the system prompt and tool schemas.

Animated bars for eight agent requests: the first is all orange (prefilled), later requests are mostly teal (cached prefix) with a small orange suffix, labeled with prompt tokens and hit rate.
Real cached-token counts from the mock run: after the first request, 89% to 98% of every prompt is a prefix hit.

One lesson fell out of building this client. The first version dropped the tools list on the final JSON turn. Chat templates render tools near the top of the prompt, so that changed the prefix and the final turn missed the cache entirely. The client now sends the same tool list on every request and sets tool_choice="none" when it wants a structured answer. Keep anything rendered early in the prompt byte-for-byte stable across turns.

On the server side, tool calling uses the usual vLLM flags (--enable-auto-tool-choice --tool-call-parser ...; the llm-d TPU7x guide uses --tool-call-parser=qwen3_coder and --reasoning-parser=qwen3 for Qwen3.5-397B), and structured outputs use the usual vLLM request parameters, which the launch post lists as supported. In SGLang-TorchTPU, structured output and function calling are listed as experimental at launch.

Speculative decoding: more tokens per weight read

Decode is bandwidth-bound, so verifying several drafted tokens in one target forward is close to free in FLOPs and directly divides the weight traffic per output token. vLLM-TorchTPU supports six methods through --speculative-config:

"method" Draft Notes from the speculative decoding guide
eagle3 EAGLE-3 checkpoint general chat, coding, reasoning
mtp built into Qwen3.5, DeepSeek-V3/R1, GLM-5 no separate draft model
dflash z-lab/*-DFlash-* block-diffusion draft, up to 16 tokens per pass (example: num_speculative_tokens: 15)
dspark deepseek-ai/dspark_*, Inferact/Kimi-K3-DSpark DFlash-style block plus a sequential Markov head
ngram, suffix none repetitive prompts, code edits, citations

DFlash and DSpark draft a whole block in one non-causal forward conditioned on the target's hidden states, and the target scores every position in one pass:

Animation of three speculative cycles: eight draft tokens, the target accepts the first few and rejects the rest, and the accepted tokens plus one target token are appended to the output.
Each target forward yields accepted + 1 tokens. The per-cycle pattern is illustrative around the 4.05-of-8 acceptance the SGLang Muse Spark recipe simulates for InferenceX.

Two TPU-specific details. For MTP with num_speculative_tokens of 2 or more, VLLM_TPU_FUSED_DRAFT_LOOP=1 compiles draft steps 1 to K-1 into one program, so the host dispatches once per proposal instead of twice per step. The envs.py TODO lists the cases that still take the per-step loop, including EP-DP lockstep, so it helps TP layouts more than DP=8 + EP. In SGLang, --speculative-algorithm takes EAGLE3, NEXTN (MTP), DFLASH or DSPARK. Host padding is unconditional there, and SGLANG_TPU_HOST_PADDING_NO_D2H (on by default) routes speculative batches to the experimental spec worker that keeps their metadata on the host as well.

Profile C in the sample builds either engine's configuration:

b = TpuServingProfileBuilder("vllm", "v7x-8", "qwen3.5-397b-a17b-fp8")
print(b.profile_c("mtp").to_shell())       # sets VLLM_TPU_FUSED_DRAFT_LOOP=1, method "mtp", K=3
print(b.profile_c("dflash").arg("--speculative-config"))
# {"method":"dflash","num_speculative_tokens":15,"model":"z-lab/Qwen3-8B-DFlash-b16"}
Enter fullscreen mode Exit fullscreen mode

Whole-decoder megakernels

At low concurrency even a well-fused graph pays per-kernel launch and HBM round trips between layers. Both engines ship Pallas megakernels that run the whole decode step as one kernel. Inferact's Kimi K3 megakernel in vLLM-TorchTPU serves more than 700 tokens per second to a single user on Ironwood, per Google's launch announcement. SGLang-TorchTPU has its own for Kimi K3, GLM-5.3-Flash and Muse Spark (SGLANG_TPU_MUSE_MEGAKERNEL=1, for decode and DFlash target-verify steps). The Muse recipe shows the trade-off in its comments: the megakernel caps a step at 32 rows (48 with its large-step program), so admission is held far below client concurrency, and it cannot run on a pipeline-parallel prefill because a single kernel cannot be staged.

Published headline numbers, with their sources:

Result Configuration Source
700+ tokens/s for a single user Kimi K3 (2.8T) megakernel, vLLM-TorchTPU, Ironwood Google Developers Blog launch post
2.01 cents per million tokens, lowest overall Qwen 3.5 397B-A17B, FP8, 8k/1k, TPU 7x with vLLM SemiAnalysis InferenceX, as reported in the same post
SOTA on AgentX (agentic multi-turn track) Qwen 3.5 397B on Ironwood same post; Ironwood "leads across most of the Pareto frontier"

The content plan for this post attributed the 2.01-cent result to the megakernel work. The source does not say that, so the table keeps them separate.

Moving the KV cache with TPU Sync (Raiden)

Two features move KV away from the device that computed it: tiered offload and prefill/decode disaggregation. Both have to overlap compute or they add straight to latency. TPU Sync is an open-source C++ library that reads the device buffers behind PyTorch tensors directly, so a transfer needs no extra host staging copy, and it runs transfers on its own threads outside Python. vLLM-TorchTPU uses it through vLLM's KV connector interface. SGLang-TorchTPU uses it as a disaggregation transfer backend (--disaggregation-transfer-backend raiden) and as the HiCache I/O backend (--hicache-io-backend raiden).

Tiered offload.

Three tiers left to right: TPU HBM, Host DRAM, Managed Lustre, with TPU Sync moving pages by DMA between HBM and DRAM, a write-through to Lustre, and a recall path back.
Tiers fill lowest latency first. A block found only on the filesystem is recalled through host staging blocks and then copied to HBM.

In vLLM the connector is TPURaidenOffloadingConnector (vllm_torchtpu.offload.raiden_connector, kv_role: kv_both), sized per engine by cpu_bytes_to_use. The llm-d tiered-prefix-cache guide runs 32 GiB per DP engine on v7x, 8 x 32 GiB = 256 GiB pinned per pod, and adds a filesystem tier by setting raiden_storage_path in kv_connector_extra_config (validated with Managed Lustre, single host). Storage keys are prefix-block hashes, so every pod must set PYTHONHASHSEED=0, and the engine refuses to start the tier without it. In SGLang, HiCache with write_back on Raiden adds a copy-ahead window (sglang_tpu/hicache_write_back_copy_ahead.py): it keeps the next eviction victims already copied to host, so an eviction does not stall the scheduler on a device sync plus a copy. SGLANG_TPU_HICACHE_WRITE_BACK_COPY_AHEAD_TOKENS sizes it (default four chunked-prefill chunks; 0 restores the synchronous policy).

Asymmetric disaggregation. The roofline told us prefill and decode want different shapes. Disaggregation gives each its own engine and layout, and TPU Sync reshards KV in flight between them. The launch post's example is prefill on PCP=4, TP=2 and decode on DP=8, TP=1:

Proxy sends to Prefill PCP=4 TP=2; KV pages flow through TPU Sync, which reshards them into Decode DP=8 TP=1; prefill also offloads to Host DRAM; a Raiden Controller coordinates TPU Sync.
The prefill engine is the KV producer, decode the consumer. The controller only coordinates metadata. Pages move by DMA.

The transfer is consumer-pull. As each chunked-prefill step commits its pages, the prefill side announces them and the decode side pulls that chunk while the next one computes. Only the last chunk is left to move when prefill finishes, and pages the decode already holds from its own prefix cache are never sent.

Animation of six prefill chunks computing left to right while a purple pull of the previous chunk runs one step behind, and decode-side page blocks accumulate; at the end only the last pull remains.
Transfer hides behind compute one chunk at a time. Without the overlap, all six pulls would land after the last chunk.

Profile D builds both engines' commands. The connector names are the ones tpu_platform.py registers with vLLM's KVConnectorFactory:

pf, dc = TpuServingProfileBuilder("vllm", "v7x-8", "qwen3.5-397b-a17b-fp8").profile_d(
    controller="raiden-controller:50055", host_offload_gib=64)
print(pf.to_shell()); print(dc.to_shell())
Enter fullscreen mode Exit fullscreen mode
# Profile D: prefill (kv_producer) (vllm, prefill, TP=2, PCP=4, EP)
export TPU_USE_RAIDEN_KV_CACHE_MANAGER=1
export TPU_RAIDEN_CONTROLLER_ADDRESS=raiden-controller:50055
export TPU_RAIDEN_RESHARD_IMPL=controller
export TPU_KV_RESHARD_TRANSPORT=raiden
export VLLM_TPU_BLOCK_MAJOR_KV=1
export PYTHONHASHSEED=0
export TPU_VLLM_ENABLE_UNIFIED_BLOCK_POOL=1
export TPU_RAIDEN_QWEN35_ADMISSION=1
export TPU_RAIDEN_JOB_NAME=prefill
export TPU_RAIDEN_ENGINE_ID=0
vllm serve Qwen/Qwen3.5-397B-A17B-FP8 \
  --tensor-parallel-size 2 \
  --prefill-context-parallel-size 4 \
  --enable-expert-parallel \
  --kv-cache-dtype fp8 \
  --block-size 256 \
  --attention-backend CUSTOM \
  --enable-prefix-caching \
  --port 8000 \
  --kv-transfer-config '{"kv_connector":"TPUMultiConnector","kv_connector_module_path":"vllm_torchtpu.distributed.kv_transfer.tpu_multi_connector","kv_role":"kv_producer","kv_connector_extra_config":{"connectors":[{"kv_connector":"TPURaidenConnector","kv_connector_module_path":"vllm_torchtpu.distributed.kv_transfer.tpu_connector","kv_role":"kv_producer"},{"kv_connector":"TPURaidenOffloadingConnector","kv_connector_module_path":"vllm_torchtpu.offload.raiden_connector","kv_role":"kv_both","kv_connector_extra_config":{"cpu_bytes_to_use":68719476736}}]}}'

# Profile D: decode (kv_consumer): same env with TPU_RAIDEN_JOB_NAME=decode, then
#   --tensor-parallel-size 1 --data-parallel-size 8 --enable-expert-parallel ... --port 8200
#   --kv-transfer-config '{"kv_connector":"TPURaidenConnector","kv_connector_module_path":"vllm_torchtpu.distributed.kv_transfer.tpu_connector","kv_role":"kv_consumer"}'
Enter fullscreen mode Exit fullscreen mode

The prefill side uses TPUMultiConnector to combine disaggregation with host offload, and its children must be listed explicitly: upstream classmethods parse the config before the connector exists, so the wrapper synthesizes no defaults. Start the controller with python examples/disagg/run_raiden_controller.py --host 0.0.0.0 --port 50055 and put examples/disagg/toy_proxy_server.py (or llm-d) in front. Check the decode side's error contract before you go live: with kv_load_failure_policy="fail" (the upstream default) a decode request evicted under KV pressure is aborted with finish_reason: "error" and stop_reason: "kv_cache_preempted" rather than recomputed on the decode pool. --additional-config '{"abort_on_preemption": false}' keeps preempt-and-recompute.

SGLang's own P/D recipe runs the opposite shape: a DP-attention prefill (attention TP=1, which the Raiden pipeline producer needs) into a TP=8 megakernel decode. TpuServingProfileBuilder("sglang").profile_d() follows that recipe and adds SGLANG_TPU_USE_BLOCK_MAJOR_KV=1 only when the model is not hybrid.

Notes on names: where the docs and the code disagree. While verifying every name in this post against the source, three doc entries did not match the code. The code wins, and the sample's validator rejects the doc spellings:

Doc says Code says Where
TpuRaidenConnector in module ...kv_transfer.raiden.raiden_connector TPURaidenConnector in vllm_torchtpu.distributed.kv_transfer.tpu_connector platforms/tpu_platform.py, every examples/disagg/*.sh
TPU_RAIDEN_RESHARD_IMPL: controller or host controller or store envs.py env_with_choices
TPU_KV_RESHARD_TRANSPORT: zmq or tcp zmq or raiden envs.py env_with_choices

Packaging it on GKE with llm-d 1.0

llm-d turns a set of model servers into one coordinated pool behind one endpoint: one router, one KV cache index, one flow-control policy. On GKE, GKE Inference Gateway runs the llm-d router in Gateway mode and calls the Endpoint Picker (EPP) on every request.

Client sends to Gateway, Gateway asks the EPP, the EPP reads the InferenceObjective and picks among Prefill Pods and Decode Pods inside one InferencePool.
Prefill and decode pods belong to one InferencePool. The llm-d.ai/role pod label is how the EPP tells them apart.

generate_llmd_gke_manifests() emits the objects, and validate_manifests() parses every document, checks each apiVersion and kind, and checks the cross-references (every poolRefs entry names a real pool, every scheduling profile references a declared plugin):

  00-disaggregatedset.yaml         disaggregatedset.x-k8s.io/v1       DisaggregatedSet
  01-leaderworkerset-unified.yaml  leaderworkerset.x-k8s.io/v1        LeaderWorkerSet
  02-inferencepool.yaml            inference.networking.k8s.io/v1     InferencePool
  03-inferenceobjectives.yaml      llm-d.ai/v1                        InferenceObjective (x2)
  04-epp-config.yaml               v1                                 ConfigMap (EndpointPickerConfig llm-d.ai/v1)
  05-raiden-controller.yaml        apps/v1, v1                        Deployment, Service
Enter fullscreen mode Exit fullscreen mode
Object Role in this deployment Detail that matters on TPU
DisaggregatedSet prefill and decode roles, each its own LeaderWorkerSet, rolled out together ships with the LWS controller (v0.11.1+, enableDisaggregatedSet=true); TPU node pools are fixed size, so a surge pod waits for the old group
LeaderWorkerSet multi-host engines, e.g. 2x2x2 with DP=16; leader serves HTTP, worker runs --headless LWS_LEADER_ADDRESS feeds --data-parallel-address
InferencePool selects model-server pods by label, names the EPP endpointPickerRef defaults to FailClose
InferenceObjective priority per workload: interactive 100, batch rollouts -10 negative priority marks traffic sheddable; spec.poolRefs replaced poolRef in v1
EndpointPickerConfig plugins and scheduling profiles, read at EPP startup not a CRD; lives in a ConfigMap; restart the EPP to change it

Each TPU pod states its slice with two node selectors and a chip count, and all three must agree with the node's machine type or the pod stays Pending without a clear error. For a tpu7x-standard-4t host that is cloud.google.com/gke-tpu-accelerator: tpu7x, cloud.google.com/gke-tpu-topology: 2x2x1 and google.com/tpu: "4" (8 devices). The generator also sets the pieces the llm-d guides call out: the TPU Sync engine ID from the pod's own name (so raising role replicas gives xPyD without other changes), cluster-autoscaler.kubernetes.io/safe-to-evict: "false", a preStop sleep of 20 s, --shutdown-timeout=90 and a 150 s grace period so in-flight requests drain, and a routing sidecar as a native sidecar in front of each decode engine.

The EPP configuration is where routing policy lives:

apiVersion: llm-d.ai/v1
kind: EndpointPickerConfig
featureGates: [flowControl]
plugins:
- type: prefill-filter
- type: decode-filter
- type: prefix-cache-scorer
- type: queue-scorer
- type: kv-cache-utilization-scorer
- type: prefix-based-pd-decider
  parameters: {nonCachedTokens: 2048}
- type: disagg-profile-handler
  parameters:
    deciders: {prefill: prefix-based-pd-decider}
schedulingProfiles:
- name: prefill
  plugins: [{pluginRef: prefill-filter}, {pluginRef: prefix-cache-scorer, weight: 2}, {pluginRef: queue-scorer, weight: 1}]
- name: decode
  plugins: [{pluginRef: decode-filter}, {pluginRef: prefix-cache-scorer, weight: 2}, {pluginRef: kv-cache-utilization-scorer, weight: 1}]
flowControl:
  enableEviction: true
  priorityBands: [{priority: 100, maxRequests: 500}]
  defaultNegativePriorityBand: {maxRequests: 200}
Enter fullscreen mode Exit fullscreen mode

The disagg-profile-handler runs the decode profile first, asks the decider whether the uncached suffix on that decode pod is large enough to be worth a remote prefill, and only then runs the prefill profile. With prefix-based-pd-decider, a turn whose prompt is mostly already cached on the decode pod skips disaggregation entirely, which is exactly the agentic case. vLLM decode pods can prefill locally, so this is safe for vLLM. An SGLang decode worker cannot, so SGLang deployments must use always-disagg-pd-decider. With enableEviction: true, in-flight negative-priority requests can be evicted to make room for blocked higher-priority ones.

The client side closes the loop. These are the canonical EPP request headers in llm-d 1.0, and MultiTurnAgenticClient.routing_headers() sends all four (the x-gateway-* and x-slo-* names are deprecated aliases):

Header Effect
x-llm-d-inference-objective names the InferenceObjective (same namespace as the pool) whose priority applies
x-llm-d-inference-fairness-id groups requests for fair sharing within a priority band (default default-flow)
x-llm-d-slo-ttft-ms TTFT target for admission and latency-aware scoring
x-llm-d-slo-tpot-ms TPOT target, same use

When flow control drops a request, the response carries x-llm-d-request-dropped-reason. rejected-* values mean no inference work was done and a retry is cheap. evicted means accelerator time was spent, so back off harder.

What this buys you, from Google's llm-d 1.0 announcement:

Four small before/after bar charts: Gemini platform prefix cache hit rate 35% to 70%; ZenteiQ tokens per day per 1,000 v6e 1.47B to 5.97B; Ironwood agentic coding throughput 1.0x to 2.4x; RL fleet duty cycle about 40% to over 70%.
Each panel uses its own units. The Ironwood agentic-coding run also cut median TTFT by more than 85% versus a plain Kubernetes Service.

Read the Ironwood panel with its provenance in mind: the announcement links it to the llm-d Qwen3-Coder-480B guide, and llm-d's current Qwen3.5 guide notes that those June to July 2026 results came from the JAX tpu_inference backend. The Torch TPU numbers for the Qwen3.5-397B guide are "being collected". The routing mechanism is engine-independent. The specific multiplier is not yet a vLLM-TorchTPU measurement.

Gate the rollout on numerical parity

Before a new image, kernel flag or quantization takes traffic, check that the endpoint still computes the model you think it does. verify_cpu_vs_tpu_serving_parity() sends a fixed prompt suite to /v1/completions with temperature: 0 and logprobs: k, runs the same prompts through a CPU PyTorch reference, and compares greedy tokens and top-k logprobs:

from sample_02_vllm_sglang_agentic_serving_and_raiden import (
    verify_cpu_vs_tpu_serving_parity, hf_cpu_reference)

report = verify_cpu_vs_tpu_serving_parity(
    "http://localhost:8000", "Qwen/Qwen3-0.6B", hf_cpu_reference("Qwen/Qwen3-0.6B"),
    max_tokens=16, top_k=5, logprob_atol=0.1, max_tie_gap=0.05)
print(report.verdict, report.max_abs_logprob_diff, report.mean_topk_overlap)
Enter fullscreen mode Exit fullscreen mode

The tricky part is the first token where the sequences disagree. BF16 on one side and FP32 on the other will legitimately flip a near-tie. Borrowing the rule from the TPU Agent Suite's compare_parity.py, a disagreement is excused only when the reference's own top-1 minus top-2 margin is under a tie gap derived from the measured noise (2x the RMS logprob difference on agreeing positions), and comparison of that prompt stops there. If the noise alone pushes the tie gap past max_tie_gap, the gate fails: a systematic error inflates the noise estimate, and a gap that wide would excuse real mismatches. In the smoke run, a small character LM served in BF16 by the mock stands in for the TPU:

== 7. CPU-vs-'TPU' parity gate ==
  bf16 endpoint vs fp32 reference: PASS  (compared 57 tokens, max |dlogp| 0.0148, top-k overlap 0.98, tie gap 0.0099)
  with a 10% LM-head scale bug:     FAIL  (max |dlogp| 0.1238; pos 3: |dlogp| 0.105 > 0.1)
Enter fullscreen mode Exit fullscreen mode

Calibrate logprob_atol on a known-good run of your own model before trusting a PASS. Part 5 calls this same function as the serving parity gate inside the TPU Agent Suite's onboarding flow.

Evaluate: what to turn on, and when

If you see Reach for Because
long cold starts on multi-rank hosts TPU_PARALLEL_PRECOMPILE=1, TPU_PRECOMPILE_PEER_REPLAY=1, persistent TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT and VLLM_CACHE_ROOT one compile per bucket per host, reused across restarts
latency spikes after warmup VLLM_XLA_CHECK_RECOMPILATION=1 in CI; SGLang's fail_on_recompile stance an unwarmed shape compiles on the serving path
MoE throughput below expectations DP=N, TP=1 + EP, fused EP MoE v2, SparseCore routing attention stays local; experts shard over the slice
TTFT dominated by long prompts PCP on a prefill pool; P/D disaggregation prefill is a different shape from decode
TPOT spikes when big prompts arrive P/D disaggregation over TPU Sync decode never waits behind a prefill
KV fills HBM before weights do FP8 KV; SEQ_ALONG_LANE at 1 head per rank; host DRAM tier fewer bytes per token, then more tiers
low per-user tokens/s at low concurrency MTP or DFlash; a megakernel if your model has one more tokens per weight read
prefix hits low across replicas llm-d prefix-cache-scorer, stable prompt prefixes, PYTHONHASHSEED=0 route turns to the replica holding their prefix
batch jobs starving interactive users InferenceObjective with negative priority, flowControl bands, eviction sheddable traffic yields under saturation

Be honest about maturity. TPU v7x is the recommended vLLM-TorchTPU target and is tested on every pull request. V6e, v5e and v5p are experimental. SGLang-TorchTPU marks structured output and function calling, pipeline parallelism and NVFP4 MoE as experimental at launch. In the llm-d 1.0 guides, the Torch TPU v6e and v7 rows are "community" (maintained, not in the nightly end-to-end matrix), and the Qwen3.5-397B disaggregated topology is labeled experimental. Plan a validation run on your own model before you adopt any of the recipes above, and keep the parity gate in the rollout.

Try it yourself

  1. Run python code/sample_02_vllm_sglang_agentic_serving_and_raiden.py --cpu-smoke and check section 1 against your guess. Then change token_buckets(1024) to the budget your workload needs and count the extra compiles.
  2. Add a ModelSpec for your own model (read num_key_value_heads, head_dim and num_hidden_layers from its config.json) and run recommend_layout() for throughput and interactive on two slices. At what TP degree does SEQ_ALONG_LANE start paying off?
  3. Extend MultiTurnAgenticClient.run_planning_workflow() with a sixth turn that calls a new tool you write, for example one that returns phase_roofline() for a proposed layout. Watch the hit rate on that turn, then break it on purpose by changing the system prompt between turns.
  4. On a TPU VM, launch Profile A with --print-profiles, point --agent at it, and compare its TTFT column with the mock's. Then run --parity against Qwen/Qwen3-0.6B and record the max logprob difference you see. That is your logprob_atol baseline.
  5. Emit the manifests with --emit-manifests out/, change the decode role to two replicas and the batch objective's priority to -50, and re-run validate_manifests().

The code, tests and every diagram source for this post live in github.com/ainaomotayo/torchtpu-sprint-26h4. Part 4 moves from serving to training: TorchTitan's SimpleFSDP and graph trainer, Ray, and GRPO with vLLM and SGLang rollout workers. If you build on this, tag it #TorchTPUSprint.

Top comments (0)