如何5分钟跑通InternVL3_5-2B-MPO:最完整的transformers多模态推理入门教程
如何5分钟跑通InternVL3_5-2B-MPO:最完整的transformers多模态推理入门教程
InternVL3_5-2B-MPO 是书生·万象(InternVL)开源的多模态大语言模型(MLLM)的轻量版本,约 2B 参数量,可通过 Hugging Face transformers 直接加载,支持"看图 + 理解 + 对话"的多模态推理。本教程面向新手和普通用户,带你用最少步骤跑通第一次多模态推理:加载模型 → 处理图片 → 发起对话。
为什么选择 InternVL3_5-2B-MPO?🎯
对刚接触多模态模型的朋友来说,InternVL3_5-2B-MPO 是一个"上手友好"的起点:
- 体积小巧:仅约 2.3B 参数,单张消费级/数据中心 GPU 即可运行,bf16 精度下显存占用约 4~6GB,门槛低。
- 开箱即用:遵循标准
transformers生态,AutoModel+AutoTokenizer两行代码即可加载,无需自建推理框架。 - 能力全面:继承 InternVL3.5 的"动态高分辨率"策略,支持纯文本对话、单图/多图理解、视频问答等场景。
- 对话模板已内置:使用
internvl2_5对话模板,默认系统提示词已配置好,无需手动拼装 prompt。
💡 版本小贴士:
MPO表示该模型完成了CPT + SFT + MPO(继续预训练 + 监督微调 + 混合偏好优化)训练阶段。如果你追求最强推理效果,官方建议优先选择不带任何后缀的完整流水线版本;MPO 版本适合做研究与轻量化部署。
架构与关键参数速览
InternVL3_5-2B-MPO 沿用 "ViT–MLP–LLM" 经典范式:视觉编码器(InternViT)+ MLP 投影 + 语言模型(Qwen3)。核心配置可在 config.json 中查到:
| 配置项 | 取值 | 含义 |
|---|---|---|
model_type |
internvl_chat |
模型类型,对应自定义模型实现 |
template |
internvl2_5 |
对话模板名 |
force_image_size |
448 |
单个图像 tile 的尺寸 |
downsample_ratio |
0.5 |
视觉特征下采样比例 |
min/max_dynamic_patch |
1 / 12 |
动态高分辨率的 tile 数量范围 |
torch_dtype |
bfloat16 |
推荐推理精度 |
模型主入口为 modeling_internvl_chat.py 中的 InternVLChatModel,对话模板定义在 conversation.py 的 internvl2_5(第 384 行附近)。
跑通前准备:环境与依赖 🛠️
在开始之前,先准备好运行环境。整个多模态推理入门只需要下面几步:
1. 安装核心依赖
pip install "transformers>=4.52.1" torch torchvision
⚠️ 官方明确要求
transformers>=4.52.1,版本过低可能导致加载失败。若使用use_flash_attn=True加速,还需额外安装flash-attn。
2. 获取模型仓库
如果希望通过本地目录加载,先 clone 仓库:
git clone https://gitcode.com/OpenGVLab/InternVL3_5-2B-MPO
仓库内是一个标准的 HF 模型目录,关键文件如下:
| 文件 | 作用 |
|---|---|
| config.json | 模型结构配置(ViT + LLM + 动态分辨率参数) |
| configuration_internvl_chat.py | 自定义 Config 类 |
| modeling_internvl_chat.py | 核心模型与 chat 推理接口 |
| modeling_intern_vit.py / configuration_intern_vit.py | 视觉编码器实现 |
| conversation.py | 对话模板(internvl2_5) |
| tokenizer_config.json / vocab.json / merges.txt | 分词器与词表 |
| model.safetensors | 模型权重 |
提示:你也可以直接把模型 ID(如
OpenGVLab/InternVL3_5-2B-MPO)传给from_pretrained,由库自动下载,省去手动 clone 步骤。
三步跑通:从加载到第一次对话 🚀
下面是最精简的"跑通"流程,建议按顺序执行。
第 1 步:加载模型与分词器
多模态推理入门最关键的一点:必须加上 trust_remote_code=True,否则会加载自定义代码失败。
import torch
from transformers import AutoModel, AutoTokenizer
path = "OpenGVLab/InternVL3_5-2B-MPO"
model = AutoModel.from_pretrained(
path,
torch_dtype=torch.bfloat16,
low_cpu_mem_usage=True,
use_flash_attn=True, # 若未安装 flash-attn,可改为 False
trust_remote_code=True,
device_map="auto").eval()
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
第 2 步:动态高分辨率预处理图片
InternVL 系列会把图片切成若干 448×448 的 tile,再附加一张缩略图,以保留细节。精简版预处理函数如下:
import torchvision.transforms as T
from torchvision.transforms.functional import InterpolationMode
from PIL import Image
MEAN, STD = (0.485, 0.456, 0.406), (0.229, 0.224, 0.225)
def build_transform(input_size=448):
return T.Compose([
T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
T.ToTensor(),
T.Normalize(mean=MEAN, std=STD)
])
def load_image(image_file, input_size=448, max_num=12):
image = Image.open(image_file).convert('RGB')
transform = build_transform(input_size)
tiles = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
return torch.stack([transform(t) for t in tiles])
dynamic_preprocess的完整实现可参考 README.md(第 468 行附近),它负责计算最合适的长宽比并切分 tile。对入门跑通而言,直接复用即可。
第 3 步:发起第一次多模态对话
核心是 model.chat 方法(见 modeling_internvl_chat.py 第 264 行)。提问时用 <image> 标记占位,模型会自动替换成对应的视觉 token。
pixel_values = load_image("./your_image.jpg", max_num=12).to(torch.bfloat16).cuda()
generation_config = dict(max_new_tokens=1024, do_sample=True)
# 纯文本对话
question = "你好,介绍一下你自己?"
print(model.chat(tokenizer, None, question, generation_config))
# 单图单轮对话:请描述这张图片
question = "<image>\n请简短描述这张图片。"
print(model.chat(tokenizer, pixel_values, question, generation_config))
看到模型输出的文字描述,说明你已经成功跑通了 InternVL3_5-2B-MPO 的多模态推理 🎉。
进阶玩法:让入门更完整 ✨
跑通之后,这些技巧能帮你快速扩展能力。
开启 Thinking(思考)模式
通过设置系统提示词,可以让模型先"分步思考"再作答,适合数学、科学推理等复杂任务:
R1_SYSTEM_PROMPT = (
"You are an AI assistant that rigorously follows this response protocol:\n"
"1. First, conduct a detailed analysis ... reason through the problem step-by-step. "
"Enclose this entire thinking process within <think> and </think> tags.\n"
"2. After the thinking section, provide a clear, concise, and direct answer.\n"
"Ensure the thinking process is thorough but focused. The final answer should be standalone."
).strip()
model.system_message = R1_SYSTEM_PROMPT
官方建议:开启思考模式时设置
do_sample=True、temperature=0.6,可缓解输出重复。
显存不够?用 8-bit 量化或多 GPU 拆分
针对资源有限的机器,可以切换加载策略:
# 8-bit 量化(显存更省)
model = AutoModel.from_pretrained(
path, torch_dtype=torch.bfloat16, load_in_8bit=True,
low_cpu_mem_usage=True, trust_remote_code=True).eval()
# 多 GPU 自动拆分(2B 通常单卡即可,此写法适用于更大模型)
model = AutoModel.from_pretrained(
path, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True,
trust_remote_code=True, device_map="auto").eval()
多轮对话与多图理解
chat 方法通过 history 参数维持上下文,return_history=True 会返回历史以便续接:
response, history = model.chat(tokenizer, pixel_values, "<image>\n详细描述这张图片。",
generation_config, history=None, return_history=True)
# 第二轮:基于同一张图追问,无需再传图
response, history = model.chat(tokenizer, pixel_values, "请根据图片写一首诗。",
generation_config, history=history, return_history=True)
多图场景下,把多张图的 pixel_values 沿维度 0 拼接,并通过 num_patches_list 告诉模型每张图各有多少个 tile 即可。
常见问题排查(FAQ)🔧
新手跑通时最容易卡在这几处,建议对照自查:
| 现象 | 可能原因 | 解决办法 |
|---|---|---|
加载报 trust_remote_code 相关错误 |
未开启自定义代码 | 所有 from_pretrained 加 trust_remote_code=True |
flash-attn 报错 |
未安装对应版本 | 安装 flash-attn,或将 use_flash_attn 设为 False |
| 输出为空 / 乱码 | transformers 版本过低 |
升级到 transformers>=4.52.1 |
| 显存不足 OOM | 精度或量化设置不当 | 改用 load_in_8bit=True 或 device_map="auto" |
| 图片理解偏差大 | tile 数量不足 | 适当调大 max_num(默认 12) |
小贴士:
use_fast=False是官方示例的默认分词器设置,保持默认即可避免行为差异。
项目文件导读 📚
想进一步理解这个多模态推理模型的内部实现,可以按下面的路径顺序阅读:
- 结构与配置:config.json(第 108 行
model_type: internvl_chat是入口标识) - 模型与推理接口:modeling_internvl_chat.py,重点看
chat/batch_chat/generate - 视觉编码器:modeling_intern_vit.py、configuration_intern_vit.py
- 对话模板:conversation.py 中的
internvl2_5模板 - 分词器:tokenizer_config.json、vocab.json、merges.txt
- 官方说明与完整示例:README.md 的 Quick Start 章节(第 354 行起)
总结
- 环境:
transformers>=4.52.1+torch+torchvision,clone 仓库或用模型 ID 自动下载。 - 加载:
AutoModel.from_pretrained+trust_remote_code=True,bf16 精度即可流畅运行。 - 预处理:动态高分辨率切分 tile + 缩略图,
max_num控制细节粒度。 - 对话:核心入口
model.chat,用<image>占位,history实现多轮。
按以上步骤,你可以在几分钟内跑通 InternVL3_5-2B-MPO 的完整多模态推理流程,并在此基础上开启思考模式、多图与多轮对话,进一步探索这个轻量而强大的开源多模态模型。