CoolFace
Modelpublic

OpenGVLab/InternVL3-78B-Instruct

sourceHugging Faceotherupdated 1y agoView on Hugging Face
8likes3kdownloads
README.md703 linesDownload Raw Back to root
1---2license: other3license_name: qwen4license_link: https://huggingface.co/Qwen/Qwen2.5-72B-Instruct/blob/main/LICENSE5pipeline_tag: image-text-to-text6library_name: transformers7base_model:8- OpenGVLab/InternVL3-78B-Pretrained9base_model_relation: finetune10language:11- multilingual12tags:13- internvl14- custom_code15---16 17# InternVL3-78B-Instruct18 19[\[📂 GitHub\]](https://github.com/OpenGVLab/InternVL)  [\[📜 InternVL 1.0\]](https://huggingface.co/papers/2312.14238)  [\[📜 InternVL 1.5\]](https://huggingface.co/papers/2404.16821)  [\[📜 InternVL 2.5\]](https://huggingface.co/papers/2412.05271)  [\[📜 InternVL2.5-MPO\]](https://huggingface.co/papers/2411.10442)  [\[📜 InternVL3\]](https://huggingface.co/papers/2504.10479)20 21[\[🆕 Blog\]](https://internvl.github.io/blog/)  [\[🗨️ Chat Demo\]](https://internvl.opengvlab.com/)  [\[🤗 HF Demo\]](https://huggingface.co/spaces/OpenGVLab/InternVL)  [\[🚀 Quick Start\]](#quick-start)  [\[📖 Documents\]](https://internvl.readthedocs.io/en/latest/)22 23<div align="center">24  <img width="500" alt="image" src="https://cdn-uploads.huggingface.co/production/uploads/64006c09330a45b03605bba3/zJsd2hqd3EevgXo6fNgC-.png">25</div>26 27## Introduction28 29***This is the SFT version of InternVL3-78B, which has undergone native multimodal pre-trainin and SFT but has not undergone MPO. If you're unsure which version to use, please use the [InternVL3-78B](https://huggingface.co/OpenGVLab/InternVL3-78B) version.***30 31We introduce InternVL3, an advanced multimodal large language model (MLLM) series that demonstrates superior overall performance.32Compared to InternVL 2.5, InternVL3 exhibits superior multimodal perception and reasoning capabilities, while further extending its multimodal capabilities to encompass tool usage, GUI agents, industrial image analysis, 3D vision perception, and more.33Additionally, we compare InternVL3 with  Qwen2.5 Chat models, whose corresponding pre-trained base models are employed as the initialization of the langauge component in InternVL3. Benefitting from Native Multimodal Pre-Training, the InternVL3 series achieves even better overall text performance than the Qwen2.5 series.34 35![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/overall.png)36 37## InternVL3 Family38 39In the following table, we provide an overview of the InternVL3 series.40 41|  Model Name   |                                       Vision Part                                       |                                 Language Part                                  |                         HF Link                          |42| :-----------: | :-------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------: | :------------------------------------------------------: |43| InternVL3-1B  | [InternViT-300M-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-300M-448px-V2_5) |            [Qwen2.5-0.5B](https://huggingface.co/Qwen/Qwen2.5-0.5B)            | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3-1B)  |44| InternVL3-2B  | [InternViT-300M-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-300M-448px-V2_5) |            [Qwen2.5-1.5B](https://huggingface.co/Qwen/Qwen2.5-1.5B)            | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3-2B)  |45| InternVL3-8B  | [InternViT-300M-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-300M-448px-V2_5) |              [Qwen2.5-7B](https://huggingface.co/Qwen/Qwen2.5-7B)              | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3-8B)  |46| InternVL3-9B  | [InternViT-300M-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-300M-448px-V2_5) | [internlm3-8b-instruct](https://huggingface.co/internlm/internlm3-8b-instruct) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3-9B)  |47| InternVL3-14B | [InternViT-300M-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-300M-448px-V2_5) |             [Qwen2.5-14B](https://huggingface.co/Qwen/Qwen2.5-14B)             | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3-14B) |48| InternVL3-38B |   [InternViT-6B-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V2_5)   |             [Qwen2.5-32B](https://huggingface.co/Qwen/Qwen2.5-32B)             | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3-38B) |49| InternVL3-78B |   [InternViT-6B-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V2_5)   |             [Qwen2.5-72B](https://huggingface.co/Qwen/Qwen2.5-72B)             | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3-78B) |50 51![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/overall-table.png)52 53## Model Architecture54 55As shown in the following figure, [InternVL3](https://internvl.github.io/blog/2025-04-11-InternVL-3/) retains the same model architecture as [InternVL 2.5](https://internvl.github.io/blog/2024-12-05-InternVL-2.5/) and its predecessors, InternVL 1.5 and 2.0, following the "ViT-MLP-LLM" paradigm. In this new version, we integrate a newly incrementally pre-trained InternViT with various pre-trained LLMs, including InternLM 3 and Qwen 2.5, using a randomly initialized MLP projector.56 57 58![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/BiiyXN6NOk0p-3rl3ueyL.png)59 60As in the previous version, we applied a pixel unshuffle operation, reducing the number of visual tokens to one-quarter of the original. Besides, we adopted a similar dynamic resolution strategy as InternVL 1.5, dividing images into tiles of 448×448 pixels. The key difference, starting from InternVL 2.0, is that we additionally introduced support for multi-image and video data.61 62Notably, in InternVL3, we integrate the [Variable Visual Position Encoding (V2PE)](https://arxiv.org/abs/2412.09616), which utilizes smaller, more flexible position increments for visual tokens. Benefiting from V2PE, InternVL3 exhibits better long context understanding capabilities compared to its predecessors.63 64## Training Strategy65 66### Native Multimodal Pre-Training67 68We propose a [Native Multimodal Pre-Training](https://huggingface.co/papers/2504.10479) approach that consolidates language and vision learning into a single pre-training stage.69In contrast to standard paradigms that first train a language-only model and subsequently adapt it to handle additional modalities, our method interleaves multimodal data (e.g., image-text, video-text, or image-text interleaved sequences) with large-scale textual corpora. This unified training scheme allows the model to learn both linguistic and multimodal representations simultaneously, ultimately enhancing its capability to handle vision-language tasks without the need for separate alignment or bridging modules.70Please see [our paper](https://huggingface.co/papers/2504.10479) for more details.71 72### Supervised Fine-Tuning73 74In this phase, the techniques of random JPEG compression, square loss re-weighting, and multimodal data packing proposed in [InternVL2.5](https://arxiv.org/abs/2412.05271) are also employed in the InternVL3 series.75The main advancement of the SFT phase in InternVL3 compared to InternVL2.5 lies in the use of higher-quality and more diverse training data.76Specifically, we further extend  training samples for tool use, 3D scene understanding, GUI operations, long context tasks, video understanding, scientific diagrams, creative writing, and multimodal reasoning.77 78### Mixed Preference Optimization79 80During Pre-training and SFT, the model is trained to predict the next token conditioned on previous ground-truth tokens.81However, during inference, the model predicts each token based on its own prior outputs. 82This discrepancy between ground-truth tokens and model-predicted tokens introduces a distribution shift, which can impair the model’s Chain-of-Thought (CoT) reasoning capabilities.83To mitigate this issue, we employ [MPO](https://arxiv.org/abs/2411.10442), which introduces additional supervision from both positive and negative samples to align the model response distribution with the ground-truth distribution, thereby improving reasoning performance.84Specifically, the training objective of MPO is a combination of85preference loss \\(\mathcal{L}_{\text{p}}\\),86quality loss \\(\mathcal{L}_{\text{q}}\\),87and generation loss \\(\mathcal{L}_{\text{g}}\\),88which can be formulated as follows:89 90 91$$92\mathcal{L}=w_{p}\cdot\mathcal{L}_{\text{p}} + w_{q}\cdot\mathcal{L}_{\text{q}} + w_{g}\cdot\mathcal{L}_{\text{g}},93$$94 95 96where \\(w_{*}\\) represents the weight assigned to each loss component. Please see [our paper](https://arxiv.org/abs/2411.10442) for more details about MPO.97 98 99### Test-Time Scaling100 101Test-Time Scaling has been shown to be an effective method to enhance the reasoning abilities of LLMs and MLLMs.102In this work, we use the Best-of-N evaluation strategy and employ [VisualPRM-8B](https://huggingface.co/OpenGVLab/VisualPRM-8B) as the critic model to select the best response for reasoning and mathematics evaluation.103 104## Evaluation on Multimodal Capability105 106### Multimodal Reasoning and Mathematics107 108![image/png](https://huggingface.co/datasets/OpenGVLab/VisualPRM400K-v1.1/resolve/main/visualprm-performance.png)109 110### OCR, Chart, and Document Understanding111 112![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/ocr.png)113 114### Multi-Image & Real-World Comprehension115 116![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/multi-images.png)117 118### Comprehensive Multimodal & Hallucination Evaluation119 120![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/comprehensive.png)121 122### Visual Grounding123 124![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/grounding.png)125 126### Multimodal Multilingual Understanding127 128![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/multilingual.png)129 130### Video Understanding131 132![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/video.png)133 134### GUI Grounding135 136![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/gui.png)137 138### Spatial Reasoning139 140![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/vsi.png)141 142## Evaluation on Language Capability143 144We compare InternVL3 with  Qwen2.5 Chat models, whose corresponding pre-trained base models are employed as the initialization of the langauge component in InternVL3.145Benefitting from Native Multimodal Pre-Training, the InternVL3 series achieves even better overall text performance than the Qwen2.5 series.146Please note that the evaluation scores of Qwen2.5 series  may differ from those officially reported, as we have adopted the prompt versions provided in the table across all datasets for OpenCompass evaluation.147 148![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/text.png)149 150## Ablation Study151 152### Native Multimodal Pre-Training153 154We conduct experiments on the InternVL2-8B model while keeping its architecture, initialization parameters, and training data entirely unchanged. Traditionally, InternVL2-8B employs a training pipeline that begins with an MLP warmup phase for feature alignment followed by an Instruction Tuning stage. In our experiments, we substitute the conventional MLP warmup phase with a native multimodal pre-training process. This modification isolates the contribution of native multimodal pre-training to the overall multimodal capability of the model.155 156The evaluation results in the Figure below shows that the model with native multimodal pre-training exhibits performance on most benchmarks that is comparable to the fully multi-stage-trained InternVL2-8B baseline. Furthermore, when followed by instruction tuning on higher-quality data, the model demonstrates further performance gains across evaluated multimodal tasks. These findings underscore the efficiency of native multimodal pre-training in imparting powerful multimodal capabilities to MLLMs.157 158![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/ablation-native.png)159 160### Mixed Preference Optimization161 162As shown in the table below, models fine-tuned with MPO demonstrate superior reasoning performance across seven multimodal reasoning benchmarks compared to their counterparts without MPO. Specifically, InternVL3-78B and InternVL3-38B outperform their counterparts by 4.1 and 4.5 points, respectively. Notably, the training data used for MPO is a subset of that used for SFT, indicating that the performance improvements primarily stem from the training algorithm rather than the training data.163 164![image/png](https://huggingface.co/datasets/OpenGVLab/MMPR-v1.2/resolve/main/ablation-mpo.png)165 166### Variable Visual Position Encoding167 168As reported in the table below, the introduction of V2PE leads to significant performance gains across most evaluation metrics. In addition, our ablation studies—by varying the positional increment \\( \delta \\)—reveal that even for tasks primarily involving conventional contexts, relatively small \\( \delta \\) values can achieve optimal performance. These findings provide important insights for future efforts aimed at refining position encoding strategies for visual tokens in MLLMs.169 170![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/ablation-v2pe.png)171 172## Quick Start173 174We provide an example code to run `InternVL3-78B` using `transformers`.175 176> Please use transformers>=4.37.2 to ensure the model works normally.177 178### Model Loading179 180#### 16-bit (bf16 / fp16)181 182```python183import torch184from transformers import AutoTokenizer, AutoModel185path = "OpenGVLab/InternVL3-78B"186model = AutoModel.from_pretrained(187    path,188    torch_dtype=torch.bfloat16,189    low_cpu_mem_usage=True,190    use_flash_attn=True,191    trust_remote_code=True).eval().cuda()192```193 194#### BNB 8-bit Quantization195 196```python197import torch198from transformers import AutoTokenizer, AutoModel199path = "OpenGVLab/InternVL3-78B"200model = AutoModel.from_pretrained(201    path,202    torch_dtype=torch.bfloat16,203    load_in_8bit=True,204    low_cpu_mem_usage=True,205    use_flash_attn=True,206    trust_remote_code=True).eval()207```208 209#### Multiple GPUs210 211The reason for writing the code this way is to avoid errors that occur during multi-GPU inference due to tensors not being on the same device. By ensuring that the first and last layers of the large language model (LLM) are on the same device, we prevent such errors.212 213```python214import math215import torch216from transformers import AutoTokenizer, AutoModel217 218def split_model(model_name):219    device_map = {}220    world_size = torch.cuda.device_count()221    config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)222    num_layers = config.llm_config.num_hidden_layers223    # Since the first GPU will be used for ViT, treat it as half a GPU.224    num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))225    num_layers_per_gpu = [num_layers_per_gpu] * world_size226    num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)227    layer_cnt = 0228    for i, num_layer in enumerate(num_layers_per_gpu):229        for j in range(num_layer):230            device_map[f'language_model.model.layers.{layer_cnt}'] = i231            layer_cnt += 1232    device_map['vision_model'] = 0233    device_map['mlp1'] = 0234    device_map['language_model.model.tok_embeddings'] = 0235    device_map['language_model.model.embed_tokens'] = 0236    device_map['language_model.output'] = 0237    device_map['language_model.model.norm'] = 0238    device_map['language_model.model.rotary_emb'] = 0239    device_map['language_model.lm_head'] = 0240    device_map[f'language_model.model.layers.{num_layers - 1}'] = 0241 242    return device_map243 244path = "OpenGVLab/InternVL3-78B"245device_map = split_model('InternVL3-78B')246model = AutoModel.from_pretrained(247    path,248    torch_dtype=torch.bfloat16,249    low_cpu_mem_usage=True,250    use_flash_attn=True,251    trust_remote_code=True,252    device_map=device_map).eval()253```254 255### Inference with Transformers256 257```python258import math259import numpy as np260import torch261import torchvision.transforms as T262from decord import VideoReader, cpu263from PIL import Image264from torchvision.transforms.functional import InterpolationMode265from transformers import AutoModel, AutoTokenizer266 267IMAGENET_MEAN = (0.485, 0.456, 0.406)268IMAGENET_STD = (0.229, 0.224, 0.225)269 270def build_transform(input_size):271    MEAN, STD = IMAGENET_MEAN, IMAGENET_STD272    transform = T.Compose([273        T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),274        T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),275        T.ToTensor(),276        T.Normalize(mean=MEAN, std=STD)277    ])278    return transform279 280def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):281    best_ratio_diff = float('inf')282    best_ratio = (1, 1)283    area = width * height284    for ratio in target_ratios:285        target_aspect_ratio = ratio[0] / ratio[1]286        ratio_diff = abs(aspect_ratio - target_aspect_ratio)287        if ratio_diff < best_ratio_diff:288            best_ratio_diff = ratio_diff289            best_ratio = ratio290        elif ratio_diff == best_ratio_diff:291            if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:292                best_ratio = ratio293    return best_ratio294 295def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):296    orig_width, orig_height = image.size297    aspect_ratio = orig_width / orig_height298 299    # calculate the existing image aspect ratio300    target_ratios = set(301        (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if302        i * j <= max_num and i * j >= min_num)303    target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])304 305    # find the closest aspect ratio to the target306    target_aspect_ratio = find_closest_aspect_ratio(307        aspect_ratio, target_ratios, orig_width, orig_height, image_size)308 309    # calculate the target width and height310    target_width = image_size * target_aspect_ratio[0]311    target_height = image_size * target_aspect_ratio[1]312    blocks = target_aspect_ratio[0] * target_aspect_ratio[1]313 314    # resize the image315    resized_img = image.resize((target_width, target_height))316    processed_images = []317    for i in range(blocks):318        box = (319            (i % (target_width // image_size)) * image_size,320            (i // (target_width // image_size)) * image_size,321            ((i % (target_width // image_size)) + 1) * image_size,322            ((i // (target_width // image_size)) + 1) * image_size323        )324        # split the image325        split_img = resized_img.crop(box)326        processed_images.append(split_img)327    assert len(processed_images) == blocks328    if use_thumbnail and len(processed_images) != 1:329        thumbnail_img = image.resize((image_size, image_size))330        processed_images.append(thumbnail_img)331    return processed_images332 333def load_image(image_file, input_size=448, max_num=12):334    image = Image.open(image_file).convert('RGB')335    transform = build_transform(input_size=input_size)336    images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)337    pixel_values = [transform(image) for image in images]338    pixel_values = torch.stack(pixel_values)339    return pixel_values340 341def split_model(model_name):342    device_map = {}343    world_size = torch.cuda.device_count()344    config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)345    num_layers = config.llm_config.num_hidden_layers346    # Since the first GPU will be used for ViT, treat it as half a GPU.347    num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))348    num_layers_per_gpu = [num_layers_per_gpu] * world_size349    num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)350    layer_cnt = 0351    for i, num_layer in enumerate(num_layers_per_gpu):352        for j in range(num_layer):353            device_map[f'language_model.model.layers.{layer_cnt}'] = i354            layer_cnt += 1355    device_map['vision_model'] = 0356    device_map['mlp1'] = 0357    device_map['language_model.model.tok_embeddings'] = 0358    device_map['language_model.model.embed_tokens'] = 0359    device_map['language_model.output'] = 0360    device_map['language_model.model.norm'] = 0361    device_map['language_model.model.rotary_emb'] = 0362    device_map['language_model.lm_head'] = 0363    device_map[f'language_model.model.layers.{num_layers - 1}'] = 0364 365    return device_map366 367# If you set `load_in_8bit=True`, you will need two 80GB GPUs.368# If you set `load_in_8bit=False`, you will need at least three 80GB GPUs.369path = 'OpenGVLab/InternVL3-78B'370device_map = split_model('InternVL3-78B')371model = AutoModel.from_pretrained(372    path,373    torch_dtype=torch.bfloat16,374    load_in_8bit=False,375    low_cpu_mem_usage=True,376    use_flash_attn=True,377    trust_remote_code=True,378    device_map=device_map).eval()379tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)380 381# set the max number of tiles in `max_num`382pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()383generation_config = dict(max_new_tokens=1024, do_sample=True)384 385# pure-text conversation (纯文本对话)386question = 'Hello, who are you?'387response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)388print(f'User: {question}\nAssistant: {response}')389 390question = 'Can you tell me a story?'391response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)392print(f'User: {question}\nAssistant: {response}')393 394# single-image single-round conversation (单图单轮对话)395question = '<image>\nPlease describe the image shortly.'396response = model.chat(tokenizer, pixel_values, question, generation_config)397print(f'User: {question}\nAssistant: {response}')398 399# single-image multi-round conversation (单图多轮对话)400question = '<image>\nPlease describe the image in detail.'401response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)402print(f'User: {question}\nAssistant: {response}')403 404question = 'Please write a poem according to the image.'405response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)406print(f'User: {question}\nAssistant: {response}')407 408# multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)409pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()410pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()411pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)412 413question = '<image>\nDescribe the two images in detail.'414response, history = model.chat(tokenizer, pixel_values, question, generation_config,415                               history=None, return_history=True)416print(f'User: {question}\nAssistant: {response}')417 418question = 'What are the similarities and differences between these two images.'419response, history = model.chat(tokenizer, pixel_values, question, generation_config,420                               history=history, return_history=True)421print(f'User: {question}\nAssistant: {response}')422 423# multi-image multi-round conversation, separate images (多图多轮对话,独立图像)424pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()425pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()426pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)427num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]428 429question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'430response, history = model.chat(tokenizer, pixel_values, question, generation_config,431                               num_patches_list=num_patches_list,432                               history=None, return_history=True)433print(f'User: {question}\nAssistant: {response}')434 435question = 'What are the similarities and differences between these two images.'436response, history = model.chat(tokenizer, pixel_values, question, generation_config,437                               num_patches_list=num_patches_list,438                               history=history, return_history=True)439print(f'User: {question}\nAssistant: {response}')440 441# batch inference, single image per sample (单图批处理)442pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()443pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()444num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]445pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)446 447questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)448responses = model.batch_chat(tokenizer, pixel_values,449                             num_patches_list=num_patches_list,450                             questions=questions,451                             generation_config=generation_config)452for question, response in zip(questions, responses):453    print(f'User: {question}\nAssistant: {response}')454 455# video multi-round conversation (视频多轮对话)456def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):457    if bound:458        start, end = bound[0], bound[1]459    else:460        start, end = -100000, 100000461    start_idx = max(first_idx, round(start * fps))462    end_idx = min(round(end * fps), max_frame)463    seg_size = float(end_idx - start_idx) / num_segments464    frame_indices = np.array([465        int(start_idx + (seg_size / 2) + np.round(seg_size * idx))466        for idx in range(num_segments)467    ])468    return frame_indices469 470def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32):471    vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)472    max_frame = len(vr) - 1473    fps = float(vr.get_avg_fps())474 475    pixel_values_list, num_patches_list = [], []476    transform = build_transform(input_size=input_size)477    frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)478    for frame_index in frame_indices:479        img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB')480        img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)481        pixel_values = [transform(tile) for tile in img]482        pixel_values = torch.stack(pixel_values)483        num_patches_list.append(pixel_values.shape[0])484        pixel_values_list.append(pixel_values)485    pixel_values = torch.cat(pixel_values_list)486    return pixel_values, num_patches_list487 488video_path = './examples/red-panda.mp4'489pixel_values, num_patches_list = load_video(video_path, num_segments=8, max_num=1)490pixel_values = pixel_values.to(torch.bfloat16).cuda()491video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])492question = video_prefix + 'What is the red panda doing?'493# Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}494response, history = model.chat(tokenizer, pixel_values, question, generation_config,495                               num_patches_list=num_patches_list, history=None, return_history=True)496print(f'User: {question}\nAssistant: {response}')497 498question = 'Describe this video in detail.'499response, history = model.chat(tokenizer, pixel_values, question, generation_config,500                               num_patches_list=num_patches_list, history=history, return_history=True)501print(f'User: {question}\nAssistant: {response}')502```503 504#### Streaming Output505 506Besides this method, you can also use the following code to get streamed output.507 508```python509from transformers import TextIteratorStreamer510from threading import Thread511 512# Initialize the streamer513streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10)514# Define the generation configuration515generation_config = dict(max_new_tokens=1024, do_sample=False, streamer=streamer)516# Start the model chat in a separate thread517thread = Thread(target=model.chat, kwargs=dict(518    tokenizer=tokenizer, pixel_values=pixel_values, question=question,519    history=None, return_history=False, generation_config=generation_config,520))521thread.start()522 523# Initialize an empty string to store the generated text524generated_text = ''525# Loop through the streamer to get the new text as it is generated526for new_text in streamer:527    if new_text == model.conv_template.sep:528        break529    generated_text += new_text530    print(new_text, end='', flush=True)  # Print each new chunk of generated text on the same line531```532 533## Finetune534 535Many repositories now support fine-tuning of the InternVL series models, including [InternVL](https://github.com/OpenGVLab/InternVL), [SWIFT](https://github.com/modelscope/ms-swift), [XTurner](https://github.com/InternLM/xtuner), and others. Please refer to their documentation for more details on fine-tuning.536 537## Deployment538 539### LMDeploy540 541LMDeploy is a toolkit for compressing, deploying, and serving LLMs & VLMs.542 543```sh544# if lmdeploy<0.7.3, you need to explicitly set chat_template_config=ChatTemplateConfig(model_name='internvl2_5')545pip install lmdeploy>=0.7.3546```547 548LMDeploy abstracts the complex inference process of multi-modal Vision-Language Models (VLM) into an easy-to-use pipeline, similar to the Large Language Model (LLM) inference pipeline.549 550#### A 'Hello, world' Example551 552```python553from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig554from lmdeploy.vl import load_image555 556model = 'OpenGVLab/InternVL3-78B'557image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')558pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=16384, tp=4), chat_template_config=ChatTemplateConfig(model_name='internvl2_5'))559response = pipe(('describe this image', image))560print(response.text)561```562 563If `ImportError` occurs while executing this case, please install the required dependency packages as prompted.564 565#### Multi-images Inference566 567When dealing with multiple images, you can put them all in one list. Keep in mind that multiple images will lead to a higher number of input tokens, and as a result, the size of the context window typically needs to be increased.568 569```python570from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig571from lmdeploy.vl import load_image572from lmdeploy.vl.constants import IMAGE_TOKEN573 574model = 'OpenGVLab/InternVL3-78B'575pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=16384, tp=4), chat_template_config=ChatTemplateConfig(model_name='internvl2_5'))576 577image_urls=[578    'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',579    'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg'580]581 582images = [load_image(img_url) for img_url in image_urls]583# Numbering images improves multi-image conversations584response = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))585print(response.text)586```587 588#### Batch Prompts Inference589 590Conducting inference with batch prompts is quite straightforward; just place them within a list structure:591 592```python593from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig594from lmdeploy.vl import load_image595 596model = 'OpenGVLab/InternVL3-78B'597pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=16384, tp=4), chat_template_config=ChatTemplateConfig(model_name='internvl2_5'))598 599image_urls=[600    "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",601    "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"602]603prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]604response = pipe(prompts)605print(response)606```607 608#### Multi-turn Conversation609 610There are two ways to do the multi-turn conversations with the pipeline. One is to construct messages according to the format of OpenAI and use above introduced method, the other is to use the `pipeline.chat` interface.611 612```python613from lmdeploy import pipeline, TurbomindEngineConfig, GenerationConfig, ChatTemplateConfig614from lmdeploy.vl import load_image615 616model = 'OpenGVLab/InternVL3-78B'617pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=16384, tp=4), chat_template_config=ChatTemplateConfig(model_name='internvl2_5'))618 619image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')620gen_config = GenerationConfig(top_k=40, top_p=0.8, temperature=0.8)621sess = pipe.chat(('describe this image', image), gen_config=gen_config)622print(sess.response.text)623sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)624print(sess.response.text)625```626 627#### Service628 629LMDeploy's `api_server` enables models to be easily packed into services with a single command. The provided RESTful APIs are compatible with OpenAI's interfaces. Below are an example of service startup:630 631```shell632lmdeploy serve api_server OpenGVLab/InternVL3-78B --chat-template internvl2_5 --server-port 23333 --tp 4633```634 635To use the OpenAI-style interface, you need to install OpenAI:636 637```shell638pip install openai639```640 641Then, use the code below to make the API call:642 643```python644from openai import OpenAI645 646client = OpenAI(api_key='YOUR_API_KEY', base_url='http://0.0.0.0:23333/v1')647model_name = client.models.list().data[0].id648response = client.chat.completions.create(649    model=model_name,650    messages=[{651        'role':652        'user',653        'content': [{654            'type': 'text',655            'text': 'describe this image',656        }, {657            'type': 'image_url',658            'image_url': {659                'url':660                'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg',661            },662        }],663    }],664    temperature=0.8,665    top_p=0.8)666print(response)667```668 669## License670 671This project is released under the MIT License. This project uses the pre-trained Qwen2.5 as a component, which is licensed under the Qwen License.672 673## Citation674 675If you find this project useful in your research, please consider citing:676 677```BibTeX678@article{chen2024expanding,679  title={Expanding Performance Boundaries of Open-Source Multimodal Models with Model, Data, and Test-Time Scaling},680  author={Chen, Zhe and Wang, Weiyun and Cao, Yue and Liu, Yangzhou and Gao, Zhangwei and Cui, Erfei and Zhu, Jinguo and Ye, Shenglong and Tian, Hao and Liu, Zhaoyang and others},681  journal={arXiv preprint arXiv:2412.05271},682  year={2024}683}684@article{wang2024mpo,685  title={Enhancing the Reasoning Ability of Multimodal Large Language Models via Mixed Preference Optimization},686  author={Wang, Weiyun and Chen, Zhe and Wang, Wenhai and Cao, Yue and Liu, Yangzhou and Gao, Zhangwei and Zhu, Jinguo and Zhu, Xizhou and Lu, Lewei and Qiao, Yu and Dai, Jifeng},687  journal={arXiv preprint arXiv:2411.10442},688  year={2024}689}690@article{chen2024far,691  title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},692  author={Chen, Zhe and Wang, Weiyun and Tian, Hao and Ye, Shenglong and Gao, Zhangwei and Cui, Erfei and Tong, Wenwen and Hu, Kongzhi and Luo, Jiapeng and Ma, Zheng and others},693  journal={arXiv preprint arXiv:2404.16821},694  year={2024}695}696@inproceedings{chen2024internvl,697  title={Internvl: Scaling up vision foundation models and aligning for generic visual-linguistic tasks},698  author={Chen, Zhe and Wu, Jiannan and Wang, Wenhai and Su, Weijie and Chen, Guo and Xing, Sen and Zhong, Muyan and Zhang, Qinglong and Zhu, Xizhou and Lu, Lewei and others},699  booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},700  pages={24185--24198},701  year={2024}702}703```