SGLang 高性能 LLM 推理框架
一句话概述
SGLang 是由 UC Berkeley 和 LMSYS 团队开发的开源高性能大模型推理框架,通过 RadixAttention 实现自动 KV Cache 复用,吞吐量最高可达竞品的 6 倍,目前已部署在全球超过 40 万张 GPU 上。
核心知识点表格
| 知识点 | 说明 |
|---|
| 项目地址 | https://github.com/sgl-project/sglang |
| 最新版本 | v0.5.11(2026年5月) |
| 核心技术 | RadixAttention(基数树自动 KV Cache 复用) |
| 适用场景 | LLM 推理服务、Agent 工作流、多模态模型 |
| 许可证 | Apache 2.0 |
| 开发语言 | Python + C++ |
| 硬件支持 | NVIDIA GPU、AMD GPU、Google TPU |
| 竞品对比 | vLLM、TensorRT-LLM、TGI |
| 企业用户 | xAI、AMD、NVIDIA、Intel、LinkedIn、Cursor、Oracle Cloud |
安装与配置
前置要求
# 检查 NVIDIA 驱动和 CUDA 版本
nvidia-smi # 需要 CUDA 12.0 及以上
# 检查 Python 版本(需要 3.9+)
python3 --version
方式一:pip 安装(推荐)
# 创建虚拟环境(避免依赖冲突)
conda create -n sglang python=3.11 # 创建名为 sglang 的 conda 环境
conda activate sglang # 激活环境
# 安装 SGLang(会自动安装 PyTorch 等依赖)
pip install "sglang[all]" # [all] 表示安装所有可选依赖
# 如果只需要 OpenAI 兼容的推理服务器
pip install "sglang[srt]" # srt = SGLang Runtime
方式二:Docker 安装
# 拉取官方 Docker 镜像(包含 CUDA 运行时)
docker pull lmsysorg/sglang:latest
# 启动容器(挂载 GPU 并映射端口)
docker run --gpus all \ # 使用所有 GPU
-p 30000:30000 \ # 映射推理服务端口
-v ~/.cache/huggingface:/root/.cache/huggingface \ # 共享模型缓存
lmsysorg/sglang:latest \
python3 -m sglang.launch_server \ # 启动推理服务
--model-path meta-llama/Llama-3.1-8B-Instruct \ # 指定模型
--host 0.0.0.0 \ # 监听所有网络接口
--port 30000 # 监听端口
方式三:从源码编译
# 克隆仓库
git clone https://github.com/sgl-project/sglang.git # 下载源码
cd sglang # 进入项目目录
# 安装依赖并编译
pip install -e ".[all]" # -e 表示可编辑模式安装,方便开发调试
基本使用
启动推理服务器
# 启动 SGLang 推理服务(OpenAI 兼容 API)
python3 -m sglang.launch_server \
--model-path meta-llama/Llama-3.1-8B-Instruct \ # HuggingFace 模型路径
--host 0.0.0.0 \ # 监听地址,0.0.0.0 表示所有网卡
--port 30000 \ # 端口号
--tp 1 # tensor parallelism,张量并行数(GPU数量)
使用 OpenAI 兼容 API 调用
import openai # 使用 OpenAI 的 Python SDK
# 创建客户端,指向本地 SGLang 服务
client = openai.Client(
base_url="http://localhost:30000/v1", # SGLang 的 API 地址
api_key="EMPTY" # SGLang 不需要 API key,随便填
)
# 发送对话请求(和调用 OpenAI API 完全一样)
response = client.chat.completions.create(
model="meta-llama/Llama-3.1-8B-Instruct", # 模型名
messages=[
{"role": "system", "content": "你是一个有帮助的助手。"}, # 系统提示
{"role": "user", "content": "什么是宏基因组学?"} # 用户问题
],
temperature=0.7, # 温度参数,越高回答越随机
max_tokens=512 # 最大生成长度
)
print(response.choices[0].message.content) # 打印回答内容
使用 curl 调用
# 用 curl 发送请求(适合快速测试)
curl http://localhost:30000/v1/chat/completions \
-H "Content-Type: application/json" \ # 请求头:JSON 格式
-d '{
"model": "meta-llama/Llama-3.1-8B-Instruct",
"messages": [{"role": "user", "content": "Hello!"}],
"temperature": 0.7,
"max_tokens": 128
}'
批量推理
import sglang as sgl # 导入 SGLang 原生 SDK
# 定义一个推理函数(使用 SGLang 的装饰器语法)
@sgl.function
def text_qa(s, question):
s += sgl.system("你是一个生物信息学专家。") # 设置系统角色
s += sgl.user(question) # 添加用户问题
s += sgl.assistant(sgl.gen("answer", max_tokens=256)) # 生成回答
# 批量处理多个问题
questions = [
"什么是 16S rRNA 测序?",
"宏基因组 binning 是什么意思?",
"Alpha 多样性有哪些指标?"
]
# 并行执行所有问题(SGLang 自动批处理)
states = text_qa.run_batch(
[{"question": q} for q in questions], # 构造参数列表
progress_bar=True # 显示进度条
)
# 打印所有回答
for i, state in enumerate(states):
print(f"问题 {i+1}: {questions[i]}") # 打印问题
print(f"回答: {state['answer']}\n") # 打印对应回答
高级用法
多 GPU 张量并行
# 使用 4 张 GPU 进行张量并行(大模型必须分片到多卡)
python3 -m sglang.launch_server \
--model-path meta-llama/Llama-3.1-70B-Instruct \ # 70B 大模型
--tp 4 \ # 4 卡并行
--mem-fraction-static 0.85 # 85% 显存用于 KV Cache
结构化输出(JSON 模式)
import openai # 使用 OpenAI SDK
import json # JSON 解析
client = openai.Client(base_url="http://localhost:30000/v1", api_key="EMPTY")
# 定义 JSON Schema(约束输出格式)
json_schema = {
"type": "object",
"properties": {
"gene_name": {"type": "string"}, # 基因名,字符串类型
"function": {"type": "string"}, # 功能描述
"organism": {"type": "string"}, # 来源物种
"confidence": {"type": "number"} # 置信度,数值类型
},
"required": ["gene_name", "function"] # 必填字段
}
# 请求结构化输出
response = client.chat.completions.create(
model="meta-llama/Llama-3.1-8B-Instruct",
messages=[{"role": "user", "content": "分析基因 lacZ 的功能"}],
response_format={
"type": "json_schema", # 使用 JSON Schema 模式
"json_schema": {
"name": "gene_info", # Schema 名称
"schema": json_schema # 上面定义的 Schema
}
}
)
result = json.loads(response.choices[0].message.content) # 解析 JSON
print(result) # 输出结构化结果
投机解码(Speculative Decoding)
# 使用小模型做草稿、大模型验证,加速生成
python3 -m sglang.launch_server \
--model-path meta-llama/Llama-3.1-70B-Instruct \ # 主模型(大)
--speculative-model meta-llama/Llama-3.1-8B-Instruct \ # 草稿模型(小)
--speculative-num-draft-tokens 5 \ # 每次草稿生成 5 个 token
--tp 4 # 4 卡并行
Prefill-Decode 分离部署
# 分离预填充(Prefill)和解码(Decode)节点
# 适合大规模生产环境,可以独立扩缩容
# 节点1:Prefill 节点(处理输入 prompt)
python3 -m sglang.launch_server \
--model-path meta-llama/Llama-3.1-70B-Instruct \
--tp 4 \
--disagg-mode prefill # 设为 prefill 模式
# 节点2:Decode 节点(生成输出 token)
python3 -m sglang.launch_server \
--model-path meta-llama/Llama-3.1-70B-Instruct \
--tp 4 \
--disagg-mode decode # 设为 decode 模式
常见报错与解决
| 报错信息 | 原因 | 解决方法 |
|---|
CUDA out of memory | GPU 显存不足 | 减小 --mem-fraction-static(如 0.7)或使用更多 GPU(增加 --tp) |
Model not found | 模型路径错误或未下载 | 检查模型路径,先用 huggingface-cli download 下载模型 |
Connection refused | 服务未启动或端口被占用 | 检查服务是否正在运行,换一个端口 |
torch.cuda.is_available() = False | CUDA 未正确安装 | 重新安装 CUDA 版本匹配的 PyTorch |
Tokenizer not found | 分词器文件缺失 | 确保模型目录下有 tokenizer.json 或 tokenizer.model |
tp size > num GPUs | 张量并行数大于可用 GPU 数 | 减小 --tp 值或增加 GPU |
速查表
# === SGLang 常用命令速查 ===
# 启动服务(单卡)
python3 -m sglang.launch_server --model-path <模型路径> --port 30000
# 启动服务(多卡并行)
python3 -m sglang.launch_server --model-path <模型路径> --tp <GPU数>
# 启动服务(指定量化)
python3 -m sglang.launch_server --model-path <模型路径> --quantization awq
# 查看支持的参数
python3 -m sglang.launch_server --help
# 健康检查
curl http://localhost:30000/health
# 获取模型信息
curl http://localhost:30000/v1/models
# 文本补全 API
curl http://localhost:30000/v1/completions -d '{"model":"...","prompt":"Hello"}'
# 对话补全 API
curl http://localhost:30000/v1/chat/completions -d '{"model":"...","messages":[...]}'
与同类工具对比
| 特性 | SGLang | vLLM | TensorRT-LLM | TGI |
|---|
| 核心优势 | RadixAttention 前缀缓存 | PagedAttention 内存管理 | NVIDIA 硬件深度优化 | HuggingFace 生态整合 |
| 适合场景 | Agent/共享前缀工作流 | 通用云端推理 | NVIDIA GPU 极致性能 | HuggingFace 模型快速部署 |
| 硬件支持 | NVIDIA + AMD + TPU | NVIDIA + AMD + TPU | 仅 NVIDIA | NVIDIA + AMD |
| 上手难度 | 中等 | 简单 | 较难(需要编译) | 简单 |
| 结构化输出 | 原生支持 | 支持 | 有限 | 支持 |
| 投机解码 | 支持 | 支持 | 支持 | 支持 |
| 社区活跃度 | 非常活跃 | 非常活跃 | 活跃 | 活跃 |
| 生产就绪度 | 高(40万+ GPU 部署) | 高 | 高 | 高 |
选择建议:如果你的工作流涉及大量共享前缀(如 Agent 多轮对话、RAG 检索),SGLang 的 RadixAttention 能带来显著性能提升。如果追求通用性和易用性,vLLM 是更稳妥的选择。