Recipes: environment, training, serving and orchestration¶
Related chapters
Section 3.1 is covered in depth in chapter 8 (with the guides Install on GKE and Ray on TPU), 3.2 in chapter 9, 3.3 in chapter 14, chapter 15 and chapter 16, 3.4 in chapter 18 and chapter 19 (with the Serving guides), 3.5 in chapter 20 and chapter 21 (with the llm-d guides), and 3.6 in chapter 22 with the vLLM-TorchTPU v7x recipes and llm-d model recipes. Where a command here and a guide differ in detail, follow the guide.
This page collects recipes for single-host TPU VMs, multi-host Pod slices, GKE clusters, distributed training (torch_tpu, TorchTitan, Miles RL), inference (vLLM-TorchTPU, SGLang-TorchTPU) and llm-d orchestration. They are grouped by task: provisioning and installation (3.1), TorchTPU idioms (3.2), distributed training (3.3), serving (3.4), llm-d on Kubernetes (3.5) and model blueprints (3.6).
3.1 Provisioning, installation and cluster infrastructure¶
3.1.1 Single-host and multi-host TPU VM provisioning¶
Overview: A Cloud TPU slice is either a single host VM directly attached to 1–8 chips over PCIe/ICI, or a lockstep fleet of \(N\) worker VMs whose chips are joined by a 2D or 3D torus of Inter-Chip Interconnect (ICI); every worker must run the same SPMD program.
One command reaches every worker VM of the slice over SSH, and every worker must run it. Collectives between the slice's chips move over ICI, not through the worker VMs; only links between neighbouring workers are drawn, not the torus wiring.
Provisioning methods, FLEX_START and machine types¶
| Provisioning Method | Command Surface | Target Topologies & Zones | Machine Types (--machine-type) |
Runtime / Image Family | Quota Metric & Key Operational Behavior |
|---|---|---|---|---|---|
| Direct TPU VM API | gcloud compute tpus tpu-vm create |
Single-host (v5p-8) & Multi-host (v5p-16+) on the Cloud TPU API |
Implied by --accelerator-type |
tpu-vm-v4-base, v2-alpha-tpuv5 |
Provisions entire slice atomically (100GB default boot disk); supports --worker=all SSH fan-out. The Cloud TPU API is in maintenance mode and does not support TPU7x and later (Google Cloud: queued resources); provision v7x through GKE (section 3.1.2). |
| Queued Resources API | gcloud alpha compute tpus queued-resources create |
Legacy v5e (us-west4-a, europe-west4-b), v5p, v4 |
--accelerator-type=v5litepod-4 |
v2-alpha-tpuv5-lite |
v5e Quota: tpu-v5s-litepod-serving-preemptible (or -preemptible for training); supports --provisioning-model=flex-start / --spot. Not available for v7x (Google Cloud: queued resources); TorchTPU's TPU VM guide points to GKE for recent hardware. |
GCE Instance API (FLEX_START / SPOT) |
gcloud compute instances create |
Single-host 4-chip VMs (v6e: us-east5-a/b, us-central1-a, europe-west4-a, sa-west1-a; v5p: us-east5-a, us-central1-a) |
ct6e-standard-4t (1t/4t/8t), ct5p-hightpu-4t, tpu7x-standard-4t |
--image-project=ubuntu-os-accelerator-images--image-family=ubuntu-accel-2204-amd64-tpu-v5e-v5p-v6e |
Quota: PREEMPTIBLE_TPU_V6E / PREEMPTIBLE_TPU_V5P + GPUS_ALL_REGIONS above 0 (request 8 or 16). FLEX_START guarantees up to 7 days (--max-run-duration=168h, default 24h); no stop/restart (must delete & use Persistent hyperdisk-balanced / hyperdisk-ml). |
Recipe 1: quota checks, a FLEX_START VM, a multi-host slice and verification on every worker¶
References: Get started with TorchTPU on a TPU VM, TPU Builders Program Getting Started Guide, Google Cloud: queued resources, Hugging Face and TorchTPU: TPUs, Natively.
# ==============================================================================
# 1. PREREQUISITES AND QUOTA CHECKS (billing, APIs, quotas)
# ==============================================================================
export PROJECT_ID="your-net-new-gcp-project-id" # Use a net-new project to avoid Code 10 tenant error
export ZONE="us-east5-a"
export TPU_NAME="torchtpu-v6e-slice"
gcloud config set project "${PROJECT_ID}"
gcloud config set compute/zone "${ZONE}"
gcloud services enable compute.googleapis.com tpu.googleapis.com
gcloud components install alpha --quiet
# Check the global accelerator quota (GPUS_ALL_REGIONS must be above 0) and the regional TPU quota
gcloud compute project-info describe --flatten="quotas[]" \
--format="table(quotas.metric,quotas.limit,quotas.usage)" | grep -i GPUS_ALL_REGIONS
gcloud compute regions describe "${ZONE%-*}" --flatten="quotas[]" \
--format="table(quotas.metric,quotas.limit,quotas.usage)" | grep -i TPU
# ==============================================================================
# 2A. PERSISTENT HYPERDISK + GCE FLEX_START VM (4-CHIP SINGLE-HOST, UP TO 7 DAYS)
# ==============================================================================
gcloud compute disks create my-data-disk --size=200GB --zone="${ZONE}" --type=hyperdisk-balanced
cat << 'EOF' > startup.sh
#!/bin/bash
set -euxo pipefail
if [ -z "$(sudo blkid /dev/disk/by-id/google-data-disk)" ]; then
sudo mkfs.ext4 -m 0 -E lazy_itable_init=0,lazy_journal_init=0,discard /dev/disk/by-id/google-data-disk
fi
sudo mkdir -p /mnt/data && sudo mount -o discard,defaults /dev/disk/by-id/google-data-disk /mnt/data
sudo chmod a+w /mnt/data
export HF_HOME=/mnt/data/huggingface
EOF
gcloud compute instances create "${TPU_NAME}-vm" \
--zone="${ZONE}" \
--machine-type=ct6e-standard-4t \
--provisioning-model=FLEX_START \
--request-valid-for-duration=2h \
--max-run-duration=168h \
--instance-termination-action=DELETE \
--boot-disk-size=100GB \
--image-project=ubuntu-os-accelerator-images \
--image-family=ubuntu-accel-2204-amd64-tpu-v5e-v5p-v6e \
--maintenance-policy=TERMINATE \
--disk=name=my-data-disk,device-name=data-disk,mode=rw,boot=no \
--metadata-from-file=startup-script=startup.sh
# ==============================================================================
# 2B. QUEUED RESOURCE ON THE CLOUD TPU API (v5e, v5p, v4; NOT TPU7x)
# ==============================================================================
# Builders guide v5e request; set ZONE to a zone that offers the accelerator type.
# For a multi-host slice, pass a larger --accelerator-type (for example v5p-32).
gcloud alpha compute tpus queued-resources create "${TPU_NAME}-qr" \
--node-id="${TPU_NAME}" --zone="${ZONE}" \
--accelerator-type=v5litepod-4 --runtime-version=v2-alpha-tpuv5-lite \
--provisioning-model=flex-start --max-run-duration=4h --valid-until-duration=4h
# ==============================================================================
# 3. TORCHTPU INSTALL AND VERIFICATION ON EVERY WORKER
# ==============================================================================
gcloud compute tpus tpu-vm ssh "${TPU_NAME}" --zone="${ZONE}" --worker=all --command="
sudo apt update && sudo apt install -y python3.12 python3.12-venv google-perftools
python3.12 -m venv ~/env && source ~/env/bin/activate
pip install --upgrade pip
# Single command installs CPU PyTorch + TorchTPU + libtpu (avoids pulling multi-GB CUDA wheels):
pip install torch_tpu==0.2.0 --extra-index-url https://download.pytorch.org/whl/cpu
"
# Verify hardware via PyTorch 2.11+ torch.accelerator & torch.tpu APIs:
gcloud compute tpus tpu-vm ssh "${TPU_NAME}" --zone="${ZONE}" --worker=all --command='
source ~/env/bin/activate
python3 -c "
import socket, torch
device = torch.device(\"tpu\")
x = torch.ones((5, 5), device=device) + torch.randn((5, 5), device=\"tpu\")
print(f\"[{socket.gethostname()}] Device={device} | Count={torch.accelerator.device_count()} | \"
f\"Model={torch.tpu.get_device_properties().name} | Sum={x.cpu().sum():.4f}\")
"'
The install line pins the release, as TorchTPU's README does, so every worker gets the same version. A slice whose workers resolved different versions at different times fails in ways that look like hardware faults (chapter 8). Queued-resource flags follow Google's queued resources documentation, whose examples use v5e and v5p.
Warning
Onboarding traps (GPUS_ALL_REGIONS=0, 24h termination and the Code 10 tenant error):
GPUS_ALL_REGIONS = 0global block: New GCP billing accounts default tocompute.googleapis.com/gpus_all_regions = 0, causing TPU requests to hang inWAITING_FOR_RESOURCESor fail withRESOURCE_POOL_EXHAUSTEDeven when regionalPREEMPTIBLE_TPU_V6Equota is available. Link a verified payment method and requestGPUS_ALL_REGIONSof 8 or 16 before requesting TPU quota; any value above 0 unblocks TPU requests (chapter 8).- 24-hour default
FLEX_STARTtermination:FLEX_STARTVMs terminate after 24 hours by default unless--max-run-duration=168h(7 days) and--instance-termination-action=DELETEare explicitly passed. Code 10: Failed to perform tenant project creation: Caused by reusing a legacy TRC GCP project; create a new GCP project.
3.1.2 GKE Standard and Autopilot TPU node pools and Kubernetes orchestration CRDs¶
Overview: On Google Kubernetes Engine (GKE), single-host TPU workloads schedule as standard Pods via topology node selectors, whereas multi-host TPU slices require gang-scheduled indexed controllers (JobSet for training, LeaderWorkerSet for unified multi-host inference, and DisaggregatedSet, which runs one LeaderWorkerSet per role, for decoupled Prefill/Decode pools) so GKE provisions an intact physical 2D/3D ICI torus with high-speed RDMA/RoCE or DCN networking.
JobSet and LeaderWorkerSet place one pod on every host of the slice; DisaggregatedSet does not schedule pods itself but runs one LeaderWorkerSet per role.
GKE TPU generations, node selectors, TORCH_TPU_TOPOLOGY and resource requests¶
| Generation | GKE gke-tpu-accelerator Label |
Chips / Host | google.com/tpu K8s Resource Request |
gke-tpu-slice-topology / gke-tpu-topology |
TORCH_TPU_TOPOLOGY 4-Tuple (X,Y,Z,CoresPerChip) |
|---|---|---|---|---|---|
| TPU v5e | tpu-v5-lite-podslice |
4 or 8 (ct5lp-hightpu-4t / 8t) |
4 or 8 (1 chip = 1 TensorCore) |
1x1, 2x2, 2x4 (1-host); 4x4, 4x8, 16x16 (2D Torus) |
Auto-detect with eval "$(python3 -m torch.tpu.distributed)" and read the value from the log |
| TPU v5p | tpu-v5p-slice |
4 (ct5p-hightpu-4t) |
4 (1 chip = 2 TensorCores = 8 TCs/host) |
2x2x1 (1-host); 2x2x2, 2x2x4, 4x4x4 (3D Torus) |
Auto-detect with eval "$(python3 -m torch.tpu.distributed)" and read the value from the log |
| TPU v6e (Trillium) | tpu-v6e-slice |
4 or 8 (ct6e-standard-4t / 8t) |
4 or 8 (1 chip = 1 TensorCore + 2 SparseCores) |
1x1, 2x2, 2x4 (1-host); 4x4, 4x8, 8x16 (2D Torus) |
Auto-detect with eval "$(python3 -m torch.tpu.distributed)" and read the value from the log |
| TPU v7x (Ironwood) | tpu7x |
4 (tpu7x-standard-4t) |
4 (1 chip = 2 TensorCores = 8 TCs/host; 192 GiB HBM3e/chip) |
2x2x1 (1-host = 4 chips); 2x2x2 (8 chips); 2x2x4 (16 chips); 2x4x4 (32 chips); 4x4x4 (64 chips) |
"1,1,1,1" (1 TensorCore); "2,2,1,2" (1 host, 8 TCs); "4,4,4,2" (64 chips), as in TorchTPU's GKE manifests |
The v7x TORCH_TPU_TOPOLOGY values are the ones TorchTPU's GKE guide manifests use. On other generations, let eval "$(python3 -m torch.tpu.distributed)" detect the value and confirm it in the job's log (chapter 8, Install on GKE).
Info
GKE google.com/tpu vs TORCH_TPU_TOPOLOGY & DataLoader(num_workers=0) Rules:
- Physical Chip Requests vs TensorCores: On GKE (
tpu-v5p-slice,tpu7x), Kubernetes always counts physical chips (google.com/tpu: 4per2x2x1node). Inside the container,TORCH_TPU_TOPOLOGYis a 4-tuple"X,Y,Z,CoresPerChip"("1,1,1,1"to run a single-core job on 1 TensorCore;"2,2,1,2"for all 8 TensorCores on 1 host;"4,4,4,2"for 128 TensorCores across a 16-host4x4x4JobSet). Instead of hardcodingTORCH_TPU_TOPOLOGYandTORCH_TPU_SLICEBUILDER_ADDRESSES, runeval "$(python3 -m torch.tpu.distributed)" && export TORCH_TPU_TOPOLOGY TORCH_TPU_SLICEBUILDER_ADDRESSES(or calltorch.tpu.distributed.set_tpu_launch_env()in Python beforetorchrun). DataLoader(num_workers=0)Lockfile Constraint: When running upstream PyTorch scripts (e.g.,pytorch/examples/mnist) on TPU withoutspawn, setnum_workers=0inDataLoader(or pass--no-accelto avoid legacy flags) so forked worker subprocesses do not attempt to re-open the exclusivelibtpuVFIO device lockfile.- Public Container Image:
us-docker.pkg.dev/ml-oss-artifacts-published/torch-tpu-public-release-container/torch-tpu:latest.
Recipe 2: GKE cluster and multi-host JobSet training (eval "$(python3 -m torch.tpu.distributed)")¶
References: Get started with TorchTPU on GKE, Announcing Ray support for PyTorch on Google TPUs, llm-d: Google Kubernetes Engine (GKE).
# 1. Create GKE Standard Cluster & Add a Multi-Host TPU Node Pool (e.g. v5p 4x4x4 or v7x 2x2x4)
gcloud container clusters create torchtpu-gke-cluster \
--project="${PROJECT_ID}" --location="${ZONE}" --release-channel=rapid \
--workload-pool="${PROJECT_ID}.svc.id.goog" --datapath-provider=ADVANCED_DATAPATH \
--addons=HttpLoadBalancing,GcpFilestoreCsiDriver,GcsFuseCsiDriver --gateway-api=standard
# General form of a TPU node pool (v5p, v6e). For v7x, see the note below the block.
gcloud container node-pools create NODE_POOL_NAME \
--cluster=torchtpu-gke-cluster --location=CONTROL_PLANE_LOCATION \
--node-locations=NODE_ZONE --machine-type=MACHINE_TYPE \
--tpu-topology=TPU_TOPOLOGY --placement-type=COMPACT
# 2. Install JobSet (current release, https://jobset.sigs.k8s.io/) and LeaderWorkerSet.
# llm-d recommends LWS 1.0.0 with the DisaggregatedSet API enabled:
helm install lws oci://registry.k8s.io/lws/charts/lws \
--version 1.0.0 --namespace lws-system --create-namespace \
--set enableDisaggregatedSet=true
On TPU v7x the node pool does not take --tpu-topology: the topology goes into a workload policy (gcloud compute resource-policies create workload-policy --type=HIGH_THROUGHPUT --accelerator-topology=...) that the node pool references with --placement-policy. Follow Google's Deploy TPU workloads in GKE Standard for the current v7x flags. Install the current JobSet release; llm-d's Model Server Orchestration page recommends LWS 1.0.0 installed with enableDisaggregatedSet=true, as above (chapter 8, Install on GKE).
# ==============================================================================
# Multi-Host Distributed Training with JobSet (Dynamic Topology Discovery + torchrun)
# ==============================================================================
apiVersion: jobset.x-k8s.io/v1alpha2
kind: JobSet
metadata:
name: torch-tpu-multihost-jobset
spec:
failurePolicy:
maxRestarts: 2
replicatedJobs:
- name: workers
replicas: 1
template:
spec:
parallelism: 16 # 16 hosts in a 4x4x4 slice (64 chips / 128 TensorCores)
completions: 16
backoffLimit: 0
completionMode: Indexed
template:
spec:
restartPolicy: Never
nodeSelector:
cloud.google.com/gke-tpu-accelerator: tpu-v5p-slice
cloud.google.com/gke-tpu-topology: 4x4x4
containers:
- name: torch-tpu
image: us-docker.pkg.dev/ml-oss-artifacts-published/torch-tpu-public-release-container/torch-tpu:latest
ports:
- containerPort: 29500
- containerPort: 8471
- containerPort: 8888
env:
- name: MASTER_ADDR
value: "torch-tpu-multihost-jobset-workers-0-0.torch-tpu-multihost-jobset"
- name: MASTER_PORT
value: "29500"
command: ["bash", "-c"]
args:
- |
# Auto-discover TORCH_TPU_TOPOLOGY ("4,4,4,2") & TORCH_TPU_SLICEBUILDER_ADDRESSES:
eval "$(python3 -m torch.tpu.distributed)"
export TORCH_TPU_TOPOLOGY TORCH_TPU_SLICEBUILDER_ADDRESSES
torchrun \
--nnodes=16 --nproc_per_node=8 \
--node_rank=$JOB_COMPLETION_INDEX \
--master_addr=$MASTER_ADDR --master_port=$MASTER_PORT \
train.py
resources:
requests:
google.com/tpu: 4
limits:
google.com/tpu: 4
Recipe 3: Ray on TPU (@ray.remote, SlicePlacementGroup, TorchTrainer and Ray Serve LLM)¶
Overview: Ray natively supports single-device-per-worker PyTorch on TPU (@ray.remote(resources={"TPU": 1})): Ray automatically sets TPU_VISIBLE_CHIPS so each Ray actor binds to an isolated TPU device, while SlicePlacementGroup and ScalingConfig(use_tpu=True, topology="4x4", accelerator_type="TPU-V6E") gang-schedule multi-host slices for TorchTrainer (backend="tpu_dist") and Ray Serve LLM.
Reference: Announcing Ray support for PyTorch on Google TPUs.
import os
import ray
import torch
import torch.distributed as dist
import ray.train.torch
from ray.train import ScalingConfig
from ray.train.torch import TorchTrainer
from ray.serve.llm import LLMConfig, LLMServingArgs, ModelLoadingConfig, build_openai_app
ray.init()
# ------------------------------------------------------------------------------
# A. Single-Device-Per-Worker Ray Actor (Ray Auto-Sets TPU_VISIBLE_CHIPS)
# ------------------------------------------------------------------------------
@ray.remote(resources={"TPU": 1})
def tpu_worker_task(x_val: float) -> str:
device = torch.device("tpu")
t = torch.ones((1024, 1024), device=device, dtype=torch.bfloat16) * x_val
return f"Chip={os.environ.get('TPU_VISIBLE_CHIPS')} | Device={torch.tpu.get_device_properties().name} | Sum={t.sum().item()}"
# ------------------------------------------------------------------------------
# B. Ray Train TorchTrainer with Multi-Slice / Topology-Aware ScalingConfig
# ------------------------------------------------------------------------------
def train_func_per_worker(config: dict):
# Ray Train initializes ProcessGroup with backend="tpu_dist" automatically
device = ray.train.torch.get_device()
model = torch.nn.Linear(4096, 4096).to(device=device, dtype=torch.bfloat16)
model = torch.compile(model, backend="tpu")
model = ray.train.torch.prepare_model(model)
opt = torch.optim.AdamW(model.parameters(), lr=1e-4)
for step in range(10):
x = torch.randn(8, 4096, device=device, dtype=torch.bfloat16)
loss = model(x).pow(2).mean()
opt.zero_grad()
loss.backward()
opt.step()
ray.train.report({"loss": loss.item(), "step": step})
trainer = TorchTrainer(
train_loop_per_worker=train_func_per_worker,
scaling_config=ScalingConfig(
num_workers=16, # 16 workers across a 4x4 v6e slice (1 chip/worker)
use_tpu=True,
topology="4x4",
accelerator_type="TPU-V6E",
resources_per_worker={"TPU": 1},
),
)
# ------------------------------------------------------------------------------
# C. Ray Serve LLM on TPU (vLLM Engine + Topology-Aware Placement Group)
# ------------------------------------------------------------------------------
llm_config = LLMConfig(
model_loading_config=ModelLoadingConfig(model_id="google/gemma-4-26B-A4B-it"),
accelerator_type="TPU-V6E",
accelerator_config={"kind": "tpu", "topology": "4x4"},
placement_group_config={"bundle_per_worker": {"TPU": 1}},
engine_kwargs={"tensor_parallel_size": 16, "enable_expert_parallel": True, "max_model_len": 8192},
)
app = build_openai_app(LLMServingArgs(llm_configs=[llm_config]))
Part C follows the Ray announcement's Ray Serve LLM example: the configs go into LLMServingArgs(llm_configs=[...]), and accelerator_config carries the slice topology (Ray on TPU, chapter 15).
Recipe 4: multi-host inference with LeaderWorkerSet (leaderworkerset.x-k8s.io/v1) and DisaggregatedSet (disaggregatedset.x-k8s.io/v1)¶
References: llm-d: Google Kubernetes Engine (GKE), llm-d: LeaderWorkerSet (LWS), llm-d: DisaggregatedSet, Safe Rollouts of Disaggregated Deployments with DisaggregatedSet.
# ==============================================================================
# A. LeaderWorkerSet (LWS) for Multi-Host Ray / SPMD Inference on TPU v7x (2x2x2 = 8 chips)
# ==============================================================================
apiVersion: leaderworkerset.x-k8s.io/v1
kind: LeaderWorkerSet
metadata:
name: vllm-tpu7x-multihost
labels:
llm-d.ai/inferenceServing: "true"
llm-d.ai/model: DeepSeek-V4
spec:
replicas: 2 # 2 independent 8-chip model replicas
startupPolicy: LeaderCreated
rolloutStrategy:
type: RollingUpdate
rollingUpdateConfiguration:
maxUnavailable: 1
maxSurge: 1
leaderWorkerTemplate:
size: 2 # 1 Leader Host + 1 Worker Host = 2 hosts (8 v7x chips)
restartPolicy: RecreateGroupAfterStart # CRITICAL: Atomic slice restart on any worker crash
subGroupPolicy: # Optional: Partition larger torus into smaller ICI islands
subGroupSize: 2
type: LeaderWorker
leaderTemplate:
metadata:
labels:
llm-d.ai/role: decode
spec:
nodeSelector:
cloud.google.com/gke-tpu-accelerator: tpu7x
cloud.google.com/gke-tpu-topology: 2x2x2
containers:
- name: vllm-leader
image: vllm/vllm-tpu:latest
command: ["bash", "-c"]
args:
- |
ray start --head --port=6379 --num-cpus=16 --resources='{"TPU": 4}'
until [ "$(ray status | grep -c 'node_')" -eq 2 ]; do sleep 2; done
vllm serve deepseek-ai/DeepSeek-V4-Flash \
--tensor-parallel-size 8 \
--distributed-executor-backend ray \
--port 8000
ports:
- containerPort: 8000
resources:
limits:
google.com/tpu: 4
requests:
google.com/tpu: 4
workerTemplate:
spec:
nodeSelector:
cloud.google.com/gke-tpu-accelerator: tpu7x
cloud.google.com/gke-tpu-topology: 2x2x2
containers:
- name: vllm-worker
image: vllm/vllm-tpu:latest
command: ["bash", "-c"]
args:
- |
ray start --address="${LWS_LEADER_ADDRESS}:6379" --num-cpus=16 --resources='{"TPU": 4}' --block
resources:
limits:
google.com/tpu: 4
requests:
google.com/tpu: 4
---
# ==============================================================================
# B. DisaggregatedSet for Coordinated Prefill/Decode Rollouts & Autoscaling
# ==============================================================================
apiVersion: disaggregatedset.x-k8s.io/v1
kind: DisaggregatedSet
metadata:
name: llm-d-pd-cluster
spec:
roles:
- name: prefill
spec:
replicas: 4
rolloutStrategy:
rollingUpdateConfiguration:
maxUnavailable: 1
maxSurge: 1
leaderWorkerTemplate:
size: 1
restartPolicy: RecreateGroupAfterStart
workerTemplate:
metadata:
labels:
llm-d.ai/inferenceServing: "true"
llm-d.ai/role: prefill
spec:
nodeSelector:
cloud.google.com/gke-tpu-accelerator: tpu7x
cloud.google.com/gke-tpu-topology: 2x2x1
containers:
- name: vllm-prefill
image: vllm/vllm-tpu:latest
resources:
limits:
google.com/tpu: 4
- name: decode
spec:
replicas: 2
rolloutStrategy:
rollingUpdateConfiguration:
maxUnavailable: 0
maxSurge: 1
leaderWorkerTemplate:
size: 2
restartPolicy: RecreateGroupAfterStart
workerTemplate:
metadata:
labels:
llm-d.ai/inferenceServing: "true"
llm-d.ai/role: decode
spec:
nodeSelector:
cloud.google.com/gke-tpu-accelerator: tpu7x
cloud.google.com/gke-tpu-topology: 2x2x2
containers:
- name: vllm-decode
image: vllm/vllm-tpu:latest
resources:
limits:
google.com/tpu: 4
A DisaggregatedSet (disaggregatedset.x-k8s.io/v1) puts replicas, leaderWorkerTemplate and rolloutStrategy.rollingUpdateConfiguration under each role's spec (llm-d: DisaggregatedSet, chapter 20, Rollouts).
The two manifests show the structure of a multi-host LWS replica and a prefill/decode DisaggregatedSet; the model, parallelism and slice sizes are placeholders. They run vllm/vllm-tpu, the upstream vLLM TPU image listed on llm-d's Artifacts page, with vLLM's generic Ray flags. For vLLM-TorchTPU, use the vllm/vllm-torchtpu image and its own multi-host modes (Serve across several TPU hosts), or start from llm-d's TPU overlays (llm-d quickstart on GKE TPU).
RDMA, RoCE and NIXL transports for P/D KV transfer¶
| Transport Layer | Environment Variable & Value | Required K8s Resource / Device Mount | Target Cloud / Interconnect | Latency / Bandwidth Characteristics |
|---|---|---|---|---|
| NIXL + UCX (RoCEv2 / InfiniBand) | UCX_TLS="rc,sm,self,cuda_copy,cuda_ipc"UCX_NET_DEVICES="mlx5_0:1" |
rdma/ib: 1 or rdma/roce_gdr: 1capabilities.add: ["IPC_LOCK"] |
GKE A3-Ultra/A4, CoreWeave IB, AKS dranet |
Zero-copy GPUDirect RDMA; sub-millisecond KV block transfer up to 400–800 Gbps/NIC. |
| NIXL + Libfabric (EFA / CXI) | NIXL_BACKEND="LIBFABRIC"FI_PROVIDER="efa" |
vpc.amazonaws.com/efa: 4 |
AWS EKS / ROSA (p5.48xlarge) |
OS-bypass SRD transport over AWS EFA NICs. |
| TPU Raiden / ICI + Host DRAM | --kv-transfer-config '{"kv_connector":"TPURaidenOffloadingConnector"}' |
/dev/shm (128Gi–256Gi) + privileged: true |
GKE TPU v6e / tpu7x |
Asynchronous TPU DMA engine \(\leftrightarrow\) Host DRAM pinned buffer (256 GiB) + DCN/ICI P/D transfer. |
3.1.3 Docker, wheels and tcmalloc¶
Overview: Because torch_tpu implements an Out-Of-Tree (PrivateUse1) C++ runtime on top of CPU PyTorch, building or installing vllm-torchtpu, sglang-torchtpu, and torchtitan requires strictly isolating CUDA dependencies (UV_TORCH_BACKEND=cpu, VLLM_TARGET_DEVICE=empty) and preloading tcmalloc, because the Python dispatch thread and the runtime's worker threads allocate and free objects across threads, which contends on glibc's default allocator.
Recipe 5: production Dockerfile and wheel installation (torch_tpu, vllm-torchtpu, sglang-torchtpu, torchtitan)¶
References: vLLM-TorchTPU: Installation, vLLM-TorchTPU: Docker images, SGLang‑TorchTPU: PyTorch‑Native Production Serving on TPUs, sglang-torchtpu repository, TorchTPU Dockerfile.
# syntax=docker/dockerfile:1
FROM ubuntu:24.04
ENV DEBIAN_FRONTEND=noninteractive \
PYTHONUNBUFFERED=1 \
PIP_NO_CACHE_DIR=1 \
# Preload tcmalloc: TorchTPU warns once at import when glibc malloc is the allocator
LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libtcmalloc_minimal.so.4
# 1. Install system dependencies, Python 3.12, and google-perftools (tcmalloc)
RUN apt-get update && apt-get install -y --no-install-recommends \
python3.12 python3.12-venv python3.12-dev python3-pip \
git curl wget build-essential cmake ninja-build pkg-config \
google-perftools libgoogle-perftools-dev numactl libibverbs-dev \
&& rm -rf /var/lib/apt/lists/*
# 2. Create isolated virtual environment via uv
RUN curl -LsSf https://astral.sh/uv/install.sh | sh
ENV PATH="/root/.local/bin:/opt/venv/bin:${PATH}"
RUN uv venv /opt/venv --python 3.12
# 3. Install TorchTPU, which pulls CPU PyTorch 2.11+, libtpu and JAX (CPU index avoids CUDA torch)
ENV UV_TORCH_BACKEND=cpu
RUN uv pip install torch_tpu==0.2.0 --extra-index-url https://download.pytorch.org/whl/cpu
# 4A. Install vLLM-TorchTPU: pulls upstream vllm (built with VLLM_TARGET_DEVICE="empty"),
# the vllm-torchtpu-core plugin, torch-tpu, libtpu and tpu-sync-torch
WORKDIR /workspace
RUN uv pip install vllm-torchtpu
# 4B. Install SGLang-TorchTPU from source (engine with the TPU manifest, then the plugin):
# Note: --no-deps on the plugin keeps pip from re-resolving dependencies
# git clone https://github.com/sgl-project/sglang-torchtpu.git /workspace/sglang-torchtpu
# RUN cd /workspace/sglang-torchtpu && \
# cp python/pyproject_tpu.toml python/pyproject.toml && \
# pip install --extra-index-url https://download.pytorch.org/whl/cpu -e python/ && \
# pip install --no-deps -e .
# 4C. TorchTitan: its TPU lane pins its own torch and torch_tpu under Python 3.14,
# so install it in a separate image or venv as chapter 14 shows.
# Container Launch Command with TPU VFIO Device Passthrough & Shared Memory
docker run --rm -it \
--privileged \
--network=host \
--shm-size=128g \
--ulimit memlock=-1 \
-e LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libtcmalloc_minimal.so.4 \
-v /mnt/disks/persist:/mnt/disks/persist \
us-docker.pkg.dev/your-project/torchtpu/runtime:latest bash
Tip
Why preload tcmalloc: On every import, TorchTPU checks whether tcmalloc is the process allocator and, if not, warns once with a message starting //TorchTpu/Performance/TcMalloc// (_tcmalloc_check.py). In eager execution the Python dispatch thread and the runtime's worker threads allocate and free objects across threads, which contends on glibc's default allocator. Any preloaded tcmalloc satisfies the check: TorchTPU's own Docker image preloads /usr/lib/x86_64-linux-gnu/libtcmalloc.so.4, and on a bare Ubuntu image the google-perftools package provides libtcmalloc_minimal.so.4.
The install steps match the book's install and serving guides: TorchTPU pinned with the PyTorch CPU index (chapter 8), uv pip install vllm-torchtpu, which pulls vllm-torchtpu-core itself (vLLM-TorchTPU quickstart), and SGLang-TorchTPU's source install with python/pyproject_tpu.toml (SGLang-TorchTPU quickstart). Let TorchTPU resolve JAX: its pyproject.toml requires jax >= 0.11.0 on Python 3.12, so an older pin conflicts. PJRT_DEVICE=TPU is a PyTorch/XLA variable that TorchTPU does not read.
3.2 TorchTPU idioms, API mapping and Hugging Face¶
Overview: Porting PyTorch from CUDA to torch_tpu requires zero model architecture rewrites when using torch.device("tpu") and torch.accelerator, provided you respect three XLA/TPU hardware laws: (1) Static or bucketed tensor shapes (avoiding dynamic host-dependent slicing), (2) Explicit matmul accumulator precision control (bfloat16 weights with float32 accumulation), and (3) Graph-captured optimizer steps (from torch.tpu.optimizers import SingleTraceTrainer, AdamW, Muon, Sgd) to eliminate per-parameter kernel launch overhead.
The three rules stated above: shapes the compiler can fix, an explicit matmul precision, and an optimizer step traced into the same graph as forward and backward. Together they let the step compile once.
3.2.1 API mapping and the training loop¶
CUDA to PyTorch 2.11+ torch.accelerator and torch.tpu¶
| Subsystem | Legacy CUDA Idiom | Recommended PyTorch 2.11+ torch.accelerator / torch.tpu API |
Internal / Legacy torch.tpu API (Requires TORCH_TPU_ALLOW_LEGACY_DEVICE_APIS=1) |
Critical Hardware / Compiler Nuance |
|---|---|---|---|---|
| Device Selection | torch.cuda.set_device(rank) |
torch.accelerator.set_device_index(rank)torch.accelerator.current_device_index() |
torch.tpu.set_device(rank)torch.tpu.current_device() |
In PyTorch 2.11+, redundant device management APIs on torch.tpu raise RuntimeError unless TORCH_TPU_ALLOW_LEGACY_DEVICE_APIS=1 is set; always prefer torch.accelerator.*. |
| Device Count & Info | torch.cuda.device_count() |
torch.accelerator.device_count()torch.tpu.get_device_properties(dev) |
torch.tpu.device_count()torch.tpu.is_available() |
get_device_properties() returns name, devices_per_chip, hbm_bytes_per_device, bf16_flops_per_device and more; total_memory and multi_processor_count are deprecated since TorchTPU 0.2.1. |
| Synchronization | torch.cuda.synchronize() |
torch.accelerator.synchronize() |
torch.tpu.synchronize() |
Blocks host thread until all queued PJRT/XLA futures on the device complete. |
| Streams & Core Pinning | torch.cuda.Stream() |
torch.tpu.Stream(device=dev, pinned="dense" \| "sparse") |
torch.tpu.current_stream() |
Pinning a stream to "dense" (TensorCore) or "sparse" (SparseCore) routes ops to dedicated hardware queues. |
| Eager Execution Modes | Immediate kernel launch | torch.tpu.set_eager_mode(EagerMode.DEFER_AND_FUSE) |
EagerMode.DEFER_NEVER (default)DEFER_NEVER_AND_LAUNCH_BLOCKING |
DEFER_AND_FUSE defers eager ops until an action forces execution or a repetition is detected, then compiles them together. |
| Memory Telemetry | torch.cuda.max_memory_allocated() |
torch.accelerator.memory.memory_allocated(), max_memory_allocated(), memory_stats(), reset_peak_memory_stats(), empty_cache() (Stable) |
n/a (torch.tpu has no public memory functions) |
TpuAllocator leaves HBM management to PjRt, so empty_cache() is a no-op (chapter 5). |
| Graph Compilation | torch.compile(m, backend="inductor") |
torch.compile(m, backend="tpu", fullgraph=True, dynamic=False) |
TORCH_TPU_TIER2_COMPILATION_CACHETORCH_TPU_TIER3_COMPILATION_CACHE_ROOT |
Tier 1 = in-memory; Tier 2 = /dev/shm/torch_tpu_cache/<dir>; Tier 3 = persistent local disk or gs:// bucket. |
| Matmul Precision | torch.set_float32_matmul_precision("high") |
torch.set_float32_matmul_precision("medium") or with torch.tpu.precision(Precision.DEFAULT):torch.tpu.allow_excess_precision = True |
Precision.HIGH (3-pass bf16)Precision.HIGHEST (6-pass fp32) |
DEFAULT = 1-pass bf16 (1x MXU); HIGH = 3-pass bf16 (~3x slower); HIGHEST = 6-pass fp32 (~6x slower). |
| Functional Optimizers | torch.optim.AdamW(..., fused=True) |
from torch.tpu.optimizers import SingleTraceTrainer, AdamW, Muon, Sgd |
n/a | Functional in-graph optimizers (AdamW, Muon, Sgd) trace forward + backward + optimizer into 1 HLO graph. |
| Distributed Backend | dist.init_process_group("nccl") |
dist.init_process_group("tpu_dist") ("tpu" is an alias) |
eval "$(python3 -m torch.tpu.distributed)" |
Uses ProcessGroupTPU over optical ICI + MegaScale DCN. |
Precision is controlled with the torch.tpu.precision(level) context manager, the PyTorch torch.set_float32_matmul_precision setting and the torch.tpu.allow_excess_precision property; there are no set_* functions for them. The process group backend is "tpu_dist", aliased as "tpu". DEFER_AND_FUSE takes no bound on the number of deferred ops (chapter 4). SingleTraceTrainer is imported from torch.tpu.optimizers (chapter 9, TorchTPU API Reference).
Recipe 1: training loop (SingleTraceTrainer, functional AdamW/Muon, bounded dynamism, async DCP)¶
References: TorchTPU API Reference, Dynamic shapes, Manage numerical precision in TorchTPU.
import os
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dist
import torch.distributed.checkpoint as dcp
from torch.tpu import EagerMode, Precision
from torch.tpu.optimizers import SingleTraceTrainer, AdamW, Muon, Sgd
# ------------------------------------------------------------------------------
# 1. Compilation Cache, Device, RNG, and Distributed Initialization
# ------------------------------------------------------------------------------
os.environ.setdefault("TORCH_TPU_TIER2_COMPILATION_CACHE", "session_cache")
os.environ.setdefault("TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT", "/mnt/disks/persist/tpu_cache")
dist.init_process_group(backend="tpu")
device = torch.device("tpu") # each process sees its own device
torch.manual_seed(1337 + dist.get_rank())
# Precision.DEFAULT (1-pass bf16 MXU) is the default; scope torch.tpu.precision(...) locally.
# allow_excess_precision locks at the first XLA compile, so set it before any compile:
torch.tpu.allow_excess_precision = True
# ------------------------------------------------------------------------------
# 2. Precision-Aware Model Definition & Functional In-Graph Optimizer
# ------------------------------------------------------------------------------
class TPUTransformerBlock(nn.Module):
def __init__(self, d_model: int = 4096, vocab_size: int = 128256):
super().__init__()
self.qkv = nn.Linear(d_model, 3 * d_model, bias=False)
self.proj = nn.Linear(d_model, d_model, bias=False)
self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
q, k, v = self.qkv(x).chunk(3, dim=-1)
attn_out = F.scaled_dot_product_attention(q.unsqueeze(1), k.unsqueeze(1), v.unsqueeze(1)).squeeze(1)
hidden = x + self.proj(attn_out)
# Accumulate final LM Head logits in fp32 to prevent cross-entropy drift
return F.linear(hidden, self.lm_head.weight).to(torch.float32)
model = TPUTransformerBlock().to(device=device, dtype=torch.bfloat16)
# Functional TPU optimizer (AdamW, Muon, or Sgd): takes hyperparameters, not model.parameters()
optimizer = AdamW(lr=3e-4, weight_decay=0.1)
# ------------------------------------------------------------------------------
# 3. SingleTraceTrainer: Fuse Forward + Backward + Optimizer into 1 XLA Graph
# ------------------------------------------------------------------------------
def compute_loss(m, args, kwargs): # called with (inputs, targets) as args
x, y = args
logits = m(x)
return F.cross_entropy(logits.view(-1, logits.size(-1)), y.view(-1), ignore_index=-100)
trainer = SingleTraceTrainer(
model,
optimizer=optimizer,
compile_fn=lambda gm: torch.compile(gm, backend="tpu", dynamic=False),
compute_loss_fn=compute_loss, # without it, the built-in loss is MSE against targets
)
raw_x = torch.randn(4, 2048, 4096, device=device, dtype=torch.bfloat16)
raw_y = torch.randint(0, 128256, (4, 2048), device=device)
# Trace once on representative bucketed shapes -> returns compiled callable
compiled_train_step = trainer.make_compiled_train_step((raw_x, raw_y))
loss_tensor = compiled_train_step((raw_x, raw_y))
# Sync and log only every N steps to avoid stalling the PJRT async execution queue:
if dist.get_rank() == 0:
print(f"Step Loss: {loss_tensor.item():.4f} | Peak HBM: {torch.accelerator.max_memory_allocated() / 1e9:.2f} GB")
# ------------------------------------------------------------------------------
# 4. Distributed Checkpointing (PyTorch DCP)
# ------------------------------------------------------------------------------
# The train step updates the model's parameters in place; optimizer state lives in
# trainer.param_group (experimental), not in a torch.optim optimizer.
dcp.save({"model": model.state_dict()}, checkpoint_id="/mnt/disks/persist/ckpt_1000")
In TorchTPU 0.2.x, the functional AdamW (like Muon and Sgd) takes hyperparameters, not model.parameters(). SingleTraceTrainer needs a compile_fn and takes a custom loss as compute_loss_fn(model, args, kwargs); without it, the loss is MSE against the targets. Its optimizer is not a torch.optim optimizer, so get_state_dict(model, optimizer) does not apply. Each process uses torch.device("tpu"), without an index. The trainer and the optimizers are Experimental (single_trace_trainer.py, chapter 9, chapter 14).
3.2.2 Hugging Face integration¶
Recipe 2: Hugging Face libraries (Transformers v5, Diffusers and the Kernels Hub Tokamax MoE kernel)¶
Overview: Starting with Hugging Face Transformers v5, Diffusers, Accelerate, and Kernels Hub, torch_tpu works without code changes (device_map="tpu", pipe.to("tpu"), and kernels.get_kernel("tengomucho/ragged-dot-tpu") for 21.5x faster MoE decode on Qwen3-30B-A3B and 12.8x on Gemma 4 26B-A4B).
Reference: Hugging Face and TorchTPU: TPUs, Natively.
| Hugging Face Library | Key TPU Integration Idiom | Validated Model & Hardware | Eager Latency | Compiled / Kernel Latency | Speedup |
|---|---|---|---|---|---|
transformers (v5+) |
device_map="tpu" or tp_plan="auto" (generate() compiles decode only with a static cache; the default DynamicCache runs eagerly) |
google/gemma-4-31B-it / 26B-A4B-it (v6e-8) |
Baseline | Compiled + Static Cache | Native zero-change execution |
diffusers (Video) |
pipe.to("tpu") + pipe.transformer.compile(backend="tpu", fullgraph=True, dynamic=False) |
MiniMax/MiniMax-H3 Video Gen (v6e-4 w/ TensorParallelConfig) |
262.0 s |
188.0 s |
1.39x |
diffusers (Image) |
pipe.to("tpu") + pipe.transformer.compile(backend="tpu", fullgraph=True, dynamic=False) |
Qwen/Qwen-Image-2.1 (v6e-4) |
8.0 s |
3.5 s |
2.29x |
kernels Hub (MoE) |
get_kernel("tengomucho/ragged-dot-tpu") + ALL_EXPERTS_FUNCTIONS.register("tokamax_ragged_dot", ...) |
Qwen/Qwen3-30B-A3B-Instruct-2507 (v6e-8, B=64 decode)google/gemma-4-26B-A4B-it (v6e-8, B=64 decode) |
Default experts implementation | Tokamax Pallas ragged_dot |
21.5x (Qwen3)12.8x (Gemma 4) |
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.integrations.moe import ALL_EXPERTS_FUNCTIONS
from diffusers import DiffusionPipeline
from kernels import get_kernel
# ==============================================================================
# A. Transformers v5 + Kernels Hub Tokamax Ragged-Dot MoE Acceleration (21.5x)
# ==============================================================================
# 1. Fetch pre-compiled Tokamax Pallas ragged_dot kernel from Hugging Face Kernels Hub
repo_id = "tengomucho/ragged-dot-tpu"
kernel = get_kernel(repo_id, version=1, trust_remote_code=[repo_id]) # pin v1, allow-list this repo
ALL_EXPERTS_FUNCTIONS.register("tokamax_ragged_dot", kernel.experts_forward)
# 2. Load MoE model directly onto TPU (use tp_plan="auto" under torchrun for multi-chip TP)
model_id = "Qwen/Qwen3-30B-A3B-Instruct-2507"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
model_id,
dtype=torch.bfloat16,
device_map="tpu", # Or tp_plan="auto" for multi-chip Tensor Parallelism
experts_implementation="tokamax_ragged_dot",
)
# ==============================================================================
# B. Diffusers Image/Video Generation with Multi-Chip TP & Fullgraph Compilation
# ==============================================================================
pipe = DiffusionPipeline.from_pretrained("Qwen/Qwen-Image-2.1", torch_dtype=torch.bfloat16)
pipe.to("tpu")
# Compile the DiT backbone into a static single-graph XLA executable (8.0s -> 3.5s on v6e-4)
pipe.transformer.compile(backend="tpu", fullgraph=True, dynamic=False)
The Kernels Hub recipe follows Hugging Face's TorchTPU post: ALL_EXPERTS_FUNCTIONS comes from transformers.integrations.moe, and the registered function is kernel.experts_forward. The 21.5x and 12.8x figures are decode throughput against the default experts implementation at batch 64 on a TPU v6e-8; at batch 1 the kernel's README, as quoted in the post, gives about 1.13x and 1.07x. The Diffusers timings (8.0 s to 3.5 s, 262 s to 188 s) are on a TPU v6e-4 with TP=4 (chapter 9, Port a Hugging Face model).
Warning
Four common performance problems when porting to torch_tpu:
- Per-Step
.item()orprint(tensor)Calls: Callingloss.item()orif (grad_norm > 1.0).any():inside the training step forces an immediate host-device barrier (torch.accelerator.synchronize()), stalling the asynchronous PJRT execution queue. Keep gradient clipping in tensor space (torch.clamporCompiledGradNorm) and read.item()only every \(N\) logging steps. - Boolean Mask Indexing (
x[x > 0]): Produces data-dependent output shapes that trigger XLA recompilation on every batch. Replace with static shape selection:torch.where(x > 0, x, torch.zeros_like(x)). - Python Int LR Schedulers Inside Compiled Optimizer: Mutating
param_group['lr'] = float_valre-triggers Dynamo guards. Wrap scalar hyperparameters (lr,step) in 0-Dtorch.Tensors (torch.tensor(3e-4, device="tpu")). - Setting
Precision.HIGHESTGlobally: Forces 6-pass IEEEfp32emulation on thebf16MXU, reducing matmul throughput by 6x. KeepPrecision.DEFAULTfor Transformer blocks and scopeout_dtype=torch.float32orPrecision.HIGHstrictly to final logits, RoPE frequencies, or sensitive normalization layers.
3.3 Distributed training (torch_tpu, TorchTitan, Miles RL)¶
3.3.1 FSDP2 (fully_shard), SimpleFSDP (TpuGraphTrainer) and tensor parallelism¶
Overview: torch_tpu supports two complementary sharding paradigms: PyTorch-native FSDP2 (fully_shard), which uses dynamic per-layer hooks over a topology_aware_mesh, and TPU-native SimpleFSDP + TpuGraphTrainer, which uses make_fx / aot_autograd to trace the entire forward, backward, scan_layers loop, and optimizer step into a single whole-step XLA HLO graph so the XLA compiler's Latency Hiding Scheduler (LHS) can globally overlap ICI all-gather and reduce-scatter collectives with MXU compute.
Row by row the two paths do the same job. FSDP2 gathers weights from Python hooks around per-layer graphs; SimpleFSDP puts the collectives into one whole-step graph, where XLA schedules them against the matmuls.
Three FSDP approaches compared (SimpleFSDP, manual FSDP, PyTorch FSDPv2)¶
| Dimension | TPU-Native SimpleFSDP + TpuGraphTrainer |
Manual FSDP (func_col.all_gather_single + autograd.Function) |
PyTorch FSDPv2 (torch.distributed.fsdp.fully_shard) |
|---|---|---|---|
| Source Implementation | simple_fsdp.py (Migrating from FSDPv2 to SimpleFSDP on TorchTPU) + graph_trainer |
Manual Fully Sharded Data Parallel (DIY FSDP) on TorchTPU, FSDP best practices, Muse Glimmer 30B: training | PyTorch Core (torch.distributed.fsdp.fully_shard) |
| Tracing & Graph Boundary | Whole-step make_fx + aot_autograd (forward + backward + optimizer in 1 HLO graph) |
Per-block torch.compile(backend="tpu") wrapping checkpoint(block, use_reentrant=False) |
Per-module eager hooks + per-layer torch.compile |
| Communication Overlap | Global XLA Latency Hiding Scheduler (LHS) + ICI_AG_PIPELINING |
XLA fuses/pipelines functional all_gather_tensor & reduce_scatter_tensor inside compiled block |
Python-level explicit prefetch (set_modules_to_forward_prefetch) |
| Compile Time Optimization | compile.use_scan_layers runs the \(L\) decoder layers as one loop, so the layer body compiles once and the part of compile time and memory that grew with depth no longer does; scan_backward_patch stops scan's backward from copying every saved activation stack (Guide to optimizing LLMs on TorchTPU, scan_backward_patch.py) |
Identical layer structure hits Dynamo/XLA compilation cache after Layer 0 | Standard per-layer caching; requires set_force_sum_reduction_for_comms(True) |
| Best Use Case & MFU | Production TorchTitan LLM/MoE/Diffusion training (51 to 52% MFU on Qwen3-8B with the in-graph optimizer; about 57% MFU on Llama 3 405B, 128 to 1,024 v7x chips) |
Custom research trainers (e.g., Muse Glimmer 30B single-host 19k–22k TPS on v7x) |
Drop-in compatibility for existing upstream PyTorch fully_shard scripts (~36% MFU before graph fusion) |
Tip
7 TPU FSDP Best Practices (FSDP best practices):
- Shard Along Dimension 0 (
dim=0): Always shard weights alongdim=0(w.chunk(world_size, dim=0)[rank]) sofunc_col.all_gather_singlewrites contiguous memory without strided VPU transposes. - Wrap
torch.compileOutsidecheckpoint: Usetorch.compile(lambda *a: checkpoint(block, *a, use_reentrant=False), backend="tpu")soall_gatherruns inside the compiled forward and again inside the recomputed backward: automatically freeing unsharded weights between forward and backward. - Rank-Dependent Data Seeding: Always seed synthetic/sharded dataloaders with
torch.manual_seed(base_seed + dist.get_rank()); identical inputs across FSDP ranks zero out cross-rank gradient variance and mask collective bugs. - Use Functional Collectives (
torch.distributed._functional_collectives): Prefer traceableall_gather_tensorandreduce_scatter_tensor( reduceOp="avg" | "sum")over in-place collectives insidetorch.compile. - Force Sum-Reduction on FSDPv2: Call
layer.set_force_sum_reduction_for_comms(True)on everyfully_shardmodule to use native TPU sum-reduction hardware collectives. - Materialize Forward Before Backward: Insert
synchronize(loss, wait=False)between forward and backward (TorchTitan:--compile.materialize_forward_before_backward) so the step compiles as two smaller graphs, which cuts first-step XLA compilation time; autograd still runs through the whole model. The switch lives undercompilein TorchTitan's TPU trainer (Guide to optimizing LLMs on TorchTPU). - Enforce
[B, L, D]Activation Layout (apply_bld_layout): Keep hidden states in[B, L, D]so the trailing dimensions(L, D)map directly to the TPU's native(8, 128)2D MXU/VMEM tile layout.
Recipe 1: topology-aware FSDP2 (fully_shard) with 2D tensor parallelism (ColwiseParallel / RowwiseParallel)¶
References: TorchTPU distributed support, FSDP best practices, device_mesh.py.
import torch
import torch.distributed as dist
from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
from torch.distributed.tensor.parallel import (
parallelize_module, ColwiseParallel, RowwiseParallel, SequenceParallel, PrepareModuleInput
)
from torch.distributed._tensor import Shard, Replicate
from torch.distributed.device_mesh import DeviceMesh
dist.init_process_group(backend="tpu_dist")
# 1. Build a Physical-Torus-Aligned 2D DeviceMesh (e.g., 16 devices -> 4 DP x 4 TP)
# topology_aware_mesh returns a rank tensor laid out so the inner (TP) dimension sits on the shortest ICI links
rank_tensor = torch.tpu.distributed.topology_aware_mesh(mesh_shape=(4, 4))
mesh_2d = DeviceMesh("tpu", mesh=rank_tensor, mesh_dim_names=("dp", "tp"), preserve_rank_order=True)
dp_mesh = mesh_2d["dp"]
tp_mesh = mesh_2d["tp"]
# 2. Apply Tensor Parallelism + Sequence Parallelism within each Transformer Layer
for layer in model.layers:
parallelize_module(
module=layer,
device_mesh=tp_mesh,
parallelize_plan={
"attention_norm": SequenceParallel(),
"attention": PrepareModuleInput(
input_layouts=(Shard(1),), desired_input_layouts=(Replicate(),)
),
"attention.wq": ColwiseParallel(),
"attention.wk": ColwiseParallel(),
"attention.wv": ColwiseParallel(),
"attention.wo": RowwiseParallel(output_layouts=Shard(1)),
"ffn_norm": SequenceParallel(),
"feed_forward": PrepareModuleInput(
input_layouts=(Shard(1),), desired_input_layouts=(Replicate(),)
),
"feed_forward.w1": ColwiseParallel(),
"feed_forward.w3": ColwiseParallel(),
"feed_forward.w2": RowwiseParallel(output_layouts=Shard(1)),
},
)
# 3. Apply FSDP2 across the DP Mesh Dimension with TPU Sum-Reduction Collective Fix
mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)
for layer in model.layers:
fully_shard(layer, mesh=dp_mesh, mp_policy=mp_policy, reshard_after_forward=True)
# CRITICAL for TPU: Use native sum-reduction collective instead of pre-dividing before reduce-scatter
layer.set_force_sum_reduction_for_comms(True)
fully_shard(model, mesh=dp_mesh, mp_policy=mp_policy)
model.set_force_sum_reduction_for_comms(True)
# 4. Configure Explicit Multi-Layer Prefetching to Overlap ICI All-Gather with MXU
for i, layer in enumerate(model.layers):
if i + 2 < len(model.layers):
layer.set_modules_to_forward_prefetch([model.layers[i + 1], model.layers[i + 2]])
if i - 1 >= 0:
layer.set_modules_to_backward_prefetch([model.layers[i - 1]])
topology_aware_mesh is torch.tpu.distributed.topology_aware_mesh(mesh_shape, *, dcn_mesh_shape=None, ...). It returns an int64 rank tensor, not a mesh, and takes no mesh_dim_names; pass the tensor to DeviceMesh("tpu", mesh=...) as above (chapter 13, device_mesh.py). Use MixedPrecisionPolicy(param_dtype=bfloat16, reduce_dtype=float32): TorchTitan's optimization guide says that dropping reduce_dtype to bfloat16 to save bandwidth is a model-quality regression (chapter 14).
Recipe 2: whole-step SimpleFSDP with TpuGraphTrainer and use_scan_layers (Qwen3-8B, in-graph optimizer)¶
References: Integrating TorchTPU into TorchTitan and Optimizing Models for TPU, graph_trainer/simple_fsdp.py, graph_trainer/config.py, scan_backward_patch.py.
# Inside a TorchTitan TPU recipe (a function in config_registry.py, e.g. qwen3_8b()):
# Graph Trainer is selected by returning its config type, not by a constructor call.
config = TpuGraphTrainer.Config.from_tpu_trainer_config(
base_config, graph_trainer_model_registry # e.g. graph_trainer.qwen3.model_registry
)
config.compile = TpuGraphTrainerCompileConfig(
enable=True,
components=["model"],
memory_policy="default", # replaces the eager activation_checkpoint config
optimizer_compile="in_graph", # fold AdamW into the step graph; inputs are not donated, so budget HBM
use_scan_layers=True, # fold homogeneous layers into one scan loop body
)
# Graph Trainer shards with SimpleFSDP (graph_trainer/simple_fsdp.py): DTensor collectives in the graph
# Launch one host (devices per host = processes); any field can be overridden as --section.field
torchrun --nproc_per_node=<DEVICES_PER_HOST> -m torchtitan.experiments.tpu.train \
--module=torchtitan.experiments.tpu.qwen3 --config=qwen3_8b
Graph Trainer is TorchTitan's (torchtitan/experiments/tpu/graph_trainer/) and is chosen by the recipe's config type; it is not imported from torch_tpu. Scan and the graph splitter are the config fields compile.use_scan_layers and compile.graph_split.enabled. The block above is the conversion the Guide to optimizing LLMs on TorchTPU gives (chapter 14). With the in-graph optimizer, step inputs are not donated, so budget HBM for them; on Qwen3-8B this path reaches 51 to 52% MFU (Integrating TorchTPU into TorchTitan and Optimizing Models for TPU).
3.3.2 TorchTitan parallelism, declarative ShardingConfig and scale results (up to 8,192 TPU v7x chips)¶
Overview: TorchTitan on TPU (TPUTrainer) extends standard PyTorch training to 8,192 TPU v7x chips. It views the same devices as four meshes that ParallelDims builds from one world mesh: it unflattens it into data-loading, dense and sparse views and flattens the data-loading view's batch and cp dimensions into the loss mesh. It applies its libtpu and XLA flag config before any TPU device is used and combines whole-graph TpuGraphTrainer / GraphSplitter (compile.graph_split.enabled), CompiledGradNorm, [B,L,D] layout enforcement, and Pallas kernels (PallasCrossEntropyLoss, splash_attention, gmm/ragged_dot_moe).
ParallelDims unflattens one world mesh into the data-loading, dense and sparse views, and flattens the data-loading view's batch and cp dimensions into the loss mesh. All four are views of the same devices.
TorchTitan TPU XLA flag bundles (tpu_flags.py) & Runtime Passes¶
| Flag Bundle / Subsystem | Underlying LIBTPU_INIT_ARGS / Module Implementation |
Hardware Mechanism & Measured Performance Impact |
|---|---|---|
SPARSECORE_LATENCY_HIDING_SCHEDULER |
xla_tpu_enable_sparse_core_collective_aggregator=truexla_tpu_enable_latency_hiding_layer_scheduler=true |
Aggregates SparseCore collectives and schedules them layer by layer to hide ICI communication behind MXU work. |
ICI_AG_PIPELINING |
xla_tpu_enable_ici_ag_pipelining=true |
Starts each layer's FSDP weight all-gather one scan iteration early so it overlaps the previous layer's compute; costs HBM for the prefetched weights. |
SELECTIVE_ICI_RS_PIPELINING |
xla_tpu_enable_ici_rs_pipelining=truexla_tpu_ici_rs_pipelining_threshold_kib=1024 |
Pipelines small (up to 1,024 KiB per shard) reduce-scatters across the scan backward loop while keeping larger weight reductions in their own iteration. |
SPARSECORE_ASYNC_ALL_GATHER |
xla_enable_async_all_gather=truexla_tpu_prefer_async_allgather_to_allreduce=truexla_tpu_enable_sparse_core_collective_offload_all_gather=true |
Runs FSDP all-gather asynchronously and offloads it to the SparseCore. |
SPARSECORE_COLLECTIVE_OFFLOAD |
xla_tpu_enable_sparse_core_collective_aggregator=truexla_tpu_enable_sparse_core_offload_queuing_in_lhs=truexla_tpu_enable_sparse_core_collective_offload_2d_all_gather=truexla_tpu_enable_sparse_core_collective_offload_3d_all_gather=truexla_tpu_enable_sparse_core_collective_offload_reduce_scatter=true |
Offloads FSDP all-gather and reduce-scatter from the TensorCore to the SparseCore (v6e / v7x). |
HIERARCHICAL_REDUCE_SCATTER / DUAL_SPARSECORE_REDUCE_SCATTER |
xla_tpu_use_single_sparse_core_for_reduce_scatter_offload=false(+ xla_tpu_enable_sparse_core_collective_offload_nd_reduce_scatter=true, xla_tpu_enable_sparse_core_hierarchical_reduce_scatter=true for the hierarchical bundle) |
Uses both SparseCores for offloaded reduce-scatter, and splits multi-axis reduce-scatter hierarchically on SparseCore. |
TPU7X_THROUGHPUT_P_STATE / DISABLE_ENHANCED_LAUNCH_BARRIER / CONVOLUTION_UNFUSING |
xla_tpu_dvfs_p_state=7 / xla_tpu_use_enhanced_launch_barrier=false / xla_tpu_enable_convolution_unfusing=true |
v7x power state, launch barrier and convolution unfusing switches. |
GraphSplitter & Host Offload |
graph_split.py (compile.graph_split.enabled) + tpu_host_offload.py |
Splits large models into stage subgraphs with torch.ops.tpu.host_CopyToHost/Device activation offloading to CPU DRAM. |
| HF Model Backend & Agentic Onboarding | transformers_modeling_backend + .claude/skills/tpu_model_onboarding |
Runs 500+ Hugging Face models directly inside TorchTitan and automates model onboarding, numerical verification, and MFU tuning. |
The table lists the bundles and flags as tpu_flags.py defines them. A recipe composes bundles with tpu_flags.merge_flags(...); --extra-libtpu-init-flags adds or overrides single flags (chapter 14). The graph splitter is switched on with compile.graph_split.enabled.
TorchTitan on TPU: published scale results¶
Figures from Integrating TorchTPU into TorchTitan and Optimizing Models for TPU.
| Model Family | Hardware & Slice Scale | Parallelism & Optimization Recipe | Throughput (tok/s/chip or s/step) |
Achieved MFU / Scaling Efficiency |
|---|---|---|---|---|
| Qwen3-8B | n/a | SimpleFSDP + TpuGraphTrainer + in-graph functional AdamW |
n/a | 51 to 52% MFU |
| Llama 3.1 405B | v7x 128 to 1,024 chips |
3D Parallelism (SimpleFSDP + TP + SplashAttention + SparseCore offload) |
Linear scaling across 128–1,024 chips | ~57.0% MFU |
| Qwen3-235B-A22B (MoE) | v7x 1,024 chips (1 full slice) |
SimpleFSDP + EP (gmm / ragged_dot_moe) + scan_backward_patch |
n/a (4,568 tok/s/chip at 64 chips) |
32.42% MFU |
| Qwen3-235B-A22B (MoE) | v7x 8,192 chips (8 slices \(\times\) 1,024 chips) |
Multi-Slice HSDP (dp_replicate=8 over DCN, dp_shard + ep over ICI) |
4,208 tok/s/chip |
30.51% MFU (92% weak scaling from 64 to 8,192 chips) |
| Muse Glimmer 30B | v7x 64 chips (4x4x4) / 128 chips (4x4x8) |
SimpleFSDP + 3:1 SWA/Full SplashAttention + PallasCrossEntropyLoss (S=16384) |
5,848 tok/s/chip (64c) |
~44.0% MFU (64c) / 43.4% MFU (128c) |
| FLUX.1-dev 12B | v7x 8 chips \(\to\) 1,024 chips (8x8x16) |
HSDP + Packed SplashAttention + Per-Block torch.compile (1024x1024, B=3) |
2.53 s/step (8c) \(\to\) 2.71 s/step (1,024c) |
20.76% \(\to\) 19.4% MFU (93% weak scaling) |
Per-chip throughput falls by 8% from 64 to 8,192 chips (4,568 to 4,208 tokens per second per chip). MFU figures from different posts use different FLOP conventions, so compare throughput rather than MFU across rows (chapter 16, chapter 14).
Recipe 3: TorchTitan CLI launch and declarative ShardingConfig on TPU v7x¶
References: Integrating TorchTPU into TorchTitan and Optimizing Models for TPU, train.py, protocols/sharding.py.
# One v6e-4 VM: the TPU lane README's first job (Qwen3 1.7B, FSDP, bundled tokenizer and data)
torchrun --nproc_per_node=4 -m torchtitan.experiments.tpu.train \
--module=torchtitan.experiments.tpu.qwen3 \
--config=qwen3_1_7b \
--training.steps=10
# Multi-host (run on every host; chapter 14 submits it with `gcluster job submit`):
# Llama 3 8B on a v6e-8 slice (2x4 = two hosts of four chips)
torchrun \
--nnodes=2 --nproc_per_node=4 \
--rdzv_backend=static --rdzv_endpoint=$WORKERS_0_HOSTNAME:29501 --node_rank=$TPU_WORKER_ID \
-m torchtitan.experiments.tpu.train \
--module=torchtitan.experiments.tpu.llama3 --config=llama3_8b \
--hf_assets_path=tests/assets/tokenizer --dataloader.dataset_path=tests/assets/c4_test \
--training.steps=20 \
--training.num_tokens_per_microbatch_per_dp_rank=16384 \
--training.max_context_length=8192 \
--compile.enable \
--parallelism.use_simple_fsdp \
--splash_attention_kernel.use_splash_attention_kernel \
--splash_attention_kernel.sa_block_kv_compute=2048 \
--tpu_config.eager_mode=DEFER_AND_FUSE \
--libtpu-init-flags='xla_tpu_scoped_vmem_limit_kib=131072 tpu_program_stack_shrink_after_unload=false'
The launch commands match chapter 14 and the Run TorchTitan on TPU guide. The entry point is -m torchtitan.experiments.tpu.train under torchrun; --module takes a package path, and --config names a recipe function in that package's config_registry.py. materialize_forward_before_backward is a compile field (--compile.materialize_forward_before_backward). Do not export TORCH_DEVICE_BACKEND_AUTOLOAD=0 for a TPU job: it turns TorchTPU's autoload off, so import torch no longer registers the tpu device, and TorchTitan's TPU lane sets it only to force CPU-only child processes (chapter 8, device_env.py). libtpu and XLA flags are config fields (--libtpu-init-flags, --extra-libtpu-init-flags) that the trainer applies before any TPU device is used.
# Declarative sharding in TorchTitan (torchtitan/protocols/sharding.py): each
# Module.Config carries a ShardingConfig, and Module.parallelize(parallel_dims)
# shards the module's states and redistributes its inputs and outputs.
# Placements are SpmdType values keyed by mesh axis name.
import spmd_types as spmd
from spmd_types import SpmdType
from torchtitan.distributed.parallel_dims import MeshAxisName
from torchtitan.protocols.sharding import ShardingConfig
from torchtitan.models.common.decoder_sharding import (
colwise_config, rowwise_config, dense_activation_placement,
)
DP, CP, TP = MeshAxisName.DP, MeshAxisName.CP, MeshAxisName.TP
# ColwiseParallel spelled out (this is what colwise_config() returns, without bias):
# weight Shard(0) on TP and replicated on DP and CP; output sharded on its last dim.
colwise = ShardingConfig(
state_shardings={"weight": SpmdType({DP: spmd.R, CP: spmd.R, TP: spmd.S(0)})},
out_src_shardings=dense_activation_placement(tp=spmd.S(-1), cp=spmd.S(0)),
)
# Dense FFN of one decoder layer config, as set_dense_ffn_sharding() does it:
ffn = layer_cfg.feed_forward
ffn.w1.sharding_config = colwise_config()
ffn.w3.sharding_config = colwise_config()
# Rowwise: weight Shard(1); output reduce-scatters with sequence parallelism, else all-reduces
ffn.w2.sharding_config = rowwise_config(output_sp=enable_sp)
# Llama 3 fills every sub-config in one call from Llama3Model.Config.update_from_config:
# set_llama3_sharding_config(config, enable_sp=parallelism.enable_sequence_parallel)
ShardingConfig (torchtitan/protocols/sharding.py) is set per module on Module.Config and read by Module.parallelize(parallel_dims). Its fields are state_shardings (keyed by parameter or buffer name), in_src_shardings / in_dst_shardings and out_src_shardings / out_dst_shardings for redistribution at the module boundary, and local_map for modules that compute on local tensors. resolve_placements raises ValueError when a placement is missing for a mesh axis, and turns Shard or Partial on a size-1 axis into Replicate(). The shared decoder helpers are in models/common/decoder_sharding.py, and each model's sharding.py (for example models/llama3/sharding.py) applies them.
3.3.3 Case studies: FLUX diffusion, Muse Glimmer 30B and Miles RL (GRPO)¶
Case study 1: FLUX.1 12B diffusion optimization (1.46x Block Speedup, 4.1x End-to-End v6e-8 Speedup & 93% Scaling on 1,024 v7x Chips)¶
Overview: Out-of-the-box diffusion models (FLUX.1-dev 12B) suffer on TPUs from dynamic torch.split allocations, strided [..., ::2] RoPE operations, FSDP2 per-op barrier overhead, and \(O(N^2)\) HBM attention traffic, all solved by two complementary optimization cascades: (A) Single-chip DoubleStreamBlock micro-optimizations (178.61 ms \(\to\) 122.51 ms, 1.46x) and (B) Full-model distributed training optimizations on v6e-8 (11.49 s \(\to\) 2.78 s, 4.1x, reaching 99% of native JAX MaxDiffusion performance and scaling to 1,024 v7x chips at 93% weak-scaling efficiency).
References: FLUX optimization, Integrating TorchTPU into TorchTitan and Optimizing Models for TPU.
Cascade A: single-chip DoubleStreamBlock forward and backward optimizations (TPU v6e-1, B=2, S=32768, bf16)¶
Each row is a separate configuration measured from the same eager baseline, not a cumulative sequence.
Each bar is a separate configuration, not a step added to the one above; rows without torch.compile run eagerly. Alone, SplashAttention helps most, and all four together cut the block from 178.61 ms to 122.51 ms.
Configuration of DoubleStreamBlock |
Latency (ms) |
Speedup vs Eager | What it changes |
|---|---|---|---|
Eager baseline (torch.split, strided RoPE, math SDPA) |
178.61 ms |
1.00x |
Host launch overhead + VPU layout transposes + HBM bandwidth |
| Zero-copy views only (eager) | 178.30 ms |
1.00x |
.view(B, L, 3, H, D).unbind(2) replaces the intermediate torch.split copy |
| Pallas SplashAttention only (eager) | 149.81 ms |
1.19x |
Keeps attention scores inside VMEM |
torch.compile only |
159.33 ms |
1.12x |
Fuses AdaLN modulation + QKV projections + MLP into XLA graphs |
| Zero-copy views + fused RoPE + Pallas SplashAttention (eager) | 156.73 ms |
1.14x |
Splash attention with the layout fixes, without compilation |
Zero-copy views + torch.compile |
159.08 ms |
1.12x |
The copy is a small fraction of the step |
Zero-copy views + fused RoPE + torch.compile |
153.60 ms |
1.16x |
Compact elementwise [cos, sin] RoPE removes the strided sub-tile transpose |
All four: views + fused RoPE + Pallas SplashAttention + torch.compile |
122.51 ms |
1.46x |
splash_sdpa (block=2048, bf16) saves the lse residual via @jax_op, so backward does not recompute the forward attention |
The case study defines its own splash_sdpa with jax_op; the code below uses TorchTPU's public torch.tpu.ops.splash_sdpa, which takes the same block_q / block_kv keywords (chapter 9, FLUX optimization).
Cascade B: end-to-end FLUX.1-dev 12B distributed training (TPU v6e-8 & TPU v7x-1024, 1024x1024, B=3)¶
Each row keeps every change above it. Replacing FSDP2 with SimpleFSDP and compiling each block remove the most time; the five changes together make the step 4.1x faster.
| Step | Distributed Training Optimization (v6e-8, 8 chips) |
Step Time (s) |
Cumulative Speedup | Architectural Mechanism |
|---|---|---|---|---|
| 0 | Eager Baseline (FSDPv2 + DEFER_NEVER) |
11.49 s |
1.00x |
Synchronous per-op PJRT dispatch + un-overlapped FSDP2 collectives |
| 1 | Async Eager Fusion (EagerMode.DEFER_AND_FUSE) |
9.95 s |
1.15x |
Clusters deferred eager ops before XLA compilation |
| 2 | Switch FSDPv2 \(\to\) Traceable SimpleFSDP |
6.52 s |
1.76x |
Eliminates Python hook barriers; expresses sharding as functional DTensor collectives |
| 3 | Packed SplashAttention (Pad 512 txt + 4096 img \(\to\) 4608 w/ segment mask) |
5.55 s |
2.07x |
Replaces flash-attention fallback with hardware-tiled Pallas splash_attention |
| 4 | Per-Block torch.compile(backend="tpu") (19 Double + 38 Single blocks) |
3.02 s |
3.80x |
Fuses per-layer forward/backward + FSDP all-gather/reduce-scatter |
| 5 | Local Graph Rewrites (split fused projection + zero-copy .unbind(2) + [cos, sin] RoPE) |
2.78 s |
4.13x (99% of JAX MaxDiffusion) |
Removes remaining VPU layout relayouts. |
On v7x the best configuration went from 2.53 s per step on 8 chips to 2.71 s on 1,024 chips, 93% weak-scaling efficiency.
import torch
splash_sdpa = torch.tpu.ops.splash_sdpa # public TorchTPU op backed by Pallas Splash Attention
# 1. TPU-Friendly Elementwise RoPE (Replaces strided stack(-x[...,1::2], x[...,::2]))
def apply_tpu_rope(xq: torch.Tensor, xk: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor):
def rotate_half(x: torch.Tensor) -> torch.Tensor:
x1, x2 = x.chunk(2, dim=-1) # Contiguous half-split (no stride=2 gather)
return torch.cat((-x2, x1), dim=-1)
cos_full = torch.cat([cos, cos], dim=-1)
sin_full = torch.cat([sin, sin], dim=-1)
return (xq * cos_full) + (rotate_half(xq) * sin_full), (xk * cos_full) + (rotate_half(xk) * sin_full)
# 2. TPU-Optimized FLUX DoubleStream Attention with Zero-Copy Unbind & Pallas Splash SDPA
def flux_double_stream_attention(qkv_img: torch.Tensor, qkv_txt: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, num_heads: int = 24):
B, S_img, _ = qkv_img.shape
_, S_txt, _ = qkv_txt.shape
head_dim = qkv_img.size(-1) // (3 * num_heads)
# Zero-copy view + unbind instead of torch.split
q_i, k_i, v_i = qkv_img.view(B, S_img, 3, num_heads, head_dim).unbind(dim=2)
q_t, k_t, v_t = qkv_txt.view(B, S_txt, 3, num_heads, head_dim).unbind(dim=2)
q = torch.cat([q_t, q_i], dim=1).transpose(1, 2).contiguous() # [B, H, S_total, D]
k = torch.cat([k_t, k_i], dim=1).transpose(1, 2).contiguous()
v = torch.cat([v_t, v_i], dim=1).transpose(1, 2).contiguous()
q, k = apply_tpu_rope(q, k, cos, sin)
# Pallas SplashAttention (block_q=2048, block_kv=2048) saves log-sum-exp (lse) residual for backward.
attn_out = splash_sdpa(q, k, v, is_causal=False, block_q=2048, block_kv=2048)
attn_out = attn_out.transpose(1, 2).reshape(B, S_txt + S_img, num_heads * head_dim)
return attn_out[:, :S_txt], attn_out[:, S_txt:]
Case study 2: Muse Glimmer 30B hybrid SWA/NoPE training (19k–22k TPS on 1 v7x Host; 44% MFU on 64 v7x Chips) & Inference (23.58 ms/tok)¶
Overview: Muse Glimmer 30B is a 52-layer hybrid transformer (vocab_size=202048, dmodel=6656, dff=19968, num_q_heads=32, num_kv_heads=2, head_dim=128, qk_scale_factor=3.87, final_logit_softcapping=20.0, output_multiplier=0.19611613513818404) that alternates 3 Sliding-Window RoPE Attention layers (swa_size=2048) with 1 Full Global NoPE (No Positional Encoding) Attention layer (3:1 pattern).
- Single-Host Training (
1x v7xhost = 8 TensorCores,B=8, S=5120): Materializing the[8, 5120, 202048]logits would take about 16 GiB of HBM;MuseGlimmerChunkwiseFusedLMHeadLosscomputes the loss in chunks ofCHUNKWISE_FUSED_LOSS_CHUNK_SIZE = 4096tokens with a per-chunk.backward(), and the run reaches 19,000–22,000 tokens/sec (2,400–2,800 TPS/rank). - Multi-Host
TorchTitanTraining (64–128 v7xchips,S=16384): CombiningSimpleFSDP, 3:1 SWA/FullSplashAttentionmasks, andPallasCrossEntropyLossreaches 5,848 tok/s/chip (~44% MFU) on 64 chips (4x4x4) and 43.4% MFU on 128 chips (4x4x8). - Single-Chip Inference (
1x v7xchip): UsingStaticCache(dynamic=False+ 0-D tensorindex_copy_) eliminates per-token shape recompilations, achieving 23.58 ms/token steady-state decode.
References: Muse Glimmer 30B: training, Muse Glimmer 30B: autoregressive decoding, Integrating TorchTPU into TorchTitan and Optimizing Models for TPU.
Muse Glimmer 30B single-chip inference (StaticCache vs DynamicCache on 1x TPU v7x)¶
| Cache & Dynamo Strategy | Prefill (ms) |
Decode Step 1 (ms) |
Decode Step 2 (ms) |
Decode Step 3 (ms) |
Steady-State Decode (Avg Steps 2–20 / 4–20) | Recompilation Behavior |
|---|---|---|---|---|---|---|
StaticCache + torch.compile(dynamic=False) |
21,024.81 ms |
19,756.86 ms (1st compile) |
24.66 ms |
24.29 ms |
23.58 ms/token |
Zero recompilations after Step 1 (fixed [B, H, max_len, D] buffer + 0-D tensor index_copy_) |
DynamicCache + torch.compile(dynamic=None) |
18,256.18 ms |
19,969.41 ms (compile #1) |
21,985.62 ms (compile #2) |
4,908.23 ms (symbolic transition) |
24.17 ms/token |
Recompiles across Steps 1–3 before Dynamo auto-generalizes symbolic KV length |
The example's Config (examples/muse_glimmer_30b/llm_inference/model.py) has 32 query heads and 2 KV heads. The case study's table gives 24.66 ms and 24.29 ms for StaticCache decode steps 2 and 3; 23.58 ms is the average over steps 2 to 20 (chapter 22). In the training example, the chunked loss uses CHUNKWISE_FUSED_LOSS_CHUNK_SIZE = 4096 tokens per chunk (model_fsdp.py, chapter 16).
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint
# ==============================================================================
# PART A: Sequence-Chunked Fused Softcap LM Head + Cross-Entropy (avoids ~16 GiB of logits)
# ==============================================================================
# Muse Glimmer 30B Config: vocab_size=202048, final_logit_softcapping=20.0,
# output_multiplier=0.19611613513818404 (1 / sqrt(26)).
# Chunk the [B*S=40960, D=6656] hidden states into 4096-token slices
# (the example's CHUNKWISE_FUSED_LOSS_CHUNK_SIZE), so only one slice of logits is live.
def chunked_softcap_lm_head_loss(
hidden_states: torch.Tensor, # [B, S, D] from final RMSNorm
lm_head_weight: torch.Tensor, # [V=202048, D=6656]
targets: torch.Tensor, # [B, S]
output_multiplier: float = 0.19611613513818404,
softcap: float = 20.0,
chunk_size: int = 4096,
) -> torch.Tensor:
flat_h = hidden_states.view(-1, hidden_states.size(-1))
flat_y = targets.view(-1)
h_detached = flat_h.detach().requires_grad_(True)
@torch.compile(backend="tpu")
def compute_chunk_loss(h_chunk: torch.Tensor, w: torch.Tensor, y_chunk: torch.Tensor) -> torch.Tensor:
logits = F.linear(h_chunk, w).to(torch.float32) * output_multiplier
logits = softcap * torch.tanh(logits / softcap)
return F.cross_entropy(logits, y_chunk, reduction="sum")
h_chunks = h_detached.split(chunk_size, dim=0)
y_chunks = flat_y.split(chunk_size, dim=0)
total_tokens = (flat_y != -100).sum().clamp(min=1)
total_loss = torch.zeros((), device=hidden_states.device, dtype=torch.float32)
for hc, yc in zip(h_chunks, y_chunks):
chunk_loss = compute_chunk_loss(hc, lm_head_weight, yc) / total_tokens
chunk_loss.backward() # Frees this chunk's [4096, 202048] logits before the next chunk
total_loss = total_loss + chunk_loss.detach()
flat_h.backward(h_detached.grad)
return total_loss
# ==============================================================================
# PART B: Compile OUTSIDE Activation Checkpointing (Prevents Re-Tracing & Frees FSDP Weights)
# ==============================================================================
def wrap_layer_for_tpu_training(layer: nn.Module):
def ckpt_forward(*args):
return checkpoint(layer, *args, use_reentrant=False)
return torch.compile(ckpt_forward, backend="tpu")
# ==============================================================================
# PART C: Single-Chip v7x Inference with StaticCache & 0-D Tensor index_copy_ (23.58 ms/tok)
# ==============================================================================
class TPUStaticKVCache(nn.Module):
def __init__(self, max_batch: int, num_kv_heads: int, max_seq_len: int, head_dim: int, device: torch.device):
super().__init__()
shape = (max_batch, num_kv_heads, max_seq_len, head_dim)
self.register_buffer("k_cache", torch.zeros(shape, dtype=torch.bfloat16, device=device))
self.register_buffer("v_cache", torch.zeros(shape, dtype=torch.bfloat16, device=device))
def update(self, k_val: torch.Tensor, v_val: torch.Tensor, cache_position: torch.Tensor):
# cache_position is a 1-D Tensor on TPU (shape [1] during decode); no Python int indexing
self.k_cache.index_copy_(2, cache_position, k_val)
self.v_cache.index_copy_(2, cache_position, v_val)
return self.k_cache, self.v_cache
Case study 3: Miles end-to-end RL (GRPO) with SGLang-TorchTPU and TorchTitan¶
Overview: Reinforcement Learning with Verifiable Rewards (GRPO) on a single 4-chip TPU v7x host (tpu7x-standard-4t) partitions the host into 2 chips for SGLang-TorchTPU rollout generation and 2 chips for TorchTitan policy training, synchronizing updated policy weights after every step (or every few steps) via Shared Memory (what the runs use today), Disk Checkpoints (works across hosts, slowest), or a planned Direct ICI Transfer (measured about 50x faster than shared memory).
Rollouts flow from the engine to the trainer, and new weights flow back through one of three transports after every step or every few steps. Today's runs use shared memory; ICI is planned.
References: SGLang‑TorchTPU: PyTorch‑Native Production Serving on TPUs, Miles, Integrating TorchTPU into TorchTitan and Optimizing Models for TPU.
| Miles RL Component | Placement on 1x TPU v7x Host (4 Chips) | Role in the Qwen3-4B GRPO run on DAPO-Math-17k |
|---|---|---|
Rollout Engine (SGLang-TorchTPU) |
2 chips | Generates the rollouts the policy is trained on |
Policy Trainer (TorchTitan) |
2 chips | Trains on the rollouts; no TPU-specific model code |
| Weight Sync Mechanism | Shared memory (trainer and engine on one host), disk checkpoints, or ICI (planned) | Shared memory today; ICI measured about 50x faster than shared memory |
The run trains Qwen3-4B with GRPO on DAPO-Math-17k on one 4-chip v7x host and matches a reference run of the same recipe and hyperparameters on 6 H200 GPUs (two seeds per platform). Miles TPU training is in preview; take launch commands from Miles' own documentation. Chapter 15 builds the same loop with Ray actors (SGLang‑TorchTPU: PyTorch‑Native Production Serving on TPUs).
3.4 Inference serving (vLLM-TorchTPU, SGLang-TorchTPU)¶
3.4.1 Engine comparison, 6D parallelism, compilation cache and offline serving¶
Overview: Both vLLM-TorchTPU (tpu_platform.py, pip install vllm-torchtpu) and SGLang-TorchTPU (platform.py, SGLANG_PLATFORM=tpu_oot) register as out-of-tree torch_tpu plugins that run one PyTorch process per TPU core, pre-compile static bucketed token/batch shapes during warmup (--compilation-config '{"compile_sizes": [...]}'), replace CUDA kernels with Pallas TPU ops (ragged_paged_attention_v3, Sparse/Dense MLA, GDN/KDA linear attention, fused_moe, and whole-decoder megakernels), and transfer/offload KV caches via TPU Sync (TPURaidenConnector & TPURaidenOffloadingConnector).
Both engines keep their own scheduler and KV cache management and add TPU parts underneath: a model runner that compiles one graph per shape bucket and Pallas kernels inside that graph. KV that leaves the device, for host offload or prefill-to-decode transfer, moves through TPU Sync.
vLLM-TorchTPU and SGLang-TorchTPU compared¶
| Dimension | vLLM-TorchTPU (repository, Introducing vLLM TorchTPU) |
SGLang-TorchTPU (repository, launch post) |
|---|---|---|
| Plugin Activation | Automatic via entry point vllm.platform_plugins (pip install vllm-torchtpu) |
SGLANG_PLATFORM=tpu_oot (launch post, lmsysorg/sglang:v0.1.0-tpu) or tpu / unset (the recipes' default, in-tree TpuSRTPlatform) + --device tpu |
| Attention & Linear Kernels | Ragged Paged Attention v3 (--attention-backend CUSTOM, VLLM_TPU_BLOCK_MAJOR_KV=1), Dense/Sparse MLA (SparseCore top-\(k\)), GDN & KDA (TPU_VLLM_ENABLE_UNIFIED_BLOCK_POOL=1), n-gram PLE (Qwen4Exp) |
TpuPallasRpaV3AttnBackend (ragged paged attention v3), TpuPallasMlaAttnBackend, TpuKDAAttnBackend, hybrid SWA/Full & linear-attention pools |
| Prefix / KV Caching & Offload | Automatic Prefix Caching (--enable-prefix-caching, PrefixAwareScheduler) + TPURaidenOffloadingConnector (tpu-sync zero-copy DRAM DMA) |
Tree-based RadixAttention (RadixCache, including hybrid SWA/linear state) + TPU Sync Host DRAM pool DMA |
| P/D Disaggregation | TPURaidenConnector (kv_producer / kv_consumer + run_raiden_controller.py:50055) with heterogeneous P/D resharding (PCP=4,TP=2 \(\to\) DP=4,TP=2) |
Consumer-pull chunked KV transfer via TPU Sync (pulls chunk \(i\) while chunk \(i+1\) computes; strided in-flight TP resharding) |
| Whole-Model Megakernels | torch.compile(backend="tpu") + Pallas custom ops + SrptPrefillScheduler |
C++/Pallas Whole-Decoder Megakernels (k3_megakernel, glm_flash_megakernel, muse_megakernel) |
| Compilation Cache & Guarding | TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT (C++ PJRT .bins) + VLLM_CACHE_ROOT / VLLM_XLA_CACHE_PATH (Python FX/AOT) + VLLM_XLA_CHECK_RECOMPILATION=1 + TPU_PARALLEL_PRECOMPILE=1 |
Bucketed prefill/decode AOT warmup + TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT |
| Multi-Host Backend | Native mp (default, TCPStore via --nnodes or --data-parallel-size) or Ray (TPU_MULTIHOST_BACKEND=ray) |
Native torch.distributed (backend="tpu") via --nnodes, --node-rank, --dist-init-addr |
6D parallelism on vLLM-TorchTPU¶
Reference: vLLM-TorchTPU: Parallelism & Scaling.
| Dimension | CLI Flag | Key TPU Environment Variables & Tuning Knobs | Architectural Mechanism & When to Use |
|---|---|---|---|
1. Tensor Parallelism (TP) |
--tensor-parallel-size N |
TPU_LATENT_PROJ_INTRA_CHIP_TP=1 (shards MLA latent proj across 2 cores of a v7x chip even when TP=1) |
Shards attention heads & dense MLP weights within a fast ICI domain (TP=1..32). |
2. Data Parallelism (DP) |
--data-parallel-size N |
DP_SCHED_ENABLED=1, --data-parallel-size-local, --data-parallel-start-rank, --data-parallel-rpc-port |
Replicates attention (TP=1 or 2 = zero inter-chip attention all-reduce) while sharing a global DP * TP MoE mesh. |
3. Expert Parallelism (EP) |
--enable-expert-parallel |
USE_MOE_SPARSE_CORE=1 (default), ONEHOT_MOE_PERMUTE_THRESHOLD=32768, USE_MOE_FUSED_EP_KERNEL=1, TPU_MOE_HIERARCHICAL_EP=1, TPU_MOE_SEQUENCE_PARALLEL=1 |
Distributes num_experts / (TP * DP) routed experts across the slice using Pallas SparseCore/GMM dispatch. |
4. Pipeline Parallelism (PP) |
--pipeline-parallel-size N |
TPU_PP_DYNAMIC_CHUNKS=1 (default), TPU_PP_HANDOFF=wave\|ring (ring overlaps P2P with TPU_PP_RING_DEPTH=2), VLLM_TPU_DEVICE_ORDER="0,2,1,3,4,6,5,7" |
Partitions layers across PP stages; VLLM_TPU_DEVICE_ORDER prevents a 2-core stage from binding both cores of 1 v7x chip. |
5. Prefill Context Parallelism (PCP) |
--prefill-context-parallel-size N |
TPU_PCP_TOPOLOGY_AWARE_MESH=1 (default: binds consecutive PCP ranks to adjacent ICI torus chips) |
Splits long prefill prompts (32K–256K+) across PCP ranks to slash TTFT. |
6. Decode Context Parallelism (DCP) |
--decode-context-parallel-size N |
TPU_DCP_LSE_MERGE_A2A=1 |
Shards KV cache along sequence dimension across DCP ranks with online log-sum-exp (LSE) attention merge. |
Recipe 1: offline batch inference, multi-LoRA, pooling/embeddings and structured outputs (vLLM-TorchTPU)¶
References: vLLM-TorchTPU: Supported Models & Features, vLLM-TorchTPU: TorchTPU Compilation Cache.
# ==============================================================================
# A. Offline Batch Inference + Dynamic Multi-LoRA Routing in Python
# ==============================================================================
from vllm import LLM, SamplingParams
from vllm.lora.request import LoRARequest
llm = LLM(
model="Qwen/Qwen2.5-3B",
tensor_parallel_size=4,
max_model_len=8192,
enable_lora=True,
max_loras=4,
max_lora_rank=32,
gpu_memory_utilization=0.90,
)
sql_lora = LoRARequest(lora_name="sql-adapter", lora_int_id=1, lora_path="/mnt/disks/persist/loras/sql_lora")
outputs = llm.generate(
prompts=["Translate to SQL: find top 5 customers by revenue in 2026"],
sampling_params=SamplingParams(temperature=0.0, max_tokens=128),
lora_request=sql_lora,
)
# ==============================================================================
# B. Persistent Compilation Cache + Structured Outputs (xgrammar) + Pooling
# ==============================================================================
export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libtcmalloc_minimal.so.4
# 1. Persistent C++ PJRT binaries (.bin) + 2. Python FX/AOT cache + 3. Parallel Warmup:
export TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT="/mnt/disks/persist/tpu_pjrt_cache"
export VLLM_CACHE_ROOT="/mnt/disks/persist/vllm_fx_cache"
export VLLM_XLA_CACHE_PATH="/mnt/disks/persist/vllm_xla_cache"
export TPU_PARALLEL_PRECOMPILE=1
export VLLM_XLA_CHECK_RECOMPILATION=0 # Set to 1 in CI to fail/log on unexpected runtime recompiles.
# Serve with xgrammar Structured Outputs & Multi-LoRA:
vllm serve meta-llama/Llama-3.1-8B-Instruct \
--tensor-parallel-size 4 \
--structured-outputs-config '{"backend": "xgrammar"}' \
--enable-lora --max-lora-rank 64 \
--compilation-config '{"compile_sizes": [1, 8, 64, 2048]}' \
--port 8000
# Serve Multimodal Embedding / Pooling Model (On-Device Request Bucketing):
vllm serve Qwen/Qwen3-VL-Embedding-8B --runner pooling --tensor-parallel-size 2 --port 8001
Put all three caches on persistent storage. The compilation cache guide calls TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT the primary driver and adds VLLM_CACHE_ROOT; the quickstart, the launch post and the GKE manifest also set VLLM_XLA_CACHE_PATH (chapter 18, compilation cache guide).
3.4.2 Multimodal, omni and diffusion serving (Wan2.2, FLUX, MiniMax-H3, Qwen3-VL, Gemma 4, Kimi-K3)¶
Overview: Multi-modal VLMs (Qwen2.5-VL, Qwen3-VL, Gemma 4, Kimi-K3 MoonViT, Muse Spark) and diffusion/video generators (Wan2.2, MiniMax-H3, FLUX.1, Qwen-Image, Qwen3-Omni, Qwen3-TTS) run on TPUs by chunking video frames (MM_ENCODER_FRAME_CHUNK_PATCH_SIZE), using 3D M-RoPE / hybrid SWA-Global paging, or bypassing vision towers via --language-model-only when serving text-only traffic.
References: vLLM-TorchTPU: Supported Models & Features, vLLM-TorchTPU: TPU v7x (Ironwood) Serving Recipes, SGLang‑TorchTPU: PyTorch‑Native Production Serving on TPUs.
Multimodal, audio, safety and diffusion models on TPU¶
| Category | Validated Model Checkpoints | Supported Engine(s) | Key TPU Optimization / Architectural Feature | Recommended Flag / Env Var |
|---|---|---|---|---|
Vision-Language (M-RoPE) |
Qwen/Qwen2.5-VL-3B/7B/72B-Instruct, Qwen/Qwen3-VL-4B/30B-A3B, Qwen/Qwen3.5-VL |
vLLM-TorchTPU, SGLang-TorchTPU, llm-d EPD |
3D M-RoPE + multimodal encoder manager with video frame chunking | --limit-mm-per-prompt '{"image": 4, "video": 1}'MM_ENCODER_FRAME_CHUNK_PATCH_SIZE |
| Multimodal Hybrid SWA | RedHatAI/gemma-4-31B-it-FP8-Dynamic, RedHatAI/gemma-4-26B-A4B-it-FP8-Dynamic, google/gemma-4-31B-it |
vLLM-TorchTPU, SGLang-TorchTPU |
Hybrid sliding-window / global attention page sizing (validated on MMMU-Pro) | --tensor-parallel-size 2 --data-parallel-size 4 (v7x-8) |
MLA + Vision (MoonViT) |
moonshotai/Kimi-K3 |
vLLM-TorchTPU, SGLang-TorchTPU |
MLA + KDA linear attention + MoonViT vision tower (or text-only via --language-model-only) |
--language-model-only --limit-mm-per-prompt '{"image":0,"video":0}' |
| Safety & Multimodal Embeddings | meta-llama/Llama-Guard-4-12B, Qwen/Qwen3-VL-Embedding-8B |
vLLM-TorchTPU |
On-device pooling (--runner pooling) & AILuminate safety classification |
--runner pooling |
| Video & Image Diffusion | MiniMax/MiniMax-H3, Wan-AI/Wan2.2-T2V-14B, black-forest-labs/FLUX.1-dev |
SGLang-TorchTPU, vllm-omni (llm-d), Diffusers |
Pallas splash_sdpa (block=2048), TeaCache / Cache-DiT step skipping, Ulysses + Ring SP |
--ulysses-degree 4 --ring-degree 2 --cache-backend teacache |
3.4.3 Speculative decoding (EAGLE-3, MTP, DFlash, DFlash2, DSpark, Ngram, Suffix)¶
Overview: Speculative decoding reduces median TPOT by proposing \(K\) draft tokens per step and verifying all \(K+1\) tokens in a single parallel target MXU pass: supporting both autoregressive chain drafters (eagle3, mtp) and non-causal parallel block drafters (dflash proposing up to 15–16 tokens in 1 pass, and dspark combining non-causal block forward on target auxiliary hidden states with a sequential Markov head).
References: vLLM-TorchTPU: Speculative Decoding, SGLang‑TorchTPU: PyTorch‑Native Production Serving on TPUs.
Speculative decoding methods on vLLM-TorchTPU and SGLang-TorchTPU¶
Method ("method") |
Draft Checkpoint Required? | Validated Target + Draft Checkpoints in CI | Architectural Mechanism & Best Use Case |
|---|---|---|---|
"eagle3" |
Yes | Qwen/Qwen3-32B + RedHatAI/Qwen3-32B-speculator.eagle3Llama-3.1-8B-Instruct + yuhuili/EAGLE3-LLaMA3.1-Instruct-8B |
Autoregressive feature-level draft head consuming target multi-layer hidden states (num_speculative_tokens: 3..5). |
"mtp" ("qwen3_next_mtp") |
Built into target | Qwen/Qwen3.5-35B-A3B-FP8, Qwen/Qwen3.5-397B-A17B, Qwen/Qwen3.5-4B, DeepSeek-R1, GLM-5 |
Uses native Multi-Token Prediction heads trained jointly with the backbone; zero external draft model management. |
"dflash" / "dflash2" |
Yes | Qwen/Qwen3-8B + z-lab/Qwen3-8B-DFlash-b16 (K=15)Qwen/Qwen3-4B, Qwen/Qwen3.5-35B |
Non-causal block-diffusion draft head proposing up to 15–16 tokens in a single forward pass. |
"dspark" |
Yes | Qwen/Qwen3-4B + deepseek-ai/dspark_qwen3_4b_block7 (K=7)DeepSeek-V4-Flash, Kimi-K3 (Inferact/Kimi-K3-DSpark) |
Semi-autoregressive parallel block drafting: DFlash-style non-causal block forward conditioned on target auxiliary hidden states + sequential Markov head. |
"ngram" |
No | meta-llama/Llama-3.1-8B-Instruct (num_speculative_tokens: 5, prompt_lookup_max: 4) |
Zero-weight N-gram prompt lookup; ideal for code editing, citations, and RAG extraction. |
"suffix" |
No | meta-llama/Llama-3.1-8B-Instruct (num_speculative_tokens: 5) |
Speculates from a suffix tree built over the current prompt and prior responses. |
Recipe 2: launching EAGLE-3, MTP, DFlash, DSpark, N-Gram and Suffix speculative decoding¶
# 1. EAGLE-3 Speculative Decoding (Qwen3-32B on TPU v7x-8)
vllm serve Qwen/Qwen3-32B --tensor-parallel-size 8 --max-model-len 8192 \
--speculative-config '{"method": "eagle3", "model": "RedHatAI/Qwen3-32B-speculator.eagle3", "num_speculative_tokens": 3}'
# 2. Built-In Multi-Token Prediction (MTP on Qwen3.5-35B-A3B-FP8)
vllm serve Qwen/Qwen3.5-35B-A3B-FP8 --tensor-parallel-size 4 --enable-expert-parallel --kv-cache-dtype fp8 \
--speculative-config '{"method": "mtp", "num_speculative_tokens": 1}'
# 3. DFlash Block-Diffusion Drafting (15 Speculative Tokens in 1 Forward Pass)
vllm serve Qwen/Qwen3-8B --tensor-parallel-size 2 --max-model-len 4096 \
--speculative-config '{"method": "dflash", "model": "z-lab/Qwen3-8B-DFlash-b16", "num_speculative_tokens": 15}'
# 4. DSpark Semi-Autoregressive Block + Markov Head Drafting (7 Speculative Tokens)
vllm serve Qwen/Qwen3-4B --tensor-parallel-size 1 --max-model-len 2048 \
--speculative-config '{"method": "dspark", "model": "deepseek-ai/dspark_qwen3_4b_block7", "num_speculative_tokens": 7}'
# 5. Draft-Model-Free N-Gram or Suffix Speculative Decoding
vllm serve meta-llama/Llama-3.1-8B-Instruct --tensor-parallel-size 2 \
--speculative-config '{"method": "ngram", "num_speculative_tokens": 5, "prompt_lookup_max": 4}'
3.4.4 Quantization and load-time requantization (FP8, compressed-tensors, MXFP4, NVFP4, AWQ, GPTQ, deepseek_v4_fp8, online_fp8)¶
Overview: vllm-torchtpu reshapes and packs quantized weights once at load time (process_weights_after_loading) so Pallas matmul, attention, and fused MoE kernels execute directly on TPU v6e/v7x MXU low-precision paths (fp8 and int4/fp4 \(\to\) fp8), while supporting load-time weight requantization (MOE_REQUANTIZE_WEIGHT_DTYPE=fp4 for W4A8 MoE) and small-batch W8A16 decode switching (TPU_FP8_LINEAR_W8A16_MAX_ROWS).
Reference: vLLM-TorchTPU: Quantization.
--quantization formats and requantization settings¶
--quantization Format |
Weight \(\times\) Activation Dtype | Supported Layers & Checkpoints | Load-Time Requantization & Runtime Tuning Env Vars |
|---|---|---|---|
(auto) / fp8 |
float8_e4m3fn \(\times\) float8_e4m3fn (or bf16) |
Linear, Fused MoE, Attention KV (Qwen3.5-*-FP8, Qwen3-Coder-*-FP8, GLM-5.2-FP8) |
TPU_FP8_LINEAR_W8A16_MAX_ROWS (default 0; opt-in: padded token buckets up to this many rows skip activation quantization and run bf16 \(\times\) fp8 W8A16 for faster small-batch decode on v7x; per-channel fp8 path only; the quantization guide gives no recommended value). |
compressed-tensors |
fp8 (W8A8), int4 (W4A8, W4A16), mxfp4 |
Linear, Fused MoE (RedHatAI/gemma-4-*-FP8-Dynamic, moonshotai/Kimi-K3, Kimi-K2.6 W4A16) |
Auto-selected from HF config.json; combine with --kv-cache-dtype fp8 to halve KV HBM. |
deepseek_v4_fp8 |
float8_e4m3fn (with optional fp4 MoE requant) \(\times\) float8_e4m3fn |
Linear, Sparse MLA, Fused MoE (DeepSeek-V4-Flash, DeepSeek-V4-Pro-0813) |
Set USE_MOE_FUSED_EP_KERNEL=1, MOE_FUSED_EP_ENABLE_W4A8=1, MOE_REQUANTIZE_WEIGHT_DTYPE=fp4, MOE_REQUANTIZE_BLOCK_SIZE=512 for W4A8 MoE. |
mxfp4 |
fp4 (e2m1) + e8m0 block scales (block=32) \(\times\) bf16/fp8 |
Linear, Fused MoE (openai/gpt-oss-120b, openai/gpt-oss-20b) |
Native hardware microscaling FP4 path. |
nvfp4 |
fp4 (e2m1) + fp8 block scales \(\times\) bf16/fp8 |
Linear, Fused MoE (nvidia/Qwen3-30B-A3B-NVFP4, nvidia/GLM-5.2-NVFP4, Qwen3-Coder-480B-NVFP4) |
Native NVFP4 block-scaled matmul & MoE execution on v7x. |
awq / gptq |
int4 / int8 packed \(\times\) bf16 |
Linear (weight-only 4-bit/8-bit checkpoints) | Group-wise VPU unpack + bf16 MXU. |
online_fp8 |
bf16 checkpoint \(\to\) quantized to float8_e4m3fn at load time |
Linear, Fused MoE (any unquantized bf16 checkpoint) |
Also supports linear load-time requant via ENABLE_QUANTIZED_MATMUL_KERNEL=1, REQUANTIZE_WEIGHT_DTYPE, REQUANTIZE_BLOCK_SIZE. |
3.4.5 Validated v6e and v7x model recipes, multi-host (mp or ray) and Raiden P/D disaggregation¶
Overview: Production TPU deployment spans TPU v6e (Trillium, 1 TensorCore / 32 GB HBM per chip) and TPU v7x (Ironwood, 2 TensorCores / 192 GB HBM per chip = 8 logical devices & 768 GB HBM per 4-chip v7x-8 host). For large MoE models (Qwen3.5-397B, DeepSeek-V4, GLM-5.2), Data-Parallel Attention (TP=1, DP=8 or DP=16) + Expert Parallelism (--enable-expert-parallel) eliminates cross-chip attention all-reduces while sharding experts across the entire slice, whereas multi-host slices (v7x-16, v7x-32) stream weights directly from GCS (--load-format runai_streamer --enable-ep-weight-filter) and disaggregate Prefill/Decode via Raiden (TPURaidenConnector).
References: vLLM-TorchTPU: TPU v6e (Trillium) Serving Recipes, vLLM-TorchTPU: TPU v7x (Ironwood) Serving Recipes, vLLM-TorchTPU: Multi-Host Serving, vLLM-TorchTPU: Disaggregated Serving (Prefill / Decode).
A. TPU v6e (Trillium, 32 GB HBM/chip) model topologies¶
| Model Checkpoint(s) | Precision & KV Cache | Recommended v6e Slice |
Parallelism & Key CLI Flags |
|---|---|---|---|
Llama-3.2-1B/3B-Instruct, Qwen/Qwen3-8B |
bf16 / fp8 (--kv-cache-dtype fp8) |
v6e-1 (1 chip, 32 GB) |
--tensor-parallel-size 1 --max-model-len 8192 --max-num-batched-tokens 2048 --async-scheduling |
Qwen/Qwen2.5-VL-7B-Instruct, google/gemma-3-12b-it |
bf16 / fp8 |
v6e-1 or v6e-4 (128 GB) |
--tensor-parallel-size 1 or 4 |
Qwen/Qwen3-32B, Qwen3-Coder-30B-A3B-Instruct-FP8, Qwen3.5-35B-A3B-FP8 |
fp8 (--kv-cache-dtype fp8) |
v6e-4 (4 chips, 128 GB) |
--tensor-parallel-size 4 --enable-expert-parallel --attention-backend CUSTOM --max-model-len 16384 |
meta-llama/Llama-3.3-70B-Instruct, openai/gpt-oss-120b (mxfp4) |
fp8 / mxfp4 (--kv-cache-dtype fp8) |
v6e-8 (8 chips, 256 GB) |
--tensor-parallel-size 8 (+ --enable-expert-parallel for gpt-oss-120b) --max-model-len 16384 |
Qwen/Qwen3.5-397B-A17B-FP8 |
fp8 (--kv-cache-dtype fp8) |
v6e-16 (2 hosts, 512 GB) |
--tensor-parallel-size 16 or --data-parallel-size 2 --tensor-parallel-size 8 --enable-expert-parallel |
B. TPU v7x (Ironwood, 96 GB/device, 768 GB/host) validated CI recipes¶
| Model Checkpoint | v7x Slice (Logical Devices) |
Parallelism Layout | Quantization & KV Cache | Critical Env Vars & CI Benchmark Config Flags |
|---|---|---|---|---|
Qwen/Qwen3.5-397B-A17B-FP8 |
v7x-8 (1 host, 8 devs) |
TP=1, DP=8 + EP (or TP=2, DP=4 / TP=8) |
fp8 weights, fp8 KV (--block-size 256) |
USE_MOE_SPARSE_CORE=1, ONEHOT_MOE_PERMUTE_THRESHOLD=32768, --max-model-len 10240 --max-num-batched-tokens 1024 --max-num-seqs 64 --language-model-only |
Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8 |
v7x-8 (1 host, 8 devs) |
TP=8, DP=1 + EP |
fp8 weights, fp8 KV |
--max-model-len 16384 --max-num-batched-tokens 8192 --max-num-seqs 512 --gpu-memory-utilization 0.95 --async-scheduling |
Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8 & Qwen3.5-35B-A3B-FP8 |
v7x-8 (1 host, 8 devs) |
TP=8, DP=1 + EP |
fp8 weights, fp8 KV |
PR performance guard gate (--max-model-len 16384 --max-num-batched-tokens 8192 --max-num-seqs 512) |
RedHatAI/gemma-4-31B-it-FP8-Dynamic |
v7x-8 (1 host, 8 devs) |
TP=2, DP=4 |
compressed-tensors FP8 |
Hybrid SWA/Global multimodal serving |
deepseek-ai/DeepSeek-V4-Flash |
v7x-8 (1 host, 8 devs) |
TP=1, DP=8 + EP |
deepseek_v4_fp8 (W4A8 MoE), fp8_e4m3 KV |
MOE_REQUANTIZE_WEIGHT_DTYPE=fp4, MOE_REQUANTIZE_BLOCK_SIZE=512, TPU_ROPE_CACHE_ROW_MAJOR=1, TPU_MOE_HASH_TABLE_ROW_MAJOR=1, --max-model-len 9216 |
deepseek-ai/DeepSeek-V4-Pro-0813 |
v7x-16 (2 hosts, 16 devs) |
TP=1, DP=16 + EP |
deepseek_v4_fp8 (W4A8 MoE), fp8_e4m3 KV |
Above + USE_MOE_FUSED_EP_KERNEL=1, MOE_FUSED_EP_ENABLE_W4A8=1, MOE_FUSED_EP_V2_HEIGHT_RUNGS_OVERRIDE=2, TPU_MOE_SKIP_PADDED_TOKENS=1, RAGGED_GATHER_REDUCE_VERSION=v3, --enable-ep-weight-filter --safetensors-load-strategy prefetch |
zai-org/GLM-5.2-FP8 |
v7x-16 (2 hosts, 16 devs) |
TP=1, DP=16 + EP |
fp8 weights, fp8 KV |
--enable-ep-weight-filter --safetensors-load-strategy prefetch --tool-call-parser glm47 --enable-auto-tool-choice --reasoning-parser glm45 |
moonshotai/Kimi-K3 |
v7x-32 (4 hosts, 16 chips, 32 devices) |
TP=32, DP=1 + EP |
compressed-tensors FP8, fp8 KV |
--enable-ep-weight-filter --language-model-only --block-size 256 --compilation-config '{"compile_sizes":[1,8,8192]}' --model-loader-extra-config '{"memory_limit":17179869184}' |
Recipe 3: multi-host execution (mp or ray), Raiden P/D disaggregation and SGLang-TorchTPU launch¶
# ==============================================================================
# A. Option 1: Native Multiprocessing (mp) Multi-Host Backend (Default, No Ray)
# ==============================================================================
# Mode 1A (Multi-Host TP/PP via --nnodes): Run on Host 0 (Leader) & Host 1 (--headless)
vllm serve Qwen/Qwen3.5-397B-A17B --tensor-parallel-size 16 --enable-expert-parallel \
--nnodes 2 --node-rank "${NODE_RANK}" --master-addr "${HOST_0_IP}" --master-port 29500 \
$( [ "${NODE_RANK}" -ne 0 ] && echo "--headless" )
# Mode 1B (Multi-Host DP+EP via --data-parallel-size-local): Host 0 (start-rank 0) & Host 1 (start-rank 8, --headless)
vllm serve Qwen/Qwen3.5-397B-A17B --tensor-parallel-size 1 --data-parallel-size 16 \
--data-parallel-size-local 8 --data-parallel-start-rank $(( NODE_RANK * 8 )) \
--data-parallel-address "${HOST_0_IP}" --data-parallel-rpc-port 13345 --enable-expert-parallel \
$( [ "${NODE_RANK}" -ne 0 ] && echo "--headless" )
# ==============================================================================
# B. Option 2: Ray Multi-Host Backend (TPU_MULTIHOST_BACKEND=ray) + GCS Weight Streaming
# ==============================================================================
export TPU_MULTIHOST_BACKEND=ray
export VLLM_RAY_EXTRA_ENV_VARS_TO_COPY="MOE_REQUANTIZE_WEIGHT_DTYPE,MOE_REQUANTIZE_BLOCK_SIZE,TPU_ROPE_CACHE_ROW_MAJOR,TPU_MOE_HASH_TABLE_ROW_MAJOR,USE_MOE_FUSED_EP_KERNEL,MOE_FUSED_EP_ENABLE_W4A8,MOE_FUSED_EP_V2_HEIGHT_RUNGS_OVERRIDE,TPU_MOE_SKIP_PADDED_TOKENS,RAGGED_GATHER_REDUCE_VERSION,LIBTPU_INIT_ARGS"
vllm serve gs://your-bucket/DeepSeek-V4-Pro-0813 \
--load-format runai_streamer \
--model-loader-extra-config '{"memory_limit":4294967296,"concurrency":8}' \
--enable-ep-weight-filter --safetensors-load-strategy prefetch \
--tensor-parallel-size 1 --data-parallel-size 16 --enable-expert-parallel \
--quantization deepseek_v4_fp8 --kv-cache-dtype fp8_e4m3 --async-scheduling
# ==============================================================================
# C. Multi-Host Prefill/Decode Disaggregation with Raiden (TPURaidenConnector)
# ==============================================================================
# 1. Start Coordinator: python examples/disagg/run_raiden_controller.py --port 50055
# 2. Launch Prefill (kv_producer, PCP=2, TP=4) & Decode (kv_consumer, TP=2, DP=4; KV is resharded automatically):
export TPU_USE_RAIDEN_KV_CACHE_MANAGER=1
export TPU_RAIDEN_CONTROLLER_ADDRESS="${CONTROLLER_IP}:50055"
export TPU_RAIDEN_JOB_NAME="prefill" # Set "decode" on Decode pool with kv_role="kv_consumer"
export TPU_RAIDEN_ENGINE_ID="0"
export TPU_RAIDEN_QWEN35_ADMISSION=1
vllm serve Qwen/Qwen3.5-35B-A3B-FP8 --port 8400 \
--tensor-parallel-size 4 --prefill-context-parallel-size 2 --enable-expert-parallel \
--kv-cache-dtype fp8 --block-size 256 --attention-backend CUSTOM \
--kv-transfer-config '{"kv_connector":"TPURaidenConnector","kv_connector_module_path":"vllm_torchtpu.distributed.kv_transfer.tpu_connector","kv_role":"kv_producer"}'
# ==============================================================================
# D. SGLang-TorchTPU Production Container & Recipe Launch (TPU v7x)
# ==============================================================================
docker run -it --rm --privileged --net=host --shm-size=64g \
-e SGLANG_PLATFORM=tpu_oot lmsysorg/sglang:v0.1.0-tpu \
python -m benchmark.tpu.launch_server --config recipe/configs/gpt_oss_20b/server.py
The Raiden connector class is TPURaidenConnector in vllm_torchtpu.distributed.kv_transfer.tpu_connector, as the vLLM-TorchTPU code defines it and every examples/disagg/*.sh script passes it. The disaggregated-serving guide writes TpuRaidenConnector in ...kv_transfer.raiden.raiden_connector, a class and module the code does not define (chapter 20, vLLM-TorchTPU disaggregated serving). The decode instance runs the same exports with TPU_RAIDEN_JOB_NAME="decode", --tensor-parallel-size 2 --data-parallel-size 4 and "kv_role":"kv_consumer".
Two names for the SGLang platform
The launch post and the README's Docker command set SGLANG_PLATFORM=tpu_oot (the out-of-tree TpuOOTPlatform); the recipes' base config defaults to tpu, the in-tree TpuSRTPlatform that TpuOOTPlatform subclasses, and SUPPORT.md lists out-of-tree mode as Experimental. Both run the same kernels (chapter 19).
3.5 Distributed inference with llm-d on Kubernetes¶
3.5.1 llm-d CRDs, EndpointPickerConfig (v1) and the foundational well-lit paths¶
Overview: llm-d extends the Kubernetes Gateway API Inference Extension (GAIE) with an Envoy ext_proc Endpoint Picker (epp) that inspects every incoming OpenAI/Anthropic prompt, runs Data-Layer Producers (approximate or precise ZMQ KV-block indexing, multimodal token estimation, in-flight token accounting, P2P KV source selection, and online xgboost TTFT/TPOT prediction), applies Admitters, Filters, Scorers, and Profile Deciders, and routes traffic across aggregated or disaggregated (Encode / Prefill / Decode) vLLM and SGLang pools.
The gateway asks the EPP for a decode and a prefill endpoint, then hands the request to the decode pod's sidecar, which runs prefill remotely before decoding locally. The KV cache moves straight from the prefill engine to the decode engine; tokens return through the sidecar and the gateway.
EndpointPickerConfig (llm-d.ai/v1) producers, admitters, deciders, filters, scorers and pickers¶
References: EndpointPickerConfig (EPP Configuration), Deploy an Optimized Baseline, Enable Precise Prefix-Cache Aware Routing, Route Requests by Predicted Latency, Enable P2P Prefix Cache Sharing.
| Plugin Stage | Plugin type Name |
Key parameters & Defaults |
Scoring / Filtering Formula & Operational Behavior |
|---|---|---|---|
| Producer | approx-prefix-cache-producer / precise-prefix-cache-producer |
blockSizeTokens: 64 (256 on TPU v6e, 4352 on Qwen3.5 TPU v7x), lruCapacityPerServer, zmqPort: 5556 |
Hashes prompt prefix blocks (approximate) or subscribes to engine ZMQ KVEvents (BlockStored / BlockRemoved on :5556 or DP ports 5557..5564) + HTTP /v1/*/render tokenization (precise). |
| Producer | token-producer |
vllm.messagesRenderMode: auto\|native\|legacy, estimate.mode: dynamic\|static |
Tokenizes chat/messages/responses via engine /render endpoints and estimates image/video token costs (width*height/1024 for Qwen3-VL; static 70..1120 for Gemma 4). |
| Producer | inflight-load-producer & p2p-source-producer |
minCachedTokenDelta: 2048 |
Tracks in-flight tokens/requests per pod and selects a peer donor pod (kv_transfer_params.remote_kv_source) when a peer holds \(\ge 2048\) more cached prefix tokens than the chosen destination pod. |
| Producer | predicted-latency-producer |
streamingMode: false\|true, predictionServerUrl: "http://localhost:8001" |
Queries sidecar xgboost predictor (prediction-server-1:8001) trained every 10s by training-server:8000 (LATENCY_MIN_SAMPLES_FOR_RETRAIN_FRESH=10) for per-server \(\widehat{\text{TTFT}}\) & \(\widehat{\text{TPOT}}\). |
| Admitter | latency-slo-admitter |
Reads x-llm-d-slo-ttft-ms, x-llm-d-slo-tpot-ms, x-llm-d-inference-objective |
Rejects sheddable traffic (priority < 0) at admission when no server is predicted to meet SLOs; admits priority >= 0 traffic best-effort to the server with smallest SLO deficit. |
| Decider | always-disagg-pd-decider / prefix-based-pd-decider / always-disagg-multimodal-decider |
disagg-profile-handler (prefill, decode, encode profiles) |
Decides per request whether to execute remote Prefill (always-disagg-pd-decider or prefix-based-pd-decider based on uncached token length) and/or remote Vision Encode (always-disagg-multimodal-decider). |
| Filter | prefix-cache-affinity-filter (strict / loose) |
affinityThreshold: 0.80 (0.60 MM), peakPrefillThroughput, maxTTFTPenaltyMs: 18000 (36000 MM) |
Sticky gate: narrows candidates to pods holding \(\ge\) affinityThreshold of the prompt prefix unless queued prefill load divided by peakPrefillThroughput exceeds maxTTFTPenaltyMs. |
| Filter | slo-headroom-tier-filter |
headroomThreshold: 0.0 |
Partitions candidate pods into SLO-compliant (\(\text{SLO} - \widehat{\text{Latency}} \ge 0\)) vs violating tiers before affinity and latency scoring. |
| Filter | prefill-filter / decode-filter / encode-filter |
Matches llm-d.ai/role: prefill \| decode \| encode |
Restricts each scheduling profile in disagg-profile-handler to pods of the matching worker role. |
| Scorer | token-load-scorer / active-request-scorer / queue-scorer |
In-flight token count / active request count / waiting queue depth | token-load-scorer balances prefill token work (optimized-baseline); active-request-scorer balances decode & diffusion/TTS concurrency (pd-disaggregation, omni-serving); queue-scorer balances omni queues. |
| Scorer | prefix-cache-scorer / latency-scorer / lora-affinity-scorer |
Weighted in schedulingProfiles (weight: float) |
Scores candidate pods by prefix-cache hit ratio, predicted latency headroom (latency-scorer), or hot LoRA adapter residency (lora-affinity-scorer). |
| Picker | max-score-picker / weighted-random-picker |
maxNumOfEndpoints: 1 |
max-score-picker deterministically picks top scorer; weighted-random-picker samples proportionally to score (default in predicted-latency-routing). |
llm-d foundational well-lit paths (release-1.0)¶
References: llm-d foundational well-lit paths and the ten guides it links: Optimized Baseline, Precise Prefix-Cache Routing, Tiered Prefix Cache, P2P Prefix Cache Sharing, P/D Disaggregation, Wide Expert Parallelism, Predicted Latency, Multimodal Models, Omni Models, Responses API.
| # | Well-Lit Path (GUIDE_NAME) |
Core Problem Solved & Router Pipeline | Validated TPU Recipes (v5p, v6e, v7x) |
Validated GPU / XPU / Other Recipes | Key Flags, Connectors & Measured Impact |
|---|---|---|---|---|---|
| 1 | Optimized Baseline ( optimized-baseline) |
Prefix-cache affinity with saturation override (prefix-cache-affinity-filter + token-load-scorer). |
• tpu/v5p: 2x2x1 (4 chips, TP=4) Qwen3-32B• tpu/v6: 2x4 (8 chips, TP=8) Qwen3-32B• tpu/v7: 2x2x1 (4 chips = 8 TCs, DP=8, TP=1+EP) Qwen3.5-397B-A17B-FP8• tpu/v7-dynamic-slice: Kueue 2x2x1/2x2x2 Qwen3-Coder-480B |
gpu (H100 2x TP=2 Qwen3-32B, vLLM & SGLang), amd (MI300X), xpu (Arc B60), npu, cpu, iluvatar, metax, biren, mthreads |
router/tpu-v7.values.yaml sets blockSizeTokens: 4352 & 262,144 context; peakPrefillThroughput gates sticky cache affinity. |
| 2 | Precise Prefix-Cache Routing ( precise-prefix-cache-routing) |
Eliminates cache-index drift via real-time ZMQ KVEvents (:5556) + HTTP /v1/*/render tokenization (replicas=1). |
• tpu/v6: 2x4 (TP=8) Qwen3-32B w/ router/tpu-v6e.values.yaml (--block-size=256)• tpu/v7: 2x2x1 (DP=8, EP) Qwen3.5-397B-A17B-FP8 (--block-size=4352) |
gpu (H100 2x TP=2, vLLM & SGLang w/ dedicated render pool), amd, xpu |
Mandatory on TPU v6e: --block-size=256 (blockSizeTokens: 256) because --block-size=64 exhausts SMEM on TorchTPU. |
| 3 | Tiered Prefix Cache ( tiered-prefix-cache) |
Spills evicted HBM KV blocks to host DRAM (VARIANT=cpu) or shared RWX filesystem (VARIANT=fs). |
• tpu/v6 (cpu): TPURaidenOffloadingConnector• tpu/v7 (cpu & fs): 2x2x1 or 2x2x2 (32 GiB/rank DRAM) + GCP Managed Lustre (lustre-class, raiden_storage_path: "/mnt/files-storage/kv") |
gpu (native OffloadingConnector, lmcache-connector, mooncake-store, SGLang HiCache; AWS EFS / Lustre), amd, xpu |
On TPU v7x VARIANT=fs: sets PYTHONHASHSEED=0, direct_io: true, metadata_cache_max_entries: 1048576, lruCapacityPerServer sized to DRAM+FS tier. |
| 4 | P2P Prefix Cache Sharing ( p2p-kv-cache-sharing) |
Cross-pod KV transfer over OffloadingConnector P2P tier (:7777) when target pod is cold (minCachedTokenDelta: 2048). |
Uses tiered-prefix-cache shared Lustre tier on TPU; P2P socket connector validated on gpu & xpu. |
gpu (8x H200 TP=1 openai/gpt-oss-120b), xpu (2x Arc B60 Qwen3-0.6B) |
On 8x H200 Doc Q&A (96 convs \(\times\) 48K tok): 6.3 req/s (0.67s P50 TTFT, 34ms P90 TPOT) vs 4.4 req/s load-aware (+43%) & 2.75 req/s affinity (+129%). |
| 5 | P/D Disaggregation ( pd-disaggregation) |
Splits Prefill & Decode via DisaggregatedSet (lws v0.11.1+) + always-disagg-pd-decider (or prefix-based-pd-decider). |
• tpu/v5p & tpu/v6: 1P + 1D w/ TPUConnector• tpu/v7: 2x2x1 Prefill (PCP=8 + 64GiB DRAM offload) \(\to\) Decode (DP=8) w/ TPURaidenConnector• tpu/v7-dynamic-slice: TPUConnectorHMA |
gpu (gpt-oss-120b NixlConnector / MooncakeConnector, SGLang nixl/mooncake), amd (MoRIIOConnector), xpu, npu, rbln, iluvatar |
Separates TTFT-bound prefill scaling (token-load-scorer) from TPOT-bound decode scaling (active-request-scorer). |
| 6 | Wide Expert Parallelism ( wide-ep) |
Multi-node MoE DP/EP + P/D DisaggregatedSet with per-DP-rank routing (ports 8000..8007 & 8200..8207). |
Covered in the model guides: DeepSeek-V4 (v7x-8/16) & GLM-5.2 (tpu7x-2x2x2-dp16). |
gpu (32x H200 DeepSeek-R1-0528: DP16 P + DP16 D w/ DeepEP + NIXL), amd (32x MI355X DeepSeek-V3 MoRI-EP + MoRI-IO), xpu (4x XPU) |
Requires full-mesh all-to-all RDMA connectivity across NICs; routes directly to individual DP rank ports. |
| 7 | Predicted Latency Routing ( predicted-latency-routing) |
Online xgboost sidecars (training-server:8000, prediction-server-1:8001) predicting TTFT & TPOT (SLO_AWARE=false\|true). |
• tpu/v6: 2 replicas \(\times\) 2x4 (TP=8) Qwen3-32B• tpu/v7: 2 replicas \(\times\) 2x2x1 (TP=8) Qwen3-32B |
gpu (H100 2x TP=2 Qwen3-32B, 131K RoPE context, vLLM & SGLang), amd (MI355X), xpu (Qwen3-0.6B) |
Router pod requests 18 vCPUs, 24 GiB RAM; SLO_AWARE=true requires "stream": true and enforces x-llm-d-slo-{ttft,tpot}-ms. |
| 8 | Serve Multimodal Models ( multimodal-serving) |
Media-aware hashing & token estimation across TOPOLOGY=aggregation, e-pd (Encode + PD), and e-p-d (Encode + P + D). |
• tpu/v7 (aggregation): 8 replicas \(\times\) 2x2x1 (TP=4) Qwen3-VL-32B-Instruct (or google/gemma-4-31B-it w/ gemma4 static token estimate) |
gpu (H200 Qwen3-VL-32B: aggregation 8xTP2, e-pd 2E+8PD, e-p-d 2E+4P+4D via ECCPUConnector over NIXL), xpu (2x2 Arc B60) |
Tuned affinityThreshold: 0.6, maxTTFTPenaltyMs: 36000, peakPrefillThroughput: 15751; video headers x-llm-d-video-{fps,duration-seconds,resolution}. |
| 9 | Serve Omni Models ( omni-serving) |
Serves speech & image generation via vllm-omni (--omni) & sglang (TASK=omni \| text-to-image \| image-to-image \| text-to-speech). |
Standalone TPU diffusion/omni recipes via Diffusers (Qwen-Image-2.1 on v6e-4) and Muse-Spark-30B (v7x-4). |
gpu (H100: Qwen3-Omni-30B-A3B 1x2GPU; Qwen-Image, Qwen-Image-Edit-2511, Qwen3-TTS-12Hz-1.7B 3x1GPU), xpu (FLUX.2-klein-4B SGLang) |
omni uses queue-scorer; text-to-image/image-to-image/text-to-speech use active-request-scorer (injectDefaults: false). |
| 10 | Stateful Responses API ( agentic-api) |
Deploys vllm/agentic-api:9000 + PostgreSQL 17:5432 in front of llm-d router for stateful /v1/responses (previous_response_id). |
Layers onto any vLLM TPU guide (pd-disaggregation tpu/v6 Qwen3-32B or tpu/v7 Qwen3.5-397B w/ --tool-call-parser=qwen3_xml). |
gpu (H100 2x TP=2 Qwen3-32B w/ --enable-auto-tool-choice --tool-call-parser=hermes --reasoning-parser=qwen3) |
Supports server-side previous_response_id state rehydration, webhook tool loops, RFC 6455 WebSocket /v1/responses, & Codex CLI. |
Recipe 1: deploying an llm-d well-lit path and its CRDs (InferencePool, InferenceObjective, InferenceModelRewrite, EndpointPickerConfig)¶
References: InferencePool, InferenceObjective, InferenceModelRewrite, EndpointPickerConfig (EPP Configuration).
# ==============================================================================
# Three-step deployment pattern shared by the llm-d foundational guides
# ==============================================================================
export BRANCH=release-1.0
git clone https://github.com/llm-d/llm-d.git && cd llm-d && git checkout ${BRANCH}
export REPO_ROOT=$(realpath $(git rev-parse --show-toplevel))
export GUIDE_NAME=optimized-baseline # Or: precise-prefix-cache-routing | tiered-prefix-cache | pd-disaggregation | predicted-latency-routing | multimodal-serving
export NAMESPACE=llm-d-${GUIDE_NAME}
export ACCELERATOR_TYPE=tpu/v7 # Options: tpu/v5p, tpu/v6, tpu/v7, tpu/v7-dynamic-slice, gpu, amd, xpu, npu
export MODEL_SERVER=vllm # Options: vllm, sglang, vllmomni
export INFRA_PROVIDER=gke # Options: base, gke, coreweave, amd-ci
source ${REPO_ROOT}/guides/env.sh # Sets GAIE_VERSION, ROUTER_CHART_VERSION, ROUTER_STANDALONE_CHART, ROUTER_GATEWAY_CHART
# 1. Install GAIE v1 CRDs, Namespace, and HuggingFace Secret (plus LWS v0.11.1+ for P/D or multi-host)
kubectl apply -f https://github.com/kubernetes-sigs/gateway-api-inference-extension/${GAIE_URL}/v1-manifests.yaml
kubectl create namespace ${NAMESPACE} --dry-run=client -o yaml | kubectl apply -f -
kubectl create secret generic llm-d-hf-token --from-literal="HF_TOKEN=${HF_TOKEN}" -n "${NAMESPACE}" --dry-run=client -o yaml | kubectl apply -f -
# 2. Deploy the llm-d Router (Standalone Mode w/ Envoy sidecar, or Gateway Mode via ROUTER_GATEWAY_CHART)
helm install ${GUIDE_NAME} ${ROUTER_STANDALONE_CHART} \
-f ${REPO_ROOT}/guides/recipes/router/base.values.yaml \
-f ${REPO_ROOT}/guides/${GUIDE_NAME}/router/${GUIDE_NAME}.values.yaml \
-f ${REPO_ROOT}/guides/${GUIDE_NAME}/router/tpu-v7.values.yaml \
-n ${NAMESPACE} --version ${ROUTER_CHART_VERSION}
# 3. Deploy the Model Server Kustomize Overlay for Your Accelerator & Provider
kubectl apply -n ${NAMESPACE} -k ${REPO_ROOT}/guides/${GUIDE_NAME}/modelserver/${ACCELERATOR_TYPE}/${MODEL_SERVER}/${INFRA_PROVIDER}/
# ==============================================================================
# Condensed Production Manifest: InferencePool + InferenceObjective +
# InferenceModelRewrite + EndpointPickerConfig (v1)
# ==============================================================================
apiVersion: inference.networking.k8s.io/v1
kind: InferencePool
metadata:
name: qwen3-tpu-pool
namespace: llm-d
spec:
targetPorts: [{number: 8000}] # Or [{number: 8000}, ..., {number: 8007}] for 8-rank Wide-EP DP pods.
selector:
matchLabels: {llm-d.ai/guide: pd-disaggregation}
endpointPickerRef:
group: ""
kind: Service
name: pd-disaggregation-epp
port: {number: 9002}
failureMode: FailClose
---
apiVersion: llm-d.ai/v1
kind: InferenceObjective
metadata:
name: realtime-gold-tier
namespace: llm-d
spec:
priority: 100 # >= 0: Protected interactive traffic; < 0: Sheddable batch traffic
poolRefs: [{name: qwen3-tpu-pool}] # v1 removed poolRef; or use poolSelector
---
apiVersion: llm-d.ai/v1alpha2
kind: InferenceModelRewrite
metadata:
name: lora-canary-split
namespace: llm-d
spec:
poolRef: {group: inference.networking.k8s.io, name: qwen3-tpu-pool}
rules:
- matches: [{model: {type: Exact, value: "finance-assistant-prod"}}]
targets:
- {modelRewrite: "finance-lora-v1", weight: 90}
- {modelRewrite: "finance-lora-v2", weight: 10}
---
apiVersion: llm-d.ai/v1
kind: EndpointPickerConfig
featureGates: [flowControl]
plugins:
- {name: prefill-filter, type: prefill-filter}
- {name: decode-filter, type: decode-filter}
- {name: affinity-filter, type: prefix-cache-affinity-filter, parameters: {affinityThreshold: 0.8, peakPrefillThroughput: 16444, maxTTFTPenaltyMs: 18000}}
- {name: slo-admitter, type: latency-slo-admitter}
- {name: slo-filter, type: slo-headroom-tier-filter, parameters: {headroomThreshold: 0.0}}
- {name: token-load, type: token-load-scorer}
- {name: active-reqs, type: active-request-scorer}
- {name: latency-pred, type: latency-scorer}
- {name: pd-decider, type: always-disagg-pd-decider}
- {name: pd-handler, type: disagg-profile-handler, parameters: {deciderPluginName: pd-decider}}
schedulingProfiles:
- name: prefill
plugins: [{pluginRef: prefill-filter}, {pluginRef: affinity-filter}, {pluginRef: token-load, weight: 1.0}]
- name: decode
plugins: [{pluginRef: decode-filter}, {pluginRef: slo-filter}, {pluginRef: active-reqs, weight: 1.0}, {pluginRef: latency-pred, weight: 2.0}]
llm-d's API reference serves InferenceObjective as llm-d.ai/v1, where spec.poolRef is replaced by spec.poolRefs (1 to 16 references) or spec.poolSelector (InferenceObjective), and InferenceModelRewrite as llm-d.ai/v1alpha2 (InferenceModelRewrite, chapter 20). The EndpointPickerConfig above is a condensed listing that mixes plugins from several well-lit paths; start from a guide's router values rather than this listing.
Info
Security Trust Boundary for Client SLO & Priority Headers (EPP HTTP Headers Reference):
The EPP honors x-llm-d-slo-ttft-ms, x-llm-d-slo-tpot-ms, and x-llm-d-inference-objective (legacy x-gateway-inference-objective). Always strip or sanitize untrusted client x-llm-d-* and x-gateway-inference-objective headers at your ingress Gateway or Envoy ext_authz filter and inject authoritative tenant headers.
3.5.2 Gateway providers, GKE TPU chips, devices and slices, and cloud providers¶
Overview: llm-d decouples inference scheduling (InferencePool + EPP) from the north-south proxy layer via standard Envoy ext_proc gRPC hooks across 8 Gateway providers and 7 Kubernetes cloud infrastructures, with support for Google Cloud TPU (v5p, v6e, tpu7x) and GKE Dynamic Slicing with Kueue.
References: Gateway Guides, Google Kubernetes Engine (GKE), Google Cloud TPU, Azure Kubernetes Service, CoreWeave, DigitalOcean, OpenShift, OpenShift on AWS, minikube.
A. llm-d gateway providers¶
| Gateway Provider | Tested Version | GatewayClassName / Mode |
Helm Chart / provider.name |
Key Production Feature & Timeout Policy Resource |
|---|---|---|---|---|
| Standalone Envoy Sidecar | Envoy + epp in 1 Pod |
None (Service/${GUIDE_NAME}-epp:80) |
${ROUTER_STANDALONE_CHART} |
Zero Gateway CRD setup; ideal for internal cluster services, agentic-api, or batch-gateway. |
| GKE Inference Gateway | GKE Rapid 1.32+ |
gke-l7-regional-external-managed / gke-l7-rilb |
${ROUTER_GATEWAY_CHART} (--set provider.name=gke) |
Native GCP L7 LB + Preferred Backends HA (TrafficDistribution: PreferClose); uses GCPBackendPolicy (timeoutSec: 3600). |
| Istio Gateway | 1.29.2 |
istio |
--set provider.name=istio |
Lowest-latency in-cluster Envoy mesh; uses DestinationRule + EnvoyFilter for ext_proc. |
| Envoy AI Gateway | v0.7.0 + EG v1.8.1 |
envoy-ai-gateway |
--set provider.name=envoy-ai-gateway |
Token-based rate limiting (BackendTrafficPolicy), unified multi-vendor LLM routing (AIServiceBackend). |
| Agentgateway | v1.1.0 (kgateway v2.2.2) |
agentgateway |
--set provider.name=agentgateway |
Native MCP (Model Context Protocol) tool routing + A2A (Agent-to-Agent) multiplexing alongside InferencePool. |
| NGINX Gateway Fabric | v2.7.2 |
nginx |
--set provider.name=nginx |
Native NGINX ext_proc integration with SnippetsFilter / ClientSettingsPolicy. |
| Kong AI Gateway / LiteLLM | Kong v3.9.3 / LiteLLM v1.90.2 |
Upstream of llm-d Router |
See Kong AI Gateway and LiteLLM | Enterprise API keys, team cost budgets, PII scrubbing, and multi-region fallback chains. |
| No-K8s Standalone | Docker / Bare-Metal VM | --endpoints-file discovery |
See No-Kubernetes Deployment | Runs epp + Envoy on bare metal or VMs without a Kubernetes control plane. |
B. GKE TPU chips, devices and slices¶
Reference: llm-d: Google Cloud TPU.
| GKE Machine Type | Node Selectors (gke-tpu-accelerator / gke-tpu-topology) |
Pod Request (google.com/tpu) |
Physical Chips | Framework Devices (TensorCores) |
Total HBM & Bandwidth | Required vllm serve Parallelism (TP × DP = Devices) |
|---|---|---|---|---|---|---|
ct6e-standard-4t (v6e, 1 host) |
tpu-v6e-slice / 2x2 |
google.com/tpu: 4 |
4 | 4 (1 TC/chip) | 128 GB (6.5 TB/s) |
--tensor-parallel-size=4 |
ct6e-standard-8t (v6e, 1 host) |
tpu-v6e-slice / 2x4 |
google.com/tpu: 8 |
8 | 8 (1 TC/chip) | 256 GB (13.1 TB/s) |
--tensor-parallel-size=8 (Foundations v6e baseline) |
tpu7x-standard-4t (TPU7x, 1 host) |
tpu7x / 2x2x1 |
google.com/tpu: 4 |
4 | 8 (2 TCs/chip, 6x faster die-to-die ICI) | 768 GB (29.5 TB/s) |
--data-parallel-size=8 --tensor-parallel-size=1 --enable-expert-parallel (MoE) or --tensor-parallel-size=8 |
tpu7x-standard-4t \(\times\) 2 (2 hosts, LWS) |
tpu7x / 2x2x2 |
google.com/tpu: 4 per pod |
8 | 16 (8 TCs/host \(\times\) 2 hosts) | 1,536 GB (59.0 TB/s) |
--data-parallel-size=16 --tensor-parallel-size=1 --enable-expert-parallel (GLM-5.2) or --tensor-parallel-size=16 |
tpu7x Dynamic Slice (4x4x4 sub-block) |
tpu7x (Kueue Topology + WorkloadPriorityClass) |
google.com/tpu: 4 per pod |
4 or 8 | 8 or 16 | 768–1,536 GB |
Kueue places 2x2x1 or 2x2x2 slices dynamically inside a pre-provisioned 4x4x4 sub-block (tpu/v7-dynamic-slice). |
C. Cloud provider specifics for llm-d¶
| Cloud Provider | Accelerator Node Labels | High-Speed RDMA / Interconnect | Model Weight & KV Cache Storage | Critical Provider Setup Requirement |
|---|---|---|---|---|
GKE TPU (v6e, tpu7x) |
cloud.google.com/gke-tpu-accelerator: tpu7xcloud.google.com/gke-tpu-topology: 2x2x1 |
2D/3D Optical ICI Torus (800–1200 GB/s) + 100 Gb/s DCN (TPURaidenConnector) |
Node hostPath /var/cache/huggingface (gke-model-cache-hostpath, \(\ge 200\text{ GB}\) v6e, \(\ge 1\text{ TB}\) v7x) + GCP Managed Lustre (lustre-class) |
Set cluster-autoscaler.kubernetes.io/safe-to-evict: "false" (or a PodDisruptionBudget) on model-server pods under the OPTIMIZE_UTILIZATION autoscaler profile; use a Custom ComputeClass that falls back from reservation to Spot to DWS flex-start. |
GKE GPU (A3-Ultra, A4) |
cloud.google.com/gke-accelerator: nvidia-h200-141gb / nvidia-b200 |
GPUDirect RDMA over RoCEv2 (gvnic + gke-rdma DRANet component) |
GcsFuseCsiDriver / Hyperdisk ML (hyperdisk-ml) |
Multi-NIC subnet setup + disable-gke-nccl-tuner-patch component where required. |
Azure AKS (ND H100/H200 v5) |
accelerator: nvidia |
Kubernetes DRA (dranet) + InfiniBand (mlx5_ib0..7) |
azurefile-csi (Premium NFS) or blob-csi |
Enable --enable-dra on AKS; attach ResourceClaimTemplate (deviceClassName: dranet). |
CoreWeave (H200, GB200) |
gpu.nvidia.com/class: H200 |
8x 400G InfiniBand (rdma/ib: 8) + MNNVL ComputeDomain (resource.nvidia.com/v1beta1) |
CoreWeave Shared Object / NVMe vast-csi |
Set UCX_NET_DEVICES=mlx5_0:1..mlx5_7:1 and IPC_LOCK capability. |
DigitalOcean (DOKS H100) |
doks.digitalocean.com/gpu-brand: nvidia |
8x 400G RoCEv2 | do-block-storage |
Install NVIDIA Network Operator + PodSecurity privileged namespace. |
Red Hat OpenShift (OCP / ROSA) |
nvidia.com/gpu.present: "true" |
SR-IOV Network Operator + AWS EFA (vpc.amazonaws.com/efa: 4) |
ocs-storagecluster-cephfs / AWS FSx for Lustre |
Bind SecurityContextConstraints (scc/privileged or ipc-lock) to llm-d ServiceAccount. |
3.5.3 Batch serving (/v1/batches), the async processor (llm-d-async) and stateful /v1/responses (agentic-api)¶
Overview: Beyond synchronous /v1/chat/completions, llm-d provides three complementary engines that share the same InferencePool and EPP router: (1) OpenAI /v1/batches + /v1/files (batch-gateway) for up to 50,000-request JSONL jobs backed by PostgreSQL + Redis/Valkey + RWX PVC/S3, (2) Queue-driven llm-d-async processor consuming GCP Pub/Sub or Redis Sorted Sets with priority/quota dispatch gates to fill idle accelerator slack, and (3) Stateful /v1/responses (vllm/agentic-api + PostgreSQL 17) for multi-turn conversation continuation (previous_response_id), webhook tool loops, and WebSocket streaming.
References: Run Batch Jobs (Batch Gateway), Queue Async Requests (Async Processor), Serve the Stateful OpenAI Responses API.
# ==============================================================================
# A. Deploy OpenAI /v1/batches & /v1/files Batch Gateway (PostgreSQL + Redis + RWX PVC/S3)
# ==============================================================================
kubectl create namespace batch-gateway
kubectl create secret generic batch-gateway-secrets -n batch-gateway \
--from-literal=redis-url="redis://redis-master.redis.svc.cluster.local:6379/0" \
--from-literal=postgresql-url="postgresql://user:password@postgresql.postgresql.svc.cluster.local:5432/batchgateway"
helm install batch-gateway oci://ghcr.io/llm-d/charts/batch-gateway \
-n batch-gateway \
--set processor.config.globalInferenceGateway.url="http://optimized-baseline-epp.llm-d-optimized-baseline.svc.cluster.local:80" \
--set "apiserver.config.batchAPI.passThroughHeaders={Authorization}" \
--set global.fileClient.fs.pvcName="batch-gateway-pvc"
# Upload JSONL & Submit Batch Job (Port 8000 = API, Port 8081 = /health):
FILE_ID=$(curl -s -X POST http://localhost:8000/v1/files -F "purpose=batch" -F "file=@batch_input.jsonl" | jq -r '.id')
curl -s -X POST http://localhost:8000/v1/batches -H "Content-Type: application/json" \
-d "{\"input_file_id\": \"${FILE_ID}\", \"endpoint\": \"/v1/chat/completions\", \"completion_window\": \"24h\"}"
# ==============================================================================
# B. Deploy Queue-Driven Async Processor (llm-d-async: GCP Pub/Sub or Redis Sorted Set)
# ==============================================================================
export MQ_PROVIDER=gcp-pubsub # Options: gcp-pubsub, redis
export IP=$(kubectl get svc optimized-baseline-epp -n llm-d-optimized-baseline -o jsonpath='{.spec.clusterIP}')
[ "$MQ_PROVIDER" = "redis" ] && TARGET_KEY="ap.transportConfig.queues[0].igw_base_url" || TARGET_KEY="ap.transportConfig.topics[0].igw_base_url"
helm install llm-d-async oci://ghcr.io/llm-d/charts/llm-d-async \
-f ${REPO_ROOT}/guides/batch-serving/asynchronous-processing/${MQ_PROVIDER}/values.yaml \
--set ${TARGET_KEY}=http://${IP}:80 \
-n llm-d-async --create-namespace --version v1.0.0
# Publish Async Request (Note: created & deadline MUST be unquoted Unix-second numbers):
gcloud pubsub topics publish async-proc-requests \
--message='{"id":"req-1","created":1700000000,"deadline":1999999999,"payload":{"model":"Qwen/Qwen3-32B","prompt":"Summarize TPU v7x"}}'
# ==============================================================================
# C. Layer Stateful /v1/responses (vllm/agentic-api + PostgreSQL 17) onto Any vLLM Guide
# ==============================================================================
export NAMESPACE=llm-d-pd-disaggregation
export LLM_API_BASE=pd-disaggregation-epp.${NAMESPACE}.svc.cluster.local:80
PGPASS=$(openssl rand -hex 16)
kubectl create secret generic agentic-api-postgres -n ${NAMESPACE} \
--from-literal=password="${PGPASS}" \
--from-literal=database-url="postgres://postgres:${PGPASS}@agentic-api-postgres:5432/agentic_api"
kubectl apply -n ${NAMESPACE} -f ${REPO_ROOT}/guides/agentic-api/manifests/postgres.yaml
kubectl kustomize ${REPO_ROOT}/guides/agentic-api/manifests/base | envsubst '${LLM_API_BASE}' | kubectl apply -n ${NAMESPACE} -f -
# Run End-to-End 4-Stage Mechanism Verification (Health, Stateful previous_response_id, Webhook Tool Loop, RFC 6455 WebSocket):
kubectl port-forward -n ${NAMESPACE} svc/agentic-api 9000:9000 &
python3 ${REPO_ROOT}/guides/agentic-api/verify.py --base-url http://127.0.0.1:9000
3.5.4 Day-2 operations: startup acceleration, fast actuation and zero-downtime rollouts¶
Overview: Operating 400B–750B models in production requires accelerating multi-hundred-gigabyte pod cold starts, scaling replicas on KV-cache and SLO saturation signals rather than CPU/GPU utilization, and executing rollouts without dropping streaming completions or corrupting disaggregated KV transfers.
References: Load and Cache Model Weights, Transfer Weights Peer-to-Peer (ModelExpress), Restore from Pod Snapshots, Reuse Warm Model Servers (FMA), Blue-Green Update, Safe Rollouts of Disaggregated Deployments with DisaggregatedSet, LoRA Adapter Rollout, Graceful Shutdown & Request Draining, vLLM Model-Aware Readiness Probes.
Startup acceleration, fast actuation and rollout safeguards¶
| Operational Pillar | llm-d / Kubernetes Mechanism |
Critical Flags, Annotations & Parameters | Bottleneck Eliminated / Failure Prevented |
|---|---|---|---|
| 1. Model Weight & JIT Cache Reuse | gke-model-cache-hostpath (/var/cache/huggingface) or RWX model-pvc + VLLM_CACHE_ROOT / VLLM_XLA_CACHE_PATH |
Mount HF_HOME to node SSD or RWX PVC; persist XLA & Torch compile caches (VLLM_XLA_CACHE_PATH, VLLM_CACHE_ROOT, TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT); use HF_ENDPOINT for self-hosted MatrixHub. |
Eliminates 400–750 GB Hugging Face weight re-downloads and 10–25 minute cold XLA compilations on pod restart. |
2. P2P Weight Streaming (ModelExpress) |
guides/modelexpress-p2p (--load-format=mx) |
1 seed replica loads checkpoint from storage; scale-out peers stream weights directly from seed HBM over NIXL/RDMA (--load-format=mx). |
Avoids shared filesystem/GCS bandwidth bottlenecks when scaling out 8–64 replicas simultaneously. |
| 3. Pod Snapshots & Fast Model Actuation (FMA) | GKE Pod Snapshots (guides/pod-snapshot) & FMA Sleep/Wake (guides/fast-model-actuation, -keda) |
Pod Snapshot: Restores checkpointed GPU/CPU process state. FMA: Keeps resident sleeping model servers + KEDA scale-from-zero on EPP flow-control queue metrics. |
Cuts scale-out readiness from minutes to seconds while reclaiming idle accelerator cost. The llm-d guides describe pod snapshots, FMA and ModelExpress for GPUs only; on TPU, rely on weight and compile caches (chapter 21). |
| 4. Blue-Green & Safe P/D Rollouts | Dual InferencePools (HTTPRoute weights) or DisaggregatedSet (lws v0.11.1+) |
Use HTTPRoute backendRefs.weight (100/0 -> 90/10 -> 0/100) for incompatible KV/TP changes; use DisaggregatedSet coordinated P/D rolling updates for compatible changes. |
Prevents a v1 Prefill pod from DMA-transferring an incompatible KV layout into a v2 Decode pod. |
| 5. Dynamic LoRA Hot-Reloading | VLLM_ALLOW_RUNTIME_LORA_UPDATING=true + lora_filesystem_resolver + InferenceModelRewrite |
Drop adapter into /mnt/shared-loras; vLLM auto-loads without restart; shift traffic weights via InferenceModelRewrite. |
Zero pod restarts or XLA recompilations when rolling out fine-tuned LoRA adapters. |
| 6. Graceful Drain & Compilation-Safe Probes | lifecycle.preStop (sleep 30) + --shutdown-timeout=240 + startupProbe (/v1/models) |
terminationGracePeriodSeconds: 300 (\(\ge 30\text{s} + 240\text{s} + 30\text{s}\)); startupProbe failureThreshold: 180, periodSeconds: 10 (30m window). |
Prevents 502 Bad Gateway during scale-down and stops Kubelet from SIGKILL-looping TPU pods during initial XLA compilation. |
Recipe 2: production pod spec (Compilation-Safe Probes, Graceful Drain, Weight/XLA Cache & LoRA Hot-Reload)¶
containers:
- name: modelserver
image: vllm/vllm-torchtpu:v0.29.0
env:
- {name: LD_PRELOAD, value: "/usr/lib/x86_64-linux-gnu/libtcmalloc_minimal.so.4"}
- {name: HF_HOME, value: "/var/cache/huggingface"}
- {name: VLLM_XLA_CACHE_PATH, value: "/var/cache/vllm-xla"}
- {name: TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT, value: "/var/cache/torch-tpu"}
- {name: VLLM_ALLOW_RUNTIME_LORA_UPDATING, value: "true"}
- {name: VLLM_PLUGINS, value: "lora_filesystem_resolver"}
- {name: VLLM_LORA_RESOLVER_CACHE_DIR, value: "/mnt/shared-loras"}
args:
- serve
- Qwen/Qwen3-32B
- --tensor-parallel-size=8
- --enable-lora
- --max-loras=16
- --shutdown-timeout=240 # Drain in-flight streaming requests for up to 240s after SIGTERM
- --port=8000
lifecycle:
preStop:
exec: {command: ["/bin/sh", "-c", "sleep 30"]} # Let EndpointSlice & EPP deregister pod before SIGTERM
startupProbe:
httpGet: {path: /v1/models, port: 8000} # Marks Started ONLY after weights load & XLA warmup completes
periodSeconds: 10
failureThreshold: 180 # 180 * 10s = 30m cold XLA compile & weight load budget
readinessProbe:
httpGet: {path: /v1/models, port: 8000} # /health returns 200 before the model is loaded
periodSeconds: 5
failureThreshold: 3
livenessProbe:
httpGet: {path: /health, port: 8000}
periodSeconds: 15
failureThreshold: 4
terminationGracePeriodSeconds: 300 # MUST be >= preStop (30s) + --shutdown-timeout (240s) + 30s buffer.
The readiness probe uses /v1/models: llm-d's readiness probe guide says vLLM's /health "only indicates that the server process is running, not that models are loaded", so a /health readiness probe admits traffic to a pod that is still loading; keep /health for liveness. The persistent compile cache root is TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT. The drain values above keep the grace period longer than preStop plus --shutdown-timeout; the llm-d TPU overlays ship a 15 s preStop, --shutdown-timeout=45 and a 75 s grace period, and P/D prefill pods use a longer drain (Graceful Shutdown & Request Draining, chapter 21).
3.6 Model blueprints (well-lit paths and recipes)¶
Overview: Frontier 2026 architectures (671B–1T+ Sparse MoEs, Multi-head Latent Attention [MLA], Hybrid Linear/Gated-DeltaNet/Mamba-2 + Full Attention, and Multi-Token Prediction [MTP]) require co-designing parallelism topology (DP, TP, EP, PCP, P/D Split), quantization (FP8, W4A8), custom TPU Pallas/Megakernel ops, and Host DRAM/NVMe/Lustre KV cache tiering to saturate TPU v7x (Ironwood) 192 GiB HBM3e and GPU NVL72/H200 clusters.
Models across TPU v7x / v6e and GPU well-lit paths¶
References: llm-d: DeepSeek-V4, llm-d: GLM-5.2, llm-d: Qwen3.5-397B, llm-d: NVIDIA Nemotron 3 Ultra, vLLM-TorchTPU: TPU v7x (Ironwood) Serving Recipes, SGLang‑TorchTPU: PyTorch‑Native Production Serving on TPUs, SGLang-TorchTPU Kimi-K3 cookbook, SGLang-TorchTPU TPU serving recipes.
| Model Family & Checkpoint | Architecture & Active Params | Primary TPU Topology (v7x / v6e) |
Primary GPU / Alternative Topology | Quantization & KV Cache Dtype | Key Custom Kernel / Connector / SpecDecode | Benchmarked Production Throughput / Latency |
|---|---|---|---|---|---|---|
| DeepSeek-V4-Pro / Flash ( deepseek-ai/DeepSeek-V4-Pro) |
MLA + 256-Expert MoE (671B total, 37B active) + DSA Indexer | TPU v7x: v7x-8 (DP=8, TP=1+EP Flash) or v7x-16 (2x2x2, DP=16, TP=1+EP Pro-0813) |
GB200 NVL72: 9 P/D presets (oci-low-latency 16 GPUs 1P DEP8:1D TP8 to oci-3p2d-dep8-dep16 56 GPUs) |
deepseek_v4_fp8 or W4A8 (MOE_FUSED_EP_ENABLE_W4A8=1) + fp8 KV (--block-size 256) |
TPU USE_MOE_FUSED_EP_KERNEL=1 (fused EP v2); GB200 deep_gemm_mega_moe + --data-parallel-hybrid-lb + NixlConnector |
GB200 peakPrefillThroughput: 20000 |
| GLM-5.2-FP8 & GLM-5.3-Flash ( zai-org/GLM-5.2-FP8, THUDM/glm-5.3-flash) |
753B Sparse MoE (756 GB FP8) + MLA + mHC + MTP=3 |
TPU v7x: tpu7x-2x2x2-dp16 (2x2x2 = 2 hosts \(\times\) 4 chips = 16 TCs: DP=16, TP=1, EP, 32K len) |
H200 (64 GPUs): p3w2d1w2 (3x DEP16 P + 1x DEP16 D) on vLLM & SGLang (HiCache + Mooncake) |
FP8 (W8A8) + fp8 KV cache |
TPU glm_flash_megakernel; H200 offloading-tiered (1500Gi /dev/shm + NVMe kv-cache-evictor) + MTP=3 |
2.9x output tok/s (951 -> 2,776 tok/s at conc 128) & -32% TTFT w/ CPU offload; 1.6–2.0x w/ MTP |
| Qwen3.5-397B-A17B-FP8 & Qwen3.8 ( Qwen/Qwen3.5-397B-A17B-FP8) |
397B MoE (17B active, 406 GB FP8), 60L (3:1 Gated-DeltaNet + Full GQA) | TPU v7x (2x2x1, 4 chips = 8 TCs): unified (2x DP=8, EP) OR disaggregated (1P PCP=8 \(\to\) 1D DP=8) |
B200 / H200: TP=8, EP=8 |
FP8 + auto (bf16) hybrid state/KV (262,144 context) |
--block-size 4352 + TPURaidenOffloadingConnector (256 GiB DRAM/pod) + TPURaidenConnector + MTP=3 |
peakPrefillThroughput: 16444 (a proxy carried over from Qwen3-Coder-480B-FP8 until this model is calibrated); full 262K context |
| NVIDIA-Nemotron-3-Ultra-550B ( RedHatAI/...-550B-A55B-FP8-block) |
550B Total (55B active): NemotronHForCausalLM Mamba-Hybrid |
TPU v7x: 2x2x4 (16 chips) |
H200 (64 GPUs, 8 nodes): DisaggregatedSet 6P:2D (6x Prefill TP=8, EP + 2x Decode TP=8, EP) |
Block FP8 |
200 GiB/pod CPU KV Offload (~1.6 TB total) + VLLM_PREFIX_CACHE_RETENTION_INTERVAL=0 + NixlConnector |
At 60 coding sessions (160K ISL): -58% P50 TTFT (49.5s -> 20.5s) & +92% output tok/s (484 -> 929 tok/s) |
| Kimi-K2.5 / K2.6 / K3 ( moonshotai/Kimi-K3) |
1T+ MoE: Hybrid KDA (Kimi Delta Attention) + MLA + MoonViT | TPU v7x-32 (2x2x4, 16 chips, 32 devices): TP=32 + EP=32 or Disagg 1P1D (4DP x 8TP) |
H200: 2x 8-GPU nodes (PP=2, TP=8 or Wide-EP) |
FP8 / INT4 (compressed-tensors) |
SGLang k3_megakernel + Static FP8 GEMV + Fused KDA recurrent state kernel |
One request: decode megakernel about 2x faster TPOT than the default path, about 4–5.5x with DSpark |
| Muse Glimmer 30B | 30B: 52L Interleaved 3:1 SWA (2048) / Full Attention | TPU v7x: 1 device (case study, StaticCache) |
n/a | bfloat16 |
torch.compile(dynamic=False) + StaticCache |
23.58 ms/tok (1 device, average of decode steps 2 to 20) |
| Muse Spark Open ( Muse-Spark-Open-816B-A42B-NVFP4) |
816B MoE (42B active) | TPU7x: 1 host, TP=8 (SGLang-TorchTPU muse_spark recipe) |
n/a | NVFP4 |
SGLang muse_megakernel + DFlash2 draft |
n/a |
Llama 3.1 / 3.3 (8B, 70B) |
Dense GQA | TPU v6e-8: TP=8 (Llama-3.3-70B-Instruct, fp8 KV) |
n/a | bf16 / fp8 KV |
EAGLE-3 drafter for Llama-3.1-8B-Instruct (yuhuili/EAGLE3-LLaMA3.1-Instruct-8B) |
n/a |
Gemma 4 (31B-it, 26B-A4B-it) |
Multimodal Hybrid 5:1 Sliding Window + Global Attention | TPU v7x-8: TP=2, DP=4 (RedHatAI/gemma-4-31B-it-FP8-Dynamic); llm-d multimodal-serving/aggregation/modelserver/tpu/v7/vllm/gemma4/ |
n/a | compressed-tensors FP8 |
Native multimodal audio/image/video processor + --reasoning-parser gemma4 |
n/a |
Muse Glimmer 30B's Config uses a 2,048-token sliding window, and 23.58 ms per token is the case study's single-device StaticCache average (chapter 22). Muse Spark Open is a different model: SGLang-TorchTPU's muse_spark recipe serves Muse-Spark-Open-816B-A42B-NVFP4 on one TPU7x host. DeepSeek-V4-Pro-0813 runs on a 2x2x2 v7x-16 slice with USE_MOE_FUSED_EP_KERNEL=1 (vLLM-TorchTPU v7x recipes).
3.6.1 Blueprint 1: DeepSeek-V4-Pro / Flash (TPU v7x W4A8 Fused EP v2 & GB200 NVL72 ComputeDomain)¶
Overview: DeepSeek-V4-Pro and DeepSeek-V4-Flash combine Multi-head Latent Attention (MLA) with 256 routed experts:
- On TPU v7x (vLLM-TorchTPU v7x recipes): Attention runs Data-Parallel (
DP=8onv7x-8forFlash;DP=16onv7x-162x2x2forPro-0813) withTP=1, EP=Trueand Pallas Fused EP v2 + W4A8 (USE_MOE_FUSED_EP_KERNEL=1,MOE_FUSED_EP_ENABLE_W4A8=1) to avoid duplicating MLA KV cache across TP ranks. - On NVIDIA GB200 NVL72 (llm-d: DeepSeek-V4): Deployed as a P/D
DisaggregatedSetacross 4-GPUBM.GPU.GB200.4nodes joined by an NVIDIA DRAComputeDomain(resource.nvidia.com/v1beta1) for multi-node NVLink fabric, using--data-parallel-hybrid-lb,--all2all-backend=deep_gemm_mega_moe,NixlConnector, FP8 KV cache (--block-size 256,--max-model-len 9280), and 9DEPLOYMENTpresets ranging fromoci-low-latency(16 GPUs:1P DEP8 : 1D TP8) up tooci-3p2d-dep8-dep16-flashinfer(56 GPUs, 14 nodes).
# ==============================================================================
# A. Standalone TPU v7x (v7x-8 DP=8 Flash OR v7x-16 DP=16 Pro-0813) w/ W4A8 Fused EP v2
# ==============================================================================
export MOE_REQUANTIZE_WEIGHT_DTYPE=fp4
export MOE_REQUANTIZE_BLOCK_SIZE=512
export TPU_ROPE_CACHE_ROW_MAJOR=1
export TPU_MOE_HASH_TABLE_ROW_MAJOR=1
export USE_MOE_FUSED_EP_KERNEL=1
export MOE_FUSED_EP_ENABLE_W4A8=1
export MOE_FUSED_EP_V2_HEIGHT_RUNGS_OVERRIDE=2
export TPU_MOE_SKIP_PADDED_TOKENS=1
export RAGGED_GATHER_REDUCE_VERSION=v3
export LIBTPU_INIT_ARGS="--xla_tpu_use_minor_sharding_for_major_trivial_input=true --xla_tpu_enable_sparse_core_collective_offload_reduce_scatter=false --xla_tpu_ars_combiner_threshold_in_bytes=0 --xla_tpu_enable_async_collective_merger=false --xla_enable_async_all_gather=true --xla_tpu_enable_sparse_core_collective_offload_all_gather=true --xla_tpu_sparse_core_all_gather_offload_min_size_in_bytes=262144"
# Run on both hosts with the multi-host flags (mp mode B for DP=16), or TPU_MULTIHOST_BACKEND=ray
vllm serve deepseek-ai/DeepSeek-V4-Pro-0813 \
--tensor-parallel-size 1 \
--data-parallel-size 16 \
--enable-expert-parallel \
--enable-ep-weight-filter \
--safetensors-load-strategy prefetch \
--quantization deepseek_v4_fp8 \
--kv-cache-dtype fp8_e4m3 \
--trust-remote-code \
--max-model-len 9216 \
--max-num-batched-tokens 1024 \
--max-num-seqs 256 \
--no-enable-prefix-caching \
--gpu-memory-utilization 0.90 \
--async-scheduling \
--port 8000
# ==============================================================================
# B. llm-d Well-Lit Path on GB200 NVL72 (9 Presets: oci-low-latency .. oci-3p2d-dep8-dep16-flashinfer)
# ==============================================================================
export GUIDE_NAME=models/deepseek-v4
export NAMESPACE=llm-d-deepseek-v4
export DEPLOYMENT=oci-low-latency # Or: oci (32 GPUs 1P1D DEP16) | oci-2p1d-dep8-dep16 (32 GPUs) | oci-3p2d-dep8-dep16-flashinfer (56 GPUs)
source ${REPO_ROOT}/guides/env.sh
helm install deepseek-v4 ${ROUTER_STANDALONE_CHART} \
-f ${REPO_ROOT}/guides/recipes/router/base.values.yaml \
-f ${REPO_ROOT}/guides/${GUIDE_NAME}/router/deepseek-v4.values.yaml \
-n ${NAMESPACE} --version ${ROUTER_CHART_VERSION}
kubectl apply -n ${NAMESPACE} -k ${REPO_ROOT}/guides/${GUIDE_NAME}/modelserver/gpu/vllm/${DEPLOYMENT}/
Part A is the vLLM-TorchTPU v7x recipe for DeepSeek-V4-Pro-0813 without its generation-config overrides (vLLM-TorchTPU v7x recipes). llm-d's DeepSeek-V4 guide is GPU only (GB200); for a large MoE with EP on TPU7x, llm-d points to the Qwen3.5-397B or GLM-5.2 recipes (llm-d model recipes).
3.6.2 Blueprint 2: GLM-5.2-FP8 (753B MoE) & GLM-5.3-Flash (TPU v7x 2x2x2 DP16 & H200 Tiered KV + MTP=3)¶
Overview: zai-org/GLM-5.2-FP8 (756 GB FP8 checkpoint) ships with validated llm-d recipes on both Google TPU v7x and NVIDIA H200 (llm-d: GLM-5.2):
- Google TPU v7x (
ACCELERATOR_TYPE=tpu,DEPLOYMENT=tpu7x-2x2x2-dp16): Runs 1 aggregatedLeaderWorkerSet(size: 2) on a 2-host2x2x2TPU7x slice (4 chips = 8 TensorCores/host, 16 TensorCores total,>= 1.5 TBboot disk for/var/cache/huggingface) with--data-parallel-size 16 --tensor-parallel-size 1 --enable-expert-parallel,fp8KV cache, and--max-model-len 32768behindrouter/glm-5-2-tpu.values.yaml(single-profile-handler). - NVIDIA H200 (
ACCELERATOR_TYPE=gpu,vllm&sglang): Defaultp3w2d1w2(3x DEP16prefill +1x DEP16decode = 8 nodes / 64 GPUs) uses--data-parallel-multi-port-external-lb(exposing all 8 DP rank ports8000..8007onInferencePool),deepep_high_throughput(prefill) /deepep_low_latencywithIBGDA + NVSHMEM(decode),offloading-tiered(1500Gi/dev/shmCPU +/mnt/local/kv-cacheNVMe withkv-cache-evictorDaemonSet 90% \(\to\) 70%), andMTP=3. On SemiAnalysiscc-traces-weka(~195K median ISL), CPU offloading delivers 2.9x higher output tok/s at concurrency 128 (951 -> 2,776 tok/s) and -32% median TTFT; MTP delivers 1.6–2.0x output tok/s;ROUTING=precise(p2w1d1w1-precise) adds awide-ep-renderService and 8 ZMQ subscriptions (5557..5564) per pod.
# ==============================================================================
# A. Deploy GLM-5.2-FP8 on Google TPU v7x (2x2x2 Slice = 2 Hosts x 4 Chips = 16 TensorCores, DP=16+EP)
# ==============================================================================
export GUIDE_NAME=models/glm-5-2
export NAMESPACE=llm-d-glm-5-2
export ACCELERATOR_TYPE=tpu
export MODEL_SERVER=vllm
export DEPLOYMENT=tpu7x-2x2x2-dp16
source ${REPO_ROOT}/guides/env.sh
# 1. Deploy Router with TPU single-profile values (router/glm-5-2-tpu.values.yaml)
helm install glm-5-2 ${ROUTER_STANDALONE_CHART} \
-f ${REPO_ROOT}/guides/recipes/router/base.values.yaml \
-f ${REPO_ROOT}/guides/${GUIDE_NAME}/router/glm-5-2-tpu.values.yaml \
-n ${NAMESPACE} --version ${ROUTER_CHART_VERSION}
# 2. Deploy 2-Host TPU v7x LeaderWorkerSet (DP=16, TP=1, EP, fp8 KV, 32768 context)
kubectl apply -n ${NAMESPACE} -k ${REPO_ROOT}/guides/${GUIDE_NAME}/modelserver/tpu/vllm/deployments/${DEPLOYMENT}
# ==============================================================================
# B. Deploy GLM-5.2-FP8 on H200 (p3w2d1w2 = 64 GPUs, Tiered DRAM+NVMe KV Offload, MTP=3)
# ==============================================================================
export ACCELERATOR_TYPE=gpu
export DEPLOYMENT=p3w2d1w2 # Or: p2w1d1w1-precise (with ROUTING=precise & wide-ep-render)
export KV_OFFLOAD=offloading-tiered # Options: none, offloading-cpu (1500Gi /dev/shm), offloading-tiered (+NVMe evictor)
export SPEC_DECODING=mtp-3 # Options: none, mtp-3, mtp-5 (vLLM) | mtp-3-s4d4 (SGLang)
helm install glm-5-2 ${ROUTER_STANDALONE_CHART} \
-f ${REPO_ROOT}/guides/recipes/router/base.values.yaml \
-f ${REPO_ROOT}/guides/${GUIDE_NAME}/router/glm-5-2.values.yaml \
-n ${NAMESPACE} --version ${ROUTER_CHART_VERSION}
# Enable KV offloading & MTP components in kustomization.yaml and apply:
kubectl apply -n ${NAMESPACE} -k ${REPO_ROOT}/guides/${GUIDE_NAME}/modelserver/gpu/${MODEL_SERVER}/${DEPLOYMENT}/
# ==============================================================================
# C. Single-Host TPU v7x (4 Chips): GLM-5.3-Flash with SGLang Whole-Decoder Megakernel
# ==============================================================================
# Run from the sglang-torchtpu repository root; the recipe sets SGLANG_TPU_GLM_FLASH_MEGAKERNEL=1
# on top of the base GLM-5.3-Flash recipe (tp8 = 4 chips x 2 cores, one request at a time).
python3 -m benchmark.tpu.launch_server --config recipe/configs/glm_5_3_flash/server_mk.py --dry-run # print flags
python3 -m benchmark.tpu.launch_server --config recipe/configs/glm_5_3_flash/server_mk.py
Part A's model-server path follows the llm-d GLM-5.2 recipe (modelserver/tpu/vllm/deployments/${DEPLOYMENT}). Part C uses SGLang-TorchTPU's own recipe launcher, as the SGLang-TorchTPU quickstart does: the GLM-5.3-Flash megakernel recipe sets SGLANG_TPU_GLM_FLASH_MEGAKERNEL=1 and runs at tp_size 8 on one TPU7x host, and recipe/configs/glm_5_3_flash/mtp_mk.py is its speculative variant.
3.6.3 Blueprint 3: Qwen3.5-397B-A17B-FP8 & Qwen3.8 (TPU v7x 262K Context, block-size=4352, Unified vs Disaggregated PCP=8 -> DP=8)¶
Overview: Qwen/Qwen3.5-397B-A17B-FP8 (406 GB FP8 checkpoint, 60-layer 3:1 Hybrid Gated-DeltaNet Linear + Full GQA architecture) is the agentic coding model of the llm-d guides on Google TPU v7x (2x2x1 = 4 chips = 8 TensorCores/node, \(\ge 1\text{ TB}\) boot disk) (llm-d: Qwen3.5-397B), supporting two production topologies behind router/qwen3-5-397b.values.yaml (blockSizeTokens: 4352, peakPrefillThroughput: 16444):
TOPOLOGY=unified(Default): 2 replicas \(\times\)2x2x1(DP=8, TP=1, EP),262,144context,--block-size 4352,TPURaidenOffloadingConnector(32 GiB/DP rank =256 GiBpinned host DRAM/pod),MTP=3(qwen3_next_mtp), and--tool-call-parser=qwen3_xml.TOPOLOGY=disaggregated:DisaggregatedSet(pd-disagg-tpu) with 1 Prefill slice (PCP=8Prefill Context Parallelism, EP,64 GiBhost KV offload,MTP=1to warm the MTP draft KV cache) + 1 Decode slice (DP=8, EP,MTP=3draft tokens) connected overTPURaidenConnector(scalable toxPyDviakubectl patch disaggregatedset/pd-disagg-tpu).
Prefill and decode run on separate TPU7x hosts with different layouts, PCP=8 and DP=8, and TPU Sync moves the KV cache between them. Only the prefill pod keeps a host-DRAM KV tier.
# ==============================================================================
# A. Deploy Qwen3.5-397B-A17B-FP8 on GKE TPU v7x via llm-d (Unified OR Disaggregated)
# ==============================================================================
export GUIDE_NAME=qwen3-5-397b
export NAMESPACE=llm-d-qwen3-5-397b
export ACCELERATOR_TYPE=tpu
export MODEL_SERVER=vllm
export TOPOLOGY=unified # Options: unified (2x 2x2x1 DP=8) | disaggregated (1P PCP=8 + 1D DP=8, experimental)
source ${REPO_ROOT}/guides/env.sh
# 1. Select Router Values (disaggregated: router/${GUIDE_NAME}-disagg.values.yaml)
export ROUTER_VALUES="${REPO_ROOT}/guides/models/${GUIDE_NAME}/router/${GUIDE_NAME}.values.yaml"
[ "${TOPOLOGY}" = "disaggregated" ] && export ROUTER_VALUES="${REPO_ROOT}/guides/models/${GUIDE_NAME}/router/${GUIDE_NAME}-disagg.values.yaml"
helm install ${GUIDE_NAME} ${ROUTER_STANDALONE_CHART} \
-f ${REPO_ROOT}/guides/recipes/router/base.values.yaml \
-f ${ROUTER_VALUES} -n ${NAMESPACE} --version ${ROUTER_CHART_VERSION}
# 2. Deploy Model Server Overlay (unified Deployment OR disaggregated DisaggregatedSet)
if [ "${TOPOLOGY}" = "disaggregated" ]; then
kubectl apply -n ${NAMESPACE} -k ${REPO_ROOT}/guides/models/${GUIDE_NAME}/modelserver/${ACCELERATOR_TYPE}/${MODEL_SERVER}-disaggregated/
else
kubectl apply -n ${NAMESPACE} -k ${REPO_ROOT}/guides/models/${GUIDE_NAME}/modelserver/${ACCELERATOR_TYPE}/${MODEL_SERVER}/
fi
# 3. Scale Disaggregated Prefill / Decode Independently to xPyD (role 0 prefill, role 1 decode):
kubectl patch disaggregatedset/pd-disagg-tpu -n ${NAMESPACE} --type=json \
-p '[{"op": "replace", "path": "/spec/roles/0/spec/replicas", "value": 2},
{"op": "replace", "path": "/spec/roles/1/spec/replicas", "value": 1}]'
The commands follow the llm-d Qwen3.5-397B recipe as the llm-d model recipes guide gives it: the disaggregated router values are ${GUIDE_NAME}-disagg.values.yaml, the overlays are modelserver/tpu/vllm/ and modelserver/tpu/vllm-disaggregated/, and the replica patch path is /spec/roles/N/spec/replicas, matching the DisaggregatedSet v1 schema. The guide states the server parameters (262,144-token context, fp8 KV, 4,352-token blocks, a 32 GiB host tier per DP engine, 3 MTP draft tokens); read the overlay's manifest for the exact vllm serve arguments. It publishes no TorchTPU results for this model yet; the earlier Qwen3-Coder-480B results were on the JAX tpu_inference backend (chapter 20).
3.6.4 Blueprint 4: NVIDIA-Nemotron-3-Ultra-550B (Mamba-Hybrid 6P:2D DisaggregatedSet + 1.6 TB CPU KV Offload)¶
Overview: RedHatAI/NVIDIA-Nemotron-3-Ultra-550B-A55B-FP8-block (NemotronHForCausalLM, 550B total / 55B active Mamba-2 + Attention + MoE hybrid) runs on 8 H200 nodes (64 GPUs) as a DisaggregatedSet (pd-disagg-vllm) with 6 Prefill replicas (TP=8, EP) + 2 Decode replicas (TP=8, EP), 200 GiB/replica CPU KV offloading (~1.6 TB total), and VLLM_PREFIX_CACHE_RETENTION_INTERVAL=0 (because Mamba state checkpoints are non-sliceable, so zero retention delay prevents evicting reusable prefix states before agentic turns return). Across 60 concurrent coding sessions (160K mean dynamic system prompt, 540 mean turns), 6P:2D cuts P50 TTFT by 58% (49,462 ms -> 20,543 ms) and boosts output tokens/sec by 92% (484 -> 929 tok/s) over aggregated serving (llm-d: NVIDIA Nemotron 3 Ultra).
# ==============================================================================
# 1. Deploy Nemotron-3-Ultra-550B 6P:2D DisaggregatedSet on 8x H200 Nodes (64 GPUs)
# ==============================================================================
export GUIDE_NAME=models/nemotron-3-ultra
export NAMESPACE=llm-d-nemotron-3-ultra
export INFRA_PROVIDER=gke # Options: base, gke, coreweave
source ${REPO_ROOT}/guides/env.sh
helm install nemotron-3-ultra ${ROUTER_STANDALONE_CHART} \
-f ${REPO_ROOT}/guides/recipes/router/base.values.yaml \
-f ${REPO_ROOT}/guides/${GUIDE_NAME}/router/nemotron-3-ultra.values.yaml \
-n ${NAMESPACE} --version ${ROUTER_CHART_VERSION}
kubectl apply -n ${NAMESPACE} -k ${REPO_ROOT}/guides/${GUIDE_NAME}/modelserver/gpu/vllm/${INFRA_PROVIDER}/
# ==============================================================================
# 2. Underlying vLLM Flags in patch-prefill.yaml (6 Replicas) & patch-decode.yaml (2 Replicas)
# ==============================================================================
export VLLM_PREFIX_CACHE_RETENTION_INTERVAL=0
vllm serve RedHatAI/NVIDIA-Nemotron-3-Ultra-550B-A55B-FP8-block \
--tensor-parallel-size 8 --enable-expert-parallel --enable-prefix-caching \
--kv-offloading-size 200 --kv-offloading-backend native \
--kv-transfer-config '{"kv_connector":"NixlConnector","kv_role":"kv_both"}' \
--enable-auto-tool-choice --tool-call-parser qwen3_coder --reasoning-parser nemotron_v3 \
--max-model-len 262144 --port 8000
3.6.5 Blueprint 5: Kimi-K2.5 / K2.6 / K3, Muse Spark Open, Llama 3.1/3.3 and Gemma 4¶
Overview: Kimi-K3 combines Kimi Delta Attention (KDA) + MLA + MoonViT across v7x-32 (TP=32 + EP) or SGLang's k3_megakernel, Muse Spark Open (816B-A42B NVFP4, not Muse Glimmer 30B) has a muse_megakernel agentic recipe, Llama 3.1/3.3 runs on v6e-8 at TP=8 and takes EAGLE-3 drafters, and Gemma 4 (31B-it & 26B-A4B-it) serves native multimodal reasoning with 5:1 hybrid sliding-window attention.
References: SGLang‑TorchTPU: PyTorch‑Native Production Serving on TPUs, SGLang-TorchTPU TPU serving recipes, vLLM-TorchTPU: TPU v7x (Ironwood) Serving Recipes, vLLM-TorchTPU: Speculative Decoding, llm-d: Serve Multimodal Models.
# ==============================================================================
# 1. Kimi-K3 (Hybrid KDA + MLA + MoonViT) on TPU v7x-32 (2x2x4 = 16 chips, 32 devices)
# ==============================================================================
# SGLang-TorchTPU recipe (four TPU7x hosts, tp32); run from the sglang-torchtpu repository root on every
# host of the slice (multi-host recipes run as JobSet launch groups; see benchmark/tpu/recipe/README.md).
# server_mk.py adds the decode megakernel (SGLANG_TPU_ENABLE_K3_DECODE_MEGAKERNEL=1, batch 1, no radix cache).
python3 -m benchmark.tpu.launch_server --config recipe/configs/kimi_k3/server.py # serving
python3 -m benchmark.tpu.launch_server --config recipe/configs/kimi_k3/server_mk.py # megakernel
# ==============================================================================
# 2. Muse Spark Open (816B-A42B NVFP4, hybrid SWA, muse_megakernel in the agentic recipe) on 1x v7x Host
# ==============================================================================
python3 -m benchmark.tpu.launch_server --config recipe/configs/muse_spark/server.py # tp8 = 4 chips x 2 cores
# ==============================================================================
# 3. Gemma 4 (RedHatAI/gemma-4-31B-it-FP8-Dynamic) on TPU v7x-8: TP=2, DP=4
# ==============================================================================
vllm serve RedHatAI/gemma-4-31B-it-FP8-Dynamic \
--tensor-parallel-size 2 --data-parallel-size 4 \
--max-num-seqs 128 --gpu-memory-utilization 0.90 \
--attention-backend CUSTOM --block-size 256 --port 8000
Parts 1 and 2 use SGLang-TorchTPU's recipe launcher. The Kimi-K3 megakernel recipe sets SGLANG_TPU_ENABLE_K3_DECODE_MEGAKERNEL=1 and runs on 4 hosts; the Muse Spark agentic recipe sets SGLANG_TPU_MUSE_MEGAKERNEL=1. The Muse Spark recipes serve meta-models/Muse-Spark-Open-816B-A42B-NVFP4 at TP=8 on one host; it is not Muse Glimmer 30B (chapter 19, chapter 22).
Part 3 is the vLLM-TorchTPU v7x benchmark configuration for Gemma 4 (gemma-4-31b-fp8-dp4-tp2-multimodal.sh, which adds multimodal processor and encoder options). The supported-models page validates RedHatAI/gemma-4-31B-it-FP8-Dynamic and RedHatAI/gemma-4-26B-A4B-it-FP8-Dynamic and lists google/gemma-4-31B-it as experimental. For multi-host Ray, vLLM-TorchTPU uses TPU_MULTIHOST_BACKEND=ray rather than --distributed-executor-backend ray (Serve across several TPU hosts, vLLM-TorchTPU v7x recipes).










