Views
No views yet


| Model Name | HF Link | Note |
|---|---|---|
| Mini-InternVL2-DA-Drivelm | 🤗1B / 🤗2B / 🤗4B | Adaptation for CVPR 2024 Autonomous Driving Challenge |
| Mini-InternVL2-DA-BDD | 🤗1B / 🤗2B / 🤗4B | Fine-tuning with data constructed by DriveGPT4 |
| Mini-InternVL2-DA-RS | 🤗1B / 🤗2B / 🤗4B | Adaptation for remote sensing domain |
| Mini-InternVL2-DA-Medical | 🤗1B / 🤗2B / 🤗4B | Fine-tuning using our medical data. |
Mini-InternVL2-1B using transformers.Please use transformers>=4.37.2 to ensure the model works normally.
1import numpy as np
2import torch
3import torchvision.transforms as T
4from decord import VideoReader, cpu
5from PIL import Image
6from torchvision.transforms.functional import InterpolationMode
7from transformers import AutoModel, AutoTokenizer
8
9IMAGENET_MEAN = (0.485, 0.456, 0.406)
10IMAGENET_STD = (0.229, 0.224, 0.225)
11
12def build_transform(input_size):
13 MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
14 transform = T.Compose([
15 T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
16 T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
17 T.ToTensor(),
18 T.Normalize(mean=MEAN, std=STD)
19 ])
20 return transform
21
22def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
23 best_ratio_diff = float('inf')
24 best_ratio = (1, 1)
25 area = width * height
26 for ratio in target_ratios:
27 target_aspect_ratio = ratio[0] / ratio[1]
28 ratio_diff = abs(aspect_ratio - target_aspect_ratio)
29 if ratio_diff < best_ratio_diff:
30 best_ratio_diff = ratio_diff
31 best_ratio = ratio
32 elif ratio_diff == best_ratio_diff:
33 if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
34 best_ratio = ratio
35 return best_ratio
36
37def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
38 orig_width, orig_height = image.size
39 aspect_ratio = orig_width / orig_height
40
41 # calculate the existing image aspect ratio
42 target_ratios = set(
43 (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
44 i * j <= max_num and i * j >= min_num)
45 target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
46
47 # find the closest aspect ratio to the target
48 target_aspect_ratio = find_closest_aspect_ratio(
49 aspect_ratio, target_ratios, orig_width, orig_height, image_size)
50
51 # calculate the target width and height
52 target_width = image_size * target_aspect_ratio[0]
53 target_height = image_size * target_aspect_ratio[1]
54 blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
55
56 # resize the image
57 resized_img = image.resize((target_width, target_height))
58 processed_images = []
59 for i in range(blocks):
60 box = (
61 (i % (target_width // image_size)) * image_size,
62 (i // (target_width // image_size)) * image_size,
63 ((i % (target_width // image_size)) + 1) * image_size,
64 ((i // (target_width // image_size)) + 1) * image_size
65 )
66 # split the image
67 split_img = resized_img.crop(box)
68 processed_images.append(split_img)
69 assert len(processed_images) == blocks
70 if use_thumbnail and len(processed_images) != 1:
71 thumbnail_img = image.resize((image_size, image_size))
72 processed_images.append(thumbnail_img)
73 return processed_images
74
75def load_image(image_file, input_size=448, max_num=12):
76 image = Image.open(image_file).convert('RGB')
77 transform = build_transform(input_size=input_size)
78 images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
79 pixel_values = [transform(image) for image in images]
80 pixel_values = torch.stack(pixel_values)
81 return pixel_values
82
83# If you want to load a model using multiple GPUs, please refer to the `Multiple GPUs` section.
84path = 'OpenGVLab/Mini-InternVL2-1B-DA-Medical'
85model = AutoModel.from_pretrained(
86 path,
87 torch_dtype=torch.bfloat16,
88 low_cpu_mem_usage=True,
89 use_flash_attn=True,
90 trust_remote_code=True).eval().cuda()
91tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
92
93# set the max number of tiles in `max_num`
94pixel_values = load_image('path/to/image.jpg', max_num=12).to(torch.bfloat16).cuda()
95generation_config = dict(max_new_tokens=1024, do_sample=True)
96
97# pure-text conversation (纯文本对话)
98question = 'Hello, who are you?'
99response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)
100print(f'User: {question}\nAssistant: {response}')
101
102question = 'Can you tell me a story?'
103response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)
104print(f'User: {question}\nAssistant: {response}')
105
106# single-image single-round conversation (单图单轮对话)
107question = '<image>\nPlease describe the image shortly.'
108response = model.chat(tokenizer, pixel_values, question, generation_config)
109print(f'User: {question}\nAssistant: {response}')
110
111# single-image multi-round conversation (单图多轮对话)
112question = '<image>\nPlease describe the image in detail.'
113response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
114print(f'User: {question}\nAssistant: {response}')
115
116question = 'Please write a poem according to the image.'
117response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
118print(f'User: {question}\nAssistant: {response}')
119
120# multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)
121pixel_values1 = load_image('path/to/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
122pixel_values2 = load_image('path/to/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
123pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
124
125question = '<image>\nDescribe the two images in detail.'
126response, history = model.chat(tokenizer, pixel_values, question, generation_config,
127 history=None, return_history=True)
128print(f'User: {question}\nAssistant: {response}')
129
130question = 'What are the similarities and differences between these two images.'
131response, history = model.chat(tokenizer, pixel_values, question, generation_config,
132 history=history, return_history=True)
133print(f'User: {question}\nAssistant: {response}')
134
135# multi-image multi-round conversation, separate images (多图多轮对话,独立图像)
136pixel_values1 = load_image('path/to/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
137pixel_values2 = load_image('path/to/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
138pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
139num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
140
141question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'
142response, history = model.chat(tokenizer, pixel_values, question, generation_config,
143 num_patches_list=num_patches_list,
144 history=None, return_history=True)
145print(f'User: {question}\nAssistant: {response}')
146
147question = 'What are the similarities and differences between these two images.'
148response, history = model.chat(tokenizer, pixel_values, question, generation_config,
149 num_patches_list=num_patches_list,
150 history=history, return_history=True)
151print(f'User: {question}\nAssistant: {response}')
152
153# batch inference, single image per sample (单图批处理)
154pixel_values1 = load_image('path/to/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
155pixel_values2 = load_image('path/to/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
156num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
157pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
158
159questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)
160responses = model.batch_chat(tokenizer, pixel_values,
161 num_patches_list=num_patches_list,
162 questions=questions,
163 generation_config=generation_config)
164for question, response in zip(questions, responses):
165 print(f'User: {question}\nAssistant: {response}')
1661@article{gao2024mini,
2 title={Mini-internvl: A flexible-transfer pocket multimodal model with 5\% parameters and 90\% performance},
3 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},
4 journal={arXiv preprint arXiv:2410.16261},
5 year={2024}
6}
7@article{chen2024expanding,
8 title={Expanding Performance Boundaries of Open-Source Multimodal Models with Model, Data, and Test-Time Scaling},
9 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},
10 journal={arXiv preprint arXiv:2412.05271},
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}