使用 LLaMA-Factory 对 MiniCPM-V / MiniCPM-o 系列多模态模型进行 LoRA 微调、全参微调与推理的完整实践指南
本篇技术指南以 MiniCPM-V 官方仓库的 LLaMA-Factory 实践文档(docs/llamafactory_train_and_infer.md)为核心,系统讲解如何使用 LLaMA-Factory 对 MiniCPM-V 系列(V-2_6 / V-4)与 MiniCPM-o-2_6 多模态大模型完成图像、视频、音频三类数据集的准备、LoRA 微调、全参数微调、LoRA 权重导出以及多种推理方式。读者按文中的 YAML 配置与命令行操作,即可在单卡或多卡 GPU 环境上跑通"数据 → 微调 → 导出 → 推理"的完整链路,并了解各关键参数的实际含义与调优方向。
支持模型与模板选择
LLaMA-Factory 官方已适配以下 MiniCPM 系列模型(详见 docs/llamafactory_train_and_infer.md):
openbmb/MiniCPM-V-4openbmb/MiniCPM-o-2_6openbmb/MiniCPM-V-2_6
在使用时需要同时指定对应的对话模板:
| 模型 | 模板(template) |
|---|---|
| MiniCPM-o-2_6 | minicpm_o |
| MiniCPM-V-2_6 / MiniCPM-V-4 | minicpm_v |
模板决定了 LLaMA-Factory 如何构造特殊 token(如 <image>、<video>、<audio>)与多模态输入的处理流程,配置错误会导致数据无法正确拼接。此外,仓库主 README 中说明 MiniCPM-V 4.5 / 4.6 等新版本也已获得 LLaMA-Factory 官方适配支持,可关注官方发布动态选择对应版本的适配方式。
LLaMA-Factory 安装
安装 LLaMA-Factory 时需通过 extra 依赖显式安装 MiniCPM-V 所需的依赖项,并创建存放 YAML 配置文件的目录:
git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git
cd LLaMA-Factory
pip install -e ".[torch,metrics,deepspeed,minicpm_v]"
mkdir configs # let's put all yaml files here
torch/metrics:基础训练与指标依赖;deepspeed:全参数微调阶段用于 ZeRO 显存优化;minicpm_v:MiniCPM 系列模型(含远程代码 trust_remote_code)所需的专用依赖。
后续所有微调与推理命令均假定在 LLaMA-Factory 仓库根目录下执行,configs/ 目录用于集中存放下文给出的 YAML 配置。
数据集准备:在 dataset_info.json 中注册自定义数据
LLaMA-Factory 通过 data/dataset_info.json 统一管理数据集注册信息。你需要在该文件中登记自定义数据集的名称、文件路径与格式,然后在 YAML 配置的 dataset 字段中引用该名称。官方仓库内置了三个可直接使用的演示数据集:mllm_demo(图像)、mllm_video_demo(视频)、mllm_audio_demo(音频,仅 MiniCPM-o-2_6 支持音频输入)。
数据文件的格式为 JSON 数组,每个样本由 messages(多轮对话,content 中以特殊占位符标记媒体插入位置)与对应的媒体文件路径字段(images / videos / audios)组成。
图像数据集(mllm_demo)
图像对话中,用户在内容里以 <image> 占位符指示图像插入位置,images 字段给出图像路径:
[
{
"messages": [
{
"content": "<image>Who are they?",
"role": "user"
},
{
"content": "They're Kane and Gretzka from Bayern Munich.",
"role": "assistant"
},
{
"content": "What are they doing?",
"role": "user"
},
{
"content": "They are celebrating on the soccer field.",
"role": "assistant"
}
],
"images": [
"mllm_demo_data/1.jpg"
]
},
{
"messages": [
{
"content": "<image>Who is he?",
"role": "user"
},
{
"content": "He's Thomas Muller from Bayern Munich.",
"role": "assistant"
},
{
"content": "Why is he on the ground?",
"role": "user"
},
{
"content": "Because he's sliding on his knees to celebrate.",
"role": "assistant"
}
],
"images": [
"mllm_demo_data/2.jpg"
]
},
{
"messages": [
{
"content": "<image>Please describe this image",
"role": "user"
},
{
"content": "Chinese astronaut Gui Haichao is giving a speech.",
"role": "assistant"
},
{
"content": "What has he accomplished?",
"role": "user"
},
{
"content": "He was appointed to be a payload specialist on Shenzhou 16 mission in June 2022, thus becoming the first Chinese civilian of Group 3 in space on 30 May 2023. He is responsible for the on-orbit operation of space science experimental payloads.",
"role": "assistant"
}
],
"images": [
"mllm_demo_data/3.jpg"
]
}
]
视频数据集(mllm_video_demo)
视频对话使用 <video> 占位符,videos 字段支持 mp4、avi 等常见视频格式(LLaMA-Factory 内部会抽帧处理):
[
{
"messages": [
{
"content": "<video>Why is this video funny?",
"role": "user"
},
{
"content": "Because a baby is reading, and he is so cute!",
"role": "assistant"
}
],
"videos": [
"mllm_demo_data/1.mp4"
]
},
{
"messages": [
{
"content": "<video>What is she doing?",
"role": "user"
},
{
"content": "She is cooking.",
"role": "assistant"
}
],
"videos": [
"mllm_demo_data/2.avi"
]
},
{
"messages": [
{
"content": "<video>What's in the video?",
"role": "user"
},
{
"content": "A baby is playing in the living room.",
"role": "assistant"
}
],
"videos": [
"mllm_demo_data/3.mp4"
]
}
]
音频数据集(mllm_audio_demo)
音频对话使用 <audio> 占位符,audios 字段支持 mp3、wav、flac 等格式。需要特别注意:音频能力仅存在于 MiniCPM-o-2_6,因此 mllm_audio_demo 只能用于该模型的微调:
[
{
"messages": [
{
"content": "<audio>What's that sound?",
"role": "user"
},
{
"content": "It is the sound of glass shattering.",
"role": "assistant"
}
],
"audios": [
"mllm_demo_data/1.mp3"
]
},
{
"messages": [
{
"content": "<audio>What can you hear?",
"role": "user"
},
{
"content": "A woman is coughing.",
"role": "assistant"
}
],
"audios": [
"mllm_demo_data/2.wav"
]
},
{
"messages": [
{
"content": "<audio>What does the person say?",
"role": "user"
},
{
"content": "Mister Quiller is the apostle of the middle classes and we are glad to welcome his gospel.",
"role": "assistant"
}
],
"audios": [
"mllm_demo_data/3.flac"
]
}
]
多图像数据的格式要点(官方微调脚本对照)
若需构造多图输入样本,可以参考仓库官方微调数据格式 finetune/readme.md 与 finetune/dataset.py(SupervisedDataset.__getitem__ 中按字典解析图像):将 image 字段写为以 <image_00>、<image_01> 等为键、图像路径为值的字典,并在对话中以对应占位符定位每张图像的位置。该文档还给出两点实用的 token 预算参考:
- 2.6 版本中单张图像默认表示为 64 个 token;当
slice=9时,最大 1344×1344 分辨率的图像约占 64×(9+1) 个 token; - 多图 SFT 场景建议将
MODEL_MAX_LENGTH设为 4096,超出max_length的序列会被截断。
这也解释了 LLaMA-Factory 配置中 cutoff_len: 3072 的取值逻辑——需要为图像 token 预留足够长度。
LoRA 微调
LoRA 微调只需一条命令(CUDA_VISIBLE_DEVICES=0 指定单卡):
CUDA_VISIBLE_DEVICES=0 llamafactory-cli train configs/minicpmo_2_6_lora_sft.yaml
对应的 configs/minicpmo_2_6_lora_sft.yaml 完整内容如下:
### model
model_name_or_path: openbmb/MiniCPM-o-2_6 # MiniCPM-o-2_6 MiniCPM-V-2_6
trust_remote_code: true
### method
stage: sft
do_train: true
finetuning_type: lora
lora_target: q_proj,v_proj
### dataset
dataset: mllm_demo # mllm_demo mllm_video_demo mllm_audio_demo
template: minicpm_o # minicpm_o minicpm_v
cutoff_len: 3072
max_samples: 1000
overwrite_cache: true
preprocessing_num_workers: 16
### output
output_dir: saves/minicpmo_2_6/lora/sft
logging_steps: 1
save_steps: 100
plot_loss: true
overwrite_output_dir: true
save_total_limit: 10
### train
per_device_train_batch_size: 2
gradient_accumulation_steps: 1
learning_rate: 1.0e-5
num_train_epochs: 20.0
lr_scheduler_type: cosine
warmup_ratio: 0.1
bf16: true
ddp_timeout: 180000000
save_only_model: true
### eval
do_eval: false
各分区参数的作用说明:
| 分区 | 参数 | 说明 |
|---|---|---|
| model | model_name_or_path |
基础模型名或本地路径,可切换为 MiniCPM-o-2_6 / MiniCPM-V-2_6 等 |
| model | trust_remote_code |
MiniCPM 系列依赖远程代码(modeling 文件),必须为 true |
| method | stage: sft |
微调阶段为监督微调 |
| method | finetuning_type: lora |
使用 LoRA 轻量微调 |
| method | lora_target: q_proj,v_proj |
LoRA 注入的注意力线性层;可扩展 k_proj、o_proj 提升适配能力(见下文官方脚本对照) |
| dataset | dataset: mllm_demo |
对应 dataset_info.json 中注册的数据集名,可换 mllm_video_demo / mllm_audio_demo |
| dataset | template |
minicpm_o(o 系列)或 minicpm_v(V 系列) |
| dataset | cutoff_len: 3072 |
序列截断长度,需容纳图像/视频/音频 token 与文本 |
| dataset | max_samples: 1000 |
每个 epoch 最多采样样本数,便于快速验证流程 |
| dataset | overwrite_cache / preprocessing_num_workers |
强制重算数据缓存;16 个并行预处理进程加速 |
| output | output_dir / save_steps: 100 / save_total_limit: 10 |
输出目录、每 100 步保存、最多保留 10 个 checkpoint |
| output | plot_loss / overwrite_output_dir |
绘制 loss 曲线;重复启动时覆盖旧输出 |
| train | per_device_train_batch_size: 2 |
单卡 batch size,显存不足时可降为 1 |
| train | gradient_accumulation_steps: 1 |
梯度累积步数,与大 batch 等效 |
| train | learning_rate: 1.0e-5 |
LoRA 常用学习率量级 |
| train | lr_scheduler_type: cosine / warmup_ratio: 0.1 |
余弦学习率调度 + 10% warmup |
| train | bf16: true |
bfloat16 混合精度训练 |
| train | ddp_timeout: 180000000 |
多卡 DDP 初始化超时(毫秒),大模型加载较慢时避免超时报错 |
| train | save_only_model: true |
只保存模型权重,不保存 optimizer/scheduler 状态,节省磁盘 |
| eval | do_eval: false |
微调阶段不做评估 |
与官方 LoRA 脚本的对照参考
仓库官方微调脚本 finetune/finetune_lora.sh 中 LoRA 的默认注入目标为 llm\..*layers\.\d+\.self_attn\.(q_proj|k_proj|v_proj|o_proj)(含 k_proj 与 o_proj),而 finetune/finetune.py 中 LoraArguments 的默认值为 lora_r=64、lora_alpha=64、lora_dropout=0.05、lora_bias="none",并且 use_lora 模式下 LLM 全部参数会被冻结(tune_llm 与 LoRA 不能同时开启)。若你的下游任务需要更强的适配能力,可将 lora_target 扩展为 q_proj,k_proj,v_proj,o_proj。
参考:官方微调脚本在 NVIDIA A100(80 GiB)多卡、ZeRO-3 + 梯度检查点 + 优化器/参数 CPU offload、max length 2048、batch 1 的配置下,LoRA 微调显存约为 2 卡 14.4 GiB、4 卡 13.6 GiB、8 卡 13.1 GiB(见 finetune/readme.md),可作为显存预估的参考量级。
LoRA 模型导出
训练完成后,需要将 LoRA 适配器与基础模型合并导出为完整权重,供后续推理或部署使用:
llamafactory-cli export configs/minicpmo_2_6_lora_export.yaml
configs/minicpmo_2_6_lora_export.yaml 完整内容如下:
### model
model_name_or_path: openbmb/MiniCPM-o-2_6 # MiniCPM-o-2_6 MiniCPM-V-2_6
adapter_name_or_path: saves/minicpmo_2_6/lora/sft
template: minicpm_o # minicpm_o minicpm_v
finetuning_type: lora
trust_remote_code: true
### export
export_dir: models/minicpmo_2_6_lora_sft
export_size: 2
export_device: cpu
export_legacy_format: false
参数要点:
adapter_name_or_path:指向训练输出目录saves/minicpmo_2_6/lora/sft,即上一步output_dir;export_dir:合并后完整模型的保存路径;export_size: 2:按 2 个文件分片保存权重(便于大模型分发);export_device: cpu:在 CPU 上执行权重合并,规避多卡环境下的显存与设备映射问题;export_legacy_format: false:以新版格式导出(不兼容旧版 transformers 加载方式的 legacy 格式)。
全参数微调
全参数微调更新 LLM 全部参数,通常需要配合 DeepSpeed 显存优化。同样一条命令启动:
llamafactory-cli train configs/minicpmo_2_6_full_sft.yaml
configs/minicpmo_2_6_full_sft.yaml 完整内容如下:
### model
model_name_or_path: openbmb/MiniCPM-o-2_6 # MiniCPM-o-2_6 MiniCPM-V-2_6
trust_remote_code: true
freeze_vision_tower: true
print_param_status: true
flash_attn: fa2
### method
stage: sft
do_train: true
finetuning_type: full
deepspeed: configs/deepspeed/ds_z2_config.json
### dataset
dataset: mllm_demo # mllm_demo mllm_video_demo
template: minicpm_o # minicpm_o minicpm_v
cutoff_len: 3072
max_samples: 1000
overwrite_cache: true
preprocessing_num_workers: 16
### output
output_dir: saves/minicpmo_2_6/full/sft
logging_steps: 1
save_steps: 100
plot_loss: true
overwrite_output_dir: true
save_total_limit: 10
### train
per_device_train_batch_size: 2
gradient_accumulation_steps: 1
learning_rate: 1.0e-5
num_train_epochs: 20.0
lr_scheduler_type: cosine
warmup_ratio: 0.1
bf16: true
ddp_timeout: 180000000
save_only_model: true
### eval
do_eval: false
与 LoRA 配置相比,全参微调的关键差异:
finetuning_type: full:更新全部(或经 freeze 控制的部分)参数;freeze_vision_tower: true:冻结视觉塔(VPM)参数,只训练 LLM 与连接层,显著降低显存与过拟合风险;print_param_status: true:打印各模块参数的可训练状态,便于核对冻结配置;flash_attn: fa2:使用 FlashAttention-2 加速注意力计算(需环境已安装 flash_attn);deepspeed: configs/deepspeed/ds_z2_config.json:ZeRO Stage 2 配置,显存紧张时可升级为 Stage 3。
仓库官方脚本 finetune/finetune_ds.sh 给出了同思路的完整参数清单可作对照:通过 --tune_vision true/false 控制是否训练视觉模块、--model_max_length 2048(多图 SFT 建议 4096)、--max_slice_nums 9 控制图像切片数量、--gradient_checkpointing true 开启梯度检查点,并默认使用 ds_config_zero3.json 的 ZeRO-3 配置。
显存不足(OOM)时的优先调整顺序
结合 finetune/readme.md 的 FAQ 内容,遇到 OOM 时建议按以下顺序处理:
- 降低
cutoff_len(如 3072 → 2048/1200)与per_device_train_batch_size(如 2 → 1),必要时同步提高gradient_accumulation_steps保持等效 batch; - 减少图像切片数
max_slice_nums(如 9 → 3/1),每张图可降至 64 token 的基准开销; - 冻结视觉塔(
freeze_vision_tower: true或官方脚本--tune_vision false); - 在 DeepSpeed 配置中开启 CPU offload:ZeRO-2 可
offload_optimizer到 CPU,ZeRO-3 还可将offload_param一并 offload(官方ds_config_zero2.json/ds_config_zero3.json位于 finetune/ 目录); - 仍不够再考虑降级为 LoRA 微调。
推理
微调产出的模型有两种常用推理方式:LLaMA-Factory 自带的 WebUI 对话,以及使用模型官方代码直接调用。
方式一:LLaMA-Factory Web UI ChatBox
一条命令即可启动网页对话界面:
CUDA_VISIBLE_DEVICES=0 llamafactory-cli webchat configs/minicpmo_2_6_infer.yaml
configs/minicpmo_2_6_infer.yaml 完整内容如下:
model_name_or_path: saves/minicpmo_2_6/full/sft
template: minicpm_o # minicpm_o minicpm_v
infer_backend: huggingface
trust_remote_code: true
model_name_or_path:指向全参微调(或 LoRA 导出后)的模型目录;infer_backend: huggingface:使用 transformers 原生后端推理(也可按需切换到 vllm 等后端);template与trust_remote_code必须与训练时保持一致。
仓库官方 Gradio Demo(web_demos/web_demo_2.6.py)中提供了可参考的生成参数配置:Beam Search 模式常用 num_beams=3, repetition_penalty=1.2, max_new_tokens=2048;Sampling 模式常用 top_p=0.8, top_k=100, temperature=0.7, repetition_penalty=1.05,视频输入时还会追加 max_inp_length=4352 与 max_slice_nums 限制。
方式二:官方代码直接推理
也可以完全脱离 LLaMA-Factory,用模型官方代码加载微调产物进行推理:
# test.py
import torch
from PIL import Image
from transformers import AutoModel, AutoTokenizer
model_id = "saves/minicpmo_2_6/full/sft"
model = AutoModel.from_pretrained(model_id, trust_remote_code=True,
attn_implementation='sdpa', torch_dtype=torch.bfloat16) # sdpa or flash_attention_2, no eager
model = model.eval().cuda()
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
image = Image.open('data/mllm_demo_data/1.jpg').convert('RGB')
question = 'Who are they??'
msgs = [{'role': 'user', 'content': [image, question]}]
res = model.chat(
image=None,
msgs=msgs,
tokenizer=tokenizer
)
print(res)
代码要点:
- 注意力实现:
attn_implementation只支持sdpa或flash_attention_2,不能使用eager,这是 MiniCPM 系列模型的加载约束;torch_dtype=torch.bfloat16与训练精度保持一致; - 输入格式:
msgs中用户消息的content为图像(PIL Image 对象)与文本组成的列表,多轮对话只需继续向msgs追加assistant/user消息即可; image=None:图像已内联在msgs中,故image参数传None。
仓库根目录的 chat.py 中 MiniCPMV2_6 类实现了同一套调用范式(AutoModel.from_pretrained(..., attn_implementation='sdpa', torch_dtype=torch.bfloat16) 后 model.eval().cuda()),并额外演示了两种增强用法:
- 多 GPU 推理:通过
accelerate的init_empty_weights+infer_auto_device_map把模型按层拆分到多张卡上(multi_gpus=True路径),并强制将 embed_tokens 与 lm_head 置于同一设备; - 采样参数:官方
decode逻辑中使用的生成配置为temperature=0.6, top_k=30, top_p=0.9, repetition_penalty=1.1, do_sample=True,可作为默认采样超参的参考起点。
更详细的多卡推理说明可参阅 docs/inference_on_multiple_gpus.md。
常见问题与调优建议
- LoRA 微调后无法用 AutoPeftModel 加载:部分版本模型缺少
get_input_embeddings/set_input_embeddings方法(详见 finetune/readme.md FAQ),可通过PeftModel.from_pretrained手动为模型补充该方法后再加载;同时确保model_minicpmv.py等远程代码为最新版本。 - 如何确定训练数据所需的 max_length:可使用 finetune/dataset.py 中的数据预处理逻辑抽样统计序列长度(注意
input_ids长度包含图像 token),再据此设置cutoff_len/model_max_length。 - 图像分辨率策略:模型原生支持最高 1344×1344 的无损编码,默认启用高清编码方案;若显存紧张,降低
max_slice_nums比直接压缩图像更划算(见上文"多图像数据"一节)。 - 模板与模型严格对应:
minicpm_o/minicpm_v与模型版本必须匹配,混用会导致 token 序列错乱。
至此,从环境安装、三类多模态数据集构建,到 LoRA 微调、LoRA 导出、全参数微调,再到 WebUI 与官方代码两种推理路径,你已经拥有了基于 LLaMA-Factory 定制 MiniCPM-V / MiniCPM-o 系列模型的完整可落地方案。将上述 YAML 中的 dataset、model_name_or_path、output_dir 替换为自己的数据与路径,即可快速复用于图像理解、视频理解、音频理解及图文多轮对话等下游任务。
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust4.21 K635- DDeepSeek-V4.1-FlashDeepSeek-V4.1-Flash 是一个多模态混合专家(MoE)模型,拥有 5520 亿骨干参数,并支持最多一百万 token 的上下文长度。该模型原生支持图像和文本输入,并以自回归方式生成文本Python40
jforgamejforgame是一个一站式游戏服务器开发框架。包含游戏服务器开发所需要的各种组件,比如网关,socket服务端与客户端,自定义高效消息编解码,游戏热更新,游戏通用工具等等。包含游戏服,跨服,匹配服,后台管理系统等实现,同时提供大量业务案例以供学习。亦可用于其他socket应用,例如及时聊天等。Java131
fizz-gateway-nodeAn Aggregation API Gateway in Java . FizzGate 是一个基于 Java开发的微服务聚合网关,是拥有自主知识产权的应用网关国产化替代方案,能够实现热服务编排聚合、自动授权选择、线上服务脚本编码、在线测试、高性能路由、API审核管理、回调管理等目的,拥有强大的自定义插件系统可以自行扩展,并且提供友好的图形化配置界面,能够快速帮助企业进行API服务治理、减少中间层胶水代码以及降低编码投入、提高 API 服务的稳定性和安全性。Java80
certd开源SSL证书管理工具;全自动证书申请、更新、续期;通配符证书,泛域名证书申请;证书自动化部署到阿里云、腾讯云、主机、群晖、宝塔;https证书,pfx证书,der证书,TLS证书,nginx证书自动续签自动部署JavaScript80
Spark-X2.5-1.7BSpark-X2.5-1.7B 旨在让强大的 AI 更加实用、高效且易于获取。这些模型在广泛的日常任务中表现出色,涵盖对话、写作、翻译、推理、编程、工具调用和智能体工作流,并在同等规模的开源模型中取得领先结果。Spark-X2.5 将面向效率的架构与最高 1M tokens 的原生上下文窗口相结合,并支持 200 多种语言。Python290