InternVL2_5-4B-MPO多模态实战指南:多图对比、视频理解与流式输出10种玩法
InternVL2_5-4B-MPO多模态实战指南:多图对比、视频理解与流式输出10种玩法
InternVL2_5-4B-MPO 是 OpenGVLab 推出的 MPO(Mixed Preference Optimization,混合偏好优化)多模态大语言模型,在图文理解、多图对比与视频理解等任务上表现出色。本文带你从加载模型开始,逐一演示纯文本对话、单图问答、多图对比、视频理解、流式输出与 LMDeploy 部署等 10 种实战玩法,帮助你在 4B 级轻量模型上快速跑通生产级多模态应用。
💡 图中素材来自官方示例目录,既是 examples/image1.jpg 图片问答素材,也与 examples/red-panda.mp4 视频理解示例同源,方便你直接复现下文玩法。
一、认识 InternVL2_5-4B-MPO:MPO 加持的多模态模型
InternVL2.5-MPO 系列基于 InternVL2.5 底座,通过混合偏好优化(MPO)进一步强化推理能力。MPO 将训练目标拆解为三部分加权求和:
- 偏好损失(DPO):学习成对回答的相对优劣
- 质量损失(BCO):学习单个回答的绝对质量
- 生成损失(SFT):学习偏好回答的生成过程
其中 4B 版本组合了 InternViT-300M 视觉编码器与 Qwen2.5-3B-Instruct 语言模型,是"轻量高性能"的代表。官方评测显示,相比基础版 InternVL2-5-4B(Avg 65.1),MPO 版本提升到 67.6,在 MMStar、MathVista、OCRBench 等基准上全面领先,尤其在数学推理与 OCR 场景收益明显。
📊 完整评测数据与模型家族对照表见 README.md。
二、模型架构:动态分辨率与多图视频支持
InternVL2_5-4B-MPO 延续了 InternVL 系列的 ViT-MLP-LLM 三段式范式:
- 视觉端:InternViT 将图像切分为 448×448 的动态分辨率图块(tile),再经 pixel unshuffle 将视觉 token 压缩到原始的 1/4,兼顾细节与效率
- 投影层:随机初始化的 MLP 桥接视觉与语言空间
- 语言端:Qwen2.5-3B-Instruct 负责理解与生成
关键能力:多图输入与视频帧序列支持是 2.0 之后的核心增强,这让"多图对比""视频理解"成为原生能力,而非外挂。架构配置可在 config.json 中查看,如 max_dynamic_patch: 12、use_thumbnail: true 等参数。
三、快速开始:加载模型与量化方案
一键加载(16-bit bf16)
import torch
from transformers import AutoTokenizer, AutoModel
model = AutoModel.from_pretrained(
"OpenGVLab/InternVL2_5-4B-MPO",
torch_dtype=torch.bfloat16,
low_cpu_mem_usage=True,
use_flash_attn=True,
trust_remote_code=True
).eval().cuda()
tokenizer = AutoTokenizer.from_pretrained(
"OpenGVLab/InternVL2_5-4B-MPO", trust_remote_code=True)
⚠️ 请确保
transformers>=4.37.2,并开启trust_remote_code=True加载自定义建模代码。
显存不足?用 8-bit 量化
model = AutoModel.from_pretrained(
"OpenGVLab/InternVL2_5-4B-MPO",
torch_dtype=torch.bfloat16,
load_in_8bit=True, # 关键:启用 BNB 8-bit
low_cpu_mem_usage=True,
use_flash_attn=True,
trust_remote_code=True
).eval()
多卡推理
多卡场景需手动分配 device_map,确保 LLM 首尾层在同一设备,避免张量跨卡报错。官方 split_model() 实现见 README.md 的 "Multiple GPUs" 章节。
四、10种玩法实战
以下玩法均基于 model.chat()(实现见 modeling_internvl_chat.py)与 batch_chat()(modeling_internvl_chat.py)。统一准备生成配置:
generation_config = dict(max_new_tokens=1024, do_sample=True)
玩法 1:纯文本对话
不传图像时,模型退化为纯 LLM,适合闲聊与知识问答。
question = 'Hello, who are you?'
response = model.chat(tokenizer, None, question, generation_config)
玩法 2:单图单轮对话
用 load_image() 加载图像并动态切块,在问题前加 <image> 占位符。
pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
question = '<image>\nPlease describe the image shortly.'
response = model.chat(tokenizer, pixel_values, question, generation_config)
max_num控制单图最多切块数(默认 12),图像越复杂、细节越多可设为上限。
玩法 3:单图多轮对话
通过 history 维持上下文,无需每轮重复传图。
response, history = model.chat(tokenizer, pixel_values, question,
generation_config, history=None, return_history=True)
# 第二轮:沿用同一张图,追问"根据图片写一首诗"
response, history = model.chat(tokenizer, pixel_values,
'Please write a poem according to the image.',
generation_config, history=history, return_history=True)
玩法 4:多图对比 — 拼接图像
将多张图的 pixel_values 沿维度 0 拼接,用一个 <image> 指代整体。
pv1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
pv2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
pixel_values = torch.cat((pv1, pv2), dim=0)
question = '<image>\nDescribe the two images in detail.'
response = model.chat(tokenizer, pixel_values, question, generation_config)
玩法 5:多图对比 — 独立图像
用 Image-1: <image> 编号 + num_patches_list 精确指定每张图的图块数,对比更精准。
num_patches_list = [pv1.size(0), pv2.size(0)]
question = 'Image-1: <image>\nImage-2: <image>\nWhat are the similarities and differences?'
response = model.chat(tokenizer, pixel_values, question, generation_config,
num_patches_list=num_patches_list)
玩法 6:批量推理(单图批处理)
一次处理多张图、多个问题,吞吐显著提升,适合离线批处理。
questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)
responses = model.batch_chat(tokenizer, pixel_values,
num_patches_list=num_patches_list,
questions=questions,
generation_config=generation_config)
玩法 7:视频理解
用 load_video() 按 num_segments 抽帧,逐帧拼接为 Frame1/Frame2… 前缀,一次读懂整个视频。
pixel_values, num_patches_list = load_video(
'./examples/red-panda.mp4', num_segments=8, max_num=1)
pixel_values = pixel_values.to(torch.bfloat16).cuda()
video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])
question = video_prefix + 'What is the red panda doing?'
response = model.chat(tokenizer, pixel_values, question, generation_config,
num_patches_list=num_patches_list)
玩法 8:视频多轮对话
沿用视频上下文继续追问,例如"详细描述这个视频"。
response, history = model.chat(tokenizer, pixel_values, question,
generation_config, num_patches_list=num_patches_list,
history=None, return_history=True)
# 第二轮追问
question = 'Describe this video in detail.'
response, history = model.chat(tokenizer, pixel_values, question,
generation_config, num_patches_list=num_patches_list,
history=history, return_history=True)
玩法 9:流式输出(Streaming Output)
借助 TextIteratorStreamer + 线程,实现逐字实时输出,体验接近 ChatGPT。
from transformers import TextIteratorStreamer
from threading import Thread
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True,
skip_special_tokens=True, timeout=10)
generation_config = dict(max_new_tokens=1024, do_sample=False, streamer=streamer)
thread = Thread(target=model.chat, kwargs=dict(
tokenizer=tokenizer, pixel_values=pixel_values, question=question,
history=None, return_history=False, generation_config=generation_config))
thread.start()
for new_text in streamer:
if new_text == model.conv_template.sep:
break
print(new_text, end='', flush=True)
对话模板
internvl2_5定义见 conversation.py,sep用于标识一轮回答结束。
玩法 10:LMDeploy 一键部署
不想手写推理逻辑?LMDeploy 把 VLM 推理封装成 LLM 同款管线,一条命令起服务。
from lmdeploy import pipeline, TurbomindEngineConfig
from lmdeploy.vl import load_image
model = 'OpenGVLab/InternVL2_5-4B-MPO'
pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
image = load_image('./examples/image1.jpg')
response = pipe(('describe this image', image))
print(response.text)
启动 OpenAI 兼容 API 服务:
pip install lmdeploy>=0.6.4
lmdeploy serve api_server OpenGVLab/InternVL2_5-4B-MPO --server-port 23333
🚀 多图输入会推高 token 数,记得按需调大
session_len;服务细节见 README.md "LMDeploy" 章节。
五、总结与选型建议
InternVL2_5-4B-MPO 用 4B 参数覆盖了从纯文本对话到视频理解的完整多模态链路,MPO 优化让其在推理与 OCR 上明显更稳。选型建议:
| 场景 | 推荐玩法 | 关键点 |
|---|---|---|
| 资源充足、追求精度 | 玩法 1-8 原生推理 | bf16 + flash_attn |
| 显存紧张 | 8-bit 量化 | load_in_8bit=True |
| 离线批量任务 | 玩法 6 批量推理 | batch_chat() 提吞吐 |
| 面向用户的实时应用 | 玩法 9 流式输出 | TextIteratorStreamer |
| 生产服务化 | 玩法 10 LMDeploy | OpenAI 兼容 API |
📚 更多微调(SWIFT、XTuner)、部署与数据集构建细节,可查阅 README.md 的 "Finetune / Deployment" 章节,视觉模型实现位于 modeling_intern_vit.py。
上手路径:先跑通玩法 2 建立信心 → 再尝试玩法 4/5 的多图对比 → 最后用玩法 9 或 10 落地到你的产品。
