跳至主要内容

vLLM-TorchTPU 教程:在 Cloud TPU 上服务小型 LLM

学习如何使用 vLLM-TorchTPU 在 Google Cloud TPU 上服务小型开源权重 LLM,在其之上构建工单优先级排序应用,并评估启动与提示长度对延迟的影响。
· 15分钟 阅读

使用 AI 探索

您能否用与 GPU 上相同的 vllm serve 命令在 TPU 上服务 LLM?可以。vLLM-TorchTPU 是 vLLM 的 PyTorch 原生 TPU 后端,与 TorchTPU(Google 面向 Cloud TPU 的开源 PyTorch 后端)一同发布。它运行已经内置于 vLLM 的模型定义,因此大多数能在 vLLM 上运行的模型,无需修改模型代码即可在 TPU 上提供服务。

简而言之

vLLM-TorchTPU 是一个插件,使标准的 vllm serve 命令和兼容 OpenAI 的 API 能在 Cloud TPU 上运行。在我们于 Colab TPU v5e-1 上服务 Qwen3-1.7B 的测试中,冷启动到服务器就绪耗时 192.2 秒;在保存编译缓存后两次重启,则为 67.1 秒。关闭前缀缓存时,首 token 时间(TTFT)在提示从 143 增至 2,677 个 token 时增加约 5.3 倍;开启前缀缓存时,TTFT 保持在 15.1 至 20.7 毫秒之间。

在本教程中,我们将在单芯片 Colab TPU 上从 Hugging Face 服务 Qwen3-1.7B,并通过兼容 OpenAI 的 API 构建一个小型的支持工单优先级排序应用。然后我们使用同一服务器来探索:

  • 服务器的冷启动与暖启动有何不同?
  • 随着提示变长,TTFT 在开启与关闭前缀缓存时如何变化?

完成本教程后,您将学会:

  • 在 Colab TPU 运行时安装 vLLM-TorchTPU。
  • 在 TPU 上启动兼容 OpenAI 的 vLLM 服务器并向其发送请求。
  • 构建带结构化 JSON 输出与 Gradio 界面的工单优先级排序应用。
  • 在多次重启间保留 TPU 编译缓存并测量其效果。
  • 在不同提示长度下测量首 token 时间与解码速度。
  • 解读前缀缓存对测量结果的影响。

您可以在此 Google Colab 笔记本中运行完整代码。若您初次接触 vLLM 或 Colab,我们的 vLLM 教程 与 Google Colab 指南是不错的起点。

什么是 vLLM-TorchTPU?

vllm-torchtpu 包是一个 vLLM 的 out-of-tree 平台插件。安装后,vLLM 会通过其 vllm.platform_plugins 入口点自动发现它,因此您可以像在 GPU 上一样使用相同的 vllm serve 命令、调度器、KV 缓存管理器与兼容 OpenAI 的 API 服务器。

在底层,它通过 TorchTPU 在 TPU 上运行 vLLM 的标准 PyTorch 模型定义,由 torch.compile(backend="tpu") 编译并下沉到 XLA。自定义的 JAX 与 Pallas 内核处理注意力、专家混合(MoE)与量化矩阵乘等重计算。

撰写时,vLLM-TorchTPU 支持如下内容:

属性vLLM-TorchTPU
包vllm-torchtpu(pip 或 Docker)
PythonCloud TPU VM 上的 3.12
编译torch.compile(backend="tpu") 至 XLA
推荐 TPUv7x(Ironwood)
其他 TPU支持 v6e(Trillium)但未纳入 CI;v5e、v5p 与 v4 为实验性。
API兼容 OpenAI
vLLM 功能投机解码、前缀缓存、多 LoRA、结构化输出、多模态输入
进行过 TPU 特定适配的模型家族Qwen、DeepSeek、Kimi、GLM、Llama、GPT-OSS、Gemma

注意:本教程使用的是 v5e TPU,该代属实验性,在 Google Colab 上易于获取。以下数字应视为来自实验性硬件的观察结果,而非官方性能数据。

vLLM-TorchTPU 如何工作?

在 TPU 上,模型在服务请求前必须被编译为 XLA 程序,且每个程序针对固定的输入形状编译。

vLLM 模型代码与自定义内核如何通过 StableHLO 与 Mosaic 编译为一个 TPU 程序的示意图

vLLM 的模型代码走左侧 StableHLO 路径,自定义的注意力与 MoE 内核走右侧 Mosaic 路径。两者一起编译为一个 TPU 程序,这就是服务器启动时需要等待的工作。(来源)

使用 vLLM-TorchTPU 并不需要了解这些编译阶段。关键在于:模型代码与自定义内核通过两条路径汇入同一个 TPU 程序,而构建该程序正是导致首次启动较慢的原因。

这也是 vLLM-TorchTPU 服务器在启动阶段大量时间花在编译上的原因。在预热期间,它会针对一组填充后的尺寸编译模型骨干及采样、logits 选择、结构化解码等若干辅助函数。您可以运行以下命令在服务器日志中观察这一过程:

!tail -n 30 /content/serve.log

如果您在 TPU VM 上并以 vllm serve ... > serve.log 2>&1 & 启动服务器,请去掉 ! 直接运行:

tail -n 30 serve.log

若您在前台运行了 vllm serve,日志已在您的终端中。

下面是其中一个辅助函数 gather_logprobs 的示例,正在为 8 到 256 序列的批大小编译:

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)

在请求时,每个传入批都会被填充到最近的已编译大小,这样服务器就能重用已有程序而无需重新编译。启动时打印的引擎配置会列出这些编译尺寸,从 16 到 2,048 个 token。

已编译程序可保存到磁盘,并在下次启动时重用。在我们的运行中,填充的缓存位于由 VLLM_CACHE_ROOT 指定的文件夹下。我们将在第 8 步测量它的收益。

其余栈与常规 vLLM 相同:调度器、连续批处理、KV 缓存管理器与 API 服务器都未改变。若想深入了解这些组件的工作方式,请参阅我们的LLM 推理工作原理指南。

演示:在 TPU 上服务工单优先级排序应用

在构建演示前,先过一遍实验设置:硬件、模型、提示长度与前缀缓存。

设置取值原因
硬件Colab TPU v5e-1 或 TPU v6e-1(高内存)单芯片,最小的 TPU 配置
模型Qwen/Qwen3-1.7B在 v5e 上可编译的小型开源权重模型
最大模型长度4,096 个 token限制提示加输出的总长度
温度0.0对比多次运行时获得确定性输出
思维模式关闭保持输出与 token 计数可比
输出长度128 个 token,ignore_eos确保每个请求的解码工作量相同
提示长度143 至 2,677 个 token六种长度,基于同一不断增长的支持线程
前缀缓存开启与关闭区分预填充成本与缓存复用
重复次数每种条件 5 次展示运行间的波动

注意:这些是本实验的可用设置,而非 vLLM-TorchTPU 的调优设置。

步骤 1:先决条件

获取 TPU 有两种方式。本教程使用 Colab TPU 运行时,无需 Google Cloud 项目。官方 vLLM-TorchTPU 文档使用 Cloud TPU VM,我们在本步骤的选项 B 中介绍。

选项 A:Colab TPU 运行时(本教程采用)

要跟做,您需要:

  • 一个可访问 TPU 运行时的 Google Colab 账户
  • Google 云端硬盘,用于在会话间保留编译缓存与结果
  • 可选:Hugging Face 令牌(Qwen3-1.7B 无需申请)

在 Colab 中选择运行时,再点更改运行时类型,选择 TPU。我们使用了 v5e-1,并开启高内存。

Colab 更改运行时类型对话框,选择了 TPU v5e-1 硬件加速器

高内存增加主机内存,这在首次启动(加载权重与编译图)时更有帮助。

选项 B:Cloud TPU VM

vLLM-TorchTPU 文档推荐使用 TPU v7x(Ironwood),Colab 暂不提供。若您在 Google Cloud 项目中有 TPU 配额,可以在 Cloud TPU VM 上完成本教程所有步骤。请在本机或 Cloud Shell 中运行子步骤 1 至 3,其余在 TPU VM 上运行。

  1. 启用 API 并检查配额。 启用 Cloud TPU 与 Compute Engine API,然后在 Google Cloud 控制台的IAM 与管理下的配额与系统限制中检查对应区域的 TPU 配额:
gcloud config set project PROJECT_ID
gcloud services enable tpu.googleapis.com compute.googleapis.com
  1. 创建 TPU VM。 Cloud TPU 设置页面会根据 TPU 代际、芯片数量(本教程 1 芯片足够)与供应模型生成精确的创建命令,并包含匹配的运行时版本。v7x、v5e 与 v4 使用排队资源 API,命令如下:
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 与 v5p 则使用 Compute Engine API(gcloud compute instances create)。

  1. 通过 SSH 连接。 对于排队资源(v7x、v5e、v4),运行:
gcloud compute tpus tpu-vm ssh TPU_NAME \
  --project=PROJECT_ID --zone=ZONE --worker=0

对于 Compute Engine TPU VM(v6e、v5p),运行:

gcloud compute ssh TPU_NAME --project=PROJECT_ID --zone=ZONE
  1. 安装 vLLM-TorchTPU。 以下命令会安装与插件匹配的 vLLM、torch、torch_tpu 与 libtpu:
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

然后确认 vLLM 能看到 TPU:

python -c "from vllm.platforms import current_platform; print(current_platform.device_name)"
  1. 启动服务器。 在 TPU VM 上可以直接在终端运行 vllm serve,无需第 4 步的后台辅助程序。我们还设置了原生 TorchTPU 编译缓存,它与 VLLM_CACHE_ROOT 分离(我们未测试该变量):
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

VM 的磁盘在重启间持久化,因此编译缓存无需 Google 云端硬盘配置。从这里开始,第 5 至 9 步的客户端代码无需更改即可运行。

若您偏好容器,官方镜像可通过 docker pull vllm/vllm-torchtpu:latest 获取。运行命令见Docker 指南。

  1. 删除 TPU。 TPU VM 在存在期间都会计费,即便空闲,因此完成后请删除。对于排队资源:
gcloud compute tpus queued-resources delete QUEUED_RESOURCE_ID \
  --project PROJECT_ID --zone ZONE --force --async

对于 Compute Engine TPU VM(v6e、v5p),运行:

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

步骤 2:安装 vLLM-TorchTPU

vLLM-TorchTPU 需要 Python 3.12,而 Colab 运行时可能提供不同版本。最简单的办法是使用 uv 将服务器安装到独立的 Python 3.12 环境中。笔记本内核仅通过 HTTP 与服务器通信,因此可保持任意 Python 版本。

%%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

apt-get 行安装 TPU 运行时需要的系统库 libibverbs1。--extra-index-url 指向 PyTorch 的 CPU 轮子索引,--index-strategy unsafe-best-match 允许 uv 在两个索引间选择正确版本。

接下来记录版本并检查 TorchTPU 是否能看到 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')"

在我们的运行中,输出如下:

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

步骤 3:将编译缓存连接到 Google 云端硬盘

Colab 在运行时断开后会清空内容。由于编译占据了大部分启动时间,我们将缓存存储在 Google 云端硬盘上,以便在完全重启后仍可使用。

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"

在我们的运行中,仅 VLLM_CACHE_ROOT 下的文件夹会填充,因此只需保留该目录。对于 TPU VM,文档还描述了一个原生缓存位置(TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT),我们未进行测试。

步骤 4:启动服务器

直接 !vllm serve 会阻塞笔记本单元,因此我们将服务器作为后台进程启动,并轮询其 /health 端点直至就绪:

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()

extra_args 参数允许我们稍后传递额外的 vLLM 标志,例如关闭前缀缓存。start_new_session=True 使 stop_server() 能关闭整个进程组,包括引擎进程。

步骤 5:发送首个请求

服务器暴露了常见的兼容 OpenAI 路由,因此可以直接用 curl 请求:

%%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 默认会在 <think> 块中输出推理。通过 chat_template_kwargs 传入 "enable_thinking": false 可将其关闭,从而保持 JSON 输出整洁并使 token 计数可比。在我们的运行中,响应包含 21 个提示 token、128 个补全 token,且 "reasoning": null。

模型的 generation_config.json 会覆盖 vLLM 的默认采样设置,因此未设置采样的请求会使用 Qwen 的推荐值。我们的所有请求均显式设置 temperature=0.0,以保持输出确定性。在关闭思维模式时,这样做没有问题。Qwen 建议在开启思维模式时避免贪心解码。

步骤 6:构建工单优先级排序应用

服务器已可用,接下来在其之上构建一个应用。我们的应用会为名为 BoxDrive 的产品进行支持工单分拣。针对每张工单,返回一个类别、一个优先级、一句话摘要、客户是否被阻塞,以及下一步行动建议。

工单保存在 tickets.json 中,连同提示与规则。您可以自建或直接使用该文件。下面的节选展示了结构,完整文件见 Colab 笔记本:

%%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?"
  ]
}

完整文件包含五张工单(文件丢失、重复扣费、上传缓慢、SSO 登录失败、深色模式需求)以及 history_pool 中的 20 条更早的线程消息。我们用这些消息在不改变任务的前提下拉长线程,以便进行延迟实验。

将文件加载到 CASE 并导入后续单元所需模块:

import json

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

首先,我们将一张工单转成带指定数量历史消息的线程:

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)

然后构建聊天消息,将类别、说明与优先级规则放入用户提示:

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},
    ]

模型调用使用指向我们服务器的标准 OpenAI 客户端。为确保输出始终是带允许值的有效 JSON,我们通过 response_format 传递 JSON 架构,vLLM 会以结构化输出强制执行:

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),
    }

现在运行五张工单,每张带 50 条更早的线程消息:

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"])

我们得到的输出如下:

工单提示 token模型输出期望
TCK-2101 文件丢失1,156data_loss, P1data_loss, P1
TCK-2102 重复扣费1,143billing, P1billing, P3
TCK-2103 上传缓慢1,151performance, P3performance, P3
TCK-2104 SSO 登录1,153login, P2login, P2
TCK-2105 深色模式需求1,132other, P3feature_request, P4

所有响应都是含允许值的有效 JSON,Qwen3-1.7B 正确判定了五例中的三例。我们尝试了更清晰的优先级规则与上述分类说明,但依然未能修正两个错误答案,且对提示的小幅修改经常会影响其他答案。更大的模型或在提示中加入少量已解示例可能表现更好。

步骤 7:添加 Gradio 界面

为方便试用,我们用一个小型 Gradio 界面封装应用。它展示发送给模型的准确线程、JSON 结果以及延迟与 token 统计:

BoxDrive 工单分拣的 Gradio 界面,显示线程、JSON 结果与延迟统计

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()

share=True 选项会提供公开链接,这是从 Colab 或远程 TPU VM 打开界面的最简单方式。只要单元在运行,持有链接的人都可以使用该应用。Gradio 单元在运行时会阻塞笔记本,请在运行下一个单元前中断它。

步骤 8:测量冷启动与暖启动

编译是 GPU 用户在 TPU 上服务时最先注意到的部分,因此我们对其进行测量。measure_startup.py 脚本会自行启动服务器,计时 /health 返回 200 所需时间,并对两个相同请求计时。完整脚本见 Colab 笔记本。

  • 冷启动会先删除缓存文件夹,因此所有内容从零开始编译。
  • 暖启动会复用同一缓存文件夹。

下面是脚本核心。它依赖完整文件中定义的导入(os、shutil、signal、subprocess)与辅助函数(server_env、wait_ready、one_request):

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}

先停止第 4 步的服务器,因为两者都使用 8000 端口。然后运行一次冷启动,随后两次暖启动:

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

注意,这里的“冷”指编译缓存为空。模型权重已下载,因此不包含下载时间。

为查看时间消耗位置,我们还通过以下命令从每个服务器日志中提取引擎自身的计时行:

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

结果如下:

运行就绪时间引擎初始化编译第一个请求第二个请求缓存大小
冷启动192.2 s151.41 s85.94 s0.633 s0.248 s476.4 MB
暖启动 1181.2 s149.43 s121.62 s0.635 s0.248 s804.4 MB
暖启动 267.1 s34.89 s6.24 s0.461 s0.248 s804.4 MB

TPU v5e-1 上服务器启动的柱状图,按编译、其他引擎初始化、进程启动加模型加载拆分,比较冷、暖运行

TPU v5e-1 上的服务器启动,冷缓存 vs 暖缓存。

我们原以为“冷慢暖快”,但第一次暖启动并未遵循该模式:

  • 暖启动 1 的编译耗时 121.62 秒,多于冷启动的 85.94 秒,因此冷启动产生的缓存尚未发挥作用。由于其他引擎初始化步骤变短(表中分别为 151.41 与 149.43 秒),就绪时间仅从 192.2 秒降到 181.2 秒。
  • 暖启动 2 复用了缓存。编译降至 6.24 秒,就绪时间降至 67.1 秒,较冷启动快约 2.9 倍。
  • 冷启动后缓存仍在增长:从 476.4 MB 增至第一次暖启动后的 804.4 MB,随后保持不变。

一个实用结论是:在依赖暖启动时间之前,预留两次重启。

服务器启动后,请求延迟不受缓存影响。第二个请求在每次运行中都为 0.248 秒,而第一个请求在 0.461 至 0.635 秒之间。在任何测量前先发送一次预热请求。

步骤 9:测量延迟与提示长度

支持线程会随每次回复而增长,因此提示长度是下一个要测试的因素。我们对一张工单(TCK-2101)的线程使用六种长度(0 至 150 条更早消息),并让模型为值班工程师做摘要。

我们以流式方式接收响应,以便将延迟拆成两部分:

  • TTFT:主要是提示的预填充时间。
  • 解码速度:首个 token 之后的每秒输出 token 数。

为让每个请求的解码工作相同,我们用 ignore_eos 将输出固定为 128 个 token:

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),
    }

我们的首次运行结果十分平坦:TTFT 几乎不变,从 143 token 时的 15.9 毫秒到 2,677 token 时的 20.7 毫秒。

原因在于前缀缓存,vLLM 默认开启。每个更长的提示都以完整的短提示起始,因此在第一个请求之后,vLLM 为大部分提示复用了已缓存的键值(KV)条目。我们并未真正测到预填充。

为测量真实的预填充成本,我们在关闭前缀缓存的情况下重启服务器并再次运行基准:

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

结果如下:

提示 tokenTTFT,缓存关TTFT,缓存开总耗时,缓存关解码速度,缓存关
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

首 token 时间与提示长度的中位数关系折线图,关闭前缀缓存时随长度上升,开启时保持平坦

首 token 时间与提示长度的中位数,前缀缓存关闭与开启。

关闭前缀缓存时,TTFT 随提示从 143 增至 2,677 token 增长约 5.3 倍,从 15.7 毫秒增至 82.6 毫秒。每个长度下的五次暖运行相差约 1 毫秒以内。超过 2,048 token 编译尺寸的提示会被 vLLM 的分块预填充切分,因此两个最长点仍得到测量。

570 与 997 token 的提示耗时几乎相同(32.4 与 33.2 毫秒)。很可能是由于填充,两者都被向上取整到相同的 1,024 token 编译尺寸。

开启前缀缓存时,TTFT 在所有长度下保持在 15.1 至 20.7 毫秒之间。这很适合每次只增长一条消息的支持线程,因为每条新请求都与上一条共享长前缀。不相关的提示则不会获益。

解码速度与提示长度(前缀缓存关闭)。纵轴从每秒 170 token 起。

解码速度对提示长度不太敏感。它从 191.9 下降到 179.1 token/秒,降幅 6.7%,因此输出 128 个 token 的总时间仅从 0.677 增至 0.792 秒。在该设置下,对于较短输出,解码时间占主导,提示长度主要体现在 TTFT 上。

在新长度下的第一个请求有时比重复请求更慢,例如 143 token 时为 0.271 秒,而中位数为 15.7 毫秒。即便关闭前缀缓存,这些一次性开销仍会出现,这也是在基准测试前先发送预热请求的另一个原因。

结语

vLLM-TorchTPU 让您可以用与 GPU 上相同的 vllm serve 命令与兼容 OpenAI 的 API 在 TPU 上服务模型。差异主要体现在服务器如何启动以及如何进行测量。以下是本教程的关键收获:

  • 启动阶段主要受编译主导。 冷启动耗时 192.2 秒,主要是编译。首次重启仍会编译,第二次重启才将启动时间降至 67.1 秒。
  • 前缀缓存可能掩盖预填充成本。 在重复或增长的提示下,TTFT 保持在 15.1 至 20.7 毫秒。关闭后,TTFT 在我们的提示范围内增加约 5.3 倍。
  • 对于短输出,解码时间占主导。 随提示增长至 2,677 token,解码速度仅下降 6.7%,输出 128 个 token 的总时间仍低于 0.8 秒。

注意:这些结果来自在单个芯片 TPU 与一个合成支持线程上的少量运行,因此应将其视为本演示的观察,而非关于 vLLM-TorchTPU 的通用性能结论。

若您希望在服务与构建 LLM 方面更进一步,欢迎学习我们的 AI Fundamentals 学习路径。关于跨请求复用注意力状态,请参阅我们的 LMCache 教程。

vLLM-TorchTPU 常见问题

vLLM-TorchTPU 与 vLLM JAX 有何区别?

二者都是面向 Google Cloud TPU 的 vLLM 后端。vLLM-TorchTPU 通过 TorchTPU 运行 PyTorch 模型定义,是在 TPU 上运行 PyTorch 模型的推荐路径。vLLM JAX(前称 tpu-inference)主要用于服务 JAX 模型。

使用 TPU 需要修改客户端代码吗?

不需要。vLLM-TorchTPU 保留了 vLLM 的兼容 OpenAI 的 API 服务器,因此任何能在 GPU 上与 vLLM 一起使用的客户端在这里也同样适用。在本教程中,工单排序应用使用标准的 OpenAI Python 客户端,无需 TPU 特定代码。

为什么首次启动服务器需要很长时间?

模型会在预热期间被编译为一组固定输入尺寸的 XLA 程序。在我们的运行中,冷启动耗时 192.2 秒,其中 85.94 秒用于编译。在运行间保留缓存文件夹可将启动降至 67.1 秒,但只在第二次重启之后才显现。

是否应在 vLLM 中关闭前缀缓存?

不建议在服务时关闭。此前缀缓存有助于当请求共享长前缀时(例如不断增长的聊天或支持线程)。仅在您要基准测试预填充成本时关闭它,因为缓存的前缀会让首 token 时间看起来几乎不变。

我可以在 Google Colab 的 TPU 上运行 vLLM-TorchTPU 吗?

可以,但有两点注意。Colab 提供 v5e 与 v6e TPU,文档中分别标注为实验性与“支持但未纳入 CI”。此外,Colab 运行时的 Python 版本可能不同于要求的 3.12。使用 uv 在单独的 Python 3.12 环境中安装服务器即可解决。

主题

相关