Gemma 4 生产部署指南:vLLM + Docker 实战

2026/04/07

Ollama 在本地跑 Gemma 4 开发调试没问题,但要服务几百个并发用户、每分钟处理几千个请求、延迟还要控制在一秒以内——你需要一个生产级的推理引擎。

vLLM 就是干这个的。它是目前大模型推理服务的业界标准,跟 Gemma 4 配合非常好。

为什么选 vLLM?

vLLM 用了一种叫 PagedAttention 的技术来管理显存,类似操作系统管理内存的方式——请求来了分配,走了回收,非常高效:

  • 吞吐量是普通推理的 2-4 倍
  • 兼容 OpenAI API——客户端代码不用改
  • 连续批处理——GPU 利用率拉满
  • 张量并行——大模型可以拆到多张 GPU 上

安装 vLLM

# 创建干净的环境
python -m venv vllm-env
source vllm-env/bin/activate

# 安装 vLLM
pip install vllm

需要 CUDA 12.1+ 和至少 16GB 显存的 GPU(跑小模型的话)。

启动 OpenAI 兼容 API

一行命令启动服务:

vllm serve google/gemma-4-26b \
  --host 0.0.0.0 \
  --port 8000 \
  --max-model-len 8192 \
  --gpu-memory-utilization 0.90 \
  --dtype bfloat16

然后用任何 OpenAI SDK 客户端调用:

from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="not-needed",  # vLLM 默认不需要 key
)

response = client.chat.completions.create(
    model="google/gemma-4-26b",
    messages=[
        {"role": "user", "content": "用一段话解释量子计算"}
    ],
    temperature=0.7,
    max_tokens=256,
)

print(response.choices[0].message.content)

如果你的应用原来接的是 OpenAI API,只要改 base_url 和模型名就行了,其他代码一行不用动。

GPU 显存规划

这是很多人踩坑的地方,直接看表:

模型精度最低显存推荐显存最大上下文
Gemma 4 E4BFP1610 GB16 GB32K
Gemma 4 E4BINT86 GB10 GB16K
Gemma 4 26BBF1652 GB80 GB (A100)32K
Gemma 4 26BINT828 GB40 GB (A100)32K
Gemma 4 31BBF1662 GB80 GB (A100)32K

小贴士: --gpu-memory-utilization 参数(默认 0.9)控制 vLLM 预分配多少显存。同一张卡上还有其他进程的话降到 0.8。显卡选购可以参考我们的硬件指南

多卡方案:

# Gemma 4 26B 跨 2 张 GPU
vllm serve google/gemma-4-26b \
  --tensor-parallel-size 2 \
  --host 0.0.0.0 \
  --port 8000

Docker 部署

生产环境用 Docker 是标准做法。完整的 docker-compose.yml

version: "3.8"

services:
  vllm:
    image: vllm/vllm-openai:latest
    ports:
      - "8000:8000"
    volumes:
      - model-cache:/root/.cache/huggingface
    environment:
      - HUGGING_FACE_HUB_TOKEN=${HF_TOKEN}
    command: >
      --model google/gemma-4-26b
      --host 0.0.0.0
      --port 8000
      --max-model-len 8192
      --gpu-memory-utilization 0.90
      --dtype bfloat16
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: 1
              capabilities: [gpu]
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
      interval: 30s
      timeout: 10s
      retries: 3

volumes:
  model-cache:

启动:

# 设置 HuggingFace token
export HF_TOKEN=your_token_here

# 启动服务
docker compose up -d

# 看日志
docker compose logs -f vllm

# 验证运行状态
curl http://localhost:8000/v1/models

Docker 的更多玩法可以看Docker 部署教程

批量推理

要处理大量数据——比如给一万份文档分类——批量推理比一条一条发请求高效得多:

from openai import OpenAI
import asyncio

client = OpenAI(base_url="http://localhost:8000/v1", api_key="none")

async def process_batch(items, max_concurrent=50):
    semaphore = asyncio.Semaphore(max_concurrent)
    
    async def process_one(item):
        async with semaphore:
            response = client.chat.completions.create(
                model="google/gemma-4-26b",
                messages=[{"role": "user", "content": item}],
                max_tokens=128,
            )
            return response.choices[0].message.content
    
    tasks = [process_one(item) for item in items]
    return await asyncio.gather(*tasks)

# 50 个并发处理 1000 条数据
items = ["分类这段文字: " + text for text in your_texts]
results = asyncio.run(process_batch(items))

vLLM 内部通过连续批处理自动把请求打包在一起,最大化 GPU 利用率。

负载均衡

高可用方案:多个 vLLM 实例 + 负载均衡器:

# nginx.conf
upstream vllm_backend {
    least_conn;
    server vllm-1:8000;
    server vllm-2:8000;
    server vllm-3:8000;
}

server {
    listen 80;

    location /v1/ {
        proxy_pass http://vllm_backend;
        proxy_set_header Host $host;
        proxy_read_timeout 120s;
    }
}

Vertex AI:托管方案

不想自己管服务器?Google 的 Vertex AI 提供托管的 Gemma 4 部署:

# 通过 gcloud CLI 部署
gcloud ai endpoints create \
  --region=us-central1 \
  --display-name=gemma4-endpoint

gcloud ai models upload \
  --region=us-central1 \
  --display-name=gemma-4-26b \
  --container-image-uri=us-docker.pkg.dev/vertex-ai/prediction/vllm-serve:latest \
  --artifact-uri=gs://your-bucket/gemma-4-26b

Vertex AI 帮你搞定扩缩容、监控、GPU 调度。按调用量付费,单次成本高一些但运维压力小很多。

免费方案可以看看 Google AI Studio 指南

监控

生产环境必须监控这些指标:

import requests

# vLLM 暴露 Prometheus 格式的指标
metrics = requests.get("http://localhost:8000/metrics").text

# 重点关注:
# vllm:num_requests_running    — 当前并发请求数
# vllm:num_requests_waiting    — 排队深度
# vllm:avg_generation_throughput — 每秒生成 token 数
# vllm:gpu_cache_usage_perc   — KV 缓存利用率

告警阈值建议:

  • 队列深度 > 100:需要加实例或换更大的 GPU
  • GPU 缓存 > 95%:减小 max-model-len 或加显存
  • p99 延迟 > 5s:该水平扩展了
  • 错误率 > 1%:检查 OOM 错误和模型健康状态

用 Grafana 画个仪表盘盯着这四个指标,大部分生产问题都能在用户发现之前抓到。

下一步

Gemma 4 AI

Gemma 4 AI

相关教程