5分钟跑通 InternVL3-38B-Instruct:视觉语言模型(MLLM)快速上手完全指南

原创2026-10-18 20:09:521,420 阅读

5分钟跑通 InternVL3-38B-Instruct:视觉语言模型(MLLM)快速上手完全指南

InternVL3-38B-Instruct 是 OpenGVLab 开源的 38B 参数视觉语言模型(MLLM,Multimodal LLM)SFT 指令版,一个模型就能完成图像理解、视频理解、OCR、多图对比和多轮视觉对话。这篇教程面向新手,教你 5 分钟完成环境配置、加载模型并跑通第一次图文问答,即使没有多模态开发经验也能顺利上手。

InternVL3-38B-Instruct 是什么?

InternVL3-38B-Instruct 沿用了 "ViT-MLP-LLM" 经典三段式架构:

组件 型号 作用
视觉编码器 ViT InternViT-6B(448px) 提取图像特征
投影层 MLP 随机初始化 对齐视觉与语言特征空间
语言模型 LLM Qwen2.5-32B 生成自然语言回答

它的几个亮点能力:

  • 🖼️ 动态分辨率:图像按 448×448 切块,最多 12 个 tile + 1 张缩略图,小图省资源、大图不丢细节
  • 📸 多图/视频理解:支持多图拼接、独立多图和视频帧序列输入
  • 💬 多轮对话:通过 history 参数天然支持上下文连续问答
  • ⚡ 原生多模态预训练:纯文本能力也强于同参数 Qwen2.5 系列

仓库核心文件一览(下文代码均基于这些文件):

文件 说明
config.json 模型主配置(含 llm_config、vision_config)
modeling_internvl_chat.py 聊天模型实现,model.chat() 入口
modeling_intern_vit.py InternViT 视觉编码器实现
configuration_internvl_chat.py 自定义配置类
conversation.py 对话模板 internvl2_5
tokenizer.json、vocab.json 词表与分词器
examples/image1.jpg、examples/red-panda.mp4 官方示例图与视频

硬件要求:一张表看懂显存配置

38B 参数的 bf16 权重约 76GB,单张消费级显卡放不下,请按你的硬件选择加载方式:

精度 / 方式 显存需求 适用场景
16-bit(bf16/fp16) ≥3 张 80GB(如 A100/H100) 最高精度,研究基准
BNB 8-bit 量化 2 张 80GB 生产/演示首选
LMDeploy 部署 2 张卡 tp=2 高并发服务

💡 提示:load_in_8bit=True 时必须搭配 device_map 多卡切分,不能简单 .cuda() 到单卡。

环境准备:3 条命令装好依赖

模型基于 transformers 的 trust_remote_code 机制加载,仓库内已附带全部自定义代码,无需额外克隆代码仓库:

pip install torch torchvision
pip install transformers>=4.45.1
pip install "flash-attn" --no-build-isolation   # 可选,加速推理
pip install decord pillow                        # 视频与图像处理依赖

然后把模型权重下载到本地(如 /data/InternVL3-38B-Instruct),本仓库中的所有配置文件即为其组成部分。

快速加载模型:最小化代码模板

单卡/多卡统一写法(推荐)——关键参数 trust_remote_code=True 会自动加载仓库内的 configuration_internvl_chat.py 和 modeling_internvl_chat.py:

import torch
from transformers import AutoTokenizer, AutoModel

path = "/data/InternVL3-38B-Instruct"   # 本地权重路径
model = AutoModel.from_pretrained(
    path,
    torch_dtype=torch.bfloat16,
    load_in_8bit=True,          # 两张 80GB 显卡设为 True
    low_cpu_mem_usage=True,
    use_flash_attn=True,
    trust_remote_code=True).eval()
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)

多卡显存不够时的切分方案:官方建议第一张卡只放半个 LLM(因为要容纳 ViT),首尾层必须同一设备,否则会报 tensor device 不一致错误。完整切分逻辑见 README.md 的 split_model() 函数,核心思想是按层把 language_model.model.layers.* 均匀分配到各卡。

第一次图文对话:问模型"图里有什么"

模型自带动态分辨率预处理,下面是最小可用的图像对话流程(示例图直接用仓库内的 examples/image1.jpg):

InternVL3-38B-Instruct 视觉语言模型示例图:小熊猫

import torch
from PIL import Image
import torchvision.transforms as T
from torchvision.transforms.functional import InterpolationMode

IMAGENET_MEAN = (0.485, 0.456, 0.406)
IMAGENET_STD  = (0.229, 0.224, 0.225)

def load_image(image_file, input_size=448, max_num=12):
    image = Image.open(image_file).convert('RGB')
    transform = T.Compose([
        T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
        T.ToTensor(),
        T.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)
    ])
    # 完整动态切块实现(dynamic_preprocess)见 README.md
    images = image                      # 简化:单 tile 示例
    return torch.stack([transform(img) for img in images])

pixel_values = load_image('examples/image1.jpg').to(torch.bfloat16).cuda()
generation_config = dict(max_new_tokens=1024, do_sample=True)

question = '<image>\nPlease describe the image shortly.'
response = model.chat(tokenizer, pixel_values, question, generation_config)
print(f'User: {question}\nAssistant: {response}')

⚠️ 注意:多模态问题必须以 <image> 占位符开头,再换行写用户问题,这是 internvl2_5 对话模板的固定格式。

多轮视觉对话只需传入 history,模型会自动记住上一轮的图片与答案:

question1 = '<image>\nPlease describe the image in detail.'
response, history = model.chat(tokenizer, pixel_values, question1,
                               generation_config, history=None, return_history=True)

question2 = 'Please write a poem according to the image.'
response = model.chat(tokenizer, pixel_values, question2,
                      generation_config, history=history)

视频理解与图像同理:用 decord 按帧采样(如 8 帧),每帧前缀 Frame1: <image>\n,即可问出 "What is the red panda doing?",官方完整实现见 README.md 的 load_video() 函数,示例视频为 examples/red-panda.mp4。

高频参数与避坑清单

新手最常卡住的 5 个点,提前规避能省下大量调试时间:

问题 / 参数 说明
use_fast=False tokenizer 必须关闭 fast 模式,否则特殊 token 处理异常
trust_remote_code=True 漏掉它会出现 AutoConfig 无法识别 internvl_chat 的错误
max_num=12 动态切块上限,4K 大图调大可提升细节,但显存与速度同增
do_sample=True 采样模式回答更自然;False 则结果可复现,适合评测
多图输入 torch.cat 拼接多图 pixel_values,并用 num_patches_list 标注每张图的块数

更多参数含义可对照 config.json:max_dynamic_patch: 12 对应切块上限,use_thumbnail: true 表示自动附加缩略图 tile。

部署与进阶:从 Notebook 到 API 服务

本地跑通后,生产环境推荐 LMDeploy(Turbomind 引擎,速度更快,tp=2 双卡即可跑 38B):

pip install "lmdeploy>=0.7.3"
lmdeploy serve api_server OpenGVLab/InternVL3-38B --chat-template internvl2_5 --server-port 23333 --tp 2

启动后暴露 OpenAI 兼容 RESTful 接口,业务代码只需把 base_url 换成 http://0.0.0.0:23333/v1 即可无缝迁移,多模态消息体用 image_url 字段传图。

其他进阶方向:

  • 🎯 微调:SWIFT、XTuner 等框架已支持 InternVL3 系列,适合注入领域知识
  • 📈 推理增强:MPO 混合偏好优化 + Best-of-N 测试时扩展可显著提升数学与逻辑推理表现
  • 🔍 系列选型:显存有限可换 InternVL3-8B(约 16GB 显存);追求极限效果选 InternVL3-78B

总结:你的 MLLM 上手路线

  1. ✅ 按硬件选择 bf16 或 8-bit 量化加载方式
  2. ✅ AutoModel.from_pretrained + trust_remote_code=True 三行代码加载模型
  3. ✅ <image> 占位符 + model.chat() 完成第一次图文问答
  4. ✅ history / num_patches_list 解锁多轮与多图能力
  5. ✅ LMDeploy 一键部署成 OpenAI 兼容 API

至此,你已经用不到 5 分钟跑通了 InternVL3-38B-Instruct 视觉语言模型的完整推理链路。接下来不妨试试用自己的产品截图做 OCR、用监控视频做行为描述,把这个强大的开源 MLLM 真正用起来 🚀

登录后查看全文
InternVL3-38B-Instruct