Axolotl 微调框架 — 用 YAML 配置驱动 LLM 微调的一站式工具¶
一句话说明¶
Axolotl 是社区最流行的开源微调框架,只需一个 YAML 文件就能完成 LoRA / QLoRA / 全量微调,支持 LLaMA、Mistral、Qwen、Gemma 等几乎所有主流模型。
安装与配置¶
# 方式1:pip 安装(推荐 Python 3.11+)
pip install axolotl # 安装基础包
pip install axolotl[flash-attn,deepspeed] # 安装 Flash Attention + DeepSpeed 加速
# 方式2:从源码安装(获取最新功能)
git clone https://github.com/axolotl-ai-cloud/axolotl
cd axolotl
pip install -e '.[flash-attn,deepspeed]'
# 方式3:Docker 镜像(省去环境配置麻烦)
docker pull winglian/axolotl:main-latest
核心用法¶
# 用法只需两步:1.写 YAML 配置 2.运行训练
accelerate launch -m axolotl.cli.train config.yml
# 推理测试
accelerate launch -m axolotl.cli.inference config.yml \
--lora_model_dir="./outputs/lora-out"
# 合并 LoRA 权重到基座模型
accelerate launch -m axolotl.cli.merge_lora config.yml \
--lora_model_dir="./outputs/lora-out"
参数详解¶
下面是一个典型的 config.yml 文件:
# 基座模型路径(本地路径或 HuggingFace 仓库名)
base_model: meta-llama/Llama-3.2-8B-Instruct
# 模型类型,决定如何加载
model_type: LlamaForCausalLM
tokenizer_type: AutoTokenizer
# 量化设置(节省显存)
load_in_4bit: true # 用 4bit 量化加载基座模型
adapter: qlora # 使用 QLoRA 方法(量化+LoRA)
# LoRA 超参数
lora_r: 16 # LoRA 秩,越大效果越好但越慢
lora_alpha: 32 # LoRA 缩放系数,一般设为 lora_r 的2倍
lora_dropout: 0.05 # Dropout 防止过拟合
lora_target_modules: # 对哪些层加 LoRA
- q_proj
- v_proj
# 数据集配置
datasets:
- path: mhenrichsen/alpaca_data # HuggingFace 数据集名
type: alpaca # 数据集格式(alpaca/sharegpt/oasst 等)
# 训练超参数
sequence_len: 2048 # 最大序列长度(影响显存用量)
sample_packing: true # 把多个短样本打包成一个序列(提升效率)
pad_to_sequence_len: true
micro_batch_size: 2 # 单张 GPU 的 batch 大小
gradient_accumulation_steps: 4 # 梯度累积(等效 batch = micro*grad_accum)
num_epochs: 3 # 训练轮数
learning_rate: 0.0002 # 学习率
# 输出目录
output_dir: ./outputs/lora-out
# 日志(可选)
wandb_project: my-finetune # W&B 项目名(需要 wandb login)
实战案例¶
# 案例:用 Alpaca 格式数据微调 Llama-3.2-8B(单卡 4090 可跑)
# 1. 准备数据(Alpaca 格式,每条数据含 instruction/input/output)
cat > my_data.jsonl << 'EOF'
{"instruction": "解释什么是 LoRA", "input": "", "output": "LoRA 是低秩适配方法..."}
EOF
# 2. 在 config.yml 中指向本地数据
# datasets:
# - path: my_data.jsonl
# type: alpaca
# 3. 启动训练(单卡)
python -m axolotl.cli.train config.yml
# 4. 多卡训练(4卡)
accelerate launch --num_processes=4 -m axolotl.cli.train config.yml
常见报错与解决¶
| 报错信息 | 原因 | 解决方法 |
|---|---|---|
CUDA out of memory | 显存不足 | 降低 sequence_len 或 micro_batch_size |
ValueError: sample_packing requires... | 数据集不支持打包 | 关闭 sample_packing: false |
Flash attention not found | 未安装 flash-attn | pip install flash-attn --no-build-isolation |
Cannot find module axolotl | 安装路径问题 | 用 pip install -e . 从源码重装 |
| 训练 loss 为 0 或 nan | 数据格式错误 | 检查数据集格式是否与 type 一致 |
速查表¶
| 功能 | 命令/参数 |
|---|---|
| 启动训练 | accelerate launch -m axolotl.cli.train config.yml |
| 推理测试 | accelerate launch -m axolotl.cli.inference config.yml |
| 合并权重 | accelerate launch -m axolotl.cli.merge_lora config.yml |
| 4bit 量化 | load_in_4bit: true + adapter: qlora |
| 数据格式 | alpaca / sharegpt / oasst / completion |
| 官方文档 | https://axolotl-ai-cloud.github.io/axolotl/ |