Views
No views yet


| Model Name | Vision Part | Language Part | HF Link |
|---|---|---|---|
| InternVL2_5-1B | InternViT-300M-448px-V2_5 | Qwen2.5-0.5B-Instruct | 🤗 link |
| InternVL2_5-2B | InternViT-300M-448px-V2_5 | internlm2_5-1_8b-chat | 🤗 link |
| InternVL2_5-4B | InternViT-300M-448px-V2_5 | Qwen2.5-3B-Instruct | 🤗 link |
| InternVL2_5-8B | InternViT-300M-448px-V2_5 | internlm2_5-7b-chat | 🤗 link |
| InternVL2_5-26B | InternViT-6B-448px-V2_5 | internlm2_5-20b-chat | 🤗 link |
| InternVL2_5-38B | InternViT-6B-448px-V2_5 | Qwen2.5-32B-Instruct | 🤗 link |
| InternVL2_5-78B | InternViT-6B-448px-V2_5 | Qwen2.5-72B-Instruct | 🤗 link |


n_max are allocated to a single image for maximum resolution. Visual tokens are enclosed in <img> and </img> tags.n_max are distributed across all images in a sample. Each image is labeled with auxiliary tags like Image-1 and enclosed in <img> and </img> tags.Frame-1 and enclosed in <img> and </img> tags, similar to images.


n_max controls the maximum tiles per dataset. For example, higher values (24–36) are used for multi-image or high-resolution data, lower values (6–12) for standard images, and 1 for videos.r adjusts dataset sampling frequency. Values below 1 reduce a dataset's weight, while values above 1 increase it. This ensures balanced training across tasks and prevents overfitting or underfitting.











InternVL2_5-38B using transformers.Please use transformers>=4.37.2 to ensure the model works normally.
1import torch
2from transformers import AutoTokenizer, AutoModel
3path = "OpenGVLab/InternVL2_5-38B"
4model = AutoModel.from_pretrained(
5 path,
6 torch_dtype=torch.bfloat16,
7 low_cpu_mem_usage=True,
8 use_flash_attn=True,
9 trust_remote_code=True).eval().cuda()1import torch
2from transformers import AutoTokenizer, AutoModel
3path = "OpenGVLab/InternVL2_5-38B"
4model = AutoModel.from_pretrained(
5 path,
6 torch_dtype=torch.bfloat16,
7 load_in_8bit=True,
8 low_cpu_mem_usage=True,
9 use_flash_attn=True,
10 trust_remote_code=True).eval()1import math
2import torch
3from transformers import AutoTokenizer, AutoModel
4
5def split_model(model_name):
6 device_map = {}
7 world_size = torch.cuda.device_count()
8 num_layers = {
9 'InternVL2_5-1B': 24, 'InternVL2_5-2B': 24, 'InternVL2_5-4B': 36, 'InternVL2_5-8B': 32,
10 'InternVL2_5-26B': 48, 'InternVL2_5-38B': 64, 'InternVL2_5-78B': 80}[model_name]
11 # Since the first GPU will be used for ViT, treat it as half a GPU.
12 num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
13 num_layers_per_gpu = [num_layers_per_gpu] * world_size
14 num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
15 layer_cnt = 0
16 for i, num_layer in enumerate(num_layers_per_gpu):
17 for j in range(num_layer):
18 device_map[f'language_model.model.layers.{layer_cnt}'] = i
19 layer_cnt += 1
20 device_map['vision_model'] = 0
21 device_map['mlp1'] = 0
22 device_map['language_model.model.tok_embeddings'] = 0
23 device_map['language_model.model.embed_tokens'] = 0
24 device_map['language_model.output'] = 0
25 device_map['language_model.model.norm'] = 0
26 device_map['language_model.model.rotary_emb'] = 0
27 device_map['language_model.lm_head'] = 0
28 device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
29
30 return device_map
31
32path = "OpenGVLab/InternVL2_5-38B"
33device_map = split_model('InternVL2_5-38B')
34model = AutoModel.from_pretrained(
35 path,
36 torch_dtype=torch.bfloat16,
37 low_cpu_mem_usage=True,
38 use_flash_attn=True,
39 trust_remote_code=True,
40 device_map=device_map).eval()1import math
2import numpy as np
3import torch
4import torchvision.transforms as T
5from decord import VideoReader, cpu
6from PIL import Image
7from torchvision.transforms.functional import InterpolationMode
8from transformers import AutoModel, AutoTokenizer
9
10IMAGENET_MEAN = (0.485, 0.456, 0.406)
11IMAGENET_STD = (0.229, 0.224, 0.225)
12
13def build_transform(input_size):
14 MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
15 transform = T.Compose([
16 T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
17 T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
18 T.ToTensor(),
19 T.Normalize(mean=MEAN, std=STD)
20 ])
21 return transform
22
23def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
24 best_ratio_diff = float('inf')
25 best_ratio = (1, 1)
26 area = width * height
27 for ratio in target_ratios:
28 target_aspect_ratio = ratio[0] / ratio[1]
29 ratio_diff = abs(aspect_ratio - target_aspect_ratio)
30 if ratio_diff < best_ratio_diff:
31 best_ratio_diff = ratio_diff
32 best_ratio = ratio
33 elif ratio_diff == best_ratio_diff:
34 if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
35 best_ratio = ratio
36 return best_ratio
37
38def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
39 orig_width, orig_height = image.size
40 aspect_ratio = orig_width / orig_height
41
42 # calculate the existing image aspect ratio
43 target_ratios = set(
44 (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) if
45 i * j <= max_num and i * j >= min_num)
46 target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
47
48 # find the closest aspect ratio to the target
49 target_aspect_ratio = find_closest_aspect_ratio(
50 aspect_ratio, target_ratios, orig_width, orig_height, image_size)
51
52 # calculate the target width and height
53 target_width = image_size * target_aspect_ratio[0]
54 target_height = image_size * target_aspect_ratio[1]
55 blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
56
57 # resize the image
58 resized_img = image.resize((target_width, target_height))
59 processed_images = []
60 for i in range(blocks):
61 box = (
62 (i % (target_width // image_size)) * image_size,
63 (i // (target_width // image_size)) * image_size,
64 ((i % (target_width // image_size)) + 1) * image_size,
65 ((i // (target_width // image_size)) + 1) * image_size
66 )
67 # split the image
68 split_img = resized_img.crop(box)
69 processed_images.append(split_img)
70 assert len(processed_images) == blocks
71 if use_thumbnail and len(processed_images) != 1:
72 thumbnail_img = image.resize((image_size, image_size))
73 processed_images.append(thumbnail_img)
74 return processed_images
75
76def load_image(image_file, input_size=448, max_num=12):
77 image = Image.open(image_file).convert('RGB')
78 transform = build_transform(input_size=input_size)
79 images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
80 pixel_values = [transform(image) for image in images]
81 pixel_values = torch.stack(pixel_values)
82 return pixel_values
83
84def split_model(model_name):
85 device_map = {}
86 world_size = torch.cuda.device_count()
87 num_layers = {
88 'InternVL2_5-1B': 24, 'InternVL2_5-2B': 24, 'InternVL2_5-4B': 36, 'InternVL2_5-8B': 32,
89 'InternVL2_5-26B': 48, 'InternVL2_5-38B': 64, 'InternVL2_5-78B': 80}[model_name]
90 # Since the first GPU will be used for ViT, treat it as half a GPU.
91 num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
92 num_layers_per_gpu = [num_layers_per_gpu] * world_size
93 num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
94 layer_cnt = 0
95 for i, num_layer in enumerate(num_layers_per_gpu):
96 for j in range(num_layer):
97 device_map[f'language_model.model.layers.{layer_cnt}'] = i
98 layer_cnt += 1
99 device_map['vision_model'] = 0
100 device_map['mlp1'] = 0
101 device_map['language_model.model.tok_embeddings'] = 0
102 device_map['language_model.model.embed_tokens'] = 0
103 device_map['language_model.output'] = 0
104 device_map['language_model.model.norm'] = 0
105 device_map['language_model.model.rotary_emb'] = 0
106 device_map['language_model.lm_head'] = 0
107 device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
108
109 return device_map
110
111# If you set `load_in_8bit=True`, you will need one 80GB GPUs.
112# If you set `load_in_8bit=False`, you will need at least two 80GB GPUs.
113path = 'OpenGVLab/InternVL2_5-38B'
114device_map = split_model('InternVL2_5-38B')
115model = AutoModel.from_pretrained(
116 path,
117 torch_dtype=torch.bfloat16,
118 load_in_8bit=True,
119 low_cpu_mem_usage=True,
120 use_flash_attn=True,
121 trust_remote_code=True,
122 device_map=device_map).eval()
123tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
124
125# set the max number of tiles in `max_num`
126pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
127generation_config = dict(max_new_tokens=1024, do_sample=True)
128
129# pure-text conversation (纯文本对话)
130question = 'Hello, who are you?'
131response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)
132print(f'User: {question}\nAssistant: {response}')
133
134question = 'Can you tell me a story?'
135response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)
136print(f'User: {question}\nAssistant: {response}')
137
138# single-image single-round conversation (单图单轮对话)
139question = '<image>\nPlease describe the image shortly.'
140response = model.chat(tokenizer, pixel_values, question, generation_config)
141print(f'User: {question}\nAssistant: {response}')
142
143# single-image multi-round conversation (单图多轮对话)
144question = '<image>\nPlease describe the image in detail.'
145response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
146print(f'User: {question}\nAssistant: {response}')
147
148question = 'Please write a poem according to the image.'
149response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
150print(f'User: {question}\nAssistant: {response}')
151
152# multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)
153pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
154pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
155pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
156
157question = '<image>\nDescribe the two images in detail.'
158response, history = model.chat(tokenizer, pixel_values, question, generation_config,
159 history=None, return_history=True)
160print(f'User: {question}\nAssistant: {response}')
161
162question = 'What are the similarities and differences between these two images.'
163response, history = model.chat(tokenizer, pixel_values, question, generation_config,
164 history=history, return_history=True)
165print(f'User: {question}\nAssistant: {response}')
166
167# multi-image multi-round conversation, separate images (多图多轮对话,独立图像)
168pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
169pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
170pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
171num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
172
173question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'
174response, history = model.chat(tokenizer, pixel_values, question, generation_config,
175 num_patches_list=num_patches_list,
176 history=None, return_history=True)
177print(f'User: {question}\nAssistant: {response}')
178
179question = 'What are the similarities and differences between these two images.'
180response, history = model.chat(tokenizer, pixel_values, question, generation_config,
181 num_patches_list=num_patches_list,
182 history=history, return_history=True)
183print(f'User: {question}\nAssistant: {response}')
184
185# batch inference, single image per sample (单图批处理)
186pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
187pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
188num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
189pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
190
191questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)
192responses = model.batch_chat(tokenizer, pixel_values,
193 num_patches_list=num_patches_list,
194 questions=questions,
195 generation_config=generation_config)
196for question, response in zip(questions, responses):
197 print(f'User: {question}\nAssistant: {response}')
198
199# video multi-round conversation (视频多轮对话)
200def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
201 if bound:
202 start, end = bound[0], bound[1]
203 else:
204 start, end = -100000, 100000
205 start_idx = max(first_idx, round(start * fps))
206 end_idx = min(round(end * fps), max_frame)
207 seg_size = float(end_idx - start_idx) / num_segments
208 frame_indices = np.array([
209 int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
210 for idx in range(num_segments)
211 ])
212 return frame_indices
213
214def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32):
215 vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
216 max_frame = len(vr) - 1
217 fps = float(vr.get_avg_fps())
218
219 pixel_values_list, num_patches_list = [], []
220 transform = build_transform(input_size=input_size)
221 frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
222 for frame_index in frame_indices:
223 img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB')
224 img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)
225 pixel_values = [transform(tile) for tile in img]
226 pixel_values = torch.stack(pixel_values)
227 num_patches_list.append(pixel_values.shape[0])
228 pixel_values_list.append(pixel_values)
229 pixel_values = torch.cat(pixel_values_list)
230 return pixel_values, num_patches_list
231
232video_path = './examples/red-panda.mp4'
233pixel_values, num_patches_list = load_video(video_path, num_segments=8, max_num=1)
234pixel_values = pixel_values.to(torch.bfloat16).cuda()
235video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])
236question = video_prefix + 'What is the red panda doing?'
237# Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}
238response, history = model.chat(tokenizer, pixel_values, question, generation_config,
239 num_patches_list=num_patches_list, history=None, return_history=True)
240print(f'User: {question}\nAssistant: {response}')
241
242question = 'Describe this video in detail.'
243response, history = model.chat(tokenizer, pixel_values, question, generation_config,
244 num_patches_list=num_patches_list, history=history, return_history=True)
245print(f'User: {question}\nAssistant: {response}')1from transformers import TextIteratorStreamer
2from threading import Thread
3
4# Initialize the streamer
5streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10)
6# Define the generation configuration
7generation_config = dict(max_new_tokens=1024, do_sample=False, streamer=streamer)
8# Start the model chat in a separate thread
9thread = Thread(target=model.chat, kwargs=dict(
10 tokenizer=tokenizer, pixel_values=pixel_values, question=question,
11 history=None, return_history=False, generation_config=generation_config,
12))
13thread.start()
14
15# Initialize an empty string to store the generated text
16generated_text = ''
17# Loop through the streamer to get the new text as it is generated
18for new_text in streamer:
19 if new_text == model.conv_template.sep:
20 break
21 generated_text += new_text
22 print(new_text, end='', flush=True) # Print each new chunk of generated text on the same linepip install lmdeploy>=0.6.41from lmdeploy import pipeline, TurbomindEngineConfig
2from lmdeploy.vl import load_image
3
4model = 'OpenGVLab/InternVL2_5-38B'
5image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
6pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192, tp=2))
7response = pipe(('describe this image', image))
8print(response.text)ImportError occurs while executing this case, please install the required dependency packages as prompted.1from lmdeploy import pipeline, TurbomindEngineConfig
2from lmdeploy.vl import load_image
3from lmdeploy.vl.constants import IMAGE_TOKEN
4
5model = 'OpenGVLab/InternVL2_5-38B'
6pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192, tp=2))
7
8image_urls=[
9 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',
10 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg'
11]
12
13images = [load_image(img_url) for img_url in image_urls]
14# Numbering images improves multi-image conversations
15response = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))
16print(response.text)1from lmdeploy import pipeline, TurbomindEngineConfig
2from lmdeploy.vl import load_image
3
4model = 'OpenGVLab/InternVL2_5-38B'
5pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192, tp=2))
6
7image_urls=[
8 "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",
9 "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"
10]
11prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]
12response = pipe(prompts)
13print(response)pipeline.chat interface.1from lmdeploy import pipeline, TurbomindEngineConfig, GenerationConfig
2from lmdeploy.vl import load_image
3
4model = 'OpenGVLab/InternVL2_5-38B'
5pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192, tp=2))
6
7image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')
8gen_config = GenerationConfig(top_k=40, top_p=0.8, temperature=0.8)
9sess = pipe.chat(('describe this image', image), gen_config=gen_config)
10print(sess.response.text)
11sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)
12print(sess.response.text)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:lmdeploy serve api_server OpenGVLab/InternVL2_5-38B --server-port 23333 --tp 2pip install openai1from openai import OpenAI
2
3client = OpenAI(api_key='YOUR_API_KEY', base_url='http://0.0.0.0:23333/v1')
4model_name = client.models.list().data[0].id
5response = client.chat.completions.create(
6 model=model_name,
7 messages=[{
8 'role':
9 'user',
10 'content': [{
11 'type': 'text',
12 'text': 'describe this image',
13 }, {
14 'type': 'image_url',
15 'image_url': {
16 'url':
17 'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg',
18 },
19 }],
20 }],
21 temperature=0.8,
22 top_p=0.8)
23print(response)1@article{chen2024expanding,
2 title={Expanding Performance Boundaries of Open-Source Multimodal Models with Model, Data, and Test-Time Scaling},
3 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},
4 journal={arXiv preprint arXiv:2412.05271},
5 year={2024}
6}
7@article{gao2024mini,
8 title={Mini-internvl: A flexible-transfer pocket multimodal model with 5\% parameters and 90\% performance},
9 author={Gao, Zhangwei and Chen, Zhe and Cui, Erfei and Ren, Yiming and Wang, Weiyun and Zhu, Jinguo and Tian, Hao and Ye, Shenglong and He, Junjun and Zhu, Xizhou and others},
10 journal={arXiv preprint arXiv:2410.16261},
11 year={2024}
12}
13@article{chen2024far,
14 title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},
15 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},
16 journal={arXiv preprint arXiv:2404.16821},
17 year={2024}
18}
19@inproceedings{chen2024internvl,
20 title={Internvl: Scaling up vision foundation models and aligning for generic visual-linguistic tasks},
21 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},
22 booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
23 pages={24185--24198},
24 year={2024}
25}