Serve agents with SGLang-TorchTPU¶
Use this guide when the traffic is agents or multi-turn chat: every request resends a growing conversation (system prompt, tool schemas, earlier turns and tool results) plus a few new tokens. SGLang-TorchTPU's RadixAttention keeps cached prefixes in a radix tree so only the new suffix is prefilled, and HiCache keeps evicted prefixes in host memory over TPU Sync. This guide turns on what makes reuse visible, adds the host tier, keeps prompts reusable, and measures per-turn TTFT and hit rate with a control run. Chapter 19, sections "RadixAttention" and "Agentic workloads", explains why reuse decides TTFT.
Prerequisites¶
- A working SGLang-TorchTPU server from a recipe that keeps the radix cache on: Serve a first model with SGLang-TorchTPU.
- This book's
code/ch19_sglang/agentic_client.py(source), which importscode/ch18_vllm/client.py, on a machine that can reach the server.
Steps¶
1. Try the client on a laptop first¶
python code/ch19_sglang/agentic_client.py --cpu-smoke
It runs a five-turn tool-calling conversation against a local fake SGLang endpoint that holds a real radix tree and charges prefill only for uncached tokens, then repeats it with a request counter at the start of the system prompt.
Check: the run ends cpu-smoke: OK. In the first table, turns 2 to 5 reuse 97 to 99% of the prompt and start many times faster than turn 1; in the second run that advantage disappears. The fake is a test fixture, not a TPU; its shape is what a real engine shows.
2. Start the server with reuse made visible¶
Two flags, both off by default, make reuse observable: --enable-cache-report returns the cached token count in usage.prompt_tokens_details of every response, and --enable-metrics exposes Prometheus metrics on /metrics, among them sglang:cache_hit_rate. Tool calling needs --tool-call-parser for the model's template (the reference lists gpt-oss, qwen3_coder, kimi_k3 and others, plus auto), and reasoning models need --reasoning-parser.
Add them in a recipe that derives from the serving recipe, the inheritance pattern the recipe README prescribes. Save the following recipe as benchmark/tpu/recipe/configs/gpt_oss_20b/agentic_local.py (recipes resolve only under recipe/); code/ch19_sglang/launch_profiles.py holds the same configuration as a profile:
from copy import deepcopy
from benchmark.tpu.recipe.configs.gpt_oss_20b.server import CONFIG as SERVER_CONFIG
CONFIG = deepcopy(SERVER_CONFIG)
CONFIG["server_args"].update(
{
"enable_cache_report": True,
"enable_metrics": True,
"tool_call_parser": "gpt-oss",
"reasoning_parser": "gpt-oss",
}
)
python -m benchmark.tpu.launch_server --config recipe/configs/gpt_oss_20b/agentic_local.py --dry-run
python -m benchmark.tpu.launch_server --config recipe/configs/gpt_oss_20b/agentic_local.py
The book's gpt-oss-20b-agentic profile is the same configuration and prints the full command, with the compile cache root if you pass --cache-root:
python code/ch19_sglang/launch_profiles.py --profile gpt-oss-20b-agentic --cache-root "$HOME/tpu-cache"
Check: the dry run shows --enable-cache-report, --enable-metrics and the two parsers, and no --disable-radix-cache.
3. Add the host tier for long sessions¶
A long session's prefix eventually outgrows the device pool and is evicted; with HiCache, an evicted prefix is reloaded from host memory instead of recomputed. The flags, as the prefix-cache recipe (recipe/configs/gpt_oss_20b/prefix_cache_kv_offload.py) sets them:
"enable_hierarchical_cache": True,
# Raiden reloads require RPA v3 (the base backend) and the fused host
# pool layout.
"hicache_io_backend": "raiden",
"hicache_mem_layout": "page_first_fused",
"hicache_ratio": 3.0,
# Back up each prefix before eviction
"hicache_write_policy": "write_through",
"enable_cache_report": True,
--hicache-ratio sizes the host pool relative to the device pool (default 2.0). write_through backs up each prefix before it can be evicted; write_back, which the Muse Spark agentic recipe uses with a ratio of 2.0, writes on eviction, with a copy-ahead window (SGLANG_TPU_HICACHE_WRITE_BACK_COPY_AHEAD_TOKENS) so an eviction does not stall the scheduler. --hicache-io-backend raiden uses TPU Sync (torch_tpu is the other backend) and needs --attention-backend pallas_tpu_rpa_v3 and --hicache-mem-layout page_first_fused. SUPPORT.md rates HiCache Optimized, with no L3 storage tier on raiden. The prefix-cache recipe shrinks the device pool (max_total_tokens 8192) only so its test can force evictions; do not copy that size for serving.
Check: the builder accepts your combination; it refuses raiden without RPA v3 and page_first_fused:
python code/ch19_sglang/launch_profiles.py --profile gpt-oss-20b-prefix-cache-offload
4. Keep the prompt prefix byte-stable¶
A radix match stops at the first differing token, and matches are floored to whole pages (--page-size, 64 in the GPT-OSS recipes: a 1,000-token match reuses 960). So:
- Send the same tool list on every request, in the same order. Chat templates render tools near the top of the prompt; a client that drops
toolson its final turn misses the cache entirely. - 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.
Check: diff the rendered prompts of two consecutive requests of one session: the earlier one must be a prefix of the later one.
5. Measure per-turn TTFT and hit rate¶
python code/ch19_sglang/agentic_client.py run --base-url http://localhost:30000 \
--model gpt-oss-20b --metrics --json turns.json
The client streams every request and records TTFT, TPOT, prompt tokens and cached_tokens per request, prints the TTFT speedup of each turn over turn 1, and reads sglang:cache_hit_rate from /metrics. Read reuse in three places:
usage.prompt_tokens_details.cached_tokensclose to the prompt length from the second request of a session on (thecachedandhit%columns).- The server log's
Prefill batch, #new-seq: ..., #new-token: ..., #cached-token: ...lines: a small#new-tokennext to a large#cached-token. curl -s localhost:30000/metrics | grep sglang:cache_hit_raterising as sessions continue.
Then run the control:
python code/ch19_sglang/agentic_client.py run --base-url http://localhost:30000 \
--model gpt-oss-20b --metrics --vary-system-prompt
Check: turns 2 to 5 start well below turn 1 in the first run, and the speedup disappears in the control. That difference is the evidence that the cache, not warm-up, made the later turns fast. To compare with vLLM-TorchTPU on the same conversation, start vllm serve with --enable-prompt-tokens-details and point the client at port 8000.
6. Gate on parity, cache warm and cold¶
A cached prefix's KV is the KV prefill would have computed, so the cache must not change outputs:
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
Record on a build you trust, then run parity once with the cache warm (send the prompts first) and once cold (after a restart).
Check: both runs pass. For bf16 against an fp32 reference, or after a kernel change, use the logprob gate with a tie rule from chapter 23.
7. Behind llm-d¶
For a fleet of SGLang replicas behind llm-d's router (chapter 20):
- Label the pods
llm-d.ai/engine-type: sglang; the endpoint picker defaults to vLLM metric names without it. - Start with
--enable-metrics; the picker scrapessglang:num_queue_reqs,sglang:num_running_reqsandsglang:token_usage. - Start with
--enable-kv-cache-eventsand--kv-events-configso radix insertions and evictions reach llm-d's KV-cache indexer, which routes each session's turns to the replica that holds its prefix. - With prefill and decode disaggregated, use
always-disagg-pd-decider: an SGLang decode worker cannot fall back to local prefill.
Check: a session's turns keep their hit rate when served through the router, not only against one replica.
Troubleshooting¶
| Symptom | Cause | Fix |
|---|---|---|
TTFT grows every turn; #cached-token near 0 |
Radix cache off (--disable-radix-cache inherited from the base config) |
Derive from server.py, or set "disable_radix_cache": False |
| Turn 2 no faster than turn 1 with the cache on | Unstable prefix: a timestamp, request ID or changed tool list near the top | Step 4; diff two consecutive prompts |
cached_tokens missing; no /metrics |
Both are off by default | --enable-cache-report and --enable-metrics |
| Hits good on one replica, poor across a fleet | Routing ignores prefixes | llm-d prefix-aware routing with --enable-kv-cache-events and the engine-type label |
| Long sessions slow down after a while | Prefix evicted from HBM and recomputed | HiCache over raiden with page_first_fused; a larger --hicache-ratio |
HiCache over raiden with another attention backend or host layout |
Raiden reloads require RPA v3 and the fused host pool layout | pallas_tpu_rpa_v3 and page_first_fused |
| No tool calls, or malformed ones | Missing --tool-call-parser, or grammar off (--grammar-backend none); function calling is Experimental |
Set the parser for the model's template; validate tool calls on the client |
| SGLang decode pool rejects requests behind llm-d | No local prefill fallback on SGLang decode workers | always-disagg-pd-decider |
References¶
- SGLang-TorchTPU: TPU serving recipes
- SGLang-TorchTPU: Server Arguments
- SGLang-TorchTPU: Supported models and features
- llm-d: SGLang in llm-d
- Announcing New vLLM and SGLang Inference Engines on TPU
- SGLang-TorchTPU: PyTorch-Native Production Serving on TPUs
- vLLM and SGLang on TPU: Production Serving with llm-d 1.0
- Companion code: code/ch19_sglang/
- Companion code: code/ch18_vllm/
- Chapter 19: SGLang-TorchTPU
- Chapter 20: llm-d 1.0 on GKE: routing, disaggregation, KV management
- Chapter 23: Correctness: parity gates and numerical checks