LLaMA Factory 是一个很方便的大模型微调平台,不需要写多少代码就能训练上百种模型。我最近用了一段时间,把从安装到推理的流程踩了一遍,这里记录一下。
环境准备
CUDA 安装
首先要确保 GPU 支持 CUDA,可以在 https://developer.nvidia.com/cuda-gpus 查一下。
检查 Linux 系统版本和 gcc:
uname -m && cat /etc/*release
# 输出类似 x86_64 DISTRIB_ID=Ubuntu DISTRIB_RELEASE=22.04
gcc --version
# gcc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
推荐装 CUDA 12.2,兼容性好一点。如果以前装过其他版本,先卸载干净:
# 如果 uninstaller 找不到,直接删目录也行
sudo rm -r /usr/local/cuda-12.1/
sudo apt clean && sudo apt autoclean
# 下载安装
wget https://developer.download.nvidia.com/compute/cuda/12.2.0/local_installers/cuda_12.2.0_535.54.03_linux.run
sudo sh cuda_12.2.0_535.54.03_linux.run
注意:安装时先别急着选 Driver,尤其是驱动版本和显卡不兼容的话容易出问题。装完用 nvcc -V 验证一下。
LLaMA Factory 安装
基础环境:Ubuntu 22.04, CUDA 12.x, Python 3.10, PyTorch 2.x。
conda create -n llama_factory python=3.10 -y
conda activate llama_factory
# 安装 PyTorch(根据 CUDA 版本调整)
conda install pytorch==2.2.2 torchvision==0.17.2 torchaudio==2.2.2 pytorch-cuda=11.8 -c pytorch -c nvidia
pip3 install torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
# 安装核心包
pip install llmtuner
# 克隆仓库
git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git
cd LLaMA-Factory
pip install -e ".[torch,metrics]"
如果装依赖时冲突,可以试试 pip install --no-deps -e .,跳过依赖检查,或者自己维护一个纯净环境。
验证安装:
llamafactory-cli version
启动 Web 界面:
CUDA_VISIBLE_DEVICES=0 GRADIO_SHARE=1 GRADIO_SERVER_PORT=7860 llamafactory-cli webui
离线模型下载
训练时直接用本地路径就行,比如从魔搭社区拉一个 Qwen 模型:
git clone https://www.modelscope.cn/Qwen/Qwen2.5-0.5B-Instruct.git
Windows 上的坑
如果在 Windows 上用 QLoRA,需要单独装 bitsandbytes:
pip install https://github.com/jllllll/bitsandbytes-windows-webui/releases/download/wheels/bitsandbytes-0.41.2.post2-py3-none-win_amd64.whl
FlashAttention-2 同理,去 这里 找对应版本。
数据该怎么准备
LLaMA Factory 支持多种数据集格式,所有定义都在 data/dataset_info.json 里。你要用它训练自己的数据,就得先在这个文件里注册一下。
指令监督微调(SFT)
最常用的格式是 alpaca,包含 instruction、input、output 三个字段,还可以带 history 和 system。例如:
[
{
"instruction": "计算这些物品的总费用。",
"input": "汽车 - $3000,衣服 - $100,书 - $20。",
"output": "总费用为 $3000 + $100 + $20 = $3120。"
}
]
多轮对话加上 history:
[
{
"instruction": "今天的天气怎么样?",
"input": "",
"output": "今天的天气不错,是晴天。",
"history": [
["今天会下雨吗?", "今天不会下雨,是个好天气。"],
["今天适合出去玩吗?", "非常适合,空气质量很好。"]
]
}
]
在 dataset_info.json 里这样描述:
"数据集名称": {
"file_name": "data.json",
"columns": {
"prompt": "instruction",
"query": "input",
"response": "output",
"system": "system",
"history": "history"
}
}
预训练
纯文本,一行一个 text 字段:
[
{"text": "document1"},
{"text": "document2"}
]
偏好数据集
用于 DPO/ORPO 训练,需要 chosen 和 rejected:
[
{
"instruction": "...",
"input": "...",
"chosen": "优质回答",
"rejected": "劣质回答"
}
]
KTO 数据集
加一个 kto_tag 字段,true/false 表示反馈好坏:
[
{
"instruction": "...",
"input": "...",
"output": "...",
"kto_tag": "true"
}
]
多模态数据
图像数据集,images 字段里写路径,注意和文本中 <image> 数量一致:
[
{
"instruction": "描述这张图片",
"output": "...",
"images": ["path/to/img.jpg"]
}
]
视频和音频也类似,用 videos 和 audios 字段。
用 YAML 启动训练
SFT 训练既可以用 WebUI,也可以直接用命令行。我自己更习惯 YAML 配置,调参方便。
一个典型的 LoRA 微调配置 llama3_lora_sft.yaml:
model_name_or_path: meta-llama/Meta-Llama-3-8B-Instruct
stage: sft
do_train: true
finetuning_type: lora
lora_target: all
dataset: identity,alpaca_en_demo
template: llama3
cutoff_len: 1024
max_samples: 1000
overwrite_cache: true
preprocessing_num_workers: 16
output_dir: saves/llama3-8b/lora/sft
logging_steps: 10
save_steps: 500
plot_loss: true
overwrite_output_dir: true
per_device_train_batch_size: 1
gradient_accumulation_steps: 8
learning_rate: 1.0e-4
num_train_epochs: 3.0
lr_scheduler_type: cosine
warmup_ratio: 0.1
bf16: true
ddp_timeout: 180000000
val_size: 0.1
per_device_eval_batch_size: 1
eval_strategy: steps
eval_steps: 500
然后运行:
llamafactory-cli train examples/train_lora/llama3_lora_sft.yaml
也可以直接覆盖参数:
llamafactory-cli train examples/train_lora/llama3_lora_sft.yaml \
learning_rate=1e-5 \
logging_steps=1
训练时要注意模型名、数据集、模板三者必须匹配,否则会报错。
常用参数说明:
| 名称 | 描述 |
|---|---|
| model_name_or_path | 模型名称或路径 |
| stage | 训练阶段:rm, pt, sft, PPO, DPO, KTO, ORPO |
| do_train | true 训练,false 评估 |
| finetuning_type | freeze, lora, full |
| lora_target | LoRA 目标模块,默认 all |
| dataset | 逗号分隔多个数据集 |
| template | 数据集模板,必须与模型对应 |
| output_dir | 输出路径 |
| logging_steps | 日志步数间隔 |
| save_steps | 断点保存间隔 |
| overwrite_output_dir | 是否覆盖输出目录 |
| per_device_train_batch_size | 每卡 batch size |
| gradient_accumulation_steps | 梯度累积步数 |
| max_grad_norm | 梯度裁剪阈值 |
| learning_rate | 学习率 |
| lr_scheduler_type | 学习率曲线:linear, cosine, polynomial, constant |
| num_train_epochs | 训练轮数 |
| bf16 | 是否使用 bf16 |
| warmup_ratio | 预热比例 |
| warmup_steps | 预热步数 |
| push_to_hub | 是否推送模型到 Huggingface |
合并与量化
LoRA 训练完会生成一个适配器权重,每次推理都要同时加载基座和适配器,很麻烦。可以把它俩合并成一个完整模型。
合并配置 merge_config.yaml:
model_name_or_path: meta-llama/Meta-Llama-3-8B-Instruct
adapter_name_or_path: saves/llama3-8b/lora/sft
template: llama3
finetuning_type: lora
export_dir: models/llama3_lora_sft
export_size: 2
export_device: cpu
export_legacy_format: false
执行合并:
llamafactory-cli export merge_config.yaml
一个容易踩的坑:合并时不要用量化模型或指定量化位数,否则会报错。 一定要用原始的未量化基座。
合并后如果想进一步压缩,可以用 GPTQ 等后训练量化。示例配置:
model_name_or_path: meta-llama/Meta-Llama-3-8B-Instruct
template: llama3
export_dir: models/llama3_gptq
export_quantization_bit: 4
export_quantization_dataset: data/c4_demo.json
export_size: 2
export_device: cpu
export_legacy_format: false
量化需要提供校准数据集,位数越高保存的质量越好,但体积也越大。4-bit 是常见的折中选择。
如果用的 QLoRA 训练,导出时不需要再量化,直接用合并方式导出即可。
推理几种方式
推理分为交互式对话和批量处理,底层可以选 Huggingface 或 vLLM 引擎。
原始模型推理
model_name_or_path: meta-llama/Meta-Llama-3-8B-Instruct
template: llama3
infer_backend: huggingface # 或 vllm
启动命令:
llamafactory-cli chat inference_config.yaml
# 或 Web 聊天
llamafactory-cli webchat inference_config.yaml
微调模型推理
需要额外指定适配器路径和微调类型:
model_name_or_path: meta-llama/Meta-Llama-3-8B-Instruct
adapter_name_or_path: saves/llama3-8b/lora/sft
template: llama3
finetuning_type: lora
infer_backend: huggingface
多模态模型
例如 llava:
llamafactory-cli webchat examples/inference/llava1_5.yaml
批量推理
用 vLLM 引擎处理整个数据集:
python scripts/vllm_infer.py --model_name_or_path path_to_merged_model --dataset alpaca_en_demo
还可以启动 API 服务:
API_PORT=8000 CUDA_VISIBLE_DEVICES=0 llamafactory-cli api examples/inference/llama3_lora_sft.yaml
调用示例:
from openai import OpenAI
client = OpenAI(api_key="0", base_url="http://0.0.0.0:8000/v1")
messages = [{"role": "user", "content": "Who are you?"}]
result = client.chat.completions.create(messages=messages, model="meta-llama/Meta-Llama-3-8B-Instruct")
print(result.choices[0].message)
评估模型效果
训练完了总得看看效果。LLaMA Factory 内置了 MMLU、C-Eval 等评测。
llamafactory-cli eval examples/train_lora/llama3_lora_eval.yaml
配置示例:
model_name_or_path: meta-llama/Meta-Llama-3-8B-Instruct
adapter_name_or_path: saves/llama3-8b/lora/sft
finetuning_type: lora
task: mmlu_test
template: fewshot
lang: en
n_shot: 5
save_dir: saves/llama3-8b/lora/eval
batch_size: 4
还可以评估 NLG 指标(BLEU、ROUGE),配置:
model_name_or_path: meta-llama/Meta-Llama-3-8B-Instruct
adapter_name_or_path: saves/llama3-8b/lora/sft
stage: sft
do_predict: true
finetuning_type: lora
eval_dataset: identity,alpaca_en_demo
template: llama3
cutoff_len: 2048
max_samples: 50
overwrite_cache: true
preprocessing_num_workers: 16
output_dir: saves/llama3-8b/lora/predict
overwrite_output_dir: true
per_device_eval_batch_size: 1
predict_with_generate: true
ddp_timeout: 180000000
运行后会在输出目录生成预测结果和分数。
评估常用参数:
| 参数 | 说明 |
|---|---|
| task | mmlu_test, ceval_validation, cmmlu_test |
| task_dir | 评估数据集目录,默认 evaluation |
| batch_size | 每卡 batch size,默认 4 |
| seed | 随机种子,默认 42 |
| lang | 评估语言:en, zh |
| n_shot | few-shot 样例数,默认 5 |
| save_dir | 结果保存路径 |
| download_mode | 数据集下载策略,默认复用已有 |
整个流程走下来,LLaMA Factory 确实能省很多事,尤其是 WebUI 对新手很友好。不过命令行 YAML 更可控,适合批量实验。建议先从 WebUI 上手,再切到命令行。


