Chapter 03
快速上手:XTuner CLI 三件套
XTuner 的入门体验是"找内置配置 + 一行命令"。本章用 InternLM2-7B 跑一个 LoRA SFT。
3.1三件套命令
| 命令 | 作用 |
|---|---|
xtuner train | 训练 |
xtuner chat | 交互推理 |
xtuner convert | 转 ckpt(pth ↔ HF ↔ adapter) |
xtuner copy-cfg | 把内置 config 复制出来改 |
xtuner list-cfg | 列出所有内置 config |
3.2找一个内置配置
xtuner list-cfg | grep internlm2_chat_7b
# 输出例:
# internlm2_chat_7b_full_alpaca_e3
# internlm2_chat_7b_qlora_alpaca_e3
# internlm2_chat_7b_qlora_oasst1_e3
# internlm2_chat_7b_qlora_open_platypus_e3
# ...
# 复制出来到本地(可以改)
xtuner copy-cfg internlm2_chat_7b_qlora_alpaca_e3 ./my_cfg/
3.3启动训练
# 单卡
xtuner train ./my_cfg/internlm2_chat_7b_qlora_alpaca_e3_copy.py
# 多卡(DeepSpeed)
NPROC_PER_NODE=8 xtuner train ./my_cfg/internlm2_chat_7b_qlora_alpaca_e3_copy.py \
--deepspeed deepspeed_zero2
训完产物:
./work_dirs/internlm2_chat_7b_qlora_alpaca_e3_copy/
├── epoch_1.pth # MMEngine 格式 ckpt
├── epoch_2.pth
├── epoch_3.pth
├── last_checkpoint # latest 路径
├── 20251128_120000.log # 训练日志
└── vis_data/ # tensorboard
3.4转成 HF 格式
# pth → HF adapter
xtuner convert pth_to_hf \
./my_cfg/internlm2_chat_7b_qlora_alpaca_e3_copy.py \
./work_dirs/internlm2_chat_7b_qlora_alpaca_e3_copy/epoch_3.pth \
./hf_adapter
# 合并 adapter 到 base
xtuner convert merge \
internlm/internlm2-chat-7b \
./hf_adapter \
./merged_model
3.5对话测试
xtuner chat ./merged_model --prompt-template internlm2_chat
# 或挂 LoRA
xtuner chat internlm/internlm2-chat-7b \
--adapter ./hf_adapter \
--prompt-template internlm2_chat
3.6关键概念:MMEngine config 是 Python 文件
XTuner 用 MMEngine 的 config 系统,配置文件是 Python 而非 YAML / TOML。所有字段都是 Python 表达式,灵活但学习曲线略陡(下章详讲)。
# 一个 config 是 Python
model = dict(
type=SupervisedFinetune,
use_varlen_attn=True,
llm=dict(type=AutoModelForCausalLM.from_pretrained, ...),
lora=dict(type=LoraConfig, r=64, ...),
)
3.7常见踩坑
| 现象 | 处理 |
|---|---|
| "FlashAttention2 not available" | 装 flash-attn;或在 config 里 use_varlen_attn=False |
| OOM 第一步 | 开 gradient_checkpointing;用 QLoRA 版 config |
| chat 出乱码 | prompt-template 选错;用 --prompt-template 指定对应模型 |
| convert merge 后效果差 | quantized base 不能直接 merge;先 dequantize |
3.8这章你需要带走的
- 三件套命令:
train / chat / convert; - 找配置:
xtuner list-cfg + xtuner copy-cfg; - 多卡用
NPROC_PER_NODE=8 xtuner train ... --deepspeed; - 训完
convert pth_to_hf+convert merge生成可用 HF 模型。