使用 LLaMA-Factory 微调 LLaMA3

官网

https://llamafactory.readthedocs.io/zh-cn/latest/

快速开始:
https://zhuanlan.zhihu.com/p/695287607

1. 实验环境

1.1 机器

1.2 基座模型

基于原版的 LLaMA3 8B 模型:
https://www.modelscope.cn/models/LLM-Research/Meta-Llama-3.1-8B/files

(可选)配置 hf 国内镜像站:

pip install -U huggingface_hub
pip install huggingface-cli

export HF_ENDPOINT=https://hf-mirror.com

huggingface-cli download --resume-download /Llama3-8B --local-dir /root/autodl-tmp/models/Llama3-8B

2. LLaMA-Factory 框架

2.1 安装

git clone https://github.com/hiyouga/LLaMA-Factory.git
cd LLaMA-Factory
pip install -e .

2.2 准备训练数据

训练数据:

将训练数据放在 LLaMA-Factory/data/fintech.json
并且修改数据注册文件:LLaMA-Factory/data/dataset_info.json

"fintech": {
  "file_name": "fintech.json",
  "columns": {
    "prompt": "instruction",
    "query": "input",
    "response": "output",
    "history": "history"
  }
}

2.3 启动 Web UI

cd LLaMA-Factory
llamafactory-cli webui

2.4 微调模型

sft微调参数

名称 描述
model_name_or_path 模型名称或路径
stage 训练阶段,可选: rm(reward modeling), pt(pretrain), sft(Supervised Fine-Tuning), 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 每个设备上训练的批次大小
gradient_accumulation_steps 梯度积累步数
max_grad_norm 梯度裁剪阈值
learning_rate 学习率
lr_scheduler_type 学习率曲线,可选 linearcosinepolynomialconstant 等。
num_train_epochs 训练周期数
bf16 是否使用 bf16 格式
warmup_ratio 学习率预热比例
warmup_steps 学习率预热步数
push_to_hub 是否推送模型到 Huggingface

参数详解


模型配置


训练阶段


是否训练


微调类型


数据集相关


输出路径


日志与保存


训练参数


硬件加速


推送到模型仓库


命令

训练

CUDA_VISIBLE_DEVICES=0,1 指定显卡1和2

UDA_VISIBLE_DEVICES=0,1 llamafactory-cli train cust/train_llama3_lora_sft.yaml

对话

CUDA_VISIBLE_DEVICES=0 llamafactory-cli chat cust/chat_train_llama3_lora_sft.yaml  

模型合并

将 base model 与训练好的 LoRA Adapter 合并成一个新的模型。
⚠️ 不要使用量化后的模型或 quantization_bit 参数来合并 LoRA 适配器。

llamafactory-cli export cust/merge_llama3_lora_sft.yaml

使用合并后的模型进行预测,就不需要再加载 LoRA 适配器。