news 2026/9/10 20:54:18

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

作者头像

张小明

前端开发工程师

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

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

【免费下载链接】MiniCPM-VA Pocket-Sized MLLM for Ultra-Efficient Image and Video Understanding on Your Phone项目地址: https://gitcode.com/GitHub_Trending/mi/MiniCPM-V

本篇技术指南以 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_6minicpm_o
MiniCPM-V-2_6 / MiniCPM-V-4minicpm_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

各分区参数的作用说明:

分区参数说明
modelmodel_name_or_path基础模型名或本地路径,可切换为MiniCPM-o-2_6/MiniCPM-V-2_6
modeltrust_remote_codeMiniCPM 系列依赖远程代码(modeling 文件),必须为true
methodstage: sft微调阶段为监督微调
methodfinetuning_type: lora使用 LoRA 轻量微调
methodlora_target: q_proj,v_projLoRA 注入的注意力线性层;可扩展k_projo_proj提升适配能力(见下文官方脚本对照)
datasetdataset: mllm_demo对应dataset_info.json中注册的数据集名,可换mllm_video_demo/mllm_audio_demo
datasettemplateminicpm_o(o 系列)或minicpm_v(V 系列)
datasetcutoff_len: 3072序列截断长度,需容纳图像/视频/音频 token 与文本
datasetmax_samples: 1000每个 epoch 最多采样样本数,便于快速验证流程
datasetoverwrite_cache/preprocessing_num_workers强制重算数据缓存;16 个并行预处理进程加速
outputoutput_dir/save_steps: 100/save_total_limit: 10输出目录、每 100 步保存、最多保留 10 个 checkpoint
outputplot_loss/overwrite_output_dir绘制 loss 曲线;重复启动时覆盖旧输出
trainper_device_train_batch_size: 2单卡 batch size,显存不足时可降为 1
traingradient_accumulation_steps: 1梯度累积步数,与大 batch 等效
trainlearning_rate: 1.0e-5LoRA 常用学习率量级
trainlr_scheduler_type: cosine/warmup_ratio: 0.1余弦学习率调度 + 10% warmup
trainbf16: truebfloat16 混合精度训练
trainddp_timeout: 180000000多卡 DDP 初始化超时(毫秒),大模型加载较慢时避免超时报错
trainsave_only_model: true只保存模型权重,不保存 optimizer/scheduler 状态,节省磁盘
evaldo_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=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.py 中MiniCPMV2_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替换为自己的数据与路径,即可快速复用于图像理解、视频理解、音频理解及图文多轮对话等下游任务。

【免费下载链接】MiniCPM-VA Pocket-Sized MLLM for Ultra-Efficient Image and Video Understanding on Your Phone项目地址: https://gitcode.com/GitHub_Trending/mi/MiniCPM-V

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/9/10 20:51:02

绿色能源与电力系统国际会议2026:前沿技术与应用

1. 会议背景与行业趋势2026年第五届绿色能源与电力系统国际学术会议&#xff08;ICGEPS 2026&#xff09;的召开正值全球能源转型的关键时期。过去五年间&#xff0c;可再生能源在全球电力结构中的占比从27%跃升至35%&#xff0c;其中光伏和风电的装机容量年均增长率保持在15%以…

作者头像 李华
网站建设 2026/9/10 20:48:18

Note: this error code is no longer emitted by the compiler.

Note: this error code is no longer emitted by the compiler. 【免费下载链接】rust Empowering everyone to build reliable and efficient software. 项目地址: https://gitcode.com/GitHub_Trending/ru/rust 这行注释是整个 rustc 错误码体系中"已停用错误码&q…

作者头像 李华
网站建设 2026/9/10 20:46:15

LSSVM-ABKDE多变量回归区间预测Matlab实现

1. 项目概述&#xff1a;LSSVM-ABKDE多变量回归区间预测在工程预测和数据分析领域&#xff0c;我们常常需要处理复杂的非线性关系&#xff0c;并评估预测结果的不确定性。传统的最小二乘支持向量机&#xff08;LSSVM&#xff09;虽然能提供点预测&#xff0c;但在置信区间估计方…

作者头像 李华