首页
/ 使用 LLaMA-Factory 对 MiniCPM-V / MiniCPM-o 系列多模态模型进行 LoRA 微调、全参微调与推理的完整实践指南

使用 LLaMA-Factory 对 MiniCPM-V / MiniCPM-o 系列多模态模型进行 LoRA 微调、全参微调与推理的完整实践指南

2026-09-10 20:51:47作者:明树来

本篇技术指南以 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-4
  • openbmb/MiniCPM-o-2_6
  • openbmb/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.mdfinetune/dataset.pySupervisedDataset.__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_projo_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.pyLoraArguments 的默认值为 lora_r=64lora_alpha=64lora_dropout=0.05lora_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 时建议按以下顺序处理:

  1. 降低 cutoff_len(如 3072 → 2048/1200)与 per_device_train_batch_size(如 2 → 1),必要时同步提高 gradient_accumulation_steps 保持等效 batch;
  2. 减少图像切片数 max_slice_nums(如 9 → 3/1),每张图可降至 64 token 的基准开销;
  3. 冻结视觉塔(freeze_vision_tower: true 或官方脚本 --tune_vision false);
  4. 在 DeepSpeed 配置中开启 CPU offload:ZeRO-2 可 offload_optimizer 到 CPU,ZeRO-3 还可将 offload_param 一并 offload(官方 ds_config_zero2.json / ds_config_zero3.json 位于 finetune/ 目录);
  5. 仍不够再考虑降级为 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 等后端);
  • templatetrust_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=4352max_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 只支持 sdpaflash_attention_2不能使用 eager,这是 MiniCPM 系列模型的加载约束;torch_dtype=torch.bfloat16 与训练精度保持一致;
  • 输入格式msgs 中用户消息的 content 为图像(PIL Image 对象)与文本组成的列表,多轮对话只需继续向 msgs 追加 assistant / user 消息即可;
  • image=None:图像已内联在 msgs 中,故 image 参数传 None

仓库根目录的 chat.pyMiniCPMV2_6 类实现了同一套调用范式(AutoModel.from_pretrained(..., attn_implementation='sdpa', torch_dtype=torch.bfloat16)model.eval().cuda()),并额外演示了两种增强用法:

  • 多 GPU 推理:通过 accelerateinit_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 中的 datasetmodel_name_or_pathoutput_dir 替换为自己的数据与路径,即可快速复用于图像理解、视频理解、音频理解及图文多轮对话等下游任务。

热门项目推荐
相关项目推荐

项目优选

收起
kernelkernel
deepin linux kernel
C
33
18
docsdocs
暂无描述
Markdown
900
5.83 K
ops-transformerops-transformer
本项目是CANN提供的transformer类大模型算子库,实现网络在NPU上加速计算。
C++
1.15 K
2.77 K
pytorchpytorch
作为 Ascend for PyTorch 社区的核心组件,TorchNPU 是昇腾专为 PyTorch 打造的深度学习适配插件,使 PyTorch 框架能够直接调用昇腾 NPU,为开发者提供昇腾 AI 处理器的超强算力。
Python
860
1.36 K
ops-nnops-nn
本项目是CANN提供的神经网络类计算算子库,实现网络在NPU上加速计算。
C++
929
1.85 K
jiuwenswarmjiuwenswarm
JiuwenSwarm 是一款基于openJiuwen开发的智能AI Agent,它能够将大语言模型的强大能力,通过你日常使用的各类通讯应用,直接延伸至你的指尖。
Python
3.94 K
1.02 K
kernelkernel
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
534
603
ops-mathops-math
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
1.37 K
1.46 K
AscendNPU-IRAscendNPU-IR
AscendNPU-IR是基于MLIR(Multi-Level Intermediate Representation)构建的,面向昇腾亲和算子编译时使用的中间表示,提供昇腾完备表达能力,通过编译优化提升昇腾AI处理器计算效率,支持通过生态框架使能昇腾AI处理器与深度调优
C++
548
398
cann-learning-hubcann-learning-hub
CANN 学习中心仓,支持在线互动运行、边学边练,提供教程、示例与优化方案,一站式助力昇腾开发者快速上手。
Jupyter Notebook
1.05 K
528