
使用 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.mdopenbmb/MiniCPM-V-4openbmb/MiniCPM-o-2_6openbmb/MiniCPM-V-2_6在使用时需要同时指定对应的对话模板模型模板templateMiniCPM-o-2_6minicpm_oMiniCPM-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 # lets put all yaml files heretorch/metrics基础训练与指标依赖deepspeed全参数微调阶段用于 ZeRO 显存优化minicpm_vMiniCPM 系列模型含远程代码 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: imageWho are they?, role: user }, { content: Theyre 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: imageWho is he?, role: user }, { content: Hes Thomas Muller from Bayern Munich., role: assistant }, { content: Why is he on the ground?, role: user }, { content: Because hes sliding on his knees to celebrate., role: assistant } ], images: [ mllm_demo_data/2.jpg ] }, { messages: [ { content: imagePlease 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: videoWhy 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: videoWhat is she doing?, role: user }, { content: She is cooking., role: assistant } ], videos: [ mllm_demo_data/2.avi ] }, { messages: [ { content: videoWhats 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: audioWhats that sound?, role: user }, { content: It is the sound of glass shattering., role: assistant } ], audios: [ mllm_demo_data/1.mp3 ] }, { messages: [ { content: audioWhat can you hear?, role: user }, { content: A woman is coughing., role: assistant } ], audios: [ mllm_demo_data/2.wav ] }, { messages: [ { content: audioWhat 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.pySupervisedDataset.__getitem__中按字典解析图像将image字段写为以image_00、image_01等为键、图像路径为值的字典并在对话中以对应占位符定位每张图像的位置。该文档还给出两点实用的 token 预算参考2.6 版本中单张图像默认表示为 64 个 token当slice9时最大 1344×1344 分辨率的图像约占 64×(91) 个 token多图 SFT 场景建议将MODEL_MAX_LENGTH设为 4096超出max_length的序列会被截断。这也解释了 LLaMA-Factory 配置中cutoff_len: 3072的取值逻辑——需要为图像 token 预留足够长度。LoRA 微调LoRA 微调只需一条命令CUDA_VISIBLE_DEVICES0指定单卡CUDA_VISIBLE_DEVICES0 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 文件必须为truemethodstage: sft微调阶段为监督微调methodfinetuning_type: lora使用 LoRA 轻量微调methodlora_target: q_proj,v_projLoRA 注入的注意力线性层可扩展k_proj、o_proj提升适配能力见下文官方脚本对照datasetdataset: mllm_demo对应dataset_info.json中注册的数据集名可换mllm_video_demo/mllm_audio_demodatasettemplateminicpm_oo 系列或minicpm_vV 系列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 个 checkpointoutputplot_loss/overwrite_output_dir绘制 loss 曲线重复启动时覆盖旧输出trainper_device_train_batch_size: 2单卡 batch size显存不足时可降为 1traingradient_accumulation_steps: 1梯度累积步数与大 batch 等效trainlearning_rate: 1.0e-5LoRA 常用学习率量级trainlr_scheduler_type: cosine/warmup_ratio: 0.1余弦学习率调度 10% warmuptrainbf16: 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_r64、lora_alpha64、lora_dropout0.05、lora_biasnone并且use_lora模式下 LLM 全部参数会被冻结tune_llm与 LoRA 不能同时开启。若你的下游任务需要更强的适配能力可将lora_target扩展为q_proj,k_proj,v_proj,o_proj。参考官方微调脚本在 NVIDIA A10080 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.yamlconfigs/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_direxport_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.yamlconfigs/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_attndeepspeed: configs/deepspeed/ds_z2_config.jsonZeRO 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 offloadZeRO-2 可offload_optimizer到 CPUZeRO-3 还可将offload_param一并 offload官方ds_config_zero2.json/ds_config_zero3.json位于 finetune/ 目录仍不够再考虑降级为 LoRA 微调。推理微调产出的模型有两种常用推理方式LLaMA-Factory 自带的 WebUI 对话以及使用模型官方代码直接调用。方式一LLaMA-Factory Web UI ChatBox一条命令即可启动网页对话界面CUDA_VISIBLE_DEVICES0 llamafactory-cli webchat configs/minicpmo_2_6_infer.yamlconfigs/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: truemodel_name_or_path指向全参微调或 LoRA 导出后的模型目录infer_backend: huggingface使用 transformers 原生后端推理也可按需切换到 vllm 等后端template与trust_remote_code必须与训练时保持一致。仓库官方 Gradio Demoweb_demos/web_demo_2.6.py中提供了可参考的生成参数配置Beam Search 模式常用num_beams3, repetition_penalty1.2, max_new_tokens2048Sampling 模式常用top_p0.8, top_k100, temperature0.7, repetition_penalty1.05视频输入时还会追加max_inp_length4352与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_codeTrue, attn_implementationsdpa, torch_dtypetorch.bfloat16) # sdpa or flash_attention_2, no eager model model.eval().cuda() tokenizer AutoTokenizer.from_pretrained(model_id, trust_remote_codeTrue) image Image.open(data/mllm_demo_data/1.jpg).convert(RGB) question Who are they?? msgs [{role: user, content: [image, question]}] res model.chat( imageNone, msgsmsgs, tokenizertokenizer ) print(res)代码要点注意力实现attn_implementation只支持sdpa或flash_attention_2不能使用eager这是 MiniCPM 系列模型的加载约束torch_dtypetorch.bfloat16与训练精度保持一致输入格式msgs中用户消息的content为图像PIL Image 对象与文本组成的列表多轮对话只需继续向msgs追加assistant/user消息即可imageNone图像已内联在msgs中故image参数传None。仓库根目录的 chat.py 中MiniCPMV2_6类实现了同一套调用范式AutoModel.from_pretrained(..., attn_implementationsdpa, torch_dtypetorch.bfloat16)后model.eval().cuda()并额外演示了两种增强用法多 GPU 推理通过accelerate的init_empty_weightsinfer_auto_device_map把模型按层拆分到多张卡上multi_gpusTrue路径并强制将 embed_tokens 与 lm_head 置于同一设备采样参数官方decode逻辑中使用的生成配置为temperature0.6, top_k30, top_p0.9, repetition_penalty1.1, do_sampleTrue可作为默认采样超参的参考起点。更详细的多卡推理说明可参阅 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替换为自己的数据与路径即可快速复用于图像理解、视频理解、音频理解及图文多轮对话等下游任务。【免费下载链接】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),仅供参考