MiniCPM-V 4.7
MiniCPM-V 多模态系列
从一张图片和一个问题开始,跑通首次对话,再尝试多图比较、视频理解、OCR、PDF 解析与视觉定位。选择与你任务相符的示例,逐步搭建自己的多模态应用。
MiniCPM-V 4.7 已在 transformers >= 5.18.0 中注册为独立架构 MiniCPMV4_7ForConditionalGeneration,标准 HuggingFace Processor + model.generate 流程即可使用,无需 trust_remote_code。
MiniCPM-V 4.7 有两个尺寸,改 model_path 即可切换:
model_path | 尺寸 |
|---|---|
openbmb/MiniCPM-V-4.7-1B | dense 1B(端侧) |
openbmb/MiniCPM-V-4.7-35B-A3B | MoE 35B-A3B(高吞吐) |
安装
Bash
pip install "transformers[torch]>=5.18.0" torchvision torchcodec
CUDA 提示
torchcodec(视频解码)对 CUDA 版本较敏感。若遇到 RuntimeError: Could not load libtorchcodec,可改用 PyAV:
pip install "transformers[torch]>=5.18.0" torchvision av
或在装 torch 时指定匹配的 CUDA(如 CUDA 12.8):
pip install "transformers>=5.18.0" torchvision torchcodec --index-url https://download.pytorch.org/whl/cu128
初始化模型
下面各示例共用这段初始化代码。
Python
import torch
from PIL import Image
from transformers import AutoProcessor, AutoModelForImageTextToText
model_path = "openbmb/MiniCPM-V-4.7-1B" # 或 "openbmb/MiniCPM-V-4.7-35B-A3B"
processor = AutoProcessor.from_pretrained(model_path)
model = AutoModelForImageTextToText.from_pretrained(
model_path,
dtype="auto",
device_map="auto",
attn_implementation="sdpa", # 或 "flash_attention_2"
).eval()
思考模式
MiniCPM-V 4.7 每个尺寸只有一个 checkpoint:对话模 板默认带 <think> 块,除非传入 chat_template_kwargs={"enable_thinking": False}。
- 重 OCR / 推理类任务可保留思考,模型会先审视版面再作答。
- 普通问答建议关闭,以获得更快的直答。
单图问答
Python
image = Image.open("./assets/single.png").convert("RGB")
# 第一轮
question = "图中是什么地貌?"
messages = [{
"role": "user",
"content": [
{"type": "image", "image": image},
{"type": "text", "text": question},
],
}]
inputs = processor.apply_chat_template(
messages,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
return_tensors="pt",
chat_template_kwargs={"enable_thinking": False},
).to(model.device)
out_ids = model.generate(**inputs, max_new_tokens=512)
answer = processor.decode(
out_ids[0][inputs["input_ids"].shape[-1]:],
skip_special_tokens=True,
)
print(answer)