首页
/ LlamaFactory 微调示例实战指南:从 LoRA、QLoRA 到全参数训练、模型导出与推理的完整工作流

LlamaFactory 微调示例实战指南:从 LoRA、QLoRA 到全参数训练、模型导出与推理的完整工作流

2026-09-04 18:26:38作者:姚月梅Lane

本文围绕 examples/README_zh.md 展开,系统梳理 LlamaFactory 官方示例脚本覆盖的大模型微调全流程:LoRA/QLoRA/全参数训练、多机与弹性分布式、DeepSpeed/Ray 后端、LoRA 合并与量化导出、vLLM 推理评估,以及 GaLore、Muon、PiSSA 等高级训练技巧。读完本文后,你可以直接复制运行示例中的每一条命令,并能看懂其背后 llamafactory-cli 启动器与示例配置文件的实际工作机制。

所有示例命令都要求在 LlamaFactory 仓库根目录下执行。

基本用法:一条命令启动训练

LlamaFactory 统一入口是 llamafactory-cli(源码入口为 src/llamafactory/cli.py,可分派到 trainapichatexportwebchatwebuienvversion 等子命令,其中 lmfllamafactory-cli 的快捷别名)。

计算设备选择:GPU 用 CUDA_VISIBLE_DEVICES,NPU 用 ASCEND_RT_VISIBLE_DEVICES 环境变量选择可见设备;不设置时,LlamaFactory 默认使用所有可见的计算设备(设备数量探测逻辑在 src/llamafactory/launcher.py 中的 get_device_count())。

基础用法——直接加载一个示例 YAML 配置文件:

llamafactory-cli train examples/train_lora/qwen3_lora_sft.yaml

高级用法——在命令行追加 key=value 形式的参数,覆盖 YAML 中的默认值:

CUDA_VISIBLE_DEVICES=0,1 llamafactory-cli train examples/train_lora/qwen3_lora_sft.yaml \
    learning_rate=1e-5 \
    logging_steps=1

也可以直接运行仓库中的 Shell 示例(等价于把同一份参数写成 --key value 长选项形式):

bash examples/train_lora/qwen3_lora_sft.sh

示例配置文件长什么样

以 LoRA 指令微调示例 examples/train_lora/qwen3_lora_sft.yaml 为例,其核心字段可分为五块:

### model
model_name_or_path: Qwen/Qwen3-4B-Instruct-2507
trust_remote_code: true

### method
stage: sft                    # 训练阶段:pt / sft / rm / ppo / dpo / kto
finetuning_type: lora          # 微调方法:lora / full / freeze
lora_rank: 8
lora_target: all               # all 表示对所有线性层注入 LoRA

### dataset
dataset: identity,alpaca_en_demo   # 数据集在 data/dataset_info.json 中注册
template: qwen3_nothink            # 模型对应的对话模板
cutoff_len: 2048
max_samples: 1000
preprocessing_num_workers: 16
dataloader_num_workers: 4

### output
output_dir: saves/qwen3-4b/lora/sft
logging_steps: 10
save_steps: 500
plot_loss: true
report_to: none                  # choices: [none, wandb, tensorboard, swanlab, mlflow]

### train
per_device_train_batch_size: 1
gradient_accumulation_steps: 8   # 等效全局 batch size = 8 × 卡数
learning_rate: 1.0e-4
num_train_epochs: 3.0
lr_scheduler_type: cosine
warmup_ratio: 0.1
bf16: true

从源码结构看,这些键会分别被 src/llamafactory/hparams/ 下的 model_args.pydata_args.pyfinetuning_args.pytraining_args.py 解析,stage 字段决定后续走哪条训练工作流(sft/dpo/kto/rm 等,见 src/llamafactory/train/tuner.py)。

LoRA 微调

LoRA 微调是显存开销最小的方案之一:通过 finetuning_type: lora 只训练低秩增量参数。以下示例均以 4B 级模型演示。

(增量)预训练

stage: pretrain 用于在纯文本语料上做继续预训练:

llamafactory-cli train examples/train_lora/qwen3_lora_pretrain.yaml

指令监督微调(SFT)

最常用的入口,对应上文解析过的 examples/train_lora/qwen3_lora_sft.yaml

llamafactory-cli train examples/train_lora/qwen3_lora_sft.yaml

多模态指令监督微调

视觉语言模型(VLM)同样走同一套 CLI,只需换成 VLM 配置(模型、模板、数据集均针对图文数据设置):

llamafactory-cli train examples/train_lora/qwen3vl_lora_sft.yaml

DPO / ORPO / SimPO 偏好对齐训练

偏好对齐三算法由同一配置驱动,通过参数切换:

llamafactory-cli train examples/train_lora/qwen3_lora_dpo.yaml

多模态版本:

llamafactory-cli train examples/train_lora/qwen3vl_lora_dpo.yaml

奖励模型训练与 KTO 训练

stage: rm 训练奖励模型,stage: kto 则使用 KTO 损失做对齐,两者均支持 LoRA:

llamafactory-cli train examples/train_lora/qwen3_lora_reward.yaml
llamafactory-cli train examples/train_lora/qwen3_lora_kto.yaml

预处理数据集(tokenized_path)

对于大数据集,推荐先用同一命令做一次 tokenize 缓存,之后再在训练配置中通过 tokenized_path 加载预处理结果,避免每次训练重复处理语料。示例 examples/train_lora/qwen3_preprocess.yaml 中的关键配置:

### dataset
dataset: identity,alpaca_en_demo
template: qwen3_nothink
cutoff_len: 2048
max_samples: 1000
preprocessing_num_workers: 16
tokenized_path: saves/qwen3-4b/dataset/sft   # tokenize 结果落盘位置
llamafactory-cli train examples/train_lora/qwen3_preprocess.yaml

从源码看,tokenized_path 定义在 src/llamafactory/hparams/data_args.py 中,并由 src/llamafactory/data/loader.py 负责缓存的保存与复用。

多机指令监督微调

固定两节点的场景下,在每台节点上执行对应 rank 的命令(FORCE_TORCHRUN=1 强制走 torchrun 分布式启动):

FORCE_TORCHRUN=1 NNODES=2 NODE_RANK=0 MASTER_ADDR=192.168.0.1 MASTER_PORT=29500 llamafactory-cli train examples/train_lora/qwen3_lora_sft.yaml
FORCE_TORCHRUN=1 NNODES=2 NODE_RANK=1 MASTER_ADDR=192.168.0.1 MASTER_PORT=29500 llamafactory-cli train examples/train_lora/qwen3_lora_sft.yaml

支持弹性和容错的多机微调

弹性场景下,节点数允许在 MIN_NNODES:MAX_NNODES 范围内浮动,单节点最多因错误重启 MAX_RESTARTS 次;RDZV_ID 必须是整个作业所有节点共享的唯一作业 ID。在每个节点执行:

FORCE_TORCHRUN=1 MIN_NNODES=1 MAX_NNODES=3 MAX_RESTARTS=3 RDZV_ID=llamafactory MASTER_ADDR=192.168.0.1 MASTER_PORT=29500 llamafactory-cli train examples/train_full/qwen3_full_sft.yaml

这一能力的实现可以直接在 src/llamafactory/launcher.py 中看到:当检测到 RDZV_ID 环境变量时,启动器会拼接出带 --rdzv-backend c10d --rdzv-endpoint ... --max-restarts ...torchrun 命令,并把 nnodes 写成 min: max 的弹性区间;未设置 RDZV_ID 时则走普通的固定节点 torchrun 分支。更多语义细节可参考 PyTorch 官方的 elastic run 文档。

使用 DeepSpeed ZeRO-3 平均分配显存

配置 examples/train_lora/qwen3_lora_sft_ds3.yaml 相比普通 LoRA 示例多了一行 deepspeed: examples/deepspeed/ds_z3_config.json,用于把优化器状态、梯度与参数分片到各卡,从而摊薄单卡显存:

FORCE_TORCHRUN=1 llamafactory-cli train examples/train_lora/qwen3_lora_sft_ds3.yaml

仓库 examples/deepspeed/ 下同时提供 ds_z0_config.jsonds_z2_config.jsonds_z3_config.jsonds_z2_offload_config.jsonds_z3_offload_config.json 等 DeepSpeed 配置,可在 YAML 中按需替换。

使用 Ray 在 4 张 GPU 上微调

示例 examples/train_lora/qwen3_lora_sft_ray.yamlray_num_workers: 4 指定参与训练的 GPU 数量,并支持通过 ray_init_kwargs 注入运行时环境变量或额外 pip 依赖:

USE_RAY=1 llamafactory-cli train examples/train_lora/qwen3_lora_sft_ray.yaml

QLoRA 微调

QLoRA 在加载阶段对基座模型做量化,再训练 LoRA,进一步压低显存。仓库提供了多种量化后端示例,位于 examples/train_qlora/

4/8 比特 Bitsandbytes / HQQ / EETQ 量化(推荐)

llamafactory-cli train examples/train_qlora/qwen3_lora_sft_otfq.yaml

配置 examples/train_qlora/qwen3_lora_sft_otfq.yaml 中对应的两个关键字段及取值范围:

quantization_bit: 4    # choices: [8 (bnb/hqq/eetq), 4 (bnb/hqq), 3 (hqq), 2 (hqq)]
quantization_method: bnb   # choices: [bnb, hqq, eetq]

NPU 上的 4 比特 Bitsandbytes 量化

面向昇腾 NPU 的量化微调:

llamafactory-cli train examples/train_qlora/qwen3_lora_sft_bnb_npu.yaml

GPTQ、AWQ 与 AQLM 量化

# 4/8 比特 GPTQ
llamafactory-cli train examples/train_qlora/llama3_lora_sft_gptq.yaml
# 4 比特 AWQ
llamafactory-cli train examples/train_qlora/llama3_lora_sft_awq.yaml
# 2 比特 AQLM
llamafactory-cli train examples/train_qlora/llama3_lora_sft_aqlm.yaml

注意 GPTQ/AWQ/AQLM 路径要求基座模型本身已经以对应格式量化(model_name_or_path 指向量化后的模型),而 bnb/HQQ/EETQ 属于训练时在线量化,直接加载原精度模型即可。

全参数微调

全参数微调(finetuning_type: full)训练所有参数,通常配合 DeepSpeed 使用。示例配置 examples/train_full/qwen3_full_sft.yaml 的关键差异点:学习率降到 1.0e-5gradient_accumulation_steps: 2,并显式挂上 deepspeed: examples/deepspeed/ds_z3_config.json

单机指令监督微调

FORCE_TORCHRUN=1 llamafactory-cli train examples/train_full/qwen3_full_sft.yaml

多机指令监督微调

FORCE_TORCHRUN=1 NNODES=2 NODE_RANK=0 MASTER_ADDR=192.168.0.1 MASTER_PORT=29500 llamafactory-cli train examples/train_full/qwen3_full_sft.yaml
FORCE_TORCHRUN=1 NNODES=2 NODE_RANK=1 MASTER_ADDR=192.168.0.1 MASTER_PORT=29500 llamafactory-cli train examples/train_full/qwen3_full_sft.yaml

多模态指令监督微调

FORCE_TORCHRUN=1 llamafactory-cli train examples/train_full/qwen3vl_full_sft.yaml

src/llamafactory/launcher.py 的启动逻辑看,FORCE_TORCHRUN=1 会强制进入 torchrun 分支;即使不设置该变量,只要探测到多张 GPU 且未使用 Ray/KTransformers,启动器也会自动升级为多卡分布式训练。

合并 LoRA 适配器与模型量化

训练完成后,llamafactory-cli export 子命令(实现在 src/llamafactory/train/tuner.pyexport_model)承担合并与导出工作。

合并 LoRA 适配器

注意:请勿使用量化后的模型或带 quantization_bit 参数的配置来合并 LoRA 适配器。

llamafactory-cli export examples/merge_lora/qwen3_lora_sft.yaml

使用 AutoGPTQ 量化模型

llamafactory-cli export examples/merge_lora/qwen3_gptq.yaml

保存 Ollama 配置文件

导出已合并模型的 Ollama 配置,便于在 Ollama 中直接加载微调成果:

llamafactory-cli export examples/merge_lora/qwen3_full_sft.yaml

推理 LoRA 模型

使用 vLLM 多卡推理评估

scripts/vllm_infer.py 支持批量生成预测结果,随后用 scripts/eval_bleu_rouge.py 计算 BLEU/ROUGE 指标:

python scripts/vllm_infer.py --model_name_or_path Qwen/Qwen3-4B-Instruct-2507 --template qwen3_nothink --dataset alpaca_en_demo
python scripts/eval_bleu_rouge.py generated_predictions.jsonl

命令行对话框与浏览器对话框

# 终端交互
llamafactory-cli chat examples/inference/qwen3_lora_sft.yaml
# Web 交互(Gradio 界面)
llamafactory-cli webchat examples/inference/qwen3_lora_sft.yaml

启动 OpenAI 风格 API

llamafactory-cli api examples/inference/qwen3_lora_sft.yaml

API 服务实现在 src/llamafactory/api/app.py,推理引擎可切换 HF / vLLM / SGLang(见 src/llamafactory/chat/ 下的各 engine 实现),配套的调用示例脚本位于 scripts/api_example/

杂项:高级训练方法与技巧

examples/extras/ 目录汇集了若干论文级训练技巧,全部复用同一套 YAML + CLI 接口。

显存友好的全参数训练方法

  • GaLore:梯度低秩投影,以近全参数效果降低全参数训练的显存占用:

    llamafactory-cli train examples/extras/galore/llama3_full_sft.yaml
    
  • APOLLO:逐层低秩梯度优化:

    llamafactory-cli train examples/extras/apollo/llama3_full_sft.yaml
    
  • BAdam:自适应预算的块级参数微调:

    llamafactory-cli train examples/extras/badam/llama3_full_sft.yaml
    
  • Adam-mini:低秩二阶矩估计的迷你优化器:

    llamafactory-cli train examples/extras/adam_mini/qwen2_full_sft.yaml
    
  • Muon:基于 Newton-Schulz 近似的矩阵优化器(内核实现见 src/llamafactory/third_party/muon/muon.py):

    llamafactory-cli train examples/extras/muon/qwen2_full_sft.yaml
    

对应的依赖包可在 requirements/ 目录中按需安装,例如 requirements/galore.txtrequirements/apollo.txtrequirements/badam.txtrequirements/adam-mini.txt

LoRA 变体

  • LoRA+:对 A/B 矩阵使用不同学习率:

    llamafactory-cli train examples/extras/loraplus/llama3_lora_sft.yaml
    
  • PiSSA:先用 SVD 初始化 LoRA 方向再微调(可先运行 scripts/pissa_init.py 做初始化,示例目录内也有 examples/extras/pissa/init.sh):

    llamafactory-cli train examples/extras/pissa/llama3_lora_sft.yaml
    

其他技巧

  • 深度混合微调(MoD)

    llamafactory-cli train examples/extras/mod/llama3_full_sft.yaml
    
  • LLaMA-Pro 风格扩层微调:先用 examples/extras/llama_pro/expand.sh 扩展层数,再冻结原层训练新层:

    bash examples/extras/llama_pro/expand.sh
    llamafactory-cli train examples/extras/llama_pro/llama3_freeze_sft.yaml
    
  • FSDP+QLoRA 微调(FSDP 加载量化模型 + LoRA):

    bash examples/extras/fsdp_qlora/train.sh
    
  • **OFT(正交细调)**与 QOFT(量化 + OFT,NPU 版)

    llamafactory-cli train examples/extras/oft/llama3_oft_sft.yaml
    llamafactory-cli train examples/extras/qoft/llama3_oft_sft_bnb_npu.yaml
    

启动机制小结与延伸阅读

把上面的示例串起来看,LlamaFactory 的示例脚本体系遵循一条清晰的规则链:

  1. 单卡/少量场景:直接 llamafactory-cli train <yaml>,参数可用 key=value 覆盖;
  2. 多卡多机:由 src/llamafactory/launcher.py 自动或经 FORCE_TORCHRUN=1 转交给 torchrun,固定拓扑用 NNODES/NODE_RANK/MASTER_ADDR/MASTER_PORT,弹性容错用 RDZV_ID + MIN_NNODES/MAX_NNODES/MAX_RESTARTS
  3. 异构后端:DeepSpeed 配置经 YAML 的 deepspeed 字段挂接(examples/deepspeed/),Ray 经 USE_RAY=1ray_num_workers 启用;
  4. 产出侧export 负责合并/量化/Ollama 配置导出,chat/webchat/api 负责交互与对外服务,scripts/vllm_infer.py 负责批量评估。

仓库内还有 examples/v1/(面向新数据引擎/训练管线的 FSDP2、动态 batching、padding-free 等实验性配置)以及 examples/megatron/examples/ktransformers/examples/ascend/ 等按后端/硬件划分的示例目录,参数语义可进一步对照 docs/zh/hyperparameters/ 下的 data、model、training 参数文档。以上所有命令均在仓库根目录执行,配置路径为相对路径,请保持目录结构不变。

登录后查看全文
热门项目推荐
相关项目推荐