Skip to main content

vLLM-TorchTPU Tutorial: Serving a Small LLM on a Cloud TPU

Learn how to serve a small open-weight LLM on a Google Cloud TPU with vLLM-TorchTPU, build a ticket priority sorting app on top of it, and measure how startup and prompt length affect latency.
· 15 min read

Explore with AI

Can you serve an LLM on a TPU with the same vllm serve command you use on a GPU? Yes. vLLM-TorchTPU is a PyTorch-native TPU backend for vLLM, announced alongside TorchTPU, Google's open-source PyTorch backend for Cloud TPUs. It runs the model definitions that already live in vLLM, so most models that work with vLLM can be served on a TPU without changes to the model code.

In a Nutshell

vLLM-TorchTPU is a plugin that lets the standard vllm serve command and OpenAI-compatible API run on Cloud TPUs. In our tests on a Colab TPU v5e-1 serving Qwen3-1.7B, the server took 192.2 seconds to become ready on a cold start and 67.1 seconds after two restarts with a saved compile cache. With prefix caching off, time to first token (TTFT) grew about 5.3x as prompts grew from 143 to 2,677 tokens. With it on, TTFT stayed between 15.1 and 20.7 ms.

In this tutorial, we'll serve Qwen3-1.7B from Hugging Face on a single-chip Colab TPU and build a small support ticket priority sorting app that talks to it through the OpenAI-compatible API. We'll then use the same server to explore:

  • What changes between a cold start and a warm start of the server?
  • How does TTFT change as the prompt gets longer, with and without prefix caching?

By the end of this tutorial, you'll know how to:

  • Install vLLM-TorchTPU on a Colab TPU runtime.
  • Start an OpenAI-compatible vLLM server on a TPU and send it requests.
  • Build a ticket priority sorting app with structured JSON output and a Gradio UI.
  • Keep the TPU compile cache between restarts and measure its effect.
  • Measure time to first token and decode speed across prompt lengths.
  • Interpret the effect of prefix caching on your measurements.

You can run the complete code in this Google Colab notebook. If you are new to vLLM or Colab, our vLLM tutorial and Google Colab guide are good starting points.

What Is vLLM-TorchTPU?

The vllm-torchtpu package is an out-of-tree vLLM platform plugin. Once installed, vLLM finds it automatically through its vllm.platform_plugins entry point, so you use the same vllm serve command, scheduler, KV cache manager, and OpenAI-compatible API server as on a GPU.

Under the hood, it runs vLLM's standard PyTorch model definitions on TPUs through TorchTPU, compiled with torch.compile(backend="tpu"), which lowers to XLA. Custom JAX and Pallas kernels handle the heavy operations, such as attention, Mixture-of-Experts (MoE), and quantized matrix multiplication.

At the time of writing, vLLM-TorchTPU supports the following:

PropertyvLLM-TorchTPU
Packagevllm-torchtpu (pip or Docker)
Python3.12 on a Cloud TPU VM
Compilationtorch.compile(backend="tpu") to XLA
Recommended TPUv7x (Ironwood)
Other TPUsv6e (Trillium) is supported but not covered by CI. v5e, v5p, and v4 are experimental.
APIOpenAI-compatible
vLLM featuresSpeculative decoding, prefix caching, multi-LoRA, structured output, multimodal inputs
Model families with TPU-specific workQwen, DeepSeek, Kimi, GLM, Llama, GPT-OSS, Gemma

Note: This tutorial uses a v5e TPU, which is experimental and easy to get on Google Colab. Treat the numbers below as observations from experimental hardware, not as official performance figures.

How Does vLLM-TorchTPU Work?

On a TPU, the model has to be compiled into XLA programs before it can serve requests, and each program is compiled for fixed input shapes.

Diagram of how vLLM model code and custom kernels compile into one TPU program through StableHLO and Mosaic

vLLM's model code takes the left path through StableHLO, while its custom attention and MoE kernels take the right path through Mosaic. Both are compiled together into one TPU program, which is the work you wait for when the server starts. (Source)

You don't need these compiler stages to use vLLM-TorchTPU. The main point is that model code and custom kernels take two paths into one TPU program, and building that program is what makes the first startup slow.

That is why a vLLM-TorchTPU server spends a large part of its startup compiling. During warmup, it compiles the model backbone and several helper functions like sampling, logits selection, and structured decoding for a set of padded sizes. You can watch this happen in the server log by running:

!tail -n 30 /content/serve.log

If you're on a TPU VM and started the server with vllm serve ... > serve.log 2>&1 &, run the same command without the !, like this:

tail -n 30 serve.log

If you ran vllm serve in the foreground, the log is already in your terminal.

Here is one such helper, gather_logprobs, being compiled for batch sizes from 8 to 256 sequences:

Compiling gather_logprobs with different input shapes.
  -- num_seqs: 8
  -- num_seqs: 16
  -- num_seqs: 32
  ...
  -- num_seqs: 256
Compilation finished in 0.23 [secs].
...
init engine (profile, create kv cache, warmup model) took 149.43 s (compilation: 121.62 s)

At request time, each incoming batch is padded up to the nearest compiled size, so the server can reuse a program it already has instead of compiling a new one. The engine config printed at startup lists these compile sizes, from 16 up to 2,048 tokens.

Compiled programs can be saved to disk and reused on the next start. In our runs, the cache that filled up lived under the folder set by VLLM_CACHE_ROOT. We'll measure how much it saves in Step 8.

The rest of the stack is regular vLLM: the scheduler, continuous batching, KV cache manager, and API server are unchanged. For a deeper look at how these pieces work, see our guide on how LLM inference works.

Demo: Serving a Ticket Priority Sorting App on a TPU

Before building the demo, let's go through the settings for the experiments: hardware, model, prompt length, and prefix caching.

SettingValue usedReason
HardwareColab TPU v5e-1 or TPU v6e-1 with High RAMSingle chip, the smallest TPU setup available
ModelQwen/Qwen3-1.7BSmall open-weight model that compiled on v5e
Max model length4,096 tokensCaps prompt plus output length
Temperature0.0Deterministic outputs while comparing runs
Thinking modeOffKeeps outputs and token counts comparable
Output length128 tokens, ignore_eosSame decode work for every request
Prompt lengths143 to 2,677 tokensSix lengths, built from one growing support thread
Prefix cachingOn and offSeparates prefill cost from cache reuse
Repeats5 per conditionShows run-to-run variation

Note: These are working settings for this experiment, not tuned settings for vLLM-TorchTPU.

Step 1: Prerequisites

There are two ways to get a TPU for this tutorial. We use a Colab TPU runtime, which needs no Google Cloud project. The official vLLM-TorchTPU docs use a Cloud TPU VM, which we cover as Option B in this step.

Option A: Colab TPU runtime (used in this tutorial)

To follow along, you need:

  • A Google Colab account with access to a TPU runtime
  • Google Drive, to keep the compiled cache and results between sessions
  • Optionally, a Hugging Face token (Qwen3-1.7B is not gated)

In Colab, select Runtime, then Change runtime type, and pick a TPU. We used v5e-1 with High RAM turned on.

Colab Change runtime type dialog with a TPU v5e-1 hardware accelerator selected

High RAM adds host memory, which helps during the first startup, when the server loads weights and compiles graphs.

Option B: Cloud TPU VM

The vLLM-TorchTPU docs recommend a TPU v7x (Ironwood), which Colab does not offer. If you have a Google Cloud project with a TPU quota, you can run every step of this tutorial on a Cloud TPU VM instead. Run sub-steps 1 to 3 below from your laptop or Cloud Shell, and the rest on the TPU VM.

  1. Enable the APIs and check quota. Enable the Cloud TPU and Compute Engine APIs, then check your TPU quota for the zone under IAM & Admin, then Quotas & System Limits in the Google Cloud Console:
gcloud config set project PROJECT_ID
gcloud services enable tpu.googleapis.com compute.googleapis.com
  1. Create the TPU VM. The Cloud TPU Setup page generates the exact create command from your TPU generation, chip count (1 chip is enough for this tutorial), and provisioning model, including the matching runtime version. v7x, v5e, and v4 use the queued resources API, which looks like this:
gcloud alpha compute tpus queued-resources create QUEUED_RESOURCE_ID \
  --node-id TPU_NAME \
  --project PROJECT_ID \
  --zone ZONE \
  --accelerator-type ACCELERATOR_TYPE \
  --runtime-version RUNTIME_VERSION

v6e and v5p use the Compute Engine API (gcloud compute instances create) instead.

  1. Connect with SSH. For a queued resource (v7x, v5e, v4), run the following:
gcloud compute tpus tpu-vm ssh TPU_NAME \
  --project=PROJECT_ID --zone=ZONE --worker=0

For a Compute Engine TPU VM (v6e, v5p), run:

gcloud compute ssh TPU_NAME --project=PROJECT_ID --zone=ZONE
  1. Install vLLM-TorchTPU. The following commands install a matching vLLM, torch, torch_tpu, and libtpu alongside the plugin:
sudo apt-get install libibverbs1
curl -LsSf https://astral.sh/uv/install.sh | sh
source $HOME/.local/bin/env
uv venv --python 3.12 ~/uv_venv
source ~/uv_venv/bin/activate
export UV_TORCH_BACKEND=cpu
uv pip install vllm-torchtpu

Then confirm that vLLM sees the TPU:

python -c "from vllm.platforms import current_platform; print(current_platform.device_name)"
  1. Start the server. On a TPU VM, you can run vllm serve directly in a terminal, so you don't need the background helper from Step 4. We also set the native TorchTPU compile cache, which is separate from VLLM_CACHE_ROOT (we did not test this variable):
export VLLM_CACHE_ROOT=~/vllm-cache
export TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT=~/torchtpu-cache
vllm serve Qwen/Qwen3-1.7B \
  --tensor-parallel-size 1 \
  --max-model-len 4096 \
  --port 8000

The VM's disk persists between server restarts, so the compile cache needs no Google Drive setup. From here, the client code in Steps 5 to 9 works unchanged.

If you prefer containers, the official image is available with docker pull vllm/vllm-torchtpu:latest. The Docker guide has the run command.

  1. Delete the TPU. A TPU VM is billed while it exists, even when idle, so delete it when you are done. For a queued resource:
gcloud compute tpus queued-resources delete QUEUED_RESOURCE_ID \
  --project PROJECT_ID --zone ZONE --force --async

For a Compute Engine TPU VM (v6e, v5p), run:

gcloud compute instances delete TPU_NAME \
  --project=PROJECT_ID --zone=ZONE

Step 2: Install vLLM-TorchTPU

vLLM-TorchTPU needs Python 3.12, and the Colab runtime may ship a different version. The simplest fix is to install the server into its own Python 3.12 environment with uv. The notebook kernel only talks to the server over HTTP, so it can stay on any Python version.

%%capture install_log
!apt-get install -q -y libibverbs1
!pip install -q uv
!uv venv /content/venv312 --python 3.12 --clear
!uv pip install --python /content/venv312/bin/python \
    --index-strategy unsafe-best-match \
    --extra-index-url https://download.pytorch.org/whl/cpu \
    vllm-torchtpu
!pip install -q openai requests gradio pandas matplotlib

The apt-get line installs libibverbs1, a system library the TPU runtime needs. The --extra-index-url points at PyTorch's CPU wheel index, and the --index-strategy unsafe-best-match flag lets uv pick the right version across both indexes.

Next, we record the versions and check that TorchTPU can see the TPU:

import os

VENV_PY = "/content/venv312/bin/python"
VLLM_BIN = "/content/venv312/bin/vllm"
os.environ["VLLM_BIN"] = VLLM_BIN
!{VENV_PY} --version
!uv pip list --python {VENV_PY} | grep -E "^(vllm-torchtpu|torch|torch-tpu|libtpu) "
!{VENV_PY} -c "import torch_tpu; print('torch_tpu OK')"

In our run, this printed:

Python 3.12.3
libtpu                                   0.0.50
torch                                    2.13.0+cpu
torch-tpu                                0.2.0
vllm-torchtpu                            0.32.0
torch_tpu OK

Step 3: Connect the Compile Cache to Google Drive

Colab wipes content when the runtime disconnects. Since compiling takes most of the startup time, we store the cache on Google Drive, so it survives a full restart.

import os
from google.colab import drive

drive.mount("/content/drive")
CACHE_DIR = "/content/drive/MyDrive/vllm-torchtpu-cache"
os.makedirs(CACHE_DIR, exist_ok=True)
os.environ["VLLM_CACHE_ROOT"] = f"{CACHE_DIR}/vllm"

In our runs, only the folder under VLLM_CACHE_ROOT filled up, so that is the one we keep. For a TPU VM, the docs also describe a native cache location (TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT), which we did not test.

Step 4: Start the server

A plain !vllm serve would block the notebook cell, so we start the server as a background process and poll its /health endpoint until it is ready:

import time, signal, subprocess, requests
MODEL = "Qwen/Qwen3-1.7B"
SERVER = "http://localhost:8000"
server_proc = None


def start_server(extra_args=(), log_path="/content/serve.log"):
    global server_proc
    cmd = [VLLM_BIN, "serve", MODEL,
           "--tensor-parallel-size", "1",
           "--max-model-len", "4096",
           "--port", "8000", *extra_args]
    log = open(log_path, "w")
    server_proc = subprocess.Popen(cmd, stdout=log, stderr=subprocess.STDOUT,
                                   env=os.environ.copy(), start_new_session=True)
    start = time.perf_counter()
    while True:
        if server_proc.poll() is not None:
            raise RuntimeError(f"vllm serve exited. Check {log_path}")
        try:
            if requests.get(f"{SERVER}/health", timeout=2).status_code == 200:
                break
        except requests.RequestException:
            pass
        time.sleep(2)
    ready_s = time.perf_counter() - start
    print(f"Server ready in {ready_s:.1f} s")
    return ready_s


def stop_server():
    global server_proc
    if server_proc and server_proc.poll() is None:
        os.killpg(server_proc.pid, signal.SIGTERM)
        server_proc.wait(timeout=120)
    server_proc = None


start_server()

The extra_args parameter lets us pass extra vLLM flags later, such as turning off prefix caching. The start_new_session=True setting lets stop_server() shut down the whole process group, including the engine process.

Step 5: Send the first request

The server exposes the usual OpenAI-compatible routes, so a plain curl request works:

%%bash
curl -s http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model": "Qwen/Qwen3-1.7B",
       "messages": [{"role": "user", "content": "Explain how TPUs accelerate matrix multiplication."}],
       "max_tokens": 128,
       "chat_template_kwargs": {"enable_thinking": false}}'

Qwen3 outputs its reasoning in a <think> block by default. Passing "enable_thinking": false through chat_template_kwargs turns that off, which keeps JSON outputs clean and token counts comparable. In our run, the response came back with 21 prompt tokens, 128 completion tokens, and "reasoning": null.

The model's generation_config.json overrides vLLM's default sampling settings, so requests that don't set them use Qwen's recommended values. All our requests set temperature=0.0 explicitly, so the outputs stay deterministic. This is fine with thinking mode off. Qwen recommends avoiding greedy decoding when thinking mode is on.

Step 6: Build the Ticket Priority Sorting App

Now that the server works, let's build something on top of it. Our app sorts support tickets for a product called BoxDrive. For each ticket, it returns a category, a priority, a one-line summary, and whether the customer is blocked, along with the next action.

The tickets live in tickets.json, along with the prompts and rules. You can build your own or use this file as it is. The excerpt below shows the structure, and the full file is in the Colab notebook:

%%writefile tickets.json
{
  "system_prompt": "You are a support triage assistant for a cloud storage product called BoxDrive.\nRead the ticket thread and return JSON only.\nBase every field on the thread. Do not invent account details.\nIf the thread does not say something, use \"unknown\".",
  "categories": ["billing", "sync", "login", "performance", "data_loss", "feature_request", "other"],
  "priorities": ["P1", "P2", "P3", "P4"],
  "priority_rules": [
    "P1: data loss, or the whole team is blocked",
    "P2: one user cannot use the product and has no workaround",
    "P3: a real problem, but the user can still use the product (billing errors, slow performance with a workaround)",
    "P4: question or feature request"
  ],
  "category_notes": [
    "billing: charges, refunds, invoices, plans",
    "login: sign-in, SSO, passwords, 2FA",
    "feature_request: asks for something the product does not do yet",
    "data_loss: files missing or deleted without the user doing it"
  ],
  "tickets": [
    {
      "id": "TCK-2101",
      "subject": "Files disappeared after sync",
      "latest_message": "After last night's desktop update, about 40 files in our shared Finance folder are gone on every laptop. The web app shows the folder as empty too. Month-end close is tomorrow and the whole team needs these files."
    }
  ],
  "history_pool": [
    "Customer: I tried signing out and back in on the desktop app but nothing changed.",
    "Agent: Thanks for reaching out. Could you tell me which version of the desktop app you are running?"
  ]
}

The full file has five tickets (lost files, a double charge, slow uploads, an SSO login failure, and a dark mode request) and 20 earlier thread messages in history_pool. We use those messages to make a thread longer without changing the task, which we need for the latency experiment.

Load the file into CASE and import the modules the next cells use:

import json

CASE = json.load(open("tickets.json"))

First, we turn a ticket into a thread with a chosen number of earlier messages:

def build_thread(ticket: dict, n_history: int) -> str:
    pool = CASE["history_pool"]
    history = [pool[i % len(pool)] for i in range(n_history)]
    lines = [f"Ticket {ticket['id']}: {ticket['subject']}"]
    if history:
        lines += [""] + history
    lines += ["", f"Customer (latest): {ticket['latest_message']}"]
    return "\n".join(lines)

Then we build the chat messages, with the categories, notes, and priority rules in the user prompt:

def build_messages(ticket: dict, n_history: int = 0) -> list[dict]:
    rules = "\n".join(f"- {r}" for r in CASE["priority_rules"])
    notes = "\n".join(f"- {n}" for n in CASE["category_notes"])
    task = (
        "Triage this ticket.\n"
        f"Categories: {', '.join(CASE['categories'])}\n"
        f"Category notes:\n{notes}\n"
        f"Priority rules:\n{rules}\n\n"
        "Return JSON with: category, priority, summary (one sentence), "
        "customer_blocked, next_action (one sentence).\n\n"
        f"THREAD:\n{build_thread(ticket, n_history)}"
    )
    return [
        {"role": "system", "content": CASE["system_prompt"]},
        {"role": "user", "content": task},
    ]

The model call uses the standard OpenAI client pointed at our server. To make sure the output is always valid JSON with the allowed values, we pass a JSON schema through response_format, which vLLM enforces with structured output:

from openai import OpenAI

client = OpenAI(base_url=f"{SERVER}/v1", api_key="not-needed")
NO_THINK = {"chat_template_kwargs": {"enable_thinking": False}}

TRIAGE_SCHEMA = {
    "type": "object",
    "properties": {
        "category": {"type": "string", "enum": CASE["categories"]},
        "priority": {"type": "string", "enum": CASE["priorities"]},
        "summary": {"type": "string"},
        "customer_blocked": {"type": "string", "enum": ["yes", "no", "unknown"]},
        "next_action": {"type": "string"},
    },
    "required": ["category", "priority", "summary", "customer_blocked", "next_action"],
}

def triage(ticket: dict, n_history: int = 0, max_tokens: int = 200) -> dict:
    messages = build_messages(ticket, n_history)
    start = time.perf_counter()
    response = client.chat.completions.create(
        model=MODEL,
        messages=messages,
        temperature=0.0,
        max_tokens=max_tokens,
        extra_body=NO_THINK,
        response_format={
            "type": "json_schema",
            "json_schema": {"name": "triage", "schema": TRIAGE_SCHEMA},
        },
    )
    elapsed = time.perf_counter() - start
    choice = response.choices[0]
    return {
        "ticket": ticket["id"],
        "elapsed_s": round(elapsed, 3),
        "prompt_tokens": response.usage.prompt_tokens,
        "completion_tokens": response.usage.completion_tokens,
        "triage": json.loads(choice.message.content),
    }

Now, let's run all five tickets, each with 50 earlier messages in the thread:

for t in CASE["tickets"]:
    out = triage(t, n_history=50)
    print(out["ticket"], out["prompt_tokens"], "prompt tokens |",
          out["triage"]["category"], out["triage"]["priority"])

Here is the output we got:

TicketPrompt tokensModel outputExpected
TCK-2101 lost files1,156data_loss, P1data_loss, P1
TCK-2102 double charge1,143billing, P1billing, P3
TCK-2103 slow uploads1,151performance, P3performance, P3
TCK-2104 SSO login1,153login, P2login, P2
TCK-2105 dark mode request1,132other, P3feature_request, P4

Every response was valid JSON with allowed values, and Qwen3-1.7B got three of the five cases right. We tried clearer priority rules and the category notes shown above, but neither changed the two wrong answers, and small prompt edits often moved other answers instead. A larger model or a few worked examples in the prompt might do better.

Step 7: Add a Gradio UI

To make the app easy to try, we wrap it in a small Gradio interface. It shows the exact thread sent to the model, the JSON result, and the latency and token counts:

Gradio interface for BoxDrive ticket triage showing the thread, JSON result, and latency stats

import gradio as gr


def launch_ui():
    by_id = {t["id"]: t for t in CASE["tickets"]}

    def run(ticket_id, n_history):
        out = triage(by_id[ticket_id], int(n_history))
        thread = build_thread(by_id[ticket_id], int(n_history))
        stats = (f"{out['elapsed_s']} s | prompt {out['prompt_tokens']} tokens | "
                 f"output {out['completion_tokens']} tokens")
        return thread, json.dumps(out["triage"], indent=2), stats

    with gr.Blocks(title="BoxDrive Ticket Triage on TPU") as demo:
        gr.Markdown(f"## BoxDrive ticket triage\n{MODEL} on vLLM-TorchTPU")
        with gr.Row():
            ticket_id = gr.Dropdown(list(by_id), value="TCK-2101", label="Ticket")
            n_history = gr.Slider(0, 120, value=0, step=4, label="Earlier messages in thread")
        btn = gr.Button("Triage")
        thread = gr.Textbox(label="Thread sent to the model", lines=12)
        result = gr.Code(label="Triage result", language="json")
        stats = gr.Markdown()
        btn.click(run, [ticket_id, n_history], [thread, result, stats])

    demo.launch(share=True)


launch_ui()

The share=True option gives a public link, which is the easiest way to open the UI from Colab or a remote TPU VM. Anyone with the link can use the app while the cell runs. The Gradio cell blocks the notebook while it runs, so interrupt it before you run the next cell.

Step 8: Measure Cold vs Warm Startup

Compilation is the part of TPU serving that GPU users notice first, so let's measure it. The measure_startup.py script starts its own server, times how long /health takes to return 200, and then times two identical requests. The full script is in the Colab notebook.

  • A cold run deletes the cache folder first, so everything is compiled from scratch.
  • A warm run reuses the same cache folder.

Here is the core of the script. It assumes the imports (os, shutil, signal, subprocess) and helpers (server_env, wait_ready, one_request) defined in the full file:

def run_once(label: str, idx: int) -> dict:
    if label == "cold" and CACHE_DIR.exists():
        shutil.rmtree(CACHE_DIR)
    CACHE_DIR.mkdir(parents=True, exist_ok=True)

    cmd = [os.environ.get("VLLM_BIN", "vllm"), "serve", MODEL,
           "--tensor-parallel-size", "1",
           "--max-model-len", "4096", "--port", "8000"]
    with open(f"serve_{idx}_{label}.log", "w") as log:
        proc = subprocess.Popen(cmd, env=server_env(), stdout=log,
                                stderr=subprocess.STDOUT, start_new_session=True)
        try:
            ready_s = wait_ready(proc)
            first_s = one_request()
            second_s = one_request()
        finally:
            os.killpg(proc.pid, signal.SIGTERM)
            proc.wait(timeout=120)
    return {"run": idx, "label": label, "ready_s": ready_s,
            "first_request_s": first_s, "second_request_s": second_s}

Stop the server from Step 4 first, since both use port 8000. Then run one cold start followed by two warm starts:

stop_server()
os.environ["STARTUP_CACHE_DIR"] = "/content/drive/MyDrive/vllm-torchtpu-startup-exp"
!python measure_startup.py --runs cold warm warm

Note that "cold" here means an empty compile cache. The model weights were already downloaded, so download time is not included.

To see where the time went, we also pulled the engine's own timing line from each server log by running:

!grep -h "init engine" serve_*_*.log

Here are the results:

RunTime to readyEngine initCompilationFirst requestSecond requestCache size
Cold192.2 s151.41 s85.94 s0.633 s0.248 s476.4 MB
Warm 1181.2 s149.43 s121.62 s0.635 s0.248 s804.4 MB
Warm 267.1 s34.89 s6.24 s0.461 s0.248 s804.4 MB

Bar chart of server startup on TPU v5e-1 split into compilation, other engine init, and process start plus model load, for cold and warm runs

Server startup on TPU v5e-1, cold vs warm compile cache.

We expected "cold is slow, warm is fast," but the first warm start didn't follow that pattern:

  • Warm 1 spent 121.62 seconds compiling, more than the cold run's 85.94 seconds, so the cache from the cold run did not help yet. Time to ready dropped only from 192.2 to 181.2 seconds because other engine init steps got shorter (the table shows engine init at 151.41 and 149.43 seconds).
  • Warm 2 reused the cache. Compilation fell to 6.24 seconds, and time to ready fell to 67.1 seconds, about 2.9x faster than the cold start.
  • The cache kept growing after the cold run. It went from 476.4 MB to 804.4 MB after the first warm run, then stayed there.

A practical lesson is to plan for two restarts before you rely on warm startup times.

Once the server was up, request latency did not depend on the cache. The second request took 0.248 seconds in every run, while the first request took 0.461 to 0.635 seconds. Send one warmup request before you measure anything.

Step 9: Measure Latency vs Prompt Length

A support thread grows with every reply, so prompt length is the next thing to test. We sent a ticket (TCK-2101) thread at six lengths, from 0 to 150 earlier messages, and asked the model to summarize it for an on-call engineer.

We stream each response, so we can split the latency into two parts:

  • TTFT: mostly the prefill of the prompt.
  • Decode speed: output tokens per second after the first token.

To give every request the same decode work, we fix the output at 128 tokens with ignore_eos:

def timed_stream(messages: list[dict]) -> dict:
    start = time.perf_counter()
    first, usage = None, None
    stream = client.chat.completions.create(
        model=MODEL,
        messages=messages,
        temperature=0.0,
        max_tokens=128,
        stream=True,
        stream_options={"include_usage": True},
        extra_body={"ignore_eos": True,
                    "chat_template_kwargs": {"enable_thinking": False}},
    )
    for chunk in stream:
        if chunk.usage is not None:
            usage = chunk.usage
        if chunk.choices and chunk.choices[0].delta.content and first is None:
            first = time.perf_counter()
    end = time.perf_counter()
    return {
        "ttft_s": first - start,
        "total_s": end - start,
        "prompt_tokens": usage.prompt_tokens,
        "decode_tps": (usage.completion_tokens - 1) / (end - first),
    }

Our first run gave a flat result. TTFT barely moved, from 15.9 ms at 143 tokens to 20.7 ms at 2,677 tokens.

The cause was prefix caching, which vLLM turns on by default. Each longer prompt started with the whole shorter one, so after the first request vLLM reused the cached key-value (KV) entries for most of the prompt. We were not measuring prefill at all.

To measure the real prefill cost, we restarted the server with prefix caching turned off and ran the benchmark again:

stop_server()
start_server(extra_args=["--no-enable-prefix-caching"])
!python benchmark_prompt_length.py

Here are the results:

Prompt tokensTTFT, cache offTTFT, cache onTotal, cache offDecode speed, cache off
14315.7 ms15.9 ms0.677 s191.9 tokens/s
32521.3 ms15.1 ms0.687 s190.9 tokens/s
57032.4 ms15.1 ms0.702 s189.7 tokens/s
99733.2 ms18.4 ms0.711 s187.4 tokens/s
1,82354.8 ms18.7 ms0.748 s183.3 tokens/s
2,67782.6 ms20.7 ms0.792 s179.1 tokens/s

Line chart of median time to first token against prompt length, rising with prefix caching off and flat with it on

Median time to first token vs prompt length, prefix caching off and on.

With prefix caching off, TTFT grew from 15.7 ms to 82.6 ms, about 5.3x, as the prompt grew from 143 to 2,677 tokens. The five warm runs at each length were within about 1 ms of each other. Prompts longer than the 2,048-token compile size are split into chunks by vLLM's chunked prefill, so the two longest points are still measured.

The 570-token and 997-token prompts took almost the same time (32.4 and 33.2 ms). A likely reason is padding, so both prompts round up to the same 1,024-token compile size.

With prefix caching on, TTFT stayed between 15.1 and 20.7 ms at every length. This suits a support thread that grows one message at a time, because each new request shares a long prefix with the last one. Unrelated prompts would not get the same benefit.

Decode speed vs prompt length, prefix caching off. The y-axis starts at 170 tokens per second.

Decode speed was less sensitive to prompt length. It dropped 6.7%, from 191.9 to 179.1 tokens per second, so the total time for 128 output tokens only went from 0.677 to 0.792 seconds. For short outputs on this setup, decode time dominates and prompt length mostly shows up in TTFT.

The first request at a new length was sometimes slower than the repeats, for example, 0.271 seconds at 143 tokens versus a 15.7 ms median. These one-off costs appeared even with prefix caching off, which is another reason to send warmup requests before benchmarking.

Final Thoughts

vLLM-TorchTPU lets you serve a model on a TPU with the same vllm serve command and OpenAI-compatible API you would use on a GPU. The differences show up in how the server starts and how you should measure it. Here are the key learnings from this tutorial:

  • Startup is dominated by compilation. A cold start took 192.2 seconds, mostly compiling. The first restart compiled again, and only the second restart brought startup down to 67.1 seconds.
  • Prefix caching can hide prefill cost. With repeated or growing prompts, TTFT stayed between 15.1 and 20.7 ms. With it off, TTFT grew about 5.3x across our prompt range.
  • Decode time dominates for short outputs. Decode speed dropped only 6.7% as the prompt grew to 2,677 tokens, and total time for 128 output tokens stayed under 0.8 seconds.

Note: These results come from a small number of runs on one single-chip TPU and one synthetic support thread, so treat them as observations from this demo, not general performance claims about vLLM-TorchTPU.

If you want to go further with serving and building on LLMs, try our AI Fundamentals track. For reuse of attention state across requests, see our LMCache tutorial.

vLLM-TorchTPU FAQs

What is the difference between vLLM-TorchTPU and vLLM JAX?

Both are vLLM backends for Google Cloud TPUs. vLLM-TorchTPU runs PyTorch model definitions through TorchTPU and is the recommended path for PyTorch models on TPU. vLLM JAX, formerly called tpu-inference, focuses on serving JAX models.

Do I need to change my client code to use a TPU?

No. vLLM-TorchTPU keeps vLLM's OpenAI-compatible API server, so any client that works with vLLM on a GPU works here. In this tutorial, the ticket sorting app uses the standard OpenAI Python client with no TPU-specific code.

Why does the first server take a long time to start?

The model is compiled into XLA programs for a fixed set of input sizes during warmup. In our runs, a cold start took 192.2 seconds, with 85.94 seconds of compilation. Keeping the cache folder between runs brought startup down to 67.1 seconds, but only from the second restart onward.

Should I turn off prefix caching in vLLM?

Not for serving. Prefix caching helps when requests share a long prefix, such as a growing chat or support thread. Turn it off only when you want to benchmark prefill cost, because cached prefixes make the time to first token look nearly flat.

Can I run vLLM-TorchTPU on a Google Colab TPU?

Yes, with two caveats. Colab offers v5e and v6e TPUs, which the docs list as experimental and supported but not covered by CI, respectively. Also, the Colab runtime may use a different Python version than the required 3.12. Installing the server into a separate Python 3.12 environment with uv solves that.

Topics

Related