Open the WaytoAGI knowledge base on Feishu · 100M+ visits, open to everyone →
WaytoAGI

Knowledge Base · Learning paths

Local Deployment of InternVL3: Latest Multimodal Model from Shanghai AI Lab (Supports RTX 50 Series GPUs)

Step-by-step English tutorial for locally deploying the latest InternVL3-8B multimodal model from Shanghai AI Laboratory (InternLM). This guide covers environment setup, PyTorch CUDA 12.8 installation, model download, and interactive testing scripts, fully compatible with NVIDIA RTX 50-series graphics cards.

InternVL3local deploymentmultimodal modelRTX 50 seriesInternVL3-8B

Translated from Chinese by AI. Spotted an issue? Use the feedback button.

Author: Er Shixiong

Prerequisites: Node.js and Python

Required software: VS Code, Trae, or Cursor—any of these will work

  1. Create a folder named train_and_deploy (or choose your own name) to serve as the project folder

  2. Create a data folder inside it. You can place a test image named test.jpg in this folder

  3. Download the model to a directory such as F:\train_and_deploy\models

https://internvl.github.io/blog/2025-04-11-InternVL-3.0/, download a model size that suits your hardware. Choose HF or ModelScope, then click the link to open the model download page

The following example uses the 8B model

  1. Open the rain_and_deploy folder in an IDE such as VS Code

  2. Create a new environment:

python
conda create -n internvl3 python=3.10
  1. Activate the environment
python
conda activate internvl3
  1. Install dependencies
  • PyTorch and CUDA are required: https://pytorch.org/

  • Find a version compatible with your hardware. For 50-series GPUs, you can use PyTorch 2.7.0 with CUDA 12.8

  • Enter the following command in your terminal to install them
python
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128

  • Install transformers
python
pip install transformers
  1. Start with basic interaction by creating a simple interactive interface
  • Create test_internvl3.py in the train_and_deploy folder

  • Paste the following code, making sure to replace the model path and test image path

python

# test_internvl3.py - Simple test script for the InternVL3-8B model

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="Interactive testing for the InternVL3-8B model")
    parser.add_argument("--model_path", type=str, default="F:/train_and_deploy/models/InternVL3-8B",
                        help="Model path, defaults to F:/train_and_deploy/models/InternVL3-8B")
    parser.add_argument("--image", type=str, default="data/test.jpg",
                        help="Test image path, defaults to data/test.jpg")
    parser.add_argument("--device", type=str, default="cuda",
                        help="Device to run on, defaults to cuda")
    return parser.parse_args()

def main():
    args = parse_args()
    
    # Check whether CUDA is available
    if args.device == "cuda" and not torch.cuda.is_available():
        print("CUDA is unavailable; switching to CPU")
        args.device = "cpu"
    
    # Load the model
    print(f"Loading model: {args.model_path}")
    model = AutoModel.from_pretrained(
        args.model_path,
        torch_dtype=torch.bfloat16,  # Use BF16 to reduce memory usage
        low_cpu_mem_usage=True,
        trust_remote_code=True
    ).to(args.device).eval()
    
    # Load the tokenizer
    tokenizer = AutoTokenizer.from_pretrained(args.model_path, trust_remote_code=True)
    
    # Ensure the image exists
    if not os.path.exists(args.image):
        print(f"Error: Image {args.image} does not exist")
        return
    
    # Load the image
    print(f"Loading image: {args.image}")
    image = Image.open(args.image)
    if image.mode != "RGB":
        image = image.convert("RGB")
    
    # Create an image preprocessing pipeline based on preprocessor_config.json
    image_processor = transforms.Compose([
        transforms.Resize(448),  # Size from preprocessor_config.json
        transforms.CenterCrop(448),  # Size from preprocessor_config.json
        transforms.ToTensor(),
        transforms.Normalize(
            mean=[0.485, 0.456, 0.406],  # Normalization parameters from preprocessor_config.json
            std=[0.229, 0.224, 0.225]  # Normalization parameters from preprocessor_config.json
        )
    ])
    
    # Process the image
    with torch.no_grad():
        # Apply preprocessing
        pixel_values = image_processor(image).unsqueeze(0)
        
        # Convert the image to bfloat16 to match the model's expected data type
        pixel_values = pixel_values.to(dtype=torch.bfloat16, device=args.device)
    
    # Interactive chat
    history = []
    print("\n=== InternVL3-8B Interactive Chat ===")
    print("Enter 'exit' to quit the chat")
    print("Enter 'clear' to clear the chat history\n")
    
    while True:
        question = input("Question: ")
        
        if question.lower() == 'exit':
            break
        elif question.lower() == 'clear':
            history = []
            print("Chat history cleared")
            continue
        
        # Add an image marker if needed
        if not history and '<image>' not in question:
            question = '<image>\n' + question
        
        try:
            print("The model is thinking...")
            start_time = time.time()
            
            # Configure generation parameters
            generation_config = {
                "max_new_tokens": 1024,
                "do_sample": True,
                "temperature": 0.6,
                "top_p": 0.8,
            }
            
            # Generate a response
            with torch.no_grad():
                # Use the chat method
                response = model.chat(
                    tokenizer=tokenizer,
                    pixel_values=pixel_values,
                    question=question,
                    history=history,
                    generation_config=generation_config,
                    return_history=True,
                    verbose=False
                )
            
            # Update the history
            history = response[1]
            end_time = time.time()
            
            # Print the response
            print(f"\nResponse (time taken: {end_time - start_time:.2f} seconds):")
            print(response[0])
            print("-" * 50)
            
        except Exception as e:
            print(f"Error: {e}")
            import traceback
            traceback.print_exc()

if __name__ == "__main__":
    main()
  • After saving, enter the following in the terminal:
python
python test_internvl3.py

Once the script is running successfully, enter a question to receive a response.

To specify an image, enter the following (replace the image path):

python
python test_internvl3.py --image your-image-path.jpg


# Example: python test_internvl3.py --image  F:\train_and_deploy\data\images\marine\clownfish\clownfish_2.jpg

  1. Using the Gradio web interface:
  • Install Gradio
python
conda activate internvl3
pip install gradio
pip install opencv-python
  • Create a Python file named: gradio_web_demo.py

  • Open this Python file and paste in the code. Be sure to replace the model path.

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


# Load the model and tokenizer (only once, to improve speed)
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 preprocessing
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=[]):
    # Image preprocessing
    with torch.no_grad():
        pixel_values = image_processor(image).unsqueeze(0).to(dtype=torch.bfloat16, device=DEVICE)
    # Add an image tag to the question
    if not history and '<image>' not in question:
        question = '<image>\n' + question
    # Generation configuration
    generation_config = {
        "max_new_tokens": 1024,
        "do_sample": True,
        "temperature": 0.6,
        "top_p": 0.8,
    }
    # Inference
    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 interface
with gr.Blocks() as demo:
    gr.Markdown("# InternVL3-8B Web Demo")
    with gr.Row():
        with gr.Column():
            image_input = gr.Image(type="pil", label="Upload an image")
            question_input = gr.Textbox(label="Enter your question", placeholder="For example: Please describe the contents of this image")
            submit_btn = gr.Button("Submit")
        with gr.Column():
            answer_output = gr.Textbox(label="Model response")
    state = gr.State([])  # Store conversation history

    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)
  • Run the Python file in the terminal
python
python gradio_web_demo.py

Open 127.0.0.7860 in your browser