Diagnosis and evaluation: profiling, roofline math, observability and trade-offs¶
Related chapters
Section 4.1 is chapter 10 (with the guide Capture and read an XProf trace), 4.2 is chapter 2, chapter 17 and chapter 24, 4.3 is chapter 11, and 4.4 is chapter 21 with the llm-d observability guide. In the trade-offs part, 5.1 is chapter 4 and chapter 11, 5.2 is chapter 13 and chapter 14, 5.3 is chapter 20 with the P/D disaggregation and precise prefix cache routing guides, 5.4 is chapter 21 with the autoscaling and startup guides, and 5.5 is chapter 23, chapter 24 and chapter 26. Every PromQL query on this page names only metrics that the llm-d 1.0 documentation defines.
Performance profiling, roofline math, diagnostics and observability¶
This part breaks training and serving execution down into measurable hardware, compiler, memory, network and scheduling bottlenecks, using XProf hardware traces, roofline arithmetic, diagnostic decision trees, and two-tier Prometheus/OpenTelemetry observability.
4.1 TPU profiling workflows (torch.profiler, XProf, TensorBoard and server profiling)¶
In one sentence: On Cloud TPU, Python-side timing is decoupled from asynchronous device execution (every eager mode and compiled mode dispatches asynchronously), so accurate performance analysis requires capturing synchronized host+device XPlane traces (
.xplane.pb) annotated with semantic trace scopes (torch.profiler.record_function, or vLLM-TorchTPU'sTraceAnnotationin the serving engine) and inspecting them in XProf to correlate Python dispatch, XLA HLO fusions, MXU/VPU utilization, and VMEM/HBM allocations.
Trace capture and the XPlane pipeline¶
Both tracers write into one XPlane file per rank, and XProf opens the whole run directory with every rank in it; merge_xplane is only for tools that take a single file. The Python tracer is off unless you set python_tracer_level=1.
1. The torch_tpu profiling API and step/scope annotations¶
A. torch.profiler.profile with TpuProfilerConfig, and Ironwood counter sampling¶
Sources: Performance profiling with XProf, TorchTPU API Reference, profiler_config.py
Info
Environment Prerequisites & Overhead: Native torch.profiler TPU integration requires PyTorch >= 2.12 and pip install "setuptools<81" xprof tensorboard (tensorboard relies on pkg_resources removed in setuptools >= 81). Profiling adds ~5–10% per-step overhead during active training steps and +11% TTFT / -4% throughput during vllm bench serve --profile; restrict active capture to a few steady-state steps (3 to 5 is a good start; chapter 10 explains when to capture more).
import pathlib
import torch
from torch.tpu.profiler import TpuProfilerConfig # Experimental API
# 1. Standard host/device/python tracer configuration (the defaults are the XLA ones)
tpu_prof_cfg = TpuProfilerConfig(
run_dir=pathlib.Path("./profiler_output"), # Where .xplane.pb files land
host_tracer_level=2, # 0=off, 1=user TraceMe events, 2=+XLA TraceMes (default), 3=+low-level XLA
device_tracer_level=1, # 0=off, 1=TPU device tracing (default)
python_tracer_level=0, # 0=off (default), 1=Python function tracing
worker_rank="0", # Suffix for the XPlane file name; not in the 0.2.0 documentation
)
# 1b. Ironwood (TPU v7 / v7x) Fine-Grained Kernel Performance Counter Sampling (1 us interval)
ironwood_counter_cfg = TpuProfilerConfig(
run_dir=pathlib.Path("./profiler_output_v7x"),
experimental_options={
"tpu_enable_periodic_counter_sampling": True,
"tpu_tc_perf_counter_sampling_options": (
"interval_us:1 scaling:0 counter_size_bits:1 "
"indices:10 indices:11 indices:56 indices:57 indices:58"
),
},
)
# 2. Wrap training/inference loop in scheduled torch.profiler.profile context
with torch.profiler.profile(
activities=[
torch.profiler.ProfilerActivity.CPU,
torch.profiler.ProfilerActivity.TPU,
],
schedule=torch.profiler.schedule(
wait=2, # Skip initial steps (XLA compilation & cache warmup)
warmup=1, # Warm up profiler buffers
active=3, # Record 3 steady-state steps into .xplane.pb
repeat=1, # Stop after 1 active cycle
),
on_trace_ready=torch.profiler.tensorboard_trace_handler("./log_dir"),
record_shapes=True,
profile_memory=True,
with_stack=True,
experimental_config=tpu_prof_cfg,
) as prof:
for step, batch in enumerate(dataloader):
# A named host range per step; the schedule also marks ProfilerStep#N ranges
with torch.profiler.record_function(f"train_step#{step}"):
with torch.profiler.record_function("forward_pass"):
loss = model(batch)
with torch.profiler.record_function("backward_pass"):
loss.backward()
with torch.profiler.record_function("optimizer_step"):
optimizer.step()
optimizer.zero_grad(set_to_none=True)
torch.accelerator.synchronize() # Keep while profiling: host ranges end at dispatch otherwise
prof.step()
Note
TpuProfilerConfig takes host_tracer_level, device_tracer_level, python_tracer_level, run_dir, worker_rank, experimental_options and check_experimental_options; the level descriptions above follow the class docstring in profiler_config.py. Label steps with torch.profiler.record_function and synchronize with torch.accelerator.synchronize(), as chapter 10 and the Performance profiling with XProf guide do.
B. Annotation primitives (torch_tpu and vllm_torchtpu)¶
| Annotation Primitive | Import Path & Signature | XProf Trace Emission & Key-Value Format | Best Use Case |
|---|---|---|---|
record_function |
torch.profiler.record_function("label") |
Standard PyTorch Kineto range annotation on the host timeline | Portable step and region markers across CPU/GPU/TPU codebases; the one chapter 10 uses |
TraceAnnotation (vLLM-TorchTPU) |
vllm_torchtpu.tracing.annotation.TraceAnnotation(name, **kwargs) |
Formats name#key1=val1,key2=val2# and opens a torch.profiler.record_function with that name, only while a profiler session is active |
Attaching runtime metadata (uuid, request_id, num_tokens) to serving timelines |
named_scope (TorchTPU, internal) |
torch_tpu._internal.profiler.named_scope (internal module in 0.2.0, not public API) |
Tags the TPU ops themselves with a scope name | Attributing compiled ops back to model regions |
Note
TraceAnnotation exists only in vLLM-TorchTPU, where it wraps torch.profiler.record_function; TorchTPU's named_scope is in an internal module (chapter 10).
2. Viewing options and XProf tools¶
Sources: Performance profiling with XProf, vLLM-TorchTPU profiling guide (viewing, output), tpu-agent-suite/package/skills/decompose-optimization/SKILL.md
A. Four ways to view a trace (TensorBoard XProf, standalone xprof, Perfetto, Cloud Profiler)¶
| Viewing Tool | Artifact Consumed | Launch Command / Workflow | Strengths & Primary Use Case |
|---|---|---|---|
| 1. TensorBoard + XProf Plugin | plugins/profile/<ts>/rank<N>_<host>.xplane.pb |
tensorboard --logdir=/tmp/vllm_profile --port=6006 --bind_all(SSH tunnel: ssh -N -L 6006:localhost:6006 <user>@<tpu-vm>) |
Full XProf suite (overview_page, trace_viewer, op_profile, memory_viewer, graph_viewer, hlo_stats). |
2. Standalone xprof Server |
Local ./profiler_output or GKE GCS bucket gs://<bucket>/profiler_output |
xprof --logdir=./profiler_output --port=6006or xprof --logdir=gs://<bucket>/profiler_output --port=6006 |
Directly reads GCS buckets written via GKE Cloud Storage FUSE CSI driver (gke-gcsfuse/volumes: "true") without local TensorBoard wrapper. |
3. Perfetto UI (ui.perfetto.dev) |
rank_<N>/<host>_<pid>.pt.trace.json.gz (Kineto Chrome trace) |
Open https://ui.perfetto.dev in browser \(\rightarrow\) drag-and-drop .pt.trace.json.gz |
Fast client-side inspection of CPU/Python host dispatch, PyTorch operator stacks, and async_llm frontend threads (no TPU HLO/MXU lanes). |
4. Programmatic XPlane / DuckDB (tpu-agent-suite) |
A benchmark job's XProf capture | The decompose-optimization skill runs scripts/decompose-optimization/inventory.py and q.py (DuckDB, pandas) and joins them with scripts/roofline-analysis/roofline.py |
A ranked list of operators, each with a diagnosed root cause; the skill marks every roofline number as modelled, not measured. |
B. XProf tool tabs (http://localhost:6006/#profile)¶
| XProf Tool Tab | Primary Analytical Question Answered | Key Metrics & Visual Signals | Red Flags & Immediate Diagnostic Action |
|---|---|---|---|
overview_page |
What is the average step time, FLOPs utilization, and high-level bottleneck category? | Step Time Breakdown (Compute ms vs Input ms vs Collective ms vs Host Idle ms); MXU Utilization %; Device Duty Cycle % | High Host Idle / Input %: Host-bound Python dispatch or dataloader starvation \(\rightarrow\) inspect trace_viewer host threads. |
trace_viewer |
How do host Python calls, XLA launches, DMA transfers, and TPU TensorCore ops align in wall-clock time? | Multi-lane timeline: Host Threads (TraceAnnotation / record_function), TPU TensorCore (Steps, XLA Modules, XLA Ops, Framework Name Scope), TPU SparseCore, ICI/Offload DMAs |
Gaps between device kernels: Host dispatch overhead or .item()/.cpu() sync barriers.Long copy-start/copy-done: Unaligned layout relayout ((8, 128) padding missing). |
op_profile & hlo_stats |
Which HLO operator categories (fusion, convolution, custom-call, all-reduce) consume the most time and what is their Roofline efficiency? |
Ranked tree of HLO ops by % Total Time, FLOPs Utilization %, Memory Bandwidth Utilization %, and Operational Intensity (FLOPs/Byte) |
High % Time + Low FLOPs% + Low MemBW%: Unfused elementwise chain, VPU-bound cast/layout op, or unaligned tile dimensions. |
memory_viewer |
Where does peak HBM allocation occur during the compiled XLA program, and which buffers cause OOM or fragmentation? | Timeline curve of Peak Heap Allocation (GiB) vs Unpadded Allocation + ranked table of largest live HLO buffers (parameter, temporary, output) |
Large gap between Padded and Unpadded size: Tensor inner dimensions not divisible by (8, 128) \(\rightarrow\) large tile padding waste. |
graph_viewer |
Why did XLA fuse (or refuse to fuse) specific ops, and where were layout conversion (copy) or collective nodes inserted? |
Interactive visual DAG of lowered HLO / LLO instructions around a selected target op (search by HLO op name from op_profile / trace_viewer) |
bitcast-convert / copy / pad before dot_general: Compiler inserted layout relayout; fix input tensor shapes/dtypes upstream. |
Note
TorchTPU's Performance profiling with XProf guide documents four views (Overview, Trace Viewer, Op Profile, Memory Profile), and the vLLM-TorchTPU guide says the Op Profile and Memory Profile cover MXU utilization and HBM usage. The full tool list, including Graph Viewer, Memory Viewer and HLO Op Stats, is in the XProf documentation. Column names vary by XProf version; read the XLA Ops row of the Trace Viewer for what actually ran (chapter 10).
3. vLLM-TorchTPU and SGLang-TorchTPU profiling modes¶
Sources: vLLM TorchTPU profiling, Offline profiling with examples/tpu_profiling.py, Server-side capture (vllm serve), vLLM TorchTPU phased profiling, Disaggregated serving (Prefill/Decode with Raiden3), vLLM TorchTPU profiling output layout, vLLM TorchTPU profiling troubleshooting
| Profiling Mode | Target Workload | Key CLI Flags & Environment Variables | Trigger Mechanism | Output Structure |
|---|---|---|---|---|
| 1. Offline Profiling | Single-script kernel / model bring-up (vllm.LLM or examples/tpu_profiling.py) |
VLLM_TORCH_PROFILER_DIR=/tmp/vllm_profile (or profiler_config in EngineArgs); examples/run_profiling_suite.sh |
warm-up llm.generate(...) \(\rightarrow\) llm.start_profile(...) \(\rightarrow\) llm.generate(...) \(\rightarrow\) llm.stop_profile() |
<dir>/plugins/profile/<ts>/rank<N>_<host>.xplane.pb + rank_<N>/<host>_<pid>.pt.trace.json.gz (plus batch_composition_stats_<timestamp>.json per profiled step with USE_PHASED_PROFILER=true) |
| 2. Server HTTP Profiling | Live OpenAI server under benchmark load (vllm serve / sglang.launch_server) |
--profiler-config.profiler torch --profiler-config.torch_profiler_dir /tmp/vllm_profile --profiler-config.ignore_frontend true (CAPTURE_PROFILE=1 in run_benchmarks.sh) |
vllm bench serve --profile or manual POST /start_profile (accepts JSON profile_prefix & profiler_kwargs) / POST /stop_profile |
<dir>/[<profile_prefix>/]plugins/profile/<ts>/rank<N>_<host>.xplane.pb |
| 3. Phased Profiling | Continuous batching servers where Prefill & Decode interleave | USE_PHASED_PROFILER=true + --attention-backend CUSTOM + --profiler-config.max_iterations 15 + --profiler-config.delay_iterations 0 + --additional-config '{"phased_profiler_decode_only_kv_len_threshold": N, "phased_profiler_prefill_only_kv_len_threshold": M}' |
Automatic per-step classification inside TPUModelRunner.execute_model() using get_batch_composition_stats (\(r = T_{\text{prefill}} / T_{\text{scheduled}}\)); stops each phase after max_iterations |
5 phase subdirectories under <torch_profiler_dir>/:prefill_only/, prefill_heavy/, balanced/, decode_heavy/, decode_only/ |
| 4. Disaggregated P/D (Raiden3) Profiling | Multi-host Prefill + Decode pools with TPURaidenConnector |
TPU_USE_RAIDEN_KV_CACHE_MANAGER=1, TPU_KV_RESHARD_TRANSPORT=raiden, TPU_RAIDEN_RESHARD_IMPL=store, USE_PHASED_PROFILER=true |
Simultaneous POST /start_profile on Prefill (kv_producer) and Decode (kv_consumer) pods; correlate via shared uuid in TraceAnnotation |
Separate prefill/ (prefill_only) & decode/ (decode_only) .xplane.pb trees on shared GCS/Filestore |
Recipe A: offline sweep (examples/tpu_profiling.py) and server HTTP profiling with hardware and firmware options¶
# 1A. Offline CLI Profiler (Warmup -> Start Profile -> Timed Iters -> Stop Profile)
python examples/tpu_profiling.py \
--model Qwen/Qwen3-0.6B --input-len 256 --output-len 1 \
--batch-size 8 --num-iters-warmup 3 --num-iters 1 \
--profile-result-dir /tmp/tpu_prof_out
# 1B. Launch vLLM Server with Frontend CPU Trace Suppressed (--profiler-config.ignore_frontend true)
vllm serve Qwen/Qwen3-32B \
--tensor-parallel-size 4 \
--attention-backend CUSTOM \
--profiler-config.profiler torch \
--profiler-config.torch_profiler_dir /tmp/vllm_profile \
--profiler-config.ignore_frontend true
# 2. Trigger Server Profiling with Dynamic Per-Session Hardware/SparseCore/Firmware Options
# (Parsed by src/vllm_torchtpu/tracing/options.py; also supports semicolon string in profile_prefix)
curl -X POST http://localhost:8000/start_profile \
-H "Content-Type: application/json" \
-d '{
"profile_prefix": "decode_fw_trace",
"profiler_kwargs": {
"host_tracer_level": 3,
"device_tracer_level": 1,
"python_tracer_level": 1,
"tpu_trace_mode": "TRACE_COMPUTE_AND_SYNC",
"tpu_num_sparse_cores_to_trace": 2,
"tpu_num_sparse_core_tiles_to_trace": 4,
"e2e_enable_fw_throttle_event": true,
"e2e_enable_fw_power_level_event": true,
"e2e_enable_fw_thermal_event": true
}
}'
# 3. Drive workload (or let `vllm bench serve --profile` call /start_profile and /stop_profile automatically;
# in CI/benchmarking, set `CAPTURE_PROFILE=1 PROFILE_NUM_PROMPTS=32 ./scripts/vllm/benchmarking/run_benchmarks.sh ...`)
vllm bench serve --model Qwen/Qwen3-32B --num-prompts 32 --request-rate 8
curl -X POST http://localhost:8000/stop_profile
Recipe B: phased profiling, five-bucket classification and KV-length threshold gating¶
In continuous batching, a single capture mixes prefill and decode steps. Setting USE_PHASED_PROFILER=true (with --attention-backend CUSTOM so batched-RPA Pallas kernels execute rather than FLASH_ATTN) classifies each execute_model step via get_batch_composition_stats using the prefill token ratio \(r = \text{prefill\_tokens} / \text{total\_scheduled\_tokens}\) (note: speculative decoding draft tokens count as decode, not chunked prefill):
Every engine step is classified by its prefill share r. A step in one of the two gaps never starts a capture, but a capture already running records the next max_iterations steps whatever their share (15 when it is not set). Each phase is captured once per profiling session.
| Phase Bucket Subdirectory | Prefill Ratio Condition (\(r\)) | Optional Delay / KV-Length Gate |
|---|---|---|
decode_only/ |
\(r = 0.0\) (decode_tokens == total_scheduled_tokens) |
phased_profiler_decode_only_kv_len_threshold: N (skips steps until the batch's minimum KV length reaches \(N\); both thresholds default to -1, disabled) |
decode_heavy/ |
\(0.0 < r \le 0.2\) | --profiler-config.delay_iterations N skips first \(N\) decode_heavy steps |
balanced/ |
\(0.4 \le r \le 0.6\) | n/a |
prefill_heavy/ |
\(0.9 \le r < 1.0\) | n/a |
prefill_only/ |
\(r = 1.0\) (prefill_tokens == total_scheduled_tokens) |
phased_profiler_prefill_only_kv_len_threshold: M (skips steps until the batch's minimum KV length reaches \(M\)) |
(Uncaptured: ambiguous) |
\(0.2 < r < 0.4\) or \(0.6 < r < 0.9\) | Never starts a capture; a capture already running still records these steps |
Each captured phase records max_iterations steps (--profiler-config.max_iterations, 15 when it is not set) and is captured once per profiling session.
Recipe C: cross-host disaggregated P/D trace correlation (TPURaidenConnector)¶
When profiling Disaggregated Serving across a Prefill pool (kv_role="kv_producer") and a Decode pool (kv_role="kv_consumer"), TPURaidenConnectorWorker emits four exact TraceAnnotation scopes carrying a shared transfer uuid:
All four scopes carry the same transfer uuid, so searching each host's trace for that uuid finds the same request on both. The decode host's Submit_Load to Recv_Complete span is the transfer, which Recv_Complete records as reshard_e2e_latency_ms; the producer's Send_Complete comes once the pull has completed.
KV_Cache_Prefill_Register_Blocks, prefill host (kv_producer), withuuid,request_id,num_tokens,num_blocks: Registers KV cache HBM blocks with the Raiden manager after prefill forward pass.KV_Cache_Decode_Submit_Load, decode host (kv_consumer), withuuid,request_id,source_req_id,num_tokens,num_blocks: Schedules asynchronous KV pull from producer.KV_Cache_Decode_Recv_Complete, decode host, withuuid,request_id,source_req_id,num_tokens,reshard_e2e_latency_ms: Fired when KV blocks land in Decode HBM, recording the time since the load was submitted, in ms (reshard_e2e_latency_ms).KV_Cache_Prefill_Send_Complete, prefill host, withuuid,request_id,num_tokens: Marks completion and release of the producer's KV blocks after the consumer's pull completes.
Recipe D: output directory layout and multi-rank XPlane deduplication (merge_xplane)¶
/tmp/vllm_profile/
└── [<phase_or_profile_prefix>/]
├── <phase>_<ts>.xplane.pb (1)
├── plugins/
│ └── profile/
│ └── 2026_10_28_14_22_05/ (2)
│ ├── rank0_tpu-vm-0.xplane.pb (3)
│ ├── rank1_tpu-vm-0.xplane.pb
│ └── ...
├── rank_0/
│ ├── batch_composition_stats_<timestamp>.json (4)
│ └── tpu-vm-0_12345.1729512125.pt.trace.json.gz (5)
└── rank_1/
└── ...
- Output of
python -m vllm_torchtpu.tools.merge_xplane, written to the phase directory, outsideplugins/profile/<ts>/. - Run timestamp created by rank 0; the other ranks wait up to 5 s for its marker file, so a multi-host run needs a shared directory.
- The
rank<N>_prefix appears when the slice-global TP × PP × DP is greater than 1. - Phased runs only (
USE_PHASED_PROFILER=true): one file per profiled step, named with that step's own timestamp, not the run's. - Kineto CPU and Python trace; open it in ui.perfetto.dev.
# Deduplicate redundant /host:metadata planes across TP ranks (the guide's example: 20 planes -> 17 on a v6e TP=4 run, 50% smaller overall).
# Not needed for `xprof --logdir`, which already reads the whole session directory:
python -m vllm_torchtpu.tools.merge_xplane /tmp/vllm_profile/decode_only
# WARNING: Never put a merged file inside plugins/profile/<ts>/ alongside per-rank files, or XProf will double-count every TPU core.
4. Profiling troubleshooting and environment pitfalls¶
| Symptom / Error Message | Root Cause | Command / Code Fix |
|---|---|---|
ModuleNotFoundError: No module named 'pkg_resources' |
setuptools >= 81 removed pkg_resources, which tensorboard requires |
pip install "setuptools<81" xprof tensorboard |
TensorBoard shows "No profile data was found" |
Pointed --logdir directly at a .xplane.pb file instead of the parent directory containing plugins/profile/<timestamp>/ |
Pass the directory above plugins/profile/ to tensorboard --logdir <dir> or xprof --logdir <dir> |
Legacy additional_config['phased_profiling_dir'] is no longer supported |
Removed legacy config key in vllm-torchtpu |
Set USE_PHASED_PROFILER=true and pass --profiler-config.profiler torch --profiler-config.torch_profiler_dir <DIR> |
USE_PHASED_PROFILER is set but there is nowhere to write traces |
USE_PHASED_PROFILER=true set without configuring torch_profiler_dir |
Pass --profiler-config.torch_profiler_dir /tmp/vllm_profile (or VLLM_TORCH_PROFILER_DIR=/tmp/vllm_profile) |
did not find rank 0's canonical-ts marker ... within 5.0s |
Multi-host workers writing to node-local /tmp instead of a shared filesystem, or rank 0 stalled |
Point --profiler-config.torch_profiler_dir to a shared NFS/Filestore or GCS FUSE mount across all hosts in the slice |
Phased profiler prefill_only or decode_only folder never appears |
Workload concurrency/request rate never produces a pure \(r=1.0\) or \(r=0.0\) step, or KV threshold is too high | Lower --request-rate for decode_only, burst concurrent prompts for prefill_only, or lower phased_profiler_*_kv_len_threshold |
| MoE expert routing skew distorts kernel profiling | Unbalanced token-to-expert routing on random/synthetic prompts skews GMA/all-to-all timings | Set VLLM_MOE_ROUTING_SIMULATION_STRATEGY=uniform_random (profiling only: never enable in accuracy evals) |
4.2 Roofline analysis, MFU and serving latency/throughput equations¶
In one sentence: Every neural network operation and serving system is governed by four physical ceilings, Compute FLOPs, HBM Memory Bandwidth, Inter-Chip Interconnect (ICI/DCN) Bandwidth, and HBM/Host KV Cache Capacity, which we formalize below via Roofline equations, MFU/HFU formulas, KV cache byte-sizing identities, and Little's Law concurrency bounds.
The TPU roofline and ridge point (\(\mathcal{R}_{\text{ridge}}\))¶
Each rule is a chip's ridge, its peak bf16 FLOP/s over its HBM bandwidth: an operation left of it is memory-bound on that chip. The page's M = 16 decode matmul is far left on every generation, the M = 4,096 prefill matmul is right of every ridge, and only between 166 and 560 does the answer depend on the chip.
Elementwise ops (norms, softmax, RoPE, casts) run on the VPU, whose roof is far below the MXU's (55.8 bf16 TFLOPS per v7x die in the TPU Agent Suite's model, last row of the table below). For the 8,192 x 8,192 projection of the worked example, a prefill matmul is compute-bound on every generation from \(M = 1{,}024\) (intensity 819); at \(M = 512\) its intensity of 455 is still below v6e's ridge of 560. The ridges use perflab's peaks (v5e 240.5, drawn as 241); under the TPU Agent Suite's derated constants, v7x's ridge is 265 instead of 313.
1. Operational intensity (\(\mathcal{I}\)), ridge point (\(\mathcal{R}_{\text{ridge}}\)) and hardware specifications¶
Roofline equations¶
Let an operation (or full model step) perform \(F\) floating-point operations while transferring \(B_{\text{HBM}}\) bytes to/from HBM and \(B_{\text{ICI}}\) bytes over Inter-Chip Interconnect. Its Arithmetic (Operational) Intensity \(\mathcal{I}\) and Theoretical Roofline Execution Time \(T_{\text{roofline}}\) are:
- If \(\mathcal{I}_{\text{HBM}} < \mathcal{R}_{\text{ridge}}\), the operation is Memory-Bandwidth Bound (\(T_{\text{mem}} > T_{\text{compute}}\); optimize via operator fusion, quantization
FP8/INT4, or larger batch size). - If \(\mathcal{I}_{\text{HBM}} > \mathcal{R}_{\text{ridge}}\), the operation is Compute Bound (\(T_{\text{compute}} > T_{\text{mem}}\); optimize via \((8, 128)\) MXU tile alignment,
DEFAULTBF16 matmul precision, or FP8 MXU execution).
Roofline constants by generation (v4 \(\rightarrow\) v7x)¶
Sources: torch_tpu/perflab/target.py, tpu_hardware.cc, tpu-agent-suite/package/scripts/roofline-analysis/roofline.py, the book's hardware reference
| TPU Generation | Cores / Chip (PyTorch Device Mapping) | Peak BF16 TFLOPS | Peak FP8 / INT8 TFLOPS | HBM Capacity | HBM Bandwidth (\(\beta_{\text{HBM}}\)) | BF16 Ridge Point (\(\mathcal{R}_{\text{ridge}}^{\text{BF16}}\)) | FP8 Ridge Point (\(\mathcal{R}_{\text{ridge}}^{\text{FP8}}\)) | VMEM / Core & ICI Topology (\(\beta_{\text{ICI}}\) One-Way) |
|---|---|---|---|---|---|---|---|---|
| TPU v4 | 2 TensorCores / chip (1 PyTorch device/chip) | 275 TFLOPS/chip |
Not listed | 32 GiB / chip |
1,200 GB/s / chip |
229.2 FLOPs/B |
n/a | 3D Torus (45 GB/s link) |
TPU v5e (v5litepod) |
1 TensorCore / chip (1 PyTorch device/chip) | 197 TFLOPS/chip |
Not listed | 16 GiB / chip |
819 GB/s / chip |
240.5 FLOPs/B |
n/a | 2D Torus (45 GB/s link) |
| TPU v5p | 2 TensorCores / chip (1 PyTorch device/chip) | 459 TFLOPS/chip |
Not listed | 95 GiB / chip |
2,765 GB/s / chip |
166.0 FLOPs/B |
n/a | 3D Torus (90 GB/s link) |
| TPU v6e (Trillium) | 1 TensorCore / chip (1 PyTorch device/chip) | 918 TFLOPS/chip |
918 TFLOPS/chip (fp8 at the bf16 rate) |
32 GiB / chip |
1,638 GB/s / chip |
560 FLOPs/B |
560 FLOPs/B |
256×256 MXU; 2D Torus (90 GB/s link) |
TPU v7x (Ironwood: Official Spec in perflab / torchtitan) |
2 Chiplets (Dies) / package (each die is one PyTorch device) | 1,153.5 TFLOPS/die( 2,307 TFLOPS/chip) |
2,307 TFLOPS/die( 4,614 TFLOPS/chip) |
96 GiB / die( 192 GiB / chip) |
3,690 GB/s / die( 7,380 GB/s / chip) |
313 FLOPs/B |
625 FLOPs/B |
64 MiB TC VMEM + 8 MiB SparseCore VMEM; D2D 600 GB/s; 3D Torus (90 GB/s link) |
TPU v7x (Pinned Analytical Constants in roofline.py) |
1 Die (tpu7x per-core effective ceiling) |
892.809 TFLOPS (MXU)55.8 TFLOPS (VPU BF16)13.95 TFLOPS (VPU FP32) |
1,785.62 TFLOPS (MXU FP8) |
96.0 GiB / die |
3,364.9 GB/s / die |
265.3 FLOPs/B |
530.7 FLOPs/B |
vmem_bytes = 8.0 MiB (SparseCore limit); d2d_bw = 600 GB/s; ici_bw = 80 GB/s |
Info
Dual-Die Device Mapping on TPU v7x (Ironwood): Unlike TPU v4 and v5p (which fuse 2 TensorCores into 1 logical device), TPU v7x exposes each of its 2 TensorCores, each with its own HBM, as an independent PyTorch device. Consequently, a 4-chip TPU v7x host presents 8 PyTorch devices (perflab's v7_2x2x1 platform runs 8 processes per host). The TPU Agent Suite's model gives the two devices of a chip a 600 GB/s die-to-die (D2D) link, while cross-chip links are ICI at 80–90 GB/s one way. Use 1,153.5 TFLOPS (perflab's per-device peak) or 892.8 (the agent suite's analytical constant, which is a different convention: say which) per PyTorch device when computing per-device MFU on TPU v7x.
Note
The figures follow chapter 1, chapter 2 and the hardware reference; perflab's target.py gives bf16 peaks per device, and TorchTPU's tpu_hardware.cc the device identities. llm-d's Google Cloud TPU provider page gives v6e fp8 at the bf16 rate, so its fp8 ridge equals its bf16 ridge. For VMEM size, query pltpu.get_tpu_info().vmem_capacity_bytes (chapter 12).
Worked example: matmul \([M, K] \times [K, N]\) roofline on TPU v6e and v7x¶
Consider a BF16 linear projection \(Y = X W\) where \(X \in \mathbb{R}^{M \times K}\) (BF16, \(2\text{ B}\)), \(W \in \mathbb{R}^{K \times N}\) (BF16, \(2\text{ B}\)), and \(Y \in \mathbb{R}^{M \times N}\) (BF16, \(2\text{ B}\)) with hidden sizes \(K = 8192, N = 8192\):
- FLOPs: \(F = 2 M K N = 2 \cdot M \cdot 8192 \cdot 8192 = 1.342 \times 10^8 \cdot M\text{ FLOPs}\).
- HBM Bytes Transferred: \(B_{\text{HBM}} = 2(MK + KN + MN)\text{ Bytes}\). When \(K, N \gg M\), \(B_{\text{HBM}} \approx 2KN = 134.2\text{ MB}\) (weight-streaming dominated), so \(\mathcal{I}_{\text{HBM}} \approx M\text{ FLOPs/Byte}\).
-
Decode Batch (\(M = 16\) tokens): $\(\mathcal{I}_{\text{HBM}} = \frac{2 \cdot 16 \cdot 8192^2}{2(16 \cdot 8192 + 8192^2 + 16 \cdot 8192)} = \frac{2.147 \times 10^9}{1.347 \times 10^8} = \mathbf{15.94\text{ FLOPs/Byte}}\)$
- On TPU v6e (\(\mathcal{R}_{\text{ridge}}^{\text{BF16}} \approx 560\)): \(\mathcal{I}_{\text{HBM}} \ll 560 \implies\) Strictly Memory-Bandwidth Bound (\(15.94 / 560 = \mathbf{2.85\%}\) max MXU utilization). Switching weights from BF16 to FP8 (\(1\text{ B}\)) halves \(B_{\text{HBM}}\) to \(67.6\text{ MB}\), doubling \(\mathcal{I}_{\text{HBM}}\) to \(31.7\text{ FLOPs/B}\) and cutting latency in half.
-
Prefill Batch (\(M = 4096\) tokens): $\(\mathcal{I}_{\text{HBM}} = \frac{2 \cdot 4096 \cdot 8192^2}{2(4096 \cdot 8192 + 8192^2 + 4096 \cdot 8192)} = \frac{5.498 \times 10^{11}}{2.684 \times 10^8} = \mathbf{2,048\text{ FLOPs/Byte}}\)$
-
On both TPU v6e (\(\mathcal{R}_{\text{ridge}}^{\text{BF16}} \approx 560\)) and TPU v7x (\(\mathcal{R}_{\text{ridge}}^{\text{BF16}} \approx 313\)): \(\mathcal{I}_{\text{HBM}} > \mathcal{R}_{\text{ridge}} \implies\) Strictly Compute Bound (\(T_{\text{compute}} = 549.8\text{ GFLOPs} / 918\text{ TFLOPS} = \mathbf{0.599\text{ ms}}\) on v6e).
2. Model FLOPs utilization (\(\text{MFU}\)) and hardware FLOPs utilization (\(\text{HFU}\))¶
Sources: torch_tpu/perflab/flops.py, torch_tpu/perflab/metrics.py, torch_tpu/perflab/target.py
A. Per-layer forward and backward FLOPs¶
Given batch size \(B\), sequence length \(S\), hidden size \(D\), intermediate FFN size \(I\), query heads \(H_q\), KV heads \(H_{kv}\), head dimension \(d_h = D / H_q\), layers \(L\), and vocabulary size \(V\):
- Attention Linear Projections (\(Q, K, V, O\)) Forward FLOPs per Layer: $\(F_{\text{proj, fwd}} = 2 B S D \cdot (H_q d_h + 2 H_{kv} d_h + D) = 4 B S D^2 \left(1 + \frac{H_{kv}}{H_q}\right)\)$
- Self-Attention Score & Context MatMuls (\(Q K^\top\) and \(P V\)) Forward FLOPs per Layer:
- Full Self-Attention: \(F_{\text{attn, fwd}} = 4 B S^2 H_q d_h\) (Note: causal masking computes half the triangle mathematically, i.e., \(2 B S^2 H_q d_h\) effective FLOPs in FlashAttention/Pallas
ragged_paged_attention, while dense unmasked matmul counts \(4 B S^2 H_q d_h\)). - Sliding-Window Attention (Window \(W < S\)): \(F_{\text{swa, fwd}} = 4 B S W H_q d_h\).
- MLP / MoE Feed-Forward Network Forward FLOPs per Layer:
- Dense SwiGLU MLP (3 matrices:
gate_proj,up_proj,down_proj): $\(F_{\text{mlp, fwd}}^{\text{SwiGLU}} = 6 B S D I\)$ - Sparse Mixture-of-Experts (MoE) with \(K_{\text{act}}\) Active Routed Experts + \(N_{\text{shared}}\) Shared Experts + \(E_{\text{tot}}\) Router: $\(F_{\text{moe, fwd}} = 2 B S D E_{\text{tot}} + 6 B S D \left(K_{\text{act}} I_{\text{moe}} + N_{\text{shared}} I_{\text{shared}}\right)\)$
- LM Head Logits Forward FLOPs: $\(F_{\text{head, fwd}} = 2 B S D V\)$
- Total Training Step FLOPs (Forward + Backward) & \(\text{MFU}\) / \(\text{HFU}\):
- Standard No-Recompute (
MFUNumerator): Backward pass requires \(2\times\) the forward FLOPs (\(F_{\text{bwd}} = 2 F_{\text{fwd}}\)), so total model algorithmic FLOPs per step is: $\(F_{\text{model}} = 3 F_{\text{fwd}} = 3 \left[ L \left(F_{\text{proj, fwd}} + F_{\text{attn, fwd}} + F_{\text{mlp/moe, fwd}}\right) + F_{\text{head, fwd}} \right] \approx 6 N_{\text{active\_params}} B S + 6 L B S^2 H_q d_h\)$ - Full Activation Checkpointing (
HFUNumerator): Recomputing the forward pass during backward adds \(1\times F_{\text{fwd}}\), yielding \(F_{\text{hw}} = 4 F_{\text{fwd}}\). - Utilization Definitions across \(N_{\text{chips}}\) Accelerators with Step Duration \(\Delta t\) (seconds): $\(\text{MFU} = \frac{F_{\text{model}}}{N_{\text{chips}} \cdot \pi_{\text{peak}} \cdot \Delta t} = \frac{\text{Throughput (tokens/sec/chip)} \times (F_{\text{model}} / (B \cdot S))}{\pi_{\text{peak}}}, \qquad \text{HFU} = \frac{F_{\text{hw}}}{N_{\text{chips}} \cdot \pi_{\text{peak}} \cdot \Delta t}\)$
Worked example: Llama-3.1-70B training MFU on TPU v6e-64 (6N plus attention convention, hypothetical throughput)¶
- Model Config: \(N_{\text{params}} \approx 70.6 \times 10^9\), \(L = 80\), \(D = 8192\), \(H_q = 64\), \(H_{kv} = 8\), \(d_h = 128\), \(I = 28672\), \(V = 128256\), Sequence length \(S = 8192\).
- Per-Token Algorithmic Training FLOPs (\(F_{\text{model}} / (BS)\)): $\(\frac{F_{\text{model}}}{B S} = 6 N_{\text{params}} + 6 L S H_q d_h = 6(70.6 \times 10^9) + 6(80)(8192)(8192) = 423.6 \times 10^9 + 32.2 \times 10^9 = \mathbf{455.8\text{ GFLOPs/token}}\)$
- Measured Throughput: Suppose a 64-chip TPU v6e slice (\(\pi_{\text{peak}} = 918\text{ TFLOPS/chip}\)) achieves \(1,020\text{ tokens/sec/chip}\): $\(\text{MFU} = \frac{1,020\text{ tok/s/chip} \times 455.8 \times 10^9\text{ FLOPs/tok}}{918 \times 10^{12}\text{ FLOPs/s/chip}} = \frac{464.9\text{ TFLOPS}}{918\text{ TFLOPS}} = \mathbf{50.64\%}\)$ If full activation checkpointing is enabled (\(\text{HFU} \approx \frac{4}{3} \text{MFU}\)), then \(\text{HFU} = \mathbf{67.52\%}\).
Counting FLOPs
perflab counts FLOPs with PyTorch's torch.utils.flop_counter.FlopCounterMode on one eager step of a CPU fake copy. It counts matmuls, convolutions and SDPA, ignores causal masking in its attention formula, and gives ops without a formula (its docstring names _grouped_mm, the MoE expert matmuls) zero FLOPs. The decomposition above is an analytical convention, not perflab's counter, and an MoE's MFU from perflab reads far too low. Whichever convention you use (\(6N_{\text{active}}\), with or without the attention term, with or without recompute), write it down with the unit (per chip or per device) and the peak; perflab's peak is per device, 1,153.5 TFLOP/s on v7x (chapter 24, chapter 14, chapter 16). The 1,020 tokens per second per chip above is a hypothetical input, not a measurement.
3. KV cache sizing and the TPU 5D fused layout¶
A. KV cache bytes per token for five attention architectures¶
Let \(L\) be the number of layers, \(H_{kv}\) the number of KV heads, \(d_k\) the key head dim, \(d_v\) the value head dim (usually \(d_k = d_v = d_h\)), \(b_{\text{dtype}}\) the bytes per element (2 for BF16/FP16, 1 for FP8), and \(TP\) the Tensor Parallel degree (assuming \(H_{kv} \ge TP\)):
| Architecture Family | Per-Token KV Cache Formula (Total Across All Ranks) | Example Model & Parameters | KV Size per Token (BF16 vs FP8) |
|---|---|---|---|
| 1. Multi-Head Attention (MHA) (\(H_{kv} = H_q\)) | \(2 \cdot L \cdot H_q \cdot d_h \cdot b_{\text{dtype}}\) | An MHA model at Llama-2-70B's dimensions (\(L=80, H_q=64, d_h=128\)) |
2,621,440 B (2.50 MiB/tok) BF161.25 MiB/tok FP8The released Llama-2-70B uses GQA with 8 KV heads (Llama 2 paper), so its cache is 8x smaller: 320 KiB per token in BF16. |
| 2. Grouped-Query Attention (GQA) (\(H_{kv} \ll H_q\)) | \(2 \cdot L \cdot H_{kv} \cdot d_h \cdot b_{\text{dtype}}\) | Qwen/Qwen3-32B (\(L=64, H_{kv}=8, d_h=128\)) |
262,144 B (256 KiB/tok) BF16128 KiB/tok FP8 |
| 3. Multi-Head Latent Attention (MLA) (DeepSeek-V3 / R1) | \(L \cdot (d_c + d_R) \cdot b_{\text{dtype}}\) (Caches joint compressed latent \(c_t^{KV} \in \mathbb{R}^{d_c}\) + shared decoupled RoPE key \(k_t^R \in \mathbb{R}^{d_R}\) instead of \(2 H_{kv} d_h\)) |
DeepSeek-R1 / V3 (\(L=61, d_c=512, d_R=64\)) |
70,272 B (68.625 KiB/tok) BF1635,136 B (34.31 KiB/tok) FP8(~37\(\times\) smaller than MHA) |
| 4. Hybrid Sliding-Window (SWA) + Global Attention (Gemma-3 / GPT-OSS) | \(\left[ 2 L_{\text{full}} S + 2 L_{\text{swa}} \min(S, W_{\text{swa}}) \right] H_{kv} d_h b_{\text{dtype}}\) (for a sequence of length \(S\)) | Gemma-3-27B (5:1 SWA-to-Full ratio, \(W_{\text{swa}}=1024\)) at \(S=32768\) |
Reduces KV footprint at \(32\text{K}\) context by ~81% vs all-global GQA (\(1 - \frac{1}{6} - \frac{5}{6}\cdot\frac{1024}{32768}\) for an illustrative 5:1 ratio and 1,024-token window) |
5. Hybrid Linear Attention / Mamba-2 / Gated DeltaNet (GDN) (Qwen3.5-397B-A17B) |
Full-attn layers (\(L_{\text{full}}\)): \(2 L_{\text{full}} S H_{kv} d_h b_{\text{dtype}}\) Linear/GDN layers (\(L_{\text{lin}}\)): Constant O(1) per sequence \(= L_{\text{lin}} (H_v d_k d_v + d_{\text{conv}} K_{\text{conv}}) b_{\text{dtype}}\) |
Qwen3.5-397B-A17B (3:1 GDN-to-Full ratio) |
Linear layers allocate fixed-size recurrent state slots via TpuMambaPool; only 25% of layers scale with \(S\). |
B. Physical 5D fused KV cache layout and tile padding¶
On Cloud TPU, both vllm-torchtpu (ragged_paged_attention_v3) and sglang-torchtpu (TpuFusedMHATokenToKVPool) fuse Key and Value tensors along the head axis (K0, V0, K1, V1, ...) and pack pairs of tokens into 32-bit VMEM bank words to eliminate strided gather overhead and avoid \((8, 128)\) tile padding waste:
Warning
Critical TPU KV Padding Rule: Because the TPU TensorCore requires sublanes divisible by 8 and lanes divisible by 128, if \(2 \cdot H_{kv,\text{local}} < 8\) (e.g., \(H_{kv}=8\) sharded across \(TP=8 \implies H_{kv,\text{local}}=1 \implies 2 H_{kv,\text{local}} = 2\)), the hardware pads the head dimension from 2 up to 8 (\(4\times\) HBM capacity overhead) unless KV heads are replicated or ragged_paged_attention_v3 packs along the block dimension. Also, on TPU v6e (Trillium), llm-d's precise-prefix-routing overlay sets --block-size=256 (and the router's blockSizeTokens: 256) because --block-size=64 runs out of SMEM on TorchTPU; other llm-d paths use 64.
Kernel-specific shapes
The single 5D shape above simplifies the source. vLLM-TorchTPU's kernels each define their own get_kv_cache_shape: the batched ragged paged attention wrapper's shape depends on a KVLayout (HEAD_ALONG_SUBLANE by default, or SEQ_ALONG_LANE) and on a dtype-dependent packing factor from get_dtype_packing, not a fixed pair of tokens per 32-bit word, and the MLA kernels use a 4D (pages, page_size // packing, packing, kv_dim) shape. SGLang-TorchTPU has several pool classes (TpuFusedMHATokenToKVPool, TpuSeqAlongLaneKVPool, TpuBlockMajorMHATokenToKVPool). Read the shape function of the kernel you run before you size HBM from this formula (chapter 17).
4. Serving SLO equations and three-layer concurrency sizing (Little's law)¶
Sources: Benchmarking & Evaluation Guide, Tune Flow Control Concurrency, Scale on Token Backlog (Experimental)
A. Serving latency and goodput definitions¶
For request \(i\) arriving at \(t_{\text{arrive},i}\), emitting its first output token at \(t_{1,i}\), and emitting output tokens \(k = 1, \dots, O_i\) at timestamps \(t_{k,i}\):
Goodput
Goodput as defined above is the working definition of chapter 24, whose companion code implements it; the llm-d and vLLM-TorchTPU pages cited here do not define it. Do not confuse it with Google's ML Goodput Measurement library, which measures how much of a training job's chip time becomes preserved progress. NTPOT is the router's normalized time per output token (llm_d_epp_request_ntpot_seconds).
B. Three-layer concurrency sizing (tuning_wizard.py)¶
llm-d's Tune Flow Control Concurrency guide sizes concurrency in three layers with guides/flow-control/scripts/tuning_wizard.py:
- Layer 1, engine limit (
--max-num-seqs): the active batch is \(N_{\text{active}} = \min(\text{Compute\_Bound}, \text{Memory\_Bound})\). The compute bound comes from a step-load benchmark (mean throughput and mean latency at the highest stable stage before the SLO breach); the memory bound from the engine's KV blocks and the workload's sequence lengths. - Layer 2, EPP dispatch gate:
maxConcurrency\(= N_{\text{active}} + B\), a lookahead buffer above the engine limit, with peak \(N_{\text{peak}} = N_{\text{active}}(1 + \text{headroom})\). - Layer 3, gateway burst queue:
flowControl.maxRequestsandmaxBytes(the guide's example usesmaxRequests: 200andmaxBytes: "10Gi").
The guide's example run:
python3 guides/flow-control/scripts/tuning_wizard.py \
--throughput 12.5 \
--latency-sec 3.45 \
--gpu-blocks 21875 \
--block-size 16 \
--isl-mean 4000 \
--isl-std 1500 \
--osl-mean 800 \
--osl-std 300 \
--shared-prefix 3000 \
--enable-prefix-caching \
--z-score 2.0
Without arguments the script runs in an interactive mode. Use the limits it prints (chapter 21).
4.3 Bottleneck decomposition and diagnosis¶
In one sentence: When a TPU training or inference workload underperforms or crashes, first decide whether the pod runs at all, then classify the failure into one of the table's nine categories (recompilation, host-bound, MXU utilization, VMEM OOM, HBM OOM, collectives, startup and Kubernetes, disaggregation and KV, prefix cache), and apply the remediation mapped below.
Bottleneck decision flowchart¶
If the pod never becomes Ready or a step fails, read the error first; if steps run but miss the target, read the profile.
When the workload never gets going, the error text or the pod status names the fix: VMEM and HBM exhaustion, pod limits and probes, or ranks that dispatch different programs or put TP across DCN. Anything else is in the remediation table that follows.
Once steps run, the profile names the bottleneck; take the questions in order, because recompiles and host gaps also show up as low utilization. Serving problems that pass all four are in the KV-transfer and prefix-cache rows of the table.
1. Diagnosis and remediation table¶
Sources: TorchTPU execution model, TorchTPU and the TPU memory model, Dynamic shapes, Manage numerical precision in TorchTPU, TorchTPU distributed support, vllm-torchtpu Optimization Work Best Practices, Troubleshoot Model Startup
| # | Category | Observed Symptom | Root Cause | XProf / Log Signature | Remediation |
|---|---|---|---|---|---|
| 1 | Recompilation | Severe 5–30s latency spikes every few requests or training steps | Variable input sequence lengths or batch sizes trigger new XLA HLO compilations | TORCH_LOGS="recompiles" names the guard that failed; a counting backend or torch._dynamo counters show the compile count rising |
Bucket inputs to powers of 2 / multiples of 256, or call torch._dynamo.mark_dynamic(x, 0) before torch.compile (TorchTPU's bounded dynamism, chapter 7). |
| 2 | Recompilation | torch.compile recompiles every time a shape changes |
On TorchTPU an omitted dynamic means dynamic=False, so every new shape is a new static program |
Dynamo log: Recompiling function ... due to shape change |
Bucket shapes explicitly (preferred on TPU so XLA tunes static tile sizes), or annotate exact dynamic axes via mark_dynamic. |
| 3 | Recompilation | Recompilation on every decode step despite fixed tensor shapes | Passing Python int/float counters (e.g., step_idx, rope_offset) that change value every step |
Dynamo guards fail on scalar constant specialization | Wrap changing scalars into 0D/1D device tensors (torch.tensor([step], device="tpu")) or pre-slice from a preallocated buffer. |
| 4 | Recompilation | Silent recompilation regression introduced in CI/PR | Unintended graph break or shape specialization in model code | Caught by torch.compiler.set_stance("fail_on_recompile") after warmup |
Set the stance in CI tests after warmup (SGLang-TorchTPU's platform does this once warmup has compiled every bucket); fix the offending guard or graph break. |
| 5 | Host-Bound | TPU duty cycle < 40%; large empty gaps between device kernels in trace_viewer |
Mid-step .item(), print(tensor), .cpu(), or boolean masking x[x > 0] drains the stream (and in DeferAndFuse or compiled mode forces a graph break) and blocks Python on device completion |
trace_viewer shows the host waiting (aten::item, aten::_local_scalar_dense) at the start of each gap while the TPU sits idle |
Eliminate mid-step .item()/.cpu() calls; replace dynamic boolean masks with fixed-shape torch.where(mask, x, 0). |
| 6 | Host-Bound | High per-step host overhead in eager training | Eager modes pay Python dispatch on every op; strict eager also launches one executable per op (microbubbles below the roughly 50 µs enqueue cost) | overview_page shows high Host Idle %; many short TPU bursts with gaps |
Wrap model in torch.compile(model, backend="tpu"), try DeferAndFuse (TORCH_TPU_DEFER_AND_FUSE=1), or use SingleTraceTrainer (torch.tpu.optimizers, Experimental) / TpuGraphTrainer to trace the whole step. |
| 7 | Host-Bound | Decode TPOT degraded during metadata preparation | Allocating new small index/mask tensors on TPU inside the decode loop (torch.arange(..., device="tpu")) |
trace_viewer shows many tiny H2D transfers before execute_model |
Precompute constant index/position tables during warmup, assemble dynamic metadata in pinned CPU buffers, and copy asynchronously. |
| 8 | Recompilation | SGLang KV page bookkeeping changes device tensor shapes | A free-page list held as a device tensor shrinks at page boundaries and triggers recompiles | New compiles at page boundaries in the server log | Use TpuPagedTokenToKVPoolAllocator, which keeps the free-page list on the CPU. |
| 9 | MXU Util | op_profile shows dot_general taking about \(3\times\) or \(6\times\) longer than expected |
torch.set_float32_matmul_precision("high") or "highest" runs 3-pass or 6-pass BF16 decompositions of FP32 matmuls |
Matmul time about 3x or 6x the single-pass estimate | Cast inputs to torch.bfloat16, or use the default "medium" (Precision.DEFAULT, one MXU pass) via torch.set_float32_matmul_precision or the torch.tpu.precision(...) context manager. |
| 10 | MXU Util | op_profile shows high copy / pad overhead and low MXU utilization |
Tensor contraction/feature dimensions are not multiples of the 128 tile (256 is safe across generations) | Shapes in the op's details against the tile; pad or copy ops you did not write |
Pad vocabulary size, hidden dimensions, LoRA ranks, and expert token buckets to multiples of 128 (or 256), and pay for the padding at weight-loading time (P-14). |
| 11 | MXU Util | Attention or MoE layer dominated by dozens of small elementwise kernels | Unfused PyTorch eager ops (rms_norm, rotary_embedding, paged_attention, moe_gating) |
op_profile lists many small VPU/memory-bound fusions |
Use the fused Pallas kernels the engines ship: ragged_paged_attention (v3), fused_moe, megablox grouped matmul; fuse to avoid HBM round trips (P-8). |
| 12 | MXU Util | for i in range(num_experts): or for b in range(batch): loop runs slowly on TPU |
Python for loops unroll into large HLO graphs with poor MXU occupancy and long compile times |
Huge HLO instruction count; low per-op arithmetic intensity | Vectorize into batched torch.bmm or a grouped matrix multiply (megablox); for repeated layers, scan (compile.use_scan_layers in TorchTitan). |
| 13 | VMEM OOM | Pallas kernel fails to compile with a VMEM out-of-memory error | Pallas kernel BlockSpec tiles + pipelined scratch buffers exceed VMEM (64 MiB per TensorCore on v7x) |
Compiler error naming the VMEM memory space | Shrink BlockSpec block dimensions, reduce buffering stages, and quantize or dequantize per loop iteration inside the kernel rather than the full matrix (P-7). |
| 14 | HBM OOM | RESOURCE_EXHAUSTED out of HBM during training |
Peak live activations + gradients + optimizer states exceed device HBM (16–96 GiB) |
Memory Profile shows the peak crossing the HBM ceiling during backward | Enable activation checkpointing, use scan_backward_patch.py with scanned layers, or shard via FSDP2/SimpleFSDP (chapter 14). |
| 15 | HBM OOM | HBM OOM during vLLM / SGLang server initialization or long-context burst | KV cache + compiled XLA programs + weight padding exceed available HBM | Crash during KV-cache sizing or warmup | Lower --gpu-memory-utilization (e.g., 0.85), cap --max-model-len / --max-num-seqs, or quantize weights. |
| 16 | Collectives | Multi-slice / multi-host training hangs or runs \(10\times\) slower than single-slice | DeviceMesh places Tensor Parallelism (TP) across slow DCN links and FSDP across fast ICI links |
trace_viewer shows all-gather / reduce-scatter taking hundreds of milliseconds over DCN |
Build the rank order with torch.tpu.distributed.topology_aware_mesh(...) and pass it to DeviceMesh("tpu", mesh=...) so replicate (DDP) spans DCN, shard (FSDP) spans ICI, and tp spans the fastest inner axis (chapter 13). |
| 17 | Collectives | SPMD multi-host hang where one rank executes a different program order | Non-deterministic Python dict iteration or divergent control flow across ranks | Process hangs at a collective launch | Enforce deterministic op ordering across all ranks. Mark known-SPMD functions with @torch.tpu.distributed.spmd_safe, or enable the compilation handshake (TORCH_TPU_SPMD_HANDSHAKE_STAGE=COMPILE_STAGE or DISPATCH_STAGE), which checks that compiled graphs match across ranks before fusing collectives. |
| 18 | Collectives | High all-gather / reduce-scatter exposed time in TP or FSDP layers |
Collectives execute sequentially with MXU MatMuls without overlap | trace_viewer shows MXU idle while an ICI collective executes |
In TorchTitan, enable the libtpu flag bundles in tpu_flags.py: SPARSECORE_LATENCY_HIDING_SCHEDULER, ICI_AG_PIPELINING, HIERARCHICAL_REDUCE_SCATTER (libtpu 0.0.47+), SPARSECORE_COLLECTIVE_OFFLOAD; Async TP is parallelism.enable_async_tensor_parallel. These bundles are Python dicts of xla_tpu_* flags applied to LIBTPU_INIT_ARGS. |
| 19 | Startup / K8s | Model server pod killed mid-load (Exit Code 137 / 143, CrashLoopBackOff) |
startupProbe budget (failureThreshold * periodSeconds) is shorter than weight download + XLA compile time |
kubectl describe pod shows Startup probe failed \(\rightarrow\) Killing container |
Increase the startupProbe budget and persist the compile caches (VLLM_XLA_CACHE_PATH and TorchTPU's tier-3 cache, as the Recipes page sets them) plus HF_HOME. |
| 20 | Startup / K8s | Multi-replica scale-out fails with HTTP 429 Too Many Requests, ReadTimeoutError, or Xet chunk stall from hf.co; or Permission denied on pre-populated PVC |
Concurrent replicas downloading shards simultaneously, Xet CAS proxy stall, or huggingface_hub writing .lock/metadata into a read-only PVC |
Container logs show 429 Client Error, ReadTimeoutError, or OSError: [Errno 30] Read-only file system |
Stage weights in RWX PVC (/model-cache, mounted readOnly: true) while pointing HF_HOME: /tmp/hf-cache to a writable emptyDir; set HF_HUB_DOWNLOAD_TIMEOUT="60", HF_HUB_ETAG_TIMEOUT="60", and test HF_HUB_DISABLE_XET="1" if Xet stalls. |
| 21 | Startup / K8s | vLLM / P2P KV cache pod crashes with Bus error (core dumped) |
Default Kubernetes /dev/shm (64 MiB) exhausted by pinned P2P / NCCL / Ray shared memory buffers |
Pod crashes with Bus error during KV / communicator init |
Mount an in-memory emptyDir (medium: Memory) at /dev/shm with sizeLimit \(> \text{CPU\_KV\_Tier}\) (e.g., 16Gi standard, 96Gi for 88Gi P2P KV tier). llm-d's P2P guide: size /dev/shm above cpu_bytes_to_use (the tier is an shm mmap) and the pod memory limit above both. |
| 22 | Startup / K8s | TorchTPU warns at import that tcmalloc is not the process allocator | The Python dispatch thread and the runtime's worker threads allocate and free across threads, which glibc malloc handles poorly |
TorchTPU's import-time check (_tcmalloc_check.py) warns when no tcmalloc is preloaded |
Export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libtcmalloc.so.4 before launching Python, as TorchTPU's Docker image does. |
| 23 | Disagg / KV | Disaggregated decode requests fail or fall back to local prefill under load | Prefill KV blocks expire before decode reads them (kv_lease_duration too short), or the KV transfer port is unreachable |
On NIXL (GPU) paths, vllm:nixl_num_kv_expired_reqs or vllm:nixl_num_failed_transfers rising; on TPU, the KV_Cache_* trace annotations of TPURaidenConnector |
Check the kv_port in --kv-transfer-config and network reachability, consider TPURaidenOffloadingConnector (llm-d's v7 overlay stages 64 GiB of prefill KV in host DRAM), and watch the router's llm_d_epp_disagg_decision_total. The TPU path uses Raiden, not NIXL. |
| 24 | Prefix Cache | Multi-pod prefix cache hit rate (vllm:prefix_cache_hits_total) drops to 0% |
Mismatched --block-size between engine and router, or a different Python hash() seed across pods |
Router predicts hits (llm_d_epp_prefix_indexer_hit_ratio high, or KV events arriving) but vllm:prefix_cache_hits_total stays flat |
Set PYTHONHASHSEED=0 on all model server pods and make engine --block-size (64, or 256 in llm-d's v6e overlay) match the router's blockSizeTokens. |
2. vLLM-TorchTPU optimization rules (PR-1–PR-4, P-1–P-17, Q-1–Q-7) and runtime patterns¶
Source: vllm-torchtpu Optimization Work Best Practices
A. vllm-torchtpu optimization best practices (PR-1..PR-4, P-1..P-17, Q-1..Q-7)¶
| Rule ID | Domain | vllm-torchtpu Rule (paraphrase) |
Concrete Verification / Code Pattern |
|---|---|---|---|
PR-1–PR-4 |
§0 PR Discipline | PR-1 Optimization PRs are tiny and describe the mechanism; perf PRs carry per-mode speedups (decode/prefill/mixed) and update CI perf thresholds in the same PR.PR-2 Revert fast on numeric issues; root-cause offline.PR-3 When porting code from another repo, state the source and what changed; version kernels (v2, v3), then deprecate the old one.PR-4 An honest Limitations section: unsupported shapes/configs, known perf gaps, follow-ups. |
Required in every optimization PR description. |
P-1–P-4 |
§1.1 Evidence: Traces, Not Guesses | P-1 XProf traces are the unit of evidence; an end-to-end number alone proves nothing, and a claimed hot-path no-op needs a trace at realistic (large) batch.P-2 Prove compiler impact from the compiled artifact (HLO dumps, graph viewer).P-3 Quantify trade-offs: scheduler changes report throughput and latency; extra rounding ops are measured for quality and speed.P-4 Parallelism A/Bs compare at matched global token budget; a win the mechanism does not predict is usually a batch-size artifact. |
XProf trace plus a mechanism explanation in the PR. |
P-5–P-6 |
§1.2 Let the Compiler Work | P-5 Shard via jit signatures (in_shardings/out_shardings) and the global mesh context, not manual reshard functions.P-6 Cast to bf16 before collectives when numerics tolerate it, and verify it like any dtype change. |
Compare HLO before and after. |
P-7–P-13 |
§1.3 Hardware Resources | P-7 VREG lifetime: quantize per loop iteration to avoid spills; no up-front zero-init accumulators; write results straight to out_ref on the last step.P-8 HBM traffic: avoid needless zero-initialization; fuse ops to avoid HBM round trips.P-9 MXU throughput: w8a16 beats w16a16; never silently upcast; ride 4-bit weights on the fp8 path; unpack with shifts and masks.P-10 SMEM: do not allocate the maximum; the compiler needs headroom.P-11 DMA: small DMAs are latency-bound; never start(); wait() back to back, pipeline with buffering.P-12 Layout is a first-class cost: fix interleaved splits by preprocessing weights at load time.P-13 Optimization barriers hide in innocuous constructs (jax.named_scope, lax.cond in the hot loop). |
Inspect XProf memory_viewer (VMEM/HBM), and trace_viewer (DMA overlap and TP/EP collectives). |
P-14–P-17 |
§1.4 Additional Considerations | P-14 Weight-loading time is where heavy tensor work belongs (dequantization, scale broadcasting, KV-head replication, transposes); call-time padding on the inference path needs trace proof.P-15 Every threshold should be computable from a cost model, with a code pointer to the derivation.P-16 Block sizes live in tuned tables inside the kernel directory (kernels/*/tuned_block_sizes.py), imported as Python data; misses log warning_once.P-17 Know each kernel's hard envelope (mesh rank, EP-only, dtype packing, JAX version range) and gate callers on it. |
megablox/tuned_block_sizes.py is one such table. |
Q-1–Q-7 |
§2 Quantization | Q-1 Build generic machinery: a format is a point in (block_size, weight_dtype, scale_dtype) space.Q-2 Recipe for a new method: config class, linear method, process_weights_after_loading reshaping, apply, a real-model unit test; home layers/adapter/quantization/.Q-3 Numeric verification is non-negotiable: before/after eval (e.g. MMLU/gsm8k) plus a serving benchmark on the identical rig.Q-4 Requantization is allowed when proven quality-neutral.Q-5 Track scale tensors independently of the weights they scale.Q-6 Memory validation: compare total_hbm_used_gb before and after, including a shape whose sharded last dim is not 128-divisible.Q-7 Dtype and scale choices are hardware-driven; use TPU-native stochastic rounding when requantizing at load. |
Validate with check_regression.py --mode eval and total_hbm_used_gb inspection. |
Rule IDs and texts follow the vLLM-TorchTPU optimization best practices page, as chapter 11 cites them.
B. Common runtime patterns¶
- Host-Side Decode Precomputation & Async H2D: Allocate static position/mask buffers during warmup (
__init__), build per-step ragged metadata in pinned CPU NumPy arrays, and transfer via.to(device, non_blocking=True). Keep KV page tables (TpuPagedTokenToKVPoolAllocator) on CPU and keep sampling (Top-K/Top-P/argmax) on TPU so only[batch, 1]token IDs cross PCIe. - Branchless Fixed-Shape Execution: Replace data-dependent
if tensor.any():or boolean indexingx[mask]withtorch.where(mask, x, 0), route attention through 5D fusedragged_paged_attention_v3, and route MoE throughmegablox_gmm/fused_moe.
3. Worked diagnostic scenarios¶
Illustrative scenarios
Both scenarios below are constructed, not measured: every latency, utilization, spill count and heap size in them is illustrative. The workflow (metrics, then traces, then a phased XProf capture, then a fix that names its mechanism) follows chapter 10, chapter 11 and chapter 21. In scenario 2 the uniform_random routing setting produces meaningless model output and is for profiling only; whether TPURaidenOffloadingConnector relieves this particular stall is a hypothesis to test.
Scenario 1 (illustrative numbers): tracing a P99 TTFT and TPOT spike¶
Each step uses one tool to narrow the search: metrics show the symptom, traces show the component, a phased profile shows the ops, and the fix names its mechanism. The numbers are the page's illustrative ones.
- Step 1, Triage via Tier-1 & Tier-2 PromQL (
:8000&:2112): - Run
[Q04]:vllm:time_to_first_token_secondsP99 spiked from0.40sto2.80sandvllm:inter_token_latency_secondsP99 rose from18msto54ms, whilevllm:num_preemptions_total([Q02]) is0andllm_d_epp_flow_control_queue_size([Q14]) is near zero. - Run
[Q07]/[Q08]on TPU exporter metrics:duty_cycle{make="cloud-tpu"}is98%(chips are busy), buttensorcore_utilization([Q07]) is only18%andmemory_bandwidth_utilization([Q08]) is89%\(\implies\) the TPU is stalled on HBM memory traffic / layout copies rather than host dispatch or queueing. - Step 2, Isolate the Component via W3C
traceparentDistributed Tracing (Jaeger :16686): - Query Jaeger for slow traces (
minDuration=2s). Thellm-d-router/eppservice's scheduling spans (run_scheduler_profile,scoring,pick_endpoints) take only1.2 ms, androuting-proxytakes0.4 ms, so the time is spent inside thevllm-decodepod. - Step 3, Capture Pure Phase XPlanes (
USE_PHASED_PROFILER=true): - Trigger
POST /start_profileon the target pod withUSE_PHASED_PROFILER=trueand--attention-backend CUSTOM, run 32 prompts, and callPOST /stop_profile. - Open
xprof --logdir=/tmp/vllm_profile/prefill_only, since a TTFT spike is prefill time and in a unified deployment namedvllm-decodeprefill runs in the same pod (or hand the capture to the TPU Agent Suite'sdecompose-optimizationskill):op_profilereveals38.4%of total step time is spent incopy/padHLO ops (Operational Intensity = 0.0 FLOPs/Byte) immediately precedingcustom-call(ragged_paged_attention_v3) anddot_general.memory_viewershows Peak Padded Heap =68.2 GiBvs Unpadded =41.0 GiB, and LLO compile logs show142 VREG spillsinside the attention kernel.
- Step 4, Apply Hardware-Aligned Remediation (
P-7,P-8,P-14,P-16): - Pad the non-128-divisible head/intermediate dimension once inside
process_weights_after_loading(P-14) so runtime tensors enterdot_generalandragged_paged_attention_v3pre-aligned to(8, 128)(P-8). - Reduce the Pallas kernel
BlockSpecblock_q/block_kvtile size in a dedicatedtuned_block_sizes.pycommit (P-16) to eliminate the142 VREG spills(P-7). - Result in this scenario (report it per mode, as
PR-1asks):copy/padoverhead drops from38.4%to< 0.8%,tensorcore_utilizationrises from18%to64%, TTFT P99 drops to0.38s, and TPOT P99 drops to14.2ms.
Scenario 2 (illustrative numbers): disaggregated P/D KV transfer stalls and multi-host MoE stragglers¶
- Step 1, Symptom in PromQL: Disaggregated TTFT P99 degrades under burst load ([Q04]) while the router's disaggregation share ([Q19]) holds, so requests are still being split. (On a GPU NIXL path,
sum(increase(vllm:nixl_num_kv_expired_reqs[5m]))rising ([Q13]) would point at expired KV leases; the TPU path usesTPURaidenConnectorand is read from its trace annotations instead.) - Step 2, Cross-Host XProf Correlation via
TPURaidenConnectoruuid: - Capture simultaneous phased traces on the Prefill pool (
prefill_only/) and Decode pool (decode_only/) writing to a shared GCS FUSE bucket (gs://my-profiles/disagg). - Search (
Ctrl+F) in XProftrace_viewerfor a slow request's transferuuid: inspect the gap betweenKV_Cache_Prefill_Register_Blocks\(\rightarrow\)KV_Cache_Prefill_Send_Completeon Prefill andKV_Cache_Decode_Submit_Load\(\rightarrow\)KV_Cache_Decode_Recv_Complete(reshard_e2e_latency_ms) on Decode. - Step 3, Isolate Multi-Rank Skew in
trace_viewer: - Comparing per-rank timelines in
trace_vieweron the Prefill slice shows Rank 3 taking2.4xlonger inmegablox_gmm/all-to-allthan Ranks 0–2 due to synthetic benchmark prompt token routing skew across MoE experts, delaying Rank 3'sKV_Cache_Prefill_Register_Blocks. - Step 4, Remediation:
- For synthetic kernel profiling, set
VLLM_MOE_ROUTING_SIMULATION_STRATEGY=uniform_randomto isolate true hardware collective performance from dataset skew; for production traffic, enableTPURaidenOffloadingConnector(64 GiBhost DRAM buffer on prefill pods) so finished prefill ranks immediately free HBM blocks without waiting on decode pull contention.
4.4 Production observability, golden signals and PromQL¶
In one sentence: Production observability in
llm-dand TorchTPU unifies 5 telemetry planes, EPP Router & Disagg Sidecars (:9090/metrics), Model Servers (:8000/metrics), Cloud TPU Hardware (:2112/metrics& GKEkubernetes.io/container/accelerator/*), Batch Gateway ({namespace="batch-gateway"}), and OpenCost (:9003/metrics), into a Two-Tier Triage Workflow (Tier 1 Saturation/SLO Alerts \(\rightarrow\) Tier 2 Subsystem Drill-Down) backed by W3Ctraceparentdistributed tracing and the llm-d Grafana dashboards.
Telemetry planes and two-tier triage¶
Start with the Tier 1 queries, which say that something is wrong, then drill down in Tier 2 and in the request traces to find where. The Batch Gateway's metrics carry no prefix, so they are selected by namespace rather than by a port.
1. Prometheus metrics by telemetry plane¶
Sources: Router Metrics, Model Server Metrics, Batch Gateway Metrics, Monitor GKE TPUs, Track Inference Cost, Collect Metrics
| Telemetry Plane & Scrape Port | Subsystem | Key Prometheus Metric Names | Type | Key Labels & Critical Operational Notes |
|---|---|---|---|---|
1. EPP Router (:9090/metrics, K8s SA Bearer Token auth) |
Request & Latency | llm_d_epp_request_total, llm_d_epp_request_error_total, llm_d_epp_request_duration_seconds, llm_d_epp_request_ttft_seconds, llm_d_epp_request_ntpot_seconds, llm_d_epp_request_streaming_tpot_seconds, llm_d_epp_request_streaming_itl_seconds, llm_d_epp_request_input_tokens, _output_tokens, _cached_tokens, llm_d_epp_request_running |
Counter / Histogram / Gauge | Labels: model_name, target_model_name, error_code. Measures true router-edge latency including queue wait. |
1. EPP Router (:9090/metrics) |
Inference Pool, Scheduler & ThunderAgent | llm_d_epp_ready_endpoints, llm_d_epp_average_kv_cache_utilization, llm_d_epp_average_queue_size, llm_d_epp_inflight_requests, llm_d_epp_inflight_tokens, llm_d_epp_scheduler_e2e_duration_seconds, llm_d_epp_plugin_duration_seconds, llm_d_epp_thunder_agent_sessions, _endpoint_working_set_tokens, _endpoint_capacity_tokens |
Gauge / Histogram | Labels: inference_pool, endpoint, plugin_type, plugin_name, target_pod. inflight_tokens drives Token-Aware KEDA; thunder_agent_* tracks multi-turn agent working-set tokens vs HBM capacity. |
1. EPP Router (:9090/metrics) |
Flow Control & Program-Aware Fairness | llm_d_epp_flow_control_queue_size, _queue_bytes, llm_d_epp_flow_control_request_queue_duration_seconds, llm_d_epp_flow_control_pool_saturation, llm_d_epp_flow_control_requests_total, _revocations_total, llm_d_epp_program_aware_jains_fairness_index, _avg_wait_time_milliseconds, _attained_service_tokens |
Gauge / Histogram / Counter | Labels: inference_pool, priority (100, 0, -10), flow_key, outcome, program_id. jains_fairness_index \(\in [0, 1]\) measures multi-tenant scheduling fairness. |
1. EPP Router (:9090/metrics) |
Precise KV Index, ZMQ Events & Latency Predictor | llm_d_epp_prefix_indexer_hit_ratio, llm_d_epp_kv_cache_index_admissions_total, _index_evictions_total, _index_lookup_requests_total, _index_lookup_hits_total, _index_max_pod_hit_count_total, _index_lookup_latency_seconds, llm_d_epp_kv_cache_events_active_subscribers, _events_subscriber_reconnections_total, _events_messages_received_total, _events_zmq_errors_total, _events_stores_skipped_total, _events_removals_skipped_total, _events_pool_queue_depth, _events_pool_capacity, llm_d_epp_request_predicted_ttft_seconds, _predicted_tpot_seconds, _slo_violation_total |
Gauge / Counter / Histogram | Alert when a pod's llm_d_epp_kv_cache_events_messages_received_total rate is zero while it serves traffic, or _events_zmq_errors_total rises; a _events_pool_queue_depth that keeps growing against _events_pool_capacity means the index lags the model servers. |
| 1. EPP Router / Disagg Planes | Disagg Sidecar, MoRI-IO DNS & Coordinator | Sidecar: llm_d_disagg_sidecar_requests_total, _disagg_requests_total, _encode_duration_seconds, _prefill_duration_seconds, _decode_duration_seconds, _request_errors_totalDNS: moriio_dns_reresolve_total, _ip_changed_total, _lookup_failures_totalCoordinator: llm_d_coordinator_request_total, _request_error_total, _request_duration_seconds, _step_duration_seconds, _step_errors_total, _step_running, _upstream_request_total, _execution_path_total, _conditional_decode_probes_total, _encode_subrequests, _orchestration_overhead_seconds, _media_items, _media_download_duration_seconds |
Counter / Histogram / Gauge | Tracks multimodal encode \(\rightarrow\) prefill \(\rightarrow\) decode phase latencies, conditional decode probes (outcomes served, deferred, error, transport_error), and MoRI-IO peer DNS re-resolution. |
2. Model Server (:8000/metrics; SGLang --enable-metrics; TRT-LLM /prometheus/metrics) |
Core Serving (vllm:* / sglang:*) |
vllm:num_requests_running (sglang:num_running_reqs), vllm:num_requests_waiting (sglang:num_queue_reqs), vllm:kv_cache_usage_perc (sglang:token_usage), vllm:num_preemptions_total, vllm:time_to_first_token_seconds, vllm:inter_token_latency_seconds, vllm:prefix_cache_hits_total / _queries_total |
Gauge / Counter / Histogram | vllm:num_preemptions_total rate must be 0 in steady state; non-zero means KV cache thrashing/recomputation. |
2. Model Server (:8000/metrics) |
P/D Disaggregation (NixlConnector) |
vllm:nixl_xfer_time_seconds, vllm:nixl_post_time_seconds, vllm:nixl_bytes_transferred, vllm:nixl_num_descriptors, vllm:nixl_num_failed_transfers, vllm:nixl_num_kv_expired_reqs |
Histogram / Counter | NIXL is the GPU transport; TPU P/D uses TPURaidenConnector. TP caveat: histogram observations are pooled across TP ranks, so their counts are rank-level transfers, not requests. vllm:nixl_num_kv_expired_reqs is recorded on the prefill instance; rising values suggest kv_lease_duration is too short. |
2. Model Server (:8000/metrics) |
Tiered KV Offload (vLLM OffloadingConnector / SGLang HiCache) |
vllm:external_prefix_cache_hits_total / _queries_total, vllm:kv_offload_store_bytes_total, vllm:kv_offload_load_bytes_total, vllm:kv_offload_load_time_total, vllm:kv_offload_allocation_failure_total, vllm:kv_offload_cpu_cache_usage_perc; sglang:hicache_host_used_tokens / _total_tokens, sglang:load_back_duration_seconds |
Counter / Gauge / Histogram | Caveat: vllm:kv_offload_cpu_cache_usage_perc is the fraction of the CPU tier pinned by in-flight transfers, NOT total CPU cache occupancy. |
3. Cloud TPU Exporter & GKE GCM (GKE TPU device plugin :2112/metrics; scrape job kube-system/tpu-metrics-exporter) |
GKE Cloud TPU Hardware (make="cloud-tpu" & GCM native) |
Prometheus Exporter (:2112): Always-on: tensorcore_utilization (0–100%), memory_bandwidth_utilization (0–100%). Runtime-dependent: duty_cycle (0–100%), memory_used (B), memory_total (B)GKE Cloud Monitoring Native: kubernetes.io/container/accelerator/tensorcore_utilization, .../memory_bandwidth_utilization, .../duty_cycle, .../memory_used, .../memory_total (GKE system metrics) |
Gauge | Label Caveat: the TPU recipe's PodMonitor keeps honorLabels: false, so conflicting exporter labels become exported_pod and exported_namespace; the model label is the TPU type, not the served LLM. Never sum *_node series with workload series. |
4. Batch Gateway ({namespace="batch-gateway"}) |
API, Queue Processor & GC | http_requests_total, jobs_processed_total (result="success\|failed\|skipped\|re_enqueued\|expired"), job_queue_wait_duration_seconds, job_processing_duration_seconds, batch_job_e2e_latency_seconds, active_workers, total_workers, processor_inflight_requests, batch_reconciler_errors_total, file_storage_operations_total |
Counter / Histogram / Gauge | Unprefixed Metric Caveat: Always filter by {namespace="batch-gateway"} so queries do not aggregate unrelated cluster services. |
5. OpenCost Exporter (:9003/metrics in llm-d-monitoring) |
Inference Cost & Cache ROI | llm_total_hourly_cost, llm_cost_per_million_tokens, llm_cache_savings_fraction |
Gauge | Labels: cost_basis (allocation | usage), phase ("" | prompt | generation), allocation_method: compute_time (split by prefill/decode time), prefix_caching_off (time-based split when prefix caching is disabled), multiplier (fixed 2.5x ratio when timing metrics are missing). |
2. PromQL queries¶
Sources: PromQL reference, Monitor GKE TPUs, Alerting, Track Inference Cost, Router metrics, Batch Gateway metrics, SLO-aware autoscaling, Token-aware autoscaling
Replace llm-d in the namespace selectors with your namespace, and inspect the live series' labels before you copy a selector. Windows are fixed at 5m (or the 1m the SLO-aware design uses) so each query runs as written in the Prometheus UI; in Grafana you may substitute $__rate_interval.
# ==============================================================================
# TIER 1: FAILURE, SATURATION & SLO BREACH TRIAGE (FIRST-RESPONDER QUERIES)
# ==============================================================================
# [Q01] EPP Error Ratio with Low-Volume Traffic Floor (0/0-safe, avoids startup flapping)
(
sum(rate(llm_d_epp_request_error_total[5m]))
/
clamp_min(sum(rate(llm_d_epp_request_total[5m])), 1e-9)
) and (sum(rate(llm_d_epp_request_total[5m])) > 1)
# [Q02] vLLM KV Cache Preemption Rate (Must be 0 req/s in healthy steady state)
sum by (namespace, pod) (rate(vllm:num_preemptions_total[5m]))
# [Q03] End-to-End Request Latency P99 at EPP Router
histogram_quantile(0.99, sum by (le, model_name) (rate(llm_d_epp_request_duration_seconds_bucket[5m])))
# [Q04] Engine TTFT P99 & Inter-Token Latency (ITL) P99
histogram_quantile(0.99, sum by (le, model_name) (rate(vllm:time_to_first_token_seconds_bucket[5m])))
histogram_quantile(0.99, sum by (le, model_name) (rate(vllm:inter_token_latency_seconds_bucket[5m])))
# [Q05] Multi-Pool Per-Pool EPP Metrics Absence Detection (Fires if ANY individual pool vanishes)
llm_d_epp_ready_endpoints offset 15m unless llm_d_epp_ready_endpoints
# [Q06] EPP Scheduler E2E Decision Latency P99 & Per-Plugin Breakdown P99
histogram_quantile(0.99, sum by (le) (rate(llm_d_epp_scheduler_e2e_duration_seconds_bucket[5m])))
histogram_quantile(0.99, sum by (le, plugin_type, plugin_name) (rate(llm_d_epp_plugin_duration_seconds_bucket[5m])))
# ==============================================================================
# TIER 2: CLOUD TPU HARDWARE UTILIZATION & ROOF-LINE DIAGNOSTICS (GKE)
# ==============================================================================
# [Q07] Cloud TPU TensorCore Utilization (%) by Workload Pod (`model` is the TPU type)
avg by (exported_namespace, exported_pod, model) (
tensorcore_utilization{job="kube-system/tpu-metrics-exporter", make="cloud-tpu"}
)
# [Q08] Cloud TPU HBM Memory Bandwidth Utilization (%) per Chip (Primary Decode Signal)
avg by (exported_pod, accelerator_id) (
memory_bandwidth_utilization{job="kube-system/tpu-metrics-exporter", make="cloud-tpu"}
)
# [Q09] Cloud TPU HBM Capacity Utilization Fraction (runtime-dependent series; absent is not zero)
sum by (exported_namespace, exported_pod) (memory_used{make="cloud-tpu"})
/
sum by (exported_namespace, exported_pod) (memory_total{make="cloud-tpu"})
# ==============================================================================
# TIER 2: PREFIX CACHING, TIERED KV OFFLOAD, P/D & FLOW CONTROL
# ==============================================================================
# [Q10] vLLM HBM vs External/CPU Tier Prefix Cache Hit Ratios
sum(rate(vllm:prefix_cache_hits_total[5m])) / sum(rate(vllm:prefix_cache_queries_total[5m]))
sum(rate(vllm:external_prefix_cache_hits_total[5m])) / sum(rate(vllm:external_prefix_cache_queries_total[5m]))
# [Q11] Tiered KV Offload Load Rate per Pod (MiB/s) & Load Speed (MiB per second of load time)
sum by (pod) (rate(vllm:kv_offload_load_bytes_total[5m])) / 1048576
sum by (pod) (rate(vllm:kv_offload_load_bytes_total[5m])) / sum by (pod) (rate(vllm:kv_offload_load_time_total[5m])) / 1048576
# [Q12] SGLang Host HiCache Occupancy Fraction & ZMQ KV Event Errors per Pod
sum by (pod) (sglang:hicache_host_used_tokens) / sum by (pod) (sglang:hicache_host_total_tokens)
sum by (pod_identifier) (rate(llm_d_epp_kv_cache_events_zmq_errors_total[5m]))
# [Q13] P/D Disaggregation NIXL KV Transfer P95 Latency (ms) & Expired Prefill KV Requests (GPU NIXL paths)
histogram_quantile(0.95, sum by (le) (rate(vllm:nixl_xfer_time_seconds_bucket[5m]))) * 1000
sum(increase(vllm:nixl_num_kv_expired_reqs[5m]))
# [Q14] EPP Flow Control Queue Depth, Queue Wait P99 & Pool Saturation
sum by (priority) (llm_d_epp_flow_control_queue_size)
histogram_quantile(0.99, sum by (le, priority) (rate(llm_d_epp_flow_control_request_queue_duration_seconds_bucket[5m])))
avg by (inference_pool) (llm_d_epp_flow_control_pool_saturation)
# ==============================================================================
# TIER 2: BATCH GATEWAY, AUTOSCALING SIGNALS & OPENCOST INFERENCE COST
# ==============================================================================
# [Q15] Batch Gateway Per-Pod P95 Queue Wait & Worker Saturation Ratio
histogram_quantile(0.95, sum by (le, pod) (rate(job_queue_wait_duration_seconds_bucket{namespace="batch-gateway"}[5m])))
active_workers{namespace="batch-gateway"} / total_workers{namespace="batch-gateway"}
# [Q16] SLO-Aware Raw Saturation s_raw = max(P90 TTFT / 3 s, P90 TPOT / 100 ms), clamped at 2
# max() is an aggregation, so the two ratios are joined with `or` after label_replace gives them distinct labels
clamp_max(
max(
label_replace(histogram_quantile(0.90, sum by (le) (rate(llm_d_epp_request_ttft_seconds_bucket{namespace="llm-d"}[1m]))) / 3, "slo", "ttft", "", "")
or
label_replace(histogram_quantile(0.90, sum by (le) (rate(llm_d_epp_request_streaming_tpot_seconds_bucket{namespace="llm-d"}[1m]))) / 0.1, "slo", "tpot", "", "")
),
2
)
# [Q17] Token-Aware Autoscaler Prefill Backlog in Seconds (In-Flight Tokens / Calibrated V_P)
# 15928 is the guide's Qwen3-32B H100 TP=2 reference; calibrate V_P on your TPU serving path
sum(llm_d_epp_inflight_tokens{namespace="llm-d", producer_name="inflight-load-producer"}) / 15928
# [Q18] OpenCost Cost per Million Generated Tokens & Fraction of Prompt Tokens Served from Cache
llm_cost_per_million_tokens{phase="generation", cost_basis="allocation"}
llm_cache_savings_fraction
# [Q19] Share of Requests the EPP Disaggregated (Prefill-Decode)
sum(rate(llm_d_epp_disagg_decision_total{decision_type="prefill-decode"}[5m])) / sum(rate(llm_d_epp_disagg_decision_total[5m]))
Note
Every metric name above is in the llm-d 1.0 documentation (PromQL Query Reference, Router Metrics). Prometheus max is an aggregation, so Q16 joins the two ratios with or, as chapter 21's Q21 does, over the 1-minute bucket rates the SLO-aware design uses (the guide smooths the result over 45 s in a recording rule and prefers the predicted histograms). Q12 counts ZeroMQ subscriber errors. prefix_caching_off is the allocation method used when prefix caching is disabled, not a counterfactual, so Q18 reads the generated-token cost and llm_cache_savings_fraction directly.
3. PrometheusRule alerts, inference cost and W3C distributed tracing¶
A. Inference cost attribution (OpenCost :9003/metrics)¶
llm-d's Track Inference Cost page defines three gauges, llm_total_hourly_cost, llm_cost_per_million_tokens and llm_cache_savings_fraction, with an allocation_method label: compute_time splits cost by vLLM prefill and decode time; prefix_caching_off is a time-based split used when prefix caching is disabled; multiplier is a fixed 2.5x ratio used when timing metrics are missing. Read these gauges directly (Q18 above).
B. PrometheusRule alert summary (epp-alerting-rules.yaml and batch-gateway-alerting-rules.yaml)¶
| Rule Group | Alert Name | Severity | Expression / Condition | Window | Actionable Remediation |
|---|---|---|---|---|---|
epp.availability |
EPPHighErrorRatio / EPPCriticalErrorRatio |
warning / critical |
Error ratio > 0.05 (10m) / > 0.20 (5m) |
10m / 5m |
Inspect error_code label (model_server_error vs upstream timeout). |
epp.availability |
EPPNoReadyEndpoints / EPPMetricsAbsent |
critical |
llm_d_epp_ready_endpoints == 0 / absent(...) |
2m / 5m |
Check model server pod crashes or ServiceMonitor scrape auth failure. |
epp.selfhealth |
EPPDataLayerPollErrors / EPPExtProcStreamErrors |
warning |
llm_d_epp_datalayer_poll_errors_total increasing / llm_d_epp_extproc_streams_total{code!~"OK\|Canceled"} increasing |
10m |
Verify --enable-grpc-stream-metrics on EPP and Envoy \(\leftrightarrow\) EPP gRPC health. |
batch-gateway.rules |
BatchGatewayHighQueueWait / WorkersSaturated |
warning |
P95 queue wait > 300s / active_workers / total_workers > 0.90 |
15m |
Raise NumWorkers or add batch processor replicas. |
batch-gateway.rules |
BatchGatewayHighJobFailureRate / ExpiredJobsDetected |
warning |
Failed jobs > 10% / Expired jobs > 3% (clamp_min safe) |
10m |
Check S3/PVC file_storage_operations_total{status="exhausted"} or widen SLO window. |
C. W3C traceparent OpenTelemetry tracing (EPP \(\rightarrow\) routing-proxy \(\rightarrow\) vLLM)¶
Source: Trace Requests
# 1. Model Server (vllm-prefill / vllm-decode) Container Args & Env
args:
- --otlp-traces-endpoint=http://otel-collector:4317
- --collect-detailed-traces=all
env:
- name: OTEL_SERVICE_NAME
value: "vllm-decode" # Set "vllm-prefill" on prefill pool
- name: OTEL_EXPORTER_OTLP_ENDPOINT
value: "http://otel-collector:4317" # On GKE: http://opentelemetry-collector.gke-managed-otel.svc.cluster.local:4317
- name: OTEL_TRACES_SAMPLER
value: "parentbased_traceidratio" # Mandatory so all child P/D spans inherit EPP sampling decision.
- name: OTEL_TRACES_SAMPLER_ARG
value: "0.1" # 10% in production; use "1.0" in dev/benchmarking
# 2. Extract Per-Span Latency Percentiles from the Jaeger REST API (the UI's scatter plot shows root-trace duration)
kubectl port-forward -n ${NAMESPACE} svc/jaeger-collector 16686:16686 &
curl -s "http://localhost:16686/api/traces?service=llm-d-router%2Fepp&limit=500" \
| jq '[.data[].spans[] | select(.operationName=="run_scheduler_profile") | .duration / 1000] | sort |
{count: length, p50_ms: .[length*50/100 | floor], p99_ms: .[length*99/100 | floor]}'
Note
llm-d's tracing page port-forwards svc/jaeger-collector, names the router's service llm-d-router/epp, and lists its spans as request, request_orchestration, run_scheduler_profile, filter_endpoints, scoring, pick_endpoints, tokenize and llm_request; span durations are in microseconds. It suggests 5% sampling (0.05, the router values' default) or 10% to bound tracing cost.
4. Scraping setup (ServiceMonitor / PodMonitor / GKE GMP) and Grafana dashboards¶
Sources: Set Up the Monitoring Stack, Use Grafana Dashboards, Google Kubernetes Engine (GKE)
A. Scraping on GKE Managed Prometheus (GMP), OpenShift and upstream Kubernetes¶
- OSS Stack (
guides/recipes/observability/install-prometheus-grafana.sh): Installs Prometheus and Grafana into thellm-d-monitoringnamespace (--enable-tlsfor HTTPS, which the setup guide says some autoscalers require, such as the deprecated WVA). Skip it if Prometheus already runs in the cluster or on OpenShift User Workload Monitoring. - Model Server Scraping:
kubectl apply -n ${NAMESPACE} -k guides/recipes/modelserver/components/monitoringcreatesPodMonitor(monitoring.coreos.com/v1) resources for vLLM and SGLang/metrics(monitoring-pdadds the prefill pods under P/D). - EPP Router Scraping: Layer
guides/recipes/router/features/monitoring.values.yamlwhen installing the router Helm chart; it creates the EPPServiceMonitor(epp-servicemonitor). The EPP's/metricssits behind Kubernetes ServiceAccount token authentication. - GKE Managed Prometheus (GMP) & Automatic Application Monitoring (
--auto-monitoring-scope=ALL): - GKE clusters include GMP, so no Prometheus install is needed. Automatic application monitoring generates
PodMonitoringresources (monitoring.googleapis.com/v1, distinct from CoreOSPodMonitormonitoring.coreos.com/v1) for vLLM and SGLang model servers, not for the EPP; layer the router's GKE monitoring values for the EPP. - For TPU hardware metrics, follow the llm-d TPU recipe, which scrapes the GKE TPU device plugin's
:2112/metrics(jobkube-system/tpu-metrics-exporter,honorLabels: false). - OpenShift User Workload Monitoring: Queries go to
thanos-querier.openshift-monitoring.svc.cluster.local:9091with bearer authentication and a ServiceAccount bound to thecluster-monitoring-viewClusterRole (as the token-aware autoscaling recipe configures for KEDA).
Note
The steps above follow llm-d's setup, metrics and dashboards pages. Dashboards load with ./guides/recipes/observability/load-llm-d-dashboards.sh (ConfigMaps labelled grafana_dashboard=1 in llm-d-monitoring) or by importing the JSON files from guides/recipes/observability/grafana/dashboards/.
B. llm-d Grafana dashboards (guides/recipes/observability/grafana/dashboards/)¶
Dashboard ConfigMap Name (json/<name>.json) |
Tier & Scope | Primary Panels & Diagnostic Focus |
|---|---|---|
llm-d-vllm-overview |
Tier 1 (vLLM Engine) | Per-pod vLLM TTFT/TPOT/ITL P50/P95/P99, running/waiting queues, KV cache %, prefix cache hit rate, preemptions. |
llm-d-sglang-overview |
Tier 1 (SGLang Engine) | SGLang (sglang:*) throughput, TTFT/ITL, token_usage, RadixCache hit rate, HiCache host memory & load-back latency. |
llm-d-tpu-overview |
Tier 1/2 (Cloud TPU Hardware) | GKE Cloud TPU tensorcore_utilization, memory_bandwidth_utilization, duty_cycle, and HBM memory_used / memory_total by exported_pod. |
llm-d-failure-saturation-dashboard |
Tier 1 (Triage & Saturation) | Fleet-wide HTTP error ratios, KV preemptions, flow control queue saturation, P/D NIXL expired requests, and SLO violation counters. |
llm-d-diagnostic-drilldown-dashboard |
Tier 2 (Deep Drill-Down) | Correlates EPP plugin latencies, per-pod queue wait, prefill vs decode token ratios, and tail latency distributions. |
llm-d-performance-kv-cache |
Tier 2 (KV Cache & Offload) | HBM vs CPU/Lustre tiered KV offload hit rates (vllm:external_prefix_cache_*), DMA load/store bandwidth, and EPP KV index sync lag. |
llm-d-pd-coordinator-metrics |
Tier 2 (Disaggregated P/D) | Disaggregation Coordinator (llm_d_coordinator_*), Sidecar (llm_d_disagg_sidecar_*), conditional decode probes, and NIXL transfer latency. |
llm-d-router |
Tier 1/2 (EPP Router) | llm-d Router (EPP) metrics: inference pool, inference objective, and flow control. |
llm-d-batch-gateway-apiserver |
Tier 2 (Batch API Server) | Batch HTTP request rates, status codes, upload/download latencies, and file_storage_operations_total by S3/fs backend. |
llm-d-batch-gateway-processor |
Tier 2 (Batch Processor) | Batch job_queue_wait_duration_seconds, active_workers / total_workers, per-model inflight requests, and token throughput. |
llm-d-batch-gateway-gc |
Tier 2 (Batch Garbage Collector) | Expired/completed batch artifact cleanup rates and reconciler error counts (batch_reconciler_errors_total). |
llm-d-async-processor |
Tier 2 (Async Queue Worker) | Async Processor request rate and outcomes, inference latency and queue residence time, deadline proximity, broker backlog and in-process queue depth per queue. |
Dashboard names and file locations follow llm-d's Use Grafana Dashboards page; the panel lists are summaries, so open the dashboard JSON for the exact panels. The three Batch Gateway dashboards are useful only with the Batch Gateway deployed, and the Async Processor one only with the asynchronous processor.
Architectural trade-offs, decisions and validation gates¶
This part compares execution engines, 6D parallelism layouts, disaggregated serving and KV-cache routing designs, closed-loop autoscaling and fast-actuation mechanisms, and CI and benchmarking gates, against roofline, latency, memory and cost constraints.
5.1 Choosing an execution and compilation strategy¶
In one sentence: TorchTPU provides a ladder of execution strategies trading off Python debuggability against host-dispatch elimination and XLA fusion: from op-by-op strict eager (the default) through DeferAndFuse and
torch.compileto whole-step tracing (SingleTraceTrainer,TpuGraphTrainer) and the serving engines' megakernels.
The execution ladder¶
Each step down the ladder removes host dispatch and puts more work in each launch, at the cost of Python debuggability and longer compiles. Strict eager is the default; the last two rungs belong to whole-step training and to the serving engines.
Execution and compilation strategies compared¶
Sources: TorchTPU execution model, single_trace_trainer.py, torchtitan/experiments/tpu/graph_trainer, vllm_torchtpu/megakernel
| Execution Strategy | Activation API / Env Var | Graph Capture & Lowering Mechanism | Host Dispatch Overhead | XLA Fusion Scope | Dynamic Control Flow & Break Behavior | Primary Use Case & Trade-Offs |
|---|---|---|---|---|---|---|
| 1. Strict Eager (Default) | Nothing to set (torch.tpu.EagerMode.DEFER_NEVER) |
Each op is queued and immediately flagged for execution; single-op graphs compile at -O1, in parallel on the compilation threadpool, with high cache reuse |
High: one executable per op; executables shorter than the roughly 50 µs enqueue cost leave microbubbles | Single operator only (zero cross-op fusion) | 100% Python native (if, while, pdb, print); still asynchronous, so errors may surface late |
Fastest time to first result and compile warm-up; slowest steady state. |
| 2. Debug Eager | TORCH_TPU_LAUNCH_BLOCKING=1 (EagerMode.DEFER_NEVER_AND_LAUNCH_BLOCKING) |
Strict eager, but the host blocks and synchronizes on every operation | Extreme (artificially slow) | Single operator | 100% Python native | Interactive debugging only: failures are reported at the op that caused them. |
3. DeferAndFuse (Optimized Eager) |
TORCH_TPU_DEFER_AND_FUSE=1 (EagerMode.DEFER_AND_FUSE) |
Ops stay deferred until an action forces execution (a device-to-host transfer, a synchronize) or a repetition in the dispatched ops reveals a loop; the deferred graph compiles at -O2 |
Moderate | Across the deferred ops between materialization points | Python control flow works, but a data-dependent branch forces a sync and a graph break | Up to 50% faster than strict eager with no model change; longer compiles. |
4. torch.compile(backend="tpu") |
torch.compile(fn, backend="tpu") (an omitted dynamic means dynamic=False) |
One trace with placeholder tensors produces a fully deferred graph; the StableHLO program compiles at -O2 and is returned as a Python callable |
Low: calls push the executable straight to PjRt | Whole Dynamo subgraph (forward or backward region) | Graph breaks fall back to eager; guard failures trigger recompilation | Production default for vllm-torchtpu, sglang-torchtpu, and standard training. |
5. SingleTraceTrainer / TpuGraphTrainer |
torch.tpu.optimizers.SingleTraceTrainer (Experimental)TpuGraphTrainer (torchtitan) |
Traces the entire training step (forward, loss, backward, optimizer) into one graph; TorchTitan pairs it with scanned layers (compile.use_scan_layers) |
Very low (one launch per training step) | Full training step | Requires graph-traceable code (SimpleFSDP rather than hook-based FSDP2) |
The Qwen3-8B in-graph recipe of chapter 14; scanning shortens compile time for deep models. |
| 6. Serving-Engine Megakernels | vLLM-TorchTPU vllm_torchtpu.megakernel; SGLang-TorchTPU k3_megakernel, glm_flash_megakernel, muse_megakernel |
Engine- and model-specific Pallas megakernels | Minimal inside the megakernel | Many layers per launch | Statically planned | Small-batch decode where launch gaps and HBM round trips dominate (Recipes lists the recipes that enable them). |
Note
Strict eager is the default; TORCH_TPU_DEFER_AND_FUSE and TORCH_TPU_LAUNCH_BLOCKING choose the other eager modes (also values of the Experimental torch.tpu.EagerMode). There is no fusion cap, and TorchTPU has no megakernel module: the megakernels live in the serving engines (chapter 4, chapter 11).
5.2 Parallelism and sharding decisions¶
In one sentence: Scaling models across multi-slice TPU pods requires matching each parallelism axis to the physical interconnect hierarchy: placing Tensor Parallelism (
TP) on the fastest local ICI ring (on v7x also the600 GB/sdie-to-die link), Context/Sequence, Expert and FSDP sharding (CP/SP,EP,FSDP) on the ICI axes within a slice, and Data/Pipeline Parallelism (DDP/HSDPreplicate,PP) across Data Center Network (DCN) links between slices, or on the outer ICI axis within a single slice.
Mapping 6D parallelism onto the TPU interconnect hierarchy¶
Put the axis that talks most on the fastest link: TP on the local ICI ring, FSDP, CP and EP on the slice's ICI axes, and only replicated data parallelism and pipeline stages across DCN. Sequence parallelism that shards activations beside TP travels with TP.
Two kinds of sequence parallelism sit in different tiers: Megatron-style SP (activations sharded along the TP group) rides with TP, while sequence or context parallelism of attention (all-to-all or ring) uses the slice's ICI axes. DCN gives 100 Gb/s, about 12.5 GB/s, per chip.
1. Collective communication cost equations (tpu-agent-suite roofline model)¶
Source: tpu-agent-suite/package/scripts/roofline-analysis/cost_estimator/collective.py
Given per-device payload \(V_{\text{bytes}}\), ring degree \(N\) (one axis), one-way link bandwidth \(\beta_{\text{link}}\) (e.g. \(80\text{–}90\text{ GB/s}\) ICI or \(600\text{ GB/s}\) D2D in the agent suite's v7x model), link efficiency \(\eta \le 1\), per-hop latency \(\alpha_{\text{hop}} \approx 1\text{ }\mu\text{s}\) (the model's generic default), and lanes \(\ell \in \{1, 2\}\) (\(\ell = 2\) for a wraparound torus axis with a bidirectional ring, \(\ell = 1\) for a line without wraparound):
Tip
Why AllToAll Scales as \(\mathcal{O}(N)\) on a Ring vs \(\mathcal{O}(1)\) for AllGather: In AllGather/ReduceScatter the bandwidth term approaches \(\frac{V_{\text{bytes}}}{\ell \beta_{\text{link}} \eta}\) as \(N \to \infty\) (independent of \(N\)): they are egress-bound, and no chunk crosses more than one link per step. All-to-all is a permutation: a chunk bound for a device \(d\) hops away crosses \(d\) links, so it is bisection-bound and grows with \(N\). Against a reduce-scatter proxy on the same payload the ratio is \(\frac{N^2}{4(N-1)}\), 4.3x at \(N = 16\). On TPU v7x the model treats the two devices of a chip as a size-2 D2D axis and halves every ICI axis's effective bandwidth, because both die layers' rings share the same physical links.
Note
The all-to-all term follows the TPU Agent Suite's collective.py, \(\frac{S \cdot X}{4 \cdot \text{lanes} \cdot B \cdot \eta}\) (exact for even \(X\)), including its link-efficiency factor and a 1 µs default hop latency. hierarchical_ag is one of the MoE dispatch strategies roofline.py can price (with all_to_all and all_gather). Collective rooflines in full are in chapter 13.
2. Parallelism and sharding techniques compared¶
Sources: TorchTPU distributed support, the TorchTitan repository, tpu-agent-suite/package/scripts/tpu-sharding, Scale MoE Models with Wide Expert Parallelism
| Parallelism Dimension & Variant | TorchTPU / TorchTitan / vLLM Implementation | What Is Sharded? (Weights / Grad / Opt / Activations / KV) | Collective Primitives per Layer | Optimal Hardware Axis | When to Select & Key Constraints |
|---|---|---|---|---|---|
1. DDP (Distributed Data Parallel) |
torch.nn.parallel.DistributedDataParallel |
Batch (\(B/DP\)) only; Weights/Grads/Opt replicated | 1 AllReduce of gradients per step (backward overlapped) |
Single-slice ICI or Multi-slice DCN | Small models (\(< 7\text{B}\)) that fit entirely in a single chip's HBM (16–96 GiB). |
2. FSDP2 (fully_shard) |
torch.distributed.fsdp.fully_shard (DTensor-based) |
Weights, Gradients, Optimizer States (\(1/N_{\text{fsdp}}\)) | AllGather (fwd + bwd) + ReduceScatter (bwd) |
Full 2D/3D ICI Slice (4–256 chips) |
Standard eager / torch.compile training of 8B–70B+ models when hook-based per-layer sharding is desired. |
3. SimpleFSDP |
torchtitan/experiments/tpu/graph_trainer/simple_fsdp.py |
Weights, Gradients, Optimizer States via pure DTensor Functional Collectives |
Graph-visible all_gather_into_tensor + reduce_scatter_tensor |
Full 2D/3D ICI Slice | Mandatory for TpuGraphTrainer (make_fx) and scan_layers where Python hooks cannot be traced; allows XLA Latency Hiding Scheduler to overlap collectives across layers. |
4. HSDP (2D Hybrid Sharded DP) |
DeviceMesh (dp_replicate, dp_shard) via topology_aware_mesh() |
Sharded within each ICI slice (dp_shard); Replicated across slices (dp_replicate) |
Intra-slice ICI AllGather/ReduceScatter + Inter-slice DCN AllReduce once per step |
dp_shard on ICI; dp_replicate on DCN |
Multi-slice training (2+ pods/slices) where running FSDP AllGather across slow Ethernet DCN would bottleneck every layer. |
5. TP (Tensor Parallelism) + SP (Sequence Parallelism) |
ColwiseParallel, RowwiseParallel, SequenceParallel |
Attention heads (\(H/TP\)), MLP hidden (\(I/TP\)), and LayerNorm/Dropout sequence activations (\(S/TP\)) | 2 AllGather + 2 ReduceScatter per Transformer block (with SP) |
Inner-most ICI axis or v7x D2D (TP=2, 4, 8) |
Models \(\ge 30\text{B}\) where activations/weights exceed single-chip HBM or decode latency requires aggregating HBM bandwidth across \(TP\) chips. Cap \(TP \le H_{kv}\) to avoid KV head replication. |
6. AsyncTP (Overlapped TP + SP) |
parallelism.enable_async_tensor_parallel = True (TorchTitan) |
Same as TP + SP |
Decomposes all-gather-matmul and matmul-reduce-scatter into overlapped tiles | Inner ICI / D2D (TP=2, 4, 8) |
Hides TP collective latency behind MXU MatMul execution. |
7. CP: Ulysses (All-to-All Context Parallelism) |
All-to-All transpose between sequence-sharded \((B, S/CP, H, d_h)\) and head-sharded \((B, S, H/CP, d_h)\) |
Sequence activations & KV cache (\(S/CP\)) | 4 AllToAll collectives per attention layer (Q, K, V in; O out) |
Fast 2D/3D ICI (CP <= H_{kv}) |
Long-context training/prefill (\(S = 32\text{K}–1\text{M}\)) when \(CP \le H_{kv}\); lower communication volume than Ring Attention for moderate \(CP\). |
8. CP: Ring / HeadTail / PTRR |
cp_attention.py and headtail.py (head-tail and PTRR layouts) |
Sequence chunks (\(S/CP\)) passed around P2P collective-permute KV ring |
Overlapped P2P collective-permute ring steps alongside FlashAttention |
1D/2D ICI Ring (CP=2..32+) |
Very long context (\(S \ge 128\text{K}\)) where \(CP > H_{kv}\). Always enable HeadTail (pairs chunk \(i\) with \(2CP-1-i\)) or PTRR (Per-Token-Round-Robin) to eliminate the \(2\times\) causal mask load imbalance. |
9. PCP & DCP (Prefill / Decode Context Parallelism) |
vllm-torchtpu (--prefill-context-parallel-size 8 on TPU v7x) |
Splits long prefill prompts across \(PCP\) ranks; Decode uses \(DP\) or \(DCP\) | AllGather KV blocks during prefill attention + Raiden DCN handoff |
Intra-host TPU v7x (PCP=8 across 8 dies) |
Disaggregated serving of long prompts (Qwen3.5-397B on TPU v7x: 1P PCP=8 \(\rightarrow\) 1D DP=8). |
10. EP / Wide-EP (Expert Parallelism) |
ExpertParallel (torchtitan); --enable-expert-parallel + --data-parallel-size 16 (vllm / sglang) |
Routed MoE experts (\(E_{\text{tot}} / EP\)) sharded across ranks; Attention runs DP (TP=1) |
2 AllToAll (dispatch + combine) per MoE layer (megablox_gmm / DeepEP / MoRI / hierarchical_ag on v7x) |
Multi-chip ICI (EP=8..64) or Multi-node RDMA (DP=16, EP=16) |
Sparse MoE models (DeepSeek-V3/R1, Qwen3-235B/397B). Running attention data-parallel avoids duplicating MLA KV caches across TP ranks. |
11. PP (Pipeline Parallelism: 1F1B, Interleaved1F1B, DualPipeV, ZBVZeroBubble) |
torchtitan/distributed/pipeline_parallel.py (ScheduleDualPipeV, ScheduleZBVZeroBubble) |
Contiguous (or V-shaped) subsets of layers (\(L / PP\)) per stage | Point-to-point Send/Recv of boundary activations [b_{\text{micro}}, S, D] |
Cross-slice DCN or outer ICI axis | Frontier models (\(100\text{B}–1\text{T}+\)) spanning multiple pods where DCN bandwidth is too low for FSDP. Use DualPipeV or ZBVZeroBubble (splits backward into \(B_{\text{input}}\) and \(W_{\text{weight}}\)) to drive pipeline bubble fraction near \(0\%\). |
3. Starting topologies by model scale and workload¶
These rows are starting points to measure against, not the output of a tool. Two have published counterparts: the v7x Qwen3.5-397B P/D layout (prefill PCP=8, decode DP=8, TP=1, expert parallel, TPURaidenConnector with a 64 GiB prefill host KV tier) is llm-d's v7 P/D overlay, and dense 7B-14B training with SimpleFSDP and scanned layers is chapter 14's Qwen3-8B recipe. The TPU Agent Suite's sharding tooling is scripts/tpu-sharding/ (a query index) and scripts/sharding-strategy/ (presets and search).
| Model Scale & Architecture | Target Workload | TPU v5e (16 GiB) / v6e (32 GiB) |
TPU v5p (95 GiB) / v7x (96 GiB/die) |
Key Tuning Rationale |
|---|---|---|---|---|
Dense 7B–14B (Llama-3.1-8B, Qwen3-8B/14B) |
Serving | TP=1 or TP=2 (v6e), DP=N |
TP=1 per die (v7x), DP=8 per host |
Fits in single-chip HBM; maximize throughput via horizontal DP replicas (TP=1) unless a very low TPOT target requires TP=2. |
Dense 7B–14B |
Training (\(S \le 8\text{K}\)) | SimpleFSDP=8..64, TP=1 or 2 |
SimpleFSDP=8..64, TP=1, scan_layers=True |
Pure SimpleFSDP avoids per-layer TP collectives while fitting activations in 32–96 GiB HBM. |
Dense 32B–70B (Qwen3-32B, Llama-3.3-70B) |
Serving | TP=4 or TP=8 (v6e 2x4 slice), FP8 weights |
TP=2 or TP=4 (v5p/v7x), or Disagg 1P TP=2 : 1D TP=4 |
Aggregates 6.4–14.7 TB/s HBM bandwidth for decode while holding 64–140 GB weights + KV cache. |
Dense 32B–70B |
Training (\(S = 8\text{K}–128\text{K}\)) | HSDP (DCN) \(\times\) SimpleFSDP (ICI) \(\times\) AsyncTP=4..8 \(\times\) CP=2..8 (HeadTail) |
HSDP \(\times\) SimpleFSDP \(\times\) AsyncTP=2..4 \(\times\) CP=2..4 (HeadTail) |
AsyncTP shards intra-layer memory on fast inner ICI/D2D; HeadTail CP prevents \(O(S^2)\) attention OOM at \(S \ge 32\text{K}\). |
Sparse MoE 200B–671B+ (DeepSeek-R1/V3, Qwen3.5-397B-A17B) |
Disaggregated Serving | Multi-host TP=8 + EP=8..16 (FP8) |
TPU v7x: Prefill PCP=8 (or DP=8, EP=8) \(\rightarrow\) Decode DP=8, EP=8, TP=1 + MTP=3 |
Replicating MLA/GQA attention (DP=8, TP=1) while sharding experts (EP=8) avoids KV duplication and uses TPURaidenConnector for P/D handoff. |
Sparse MoE 200B–671B+ |
Multi-Pod Training | PP=4..8 (DualPipeV) \(\times\) SimpleFSDP \(\times\) EP=8..32 \(\times\) AsyncTP=2..4 |
HSDP / PP (ZBVZeroBubble) \(\times\) SimpleFSDP \(\times\) EP=8..64 (hierarchical_ag) \(\times\) AsyncTP=2 |
EP shards routed experts; DualPipeV/ZBVZeroBubble eliminates cross-slice pipeline bubbles. |
5.3 Distributed inference architecture and routing trade-offs¶
In one sentence: Modern LLM serving decouples three historically monolithic bindings: separating Prefill from Decode (
DisaggregatedSet), separating KV-cache residency from HBM capacity (Tiered Offloading), and separating prefix-cache reuse from pod placement (P2P KV Sharing&Precise ZMQ Indexing).
llm-d disaggregation and KV paths¶
The EPP only chooses pods; the proxy and the decode pod's routing sidecar move the request. In P/D the KV cache goes from the prefill pod straight to the decode engine, and in the unified path a pod can pull a cached prefix from a peer's CPU tier instead of recomputing it.
1. Serving topologies: unified, P/D disaggregated and E-P-D multimodal¶
Sources: Deploy Prefill/Decode Disaggregation, llm-d Disaggregation, Disaggregated serving (Prefill/Decode with Raiden3)
| Architectural Pattern | Kubernetes Orchestration CRD | Request & Data Flow | Hardware Parallelism Asymmetry | Best Workload Profile | Operational Trade-Offs & Pitfalls |
|---|---|---|---|---|---|
1. Unified (Co-located P+D) |
Standard Deployment or LeaderWorkerSet (lws) |
The proxy sends the request to the model server :8000 the EPP picked; chunked prefill and decode share the same continuous batch |
Symmetric (TP_P == TP_D) |
Short-to-medium prompts (\(\text{ISL} \le 2048\)), uniform chat, or small fleets (< 4 nodes) |
Simple to operate (no KV network transfer), but long prefills cause head-of-line ITL/TPOT spikes for co-running decode streams and force compromises on TP degree. |
2. P/D Disaggregation (xPyD) |
DisaggregatedSet (lws v0.11.1+ with enableDisaggregatedSet=true) |
EPP runs disagg-profile-handler (prefill + decode profiles) and the proxy sends the request to the decode pod's routing sidecar on :8000 (llm-d-routing-sidecar) with x-llm-d-prefiller-host-port; sidecar triggers remote prefill (max_tokens=1) and injects kv_transfer_params into local Decode engine (:8200) |
Asymmetric: • GPU: 1P TP=1 : 1D TP=4• TPU v7x: 1P PCP=8 : 1D DP=8• NPU: 1P PP=4 : 1D DP=4 |
Long prompts (\(\text{ISL} \ge 4096\)), strict TPOT SLOs (< 30–50 ms), or large MoE models (DeepSeek-R1, Qwen3.5-397B) |
Eliminates prefill interference on decode and optimizes tokens/sec/chip via phase-specific parallelism; requires high-speed KV fabric (RDMA/RoCE/ICI/Raiden) and matched --block-size. |
| 3. E-P-D Multimodal Disaggregation | Multi-Role DisaggregatedSet (encode + prefill + decode) |
The decode pod's routing sidecar sends the media to an encode pod running the vision/audio encoder (ViT; encoder outputs can be cached, llm_d_epp_encoder_cache_*), and vLLM's ECCPU connector moves the embeddings to the prefill pod over NIXL; text-only requests skip the encode stage. Experimental in llm-d 1.0 and validated on GPU; on TPU v7 the multimodal guide runs aggregated only |
encode uses small TP=1 compute pods; prefill/decode scale LLM weights independently |
High-resolution video/image VLM workloads (Qwen2.5-VL, Gemma-3, Llama-4) |
Prevents heavy vision encoder bursts from starving LLM prefill/decode batches and avoids replicating giant LLM weights on vision-bound workers. |
With encode disaggregated, the vision or audio encoder runs on its own pods and only its embeddings reach prefill, so encoder bursts no longer stall the LLM's batches. In llm-d 1.0 this layout is experimental and validated on GPU; on TPU v7 the multimodal guide runs aggregated.
2. KV transfer connectors (P/D disaggregation and offloading)¶
Sources: Deploy Prefill/Decode Disaggregation, Configure a Tiered Prefix Cache, the SGLang-TorchTPU repository
| KV Connector Name | Engine & Target Hardware | CLI / kv_transfer_config Invocation |
Transport Layer & Staging Architecture | Heterogeneous TP Support? | Key Tuning Knobs & Operational Caveats |
|---|---|---|---|---|---|
TPURaidenConnector + TPURaidenOffloadingConnector |
vllm-torchtpu on Cloud TPU v6e / v7x |
kv_connector: "TPURaidenConnector" (or "TPURaidenOffloadingConnector" with cpu_bytes_to_use: 34359738368) |
Raiden3 high-speed DCN/ICI transport + 64–256 GiB pinned Host DRAM staging tier + optional Lustre Direct I/O (raiden_storage_path, direct_io: true) |
Yes (PCP=8 Prefill \(\rightarrow\) DP=8 Decode on TPU v7x) |
Stages prefill KV into host DRAM (save_kv_layer) so prefill HBM is freed immediately before decode pulls (load_kv_sync). Set PYTHONHASHSEED=0 for VARIANT=fs. |
TPUConnector / TPUConnectorHMA |
llm-d's TPU P/D overlays: v5p uses TPUConnector from tpu_inference (JAX); v6e uses vLLM-TorchTPU's TPUConnector; TPU7x dynamic slicing uses TPUConnectorHMA |
kv_connector: "TPUConnector" with kv_port in --kv-transfer-config |
TPU ICI / DCN; HMA on TPU7x | Symmetric TP (TP=4 on v5p; TP=8 on v6e) |
Standard multi-slice TPU P/D disaggregation and Kueue dynamic slices. |
TpuKVManager (ZMQ-Push) |
sglang-torchtpu on Cloud TPU |
sglang_tpu/disaggregation/tpu/ (--disaggregation-mode prefill\|decode); a raiden backend sits beside it |
Prefill gathers KV pages off-device (D2H) and background threads push the host bytes over ZeroMQ to decode, which receives into host memory | Symmetric TP | Background push threads (4 per prefill rank by default) overlap the host transfer with the next prefill. |
NixlConnector (nixlv2) |
vLLM & SGLang on NVIDIA GPU, AMD, Intel XPU |
--kv-connector=nixlv2 |
NVIDIA NIXL over UCX / LIBFABRIC (UCX_TLS=rc,sm,cuda_copy on IB/RoCE; tcp,ze_copy on XPU) |
Yes in nixlv2 (1P TP=1 : 1D TP=4) |
Monitor vllm:nixl_xfer_time_seconds and vllm:nixl_num_kv_expired_reqs (divide by TP_SIZE). |
OffloadingConnector / TieringOffloadingSpec |
vLLM (v0.26.0+) on GPU, AMD, XPU |
--kv-transfer-config '{"kv_connector":"OffloadingConnector","kv_role":"kv_both","kv_connector_extra_config":{"cpu_bytes_to_use":...,"p2p_port":7777}}' |
Async GPU DMA \(\leftrightarrow\) Pinned Host DRAM + optional POSIX file_storage_path + P2P TCP/RDMA server on :7777 |
Symmetric TP required for P2P :7777 pulls |
Powers both Tiered Prefix Cache (VARIANT=cpu/fs) and P2P Prefix Cache Sharing (:7777). Needs /dev/shm \(> \text{cpu\_bytes\_to\_use}\). |
HiCache |
SGLang on GPU, AMD, XPU |
--enable-hierarchical-cache --hicache-size 200 (+ --hicache-storage-backend file) |
SGLang native RadixCache HBM \(\leftrightarrow\) Host DRAM (200 GiB) \(\leftrightarrow\) Filesystem tier |
Symmetric TP | Expose metrics via --enable-metrics (sglang:hicache_host_used_tokens, sglang:load_back_duration_seconds). |
MooncakeConnector / MoRIIOConnector |
vLLM / SGLang on GPU (cks-mooncake) & AMD MI300X/MI355X (mori_io) |
kv_connector: "MooncakeConnector" or "MoRIIOConnector" |
mooncake_transfer_engine (DRAM + NVMe RDMA pool) or AMD MoRI-IO ROCm IPC + RoCEv2 |
Symmetric / Wide-EP per-rank | Pair MoRIIOConnector with mori_high_throughput all-to-all for DeepSeek-V3 on AMD MI355X. |
3. Prefix routing, KV indexing and latency-aware scheduling¶
Sources: Enable Precise Prefix-Cache Aware Routing, Enable P2P Prefix Cache Sharing, Configure a Tiered Prefix Cache, Route Requests by Predicted Latency
| Routing / Caching Strategy | EPP Plugins & Sidecars Required | How Cache / Load State Is Tracked | Benchmark Impact & Key Strength | Critical Constraints & Failure Modes |
|---|---|---|---|---|
| 1. Approximate Prefix Affinity (Baseline) | gpu-prefix-cache-producer + prefix-cache-affinity-filter + token-load-scorer |
Router hashes prompt characters/tokens locally and estimates pod cache state via an internal LRU model (lruCapacityPerServer) |
Zero sidecar or ZMQ setup; fast <1 ms scheduling decision |
Cache-state drift under high eviction churn or Jinja2 chat-template formatting differences between router and vLLM. |
| 2. Precise Real-Time ZMQ KV Indexer | token-producer (/v1/*/render) + precise-prefix-cache-producer (:5556 PUB / :5559 Replay) |
Tokenizes prompts via vLLM's exact HTTP /v1/chat/completions/render endpoint and ingests real-time ZMQ BlockStored/BlockRemoved events from every pod |
100% exact block-hash accuracy; zero LRU estimation drift even during heavy preemptions or multimodal/LoRA workloads | Requires EPP replicas: 1, PYTHONHASHSEED=0, --enable-scale-out on vLLM (or standalone CPU vllm launch render pool for SGLang), and matching blockSizeTokens (64, or 256 on TPU v6e). |
| 3. Dual-Tier HBM + CPU/FS Prefix Routing | gpu-prefix-cache-producer + cpu-prefix-cache-producer (lruCapacityPerServer = 19200 for 300 GiB DRAM) |
Scores pods by weighted sum of HBM cache hits and pinned Host DRAM (VARIANT=cpu) / Lustre (VARIANT=fs) cache hits |
Expands effective KV cache capacity by 2x–10x+ (256 GiB DRAM on TPU v7x via TPURaidenOffloadingConnector) |
Container memory limit must be \(\ge \text{CPU\_KV\_Tier} + 60\text{ GiB}\) to avoid Linux kernel OOMKilled on pinned buffers. |
4. P2P Cross-Pod Prefix Cache Sharing (:7777) |
precise-prefix-cache-producer + token-load-scorer + p2p-source-producer (minCachedTokenDelta: 2048, p2pPort: 7777) + routing-sidecar |
Places request with token-aware placement while a KV cache source header names Peer A; the routing sidecar injects kv_transfer_params.remote_kv_source and the engine pulls the prefix from the peer's CPU tier over NIXL (P2P port 7777) |
2.29x higher throughput (6.3 vs 2.75 req/s) and 2x lower P90 TTFT (7.1 s vs 14.1 s) than affinity placement on 48K-token document Q&A, measured on 8 x H200 (gpt-oss-120b, pull over TCP), not on TPU |
Pulls exclusively from peer's CPU tier (cpu_bytes_to_use \(\ge 2\times\) GPU KV cache); requires /dev/shm \(> \text{cpu\_bytes\_to\_use}\) (96Gi) and strict peer TP symmetry. |
| 5. Online XGBoost Predicted-Latency & SLO Routing | 4-container Router Pod (epp, envoy, training-server :8000, prediction-server-1 :8001) + latency-scorer + latency-slo-admitter |
Retrains online XGBoost models (one for TTFT, one for TPOT) every 10s on completed requests; prediction servers pull the retrained models every 30s |
Predicts exact per-pod TTFT/TPOT; enforces per-request x-llm-d-slo-ttft-ms & x-llm-d-slo-tpot-ms headers and sheds negative-priority bursts |
SLO_AWARE=true requires "stream": true in client requests; router pod requires 18 vCPUs / 24 GiB RAM (four containers: epp, envoy-proxy, training-server, prediction-server-1). |
5.4 Autoscaling and fast actuation¶
In one sentence: Because continuous batching holds accelerator compute utilization near 100% even at low queue depths, production LLM autoscaling must trigger on EPP demand, token velocity, or predicted SLO saturation (via KEDA + Kueue), paired with fast start-up (on GPU,
FMA,Pod SnapshotsorModelExpress P2P; on TPU, the compile and weight caches) so new replicas absorb load before queues expire.
Closed-loop autoscaling, quota rebalancing and fast actuation¶
KEDA turns EPP demand into the HPA's replica count, Kueue, when used, admits each new replica only within its quota, and the new replica changes the signals once it serves. How fast that happens is the start-up time: on TPU the compile and weight caches are what shorten it.
1. Autoscaling designs and their control laws¶
Sources: llm-d Autoscaling, KEDA with EPP Metrics, SLO-Aware Autoscaling with KEDA: the control law, Workload Variant Autoscaler (WVA): Deprecated, Scale on Queue Depth and Saturation, Scale on Token Backlog (Experimental), Scale to Latency SLOs, Share a GPU Budget Across Models (Experimental)
| Autoscaling Strategy | Control Signal & Mathematical Formula | Scale-to-Zero Support? | Pending Pod Warmup Credit? | Best Workload Profile | Critical Limitations & Gotchas |
|---|---|---|---|---|---|
| 0. Standard GPU/TPU Utilization HPA (Anti-Pattern) | tensorcore_utilization or DCGM_FI_DEV_GPU_UTIL |
No | No | None (Do Not Use for LLMs) | Batch of 2 requests vs batch of 64 requests both show ~90%+ compute/bandwidth utilization while queue wait explodes by \(20\times\). |
1. KEDA + EPP Request Signals (inflight, queue, saturation) |
• inflight: sum(llm_d_epp_inflight_requests) (threshold: 16)• queue: sum(llm_d_epp_flow_control_queue_size) (1) + running (16)• saturation: max(llm_d_epp_flow_control_pool_saturation) (0.7) |
Yes (with SIGNAL=queue + Flow Control enabled, or paired with FMA) |
Via 300s HPA stabilizationWindowSeconds |
Homogeneous prompt lengths (\(\text{ISL}\) variance is low); fastest production setup (inflight needs no Flow Control) |
Treats a 128-token request and a 32K-token request as 1 unit of work; never attach two ScaledObjects to one Deployment. |
2. Token-Aware KEDA Autoscaling (keda-epp-token-aware) |
• Prefill (Rate): \(\text{replicas}_P = \lceil (\text{inflight\_tokens} / V_P) / \theta_{\text{sec}} \rceil\) where \(\theta_{\text{sec}} = S_{\text{TTFT}} - \text{ISL}_{\text{uncached}}/V_P\) • Decode (Occupancy): \(\text{replicas}_D = \lceil \sum \text{kv\_cache\_usage\_perc} / 0.80 \rceil\) |
No (minReplicaCount: 1) |
300s stabilization window |
Workloads with wide prompt-length variance (256 to 32K tokens) and P/D Disaggregated pools (DisaggregatedSetRoleScaler) |
Requires calibrating \(V_P\) via calibrate.sh, pinning EPP replicas: 1, testing with open-loop load, and applying the label_replace ready-pod intersection on router <= v0.10.0 (#2529). |
3. SLO-Aware KEDA Autoscaling (slo-aware) |
Recording rule llm_d:epp:latency_saturation_ratio computes smoothed (45s), clamped (\(C=2.0\)) saturation \(s\); KEDA expr-lang formula applies dead band \([\theta_{\text{dn}}=0.40, \theta_{\text{up}}=0.55]\) + warmup credit \(c = r/n\) |
No (minReplicaCount: 3 default) |
Yes. Discounts scale-up ask by in-flight warmup credit (readyReplicas / replicas from KSM) + EPP decode warmup ramp \(R(t)\) |
Strict P90 TTFT & TPOT SLA compliance (the guide measured 95.8% combined SLO attainment at 5.93 average replicas against a static pool of 8, about 26% fewer replicas, on H100 with Qwen3-32B TP=2) | Scoped to a single variant / single SLO pair per pool; installing KEDA overwrites v1beta1.external.metrics.k8s.io APIService. |
4. Workload Variant Autoscaler (WVA) (Cross-SKU Controller) |
4-stage pipeline (Collect \(\rightarrow\) SaturationAnalyzer V1/V2 + SLOAnalyzer Kalman + M/M/1/k \(\rightarrow\) CostAware/GreedyByScore Optimizer \(\rightarrow\) Enforcer) + 100ms scale-from-zero engine |
Yes (100ms reactive watcher on EPP Flow Control / Envoy queue) |
Yes (Separates ready vs pending replicas during capacity allocation) | Heterogeneous hardware variants of the same model (e.g., overflowing from A10G/v5e to H100/v6e based on $/replica and GPU limiter) |
Deprecated in llm-d 1.0: use KEDA + EPP for new deployments. Required the WVA controller + Prometheus Adapter (wva_desired_replicas). |
5. Kueue Cohort Replica Rebalancing (kueue-rebalancing) (Experimental) |
Operates below HPA: each pod is a Kueue Workload with guaranteed floor (nominalQuota), borrowing idle GPUs from cohortName and preempting back via reclaimWithinCohort: Any |
N/A (Quota gate below HPA) | N/A (Holds over-budget pods Pending at scheduling gate) |
Multi-model clusters sharing a fixed physical GPU/TPU budget without oversubscription | Must delete native K8s GPU ResourceQuota, label pod template (not Deployment) with kueue.x-k8s.io/queue-name, set maxSurge: 0, maxUnavailable: 1, and alert on kueue_pending_workloads. |
A. SLO-aware KEDA control law and decode warmup ramp¶
Sources: SLO-Aware Autoscaling with KEDA: the control law, Scale to Latency SLOs
- Normalized P90 Latency Saturation (\(s_{\text{raw}}\)) & Clamped Smoothing (\(s\)): $\(s_{\text{raw}}(t) = \max\!\left(\frac{\text{P90}(\text{TTFT}_{[1\text{m}]})}{S_{\text{TTFT}}}, \; \frac{\text{P90}(\text{TPOT}_{[1\text{m}]})}{S_{\text{TPOT}}}\right), \qquad s(t) = \text{avg\_over\_time}\!\left(\min\!\left(s_{\text{raw}}(t), \; C\right)[45\text{s}]\right) \quad (C = 2.0)\)$
- In-Flight Pod Warmup Credit (\(c\)) & Piecewise Desired Replicas (\(d\)) with Hysteresis Band \([\theta_{\text{dn}}=0.40, \theta_{\text{up}}=0.55]\):
With \(n\) provisioned and \(r\) ready replicas (the ScaledObject's
replicasandreadyReplicastriggers), the in-flight credit is \(c = \frac{r}{n}\) when \(0 < r < n\), else \(1\), and the KEDA formula evaluates: $\(d(s, n, r) = \begin{cases} n + \left\lceil n \left( \frac{s \cdot c}{\theta_{\text{up}}} - 1 \right) \right\rceil, & \text{if } s > \theta_{\text{up}} \quad (\text{scale up, credited}) \\ n - \left\lfloor n \left( 1 - \frac{s}{\theta_{\text{dn}}} \right) \right\rfloor, & \text{if } s < \theta_{\text{dn}} \quad (\text{scale down, uncredited}) \\ n, & \text{otherwise} \quad (\text{hysteresis band}) \end{cases}\)$ Each P90 in \(s_{\text{raw}}\) ishistogram_quantile(0.9, ...)over 1-minute bucket rates, preferring the predicted histogram and falling back to the actual one; recording rules run every 15 s, and no traffic maps to 0. - HPA Rate Envelopes & Pod Warmup:
- HPA Behavior: the KEDA-generated HPA clips \(d\) to
[minReplicaCount, maxReplicaCount](3 and 8 in the guide); scale-up bursts atmax(100 %, 4 pods)per60swith a30sstabilization window; scale-down walks 1 pod per120swith a180swindow. - Ready Replicas: additions take a warmup time \(T_w\) (model load + compile) to become ready, \(R(t) = \min_{\tau \in [t - T_w, t]} N_{\text{spec}}(\tau)\); the guide's
decode-warmup-patch.yaml(a compile-cache volume plus a fast startup probe) cut pod-ready time from about 2 min 15 s to about 100 s.
B. Workload Variant Autoscaler (WVA, deprecated): token and queueing equations¶
Source: Workload Variant Autoscaler (WVA): Deprecated
- Saturation Analyzer V2 (
saturation-token-based) Effective Token Capacity (\(V_{\text{eff}}\)): $\(V_{\text{eff}} = \min(k_1, k_2), \qquad k_1 = N_{\text{blocks}} \cdot b_{\text{size}} \cdot \gamma_{\text{kv}} \quad (\text{Memory-bound KV capacity}), \qquad R_{\text{sat}} = \left\lceil \frac{\sum T_{\text{in-use}} + \sum (Q_{\text{wait}} \cdot \bar{T}_{\text{req}})}{\theta_{\text{scaleUp}} \cdot V_{\text{eff}}} \right\rceil\)$ where compute-bound token capacity \(k_2\) is resolved via a 4-level priority chain: (1) Observed live saturation (kv >= 0.80orwaiting >= 5\(\implies k_2 = T_{\text{in-use}}\)), (2) Historical rolling average under queue pressure, (3) Derived \(= B_{\text{max\_batched\_tok}} \cdot \frac{\bar{O}}{\bar{I}} \cdot 0.90\), (4) Fallback \(= k_1\). - SLO Analyzer (
SLOAnalyzer) Kalman Filter & M/M/1/k Queueing Model: - Online Kalman Filter estimates hardware latency coefficients \((\alpha, \beta, \gamma)\) from live requests: $\(\text{TTFT}_{\text{compute}} = \alpha + \gamma \cdot N_{\text{prefill\_tokens}}, \qquad \text{ITL}_{\text{compute}} = \alpha + \beta \cdot B_{\text{decode}}\)$
- Sweeps batch size \(B \in [1, B_{\max}]\) in an M/M/1/k queueing model to find max per-replica throughput \(Q_{\max}\) satisfying \(\text{TTFT}_{\text{queue}} + \text{TTFT}_{\text{compute}} \le S_{\text{TTFT}}\) and \(\text{ITL}_{\text{compute}} \le S_{\text{ITL}}\) (with idle-latency safeguard \(k = 3.0 \implies \rho = 1 - 1/k \approx 0.67\)), yielding \(R_{\text{SLO}} = \lceil \lambda_{\text{arrival}} / Q_{\max} \rceil\).
- Joint Target & Multi-Variant Allocation: \(\text{target} = \max(R_{\text{sat}}, R_{\text{SLO}})\) on scale-up and \(\min(R_{\text{sat}}, R_{\text{SLO}})\) on scale-down;
CostAwareOptimizer(orGreedyByScoreOptimizerwhenenableLimiter: truecaps cluster GPUs) allocates replicas cheapest-variant-first on scale-up and sheds most-expensive-first on scale-down.
C. Token-aware KEDA stale GaugeVec workaround (llm-d-router <= v0.10.0, Issue #2529)¶
llm_d_epp_inflight_tokens is a GaugeVec whose series were historically not pruned when an endpoint was removed, so a scaled-down pod left a series frozen at its last non-zero value and sum() could never fall back. llm-d-router#2577 fixed it after v0.10.0; on v0.10.0 or earlier, intersect the numerator with a metric rebuilt from live endpoints each scrape:
# In-flight tokens filtered to live endpoints (workaround for llm-d-router#2529 on v0.10.0 and earlier)
sum(
label_replace(
llm_d_epp_inflight_tokens{namespace="llm-d", producer_name="inflight-load-producer"},
"target_pod", "$1", "endpoint_name", "(.+)"
)
and on (target_pod)
label_replace(
llm_d_epp_per_endpoint_queue_size{name="qwen3-32b-pool"},
"target_pod", "$1", "model_server_endpoint", "(.+)"
)
) / 15928
The token-aware guide's decode signal is vllm:kv_cache_usage_perc from the engines (Scale on Token Backlog).
D. Kueue cohort rebalancing manifest (ResourceFlavor + ClusterQueue + LocalQueue)¶
Source: Share a GPU Budget Across Models (Experimental)
apiVersion: kueue.x-k8s.io/v1beta2
kind: ResourceFlavor
metadata:
name: default-flavor
---
apiVersion: kueue.x-k8s.io/v1beta2
kind: ClusterQueue
metadata:
name: model-a-cq
spec:
cohortName: shared-gpu-pool # Joins shared cluster GPU/TPU pool
preemption:
reclaimWithinCohort: Any # Preempts borrowers whenever Model A needs its nominalQuota back.
borrowWithinCohort:
policy: Never # Borrowers cannot preempt other queues simply to borrow above nominalQuota
resourceGroups:
- coveredResources: ["nvidia.com/gpu"] # On GKE Cloud TPU: ["google.com/tpu"]
flavors:
- name: default-flavor
resources:
- name: "nvidia.com/gpu"
nominalQuota: 1 # Guaranteed floor (e.g. 1 GPU for Model A + 1 GPU for Model B + 2 lend-only = 4 GPUs)
---
apiVersion: kueue.x-k8s.io/v1beta2
kind: LocalQueue
metadata:
name: model-a-lq
namespace: llm-d-rebalancing
spec:
clusterQueue: model-a-cq
Warning
Kueue Webhook & Rollout Deadlock Rules:
- Scope
managedJobsNamespaceSelectorinkueue-manager-config(kubectl label namespace llm-d-rebalancing kueue-managed=true) so Kueue'spodintegration never interceptskube-system. - Put
kueue.x-k8s.io/queue-name: model-a-lqonspec.template.metadata.labels(the Pod template), NOT onDeployment.metadata.labels(Kueue'svdeployment.kb.iowebhook treats Deployment-levelqueue-nameas immutable, breakingkubectl applyand Helm upgrades). - Always set
strategy.rollingUpdate: {maxSurge: 0, maxUnavailable: 1}so rollouts terminate an old pod to release quota before admitting the new pod.
2. Cold start, fast actuation and model registry technologies¶
Sources: Reuse Warm Model Servers (FMA), Scale from Zero with FMA and KEDA, Restore from Pod Snapshots, Transfer Weights Peer-to-Peer (ModelExpress), Load and Cache Model Weights
| Fast-Actuation Technology | Core Mechanism & Architecture | Typical Ready / Transfer Time | Multi-Chip (TP > 1) Support? |
Infrastructure Prerequisites & Engine Flags | Critical Operational Caveats |
|---|---|---|---|---|---|
1. Fast Model Actuation (FMA v0.6.5 + KEDA Scale-from-Zero) |
Decouples GPU quota reservation (Server-Requesting Pod) from execution (Node Launcher Pod via dual-pods-controller + state-change-reflector patching dual-pods.llm-d.ai/vllm-instance-signature):• Hot Start: wakes sleeping vLLM ( --enable-sleep-mode, dual-pods.llm-d.ai/sleeping=true) from CPU RAM over PCIe• Warm Start: spawns from pre-imported Python zygote |
Near-instant hot start instead of a minutes-scale cold start (KEDA cooldownPeriod: 30 scales to 0) |
Single-node GPU UUID binding | CRDs: LauncherConfig, LauncherPopulationPolicy, InferenceServerConfig; RBAC: fma-node-viewer ClusterRole + fma-launcher-pod-state-writer Role |
Strict Teardown Order: Delete modelserver requester resources and wait for dual-pods.llm-d.ai/dual pods to terminate before running helm uninstall fma to avoid stuck finalizers. |
2. GKE Pod Snapshots (gVisor + GCS) |
Pod 1 loads weights, captures CUDA graphs, offloads VRAM (engine.sleep(1) in vLLM or POST /release_memory_occupation in SGLang), purges MODEL_CACHE_DIR, and triggers /proc/gvisor/checkpoint (PodSnapshotPolicy triggerConfig.type: workload, postCheckpoint: resume); Pods \(2..N\) stream pages.img from GCS (componentCount > 1 parallel upload) and call wake_up() / /resume_memory_occupation |
Restores "in seconds", skipping minutes of load and compile | No (TP=1, DP=1 Single-GPU only) |
GKE --enable-pod-snapshots, --sandbox type=gvisor, Hierarchical Namespace GCS bucket (PodSnapshotStorageConfig), SNAPSHOT_PROVIDER=gke_gvisor,• vLLM: --enable-sleep-mode --safetensors-load-strategy eager, VLLM_HOST_IP=127.0.0.1• SGLang: --enable-memory-saver --enable-weights-cpu-backup + /health probe override |
Env var changes do not invalidate snapshot hashes (run kubectl delete podsnapshots --all after changing env/Secrets); delete PodSnapshot objects before PodSnapshotStorageConfig so GKE cleans up GCS objects. |
3. NVIDIA ModelExpress P2P (--load-format=mx) |
Seed Pod 1 downloads weights once and registers HBM tensors in ModelMetadata & ModelCacheEntry CRDs (modelexpress-server :8001); Receiver Pods \(2..N\) pull weights directly from Seed GPU HBM \(\rightarrow\) Receiver GPU HBM over NIXL RDMA (+ optional torch.compile artifact transfer cutting compile 20.1s -> 3.4s) |
0.70 s (~382 Gbps GKE A3U RoCE) to 0.93 s (~287 Gbps H200 IB) per TP rank (vs 30.3 s on warm NFS) |
Yes (TP=1..8+ per-rank transfer) |
modelexpress==0.5.0, google-crc32c==1.8.0, --load-format=mx, MX_RDMA_NIC_PIN=auto; Overlays: base (no RDMA req), coreweave (rdma/ib: 2), gke (GPU DRA + DRANet mrdma.google.com); set MX_NIXL_BACKEND=LIBFABRIC on AWS EFA |
Watch for falling back to disk load if seed pod isn't Ready=True yet; base ports MX_METADATA_PORT=5555 & MX_WORKER_GRPC_PORT=6555 allocate base + device_id per TP rank. |
4. Persistent Weight Caches & Private Model Registries (HF / MatrixHub / ModelScope) |
• Shared PVC / NVMe hostPath: Mounts HF_HOME on RWX PVC (/model-cache) or node NVMe• MatrixHub: Self-hosted registry proxy ( HF_ENDPOINT="http://<matrixhub>:9527")• ModelScope: Mirror registry ( VLLM_USE_MODELSCOPE=True, MODELSCOPE_CACHE=/model-cache) |
Weight load: ~10–30 sSkips 30–120 s of torch.compile / XLA / Triton JIT |
Yes (TP=1..N, GPU & Cloud TPU) |
RWX StorageClass (Filestore standard-rwx, Lustre, EFS, CephFS) or local NVMe SSD + pinned --revision and --tokenizer-revision commit SHAs |
Always pin exact --revision SHAs so replicas never drift across upstream repo pushes; compile caches are hardware-SKU and engine-version specific. |
Note
The ModelExpress figures (0.70 s at about 382 Gbps, 0.93 s at about 287 Gbps, 30.3 s from warm NFS, compile 20.1 s to 3.4 s) are the guide's GPU measurements. FMA, snapshots and ModelExpress are GPU paths; on TPU the compile cache and weight caches in row 4 are what apply (chapter 21, startup guide).
5.5 CI testing, benchmarking, roadmap and agent evaluation suites¶
In one sentence: Production readiness across TorchTPU and
llm-dis enforced through Buildkite Kueue-scheduled CI lanes (tests,integration,perf,verify), regression gates (check_regression.py: a 5% perf tolerance; for accuracy, an allowed drop of max(1.5 pp, 1.645 standard errors of the difference)), 6 standardized fleet benchmark harnesses (llmdbenchmark), a zero-dependency smoke gate (healthcheck.sh), and the Grounded, Bounded, Checked Harbor verifiers of thetpu-agent-suite.
CI promotion, regression gates and Harbor agent verification¶
The three projects gate different things and run separately: vLLM-TorchTPU gates pull requests (perf and eval on labelled PRs and nightly), llm-d checks a deployed stack, and the TPU Agent Suite grades agent runs. Only within each group does one gate lead to the next.
1. vLLM-TorchTPU testing: pytest markers, Buildkite lanes and pre-commit¶
Sources: Testing & CI Guide, Benchmarking & Evaluation Guide
A. Pytest hardware markers and local test commands (pyproject.toml and .buildkite/pipeline_tests.yml)¶
| Pytest Marker / Suite | CI Pod Hardware | Purpose & Ordering Rules | Local Command |
|---|---|---|---|
| 1. Unmarked (Default CPU) | CPU Pod (JAX_PLATFORMS=cpu) |
Fast unit tests with mocked TPU devices; module imports must work without TPU hardware. | JAX_PLATFORMS=cpu pytest tests/ -sv --timeout=600 -m "not tpu_test and not multichip and not nightly" |
2. @pytest.mark.tpu_test |
TPU v7x 1x1x1 (1 chip / 2 dies) |
Single-host physical TPU tests (torch.device("tpu") / device fixture). |
pytest tests/ -sv --timeout=600 --ignore=tests/entrypoints/llm/test_speculative_decoding.py -m "tpu_test and not nightly and not multichip" |
3. @pytest.mark.multichip |
TPU v7x 2x2x1 (4 chips / 8 dies) |
Multi-chip distributed (TP/EP/DP) and collective kernel tests. |
pytest tests/ -sv --timeout=600 --ignore=tests/entrypoints/llm/test_speculative_decoding.py -m "not nightly and multichip" |
4. test_speculative_decoding.py |
TPU v7x 1x1x1 & 2x2x1 |
Dedicated speculative decoding e2e suites (2-chip 1800s timeout; 8-chip DP+MTP 3600s timeout). |
pytest tests/entrypoints/llm/test_speculative_decoding.py -sv --timeout=1800 -m "not nightly and not multichip"pytest tests/entrypoints/llm/test_speculative_decoding.py -sv --timeout=3600 -m "not nightly and multichip" |
5. @pytest.mark.spawns_tpu_workers |
Multi-chip TPU slice | Spawns torch.distributed.run worker group; ordered by tests/conftest.py to run before any in-process TPU test in the same session. |
Combined with tpu_test or multichip. |
6. @pytest.mark.omni (tests_omni/) |
TPU v7x 1x1x1 (-omni image) |
Multimodal and diffusion model tests via vllm-omni (--extra omni --group omni-git). |
pytest tests_omni/ -sv --timeout=1200 -m "not nightly and omni" |
7. @pytest.mark.nightly |
Nightly CI (NIGHTLY=1, 02:00 PT) |
Long-running / full-checkpoint tests; must still carry tpu_test or multichip if TPU hardware is required. |
Triggered on PRs via run-full-ci label (NIGHTLY=1). |
B. Buildkite lanes, PR labels and pre-commit gates¶
- Buildkite Lanes (
.buildkite/scripts/bootstrap.shon Kueue Fleet): Uploadspipeline_<lane>.ymlacross 4 lanes (tests,integration,perf,verify) plusvllm-torchtpu-release(scripts/publish_nightly_images.shpublishingci,dev,prodimages to GAR andvllm/vllm-torchtpuon Docker Hub). - PR Trigger Labels:
ready+skip-tpu-ci: SetsSKIP_TPU_CI, running only image build,pyreflytype check, and CPU unit tests.ready+run-perf-eval: Triggerspipeline_perf.ymlguard configs (qwen3-coder-30b-fp8-tp8-ep).ready+run-full-ci: SetsNIGHTLY=1and executes the full nightly suite acrosstests,integration,perf, andverify..pre-commit-config.yamlhooks (pre-commit run --all-files):ruff-check&ruff-format: Enforces PEP 8 formatting (88-column width) and import sorting.pyrefly: Static type checking ([tool.pyrefly]inpyproject.toml).pymarkdown: Markdown formatting lint.check-env-reads: Enforces that all environment variable reads go exclusively throughsrc/vllm_torchtpu/envs.py.check-b023-baseline: Verifies that Pallas kernel files undersrc/vllm_torchtpu/kernels/do not introduce unintended Python loop-variable closures (B023).
2. Benchmarking harnesses (run_benchmarks.sh, check_regression.py, llmdbenchmark, healthcheck.sh)¶
Sources: Benchmarking & Evaluation Guide, Performance assessment, llm-d Deployment Smoke Test, the TorchTPU repository
| Tool / Harness | Primary Domain | CLI Invocation | Key Metrics & Statistical Gate Logic | Critical Operational Nuances |
|---|---|---|---|---|
run_benchmarks.sh (serving & spec_bench modes) |
vllm-torchtpu Automated TPU v7x-8 Perf, Spec-Bench & Accuracy Sweep |
./scripts/vllm/benchmarking/run_benchmarks.sh --config qwen3-coder-30b-fp8-tp8-ep --results-dir /tmp/perfSpec-Bench: ./scripts/vllm/benchmarking/run_benchmarks.sh --config llama-3.3-70b-eagle3 |
Sweeps each config's ISL/OSL pairs \(\times\) concurrency (serving; the guide's example cell is 1024/1024 at concurrency 64), or SPEC_BS_LIST \(\times\) SPEC_K_LIST (ngram, eagle3, mtp, dflash, dspark \(\rightarrow\) summarize_spec_bench.py) |
Forces fp8 KV cache; set CAPTURE_PROFILE=1 to run an un-scored --profile pass; set BENCHMARK_WARMUP_RUNS=1 to discard warmup pass. |
check_regression.py (--mode perf & --mode eval) |
CI Statistical Performance & Accuracy Gate | python3 scripts/vllm/benchmarking/check_regression.py --mode perf --results-dir <DIR> --baseline scripts/vllm/benchmarking/baselines/perf/<cfg>.baseline.jsonpython3 ... --mode eval --results-dir <DIR> --baseline .../eval/<cfg>.<task>.baseline.json |
• --mode perf (5% tolerance): Gates Median TPOT, Total/Output tok/s, Completed requests floor, and Median TTFT (--gate-ttft-max-concurrency 0 omits TTFT under closed-loop queueing)• --mode eval (1.5pp + 95% 1-sided z-test): Allowed drop on mmlu_llama, mmlu_pro, humaneval_plus_tpu, mbpp_plus_tpu is \(\max(\text{tol}, 1.645 \sqrt{\text{se}_{\text{base}}^2 + \text{se}_{\text{run}}^2})\) |
If only baseline has stderr: \(\sqrt{2}\cdot\text{se}_{\text{base}}\); if only run has stderr: \(\text{se}_{\text{run}}\). Set EVAL_SOFT_FAIL=1 on new baselines to emit ::warning on eval while keeping perf blocking. Tune lm_eval via EXTRA_LM_EVAL_MODEL_ARGS & LM_EVAL_GEN_KWARGS. |
llmdbenchmark (six harnesses + llm-d-prism) |
In-Cluster Multi-Replica llm-d Fleet Benchmarking |
llmdbenchmark --workspace ./res --spec guides/inference-scheduling run --endpoint-url "${URL}" --gateway-class gke --model "Qwen/Qwen3-32B" --namespace "${NS}" --harness inference-perf --workload sanity_random.yaml --monitoring |
6 Supported Harnesses: 1. inference-perf (default step-load)2. guidellm (sweep/rate)3. aiperf (GenAI-Perf)4. inferencemax5. vllm-benchmark6. lm-eval (accuracy)+ deploys llm-d-prism dashboard |
On GKE, enable GcpFilestoreCsiDriver=ENABLED (standard-rwx) or pass --no-pvc; tune timeouts via --wait-timeout, --pvc-bind-timeout 1200, --data-access-timeout 1200 and CPU via LLMDBENCH_HARNESS_CPU_NR. Cleanup: delete llm-d-prism deployment before pvc/workload-pvc. |
torch_tpu.perflab |
Training & Kernel MFU / Step-Time Benchmarking | perflab's registered benchmarks (registry.py, benchmark_registry.pbtxt), timed by measure.py; how to read them is chapter 24 |
Warm-up until the compile count stops changing (10 to 20 steps), 10 timed steps with GC disabled, wall and device step time, MFU from wall and device time (warns above 1), with FLOPs from FlopCounterMode |
Peaks from perflab.target are per device. |
healthcheck.sh (Smoke Test) |
Zero-Dependency Post-Deploy & CI/CD Readiness Gate | ./docs/operations/validation/smoke-test/healthcheck.sh --endpoint http://localhost:8000 --max-latency 5000 --api chat --output json |
Sequential checks: GET /health (a warning unless --require-health) \(\rightarrow\) GET /v1/models \(\rightarrow\) an inference request (latency_ms <= MAX_LATENCY when -l is set) |
Use --api chat for chat-only models; pass -m <model-id> explicitly if jq is not installed in the container. |
3. tpu-agent-suite design, the suite-to-Harbor compiler and verifiers¶
Sources: the TPU Agent Suite repository, eval/verifiers, Introducing the TPU agent suite (preview): Open source agents for PyTorch on Cloud TPU
A. Three design choices and four specialist sub-agents (tpu-agent front-end router)¶
- Grounded (
tpu-knowledge-base): Hardware/software answers are retrieved from curated TPU documentation and returned with verifiable source citations. - Bounded (
tpu-kernel-development&tpu-diagnostics): Pallas kernel tuning executes one attempt at a time within a strict attempt budget, logs every result, and hands back a comparison table of all attempts + the winning kernel. - Checked (
tpu-model-onboarding): Follows a deterministic checklist on TPU VMs or GKE: verifies HBM fit, triesvLLMon TorchTPU first (falling back to native PyTorch on TorchTPU if unsupported), deploys and health-checks the endpoint, and validates numerical math parity on the TPU against the original PyTorch model on CPU before returning.
B. Suite-to-Harbor compiler (eval/suite_to_harbor/) and deterministic verifiers (eval/verifiers/)¶
suite_to_harbor.py (compile_suite) validates declarative YAML suites via Pydantic v2 schema.py (EvalSuite, TestCase, ScriptCheck, ExpectationCriterion), stages gs:// assets via gcs_utils.py (fetch_gcs_asset), and generates Harbor task bundles (task.toml, reward.toml, judge.toml, environment/Dockerfile, tests/test.sh) graded by the deterministic verifiers below:
| # | Verifier / Grading Module | Key Classes & Functions | Deterministic Grading Formula & Verification Logic |
|---|---|---|---|
| 1 | onboard_hillclimb/calculate_speedup.py |
DeterministicSpeedupEvaluator, BenchmarkRunMetrics |
Discovers baseline and optimized benchmark artifacts across serving regimes (1k1k, 1k8k, 8k1k) and concurrencies, validates zero failed requests and sane TTFT/ITL/throughput bounds, computes geometric-mean speedup across regimes, and writes speedup_analysis.json. |
| 2 | onboard_hillclimb/grade.py & onboard/grade.py |
regrade_job, find_trial_directories, detect_model_name |
Offline RewardKit regrade engines that inspect completed Harbor job directories, sync verifier scripts, re-evaluate regime sweeps, speedup, tool efficiency, and subagent delegation, and generate consolidated Markdown/JSON leaderboards. |
| 3 | onboard/tests/regime_sweep/verify_regime_sweeps.py |
detect_required_regimes, evaluate_regime_sweeps |
Parses instruction prompt for required (input_len, output_len) regimes and concurrency sweeps, extracts benchmark results from workspace files and trajectory logs, and scores coverage + validity. |
| 4 | xprof/check_schema_answer.py |
grade, check_task_grade, _check_field |
Grades agent's answer.json against ground-truth XProf .xplane.pb answer.json and answer.schema.json, supporting numeric tolerances (atol, rtol), string/enum matching, and cross-field ordering constraints. |
| 5 | common/invoked_subagent.py & check_agent_utilized.py |
invoked_subagent, delegations, check_agent_utilized |
Parses Harbor trajectory.json (across both Claude Code Agent/Task and Antigravity invoke_subagent) to verify that tpu-agent delegated to the expected specialist sub-agent(s). |
| 6 | efficiency_metrics/valid_tool_calls.py |
valid_tool_calls, _collect_tool_call_outcomes |
Computes valid_calls / total_calls ratio from trajectory.json, penalizing non-zero exit codes, tool exceptions, and denied hook calls. |
| 7 | Evaluation Datasets & Suites (eval/datasets/ & eval/suites/) |
smoke-check, nightly-functional, nightly-onboard-optimize, jaxbench-level1, tpu-knowledge-base/cset, xprof, tpu-query-understanding, onboarding*, tpu-hello-world* |
Covers PR smoke gates, Pallas kernel optimization tasks (jaxbench-level1), cited TPU QA tasks, XProf .xplane.pb diagnostics, query understanding, and e2e HF model onboarding + hillclimbing. |
4. vLLM-TorchTPU and TorchTPU Q4 2026 roadmap¶
Source: vLLM TorchTPU roadmap (last updated October 19, 2026; vllm-torchtpu shares the torch_tpu runtime, the Tokamax kernel library and the TPU recipes with sglang-torchtpu, so platform milestones benefit both; dates are planning targets, not commitments)
| Target Window | Milestone | Area | Key Technical Deliverables |
|---|---|---|---|
| October 2026 | vLLM TorchTPU OSS Launch & Inferact Co-Maintainership | Core OSS & Governance | Public launch of vllm-project/vllm-torchtpu & google-pytorch/torch_tpu backed by a contributor pool (256 v6e / 32 v7x chips), plus Inferact co-maintainership delivering custom megakernels and price-performance results on InferenceX & AgentX. |
| October 2026 | TPU Agent Suite (Experimental) & Ray | Agentic Tooling & Orchestration | Experimental release of the TPU Agent Suite and native Ray integration for distributed orchestration and agentic developer workflows on Cloud TPU. |
| October 2026 | 100% Tokamax PyTorch Interfaces & Ironwood FP8 Recipes | Kernels & Recipes | Production PyTorch interfaces for 100% of openxla/tokamax kernels shared across vllm-torchtpu, sglang-torchtpu, and torchtitan; reproducible TPU v7x FP8 W8A8 recipes for Qwen 3.5 397B & Gemma 4. |
| October 2026 | Multi-Host xP-yD Disaggregation, TPU-Sync & Lustre KV Offload | Distributed Serving & Memory | Low-latency multi-host llm-d xP-yD disaggregation + zero-copy TPU-Sync KV-cache connectors across host RAM and Google Cloud Managed Lustre, scaling context windows from 128K to 1M+ tokens. |
| November 2026 | 24-Hour Day-0 Model Onboarding & Public Nightly CI Support Matrix | Community & Tooling | Automated CI pipeline to ingest, benchmark, and publish support matrices (BF16, FP8, MXFP4, eval scores) for newly released open-weight models within 24 hours of launch. |
| November 2026 | Speculative Decoding, Native Diffusion (vllm-omni) & 1M AgentX Benchmarks |
Latency & Multimodal | Multi-Token Prediction (MTP) & multi-host speculative decoding; native video/image diffusion serving (Wan 2.2, Lightrick2) via vllm-omni; AgentX submissions for Qwen 3.5, Kimi K3, and GLM 5.2/5.3 (1M context). |
| December 2026 | DeepSeek V4 Readiness & Smart Memory-Tier Routing | Frontier Models & Routing | Day-0 functional & kernel optimization for DeepSeek V4, plus prefix/cache/session-aware routing, dynamic length bucketing, and llm-d TPU memory-tier routing. |













