Skip to content

SGLang-TorchTPU

35 min read

Prerequisites: Inference math: prefill, decode, KV cache, vLLM-TorchTPU

Chapter 18 served models with vLLM on top of a TPU platform plugin. SGLang-TorchTPU is the same idea applied to the other large open-source engine: SGLang's own scheduler, API server and RadixAttention prefix cache, unchanged, over a plugin that supplies TPU attention, KV cache pools, MoE kernels and a graph runner. Most of what chapter 18 taught carries over: every step runs a precompiled program of fixed shape, attention is ragged paged attention in Pallas, and the KV arithmetic of chapter 17 decides how many users fit. This chapter covers what is different. You will install the engine, launch a recipe, and read the handful of TPU flags that differ from vLLM's. Then the chapter turns to the workload SGLang-TorchTPU is built around, agents that resend a growing conversation on every request, and shows how its radix tree of cached prefixes turns that resent history into almost free tokens. It closes with a decision table for choosing between the two engines and the checks that tell you a deployment reuses its prefixes: a hit rate you can read from the server, a turn-2 TTFT far below turn 1, and a parity gate.

What this chapter covers

  • Installing SGLang-TorchTPU on a TPU7x host, launching a recipe with benchmark.tpu.launch_server, and reading the flags it resolves to with --dry-run.
  • The TPU serving flags (--tp-size, --ep-size, --page-size, --kv-cache-dtype, --mem-fraction-static, --chunked-prefill-size, --max-running-requests), the two compile ladders, and what a radix hit saves at a given page size.
  • RadixAttention and HiCache on a multi-turn tool-calling workload: cache reporting and metrics, byte-stable prompt prefixes, and per-turn TTFT and hit rate.
  • Speculative decoding and prefill/decode disaggregation as the recipes and support tiers define them.
  • Choosing between vLLM-TorchTPU and SGLang-TorchTPU, and the failure modes of a deployment that does not reuse its prefixes or recompiles while serving.

How SGLang-TorchTPU plugs into SGLang

The launch post describes SGLang-TorchTPU as "an out-of-tree plugin": installing the sglang-tpu package registers a TPU platform with SGLang through the sglang.srt.platforms entry point, and "The scheduler, RadixAttention and API server are SGLang's own." The plugin "fills in the parts SGLang already asks each hardware platform for: the attention backend, the KV cache pools, the MoE kernels and the graph runner."

Layered diagram in three dashed bands stacked top to bottom, three blocks per band in aligned columns. The top amber band, SGLang core, holds OpenAI API server on the left, Scheduler in the middle and Radix cache on the right; an arrow labelled requests runs from OpenAI API server to Scheduler and an arrow labelled match prefix runs from Scheduler to Radix cache. The middle blue band, sglang_tpu plugin, holds Attention backend on the left, TpuGraphRunner in the middle and KV cache pools on the right; an arrow labelled padded batch runs down from Scheduler to TpuGraphRunner and an arrow labelled page indices runs down from Radix cache to KV cache pools. The bottom teal band, TorchTPU on TPU, holds Pallas kernels on the left, XLA program in the middle and Paged KV cache on the right; an arrow labelled bucketed shape runs down from TpuGraphRunner to XLA program, an arrow labelled custom ops runs from XLA program left to Pallas kernels, an arrow labelled calls runs down from Attention backend to Pallas kernels, and an arrow labelled owns pages runs down from KV cache pools to Paged KV cache.

Compare it with chapter 18's diagram: the shape is the same, but the top band now holds a radix cache, and the prefix match happens on the host before the TPU runs anything. The right column is the path from a cached prefix to the HBM pages that hold its KV.

SGLang core (unchanged). The OpenAI-compatible server, the scheduler (continuous batching, chunked prefill) and the radix cache are upstream SGLang. The scheduler asks the radix cache for the longest prefix of each new request it already holds, and only the rest is prefilled. That lookup and the page bookkeeping behind it run in host memory: the plugin's TpuPagedTokenToKVPoolAllocator keeps the free-page list on the CPU, so that no device tensor shrinks at a page boundary and triggers a recompile. A KVFreeFence holds a freed page until the forwards in flight that might still write it have finished.

The plugin. sglang_tpu provides the attention backends (the default, pallas_tpu_rpa_v3, is Ragged Paged Attention v3, the same kernel family chapter 18 used), the KV cache pools in TPU-friendly layouts, the MoE kernels and TpuGraphRunner. "Each TPU core runs its own PyTorch process through TorchTPU, as each GPU does on CUDA", the model runs under torch.compile and lowers to XLA, and there is no graph capture: "the runner pads each forward to a fixed set of token-count buckets for prefill and batch-size buckets for decode. Each bucket compiles once." Pallas kernels are exported to StableHLO by cpu_export_jax_op with JAX initialized CPU-only and registered as torch.library custom ops, so JAX never competes with TorchTPU for the TPU.

Two names for the platform. The sources describe two ways the plugin is selected, and you will meet both. The launch post and the README's Docker command set SGLANG_PLATFORM=tpu_oot, which selects TpuOOTPlatform, the out-of-tree plugin class. The plugin source and the recipes add a second route: SGLANG_PLATFORM=tpu, or no setting at all, selects TpuSRTPlatform, an in-tree platform that TpuOOTPlatform subclasses; the recipes' base config defaults to tpu unless the environment already sets the variable, and SUPPORT.md lists "Out-of-tree plugin mode" as Experimental. Both run the same kernels and pools. This chapter follows the recipes, which is what CI runs, and keeps tpu_oot where a source command uses it.

Frozen after warmup. Once warmup has compiled every bucket, the platform calls torch.compiler.set_stance("fail_on_recompile"). A shape you did not warm becomes an error instead of a silent multi-second stall, which is the stricter version of chapter 18's VLLM_XLA_CHECK_RECOMPILATION check.

What is different from vLLM-TorchTPU

Both engines are PyTorch-native plugins under their own upstream engine, both pad to precompiled shapes, both use Pallas ragged paged attention over a paged KV cache, and both move KV with TPU Sync. The differences that matter when you operate one:

vLLM-TorchTPU (chapter 18) SGLang-TorchTPU
Launch vllm serve MODEL, port 8000 python -m benchmark.tpu.launch_server --config <recipe> or python -m sglang.launch_server --model-path MODEL, port 30000
Plugin selection automatic through vllm.platform_plugins SGLANG_PLATFORM=tpu (recipes) or tpu_oot (launch post, Docker)
Python 3.12 3.11 to 3.14 for the release wheels
Compiled shapes one token ladder, doubling from 16 to --max-num-batched-tokens two ladders: --tpu-compile-tokens for prefill, --tpu-compile-bs for decode
After warmup VLLM_XLA_CHECK_RECOMPILATION=1 logs new graphs fail_on_recompile; SGLANG_TPU_CHECK_RECOMPILATION=1 logs them
Prefix cache automatic prefix caching by block hashes, --enable-prefix-caching RadixAttention, a radix tree of token prefixes, on unless --disable-radix-cache
Second KV tier TPURaidenOffloadingConnector HiCache, --enable-hierarchical-cache with --hicache-io-backend raiden
Device count flag DP x TP x PP x PCP logical devices --tp-size counts TensorCores; DP attention splits that group
Speculative decoding --speculative-config JSON, six methods --speculative-algorithm with EAGLE3, NEXTN (MTP), DFLASH (also DFlash2), DSPARK
Megakernels Kimi K3 decode megakernel Kimi K3, GLM-5.3-Flash and Muse Spark decode megakernels
Validated hardware v7x recommended and in CI; v6e supported TPU7x (Ironwood)

The last row deserves care. The SGLang-TorchTPU README says "Development and testing focus on TPU7x (Ironwood)" and every recipe targets a tpu7x host. Plan on v7x, and treat any other generation as untested.

Install and serve a first model

The README gives three routes onto a TPU7x host. The prebuilt image has the engine and the plugin installed and starts in the repository root, /sgl-workspace/sglang:

docker pull lmsysorg/sglang:v0.1.0-tpu
docker run -it --rm --privileged --net=host --shm-size=64g \
  -e SGLANG_PLATFORM=tpu_oot \
  lmsysorg/sglang:v0.1.0-tpu

With pip (Linux x86_64, Python 3.11 to 3.14), install both wheels of the v0.1.0 release together. The README is explicit that "sglang here is this repository's build, not the PyPI package", and, like chapter 18's install, routes torch to the PyTorch CPU index:

pip install --extra-index-url https://download.pytorch.org/whl/cpu \
  https://github.com/sgl-project/sglang-torchtpu/releases/download/tpu-v0.1.0/sglang-0.5.22-py3-none-any.whl \
  https://github.com/sgl-project/sglang-torchtpu/releases/download/tpu-v0.1.0/sglang_tpu-0.1.0-py3-none-any.whl

From source, install the engine with the TPU dependency manifest, then the plugin without re-resolving dependencies:

git clone https://github.com/sgl-project/sglang-torchtpu.git
cd sglang-torchtpu
cp python/pyproject_tpu.toml python/pyproject.toml
pip install --extra-index-url https://download.pytorch.org/whl/cpu -e python/
pip install --no-deps -e .

The serving recipes live in the repository, so clone it even if you installed the wheels. Launch the README's first server, GPT-OSS-20B on one host of 4 chips and 8 TensorCores, from the repository root:

python -m benchmark.tpu.launch_server --config recipe/configs/gpt_oss_20b/server.py

Once it is ready, send a request from another terminal:

curl http://localhost:30000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model": "gpt-oss-20b", "messages": [{"role": "user", "content": "Hello"}]}'

What a recipe is. A recipe module defines CONFIG with two dicts: server_args, which "becomes sglang.launch_server CLI flags", and runtime_env, the server's environment. The launcher renders True as a bare switch, omits False and None, writes a list as the flag followed by each value and a dict as compact JSON. Add --dry-run to see the result without starting anything. For the GPT-OSS-20B recipe it prints:

python -m sglang.launch_server --device tpu --dtype bfloat16 --host 127.0.0.1 --port 30000 \
  --grammar-backend none --attention-backend pallas_tpu_rpa_v3 --page-size 64 \
  --max-running-requests 64 --chunked-prefill-size 4096 --max-prefill-tokens 4096 \
  --context-length 9236 --torch-compile-max-bs 64 --enable-torch-compile \
  --kv-cache-dtype fp8_e4m3 --model-path openai/gpt-oss-20b --served-model-name gpt-oss-20b \
  --tp-size 8 --ep-size 8 --mem-fraction-static 0.6 --tpu-compile-tracer direct

The recipe file explains several of these choices in comments. EP 8 is used "not TP, for the 32 experts: sharding intermediate_size across 8 ranks fits neither the MXFP4 32-element block nor the MXU tile". "quantization": None keeps the checkpoint's own MXFP4 instead of the base config's fp8. --page-size 64 is "the TPU platform default, and the granularity a radix prefix match is floored to". --tpu-compile-tracer direct instead of dynamo because under Dynamo "a Raiden host KV reload decodes a different continuation". And the base config's "disable_radix_cache": True is switched back to False here, to "serve with prefix caching". The environment adds SGLANG_TPU_FUSED_MOE_SC_GATHER=0, because the SparseCore gather "cannot be lowered for GPT-OSS", and the base config sets LIBTPU_INIT_ARGS with XLA flags that overlap compute with collectives. --runtime-envs '{"NAME": "value"}' overrides one variable, and null removes it.

Two TPU backends for SGLang

SGLang also runs on TPU through SGLang-JAX, a separate JAX engine that remains maintained. The hardware-platforms/tpu page in the SGLang documentation tree describes SGLang-JAX (pip install sglang-jax), not SGLang-TorchTPU. Commands from that page do not apply to this chapter's engine; use the SGLang-TorchTPU README and recipes.

Static shapes: two ladders and a frozen compiler

Chapter 18's runner padded every step to one token ladder. SGLang-TorchTPU's runner keeps two, because a prefill step and a decode step vary in different dimensions. A prefill step's size is its total new tokens, which --tpu-compile-tokens buckets; a decode step's size is the number of running requests, which --tpu-compile-bs buckets. Both need --enable-torch-compile, which turns on TpuGraphRunner and is opt-in (SUPPORT.md). When you do not list the ladders, the plugin's defaults are powers of 2 up to the chunk size and up to the maximum batch.

The recipes end each ladder where the configuration's limit is. The prefix-cache recipe sets --chunked-prefill-size 2048 and --tpu-compile-tokens 512 1024 2048, and --max-running-requests 8 with --tpu-compile-bs 1 2 4 8; the MTP recipe uses --tpu-compile-tokens 512 2048 for a 2,048-token chunk. A chapter 18 reader will recognize the trade: fewer buckets compile faster and leave more HBM, more buckets waste less in padding. launch_profiles.py warns when a ladder stops short of the limit it serves.

--tpu-compile-tracer picks how the forward is traced: dynamo uses PyTorch Dynamo, direct "traces directly through TorchTPU with lower compile overhead". The serving recipes use direct; prefill context parallelism needs dynamo (SUPPORT.md).

Cold start. SUPPORT.md says it plainly: "Cold start is dominated by per-bucket compilation; use the compile cache." Persist TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT on a disk that survives restarts, as for vLLM-TorchTPU in chapter 18, so a restart loads executables instead of compiling them.

Catching what warmup missed. fail_on_recompile turns a missed shape into an error. To find out where it came from, set SGLANG_TPU_CHECK_RECOMPILATION=1, which the MTP recipe uses and comments as "Logs every XLA program compiled or loaded after warmup", and SGLANG_TPU_CHECK_RECOMPILATION_SITES=1 to attribute each compile to a source line. As in chapter 18, run these in CI and gate merges on them; the speculative decoding guide states the rule for its own code as "No serving-time recompilation. This is a requirement, not a performance goal."

RadixAttention: one tree of cached prefixes

The llm-d documentation describes SGLang's cache in one sentence: "SGLang manages KV-cache memory in a radix tree (RadixAttention), automatically reusing cached KV pages across shared system prompts, few-shot examples, and multi-turn chat histories." A radix tree stores token sequences so that a shared prefix is stored once: each edge holds a run of tokens, and two sequences share the path from the root up to the point where they first differ. When a request arrives, the scheduler walks the tree along the request's tokens as far as they match; the KV pages along that path are reused, and only the remaining suffix is prefilled. When the request finishes, its prompt and its reply are inserted, extending a branch or splitting an edge where it diverges from what was stored.

An animation in eight frames of a radix tree of cached prefixes, drawn left to right from a root, with each frame's request shown as a bar of reused teal tokens and orange tokens to prefill. Frame 1: an empty tree. Frame 2, request 1, session A turn 1: nothing is cached, all 2,112 prompt tokens are prefilled and one edge of system prompt, tools, user message and tool call is inserted. Frame 3, request 2, A sends the tool result: 2,176 of 2,496 tokens reused, 87 percent, and a tool result and answer node is added. Frame 4, request 3, A turn 2: 2,688 of 2,752 reused, 98 percent. Frame 5, request 4, session B with the same system prompt: the first edge splits after the 2,048-token system prompt and tools node, B adds its own branch, 2,048 of 2,112 reused, 97 percent. Frame 6, request 5, session C whose system prompt starts with a date: nothing matches, a new branch from the root, 0 percent. Frame 7, request 6, A turn 3: 2,944 of 3,008 reused, 98 percent. Frame 8 summarizes: the tree holds 5,760 tokens of KV for 14,592 prompt tokens sent, with a table of the six requests' prompt, reused and hit percentages.

Watch the bar under the tree: after the first request of a session, almost all of it is teal. The two moments it is not are the first request and session C, whose prompt differs in its first line, so nothing after that line can match.

The tree in the animation is computed by the chapter's RadixTree at page 64; the token counts are illustrative. Four properties of the real cache follow from the same structure:

  • Matches are whole pages. KV lives in pages, so a match is floored to --page-size. At page 64, a 1,000-token match reuses \(\lfloor 1000 / 64 \rfloor \times 64 = 960\) tokens and prefills the other 40 along with the new suffix. Larger pages reuse slightly less at each boundary.
  • Sharing is across requests, not only within a session. Session B in the animation reuses session A's system prompt and tools. Every agent or chat user behind the same system prompt shares those pages.
  • Order matters, content after a change does not. The match stops at the first differing token. A timestamp at the top of a system prompt, or a tool list that changes between turns, makes everything after it a miss even if the rest is identical.
  • Hybrid models keep their state too. For Gated DeltaNet and Kimi Delta Attention models, the recurrent state lives in TpuMambaPool, and a radix hit restores that state as well; the launch post lists RadixAttention "including hybrid sliding-window and linear-attention models".

When the cache is full. Least recently used leaves are evicted first by default (--radix-eviction-policy, default lru; the reference also lists lfu, slru and priority). HiCache, below, keeps evicted prefixes in host memory so a later hit reloads them instead of recomputing.

When the cache is off. --disable-radix-cache turns it off. The base recipe config does exactly that for throughput benchmarks on random prompts, and recipes that serve, like GPT-OSS-20B's, turn it back on. Read the flags of any recipe you copy: a recipe inherited from the base config without that override serves with no prefix cache at all.

Agentic workloads: why prefix reuse decides TTFT

Google's launch post states the problem for both engines: "Because agents repeatedly resend expanding multi-turn conversations, serving them efficiently requires finding the cached prefix instead of recomputing it." A coding agent's first request carries a system prompt, tool schemas and perhaps a repository summary; each later request resends all of it, plus every earlier turn and tool result, plus a few new tokens. Chapter 17's TTFT floor is the prefill's FLOPs over peak, so without a cache TTFT grows with the conversation. With a radix hit, the prefill covers only the new suffix, and TTFT stays roughly flat from turn 2 on.

The industry now benchmarks this workload directly. SemiAnalysis InferenceX runs AgentX, which Google's post calls "the project's dedicated track for evaluating agentic long-context and multi-turn workloads", and the post reports state-of-the-art AgentX results for Qwen 3.5 397B on Ironwood. The post does not attribute that result to one engine, so do not read it as an SGLang-TorchTPU number. What the SGLang-TorchTPU repository does contain is a Muse Spark AgentX recipe (recipe/configs/muse_spark/agentic.py), and its launch post says the feature set is "tested nightly on an agentic tool-call workload", with SUPPORT.md listing an agentic tool-call workload among the nightly checks for its flagship Qwen3-Coder-480B configuration.

What the agentic recipe turns on. The Muse Spark recipe sets, on top of its server recipe:

"enable_cache_report": True,        # cached_tokens in every response's usage
"enable_metrics": True,             # Prometheus /metrics
"enable_hierarchical_cache": True,  # HiCache: host pool = 2x device pool
"hicache_ratio": 2.0,
"hicache_io_backend": "raiden",
"hicache_mem_layout": "page_first_fused",
"hicache_write_policy": "write_back",

The first two make reuse observable. --enable-cache-report returns "number of cached tokens in usage.prompt_tokens_details for each openai request", which is how a client measures per-request hits; --enable-metrics exposes Prometheus metrics, among them the sglang:cache_hit_rate gauge. Both are off by default.

HiCache, the second tier. A long agent session's prefix eventually outgrows the HBM pool. HiCache extends the radix cache into host memory: --enable-hierarchical-cache turns it on, --hicache-ratio sizes the host pool relative to the device pool (default 2.0), and --hicache-write-policy chooses between write_through, which the prefix-cache recipe uses to "back up each prefix before eviction", and write_back, which the agentic recipe describes as "written back on eviction". On TPU the I/O goes through --hicache-io-backend raiden, TPU Sync, which the launch post describes as reading "the device buffers behind PyTorch tensors directly", or torch_tpu. The prefix-cache recipe's comments add two TPU requirements: "Raiden reloads require RPA v3 (the base backend) and the fused host pool layout", which is --hicache-mem-layout page_first_fused. With write_back over Raiden, a copy-ahead window keeps the next eviction victims already copied to host, sized by SGLANG_TPU_HICACHE_WRITE_BACK_COPY_AHEAD_TOKENS, so an eviction does not stall the scheduler. SUPPORT.md marks prefix cache, chunked prefill and HiCache Optimized, the highest tier, with one gap: "L3 storage tier not implemented on raiden".

Keep the prefix byte-stable. vLLM and SGLang on TPU: Production Serving with llm-d 1.0 records a lesson from building an agent client for these engines: a first version dropped the tools list on its final turn, and "Chat templates render tools near the top of the prompt, so that changed the prefix and the final turn missed the cache entirely." The rules that follow are simple. Send the same tool list on every request. Put anything that changes per request (a date, a request ID, retrieved documents) after the stable part, never before it. Do not reorder earlier messages or rewrite earlier tool results.

Tool calls and structured output. Tool calling needs --tool-call-parser set for the model's chat template (the reference lists gpt-oss, qwen3_coder, kimi_k3 and many others, plus auto), and reasoning models need --reasoning-parser. Two cautions from SUPPORT.md: function calling and structured output are Experimental on TPU ("Works through the eager sampler path; excluded from the spec-decode fast path. No TPU test yet."), and the serving recipes set --grammar-backend none, so a recipe you copy unchanged does no grammar-guided decoding. Validate tool-call output on the client side, as this chapter's client does by executing only tools it knows.

The serving flags that matter on TPU

These are ordinary SGLang server arguments; the TPU defaults come from the platform code and the recipes.

Flag What it sets On TPU Recipe values
--tp-size tensor-parallel group size counts TensorCores: 8 on a 4-chip TPU7x host; the README runs TP 16 over 2 hosts 8
--ep-size expert parallelism experts sharded over the group 8 (GPT-OSS-20B)
--attention-backend attention kernel and KV pool default pallas_tpu_rpa_v3; pallas_tpu_rpa_batched for context parallelism and SEQ_ALONG_LANE pallas_tpu_rpa_v3
--page-size tokens per KV page default 64, and the granularity of a radix match; batched RPA needs at least 256 64, 128
--kv-cache-dtype KV element type the platform defaults RPA backends to fp8_e4m3, which "halves KV bytes per token" fp8_e4m3, bfloat16
--mem-fraction-static HBM fraction for weights plus KV pool platform default 0.40, leaving room for XLA scratch 0.6, 0.75
--chunked-prefill-size tokens per prefill chunk top of the token ladder in the recipes 2,048, 4,096
--max-running-requests running requests the decode batch, top of the batch ladder 8 to 64
--context-length longest sequence sizes KV per request 4,096 to 9,236
--enable-torch-compile the graph runner opt-in; required for context and pipeline parallelism on
--tpu-compile-tokens, --tpu-compile-bs prefill and decode ladders each entry is a compiled program see above
--disable-radix-cache prefix cache off off in benchmark configs, on when serving serving: absent
--enable-cache-report, --enable-metrics observability needed to see hits agentic recipe: on

KV layouts. Two environment variables change the pool's layout. SGLANG_TPU_USE_SEQ_ALONG_LANE_KV=1 with pallas_tpu_rpa_batched and a page of at least 256 puts tokens on the 128-lane axis; at one KV head per rank in fp8 that is 256 bytes per token per layer instead of 512, which is why the Muse Spark recipe uses it for its 1M-token context configuration. SGLANG_TPU_USE_BLOCK_MAJOR_KV=1 puts all layers of a page in one contiguous HBM row so a Raiden transfer moves a page in one DMA; it requires pallas_tpu_rpa_v3, no speculative decoding, and Raiden as the transfer backend. vLLM and SGLang on TPU: Production Serving with llm-d 1.0 compares the three layouts in full.

Parallelism, speculative decoding and disaggregation

Parallelism. --tp-size is the whole engine's group: SGLang counts TP over all its TensorCores, and data-parallel attention splits that group. The server arguments reference marks --dp-size N --enable-dp-attention as the deprecated spelling of --attn-dp-size N; the llm-d docs still use the old one, so expect to see both. SUPPORT.md rates tensor and expert parallelism and multi-host launch Optimized, DP attention Supported ("attn-TP > 1 needs --enable-dp-lm-head"), and prefill context, decode context and pipeline parallelism Experimental. Chapter 18 explains when each layout pays; the reasons are the same here.

Speculative decoding. The launch post lists EAGLE-3, DFlash, DFlash2, DSPark and MTP drafters. On TPU they run on an experimental spec worker that "is enabled by default" and is built so that every algorithm runs "over static, bucketed shapes". --speculative-algorithm takes EAGLE3, NEXTN (MTP), DFLASH (DFlash2 "is served as --speculative-algorithm DFLASH") or DSPARK, with --speculative-draft-model-path for the methods that need a drafter. The worker does not support draft trees: "MTP and EAGLE3 need --speculative-eagle-topk 1". The MTP recipe for Qwen3.8-27B is a complete example:

python -m benchmark.tpu.launch_server --config recipe/configs/qwen3_8_27b/mtp_gate.py
# resolves to, among others:
#   --speculative-algorithm NEXTN --speculative-num-steps 3 --speculative-eagle-topk 1
#   --speculative-num-draft-tokens 4
# with SGLANG_TPU_ENABLE_EXPERIMENTAL_SPEC_WORKER=1 and SGLANG_TPU_CHECK_RECOMPILATION=1

SUPPORT.md rates EAGLE3 Optimized ("topk=1 only, no rejection sampling") and DFlash Supported ("Draft needs an lm_head"). Chapter 18's speculative decoding animation and its rule of thumb apply unchanged: speculation pays most at small batches.

Disaggregation. For prefill and decode on separate hosts, the launch post describes a consumer-pull transfer over TPU Sync: "as each chunked-prefill step commits its pages, the prefill announces them and the decode side pulls that chunk while the next one computes, so only the last chunk remains to move once prefill finishes. Pages the decode already holds from its own prefix cache are never sent." That last sentence is RadixAttention on the decode side. When prefill and decode use different TP sizes, TPU Sync reshards in flight, and SUPPORT.md lists 16 prefill shards into 8 decode shards as Optimized. A minimal pair:

# prefill
python -m sglang.launch_server --model-path openai/gpt-oss-120b \
  --tp-size 8 --attention-backend pallas_tpu_rpa_v3 --page-size 64 \
  --disaggregation-mode prefill --disaggregation-transfer-backend raiden \
  --host 0.0.0.0 --port 30001 --disaggregation-bootstrap-port 8998
# decode
python -m sglang.launch_server --model-path openai/gpt-oss-120b \
  --tp-size 8 --attention-backend pallas_tpu_rpa_v3 --page-size 64 \
  --disaggregation-mode decode --disaggregation-transfer-backend raiden \
  --host 0.0.0.0 --port 30002

A router sits in front of the pair; the Muse Spark recipe uses python3 -m sglang_router.launch_router --pd-disaggregation --mini-lb --prefill http://<prefill>:30000 8998 --decode http://<decode>:30000. Chapter 20 covers disaggregation across a cluster.

How llm-d sees an SGLang server

Chapter 20 puts engines behind llm-d's router. Four details from llm-d's SGLang page decide whether that works:

  • Label the pods. The endpoint picker "defaults to vLLM metric names when no engine label is present", so SGLang pods must carry llm-d.ai/engine-type: sglang.
  • Turn metrics on. With --enable-metrics, the picker scrapes sglang:num_queue_reqs, sglang:num_running_reqs and sglang:token_usage from /metrics for scheduling.
  • Publish the tree. With --enable-kv-cache-events and --kv-events-config, SGLang publishes radix-tree insertion and eviction events over ZeroMQ, and llm-d's KV-cache indexer uses them to route each request to the replica that already holds its prefix. For agents, that routing is what keeps a session's turns on the replica with its cache.
  • Decode cannot prefill. "An SGLang decode worker (--disaggregation-mode=decode) requires every request to include bootstrap rendezvous fields and cannot fall back to local prefill", so llm-d deployments with SGLang use the always-disagg-pd-decider. vLLM decode pods can prefill locally, which is why a prefix-based decider is safe for vLLM only.

Health probes use GET /health.

Choosing between vLLM-TorchTPU and SGLang-TorchTPU

The sources publish no head-to-head benchmark of the two engines on the same model and slice, so the choice rests on features, maturity for your model, and the stack around the engine. Both support prefix caching including hybrid models, host KV offload over TPU Sync, fp8 KV, DP attention with EP, speculative decoding, disaggregation with resharding, and vision-language models.

If Prefer Because
Your stack is vLLM already (configs, vllm bench serve, KV connectors) vLLM-TorchTPU the same CLI, server, scheduler and KV manager as on GPUs (chapter 18)
Your stack is SGLang already, or you train with Miles RL SGLang-TorchTPU Miles pairs SGLang-TorchTPU rollouts with TorchTitan training (launch post; chapter 15)
You need v6e vLLM-TorchTPU its setup guide lists v6e as supported with reference recipes; SGLang-TorchTPU's README focuses on TPU7x
You need n-gram or suffix speculation (no drafter) vLLM-TorchTPU six methods including ngram and suffix; the SGLang-TorchTPU launch lists only drafter-based methods
Your model has an SGLang megakernel (GLM-5.3-Flash, Muse Spark; Kimi K3 has one in both engines) SGLang-TorchTPU whole-decoder Pallas megakernels for those models
Your agent depends on tool calls and structured output either, after testing both list them; SGLang-TorchTPU marks them Experimental and its recipes set --grammar-backend none
Your model is in one engine's validated table and not the other's that engine supported models pages and SUPPORT.md tiers

The table is the full reference; the figure puts its rows in the order to ask them. Tool calls and structured output decide nothing on their own, since both engines list them: test them in either.

A decision tree with six white questions in a column down the middle; each No continues down to the next. Four blue cards of one size sit beside the column. Do you need v6e? Yes runs left and down into the top of the card vLLM-TorchTPU, which sits on the left level with the second question. Is your stack vLLM already? Yes leads straight left into vLLM-TorchTPU. Is your stack SGLang, or Miles RL rollouts? Yes runs right and down into the top of the card SGLang-TorchTPU, which sits on the right level with the fourth question. Do you need n-gram or suffix speculation? Yes runs left and up into the bottom of vLLM-TorchTPU. Does only SGLang have a megakernel for it? Yes runs right and up into the bottom of SGLang-TorchTPU. Is the model validated in only one engine? Yes leads right to the card Use that engine; No leads left to the card Run both, then pick: same client; compare TTFT, TPOT, hit rate.

Hard constraints come first: only vLLM-TorchTPU lists v6e, and an existing stack usually decides the rest. When nothing decides it, run both behind the same client and pick on the numbers.

The last outcome, running both, is the honest default. The chapter's agentic_client.py and chapter 18's client.py speak plain OpenAI-compatible HTTP, so the same conversation runs against vllm serve on port 8000 and SGLang on port 30000; with vLLM, start the server with --enable-prompt-tokens-details to get cached_tokens in the usage block.

The companion code

code/ch19_sglang/ (source) has two standard-library tools, and imports chapter 18's streaming client rather than copying it.

launch_profiles.py holds eight profiles. Three are recipes rendered exactly as the repository's launch_server --dry-run prints them (gpt-oss-20b-server, gpt-oss-20b-prefix-cache-offload, qwen3.8-27b-mtp-gate), one is derived for this chapter (gpt-oss-20b-agentic: the server recipe plus --enable-cache-report, --enable-metrics and the gpt-oss parsers), and four are minimal launches drawn from the SGLang-TorchTPU source and docs. The validator accepts only flags and environment variables the sources use and refuses what they rule out, including a vLLM flag pasted into an SGLang command:

$ python code/ch19_sglang/launch_profiles.py --cpu-smoke
...
recipe dict renders to the gpt-oss-20b-server profile: True
radix reuse at page 64: a 1,000-token match reuses 960 tokens; a 3,300-token prompt then prefills 2340
  rejected: gpt-oss-120b-seq-along-lane [('--page-size', 128)]: pallas_tpu_rpa_batched needs --page-size >= 256, got 128; ...
  rejected: qwen3.8-27b-mtp-gate [('--speculative-eagle-topk', 4)]: NEXTN on the TPU spec worker needs --speculative-eagle-topk 1 (no draft trees)
  rejected: gpt-oss-20b-server [('--tp-size', 16)]: --tp-size 16 needs 16 TensorCores, v7x-8 has 8
  rejected: gpt-oss-20b-server [('--enable-prefix-caching', None)]: --enable-prefix-caching is not a flag the SGLang-TorchTPU sources use
cpu-smoke: OK

agentic_client.py runs a five-turn conversation with three tools backed by the book's own code (a launch profile lookup, chapter 17's kv_bytes, and the page-floored prefill count). Every request streams; the client records TTFT to the first content or tool-call delta, TPOT, prompt tokens and cached_tokens, and can read sglang:cache_hit_rate from /metrics. Its CPU smoke run starts FakeSGLangServer, which holds a real radix tree, charges prefill only for uncached tokens, and prints SGLang's prefill log line:

$ python code/ch19_sglang/agentic_client.py --cpu-smoke
fake SGLang endpoint http://127.0.0.1:61840: 3.0 ms + 0.1 ms per uncached token, decode 1.0 ms/token, page 16
turn  kind        TTFT ms  TPOT ms   E2E ms  prompt  cached  hit%
----  ----------  -------  -------  -------  ------  ------  ----
   1  tool_call      97.5     1.53    100.6     804       0     0
   1  answer         43.4     1.55     63.5    1127     832    74
   2  tool_call       8.1     1.56     19.0    1186    1152    97
   2  answer          7.4     1.51     16.5    1270    1248    98
   3  tool_call       8.4     1.42     15.6    1309    1280    98
   3  answer          7.8     1.52     17.5    1367    1344    98
   4  answer          9.1     1.51     43.9    1401    1376    98
   5  answer          8.6     1.51     43.4    1437    1424    99
first-request TTFT speedup vs turn 1: t1=1.0x, t2=12.0x, t3=11.6x, t4=10.8x, t5=11.4x
turn 1 TTFT 97.5 ms; turns 2+ median 8.4 ms
server log, last request: Prefill batch, #new-seq: 1, #new-token: 13, #cached-token: 1424, ...
/metrics sglang:cache_hit_rate 0.874
chapter 18 parity gate against this endpoint: PASS (4/4)

The second row is worth reading: the request that sends turn 1's tool result reuses only 74%, because the tool result is new text. The smoke run then repeats the conversation with a request counter at the start of the system prompt. Only the tool schemas, which the fake renders before the system prompt, still match, the hit rate falls to between 37% and 47%, and no turn starts more than about 1.3 times faster than turn 1. The fake is a test fixture, not a TPU: no batching, no eviction, tool choice by keyword. Its numbers are illustrative; its shape is what a real engine shows.

Failure modes

Symptom Mechanism What to check or change
TTFT grows every turn; #cached-token stays near 0 Radix cache off: a recipe inherited --disable-radix-cache from the base config Remove the flag, as the GPT-OSS-20B server recipe does ("disable_radix_cache": False)
Turn 2 is no faster than turn 1, cache on Unstable prefix: a timestamp, request ID or changed tool list near the top of the prompt Diff two consecutive prompts; move per-request content after the stable part; send the same tools every turn
cached_tokens missing from responses; no /metrics Observability off: both are off by default --enable-cache-report and --enable-metrics
Hits fine on one replica, poor across a fleet Routing ignores prefixes: a session's turns land on different replicas llm-d prefix-aware routing with KV events (--enable-kv-cache-events) and the llm-d.ai/engine-type: sglang label (chapter 20)
Long sessions slow down after a while Prefix evicted from HBM and recomputed HiCache with --hicache-io-backend raiden, page_first_fused, a larger --hicache-ratio; check #cached-token against prompt length
Server errors on a request shape after warmup fail_on_recompile: a token count or batch size outside the ladders Extend --tpu-compile-tokens / --tpu-compile-bs to the chunk size and running-request cap; SGLANG_TPU_CHECK_RECOMPILATION=1 and _SITES=1 in CI
Startup takes many minutes every time Per-bucket compilation with no persistent cache Persist TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT; fewer ladder entries
Startup error: page size Backend floor: batched RPA needs --page-size of at least 256 Use 256 with pallas_tpu_rpa_batched and SEQ_ALONG_LANE
Startup error with MTP or EAGLE3 Draft trees unsupported on the TPU spec worker --speculative-eagle-topk 1
response_format ignored; tool calls malformed Grammar backend off in the recipe, and structured output and function calling Experimental Check --grammar-backend and --tool-call-parser; validate on the client
Commands from SGLang's TPU docs page fail Wrong engine: that page is SGLang-JAX Use the SGLang-TorchTPU README and recipes
SGLang decode pool rejects requests behind llm-d No local prefill fallback on SGLang decode workers always-disagg-pd-decider

Verifying the result

An agent deployment is trustworthy when it answers, when it reuses its prefixes, when that reuse shows up as latency, and when it computes the same outputs as a build you trust.

  1. Smoke request. Send the README's curl request, or reuse chapter 18's client against port 30000:

    python code/ch18_vllm/client.py smoke --base-url http://localhost:30000 --model gpt-oss-20b
    
  2. Prefix-cache hits are visible. Start the server with --enable-cache-report and --enable-metrics (the gpt-oss-20b-agentic profile does). Then read reuse in three places. Each response's usage.prompt_tokens_details.cached_tokens should be close to the prompt length from the second request of a session on. The server log's Prefill batch, #new-seq: ..., #new-token: ..., #cached-token: ... lines should show a small #new-token next to a large #cached-token. And curl -s localhost:30000/metrics | grep sglang:cache_hit_rate should show a rate that rises as sessions continue. If all three stay near zero, go back to the first two rows of the failure table.

  3. TTFT on turn 2 and later drops against turn 1. Run the agent conversation:

    python code/ch19_sglang/agentic_client.py run --base-url http://localhost:30000 \
        --model gpt-oss-20b --metrics --json turns.json
    

    The first request of turns 2 to 5 should have a hit rate near the fraction of the prompt that is old, and a TTFT well below turn 1's. How far below depends on the model and the prompt: chapter 17's floor says the prefill work falls with the uncached fraction until the step becomes memory-bound, where its floor is the weight-read time of one step. Run it again with --vary-system-prompt: the speedup should disappear. That control run proves that the speedup you measured came from the cache and not from warm-up or luck.

  4. Parity gate. Record greedy outputs from a build you trust and compare every new image, flag set or KV dtype against them with chapter 18's client, pointed at port 30000:

    python code/ch18_vllm/client.py record --base-url http://localhost:30000 --model gpt-oss-20b --out ref.json
    python code/ch18_vllm/client.py parity --base-url http://localhost:30000 --model gpt-oss-20b --reference ref.json
    

    A prefix cache must not change outputs: a cached prefix's KV is the KV that prefill would have computed. Run the parity check once with the cache warm (repeat the prompts first) and once cold; both must pass. For bf16 against an fp32 reference, or after a kernel change, use the logprob gate with a tie rule from chapter 23.

Worked problems

Problem 1. A recipe sets --page-size 64. An agent's turn sends a 3,300-token prompt; the radix tree holds a 3,250-token prefix of it. How many tokens are prefilled? With --page-size 128?

Answer

The match is floored to whole pages. At 64: \(\lfloor 3250 / 64 \rfloor \times 64 = 50 \times 64 = 3{,}200\) tokens reused, so \(3300 - 3200 = 100\) are prefilled. At 128: \(\lfloor 3250 / 128 \rfloor \times 128 = 25 \times 128 = 3{,}200\), also 100 here; but a 3,300-token match would reuse 3,264 at page 64 and only 3,200 at page 128. Larger pages lose up to one page of reuse at each match. prefill_tokens(3300, 3250, 64) in launch_profiles.py checks it.

Problem 2. You copy recipe/configs/qwen3_8_27b/mtp_gate.py to serve a coding agent and see TTFT grow every turn. Using the dry-run output in this chapter, find the cause and write the override.

Answer

The MTP recipe inherits the base config, whose server arguments include "disable_radix_cache": True, and the dry run shows --disable-radix-cache in the command. That base setting is a measurement choice for random-prompt throughput; the GPT-OSS-20B server recipe turns it back off with "disable_radix_cache": False. Do the same in your copy, and add "enable_cache_report": True so you can see the hits. With this chapter's builder: launch_profiles.py --profile qwen3.8-27b-mtp-gate --set=!--disable-radix-cache --set=--enable-cache-report.

Problem 3. A server runs --chunked-prefill-size 4096, --max-running-requests 32, --tpu-compile-tokens 512 1024 2048 and --tpu-compile-bs 1 2 4 8 16. Which requests will hit fail_on_recompile, and what ladders fix it? How many programs does warmup compile with your fix?

Answer

A prefill chunk of more than 2,048 tokens has no compiled token bucket, and a decode step with more than 16 running requests has no batch bucket; either becomes a compile after warmup, which the frozen compiler turns into an error. End each ladder at its limit, as the recipes do: --tpu-compile-tokens 512 1024 2048 4096 and --tpu-compile-bs 1 2 4 8 16 32. That is 4 + 6 = 10 programs. launch_profiles.py prints a warning for each ladder that stops short.

Problem 4. Your agent's system prompt begins Today is 2026-12-01. You are a coding assistant... and is 3,000 tokens long; the tool schemas are 1,000 tokens and the template renders them after the system prompt. Turn 2 adds 200 tokens. Estimate the hit rate of turn 2's first request on the same day and on the first request after midnight, and fix the prompt.

Answer

On the same day, everything but the 200 new tokens matches (up to page rounding): about \(4000 / 4200 = 95\%\) if turn 1's prompt was 4,000 tokens, more if turn 1's reply is part of the prefix. After midnight, the date is in the first line, so the match stops within the first few tokens: almost 0%, and every session pays a full prefill on its next turn. Move the date to the end of the system prompt, or into the latest user message, so the 4,000 stable tokens stay a prefix. The --vary-system-prompt run of the chapter's client shows the same effect.

Problem 5. Write the overrides that turn the gpt-oss-20b-server profile into one that keeps evicted prefixes in host memory over TPU Sync, with a host pool three times the device pool, backing each prefix up to host before it can be evicted. What two settings does the recipe say Raiden reloads require?

Answer

Add --enable-hierarchical-cache, --hicache-io-backend raiden, --hicache-mem-layout page_first_fused, --hicache-ratio 3.0 and --hicache-write-policy write_through, which is what gpt-oss-20b-prefix-cache-offload sets, plus --enable-cache-report to see the hits. The recipe's comment: "Raiden reloads require RPA v3 (the base backend) and the fused host pool layout", that is --attention-backend pallas_tpu_rpa_v3 and page_first_fused. The builder refuses raiden without them.

Problem 6. A team serves Qwen3-Coder on v7x behind llm-d for an agent product and is choosing an engine. They use n-gram speculation today on GPUs, their router is llm-d with a prefix-based P/D decider, and they plan an RL loop later. Use the decision table to list what each choice would require them to change.

Answer

vLLM-TorchTPU keeps n-gram speculation ("method": "ngram") and the prefix-based decider, because vLLM decode pods can prefill locally. SGLang-TorchTPU would replace n-gram with a drafter-based method (EAGLE3, NEXTN, DFLASH, DSPARK), require always-disagg-pd-decider and the llm-d.ai/engine-type: sglang label, and fits the RL plan if they use Miles, which pairs SGLang-TorchTPU rollouts with TorchTitan. Qwen3-Coder-480B is SGLang-TorchTPU's flagship Optimized model with a nightly agentic tool-call workload, and vLLM-TorchTPU has Qwen3-Coder CI recipes. Neither choice is forced; run the chapter's agent client against both and compare turn-2 TTFT, TPOT and hit rate before deciding.

Quick questions

  1. Name the three bands of the runtime diagram and place in them: the radix cache, TpuGraphRunner, the KV cache pools, Ragged Paged Attention v3.
  2. Which two environment-variable values select the TPU platform, and which class does each select?
  3. Why does SGLang-TorchTPU keep two compile ladders where vLLM-TorchTPU keeps one?
  4. What does fail_on_recompile change compared with chapter 18's recompilation check?
  5. In a radix tree, what happens on insert when a new request diverges in the middle of an edge?
  6. Why is a radix match floored to --page-size, and what does that cost at a page boundary?
  7. Which two flags make prefix reuse observable, and where does each show it?
  8. What do write_through and write_back mean for HiCache, and what do Raiden reloads require?
  9. Why must SGLang deployments behind llm-d use always-disagg-pd-decider?
  10. Give two cases where the decision table points to vLLM-TorchTPU and two where it points to SGLang-TorchTPU.

Key takeaways

  • SGLang-TorchTPU is SGLang's own scheduler, API server and RadixAttention over the sglang_tpu plugin, which supplies Pallas attention, KV cache pools, MoE kernels and TpuGraphRunner. Install the engine and plugin wheels together (or use lmsysorg/sglang:v0.1.0-tpu), launch a recipe with benchmark.tpu.launch_server, and read its flags with --dry-run. The server listens on port 30000.
  • Shapes are static in two ladders: --tpu-compile-tokens for prefill and --tpu-compile-bs for decode, ending at the chunk size and the running-request cap. After warmup the compiler is frozen with fail_on_recompile; find stray shapes in CI with SGLANG_TPU_CHECK_RECOMPILATION=1.
  • RadixAttention stores every cached prefix once in a radix tree and reuses the longest match, floored to --page-size. An agent's resent history then costs only its new suffix, so TTFT stays flat from turn 2 on, provided the first tokens of every prompt stay identical and the recipe does not inherit --disable-radix-cache.
  • For agents, add --enable-cache-report and --enable-metrics to see hits, HiCache over Raiden to keep evicted prefixes in host memory, the right --tool-call-parser, and client-side validation, since function calling and structured output are Experimental on TPU.
  • Speculative decoding uses --speculative-algorithm (EAGLE3, NEXTN, DFLASH, DSPARK) with top-k 1; disaggregation pulls KV chunk by chunk over TPU Sync and never sends pages the decode side's radix cache holds.
  • Choose the engine on hardware, existing stack, speculation method and your model's support tier, then measure both with the same multi-turn client. A deployment is verified when hits show in cached_tokens, the log and sglang:cache_hit_rate, turn-2 TTFT drops against turn 1 and vanishes with a varied system prompt, and greedy outputs match a trusted build.

References