动手 1:环境与启动
谁该读这一篇? 准备真正把 SGLang 跑起来 + 验证一切就绪的工程师。 前置阅读:
01-overview/05-quickstart.md。 耗时: 40 分钟(含下载) 学完能: 1. 在 Linux + NVIDIA GPU 机器上稳定装好 SGLang; 2. 用check_env确认所有依赖; 3. 启动 7B 模型 server; 4. 跑通 OpenAI SDK / curl / DSL 三种客户端; 5. 看/metrics确认 cache_hit_rate 等指标正常。
1. 硬件 & 系统准备
# 看 GPU
nvidia-smi
# 期望输出:
# - 至少一张 sm_80+ 的卡(A100 / H100 / RTX 30xx 系列以上)
# - 驱动版本 535+
# - 显存 ≥ 24 GB(7B fp16)或 ≥ 12 GB(7B fp8)
# 看 CUDA
nvcc --version # 12.4 / 12.6 / 12.8
ldconfig -p | grep cuda
# 看系统
uname -a # Linux x86_64
cat /etc/os-release # Ubuntu 22.04 推荐
2. 装 SGLang(uv 推荐)
# 装 uv(一次性)
curl -LsSf https://astral.sh/uv/install.sh | sh
source ~/.bashrc
# 建独立 venv
mkdir -p ~/sglang-play && cd ~/sglang-play
uv venv --python 3.11
source .venv/bin/activate
# 装 SGLang 全套
uv pip install "sglang[all]" --upgrade
国内网络慢可以加镜像:
uv pip install "sglang[all]" \
--index-url https://pypi.tuna.tsinghua.edu.cn/simple
3. 环境自检
python -m sglang.check_env
预期输出(关键行):
sglang version: 0.x.y
torch: 2.x.y+cu124
cuda: 12.4
flashinfer: ...
triton: ...
NVIDIA driver: 535.xxx
GPU: NVIDIA H100 80GB HBM3
CUDA available: True
某项 FAIL 怎么办:
| FAIL | 处理 |
|---|---|
| FlashInfer 缺失 | pip install flashinfer-python==<匹配版本> |
| Triton 缺失 | pip install triton==3.x |
| CUDA mismatch | 重装对应 CUDA 版本的 PyTorch |
| NCCL 缺 | pip install nvidia-nccl-cu12 |
| 启动慢 | 看 nvidia-smi 是否被别的进程占;free -h 看 swap |
4. 起 server(最小化)
python -m sglang.launch_server \
--model-path Qwen/Qwen2.5-7B-Instruct \
--host 0.0.0.0 \
--port 30000 \
--mem-fraction-static 0.7 \
--enable-metrics
模型第一次下载约 15 GB(HF),约 3-5 分钟。 启动看到 "The server is fired up" 表示成功。
5. 测三种客户端
5.1 curl
curl http://localhost:30000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "Qwen/Qwen2.5-7B-Instruct",
"messages": [{"role": "user", "content": "1+1?"}],
"max_tokens": 32
}'
5.2 openai SDK
from openai import OpenAI
client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")
resp = client.chat.completions.create(
model="Qwen/Qwen2.5-7B-Instruct",
messages=[{"role": "user", "content": "你好"}],
max_tokens=64
)
print(resp.choices[0].message.content)
5.3 DSL
import sglang as sgl
sgl.set_default_backend(sgl.RuntimeEndpoint("http://localhost:30000"))
@sgl.function
def hi(s, name):
s += "User: 你好,我叫 " + name + "\nAssistant: "
s += sgl.gen("reply", max_tokens=32)
print(hi.run(name="Zoe")["reply"])
三种都能跑通才算装好。
6. 看 metrics
curl http://localhost:30000/metrics | grep -E "cache_hit|tokens_per|running_requests|e2e_request" | head
关键指标:
sglang:cache_hit_rate # 前缀命中率
sglang:gen_throughput # token/s
sglang:num_running_reqs # in-flight
sglang:num_used_tokens # KV pool 已用
sglang:e2e_request_latency_seconds_* # 端到端时延
7. Cache 命中验证
跑两次相同的请求,对比 TTFT:
import time, requests
prompt = "请详细介绍 vLLM 和 SGLang 的区别。" * 3
for i in range(3):
t0 = time.time()
requests.post("http://localhost:30000/v1/chat/completions", json={
"model": "...",
"messages": [{"role": "user", "content": prompt}],
"max_tokens": 10
}, timeout=60)
print(f"Trial {i}: {time.time()-t0:.3f}s")
第二、三次应该明显比第一次快(cache 命中)。
如果没有差异:检查 server 启动是否禁用了 prefix cache(--disable-radix-cache)。
8. Warmup 脚本(生产建议)
业务上线前发几个"热"请求,让 RadixCache 沉淀关键 system prompt + 让 CUDA Graph 走过几遍:
import requests
WARMUP_PROMPTS = [
"system prompt 1...",
"system prompt 2...",
# 业务真实 system prompt
]
for p in WARMUP_PROMPTS:
requests.post(URL, json={
"model": ..., "messages": [{"role": "system", "content": p}, ...],
"max_tokens": 1
})
9. 优雅关闭
# 优先 Ctrl-C
# 远程:
kill -TERM <pid>
# 强制:
pkill -9 -f sglang.launch_server # 残留进程清理
10. 常见问题排查
| 现象 | 处理 |
|---|---|
Init torch distributed begin 卡死 |
NCCL 端口被占;unset NCCL_* 或换端口 |
| OOM 启动失败 | 减 --mem-fraction-static 或换小模型 |
| HF 下载慢 | 配 HF_ENDPOINT=https://hf-mirror.com |
| 端口被占 | lsof -i :30000 看占用 |
| 启动 5 分钟+ | 第一次拉模型;模型大;CUDA Graph 多 |
11. 完成检查清单
- [ ]
nvidia-smi看到 GPU - [ ]
python -m sglang.check_env全 OK - [ ] Server 启动,看到 "ready to roll"
- [ ] curl 收到响应
- [ ] openai SDK 收到响应
- [ ] DSL 程序输出符合预期
- [ ]
/metrics有数据 - [ ] 重复请求命中 cache(第二次明显快)
8 项全 ✓ 才算 setup 完成。
12. 下一步
02-benchmark-throughput.md— 跑真实基准。03-debug-scheduler.md— 调试 scheduler 看现象。04-custom-frontend.md— 写自己的 DSL 程序。