跳到主要内容

MiniCPM-V 4.7

MiniCPM-V 多模态系列

把模型适配到自己的任务上。ms-swift 是 MiniCPM-V 4.7 当前验证过的训练路径,官方给出了 1B 与 35B-A3B 的完整配置与评测结果;LLaMA-Factory 则提供通用的 LoRA 与全参数流程。

方案MiniCPM-V 4.7 支持情况适用
ms-swift需 PR #10338,1B / 35B-A3B 均已验证推荐,有完整参考配置与评测
LLaMA-Factory通用多模态流程LoRA / 全参数,配置文件驱动

MiniCPM-V 4.7 在 transformers>=5.18.0 版本被官方支持。各方案安装依赖时,请保证最后安装的 transformers 版本为 5.18.0 及以上。

ms-swift​

以 counting 任务 allenai/pixmo-count 作为微调示例。两个尺寸的目标输出格式略有不同:

  • 1B:先给出每个目标物体点的位置,用 x y 坐标表示(如 <point>573 489</point>),再输出最终数量。
  • 35B-A3B:直接以单个整数表示最终数量,例如 0、3、10。

1B:环境准备​

Bash
conda create -n "MiniCPM-V-4.7-1B-Counting" python=3.10 -y
conda activate "MiniCPM-V-4.7-1B-Counting"

pip install torch==2.8.0 torchvision==0.23.0

pip install \
transformers==5.18.0 accelerate==1.13.0 \
deepspeed==0.18.3 peft==0.18.1 trl==0.29.1 datasets==4.8.4 \
flash-linear-attention==0.5.2 ninja

MAX_JOBS=32 NVCC_THREADS=4 pip install --no-build-isolation flash-attn==2.8.3

git clone https://github.com/modelscope/ms-swift.git
cd ms-swift
git fetch origin pull/10338/head
git checkout FETCH_HEAD
pip install -e .
pip install transformers==5.18.0

依赖版本参考:

Plain Text
python 3.10.0
accelerate 1.13.0
deepspeed 0.18.3
flash_attn 2.8.3
flash-linear-attention 0.5.2
ms_swift 4.6.0.dev0 (PR #10338)
torch 2.8.0+cu128
torchvision 0.23.0
transformers 5.18.0

1B:数据准备​

从 allenai/pixmo-count 下载数据集,并转换为 ms-swift 格式:

JSON
{
"messages": [
{
"content": "<image>\nCarefully observe the image. Are there any people in the image? If yes, please list their respective coordinates and provide the total count. If no, answer 0.",
"role": "user"
},
{
"content": "<think>\n\n</think>\n\nThe respective coordinates of people: <point>236 469</point>, <point>307 232</point>, <point>362 434</point>, <point>485 521</point>, <point>487 340</point>, <point>615 386</point>, <point>735 441</point>, <point>870 615</point>. So the total count is 8.",
"role": "assistant"
}
],
"images": ["/path/to/images/*.jpg"],
"source_file": "pixmo-count",
"orig_index": 1,
"channel": "pixmo-count"
}
  • Counting 任务中加入对 points 预测的监督能够提高微调的效果,因此推荐将数据中的 points 坐标拼到 assistant 回复中。
  • 由于 MiniCPM-V 4.7 会将图片坐标归一化到 0~1000,因此也需要对 points 坐标做如下处理:
Python
def expected_norm(x_px: float, y_px: float, width: int, height: int) -> Tuple[int, int]:
return int((x_px / width) * 1000.0), int((y_px / height) * 1000.0)

1B:启动训练​

配置好模型路径、训练集路径、验证集路径和输出目录后,执行以下脚本即可开始训练。

Bash
# run_swift.sh
#!/bin/bash
set -euo pipefail

export CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-0,1,2,3,4,5,6,7}"
export NPROC_PER_NODE="${NPROC_PER_NODE:-8}"
export MASTER_PORT="${MASTER_PORT:-29632}"
export WANDB_API_KEY="${WANDB_API_KEY:-}"
export WANDB_PROJECT="${WANDB_PROJECT:-MiniCPMV47-Counting}"
export WANDB_RUN_NAME="${WANDB_RUN_NAME:-minicpmv47_1b_count}"
export WANDB_NAME="${WANDB_NAME:-minicpmv47_1b_count}"
export DOWNSAMPLE_MODE="${DOWNSAMPLE_MODE:-4x}"

GRADIENT_CHECKPOINTING=true
MODE_ARGS=()
if [[ "${DOWNSAMPLE_MODE}" == "16x" ]]; then
GRADIENT_CHECKPOINTING=false
MODE_ARGS+=(--ddp_find_unused_parameters true --check_model false)
fi

SWIFT_BIN="${SWIFT_BIN:-swift}"
MODEL_PATH="${MODEL_PATH:-/path/to/MiniCPM-V-4.7-1B}"
TRAIN_DATA="${TRAIN_DATA:-/path/to/task_dataset/train/pixmo_count_train_with_channel}"
VALID_DATA="${VALID_DATA:-/path/to/task_dataset/val/validation-00000-of-00001-swift.parquet}"
DEEPSPEED_CONFIG="${DEEPSPEED_CONFIG:-zero2}"
OUTPUT_DIR="${OUTPUT_DIR:-/path/to/outdir}"

${SWIFT_BIN} sft \
--model "${MODEL_PATH}" \
--model_type minicpmv4_7 \
--template minicpmv4_7 \
--add_non_thinking_prefix true \
--run_name "${WANDB_RUN_NAME}" \
--dataset "${TRAIN_DATA}" \
--val_dataset "${VALID_DATA}" \
--deepspeed "${DEEPSPEED_CONFIG}" \
--tuner_type full \
--torch_dtype bfloat16 \
--freeze_llm False \
--freeze_vit False \
--freeze_aligner True \
--packing false \
--padding_free false \
--max_length 4096 \
--num_train_epochs 4 \
--per_device_train_batch_size 1 \
--per_device_eval_batch_size 1 \
--gradient_accumulation_steps 16 \
--gradient_checkpointing "${GRADIENT_CHECKPOINTING}" \
--vit_gradient_checkpointing true \
"${MODE_ARGS[@]}" \
--learning_rate 5e-6 \
--warmup_ratio 0.05 \
--logging_steps 1 \
--save_steps 132 \
--eval_strategy steps \
--eval_steps 80 \
--save_total_limit 30 \
--load_from_cache_file false \
--dataset_num_proc 16 \
--dataloader_num_workers 16 \
--enable_channel_loss True \
--attn_impl flash_attn \
--loss_scale ignore_empty_think \
--output_dir "${OUTPUT_DIR}" \
--report_to none

关键参数说明:

  • 训练支持 16x、4x 两种视觉 Token 压缩率,通过 DOWNSAMPLE_MODE 环境变量控制。
  • 当前 MiniCPM-V 4.7 模板请保持使用 --packing false 和 --padding_free false。
  • --add_non_thinking_prefix true 可以在训练提示词后加入 <think>\n\n</think>\n\n,实现无 thinking 训练。

1B:评测结果​

指标说明
Acc@0精确匹配率,即预测值与真实值完全一致
Acc@0 Top1训练过程保存的所有 checkpoint 中,评测结果 Acc@0 的最高分数
Acc@0 Avg.Top3训练过程保存的所有 checkpoint 中,评测结果 Acc@0 前三名的平均分数
模型视觉 Token 压缩率Acc@0 Top1Acc@0 Avg.Top3
MiniCPM-V 4.7 1B1655.2N/A
MiniCPM-V 4.7 1B457.7N/A
Fine-tuned model1679.379.1
Fine-tuned model482.582.5

原始模型未经微调,仅有一个 Acc@0 结果(Acc@0 Top1),无法计算 Acc@0 Avg.Top3。

输出样例:

Plain Text
Q: Carefully observe the image. Are there any eggs in the image? If yes, please list their
respective coordinates and provide the total count. If no, answer 0.
A: The respective coordinates of eggs: 252 347, 252 703, 509 351, 517 699, 750 351, 750 670.
So the total count is 6.

35B-A3B:环境准备​

Bash
conda create -n "MiniCPM-V-4.7-35B-A3B-Counting" python=3.12 -y
conda activate "MiniCPM-V-4.7-35B-A3B-Counting"

pip install torch==2.10.0 torchvision==0.25.0

pip install \
transformers==5.18.0 accelerate==1.15.0 \
deepspeed==0.18.3 peft==0.18.1 trl==0.24.0 \
flash-linear-attention==0.5.2 wandb ninja einops safetensors tokenizers sentencepiece

MAX_JOBS=32 NVCC_THREADS=4 pip install --no-build-isolation --no-binary causal-conv1d causal-conv1d==1.7.0

git clone https://github.com/modelscope/ms-swift.git
cd ms-swift
git fetch origin pull/10338/head
git checkout FETCH_HEAD
pip install -e .
pip install transformers==5.18.0

依赖版本参考:

Plain Text
python 3.12.3
accelerate 1.15.0
deepspeed 0.18.3
flash-linear-attention 0.5.2
ms_swift 4.6.0.dev0 (PR #10338)
torch 2.10.0+cu128
torchvision 0.25.0
transformers 5.18.0

35B-A3B:数据准备​

JSON
{
"messages": [
{
"content": "<image>\nCarefully observe the image. How many people are there in the image? Answer with a single integer only.",
"role": "user"
},
{
"content": "8",
"role": "assistant"
}
],
"images": ["/path/to/images/*.jpg"],
"source_file": "pixmo-count-train",
"orig_index": 1,
"channel": "pixmo-count-no-points"
}

35B-A3B:启动训练​

Bash
# run_swift.sh
#!/bin/bash
set -euo pipefail

export CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-0,1,2,3,4,5,6,7}"
export NPROC_PER_NODE="${NPROC_PER_NODE:-8}"
export MASTER_PORT="${MASTER_PORT:-29632}"
export PYTORCH_ALLOC_CONF="${PYTORCH_ALLOC_CONF:-expandable_segments:True}"
export WANDB_API_KEY="${WANDB_API_KEY:-}"
export WANDB_PROJECT="${WANDB_PROJECT:-MiniCPMV47-35B-A3B-Counting}"
export WANDB_RUN_NAME="${WANDB_RUN_NAME:-mcpmv47_35b_count}"
export WANDB_NAME="${WANDB_NAME:-mcpmv47_35b_count}"
export DOWNSAMPLE_MODE="${DOWNSAMPLE_MODE:-4x}"

SWIFT_BIN="${SWIFT_BIN:-swift}"
MODEL_PATH="${MODEL_PATH:-/path/to/MiniCPM-V-4.7-35B-A3B}"
TRAIN_DATA="${TRAIN_DATA:-/path/to/task_dataset/train.jsonl}"
VALID_DATA="${VALID_DATA:-/path/to/task_dataset/validation.jsonl}"
DEEPSPEED_CONFIG="${DEEPSPEED_CONFIG:-zero3}"

if [[ "${DEEPSPEED_CONFIG}" == zero3 ]]; then
DEEPSPEED_CONFIG="$(python - <<'PY'
import json
from importlib.resources import files
config = json.loads(files('swift').joinpath('config/zero3.json').read_text())
config['zero_optimization']['sub_group_size'] = 100000000
print(json.dumps(config))
PY
)"
fi

OUTPUT_DIR="${OUTPUT_DIR:-path/to/outdir}"

${SWIFT_BIN} sft \
--model "${MODEL_PATH}" \
--model_type minicpmv4_7 \
--template minicpmv4_7 \
--add_non_thinking_prefix true \
--run_name "${WANDB_RUN_NAME}" \
--dataset "${TRAIN_DATA}" \
--val_dataset "${VALID_DATA}" \
--deepspeed "${DEEPSPEED_CONFIG}" \
--experts_impl grouped_mm \
--tuner_type full \
--torch_dtype bfloat16 \
--freeze_vit False \
--freeze_aligner False \
--packing false \
--padding_side left \
--gradient_checkpointing true \
--max_length 4096 \
--num_train_epochs 4 \
--per_device_train_batch_size "${PER_DEVICE_TRAIN_BATCH_SIZE:-1}" \
--gradient_accumulation_steps "${GRADIENT_ACCUMULATION_STEPS:-16}" \
--learning_rate 5e-6 \
--warmup_ratio 0.05 \
--logging_steps 1 \
--save_steps 132 \
--eval_strategy steps \
--eval_steps 80 \
--save_total_limit 30 \
--load_from_cache_file false \
--dataset_num_proc 8 \
--dataloader_num_workers 4 \
--enable_channel_loss True \
--attn_impl sdpa \
--loss_scale ignore_empty_think \
--output_dir "${OUTPUT_DIR}" \
--report_to wandb

关键参数说明:

  • 训练支持 16x、4x 两种视觉 Token 压缩率,通过 DOWNSAMPLE_MODE 环境变量控制。
  • 对于这个基于 Qwen3.5 的模型,请使用 --packing false,与已验证的训练配置保持一致。
  • --add_non_thinking_prefix true 可以在训练提示词后加入 <think>\n\n</think>\n\n,实现无 thinking 训练。

35B-A3B:评测结果​

模型视觉 Token 压缩率Acc@0 Top1Acc@0 Avg.Top3
MiniCPM-V 4.7 35B-A3B1669.1N/A
MiniCPM-V 4.7 35B-A3B473.2N/A
Fine-tuned model1681.481.3
Fine-tuned model485.084.3

此处 Acc@0 Top1 为验证集 Acc@0 最高的 checkpoint 在测试集上的分数,Acc@0 Avg.Top3 为按验证集排名前三的 checkpoint 在测试集上的平均分数。

输出样例:

Plain Text
Q: Carefully observe the image. How many airplanes are there in the image? Answer with a single integer only.
A: 7

LLaMA-Factory​

安装​

Bash
git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git
cd LLaMA-Factory
pip install -e ".[torch,metrics,deepspeed,minicpm_v]"

构造数据​

参照 LLaMA-Factory data/ 下的 mllm_demo.json,按相同格式构造图片数据集。如需在多轮对话中使用图片,请在每轮对话的 user content 中添加 <image> 标签,<image> 标签数量需与 images 中的值数量相匹配。

JSON
[
{
"messages": [
{"content": "<image>Who are they?", "role": "user"},
{"content": "They're Kane and Gretzka from Bayern Munich.", "role": "assistant"},
{"content": "What are they doing?<image>", "role": "user"},
{"content": "They are celebrating on the soccer field.", "role": "assistant"}
],
"images": ["mllm_demo_data/1.jpg", "mllm_demo_data/1.jpg"]
}
]

视频数据集参照 mllm_video_demo.json,用 <video> 标签,数量需与 videos 匹配:

JSON
[
{
"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"]
}
]

注册数据集​

  1. 将构造的 JSON 文件命名为 image_caption.json,放到 LLaMA-Factory data/ 路径下。
  2. 打开 data/dataset_info.json,搜索 mllm_demo。
  3. 将键名 mllm_demo 改成自定义的数据集名称,如 cpmv_img;将 file_name 对应的值改成构造的数据集文件名。
JSON
"cpmv_img": {
"file_name": "image_caption.json",
"formatting": "sharegpt",
"columns": {
"messages": "messages",
"images": "images"
},
"tags": {
"role_tag": "role",
"content_tag": "content",
"user_tag": "user",
"assistant_tag": "assistant"
}
}

LoRA 微调​

创建配置文件 minicpmv4_7_lora_sft.yaml:

YAML
### model
model_name_or_path: openbmb/MiniCPM-V-4.7-1B # 也可填本地模型路径
trust_remote_code: true

### method
stage: sft
do_train: true
finetuning_type: lora
lora_target: q_proj,v_proj

### dataset
dataset: cpmv_img # 改成你在 data/dataset_info.json 中新增的键名
cutoff_len: 3072
max_samples: 1000
overwrite_cache: true
preprocessing_num_workers: 16

### output
output_dir: saves/minicpmv4_7/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

启动训练:

Bash
llamafactory-cli train configs/minicpmv4_7_lora_sft.yaml

训练完成后创建合并配置 minicpmv4_7_lora_export.yaml:

YAML
### model
model_name_or_path: openbmb/MiniCPM-V-4.7-1B # 原始模型地址
adapter_name_or_path: saves/minicpmv4_7/lora/sft # 保存的 LoRA 模型地址
finetuning_type: lora
trust_remote_code: true

### export
export_dir: models/minicpmv4_7_lora_sft
export_size: 2
export_device: cpu
export_legacy_format: false

合并模型:

Bash
llamafactory-cli export configs/minicpmv4_7_lora_export.yaml

全参数微调​

创建配置文件 minicpmv4_7_full_sft.yaml:

YAML
### model
model_name_or_path: openbmb/MiniCPM-V-4.7-1B
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: cpmv_img
cutoff_len: 3072
max_samples: 1000
overwrite_cache: true
preprocessing_num_workers: 16

### output
output_dir: saves/minicpmv4_7/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

启动训练:

Bash
llamafactory-cli train configs/minicpmv4_7_full_sft.yaml

LLaMA-Factory 的 template 字段需与所用模型匹配。若所装版本尚未内置 MiniCPM-V 4.7 模板,请更新到支持 MiniCPM-V 4.7 的版本,或改用上面的 ms-swift 流程。

相关资源​

微调完成后,可按部署把新权重接入服务,或先通过量化压缩体积。

主题入口
模型概览MiniCPM-V 4.7 概览
代码仓库OpenBMB/MiniCPM-V
官方微调文档finetune.md
ms-swift 框架modelscope/ms-swift
LLaMA-Factory 框架hiyouga/LLaMA-Factory