InternVL3_5-30B-A3B-Flash 图文对话实战:单图、多图、视频 10 个即用代码案例

原创2026-10-18 20:30:371,977 阅读

InternVL3_5-30B-A3B-Flash 图文对话实战:单图、多图、视频 10 个即用代码案例

InternVL3_5-30B-A3B-Flash 是 OpenGVLab 开源的图文对话多模态大模型,支持单图描述、多图对比和视频多轮对话。本文整理了 10 个可直接运行的实战代码案例,覆盖单图、多图、视频、批量推理、流式输出与量化部署,新手 5 分钟即可上手。

为什么值得先试这个 Flash 版本 🚀

InternVL3.5 系列是 OpenGVLab 推出的开源多模态大模型(MLLM),而 30B-A3B-Flash 是其中主打"高效"的一个版本,核心卖点有三个:

特性 说明
⚡ MoE 架构,推理快 基于 Qwen3-30B-A3B,总参数约 30B,但每 token 仅激活约 3B 参数,单张 A100 即可部署
🖼️ Visual Resolution Router(ViR) 按图像块语义丰富度动态路由视觉 token(256 → 64),视觉 token 减少约 50%,性能保持近 100%
🧠 完整训练流水线 经历 CPT + SFT + CascadeRL(离线 MPO + 在线 GSPO),推理与数学能力显著增强

Flash 模式由 config.json 中的 flash_mode: true 开启,单图最多支持 12 个切块(max_dynamic_patch: 12),细节还原能力更强。

一、环境快速搭建:装依赖、拉仓库、加载模型

1. 安装依赖并获取模型

pip install "transformers>=4.52.1" torch torchvision decord
git clone https://gitcode.com/OpenGVLab/InternVL3_5-30B-A3B-Flash.git

注意 transformers>=4.52.1,版本过低会导致模型加载报错。

2. 加载模型(多 GPU 自动分配)

import torch
from transformers import AutoModel, AutoTokenizer

path = "OpenGVLab/InternVL3_5-30B-A3B-Flash"
model = AutoModel.from_pretrained(
    path,
    torch_dtype=torch.bfloat16,
    low_cpu_mem_usage=True,
    use_flash_attn=True,
    trust_remote_code=True,
    device_map="auto").eval()
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
generation_config = dict(max_new_tokens=1024, do_sample=True)

两个必记参数:tokenizer 必须 use_fast=False,模型必须 trust_remote_code=True(模型定义了自定义推理代码,见 modeling_internvl_chat.py)。

图片/视频的前处理函数 load_image、load_video(含动态高分辨率切块 dynamic_preprocess)完整代码见 README.md 的 Quick Start 一节,复制后即可使用。

二、10 个即用代码案例

案例 1:纯文本对话(不含图片)

question = '你好,请介绍一下你自己。'
response, history = model.chat(tokenizer, None, question, generation_config,
                               history=None, return_history=True)
print(f'User: {question}\nAssistant: {response}')

pixel_values 传 None 即可进入纯文本模式,return_history=True 会返回对话历史供多轮续接。

案例 2:单图单轮描述

pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()

question = '<image>\n请用一句话简短描述这张图片。'
response = model.chat(tokenizer, pixel_values, question, generation_config)
print(f'User: {question}\nAssistant: {response}')

关键就是 <image> 占位符:它会被模型自动展开为视觉 token 序列(实现见 modeling_internvl_chat.py#L505-L514)。

案例 3:单图多轮追问(history 续接)

# 第一轮:先描述
question = '<image>\n请详细描述这张图片。'
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
                               history=None, return_history=True)

# 第二轮:基于同一张图追问,无需再传 <image>
question = '请根据这张图片写一首短诗。'
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
                               history=history, return_history=True)

多轮对话的核心是把上一轮返回的 history 传给下一轮,模型会自动记住上下文(对话模板定义在 conversation.py)。

案例 4:开启 Thinking 深度思考模式

处理数学、逻辑题时,设置官方思考系统提示词:

R1_SYSTEM_PROMPT = """
You are an AI assistant that rigorously follows this response protocol:

1. First, conduct a detailed analysis of the question. Consider different angles,
   potential solutions, and reason through the problem step-by-step.
   Enclose this entire thinking process within  and  tags.

2. After the thinking section, provide a clear, concise, and direct answer
   to the user's question.
""".strip()

model.system_message = R1_SYSTEM_PROMPT
generation_config = dict(max_new_tokens=2048, do_sample=True, temperature=0.6)

官方建议:开启思考模式时设置 do_sample=True 且 temperature=0.6,可避免输出重复。

案例 5:多图对比(拼接方式)

两张图的切块直接 torch.cat 拼接,一个 <image> 代表全部图像:

pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)

question = '<image>\n请详细描述这两张图片。'
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
                               history=None, return_history=True)

question = '这两张图有什么相同点和不同点?'
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
                               history=history, return_history=True)

案例 6:多图对比(独立编号方式,更精准)

给每张图单独编号,模型能准确区分"图 1 / 图 2":

num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]  # 每张图的切块数

question = 'Image-1: <image>\nImage-2: <image>\n请比较这两张图的异同。'
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
                               num_patches_list=num_patches_list,
                               history=None, return_history=True)

💡 两种方式的区别:拼接方式 token 更省;独立编号方式通过 num_patches_list 告知模型每张图的边界(接口定义见 modeling_internvl_chat.py#L505-L507),指代更精确。

案例 7:单图批量推理(batch_chat)

一次推理多张图、每个样本独立提问,适合批量打标场景:

num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)

questions = ['<image>\n请详细描述图片。'] * len(num_patches_list)
responses = model.batch_chat(tokenizer, pixel_values,
                              num_patches_list=num_patches_list,
                              questions=questions,
                              generation_config=generation_config)

for q, r in zip(questions, responses):
    print(f'User: {q}\nAssistant: {r}')

注意 batch_chat 不支持多轮对话(history 传值会抛异常),实现见 modeling_internvl_chat.py#L456-L503。

案例 8:视频多轮对话

视频会被均匀抽帧(num_segments),每帧按图片切块处理:

video_path = './examples/red-panda.mp4'
pixel_values, num_patches_list = load_video(video_path, 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 + '视频里的小熊猫在做什么?'

response, history = model.chat(tokenizer, pixel_values, question, generation_config,
                               num_patches_list=num_patches_list,
                               history=None, return_history=True)

question = '请更详细地描述这个视频。'
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
                               num_patches_list=num_patches_list,
                               history=history, return_history=True)

抽帧数 num_segments(8~32)直接影响 token 消耗和延迟,短视频建议 8 帧起步。视频帧默认按 384×384 处理,见 video_preprocessor_config.json。

案例 9:流式输出(打字机效果)

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)

案例 10:8-bit 量化加载(显存不够时的救星)

显存不足 80G 时,用 BNB 8-bit 量化加载:

model = AutoModel.from_pretrained(
    path,
    torch_dtype=torch.bfloat16,
    load_in_8bit=True,        # 关键:启用 8-bit 量化
    low_cpu_mem_usage=True,
    use_flash_attn=True,
    trust_remote_code=True).eval()

多卡推理则改用 device_map="auto" 自动切分,30B 模型官方支持单卡 A100 部署,38B 及以上需双卡。

三、关键参数速查表 ⚙️

参数 建议值 作用
max_num 12(默认上限) 单图最大切块数,越大细节越准、token 越多
num_segments 8~32 视频抽帧数,控制视频理解精度与速度平衡
num_patches_list 按图计算 多图/视频场景下每张图的切块数列表
do_sample / temperature True / 0.6 Thinking 模式官方推荐组合
max_new_tokens 1024 起 生成最大长度,思考模式建议调大

图像预处理参数(448×448、max/min patches 1~12)定义在 preprocessor_config.json,词表与特殊 token 见 tokenizer_config.json 和 special_tokens_map.json。

四、常见坑位与排错指南 🛠️

  • 加载报错:先确认 transformers>=4.52.1,且 trust_remote_code=True 未遗漏。
  • 输出乱码/重复:多为 tokenizer 误用了 fast 版本,务必 use_fast=False。
  • 多图答非所问:想精确指代某张图时,改用案例 6 的 Image-1: <image> 编号方式。
  • 视频太慢:调低 num_segments(如 8),并给每帧设 max_num=1。
  • 显存不足:按案例 10 启用 load_in_8bit=True。

五、相关文件索引

文件 用途
README.md 完整使用文档:前处理函数、Thinking 模式、LMDeploy/vLLM 部署
modeling_internvl_chat.py 主模型推理代码,chat / batch_chat 入口
modeling_intern_vit.py 视觉编码器 InternViT 实现
conversation.py 对话模板(internvl2_5 模板)
config.json 模型总配置(Flash 开关、动态切块参数)
preprocessor_config.json / video_preprocessor_config.json 图像 / 视频预处理参数

写在最后

InternVL3_5-30B-A3B-Flash 用 MoE 稀疏激活 + 视觉 token 路由压缩的组合,在 30B 档位做到了"单卡可跑、速度快、不掉性能"。以上 10 个案例从纯文本、单图、多图、视频到批量、流式、量化,基本覆盖日常图文对话开发的 90% 场景——把代码抄走,换上你自己的图片路径,就可以开工了。🎉

登录后查看全文
InternVL3_5-30B-A3B-Flash