# 本地部署书生浦语最新多模态模型internVL3（支持50系显卡）

> 详细教程教你本地部署书生浦语最新多模态模型InternVL3-8B，支持50系显卡（RTX 50系列）。包含环境搭建、PyTorch cu128安装、模型下载及交互式测试脚本完整步骤。

- 来源: https://www.waytoagi.com/kb/learning-path/local-deploy-internvl3-8b
- 飞书原文: https://waytoagi.feishu.cn/wiki/E0ScwKO7WilX3Wk3AKgcoBzLnjg
- 更新于: 2026-10-23

---

> 作者：二师兄

前置软件：nodejs和python

必备软件：vscode、trae、cursor都行

1. 创建train_and_deploy文件夹（可自己命名），作为项目文件夹

2. 新建一个data文件夹，里面可以放一张测试图片，名为test.jpg

3. 下载模型，如F:\train_and_deploy\models

https://internvl.github.io/blog/2025-04-11-InternVL-3.0/，下载对应的大小，看自己配置选择HF或者魔搭，点击link即可进入模型下载页面

下面以8b为例

![](https://www.waytoagi.com/api/kb-media/K0VSbNZD6olXLPxFZwGcM4cGn4b)

![](https://www.waytoagi.com/api/kb-media/X085bpDOQo9QeJx7t1xcngYanEg)

1. 使用vscode等IDE工具，打开rain_and_deploy文件夹

2. 新建环境：

```python
conda create -n internvl3 python=3.10
```

1. 激活环境

```python
conda activate internvl3
```

1. 安装依赖

- pytorch和cuda必须安装，https://pytorch.org/

- 找到适合自己硬件的版本，50系显卡可以使用2.7.0和cuda128版本

![](https://www.waytoagi.com/api/kb-media/NEEPbyic1o1cBkxA3C7cHKqCnNe)

- 在终端命令行输入以下指令，进行安装

```python
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128

```

- 安装transformers

```python
pip install transformers
```

1. 先实现简单的交互，先创建一个简单的交互界面

- 在train_and_deploy文件夹新建test_internvl3.py

- 粘贴以下代码，注意替换模型路径以及测试图片的路径

```python
# test_internvl3.py - InternVL3-8B模型简单测试脚本

import os
import argparse
from PIL import Image
import torch
import torchvision.transforms as transforms
from transformers import AutoTokenizer, AutoModel
import time

def parse_args():
    parser = argparse.ArgumentParser(description="InternVL3-8B模型交互式测试")
    parser.add_argument("--model_path", type=str, default="F:/train_and_deploy/models/InternVL3-8B",
                        help="模型路径，默认为F:/train_and_deploy/models/InternVL3-8B")
    parser.add_argument("--image", type=str, default="data/test.jpg",
                        help="测试图片路径，默认为data/test.jpg")
    parser.add_argument("--device", type=str, default="cuda",
                        help="运行设备，默认为cuda")
    return parser.parse_args()

def main():
    args = parse_args()
    
    # 检查CUDA是否可用
    if args.device == "cuda" and not torch.cuda.is_available():
        print("CUDA不可用，切换到CPU")
        args.device = "cpu"
    
    # 加载模型
    print(f"正在加载模型: {args.model_path}")
    model = AutoModel.from_pretrained(
        args.model_path,
        torch_dtype=torch.bfloat16,  # 使用BF16可以减少内存消耗
        low_cpu_mem_usage=True,
        trust_remote_code=True
    ).to(args.device).eval()
    
    # 加载分词器
    tokenizer = AutoTokenizer.from_pretrained(args.model_path, trust_remote_code=True)
    
    # 确保图片存在
    if not os.path.exists(args.image):
        print(f"错误: 图片 {args.image} 不存在")
        return
    
    # 加载图片
    print(f"加载图片: {args.image}")
    image = Image.open(args.image)
    if image.mode != "RGB":
        image = image.convert("RGB")
    
    # 根据 preprocessor_config.json 创建图像预处理
    image_processor = transforms.Compose([
        transforms.Resize(448),  # 从preprocessor_config.json中获取的尺寸
        transforms.CenterCrop(448),  # 从preprocessor_config.json中获取的尺寸
        transforms.ToTensor(),
        transforms.Normalize(
            mean=[0.485, 0.456, 0.406],  # 从preprocessor_config.json中获取的归一化参数
            std=[0.229, 0.224, 0.225]  # 从preprocessor_config.json中获取的归一化参数
        )
    ])
    
    # 处理图像
    with torch.no_grad():
        # 应用预处理
        pixel_values = image_processor(image).unsqueeze(0)
        
        # 将图像转换为bfloat16类型，与模型的期望类型一致
        pixel_values = pixel_values.to(dtype=torch.bfloat16, device=args.device)
    
    # 交互式对话
    history = []
    print("\n=== InternVL3-8B 交互式对话 ===")
    print("输入'exit'退出对话")
    print("输入'clear'清除对话历史\n")
    
    while True:
        question = input("问题: ")
        
        if question.lower() == 'exit':
            break
        elif question.lower() == 'clear':
            history = []
            print("已清除对话历史")
            continue
        
        # 添加图像标记，如果需要
        if not history and '<image>' not in question:
            question = '<image>\n' + question
        
        try:
            print("模型思考中...")
            start_time = time.time()
            
            # 配置生成参数
            generation_config = {
                "max_new_tokens": 1024,
                "do_sample": True,
                "temperature": 0.6,
                "top_p": 0.8,
            }
            
            # 生成回答
            with torch.no_grad():
                # 使用chat方法
                response = model.chat(
                    tokenizer=tokenizer,
                    pixel_values=pixel_values,
                    question=question,
                    history=history,
                    generation_config=generation_config,
                    return_history=True,
                    verbose=False
                )
            
            # 更新历史
            history = response[1]
            end_time = time.time()
            
            # 打印回答
            print(f"\n回答 (用时 {end_time - start_time:.2f}秒):")
            print(response[0])
            print("-" * 50)
            
        except Exception as e:
            print(f"错误: {e}")
            import traceback
            traceback.print_exc()

if __name__ == "__main__":
    main()
```

- 保存后，在终端输入：

```python
python test_internvl3.py
```

![](https://www.waytoagi.com/api/kb-media/Lb06bZZRbo1PAuxVXg4c0uqdn6g)

运行成功后，输入问题，即可获得回复

如果需要指定某张图片，可输入（替换图片的路径）：

```python
python test_internvl3.py --image 您的图片路径.jpg

# 如：python test_internvl3.py --image  F:\train_and_deploy\data\images\marine\clownfish\小丑鱼_2.jpg
```

![](https://www.waytoagi.com/api/kb-media/Ox1FbH3yioB3dDxnIX2cKJU5nYd)

1. 使用gradio的web页面：

- 安装gradio

```python
conda activate internvl3
pip install gradio
pip install opencv-python
```

- 新建python文件，名为：gradio_web_demo.py

- 打开这个python文件，复制代码，注意替换model地址

![](https://www.waytoagi.com/api/kb-media/EPYkbd4XkoXc4DxVn0Pcaa3Zn4e)

```python
import gradio as gr
import torch
from PIL import Image
from transformers import AutoTokenizer, AutoModel
import torchvision.transforms as transforms

# 加载模型和分词器（只加载一次，提升速度）
MODEL_PATH = "F:/train_and_deploy/models/InternVL3-8B"
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"

tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)
model = AutoModel.from_pretrained(
    MODEL_PATH,
    torch_dtype=torch.bfloat16,
    low_cpu_mem_usage=True,
    trust_remote_code=True
).to(DEVICE).eval()

# 图像预处理
image_processor = transforms.Compose([
    transforms.Resize(448),
    transforms.CenterCrop(448),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])

def internvl3_chat(image, question, history=[]):
    # 图像预处理
    with torch.no_grad():
        pixel_values = image_processor(image).unsqueeze(0).to(dtype=torch.bfloat16, device=DEVICE)
    # 问题加上图片标记
    if not history and '<image>' not in question:
        question = '<image>\n' + question
    # 生成配置
    generation_config = {
        "max_new_tokens": 1024,
        "do_sample": True,
        "temperature": 0.6,
        "top_p": 0.8,
    }
    # 推理
    with torch.no_grad():
        response = model.chat(
            tokenizer=tokenizer,
            pixel_values=pixel_values,
            question=question,
            history=history,
            generation_config=generation_config,
            return_history=True,
            verbose=False
        )
    answer, new_history = response
    return answer, new_history

# Gradio界面
with gr.Blocks() as demo:
    gr.Markdown("# InternVL3-8B Web Demo")
    with gr.Row():
        with gr.Column():
            image_input = gr.Image(type="pil", label="上传图片")
            question_input = gr.Textbox(label="请输入你的问题", placeholder="例如：请描述这张图片的内容")
            submit_btn = gr.Button("提交")
        with gr.Column():
            answer_output = gr.Textbox(label="模型回复")
    state = gr.State([])  # 用于保存对话历史

    def on_submit(image, question, history):
        answer, new_history = internvl3_chat(image, question, history)
        return answer, new_history

    submit_btn.click(
        on_submit,
        inputs=[image_input, question_input, state],
        outputs=[answer_output, state]
    )

demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
```

- 在终端运行py文件

```python
python gradio_web_demo.py
```

![](https://www.waytoagi.com/api/kb-media/S3M7bCbq5ovrp4xDGU4cK2aEn7f)

用浏览器打开127.0.0.7860

![](https://www.waytoagi.com/api/kb-media/PDbhbXp4BoRTG4xnu45ckf5enzc)
