Chapter 12
模型导出与 LMDeploy 部署
XTuner 的"原配"推理是 LMDeploy(同公司)。本章把 XTuner → HF → LMDeploy → 服务化链路过一遍。
12.1导出链路
XTuner .pth ──▶ HF adapter ──▶ HF merged ──▶ LMDeploy turbomind format
(训练) (xtuner convert pth_to_hf) (xtuner convert merge) (lmdeploy convert)
12.2convert pth_to_hf
xtuner convert pth_to_hf \
./cfg.py \
./work_dirs/.../epoch_3.pth \
./hf_adapter
# 产物
./hf_adapter/
├── adapter_config.json
├── adapter_model.safetensors
└── xtuner_config.py # 记录用了什么 config
12.3convert merge
xtuner convert merge \
internlm/internlm2-chat-7b \
./hf_adapter \
./merged
# 产物:标准 HF 目录,可以直接 from_pretrained
12.4LMDeploy 部署
# 装
pip install lmdeploy
# 直接服务化(PyTorch 后端)
lmdeploy serve api_server ./merged \
--server-port 23333 \
--tp 1
# 或先转 turbomind 格式(更快)
lmdeploy convert internlm2 ./merged \
--dst-path ./tm_format
lmdeploy serve api_server ./tm_format \
--backend turbomind \
--tp 2 \
--server-port 23333
12.5LMDeploy vs vLLM
| LMDeploy | vLLM | |
|---|---|---|
| 开发方 | 上海 AI Lab | UC Berkeley + 商业 |
| 核心引擎 | turbomind(C++/CUDA) | PagedAttention(Python+CUDA) |
| InternLM 系优化 | ★★★★★ | ★★★ |
| 通用模型覆盖 | ★★★★ | ★★★★★ |
| OpenAI API 兼容 | ✅ | ✅ |
| 多 LoRA | ✅ | ✅ |
InternLM / InternVL 模型用 LMDeploy 通常更快;其他模型 vLLM 兼容性更好。
12.6量化部署
# AWQ 量化
lmdeploy lite auto_awq ./merged \
--calib-dataset 'ptb' \
--calib-samples 128 \
--w-bits 4 \
--w-group-size 128 \
--work-dir ./merged-awq
# 部署量化版
lmdeploy serve api_server ./merged-awq \
--backend turbomind \
--model-format awq
12.7VL 模型部署
lmdeploy serve api_server ./merged_internvl \
--backend turbomind \
--vision-max-batch-size 8
# 测试
curl http://localhost:23333/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "internvl",
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": "描述图片"},
{"type": "image_url", "image_url": {"url": "https://..."}}
]
}]
}'
12.8性能基线
InternLM2-7B、A100-80GB、bs=32、prompt=512、output=128:
| 方案 | tok/s |
|---|---|
| HF transformers | ~3,500 |
| vLLM | ~12,000 |
| LMDeploy turbomind | ~15,000 |
| LMDeploy + AWQ | ~28,000 |
12.9常见错误
| 现象 | 处理 |
|---|---|
| convert merge 后效果变差 | QLoRA dequant 有 1pp 损失;可接受 |
| LMDeploy 不认识模型 | 用 turbomind 时要 convert;或用 pytorch 后端 |
| VL 推理速度慢 | VL 主要瓶颈在 ViT;增 vision_max_batch_size |
| AWQ 量化后乱码 | calib 数据跟训练域不一致;换 calib |
12.10这章你需要带走的
- 导出链路:pth → adapter → merge → (optional) turbomind / awq;
- InternLM / InternVL 模型用 LMDeploy 最优,其他用 vLLM;
- AWQ 量化能再 2× 加速;
- OpenAI 兼容 API 用
lmdeploy serve api_server。