radna commited on
Commit
013ead2
·
0 Parent(s):

first commit

Browse files
.gitattributes ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ examples/red-panda.mp4 filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,917 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ pipeline_tag: image-text-to-text
4
+ library_name: transformers
5
+ base_model:
6
+ - OpenGVLab/InternViT-6B-448px-V1-5
7
+ - NousResearch/Nous-Hermes-2-Yi-34B
8
+ base_model_relation: merge
9
+ language:
10
+ - multilingual
11
+ tags:
12
+ - internvl
13
+ - vision
14
+ - ocr
15
+ - multi-image
16
+ - video
17
+ - custom_code
18
+ ---
19
+
20
+ # InternVL2-40B
21
+
22
+ [\[📂 GitHub\]](https://github.com/OpenGVLab/InternVL) [\[🆕 Blog\]](https://internvl.github.io/blog/) [\[📜 InternVL 1.0 Paper\]](https://arxiv.org/abs/2312.14238) [\[📜 InternVL 1.5 Report\]](https://arxiv.org/abs/2404.16821)
23
+
24
+ [\[🗨️ Chat Demo\]](https://internvl.opengvlab.com/) [\[🤗 HF Demo\]](https://huggingface.co/spaces/OpenGVLab/InternVL) [\[🚀 Quick Start\]](#quick-start) [\[📖 中文解读\]](https://zhuanlan.zhihu.com/p/706547971) [\[📖 Documents\]](https://internvl.readthedocs.io/en/latest/)
25
+
26
+ [切换至中文版](#简介)
27
+
28
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/_mLpMwsav5eMeNcZdrIQl.png)
29
+
30
+ ## Introduction
31
+
32
+ We are excited to announce the release of InternVL 2.0, the latest addition to the InternVL series of multimodal large language models. InternVL 2.0 features a variety of **instruction-tuned models**, ranging from 1 billion to 108 billion parameters. This repository contains the instruction-tuned InternVL2-40B model.
33
+
34
+ Compared to the state-of-the-art open-source multimodal large language models, InternVL 2.0 surpasses most open-source models. It demonstrates competitive performance on par with proprietary commercial models across various capabilities, including document and chart comprehension, infographics QA, scene text understanding and OCR tasks, scientific and mathematical problem solving, as well as cultural understanding and integrated multimodal capabilities.
35
+
36
+ InternVL 2.0 is trained with an 8k context window and utilizes training data consisting of long texts, multiple images, and videos, significantly improving its ability to handle these types of inputs compared to InternVL 1.5. For more details, please refer to our [blog](https://internvl.github.io/blog/2024-07-02-InternVL-2.0/) and [GitHub](https://github.com/OpenGVLab/InternVL).
37
+
38
+ | Model Name | Vision Part | Language Part | HF Link | MS Link |
39
+ | :------------------: | :---------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------: | :--------------------------------------------------------------: | :--------------------------------------------------------------------: |
40
+ | InternVL2-1B | [InternViT-300M-448px](https://huggingface.co/OpenGVLab/InternViT-300M-448px) | [Qwen2-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-1B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-1B) |
41
+ | InternVL2-2B | [InternViT-300M-448px](https://huggingface.co/OpenGVLab/InternViT-300M-448px) | [internlm2-chat-1_8b](https://huggingface.co/internlm/internlm2-chat-1_8b) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-2B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-2B) |
42
+ | InternVL2-4B | [InternViT-300M-448px](https://huggingface.co/OpenGVLab/InternViT-300M-448px) | [Phi-3-mini-128k-instruct](https://huggingface.co/microsoft/Phi-3-mini-128k-instruct) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-4B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-4B) |
43
+ | InternVL2-8B | [InternViT-300M-448px](https://huggingface.co/OpenGVLab/InternViT-300M-448px) | [internlm2_5-7b-chat](https://huggingface.co/internlm/internlm2_5-7b-chat) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-8B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-8B) |
44
+ | InternVL2-26B | [InternViT-6B-448px-V1-5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-5) | [internlm2-chat-20b](https://huggingface.co/internlm/internlm2-chat-20b) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-26B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-26B) |
45
+ | InternVL2-40B | [InternViT-6B-448px-V1-5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-5) | [Nous-Hermes-2-Yi-34B](https://huggingface.co/NousResearch/Nous-Hermes-2-Yi-34B) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-40B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-40B) |
46
+ | InternVL2-Llama3-76B | [InternViT-6B-448px-V1-5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-5) | [Hermes-2-Theta-Llama-3-70B](https://huggingface.co/NousResearch/Hermes-2-Theta-Llama-3-70B) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-Llama3-76B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-Llama3-76B) |
47
+
48
+ ## Model Details
49
+
50
+ InternVL 2.0 is a multimodal large language model series, featuring models of various sizes. For each size, we release instruction-tuned models optimized for multimodal tasks. InternVL2-40B consists of [InternViT-6B-448px-V1-5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-5), an MLP projector, and [Nous-Hermes-2-Yi-34B](https://huggingface.co/NousResearch/Nous-Hermes-2-Yi-34B).
51
+
52
+ ## Performance
53
+
54
+ ### Image Benchmarks
55
+
56
+ | Benchmark | GPT-4T-20240409 | Gemini-1.5-Pro | InternVL2-26B | InternVL2-40B |
57
+ | :--------------------------: | :-------------: | :------------: | :-----------: | :-----------: |
58
+ | Model Size | - | - | 25.5B | 40B |
59
+ | | | | | |
60
+ | DocVQA<sub>test</sub> | 87.2 | 86.5 | 92.9 | 93.9 |
61
+ | ChartQA<sub>test</sub> | 78.1 | 81.3 | 84.9 | 86.2 |
62
+ | InfoVQA<sub>test</sub> | - | 72.7 | 75.9 | 78.7 |
63
+ | TextVQA<sub>val</sub> | - | 73.5 | 82.3 | 83.0 |
64
+ | OCRBench | 678 | 754 | 825 | 837 |
65
+ | MME<sub>sum</sub> | 2070.2 | 2110.6 | 2260.7 | 2315.0 |
66
+ | RealWorldQA | 68.0 | 67.5 | 68.3 | 71.8 |
67
+ | AI2D<sub>test</sub> | 89.4 | 80.3 | 84.5 | 87.1 |
68
+ | MMMU<sub>val</sub> | 63.1 / 61.7 | 58.5 / 60.6 | 48.3 / 51.2 | 53.9 / 55.2 |
69
+ | MMBench-EN<sub>test</sub> | 81.0 | 73.9 | 83.4 | 86.8 |
70
+ | MMBench-CN<sub>test</sub> | 80.2 | 73.8 | 82.0 | 86.5 |
71
+ | CCBench<sub>dev</sub> | 57.3 | 28.4 | 73.5 | 80.6 |
72
+ | MMVet<sub>GPT-4-0613</sub> | - | - | 64.2 | 68.5 |
73
+ | MMVet<sub>GPT-4-Turbo</sub> | 67.5 | 64.0 | 62.1 | 65.5 |
74
+ | SEED-Image | - | - | 76.8 | 78.2 |
75
+ | HallBench<sub>avg</sub> | 43.9 | 45.6 | 50.7 | 56.9 |
76
+ | MathVista<sub>testmini</sub> | 58.1 | 57.7 | 59.4 | 63.7 |
77
+ | OpenCompass<sub>avg</sub> | 63.5 | 64.4 | 66.4 | 69.7 |
78
+
79
+ - For more details and evaluation reproduction, please refer to our [Evaluation Guide](https://internvl.readthedocs.io/en/latest/internvl2.0/evaluation.html).
80
+
81
+ - We simultaneously use [InternVL](https://github.com/OpenGVLab/InternVL) and [VLMEvalKit](https://github.com/open-compass/VLMEvalKit) repositories for model evaluation. Specifically, the results reported for DocVQA, ChartQA, InfoVQA, TextVQA, MME, AI2D, MMBench, CCBench, MMVet, and SEED-Image were tested using the InternVL repository. OCRBench, RealWorldQA, HallBench, and MathVista were evaluated using the VLMEvalKit.
82
+
83
+ - For MMMU, we report both the original scores (left side: evaluated using the InternVL codebase for InternVL series models, and sourced from technical reports or webpages for other models) and the VLMEvalKit scores (right side: collected from the OpenCompass leaderboard).
84
+
85
+ - Please note that evaluating the same model using different testing toolkits like [InternVL](https://github.com/OpenGVLab/InternVL) and [VLMEvalKit](https://github.com/open-compass/VLMEvalKit) can result in slight differences, which is normal. Updates to code versions and variations in environment and hardware can also cause minor discrepancies in results.
86
+
87
+ ### Video Benchmarks
88
+
89
+ | Benchmark | GPT-4V | VILA-1.5 | LLaVA-NeXT-Video | InternVL2-26B | InternVL2-40B |
90
+ | :-------------------------: | :----: | :------: | :--------------: | :-----------: | :-----------: |
91
+ | Model Size | - | 34B | 34B | 25.5B | 40B |
92
+ | | | | | | |
93
+ | MVBench | - | - | - | 67.5 | 72.5 |
94
+ | MMBench-Video<sub>8f</sub> | 1.53 | - | - | 1.27 | 1.32 |
95
+ | MMBench-Video<sub>16f</sub> | 1.68 | - | - | 1.41 | 1.45 |
96
+ | Video-MME<br>w/o subs | 59.9 | 59.0 | 52.0 | 54.8 | 61.2 |
97
+ | Video-MME<br>w subs | 63.3 | 59.4 | 54.9 | 57.1 | 62.4 |
98
+
99
+ - We evaluate our models on MVBench and Video-MME by extracting 16 frames from each video, and each frame was resized to a 448x448 image.
100
+
101
+ ### Grounding Benchmarks
102
+
103
+ | Model | avg. | RefCOCO<br>(val) | RefCOCO<br>(testA) | RefCOCO<br>(testB) | RefCOCO+<br>(val) | RefCOCO+<br>(testA) | RefCOCO+<br>(testB) | RefCOCO‑g<br>(val) | RefCOCO‑g<br>(test) |
104
+ | :----------------------------: | :--: | :--------------: | :----------------: | :----------------: | :---------------: | :-----------------: | :-----------------: | :----------------: | :-----------------: |
105
+ | UNINEXT-H<br>(Specialist SOTA) | 88.9 | 92.6 | 94.3 | 91.5 | 85.2 | 89.6 | 79.8 | 88.7 | 89.4 |
106
+ | | | | | | | | | | |
107
+ | Mini-InternVL-<br>Chat-2B-V1-5 | 75.8 | 80.7 | 86.7 | 72.9 | 72.5 | 82.3 | 60.8 | 75.6 | 74.9 |
108
+ | Mini-InternVL-<br>Chat-4B-V1-5 | 84.4 | 88.0 | 91.4 | 83.5 | 81.5 | 87.4 | 73.8 | 84.7 | 84.6 |
109
+ | InternVL‑Chat‑V1‑5 | 88.8 | 91.4 | 93.7 | 87.1 | 87.0 | 92.3 | 80.9 | 88.5 | 89.3 |
110
+ | | | | | | | | | | |
111
+ | InternVL2‑1B | 79.9 | 83.6 | 88.7 | 79.8 | 76.0 | 83.6 | 67.7 | 80.2 | 79.9 |
112
+ | InternVL2‑2B | 77.7 | 82.3 | 88.2 | 75.9 | 73.5 | 82.8 | 63.3 | 77.6 | 78.3 |
113
+ | InternVL2‑4B | 84.4 | 88.5 | 91.2 | 83.9 | 81.2 | 87.2 | 73.8 | 84.6 | 84.6 |
114
+ | InternVL2‑8B | 82.9 | 87.1 | 91.1 | 80.7 | 79.8 | 87.9 | 71.4 | 82.7 | 82.7 |
115
+ | InternVL2‑26B | 88.5 | 91.2 | 93.3 | 87.4 | 86.8 | 91.0 | 81.2 | 88.5 | 88.6 |
116
+ | InternVL2‑40B | 90.3 | 93.0 | 94.7 | 89.2 | 88.5 | 92.8 | 83.6 | 90.3 | 90.6 |
117
+ | InternVL2-<br>Llama3‑76B | 90.0 | 92.2 | 94.8 | 88.4 | 88.8 | 93.1 | 82.8 | 89.5 | 90.3 |
118
+
119
+ - We use the following prompt to evaluate InternVL's grounding ability: `Please provide the bounding box coordinates of the region this sentence describes: <ref>{}</ref>`
120
+
121
+ Limitations: Although we have made efforts to ensure the safety of the model during the training process and to encourage the model to generate text that complies with ethical and legal requirements, the model may still produce unexpected outputs due to its size and probabilistic generation paradigm. For example, the generated responses may contain biases, discrimination, or other harmful content. Please do not propagate such content. We are not responsible for any consequences resulting from the dissemination of harmful information.
122
+
123
+ ### Invitation to Evaluate InternVL
124
+
125
+ We welcome MLLM benchmark developers to assess our InternVL1.5 and InternVL2 series models. If you need to add your evaluation results here, please contact me at [[email protected]](mailto:[email protected]).
126
+
127
+ ## Quick Start
128
+
129
+ We provide an example code to run InternVL2-40B using `transformers`.
130
+
131
+ We also welcome you to experience the InternVL2 series models in our [online demo](https://internvl.opengvlab.com/).
132
+
133
+ > Please use transformers==4.37.2 to ensure the model works normally.
134
+
135
+ ### Model Loading
136
+
137
+ #### 16-bit (bf16 / fp16)
138
+
139
+ ```python
140
+ import torch
141
+ from transformers import AutoTokenizer, AutoModel
142
+ path = "OpenGVLab/InternVL2-40B"
143
+ model = AutoModel.from_pretrained(
144
+ path,
145
+ torch_dtype=torch.bfloat16,
146
+ low_cpu_mem_usage=True,
147
+ use_flash_attn=True,
148
+ trust_remote_code=True).eval().cuda()
149
+ ```
150
+
151
+ #### BNB 8-bit Quantization
152
+
153
+ ```python
154
+ import torch
155
+ from transformers import AutoTokenizer, AutoModel
156
+ path = "OpenGVLab/InternVL2-40B"
157
+ model = AutoModel.from_pretrained(
158
+ path,
159
+ torch_dtype=torch.bfloat16,
160
+ load_in_8bit=True,
161
+ low_cpu_mem_usage=True,
162
+ use_flash_attn=True,
163
+ trust_remote_code=True).eval()
164
+ ```
165
+
166
+ #### BNB 4-bit Quantization
167
+
168
+ > **⚠️ Warning:** Due to significant quantization errors with BNB 4-bit quantization on InternViT-6B, the model may produce nonsensical outputs and fail to understand images. Therefore, please avoid using BNB 4-bit quantization.
169
+
170
+ #### Multiple GPUs
171
+
172
+ The 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.
173
+
174
+ ```python
175
+ import math
176
+ import torch
177
+ from transformers import AutoTokenizer, AutoModel
178
+
179
+ def split_model(model_name):
180
+ device_map = {}
181
+ world_size = torch.cuda.device_count()
182
+ num_layers = {
183
+ 'InternVL2-1B': 24, 'InternVL2-2B': 24, 'InternVL2-4B': 32, 'InternVL2-8B': 32,
184
+ 'InternVL2-26B': 48, 'InternVL2-40B': 60, 'InternVL2-Llama3-76B': 80}[model_name]
185
+ # Since the first GPU will be used for ViT, treat it as half a GPU.
186
+ num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
187
+ num_layers_per_gpu = [num_layers_per_gpu] * world_size
188
+ num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
189
+ layer_cnt = 0
190
+ for i, num_layer in enumerate(num_layers_per_gpu):
191
+ for j in range(num_layer):
192
+ device_map[f'language_model.model.layers.{layer_cnt}'] = i
193
+ layer_cnt += 1
194
+ device_map['vision_model'] = 0
195
+ device_map['mlp1'] = 0
196
+ device_map['language_model.model.tok_embeddings'] = 0
197
+ device_map['language_model.model.embed_tokens'] = 0
198
+ device_map['language_model.output'] = 0
199
+ device_map['language_model.model.norm'] = 0
200
+ device_map['language_model.lm_head'] = 0
201
+ device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
202
+
203
+ return device_map
204
+
205
+ path = "OpenGVLab/InternVL2-40B"
206
+ device_map = split_model('InternVL2-26B')
207
+ model = AutoModel.from_pretrained(
208
+ path,
209
+ torch_dtype=torch.bfloat16,
210
+ low_cpu_mem_usage=True,
211
+ use_flash_attn=True,
212
+ trust_remote_code=True,
213
+ device_map=device_map).eval()
214
+ ```
215
+
216
+ ### Inference with Transformers
217
+
218
+ ```python
219
+ import math
220
+ import numpy as np
221
+ import torch
222
+ import torchvision.transforms as T
223
+ from decord import VideoReader, cpu
224
+ from PIL import Image
225
+ from torchvision.transforms.functional import InterpolationMode
226
+ from transformers import AutoModel, AutoTokenizer
227
+
228
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
229
+ IMAGENET_STD = (0.229, 0.224, 0.225)
230
+
231
+ def build_transform(input_size):
232
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
233
+ transform = T.Compose([
234
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
235
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
236
+ T.ToTensor(),
237
+ T.Normalize(mean=MEAN, std=STD)
238
+ ])
239
+ return transform
240
+
241
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
242
+ best_ratio_diff = float('inf')
243
+ best_ratio = (1, 1)
244
+ area = width * height
245
+ for ratio in target_ratios:
246
+ target_aspect_ratio = ratio[0] / ratio[1]
247
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
248
+ if ratio_diff < best_ratio_diff:
249
+ best_ratio_diff = ratio_diff
250
+ best_ratio = ratio
251
+ elif ratio_diff == best_ratio_diff:
252
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
253
+ best_ratio = ratio
254
+ return best_ratio
255
+
256
+ def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
257
+ orig_width, orig_height = image.size
258
+ aspect_ratio = orig_width / orig_height
259
+
260
+ # calculate the existing image aspect ratio
261
+ target_ratios = set(
262
+ (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
263
+ i * j <= max_num and i * j >= min_num)
264
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
265
+
266
+ # find the closest aspect ratio to the target
267
+ target_aspect_ratio = find_closest_aspect_ratio(
268
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
269
+
270
+ # calculate the target width and height
271
+ target_width = image_size * target_aspect_ratio[0]
272
+ target_height = image_size * target_aspect_ratio[1]
273
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
274
+
275
+ # resize the image
276
+ resized_img = image.resize((target_width, target_height))
277
+ processed_images = []
278
+ for i in range(blocks):
279
+ box = (
280
+ (i % (target_width // image_size)) * image_size,
281
+ (i // (target_width // image_size)) * image_size,
282
+ ((i % (target_width // image_size)) + 1) * image_size,
283
+ ((i // (target_width // image_size)) + 1) * image_size
284
+ )
285
+ # split the image
286
+ split_img = resized_img.crop(box)
287
+ processed_images.append(split_img)
288
+ assert len(processed_images) == blocks
289
+ if use_thumbnail and len(processed_images) != 1:
290
+ thumbnail_img = image.resize((image_size, image_size))
291
+ processed_images.append(thumbnail_img)
292
+ return processed_images
293
+
294
+ def load_image(image_file, input_size=448, max_num=12):
295
+ image = Image.open(image_file).convert('RGB')
296
+ transform = build_transform(input_size=input_size)
297
+ images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
298
+ pixel_values = [transform(image) for image in images]
299
+ pixel_values = torch.stack(pixel_values)
300
+ return pixel_values
301
+
302
+ def split_model(model_name):
303
+ device_map = {}
304
+ world_size = torch.cuda.device_count()
305
+ num_layers = {
306
+ 'InternVL2-1B': 24, 'InternVL2-2B': 24, 'InternVL2-4B': 32, 'InternVL2-8B': 32,
307
+ 'InternVL2-26B': 48, 'InternVL2-40B': 60, 'InternVL2-Llama3-76B': 80}[model_name]
308
+ # Since the first GPU will be used for ViT, treat it as half a GPU.
309
+ num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
310
+ num_layers_per_gpu = [num_layers_per_gpu] * world_size
311
+ num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
312
+ layer_cnt = 0
313
+ for i, num_layer in enumerate(num_layers_per_gpu):
314
+ for j in range(num_layer):
315
+ device_map[f'language_model.model.layers.{layer_cnt}'] = i
316
+ layer_cnt += 1
317
+ device_map['vision_model'] = 0
318
+ device_map['mlp1'] = 0
319
+ device_map['language_model.model.tok_embeddings'] = 0
320
+ device_map['language_model.model.embed_tokens'] = 0
321
+ device_map['language_model.output'] = 0
322
+ device_map['language_model.model.norm'] = 0
323
+ device_map['language_model.lm_head'] = 0
324
+ device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
325
+
326
+ return device_map
327
+
328
+ # If you set `load_in_8bit=True`, you will need one 80GB GPUs.
329
+ # If you set `load_in_8bit=False`, you will need at least two 80GB GPUs.
330
+ path = 'OpenGVLab/InternVL2-40B'
331
+ device_map = split_model('InternVL2-40B')
332
+ model = AutoModel.from_pretrained(
333
+ path,
334
+ torch_dtype=torch.bfloat16,
335
+ load_in_8bit=True,
336
+ low_cpu_mem_usage=True,
337
+ use_flash_attn=True,
338
+ trust_remote_code=True,
339
+ device_map=device_map).eval()
340
+ tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
341
+
342
+ # set the max number of tiles in `max_num`
343
+ pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
344
+ generation_config = dict(max_new_tokens=1024, do_sample=True)
345
+
346
+ # pure-text conversation (纯文本对话)
347
+ question = 'Hello, who are you?'
348
+ response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)
349
+ print(f'User: {question}\nAssistant: {response}')
350
+
351
+ question = 'Can you tell me a story?'
352
+ response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)
353
+ print(f'User: {question}\nAssistant: {response}')
354
+
355
+ # single-image single-round conversation (单图单轮对话)
356
+ question = '<image>\nPlease describe the image shortly.'
357
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
358
+ print(f'User: {question}\nAssistant: {response}')
359
+
360
+ # single-image multi-round conversation (单图多轮对话)
361
+ question = '<image>\nPlease describe the image in detail.'
362
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
363
+ print(f'User: {question}\nAssistant: {response}')
364
+
365
+ question = 'Please write a poem according to the image.'
366
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
367
+ print(f'User: {question}\nAssistant: {response}')
368
+
369
+ # multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)
370
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
371
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
372
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
373
+
374
+ question = '<image>\nDescribe the two images in detail.'
375
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
376
+ history=None, return_history=True)
377
+ print(f'User: {question}\nAssistant: {response}')
378
+
379
+ question = 'What are the similarities and differences between these two images.'
380
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
381
+ history=history, return_history=True)
382
+ print(f'User: {question}\nAssistant: {response}')
383
+
384
+ # multi-image multi-round conversation, separate images (多图多轮对话,独立图像)
385
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
386
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
387
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
388
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
389
+
390
+ question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'
391
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
392
+ num_patches_list=num_patches_list,
393
+ history=None, return_history=True)
394
+ print(f'User: {question}\nAssistant: {response}')
395
+
396
+ question = 'What are the similarities and differences between these two images.'
397
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
398
+ num_patches_list=num_patches_list,
399
+ history=history, return_history=True)
400
+ print(f'User: {question}\nAssistant: {response}')
401
+
402
+ # batch inference, single image per sample (单图批处理)
403
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
404
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
405
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
406
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
407
+
408
+ questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)
409
+ responses = model.batch_chat(tokenizer, pixel_values,
410
+ num_patches_list=num_patches_list,
411
+ questions=questions,
412
+ generation_config=generation_config)
413
+ for question, response in zip(questions, responses):
414
+ print(f'User: {question}\nAssistant: {response}')
415
+
416
+ # video multi-round conversation (视频多轮对话)
417
+ def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
418
+ if bound:
419
+ start, end = bound[0], bound[1]
420
+ else:
421
+ start, end = -100000, 100000
422
+ start_idx = max(first_idx, round(start * fps))
423
+ end_idx = min(round(end * fps), max_frame)
424
+ seg_size = float(end_idx - start_idx) / num_segments
425
+ frame_indices = np.array([
426
+ int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
427
+ for idx in range(num_segments)
428
+ ])
429
+ return frame_indices
430
+
431
+ def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32):
432
+ vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
433
+ max_frame = len(vr) - 1
434
+ fps = float(vr.get_avg_fps())
435
+
436
+ pixel_values_list, num_patches_list = [], []
437
+ transform = build_transform(input_size=input_size)
438
+ frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
439
+ for frame_index in frame_indices:
440
+ img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB')
441
+ img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)
442
+ pixel_values = [transform(tile) for tile in img]
443
+ pixel_values = torch.stack(pixel_values)
444
+ num_patches_list.append(pixel_values.shape[0])
445
+ pixel_values_list.append(pixel_values)
446
+ pixel_values = torch.cat(pixel_values_list)
447
+ return pixel_values, num_patches_list
448
+
449
+ video_path = './examples/red-panda.mp4'
450
+ pixel_values, num_patches_list = load_video(video_path, num_segments=8, max_num=1)
451
+ pixel_values = pixel_values.to(torch.bfloat16).cuda()
452
+ video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])
453
+ question = video_prefix + 'What is the red panda doing?'
454
+ # Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}
455
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
456
+ num_patches_list=num_patches_list, history=None, return_history=True)
457
+ print(f'User: {question}\nAssistant: {response}')
458
+
459
+ question = 'Describe this video in detail. Don\'t repeat.'
460
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
461
+ num_patches_list=num_patches_list, history=history, return_history=True)
462
+ print(f'User: {question}\nAssistant: {response}')
463
+ ```
464
+
465
+ #### Streaming output
466
+
467
+ Besides this method, you can also use the following code to get streamed output.
468
+
469
+ ```python
470
+ from transformers import TextIteratorStreamer
471
+ from threading import Thread
472
+
473
+ # Initialize the streamer
474
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10)
475
+ # Define the generation configuration
476
+ generation_config = dict(max_new_tokens=1024, do_sample=False, streamer=streamer)
477
+ # Start the model chat in a separate thread
478
+ thread = Thread(target=model.chat, kwargs=dict(
479
+ tokenizer=tokenizer, pixel_values=pixel_values, question=question,
480
+ history=None, return_history=False, generation_config=generation_config,
481
+ ))
482
+ thread.start()
483
+
484
+ # Initialize an empty string to store the generated text
485
+ generated_text = ''
486
+ # Loop through the streamer to get the new text as it is generated
487
+ for new_text in streamer:
488
+ if new_text == model.conv_template.sep:
489
+ break
490
+ generated_text += new_text
491
+ print(new_text, end='', flush=True) # Print each new chunk of generated text on the same line
492
+ ```
493
+
494
+ ## Finetune
495
+
496
+ Many 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.
497
+
498
+ ## Deployment
499
+
500
+ ### LMDeploy
501
+
502
+ LMDeploy is a toolkit for compressing, deploying, and serving LLM, developed by the MMRazor and MMDeploy teams.
503
+
504
+ ```sh
505
+ pip install lmdeploy==0.5.3
506
+ ```
507
+
508
+ LMDeploy 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.
509
+
510
+ #### A 'Hello, world' example
511
+
512
+ ```python
513
+ from lmdeploy import pipeline, TurbomindEngineConfig
514
+ from lmdeploy.vl import load_image
515
+
516
+ model = 'OpenGVLab/InternVL2-40B'
517
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
518
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
519
+ response = pipe(('describe this image', image))
520
+ print(response.text)
521
+ ```
522
+
523
+ If `ImportError` occurs while executing this case, please install the required dependency packages as prompted.
524
+
525
+ #### Multi-images inference
526
+
527
+ When 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.
528
+
529
+ > Warning: Due to the scarcity of multi-image conversation data, the performance on multi-image tasks may be unstable, and it may require multiple attempts to achieve satisfactory results.
530
+
531
+ ```python
532
+ from lmdeploy import pipeline, TurbomindEngineConfig
533
+ from lmdeploy.vl import load_image
534
+ from lmdeploy.vl.constants import IMAGE_TOKEN
535
+
536
+ model = 'OpenGVLab/InternVL2-40B'
537
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
538
+
539
+ image_urls=[
540
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',
541
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg'
542
+ ]
543
+
544
+ images = [load_image(img_url) for img_url in image_urls]
545
+ # Numbering images improves multi-image conversations
546
+ response = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))
547
+ print(response.text)
548
+ ```
549
+
550
+ #### Batch prompts inference
551
+
552
+ Conducting inference with batch prompts is quite straightforward; just place them within a list structure:
553
+
554
+ ```python
555
+ from lmdeploy import pipeline, TurbomindEngineConfig
556
+ from lmdeploy.vl import load_image
557
+
558
+ model = 'OpenGVLab/InternVL2-40B'
559
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
560
+
561
+ image_urls=[
562
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",
563
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"
564
+ ]
565
+ prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]
566
+ response = pipe(prompts)
567
+ print(response)
568
+ ```
569
+
570
+ #### Multi-turn conversation
571
+
572
+ There 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.
573
+
574
+ ```python
575
+ from lmdeploy import pipeline, TurbomindEngineConfig, GenerationConfig
576
+ from lmdeploy.vl import load_image
577
+
578
+ model = 'OpenGVLab/InternVL2-40B'
579
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
580
+
581
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')
582
+ gen_config = GenerationConfig(top_k=40, top_p=0.8, temperature=0.8)
583
+ sess = pipe.chat(('describe this image', image), gen_config=gen_config)
584
+ print(sess.response.text)
585
+ sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)
586
+ print(sess.response.text)
587
+ ```
588
+
589
+ #### Service
590
+
591
+ LMDeploy'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:
592
+
593
+ ```shell
594
+ lmdeploy serve api_server OpenGVLab/InternVL2-40B --backend turbomind --server-port 23333
595
+ ```
596
+
597
+ To use the OpenAI-style interface, you need to install OpenAI:
598
+
599
+ ```shell
600
+ pip install openai
601
+ ```
602
+
603
+ Then, use the code below to make the API call:
604
+
605
+ ```python
606
+ from openai import OpenAI
607
+
608
+ client = OpenAI(api_key='YOUR_API_KEY', base_url='http://0.0.0.0:23333/v1')
609
+ model_name = client.models.list().data[0].id
610
+ response = client.chat.completions.create(
611
+ model=model_name,
612
+ messages=[{
613
+ 'role':
614
+ 'user',
615
+ 'content': [{
616
+ 'type': 'text',
617
+ 'text': 'describe this image',
618
+ }, {
619
+ 'type': 'image_url',
620
+ 'image_url': {
621
+ 'url':
622
+ 'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg',
623
+ },
624
+ }],
625
+ }],
626
+ temperature=0.8,
627
+ top_p=0.8)
628
+ print(response)
629
+ ```
630
+
631
+ ## License
632
+
633
+ This project is released under the MIT license, while InternLM2 is licensed under the Apache-2.0 license.
634
+
635
+ ## Citation
636
+
637
+ If you find this project useful in your research, please consider citing:
638
+
639
+ ```BibTeX
640
+ @article{chen2023internvl,
641
+ title={InternVL: Scaling up Vision Foundation Models and Aligning for Generic Visual-Linguistic Tasks},
642
+ 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 Li, Bin and Luo, Ping and Lu, Tong and Qiao, Yu and Dai, Jifeng},
643
+ journal={arXiv preprint arXiv:2312.14238},
644
+ year={2023}
645
+ }
646
+ @article{chen2024far,
647
+ title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},
648
+ 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},
649
+ journal={arXiv preprint arXiv:2404.16821},
650
+ year={2024}
651
+ }
652
+ ```
653
+
654
+ ## 简介
655
+
656
+ 我们很高兴宣布 InternVL 2.0 的发布,这是 InternVL 系列多模态大语言模型的最新版本。InternVL 2.0 提供了多种**指令微调**的模型,参数从 10 亿到 1080 亿不等。此仓库包含经过指令微调的 InternVL2-40B 模型。
657
+
658
+ 与最先进的开源多模态大语言模型相比,InternVL 2.0 超越了大多数开源模型。它在各种能力上表现出与闭源商业模型相媲美的竞争力,包括文档和图表理解、信息图表问答、场景文本理解和 OCR 任务、科学和数学问题解决,以及文化理解和综合多模态能力。
659
+
660
+ InternVL 2.0 使用 8k 上下文窗口进行训练,训练数据包含长文本、多图和视频数据,与 InternVL 1.5 相比,其处理这些类型输入的能力显著提高。更多详细信息,请参阅我们的博客和 GitHub。
661
+
662
+ | 模型名称 | 视觉部分 | 语言部分 | HF 链接 | MS 链接 |
663
+ | :------------------: | :---------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------: | :--------------------------------------------------------------: | :--------------------------------------------------------------------: |
664
+ | InternVL2-1B | [InternViT-300M-448px](https://huggingface.co/OpenGVLab/InternViT-300M-448px) | [Qwen2-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-1B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-1B) |
665
+ | InternVL2-2B | [InternViT-300M-448px](https://huggingface.co/OpenGVLab/InternViT-300M-448px) | [internlm2-chat-1_8b](https://huggingface.co/internlm/internlm2-chat-1_8b) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-2B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-2B) |
666
+ | InternVL2-4B | [InternViT-300M-448px](https://huggingface.co/OpenGVLab/InternViT-300M-448px) | [Phi-3-mini-128k-instruct](https://huggingface.co/microsoft/Phi-3-mini-128k-instruct) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-4B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-4B) |
667
+ | InternVL2-8B | [InternViT-300M-448px](https://huggingface.co/OpenGVLab/InternViT-300M-448px) | [internlm2_5-7b-chat](https://huggingface.co/internlm/internlm2_5-7b-chat) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-8B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-8B) |
668
+ | InternVL2-26B | [InternViT-6B-448px-V1-5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-5) | [internlm2-chat-20b](https://huggingface.co/internlm/internlm2-chat-20b) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-26B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-26B) |
669
+ | InternVL2-40B | [InternViT-6B-448px-V1-5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-5) | [Nous-Hermes-2-Yi-34B](https://huggingface.co/NousResearch/Nous-Hermes-2-Yi-34B) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-40B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-40B) |
670
+ | InternVL2-Llama3-76B | [InternViT-6B-448px-V1-5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-5) | [Hermes-2-Theta-Llama-3-70B](https://huggingface.co/NousResearch/Hermes-2-Theta-Llama-3-70B) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-Llama3-76B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-Llama3-76B) |
671
+
672
+ ## 模型细节
673
+
674
+ InternVL 2.0 是一个多模态大语言模型��列,包含各种规模的模型。对于每个规模的模型,我们都会发布针对多模态任务优化的指令微调模型。InternVL2-40B 包含 [InternViT-6B-448px-V1-5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-5)、一个 MLP 投影器和 [Nous-Hermes-2-Yi-34B](https://huggingface.co/NousResearch/Nous-Hermes-2-Yi-34B)。
675
+
676
+ ## 性能测试
677
+
678
+ ### 图像相关评测
679
+
680
+ | 评测数据集 | GPT-4T-20240409 | Gemini-1.5-Pro | InternVL2-26B | InternVL2-40B |
681
+ | :--------------------------: | :-------------: | :------------: | :-----------: | :-----------: |
682
+ | 模型大小 | - | - | 25.5B | 40B |
683
+ | | | | | |
684
+ | DocVQA<sub>test</sub> | 87.2 | 86.5 | 92.9 | 93.9 |
685
+ | ChartQA<sub>test</sub> | 78.1 | 81.3 | 84.9 | 86.2 |
686
+ | InfoVQA<sub>test</sub> | - | 72.7 | 75.9 | 78.7 |
687
+ | TextVQA<sub>val</sub> | - | 73.5 | 82.3 | 83.0 |
688
+ | OCRBench | 678 | 754 | 825 | 837 |
689
+ | MME<sub>sum</sub> | 2070.2 | 2110.6 | 2260.7 | 2315.0 |
690
+ | RealWorldQA | 68.0 | 67.5 | 68.3 | 71.8 |
691
+ | AI2D<sub>test</sub> | 89.4 | 80.3 | 84.5 | 87.1 |
692
+ | MMMU<sub>val</sub> | 63.1 / 61.7 | 58.5 / 60.6 | 48.3 / 51.2 | 53.9 / 55.2 |
693
+ | MMBench-EN<sub>test</sub> | 81.0 | 73.9 | 83.4 | 86.8 |
694
+ | MMBench-CN<sub>test</sub> | 80.2 | 73.8 | 82.0 | 86.5 |
695
+ | CCBench<sub>dev</sub> | 57.3 | 28.4 | 73.5 | 80.6 |
696
+ | MMVet<sub>GPT-4-0613</sub> | - | - | 64.2 | 68.5 |
697
+ | MMVet<sub>GPT-4-Turbo</sub> | 67.5 | 64.0 | 62.1 | 65.5 |
698
+ | SEED-Image | - | - | 76.8 | 78.2 |
699
+ | HallBench<sub>avg</sub> | 43.9 | 45.6 | 50.7 | 56.9 |
700
+ | MathVista<sub>testmini</sub> | 58.1 | 57.7 | 59.4 | 63.7 |
701
+ | OpenCompass<sub>avg</sub> | 63.5 | 64.4 | 66.4 | 69.7 |
702
+
703
+ - 关于更多的细节以及评测复现,请看我们的[评测指南](https://internvl.readthedocs.io/en/latest/internvl2.0/evaluation.html)。
704
+
705
+ - 我们同时使用 InternVL 和 VLMEvalKit 仓库进行模型评估。具体来说,DocVQA、ChartQA、InfoVQA、TextVQA、MME、AI2D、MMBench、CCBench、MMVet 和 SEED-Image 的结果是使用 InternVL 仓库测试的。OCRBench、RealWorldQA、HallBench 和 MathVista 是使用 VLMEvalKit 进行评估的。
706
+
707
+ - 对于MMMU,我们报告了原始分数(左侧:InternVL系列模型使用InternVL代码库评测,其他模型的分数来自其技术报告或网页)和VLMEvalKit分数(右侧:从OpenCompass排行榜收集)。
708
+
709
+ - 请注意,使用不同的测试工具包(如 InternVL 和 VLMEvalKit)评估同一模型可能会导致细微差异,这是正常的。代码版本的更新、环境和硬件的变化也可能导致结果的微小差异。
710
+
711
+ ### 视频相关评测
712
+
713
+ | 评测数据集 | GPT-4V | VILA-1.5 | LLaVA-NeXT-Video | InternVL2-26B | InternVL2-40B |
714
+ | :-------------------------: | :----: | :------: | :--------------: | :-----------: | :-----------: |
715
+ | 模型大小 | - | 34B | 34B | 25.5B | 40B |
716
+ | | | | | | |
717
+ | MVBench | - | - | - | 67.5 | 72.5 |
718
+ | MMBench-Video<sub>8f</sub> | 1.53 | - | - | 1.27 | 1.32 |
719
+ | MMBench-Video<sub>16f</sub> | 1.68 | - | - | 1.41 | 1.45 |
720
+ | Video-MME<br>w/o subs | 59.9 | 59.0 | 52.0 | 54.8 | 61.2 |
721
+ | Video-MME<br>w subs | 63.3 | 59.4 | 54.9 | 57.1 | 62.4 |
722
+
723
+ - 我们通过从每个视频中提取 16 帧来评估我们的模型在 MVBench 和 Video-MME 上的性能,每个视频帧被调整为 448x448 的图像。
724
+
725
+ ### 定位相关评测
726
+
727
+ | 模型 | avg. | RefCOCO<br>(val) | RefCOCO<br>(testA) | RefCOCO<br>(testB) | RefCOCO+<br>(val) | RefCOCO+<br>(testA) | RefCOCO+<br>(testB) | RefCOCO‑g<br>(val) | RefCOCO‑g<br>(test) |
728
+ | :----------------------------: | :--: | :--------------: | :----------------: | :----------------: | :---------------: | :-----------------: | :-----------------: | :----------------: | :-----------------: |
729
+ | UNINEXT-H<br>(Specialist SOTA) | 88.9 | 92.6 | 94.3 | 91.5 | 85.2 | 89.6 | 79.8 | 88.7 | 89.4 |
730
+ | | | | | | | | | | |
731
+ | Mini-InternVL-<br>Chat-2B-V1-5 | 75.8 | 80.7 | 86.7 | 72.9 | 72.5 | 82.3 | 60.8 | 75.6 | 74.9 |
732
+ | Mini-InternVL-<br>Chat-4B-V1-5 | 84.4 | 88.0 | 91.4 | 83.5 | 81.5 | 87.4 | 73.8 | 84.7 | 84.6 |
733
+ | InternVL‑Chat‑V1‑5 | 88.8 | 91.4 | 93.7 | 87.1 | 87.0 | 92.3 | 80.9 | 88.5 | 89.3 |
734
+ | | | | | | | | | | |
735
+ | InternVL2‑1B | 79.9 | 83.6 | 88.7 | 79.8 | 76.0 | 83.6 | 67.7 | 80.2 | 79.9 |
736
+ | InternVL2‑2B | 77.7 | 82.3 | 88.2 | 75.9 | 73.5 | 82.8 | 63.3 | 77.6 | 78.3 |
737
+ | InternVL2‑4B | 84.4 | 88.5 | 91.2 | 83.9 | 81.2 | 87.2 | 73.8 | 84.6 | 84.6 |
738
+ | InternVL2‑8B | 82.9 | 87.1 | 91.1 | 80.7 | 79.8 | 87.9 | 71.4 | 82.7 | 82.7 |
739
+ | InternVL2‑26B | 88.5 | 91.2 | 93.3 | 87.4 | 86.8 | 91.0 | 81.2 | 88.5 | 88.6 |
740
+ | InternVL2‑40B | 90.3 | 93.0 | 94.7 | 89.2 | 88.5 | 92.8 | 83.6 | 90.3 | 90.6 |
741
+ | InternVL2-<br>Llama3‑76B | 90.0 | 92.2 | 94.8 | 88.4 | 88.8 | 93.1 | 82.8 | 89.5 | 90.3 |
742
+
743
+ - 我们使用以下 Prompt 来评测 InternVL 的 Grounding 能力: `Please provide the bounding box coordinates of the region this sentence describes: <ref>{}</ref>`
744
+
745
+ 限制:尽管在训练过程中我们非常注重模型的安全性,尽力促使模型输出符合伦理和法律要求的文本,但受限于模型大小以及概率生成范式,模型可能会产生各种不符合预期的输出,例如回复内容包含偏见、歧视等有害内容,请勿传播这些内容。由于传播不良信息导致的任何后果,本项目不承担责任。
746
+
747
+ ### 邀请评测 InternVL
748
+
749
+ 我们欢迎各位 MLLM benchmark 的开发者对我们的 InternVL1.5 以及 InternVL2 系列模型进行评测。如果需要在此处添加评测结果,请与我联系([[email protected]](mailto:[email protected]))。
750
+
751
+ ## 快速启动
752
+
753
+ 我们提供了一个示例代码,用于使用 `transformers` 运行 InternVL2-40B。
754
+
755
+ 我们也欢迎你在我们的[在线demo](https://internvl.opengvlab.com/)中体验InternVL2的系列模型。
756
+
757
+ > 请使用 transformers==4.37.2 以确保模型正常运行。
758
+
759
+ 示例代码请[点击这里](#quick-start)。
760
+
761
+ ## 微调
762
+
763
+ 许多仓库现在都支持 InternVL 系列模型的微调,包括 [InternVL](https://github.com/OpenGVLab/InternVL)、[SWIFT](https://github.com/modelscope/ms-swift)、[XTurner](https://github.com/InternLM/xtuner) 等。请参阅它们的文档以获取更多微调细节。
764
+
765
+ ## 部署
766
+
767
+ ### LMDeploy
768
+
769
+ LMDeploy 是由 MMRazor 和 MMDeploy 团队开发的用于压缩、部署和服务大语言模型(LLM)的工具包。
770
+
771
+ ```sh
772
+ pip install lmdeploy==0.5.3
773
+ ```
774
+
775
+ LMDeploy 将多模态视觉-语言模型(VLM)的复杂推理过程抽象为一个易于使用的管道,类似于大语言模型(LLM)的推理管道。
776
+
777
+ #### 一个“你好,世界”示例
778
+
779
+ ```python
780
+ from lmdeploy import pipeline, TurbomindEngineConfig
781
+ from lmdeploy.vl import load_image
782
+
783
+ model = 'OpenGVLab/InternVL2-40B'
784
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
785
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
786
+ response = pipe(('describe this image', image))
787
+ print(response.text)
788
+ ```
789
+
790
+ 如果在执行此示例时出现 `ImportError`,请���照提示安装所需的依赖包。
791
+
792
+ #### 多图像推理
793
+
794
+ 在处理多张图像时,可以将它们全部放入一个列表中。请注意,多张图像会导致输入 token 数量增加,因此通常需要增加上下文窗口的大小。
795
+
796
+ ```python
797
+ from lmdeploy import pipeline, TurbomindEngineConfig
798
+ from lmdeploy.vl import load_image
799
+ from lmdeploy.vl.constants import IMAGE_TOKEN
800
+
801
+ model = 'OpenGVLab/InternVL2-40B'
802
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
803
+
804
+ image_urls=[
805
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',
806
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg'
807
+ ]
808
+
809
+ images = [load_image(img_url) for img_url in image_urls]
810
+ # Numbering images improves multi-image conversations
811
+ response = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))
812
+ print(response.text)
813
+ ```
814
+
815
+ #### 批量Prompt推理
816
+
817
+ 使用批量Prompt进行推理非常简单;只需将它们放在一个列表结构中:
818
+
819
+ ```python
820
+ from lmdeploy import pipeline, TurbomindEngineConfig
821
+ from lmdeploy.vl import load_image
822
+
823
+ model = 'OpenGVLab/InternVL2-40B'
824
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
825
+
826
+ image_urls=[
827
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",
828
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"
829
+ ]
830
+ prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]
831
+ response = pipe(prompts)
832
+ print(response)
833
+ ```
834
+
835
+ #### 多轮对话
836
+
837
+ 使用管道进行多轮对话有两种方法。一种是根据 OpenAI 的格式构建消息并使用上述方法,另一种是使用 `pipeline.chat` 接口。
838
+
839
+ ```python
840
+ from lmdeploy import pipeline, TurbomindEngineConfig, GenerationConfig
841
+ from lmdeploy.vl import load_image
842
+
843
+ model = 'OpenGVLab/InternVL2-40B'
844
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
845
+
846
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')
847
+ gen_config = GenerationConfig(top_k=40, top_p=0.8, temperature=0.8)
848
+ sess = pipe.chat(('describe this image', image), gen_config=gen_config)
849
+ print(sess.response.text)
850
+ sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)
851
+ print(sess.response.text)
852
+ ```
853
+
854
+ #### API部署
855
+
856
+ LMDeploy 的 `api_server` 使模型能够通过一个命令轻松打包成服务。提供的 RESTful API 与 OpenAI 的接口兼容。以下是服务启动的示例:
857
+
858
+ ```shell
859
+ lmdeploy serve api_server OpenGVLab/InternVL2-40B --backend turbomind --server-port 23333
860
+ ```
861
+
862
+ 为了使用OpenAI风格的API接口,您需要安装OpenAI:
863
+
864
+ ```shell
865
+ pip install openai
866
+ ```
867
+
868
+ 然后,使用下面的代码进行API调用:
869
+
870
+ ```python
871
+ from openai import OpenAI
872
+
873
+ client = OpenAI(api_key='YOUR_API_KEY', base_url='http://0.0.0.0:23333/v1')
874
+ model_name = client.models.list().data[0].id
875
+ response = client.chat.completions.create(
876
+ model=model_name,
877
+ messages=[{
878
+ 'role':
879
+ 'user',
880
+ 'content': [{
881
+ 'type': 'text',
882
+ 'text': 'describe this image',
883
+ }, {
884
+ 'type': 'image_url',
885
+ 'image_url': {
886
+ 'url':
887
+ 'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg',
888
+ },
889
+ }],
890
+ }],
891
+ temperature=0.8,
892
+ top_p=0.8)
893
+ print(response)
894
+ ```
895
+
896
+ ## 开源许可证
897
+
898
+ 该项目采用 MIT 许可证发布,而 InternLM2 则采用 Apache-2.0 许可证。
899
+
900
+ ## 引用
901
+
902
+ 如果您发现此项目对您的研究有用,可以考虑引用我们的论文:
903
+
904
+ ```BibTeX
905
+ @article{chen2023internvl,
906
+ title={InternVL: Scaling up Vision Foundation Models and Aligning for Generic Visual-Linguistic Tasks},
907
+ 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 Li, Bin and Luo, Ping and Lu, Tong and Qiao, Yu and Dai, Jifeng},
908
+ journal={arXiv preprint arXiv:2312.14238},
909
+ year={2023}
910
+ }
911
+ @article{chen2024far,
912
+ title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},
913
+ 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},
914
+ journal={arXiv preprint arXiv:2404.16821},
915
+ year={2024}
916
+ }
917
+ ```
added_tokens.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</box>": 64006,
3
+ "</quad>": 64002,
4
+ "</ref>": 64004,
5
+ "<IMG_CONTEXT>": 64000,
6
+ "<box>": 64005,
7
+ "<quad>": 64001,
8
+ "<ref>": 64003
9
+ }
config.json ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_commit_hash": null,
3
+ "architectures": [
4
+ "InternVLChatModel"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_internvl_chat.InternVLChatConfig",
8
+ "AutoModel": "modeling_internvl_chat.InternVLChatModel",
9
+ "AutoModelForCausalLM": "modeling_internvl_chat.InternVLChatModel"
10
+ },
11
+ "downsample_ratio": 0.5,
12
+ "dynamic_image_size": true,
13
+ "force_image_size": 448,
14
+ "llm_config": {
15
+ "_name_or_path": "NousResearch/Nous-Hermes-2-Yi-34B",
16
+ "add_cross_attention": false,
17
+ "architectures": [
18
+ "LlamaForCausalLM"
19
+ ],
20
+ "attention_bias": false,
21
+ "attention_dropout": 0.0,
22
+ "bad_words_ids": null,
23
+ "begin_suppress_tokens": null,
24
+ "bos_token_id": 1,
25
+ "chunk_size_feed_forward": 0,
26
+ "cross_attention_hidden_size": null,
27
+ "decoder_start_token_id": null,
28
+ "diversity_penalty": 0.0,
29
+ "do_sample": false,
30
+ "early_stopping": false,
31
+ "encoder_no_repeat_ngram_size": 0,
32
+ "eos_token_id": 7,
33
+ "exponential_decay_length_penalty": null,
34
+ "finetuning_task": null,
35
+ "forced_bos_token_id": null,
36
+ "forced_eos_token_id": null,
37
+ "hidden_act": "silu",
38
+ "hidden_size": 7168,
39
+ "id2label": {
40
+ "0": "LABEL_0",
41
+ "1": "LABEL_1"
42
+ },
43
+ "initializer_range": 0.02,
44
+ "intermediate_size": 20480,
45
+ "is_decoder": false,
46
+ "is_encoder_decoder": false,
47
+ "label2id": {
48
+ "LABEL_0": 0,
49
+ "LABEL_1": 1
50
+ },
51
+ "length_penalty": 1.0,
52
+ "max_length": 20,
53
+ "max_position_embeddings": 8192,
54
+ "min_length": 0,
55
+ "model_type": "llama",
56
+ "no_repeat_ngram_size": 0,
57
+ "num_attention_heads": 56,
58
+ "num_beam_groups": 1,
59
+ "num_beams": 1,
60
+ "num_hidden_layers": 60,
61
+ "num_key_value_heads": 8,
62
+ "num_return_sequences": 1,
63
+ "output_attentions": false,
64
+ "output_hidden_states": false,
65
+ "output_scores": false,
66
+ "pad_token_id": 0,
67
+ "prefix": null,
68
+ "pretraining_tp": 1,
69
+ "problem_type": null,
70
+ "pruned_heads": {},
71
+ "remove_invalid_values": false,
72
+ "repetition_penalty": 1.0,
73
+ "return_dict": true,
74
+ "return_dict_in_generate": false,
75
+ "rms_norm_eps": 1e-05,
76
+ "rope_scaling": {
77
+ "factor": 3.0,
78
+ "type": "dynamic"
79
+ },
80
+ "rope_theta": 5000000.0,
81
+ "sep_token_id": null,
82
+ "suppress_tokens": null,
83
+ "task_specific_params": null,
84
+ "temperature": 1.0,
85
+ "tf_legacy_loss": false,
86
+ "tie_encoder_decoder": false,
87
+ "tie_word_embeddings": false,
88
+ "tokenizer_class": null,
89
+ "top_k": 50,
90
+ "top_p": 1.0,
91
+ "torch_dtype": "bfloat16",
92
+ "torchscript": false,
93
+ "transformers_version": "4.37.2",
94
+ "typical_p": 1.0,
95
+ "use_bfloat16": true,
96
+ "use_cache": true,
97
+ "vocab_size": 64007
98
+ },
99
+ "max_dynamic_patch": 12,
100
+ "min_dynamic_patch": 1,
101
+ "model_type": "internvl_chat",
102
+ "ps_version": "v2",
103
+ "select_layer": -1,
104
+ "template": "Hermes-2",
105
+ "torch_dtype": "bfloat16",
106
+ "use_backbone_lora": 0,
107
+ "use_llm_lora": 0,
108
+ "use_thumbnail": true,
109
+ "vision_config": {
110
+ "architectures": [
111
+ "InternVisionModel"
112
+ ],
113
+ "attention_dropout": 0.0,
114
+ "drop_path_rate": 0.0,
115
+ "dropout": 0.0,
116
+ "hidden_act": "gelu",
117
+ "hidden_size": 3200,
118
+ "image_size": 448,
119
+ "initializer_factor": 0.1,
120
+ "initializer_range": 1e-10,
121
+ "intermediate_size": 12800,
122
+ "layer_norm_eps": 1e-06,
123
+ "model_type": "intern_vit_6b",
124
+ "norm_type": "rms_norm",
125
+ "num_attention_heads": 25,
126
+ "num_channels": 3,
127
+ "num_hidden_layers": 45,
128
+ "output_attentions": false,
129
+ "output_hidden_states": false,
130
+ "patch_size": 14,
131
+ "qk_normalization": true,
132
+ "qkv_bias": false,
133
+ "return_dict": true,
134
+ "torch_dtype": "bfloat16",
135
+ "transformers_version": "4.37.2",
136
+ "use_bfloat16": true,
137
+ "use_flash_attn": true
138
+ }
139
+ }
configuration_intern_vit.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+ import os
7
+ from typing import Union
8
+
9
+ from transformers.configuration_utils import PretrainedConfig
10
+ from transformers.utils import logging
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+
15
+ class InternVisionConfig(PretrainedConfig):
16
+ r"""
17
+ This is the configuration class to store the configuration of a [`InternVisionModel`]. It is used to
18
+ instantiate a vision encoder according to the specified arguments, defining the model architecture.
19
+
20
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
21
+ documentation from [`PretrainedConfig`] for more information.
22
+
23
+ Args:
24
+ num_channels (`int`, *optional*, defaults to 3):
25
+ Number of color channels in the input images (e.g., 3 for RGB).
26
+ patch_size (`int`, *optional*, defaults to 14):
27
+ The size (resolution) of each patch.
28
+ image_size (`int`, *optional*, defaults to 224):
29
+ The size (resolution) of each image.
30
+ qkv_bias (`bool`, *optional*, defaults to `False`):
31
+ Whether to add a bias to the queries and values in the self-attention layers.
32
+ hidden_size (`int`, *optional*, defaults to 3200):
33
+ Dimensionality of the encoder layers and the pooler layer.
34
+ num_attention_heads (`int`, *optional*, defaults to 25):
35
+ Number of attention heads for each attention layer in the Transformer encoder.
36
+ intermediate_size (`int`, *optional*, defaults to 12800):
37
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
38
+ qk_normalization (`bool`, *optional*, defaults to `True`):
39
+ Whether to normalize the queries and keys in the self-attention layers.
40
+ num_hidden_layers (`int`, *optional*, defaults to 48):
41
+ Number of hidden layers in the Transformer encoder.
42
+ use_flash_attn (`bool`, *optional*, defaults to `True`):
43
+ Whether to use flash attention mechanism.
44
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
45
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
46
+ `"relu"`, `"selu"` and `"gelu_new"` ``"gelu"` are supported.
47
+ layer_norm_eps (`float`, *optional*, defaults to 1e-6):
48
+ The epsilon used by the layer normalization layers.
49
+ dropout (`float`, *optional*, defaults to 0.0):
50
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
51
+ drop_path_rate (`float`, *optional*, defaults to 0.0):
52
+ Dropout rate for stochastic depth.
53
+ attention_dropout (`float`, *optional*, defaults to 0.0):
54
+ The dropout ratio for the attention probabilities.
55
+ initializer_range (`float`, *optional*, defaults to 0.02):
56
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
57
+ initializer_factor (`float`, *optional*, defaults to 0.1):
58
+ A factor for layer scale.
59
+ """
60
+
61
+ model_type = 'intern_vit_6b'
62
+
63
+ def __init__(
64
+ self,
65
+ num_channels=3,
66
+ patch_size=14,
67
+ image_size=224,
68
+ qkv_bias=False,
69
+ hidden_size=3200,
70
+ num_attention_heads=25,
71
+ intermediate_size=12800,
72
+ qk_normalization=True,
73
+ num_hidden_layers=48,
74
+ use_flash_attn=True,
75
+ hidden_act='gelu',
76
+ norm_type='rms_norm',
77
+ layer_norm_eps=1e-6,
78
+ dropout=0.0,
79
+ drop_path_rate=0.0,
80
+ attention_dropout=0.0,
81
+ initializer_range=0.02,
82
+ initializer_factor=0.1,
83
+ **kwargs,
84
+ ):
85
+ super().__init__(**kwargs)
86
+
87
+ self.hidden_size = hidden_size
88
+ self.intermediate_size = intermediate_size
89
+ self.dropout = dropout
90
+ self.drop_path_rate = drop_path_rate
91
+ self.num_hidden_layers = num_hidden_layers
92
+ self.num_attention_heads = num_attention_heads
93
+ self.num_channels = num_channels
94
+ self.patch_size = patch_size
95
+ self.image_size = image_size
96
+ self.initializer_range = initializer_range
97
+ self.initializer_factor = initializer_factor
98
+ self.attention_dropout = attention_dropout
99
+ self.layer_norm_eps = layer_norm_eps
100
+ self.hidden_act = hidden_act
101
+ self.norm_type = norm_type
102
+ self.qkv_bias = qkv_bias
103
+ self.qk_normalization = qk_normalization
104
+ self.use_flash_attn = use_flash_attn
105
+
106
+ @classmethod
107
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> 'PretrainedConfig':
108
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
109
+
110
+ if 'vision_config' in config_dict:
111
+ config_dict = config_dict['vision_config']
112
+
113
+ if 'model_type' in config_dict and hasattr(cls, 'model_type') and config_dict['model_type'] != cls.model_type:
114
+ logger.warning(
115
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
116
+ f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'
117
+ )
118
+
119
+ return cls.from_dict(config_dict, **kwargs)
configuration_internvl_chat.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+
7
+ import copy
8
+
9
+ from transformers import AutoConfig, LlamaConfig
10
+ from transformers.configuration_utils import PretrainedConfig
11
+ from transformers.utils import logging
12
+
13
+ from .configuration_intern_vit import InternVisionConfig
14
+
15
+ logger = logging.get_logger(__name__)
16
+
17
+
18
+ class InternVLChatConfig(PretrainedConfig):
19
+ model_type = 'internvl_chat'
20
+ is_composition = True
21
+
22
+ def __init__(
23
+ self,
24
+ vision_config=None,
25
+ llm_config=None,
26
+ use_backbone_lora=0,
27
+ use_llm_lora=0,
28
+ select_layer=-1,
29
+ force_image_size=None,
30
+ downsample_ratio=0.5,
31
+ template=None,
32
+ dynamic_image_size=False,
33
+ use_thumbnail=False,
34
+ ps_version='v1',
35
+ min_dynamic_patch=1,
36
+ max_dynamic_patch=6,
37
+ **kwargs):
38
+ super().__init__(**kwargs)
39
+
40
+ if vision_config is None:
41
+ vision_config = {}
42
+ logger.info('vision_config is None. Initializing the InternVisionConfig with default values.')
43
+
44
+ if llm_config is None:
45
+ llm_config = {}
46
+ logger.info('llm_config is None. Initializing the LlamaConfig config with default values (`LlamaConfig`).')
47
+
48
+ self.vision_config = InternVisionConfig(**vision_config)
49
+ if llm_config['architectures'][0] == 'LlamaForCausalLM':
50
+ self.llm_config = LlamaConfig(**llm_config)
51
+ else:
52
+ raise ValueError('Unsupported architecture: {}'.format(llm_config['architectures'][0]))
53
+ self.use_backbone_lora = use_backbone_lora
54
+ self.use_llm_lora = use_llm_lora
55
+ self.select_layer = select_layer
56
+ self.force_image_size = force_image_size
57
+ self.downsample_ratio = downsample_ratio
58
+ self.template = template
59
+ self.dynamic_image_size = dynamic_image_size
60
+ self.use_thumbnail = use_thumbnail
61
+ self.ps_version = ps_version # pixel shuffle version
62
+ self.min_dynamic_patch = min_dynamic_patch
63
+ self.max_dynamic_patch = max_dynamic_patch
64
+
65
+ logger.info(f'vision_select_layer: {self.select_layer}')
66
+ logger.info(f'ps_version: {self.ps_version}')
67
+ logger.info(f'min_dynamic_patch: {self.min_dynamic_patch}')
68
+ logger.info(f'max_dynamic_patch: {self.max_dynamic_patch}')
69
+
70
+ def to_dict(self):
71
+ """
72
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
73
+
74
+ Returns:
75
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
76
+ """
77
+ output = copy.deepcopy(self.__dict__)
78
+ output['vision_config'] = self.vision_config.to_dict()
79
+ output['llm_config'] = self.llm_config.to_dict()
80
+ output['model_type'] = self.__class__.model_type
81
+ output['use_backbone_lora'] = self.use_backbone_lora
82
+ output['use_llm_lora'] = self.use_llm_lora
83
+ output['select_layer'] = self.select_layer
84
+ output['force_image_size'] = self.force_image_size
85
+ output['downsample_ratio'] = self.downsample_ratio
86
+ output['template'] = self.template
87
+ output['dynamic_image_size'] = self.dynamic_image_size
88
+ output['use_thumbnail'] = self.use_thumbnail
89
+ output['ps_version'] = self.ps_version
90
+ output['min_dynamic_patch'] = self.min_dynamic_patch
91
+ output['max_dynamic_patch'] = self.max_dynamic_patch
92
+
93
+ return output
conversation.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Conversation prompt templates.
3
+
4
+ We kindly request that you import fastchat instead of copying this file if you wish to use it.
5
+ If you have changes in mind, please contribute back so the community can benefit collectively and continue to maintain these valuable templates.
6
+ """
7
+
8
+ import dataclasses
9
+ from enum import IntEnum, auto
10
+ from typing import Any, Dict, List, Tuple, Union
11
+
12
+
13
+ class SeparatorStyle(IntEnum):
14
+ """Separator styles."""
15
+
16
+ ADD_COLON_SINGLE = auto()
17
+ ADD_COLON_TWO = auto()
18
+ ADD_COLON_SPACE_SINGLE = auto()
19
+ NO_COLON_SINGLE = auto()
20
+ NO_COLON_TWO = auto()
21
+ ADD_NEW_LINE_SINGLE = auto()
22
+ LLAMA2 = auto()
23
+ CHATGLM = auto()
24
+ CHATML = auto()
25
+ CHATINTERN = auto()
26
+ DOLLY = auto()
27
+ RWKV = auto()
28
+ PHOENIX = auto()
29
+ ROBIN = auto()
30
+ FALCON_CHAT = auto()
31
+ CHATGLM3 = auto()
32
+ INTERNVL_ZH = auto()
33
+ MPT = auto()
34
+
35
+
36
+ @dataclasses.dataclass
37
+ class Conversation:
38
+ """A class that manages prompt templates and keeps all conversation history."""
39
+
40
+ # The name of this template
41
+ name: str
42
+ # The template of the system prompt
43
+ system_template: str = '{system_message}'
44
+ # The system message
45
+ system_message: str = ''
46
+ # The names of two roles
47
+ roles: Tuple[str] = ('USER', 'ASSISTANT')
48
+ # All messages. Each item is (role, message).
49
+ messages: List[List[str]] = ()
50
+ # The number of few shot examples
51
+ offset: int = 0
52
+ # The separator style and configurations
53
+ sep_style: SeparatorStyle = SeparatorStyle.ADD_COLON_SINGLE
54
+ sep: str = '\n'
55
+ sep2: str = None
56
+ # Stop criteria (the default one is EOS token)
57
+ stop_str: Union[str, List[str]] = None
58
+ # Stops generation if meeting any token in this list
59
+ stop_token_ids: List[int] = None
60
+
61
+ def get_prompt(self) -> str:
62
+ """Get the prompt for generation."""
63
+ system_prompt = self.system_template.format(system_message=self.system_message)
64
+ if self.sep_style == SeparatorStyle.ADD_COLON_SINGLE:
65
+ ret = system_prompt + self.sep
66
+ for role, message in self.messages:
67
+ if message:
68
+ ret += role + ': ' + message + self.sep
69
+ else:
70
+ ret += role + ':'
71
+ return ret
72
+ elif self.sep_style == SeparatorStyle.ADD_COLON_TWO:
73
+ seps = [self.sep, self.sep2]
74
+ ret = system_prompt + seps[0]
75
+ for i, (role, message) in enumerate(self.messages):
76
+ if message:
77
+ ret += role + ': ' + message + seps[i % 2]
78
+ else:
79
+ ret += role + ':'
80
+ return ret
81
+ elif self.sep_style == SeparatorStyle.ADD_COLON_SPACE_SINGLE:
82
+ ret = system_prompt + self.sep
83
+ for role, message in self.messages:
84
+ if message:
85
+ ret += role + ': ' + message + self.sep
86
+ else:
87
+ ret += role + ': ' # must be end with a space
88
+ return ret
89
+ elif self.sep_style == SeparatorStyle.ADD_NEW_LINE_SINGLE:
90
+ ret = '' if system_prompt == '' else system_prompt + self.sep
91
+ for role, message in self.messages:
92
+ if message:
93
+ ret += role + '\n' + message + self.sep
94
+ else:
95
+ ret += role + '\n'
96
+ return ret
97
+ elif self.sep_style == SeparatorStyle.NO_COLON_SINGLE:
98
+ ret = system_prompt
99
+ for role, message in self.messages:
100
+ if message:
101
+ ret += role + message + self.sep
102
+ else:
103
+ ret += role
104
+ return ret
105
+ elif self.sep_style == SeparatorStyle.NO_COLON_TWO:
106
+ seps = [self.sep, self.sep2]
107
+ ret = system_prompt
108
+ for i, (role, message) in enumerate(self.messages):
109
+ if message:
110
+ ret += role + message + seps[i % 2]
111
+ else:
112
+ ret += role
113
+ return ret
114
+ elif self.sep_style == SeparatorStyle.RWKV:
115
+ ret = system_prompt
116
+ for i, (role, message) in enumerate(self.messages):
117
+ if message:
118
+ ret += (
119
+ role
120
+ + ': '
121
+ + message.replace('\r\n', '\n').replace('\n\n', '\n')
122
+ )
123
+ ret += '\n\n'
124
+ else:
125
+ ret += role + ':'
126
+ return ret
127
+ elif self.sep_style == SeparatorStyle.LLAMA2:
128
+ seps = [self.sep, self.sep2]
129
+ if self.system_message:
130
+ ret = system_prompt
131
+ else:
132
+ ret = '[INST] '
133
+ for i, (role, message) in enumerate(self.messages):
134
+ tag = self.roles[i % 2]
135
+ if message:
136
+ if i == 0:
137
+ ret += message + ' '
138
+ else:
139
+ ret += tag + ' ' + message + seps[i % 2]
140
+ else:
141
+ ret += tag
142
+ return ret
143
+ elif self.sep_style == SeparatorStyle.CHATGLM:
144
+ # source: https://huggingface.co/THUDM/chatglm-6b/blob/1d240ba371910e9282298d4592532d7f0f3e9f3e/modeling_chatglm.py#L1302-L1308
145
+ # source2: https://huggingface.co/THUDM/chatglm2-6b/blob/e186c891cf64310ac66ef10a87e6635fa6c2a579/modeling_chatglm.py#L926
146
+ round_add_n = 1 if self.name == 'chatglm2' else 0
147
+ if system_prompt:
148
+ ret = system_prompt + self.sep
149
+ else:
150
+ ret = ''
151
+
152
+ for i, (role, message) in enumerate(self.messages):
153
+ if i % 2 == 0:
154
+ ret += f'[Round {i//2 + round_add_n}]{self.sep}'
155
+
156
+ if message:
157
+ ret += f'{role}:{message}{self.sep}'
158
+ else:
159
+ ret += f'{role}:'
160
+ return ret
161
+ elif self.sep_style == SeparatorStyle.CHATML:
162
+ ret = '' if system_prompt == '' else system_prompt + self.sep + '\n'
163
+ for role, message in self.messages:
164
+ if message:
165
+ ret += role + '\n' + message + self.sep + '\n'
166
+ else:
167
+ ret += role + '\n'
168
+ return ret
169
+ elif self.sep_style == SeparatorStyle.CHATGLM3:
170
+ ret = ''
171
+ if self.system_message:
172
+ ret += system_prompt
173
+ for role, message in self.messages:
174
+ if message:
175
+ ret += role + '\n' + ' ' + message
176
+ else:
177
+ ret += role
178
+ return ret
179
+ elif self.sep_style == SeparatorStyle.CHATINTERN:
180
+ # source: https://huggingface.co/internlm/internlm-chat-7b-8k/blob/bd546fa984b4b0b86958f56bf37f94aa75ab8831/modeling_internlm.py#L771
181
+ seps = [self.sep, self.sep2]
182
+ ret = system_prompt
183
+ for i, (role, message) in enumerate(self.messages):
184
+ # if i % 2 == 0:
185
+ # ret += "<s>"
186
+ if message:
187
+ ret += role + ':' + message + seps[i % 2] + '\n'
188
+ else:
189
+ ret += role + ':'
190
+ return ret
191
+ elif self.sep_style == SeparatorStyle.DOLLY:
192
+ seps = [self.sep, self.sep2]
193
+ ret = system_prompt
194
+ for i, (role, message) in enumerate(self.messages):
195
+ if message:
196
+ ret += role + ':\n' + message + seps[i % 2]
197
+ if i % 2 == 1:
198
+ ret += '\n\n'
199
+ else:
200
+ ret += role + ':\n'
201
+ return ret
202
+ elif self.sep_style == SeparatorStyle.PHOENIX:
203
+ ret = system_prompt
204
+ for role, message in self.messages:
205
+ if message:
206
+ ret += role + ': ' + '<s>' + message + '</s>'
207
+ else:
208
+ ret += role + ': ' + '<s>'
209
+ return ret
210
+ elif self.sep_style == SeparatorStyle.ROBIN:
211
+ ret = system_prompt + self.sep
212
+ for role, message in self.messages:
213
+ if message:
214
+ ret += role + ':\n' + message + self.sep
215
+ else:
216
+ ret += role + ':\n'
217
+ return ret
218
+ elif self.sep_style == SeparatorStyle.FALCON_CHAT:
219
+ ret = ''
220
+ if self.system_message:
221
+ ret += system_prompt + self.sep
222
+ for role, message in self.messages:
223
+ if message:
224
+ ret += role + ': ' + message + self.sep
225
+ else:
226
+ ret += role + ':'
227
+
228
+ return ret
229
+ elif self.sep_style == SeparatorStyle.INTERNVL_ZH:
230
+ seps = [self.sep, self.sep2]
231
+ ret = self.system_message + seps[0]
232
+ for i, (role, message) in enumerate(self.messages):
233
+ if message:
234
+ ret += role + ': ' + message + seps[i % 2]
235
+ else:
236
+ ret += role + ':'
237
+ return ret
238
+ elif self.sep_style == SeparatorStyle.MPT:
239
+ ret = system_prompt + self.sep
240
+ for role, message in self.messages:
241
+ if message:
242
+ if type(message) is tuple:
243
+ message, _, _ = message
244
+ ret += role + message + self.sep
245
+ else:
246
+ ret += role
247
+ return ret
248
+ else:
249
+ raise ValueError(f'Invalid style: {self.sep_style}')
250
+
251
+ def set_system_message(self, system_message: str):
252
+ """Set the system message."""
253
+ self.system_message = system_message
254
+
255
+ def append_message(self, role: str, message: str):
256
+ """Append a new message."""
257
+ self.messages.append([role, message])
258
+
259
+ def update_last_message(self, message: str):
260
+ """Update the last output.
261
+
262
+ The last message is typically set to be None when constructing the prompt,
263
+ so we need to update it in-place after getting the response from a model.
264
+ """
265
+ self.messages[-1][1] = message
266
+
267
+ def to_gradio_chatbot(self):
268
+ """Convert the conversation to gradio chatbot format."""
269
+ ret = []
270
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
271
+ if i % 2 == 0:
272
+ ret.append([msg, None])
273
+ else:
274
+ ret[-1][-1] = msg
275
+ return ret
276
+
277
+ def to_openai_api_messages(self):
278
+ """Convert the conversation to OpenAI chat completion format."""
279
+ ret = [{'role': 'system', 'content': self.system_message}]
280
+
281
+ for i, (_, msg) in enumerate(self.messages[self.offset :]):
282
+ if i % 2 == 0:
283
+ ret.append({'role': 'user', 'content': msg})
284
+ else:
285
+ if msg is not None:
286
+ ret.append({'role': 'assistant', 'content': msg})
287
+ return ret
288
+
289
+ def copy(self):
290
+ return Conversation(
291
+ name=self.name,
292
+ system_template=self.system_template,
293
+ system_message=self.system_message,
294
+ roles=self.roles,
295
+ messages=[[x, y] for x, y in self.messages],
296
+ offset=self.offset,
297
+ sep_style=self.sep_style,
298
+ sep=self.sep,
299
+ sep2=self.sep2,
300
+ stop_str=self.stop_str,
301
+ stop_token_ids=self.stop_token_ids,
302
+ )
303
+
304
+ def dict(self):
305
+ return {
306
+ 'template_name': self.name,
307
+ 'system_message': self.system_message,
308
+ 'roles': self.roles,
309
+ 'messages': self.messages,
310
+ 'offset': self.offset,
311
+ }
312
+
313
+
314
+ # A global registry for all conversation templates
315
+ conv_templates: Dict[str, Conversation] = {}
316
+
317
+
318
+ def register_conv_template(template: Conversation, override: bool = False):
319
+ """Register a new conversation template."""
320
+ if not override:
321
+ assert (
322
+ template.name not in conv_templates
323
+ ), f'{template.name} has been registered.'
324
+
325
+ conv_templates[template.name] = template
326
+
327
+
328
+ def get_conv_template(name: str) -> Conversation:
329
+ """Get a conversation template."""
330
+ return conv_templates[name].copy()
331
+
332
+
333
+ # Both Hermes-2 and internlm2-chat are chatml-format conversation templates. The difference
334
+ # is that during training, the preprocessing function for the Hermes-2 template doesn't add
335
+ # <s> at the beginning of the tokenized sequence, while the internlm2-chat template does.
336
+ # Therefore, they are completely equivalent during inference.
337
+ register_conv_template(
338
+ Conversation(
339
+ name='Hermes-2',
340
+ system_template='<|im_start|>system\n{system_message}',
341
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
342
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
343
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
344
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
345
+ sep_style=SeparatorStyle.MPT,
346
+ sep='<|im_end|>',
347
+ stop_token_ids=[
348
+ 2,
349
+ 6,
350
+ 7,
351
+ 8,
352
+ ],
353
+ stop_str='<|endoftext|>',
354
+ )
355
+ )
356
+
357
+
358
+ register_conv_template(
359
+ Conversation(
360
+ name='internlm2-chat',
361
+ system_template='<|im_start|>system\n{system_message}',
362
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
363
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
364
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
365
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
366
+ sep_style=SeparatorStyle.MPT,
367
+ sep='<|im_end|>',
368
+ stop_token_ids=[
369
+ 2,
370
+ 92543,
371
+ 92542
372
+ ]
373
+ )
374
+ )
375
+
376
+
377
+ register_conv_template(
378
+ Conversation(
379
+ name='phi3-chat',
380
+ system_template='<|system|>\n{system_message}',
381
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
382
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
383
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
384
+ roles=('<|user|>\n', '<|assistant|>\n'),
385
+ sep_style=SeparatorStyle.MPT,
386
+ sep='<|end|>',
387
+ stop_token_ids=[
388
+ 2,
389
+ 32000,
390
+ 32007
391
+ ]
392
+ )
393
+ )
examples/image1.jpg ADDED
examples/image2.jpg ADDED
examples/red-panda.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d921c07bb97224d65a37801541d246067f0d506f08723ffa1ad85c217907ccb8
3
+ size 1867237
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.37.2",
4
+ "eos_token_id": [
5
+ 2,
6
+ 6,
7
+ 7
8
+ ]
9
+ }
model-00001-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c2e9c8f2eef93cca26b264644bbd1e60628509ba86cbd165d7dfcefae31a145c
3
+ size 4988569440
model-00002-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c9eb45570a3d8ef7531b3b3639aeee3332306743e6f6fc7ea1016df2dea6e71
3
+ size 4937253584
model-00003-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:52dd534aad2a47b0b090095503ec0919c3cfeb5d06e605a16eb34ef519a76ab9
3
+ size 4824755816
model-00004-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df877c2baafa117b17f01a95d138871b94f9e96fc7aaddf9a285cdd510c4d6ec
3
+ size 4756460272
model-00005-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:780130f0ee53e957929fcb9464aa9a589fc3b679deedba18597af1ccab790e83
3
+ size 4991370776
model-00006-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b14d64e3fa3df206e0d1c9a1fa9e580cd0b5c353eee68a7d5e54bf0c78b4b32f
3
+ size 4756460312
model-00007-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4f618c5331913ced2396d4f12680da1b56ca2b55a88c3a2c95829ecf8e3bfb4f
3
+ size 4756460312
model-00008-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:956f796b54b3ae052b45b9782c1d9105826d4de52edda10f858d23d460073f22
3
+ size 4991370808
model-00009-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:83f3ba456f52aece1995dc0189a2ea076fb0cae34bafa9c0645422181ce8f9de
3
+ size 4756460312
model-00010-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:681d56b93f433bddf6c852588c6434c9b4ef98d84ec52dc874b9ce4018eddc68
3
+ size 4756460312
model-00011-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1b6777cb681d25f05fe6eee1ff9b8e1616b364564a1ea94863f63c32c5ae56f0
3
+ size 4991370808
model-00012-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:603ebafa77744de964ad013bb10e01336c9fb6b077f917800040b0ef177aa2bd
3
+ size 4756460312
model-00013-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b37c1abdc6235f39ac3f1c543da51cec39b862daea98ca552f36fd1e69ab747f
3
+ size 4756460312
model-00014-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9f667ade7d23d434b8629043085a4b520a66fcee28fb02786d927cf15e567f51
3
+ size 4991370808
model-00015-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fe21d55429ad26c3e2f4bc5c0a9f3acd2975a99417f9f7805c1740231f1482d8
3
+ size 4756460312
model-00016-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae329cb9495eb32b8bf3bbfae93925538ab3e2fd4190e4f1f2fed4dd28091d64
3
+ size 4756460312
model-00017-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:16ebf24219a66f553f3e5742a4525998c14adc3466bad489828637e97ad8730b
3
+ size 2613305648
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_intern_vit.py ADDED
@@ -0,0 +1,477 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+ from typing import Optional, Tuple, Union
7
+ import math
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ import torch.utils.checkpoint
12
+ from einops import rearrange
13
+ from timm.models.layers import DropPath
14
+ from torch import nn
15
+ from transformers.activations import ACT2FN
16
+ from transformers.modeling_outputs import (BaseModelOutput,
17
+ BaseModelOutputWithPooling)
18
+ from transformers.modeling_utils import PreTrainedModel
19
+ from transformers.utils import logging
20
+
21
+ from .configuration_intern_vit import InternVisionConfig
22
+
23
+ from torch_xla import runtime as xr
24
+
25
+ from torch_xla.experimental.custom_kernel import flash_attention
26
+
27
+ def apply_xla_flash_attention(query_states, key_states, value_states):
28
+ from torch_xla.experimental.custom_kernel import flash_attention
29
+
30
+ # q, k, v should all have the shape [B, n_head, S, head_dim]
31
+ head_dim = query_states.size()[-1]
32
+ query_states = query_states / math.sqrt(head_dim)
33
+ # Our simplified version of decoder only model does not use any mask.
34
+ attn_output = flash_attention(
35
+ query_states, key_states, value_states, causal=False)
36
+ return attn_output
37
+
38
+
39
+ try:
40
+ from flash_attn.bert_padding import pad_input, unpad_input
41
+ from flash_attn.flash_attn_interface import \
42
+ flash_attn_varlen_qkvpacked_func
43
+ has_flash_attn = True
44
+ except:
45
+ print('FlashAttention2 is not installed.')
46
+ has_flash_attn = False
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+
51
+ class FlashAttention(nn.Module):
52
+ """Implement the scaled dot product attention with softmax.
53
+ Arguments
54
+ ---------
55
+ softmax_scale: The temperature to use for the softmax attention.
56
+ (default: 1/sqrt(d_keys) where d_keys is computed at
57
+ runtime)
58
+ attention_dropout: The dropout rate to apply to the attention
59
+ (default: 0.0)
60
+ """
61
+
62
+ def __init__(self, softmax_scale=None, attention_dropout=0.0, device=None, dtype=None):
63
+ super().__init__()
64
+ self.softmax_scale = softmax_scale
65
+ self.dropout_p = attention_dropout
66
+
67
+ def forward(self, qkv, key_padding_mask=None, causal=False, cu_seqlens=None,
68
+ max_s=None, need_weights=False):
69
+ """Implements the multihead softmax attention.
70
+ Arguments
71
+ ---------
72
+ qkv: The tensor containing the query, key, and value. (B, S, 3, H, D) if key_padding_mask is None
73
+ if unpadded: (nnz, 3, h, d)
74
+ key_padding_mask: a bool tensor of shape (B, S)
75
+ """
76
+ assert not need_weights
77
+ assert qkv.dtype in [torch.float16, torch.bfloat16]
78
+
79
+ if cu_seqlens is None:
80
+ batch_size = qkv.shape[0]
81
+ seqlen = qkv.shape[1]
82
+ if key_padding_mask is None:
83
+ qkv = rearrange(qkv, 'b s ... -> (b s) ...')
84
+ max_s = seqlen
85
+ cu_seqlens = torch.arange(0, (batch_size + 1) * seqlen, step=seqlen, dtype=torch.int32,
86
+ device=qkv.device)
87
+ output = flash_attn_varlen_qkvpacked_func(
88
+ qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
89
+ softmax_scale=self.softmax_scale, causal=causal
90
+ )
91
+ output = rearrange(output, '(b s) ... -> b s ...', b=batch_size)
92
+ else:
93
+ nheads = qkv.shape[-2]
94
+ x = rearrange(qkv, 'b s three h d -> b s (three h d)')
95
+ x_unpad, indices, cu_seqlens, max_s = unpad_input(x, key_padding_mask)
96
+ x_unpad = rearrange(x_unpad, 'nnz (three h d) -> nnz three h d', three=3, h=nheads)
97
+ output_unpad = flash_attn_varlen_qkvpacked_func(
98
+ x_unpad, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
99
+ softmax_scale=self.softmax_scale, causal=causal
100
+ )
101
+ output = rearrange(pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'),
102
+ indices, batch_size, seqlen),
103
+ 'b s (h d) -> b s h d', h=nheads)
104
+ else:
105
+ assert max_s is not None
106
+ output = flash_attn_varlen_qkvpacked_func(
107
+ qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
108
+ softmax_scale=self.softmax_scale, causal=causal
109
+ )
110
+
111
+ return output, None
112
+
113
+
114
+ class InternRMSNorm(nn.Module):
115
+ def __init__(self, hidden_size, eps=1e-6):
116
+ super().__init__()
117
+ self.weight = nn.Parameter(torch.ones(hidden_size))
118
+ self.variance_epsilon = eps
119
+
120
+ def forward(self, hidden_states):
121
+ input_dtype = hidden_states.dtype
122
+ hidden_states = hidden_states.to(torch.float32)
123
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
124
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
125
+ return self.weight * hidden_states.to(input_dtype)
126
+
127
+
128
+ try:
129
+ from apex.normalization import FusedRMSNorm
130
+
131
+ InternRMSNorm = FusedRMSNorm # noqa
132
+
133
+ logger.info('Discovered apex.normalization.FusedRMSNorm - will use it instead of InternRMSNorm')
134
+ except ImportError:
135
+ # using the normal InternRMSNorm
136
+ pass
137
+ except Exception:
138
+ logger.warning('discovered apex but it failed to load, falling back to InternRMSNorm')
139
+ pass
140
+
141
+
142
+ NORM2FN = {
143
+ 'rms_norm': InternRMSNorm,
144
+ 'layer_norm': nn.LayerNorm,
145
+ }
146
+
147
+
148
+ class InternVisionEmbeddings(nn.Module):
149
+ def __init__(self, config: InternVisionConfig):
150
+ super().__init__()
151
+ self.config = config
152
+ self.embed_dim = config.hidden_size
153
+ self.image_size = config.image_size
154
+ self.patch_size = config.patch_size
155
+
156
+ self.class_embedding = nn.Parameter(
157
+ torch.randn(1, 1, self.embed_dim),
158
+ )
159
+
160
+ self.patch_embedding = nn.Conv2d(
161
+ in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
162
+ )
163
+
164
+ self.num_patches = (self.image_size // self.patch_size) ** 2
165
+ self.num_positions = self.num_patches + 1
166
+
167
+ self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
168
+
169
+ def _get_pos_embed(self, pos_embed, H, W):
170
+ target_dtype = pos_embed.dtype
171
+ B, N, C = pos_embed.shape # Get the batch, number of patches, and channels
172
+ sqrt_N = int(math.sqrt(N))
173
+ if sqrt_N * sqrt_N != N:
174
+ raise ValueError("Input tensor size does not match a square grid. Adjust H and W accordingly.")
175
+
176
+ pos_embed = (
177
+ pos_embed.float()
178
+ .reshape(
179
+ B,
180
+ sqrt_N,
181
+ sqrt_N,
182
+ C,
183
+ )
184
+ .permute(0, 3, 1, 2)
185
+ )
186
+ pos_embed = (
187
+ F.interpolate(pos_embed, size=(H, W), mode="bicubic", align_corners=False)
188
+ .reshape(B, -1, H * W)
189
+ .permute(0, 2, 1)
190
+ .to(target_dtype)
191
+ )
192
+ return pos_embed
193
+
194
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
195
+ with torch.inference_mode(False):
196
+ target_dtype = self.patch_embedding.weight.dtype
197
+ patch_embeds = self.patch_embedding(pixel_values.clone()) # shape = [*, channel, width, height]
198
+ batch_size, _, height, width = patch_embeds.shape
199
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
200
+
201
+ # Expand first, then convert dtype
202
+ class_embeds = self.class_embedding.repeat(batch_size, 1, 1).to(target_dtype)
203
+ class_embeds = class_embeds.to(target_dtype)
204
+
205
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
206
+ position_embedding = torch.cat([
207
+ self.position_embedding.clone()[:, :1, :],
208
+ self._get_pos_embed(self.position_embedding.clone()[:, 1:, :], height, width)
209
+ ], dim=1)
210
+ embeddings = embeddings + position_embedding.to(target_dtype)
211
+ return embeddings
212
+
213
+
214
+
215
+ class InternAttention(nn.Module):
216
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
217
+
218
+ def __init__(self, config: InternVisionConfig):
219
+ super().__init__()
220
+ self.config = config
221
+ self.embed_dim = config.hidden_size
222
+ self.num_heads = config.num_attention_heads
223
+ self.use_flash_attn = config.use_flash_attn and has_flash_attn
224
+ if config.use_flash_attn and not has_flash_attn:
225
+ print('Warning: Flash Attention is not available, use_flash_attn is set to False.')
226
+ self.head_dim = self.embed_dim // self.num_heads
227
+ if self.head_dim * self.num_heads != self.embed_dim:
228
+ raise ValueError(
229
+ f'embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:'
230
+ f' {self.num_heads}).'
231
+ )
232
+
233
+ self.scale = self.head_dim ** -0.5
234
+ self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim, bias=config.qkv_bias)
235
+ self.attn_drop = nn.Dropout(config.attention_dropout)
236
+ self.proj_drop = nn.Dropout(config.dropout)
237
+
238
+ self.qk_normalization = config.qk_normalization
239
+
240
+ if self.qk_normalization:
241
+ self.q_norm = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
242
+ self.k_norm = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
243
+
244
+ if self.use_flash_attn:
245
+ self.inner_attn = FlashAttention(attention_dropout=config.attention_dropout)
246
+ self.proj = nn.Linear(self.embed_dim, self.embed_dim)
247
+
248
+ def _xla_flash_attn(self, x):
249
+ print(f"x: {x.device}")
250
+ with torch.inference_mode(False):
251
+ qkv = self.qkv(x)
252
+ qkv = rearrange(qkv, 'b s (three h d) -> b s three h d', three=3, h=self.num_heads)
253
+
254
+ # Unbind the qkv tensor into separate query, key, and value tensors
255
+ q, k, v = qkv.unbind(2)
256
+
257
+ # Optional query/key normalization
258
+ if self.qk_normalization:
259
+ q = self.q_norm(q.flatten(-2, -1)).view(q.shape)
260
+ k = self.k_norm(k.flatten(-2, -1)).view(k.shape)
261
+
262
+ # Apply XLA flash attention
263
+ context = apply_xla_flash_attention(q, k, v)
264
+
265
+ # Reshape and project the output
266
+ outs = self.proj(rearrange(context, 'b s h d -> b s (h d)'))
267
+ outs = self.proj_drop(outs)
268
+
269
+ return outs
270
+
271
+ def _flash_attn(self, x, key_padding_mask=None, need_weights=False):
272
+ qkv = self.qkv(x)
273
+ qkv = rearrange(qkv, 'b s (three h d) -> b s three h d', three=3, h=self.num_heads)
274
+
275
+ if self.qk_normalization:
276
+ q, k, v = qkv.unbind(2)
277
+ q = self.q_norm(q.flatten(-2, -1)).view(q.shape)
278
+ k = self.k_norm(k.flatten(-2, -1)).view(k.shape)
279
+ qkv = torch.stack([q, k, v], dim=2)
280
+
281
+ context, _ = self.inner_attn(
282
+ qkv, key_padding_mask=key_padding_mask, need_weights=need_weights, causal=False
283
+ )
284
+ outs = self.proj(rearrange(context, 'b s h d -> b s (h d)'))
285
+ outs = self.proj_drop(outs)
286
+ return outs
287
+
288
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
289
+ x = self._xla_flash_attn(hidden_states) if not self.use_flash_attn else self._flash_attn(hidden_states)
290
+ return x
291
+
292
+
293
+ class InternMLP(nn.Module):
294
+ def __init__(self, config: InternVisionConfig):
295
+ super().__init__()
296
+ self.config = config
297
+ self.act = ACT2FN[config.hidden_act]
298
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
299
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
300
+
301
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
302
+ with torch.inference_mode(False):
303
+ hidden_states = self.fc1(hidden_states)
304
+ hidden_states = self.act(hidden_states)
305
+ hidden_states = self.fc2(hidden_states)
306
+ return hidden_states
307
+
308
+
309
+ class InternVisionEncoderLayer(nn.Module):
310
+ def __init__(self, config: InternVisionConfig, drop_path_rate: float):
311
+ super().__init__()
312
+ self.embed_dim = config.hidden_size
313
+ self.intermediate_size = config.intermediate_size
314
+ self.norm_type = config.norm_type
315
+
316
+ self.attn = InternAttention(config)
317
+ self.mlp = InternMLP(config)
318
+ self.norm1 = NORM2FN[self.norm_type](self.embed_dim, eps=config.layer_norm_eps)
319
+ self.norm2 = NORM2FN[self.norm_type](self.embed_dim, eps=config.layer_norm_eps)
320
+
321
+ self.ls1 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
322
+ self.ls2 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
323
+ self.drop_path1 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
324
+ self.drop_path2 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
325
+
326
+ def forward(
327
+ self,
328
+ hidden_states: torch.Tensor,
329
+ ) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor], Optional[Tuple[torch.FloatTensor]]]:
330
+ """
331
+ Args:
332
+ hidden_states (`Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]`): input to the layer of shape `(batch, seq_len, embed_dim)`
333
+ """
334
+ norm1_ = self.norm1(hidden_states).clone().to(hidden_states.dtype)
335
+ norm1 = self.attn(norm1_) * self.ls1
336
+
337
+ hidden_states = hidden_states + self.drop_path1(norm1)
338
+
339
+ norm2 = self.mlp(self.norm2(hidden_states).clone().to(hidden_states.dtype)) * self.ls2
340
+ hidden_states = hidden_states + self.drop_path2(norm2)
341
+
342
+ return hidden_states
343
+
344
+
345
+ class InternVisionEncoder(nn.Module):
346
+ """
347
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
348
+ [`InternEncoderLayer`].
349
+
350
+ Args:
351
+ config (`InternConfig`):
352
+ The corresponding vision configuration for the `InternEncoder`.
353
+ """
354
+
355
+ def __init__(self, config: InternVisionConfig):
356
+ super().__init__()
357
+ self.config = config
358
+ # stochastic depth decay rule
359
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers)]
360
+ self.layers = nn.ModuleList([
361
+ InternVisionEncoderLayer(config, dpr[idx]) for idx in range(config.num_hidden_layers)])
362
+ self.gradient_checkpointing = True
363
+
364
+ def forward(
365
+ self,
366
+ inputs_embeds,
367
+ output_hidden_states: Optional[bool] = None,
368
+ return_dict: Optional[bool] = None,
369
+ ) -> Union[Tuple, BaseModelOutput]:
370
+ r"""
371
+ Args:
372
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
373
+ Embedded representation of the inputs. Should be float, not int tokens.
374
+ output_hidden_states (`bool`, *optional*):
375
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
376
+ for more detail.
377
+ return_dict (`bool`, *optional*):
378
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
379
+ """
380
+ output_hidden_states = (
381
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
382
+ )
383
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
384
+
385
+ encoder_states = () if output_hidden_states else None
386
+ hidden_states = inputs_embeds
387
+
388
+ for idx, encoder_layer in enumerate(self.layers):
389
+ if output_hidden_states:
390
+ encoder_states = encoder_states + (hidden_states,)
391
+ if self.gradient_checkpointing and self.training:
392
+ layer_outputs = torch.utils.checkpoint.checkpoint(
393
+ encoder_layer,
394
+ hidden_states)
395
+ else:
396
+ layer_outputs = encoder_layer(
397
+ hidden_states,
398
+ )
399
+ hidden_states = layer_outputs
400
+
401
+ if output_hidden_states:
402
+ encoder_states = encoder_states + (hidden_states,)
403
+
404
+ if not return_dict:
405
+ return tuple(v for v in [hidden_states, encoder_states] if v is not None)
406
+ return BaseModelOutput(
407
+ last_hidden_state=hidden_states, hidden_states=encoder_states
408
+ )
409
+
410
+
411
+ class InternVisionModel(PreTrainedModel):
412
+ main_input_name = 'pixel_values'
413
+ _supports_flash_attn_2 = True
414
+ config_class = InternVisionConfig
415
+ _no_split_modules = ['InternVisionEncoderLayer']
416
+
417
+ def __init__(self, config: InternVisionConfig):
418
+ super().__init__(config)
419
+ self.config = config
420
+
421
+ self.embeddings = InternVisionEmbeddings(config)
422
+ self.encoder = InternVisionEncoder(config)
423
+
424
+ def resize_pos_embeddings(self, old_size, new_size, patch_size):
425
+ pos_emb = self.embeddings.position_embedding
426
+ _, num_positions, embed_dim = pos_emb.shape
427
+ cls_emb = pos_emb[:, :1, :]
428
+ pos_emb = pos_emb[:, 1:, :].reshape(1, old_size // patch_size, old_size // patch_size, -1).permute(0, 3, 1, 2)
429
+ pos_emb = F.interpolate(pos_emb.float(), size=new_size // patch_size, mode='bicubic', align_corners=False)
430
+ pos_emb = pos_emb.to(cls_emb.dtype).reshape(1, embed_dim, -1).permute(0, 2, 1)
431
+ pos_emb = torch.cat([cls_emb, pos_emb], dim=1)
432
+ self.embeddings.position_embedding = nn.Parameter(pos_emb)
433
+ self.embeddings.image_size = new_size
434
+ logger.info('Resized position embeddings from {} to {}'.format(old_size, new_size))
435
+
436
+ def get_input_embeddings(self):
437
+ return self.embeddings
438
+
439
+ def forward(
440
+ self,
441
+ pixel_values: Optional[torch.FloatTensor] = None,
442
+ output_hidden_states: Optional[bool] = None,
443
+ return_dict: Optional[bool] = None,
444
+ pixel_embeds: Optional[torch.FloatTensor] = None,
445
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
446
+ output_hidden_states = (
447
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
448
+ )
449
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
450
+
451
+ if pixel_values is None and pixel_embeds is None:
452
+ raise ValueError('You have to specify pixel_values or pixel_embeds')
453
+
454
+ if pixel_embeds is not None:
455
+ hidden_states = pixel_embeds
456
+ else:
457
+ if len(pixel_values.shape) == 4:
458
+ hidden_states = self.embeddings(pixel_values)
459
+ else:
460
+ raise ValueError(f'wrong pixel_values size: {pixel_values.shape}')
461
+ encoder_outputs = self.encoder(
462
+ inputs_embeds=hidden_states,
463
+ output_hidden_states=output_hidden_states,
464
+ return_dict=return_dict,
465
+ )
466
+ last_hidden_state = encoder_outputs.last_hidden_state
467
+ pooled_output = last_hidden_state[:, 0, :]
468
+
469
+ if not return_dict:
470
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
471
+
472
+ return BaseModelOutputWithPooling(
473
+ last_hidden_state=last_hidden_state,
474
+ pooler_output=pooled_output,
475
+ hidden_states=encoder_outputs.hidden_states,
476
+ attentions=encoder_outputs.attentions,
477
+ )
modeling_internvl_chat.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+ import warnings
7
+ from typing import Any, List, Optional, Tuple, Union
8
+
9
+ import torch.utils.checkpoint
10
+ import transformers
11
+ from torch import nn
12
+ from torch.nn import CrossEntropyLoss
13
+ from transformers import AutoModel, GenerationConfig, LlamaForCausalLM
14
+ from transformers.modeling_outputs import CausalLMOutputWithPast
15
+ from transformers.modeling_utils import PreTrainedModel
16
+ from transformers.utils import ModelOutput, logging
17
+
18
+ from .configuration_internvl_chat import InternVLChatConfig
19
+ from .conversation import get_conv_template
20
+ from .modeling_intern_vit import InternVisionModel, has_flash_attn
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ def version_cmp(v1, v2, op='eq'):
26
+ import operator
27
+
28
+ from packaging import version
29
+ op_func = getattr(operator, op)
30
+ return op_func(version.parse(v1), version.parse(v2))
31
+
32
+
33
+ class InternVLChatModel(PreTrainedModel):
34
+ config_class = InternVLChatConfig
35
+ main_input_name = 'pixel_values'
36
+ _supports_flash_attn_2 = True
37
+ _no_split_modules = ['InternVisionModel', 'LlamaDecoderLayer']
38
+
39
+ def __init__(self, config: InternVLChatConfig, vision_model=None, language_model=None, use_flash_attn=True):
40
+ super().__init__(config)
41
+
42
+ assert version_cmp(transformers.__version__, '4.36.2', 'ge')
43
+ image_size = config.force_image_size or config.vision_config.image_size
44
+ patch_size = config.vision_config.patch_size
45
+ self.patch_size = patch_size
46
+ self.select_layer = config.select_layer
47
+ self.template = config.template
48
+ self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio ** 2))
49
+ self.downsample_ratio = config.downsample_ratio
50
+ self.ps_version = config.ps_version
51
+ use_flash_attn = use_flash_attn if has_flash_attn else False
52
+ config.vision_config.use_flash_attn = True if use_flash_attn else False
53
+ config.llm_config._attn_implementation = 'flash_attention_2' if use_flash_attn else 'eager'
54
+
55
+ logger.info(f'num_image_token: {self.num_image_token}')
56
+ logger.info(f'ps_version: {self.ps_version}')
57
+ if vision_model is not None:
58
+ self.vision_model = vision_model
59
+ else:
60
+ self.vision_model = InternVisionModel(config.vision_config)
61
+ if language_model is not None:
62
+ self.language_model = language_model
63
+ else:
64
+ if config.llm_config.architectures[0] == 'LlamaForCausalLM':
65
+ self.language_model = LlamaForCausalLM(config.llm_config)
66
+ else:
67
+ raise NotImplementedError(f'{config.llm_config.architectures[0]} is not implemented.')
68
+
69
+ vit_hidden_size = config.vision_config.hidden_size
70
+ llm_hidden_size = config.llm_config.hidden_size
71
+
72
+ self.mlp1 = nn.Sequential(
73
+ nn.LayerNorm(vit_hidden_size * int(1 / self.downsample_ratio) ** 2),
74
+ nn.Linear(vit_hidden_size * int(1 / self.downsample_ratio) ** 2, llm_hidden_size),
75
+ nn.GELU(),
76
+ nn.Linear(llm_hidden_size, llm_hidden_size)
77
+ )
78
+
79
+ self.img_context_token_id = None
80
+ self.conv_template = get_conv_template(self.template)
81
+ self.system_message = self.conv_template.system_message
82
+
83
+ def forward(
84
+ self,
85
+ pixel_values: torch.FloatTensor,
86
+ input_ids: torch.LongTensor = None,
87
+ attention_mask: Optional[torch.Tensor] = None,
88
+ position_ids: Optional[torch.LongTensor] = None,
89
+ image_flags: Optional[torch.LongTensor] = None,
90
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
91
+ labels: Optional[torch.LongTensor] = None,
92
+ use_cache: Optional[bool] = None,
93
+ output_attentions: Optional[bool] = None,
94
+ output_hidden_states: Optional[bool] = None,
95
+ return_dict: Optional[bool] = None,
96
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
97
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
98
+
99
+ image_flags = image_flags.squeeze(-1)
100
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
101
+
102
+ vit_embeds = self.extract_feature(pixel_values)
103
+ vit_embeds = vit_embeds[image_flags == 1]
104
+ vit_batch_size = pixel_values.shape[0]
105
+
106
+ B, N, C = input_embeds.shape
107
+ input_embeds = input_embeds.reshape(B * N, C)
108
+
109
+ if torch.distributed.get_rank() == 0:
110
+ print(f'dynamic ViT batch size: {vit_batch_size}, images per sample: {vit_batch_size / B}, dynamic token length: {N}')
111
+
112
+ input_ids = input_ids.reshape(B * N)
113
+ selected = (input_ids == self.img_context_token_id)
114
+ try:
115
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds.reshape(-1, C)
116
+ except Exception as e:
117
+ vit_embeds = vit_embeds.reshape(-1, C)
118
+ print(f'warning: {e}, input_embeds[selected].shape={input_embeds[selected].shape}, '
119
+ f'vit_embeds.shape={vit_embeds.shape}')
120
+ n_token = selected.sum()
121
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds[:n_token]
122
+
123
+ input_embeds = input_embeds.reshape(B, N, C)
124
+
125
+ outputs = self.language_model(
126
+ inputs_embeds=input_embeds,
127
+ attention_mask=attention_mask,
128
+ position_ids=position_ids,
129
+ past_key_values=past_key_values,
130
+ use_cache=use_cache,
131
+ output_attentions=output_attentions,
132
+ output_hidden_states=output_hidden_states,
133
+ return_dict=return_dict,
134
+ )
135
+ logits = outputs.logits
136
+
137
+ loss = None
138
+ if labels is not None:
139
+ # Shift so that tokens < n predict n
140
+ shift_logits = logits[..., :-1, :].contiguous()
141
+ shift_labels = labels[..., 1:].contiguous()
142
+ # Flatten the tokens
143
+ loss_fct = CrossEntropyLoss()
144
+ shift_logits = shift_logits.view(-1, self.language_model.config.vocab_size)
145
+ shift_labels = shift_labels.view(-1)
146
+ # Enable model parallelism
147
+ shift_labels = shift_labels.to(shift_logits.device)
148
+ loss = loss_fct(shift_logits, shift_labels)
149
+
150
+ if not return_dict:
151
+ output = (logits,) + outputs[1:]
152
+ return (loss,) + output if loss is not None else output
153
+
154
+ return CausalLMOutputWithPast(
155
+ loss=loss,
156
+ logits=logits,
157
+ past_key_values=outputs.past_key_values,
158
+ hidden_states=outputs.hidden_states,
159
+ attentions=outputs.attentions,
160
+ )
161
+
162
+ def pixel_shuffle(self, x, scale_factor=0.5):
163
+ n, w, h, c = x.size()
164
+ # N, W, H, C --> N, W, H * scale, C // scale
165
+ x = x.view(n, w, int(h * scale_factor), int(c / scale_factor))
166
+ # N, W, H * scale, C // scale --> N, H * scale, W, C // scale
167
+ x = x.permute(0, 2, 1, 3).contiguous()
168
+ # N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
169
+ x = x.view(n, int(h * scale_factor), int(w * scale_factor),
170
+ int(c / (scale_factor * scale_factor)))
171
+ if self.ps_version == 'v1':
172
+ warnings.warn("In ps_version 'v1', the height and width have not been swapped back, "
173
+ 'which results in a transposed image.')
174
+ else:
175
+ x = x.permute(0, 2, 1, 3).contiguous()
176
+ return x
177
+
178
+ def extract_feature(self, pixel_values):
179
+
180
+ if self.select_layer == -1:
181
+ vit_embeds = self.vision_model(
182
+ pixel_values=pixel_values,
183
+ output_hidden_states=False,
184
+ return_dict=True).last_hidden_state
185
+ else:
186
+ vit_embeds = self.vision_model(
187
+ pixel_values=pixel_values,
188
+ output_hidden_states=True,
189
+ return_dict=True).hidden_states[self.select_layer]
190
+ vit_embeds = vit_embeds[:, 1:, :]
191
+ h = w = int(vit_embeds.shape[1] ** 0.5)
192
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
193
+ vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio)
194
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
195
+ vit_embeds = self.mlp1(vit_embeds)
196
+ return vit_embeds
197
+
198
+ def batch_chat(self, tokenizer, pixel_values, questions, generation_config, num_patches_list=None,
199
+ history=None, return_history=False, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>',
200
+ IMG_CONTEXT_TOKEN='<IMG_CONTEXT>', verbose=False, image_counts=None):
201
+ if history is not None or return_history:
202
+ print('Now multi-turn chat is not supported in batch_chat.')
203
+ raise NotImplementedError
204
+
205
+ if image_counts is not None:
206
+ num_patches_list = image_counts
207
+ print('Warning: `image_counts` is deprecated. Please use `num_patches_list` instead.')
208
+
209
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
210
+ self.img_context_token_id = img_context_token_id
211
+
212
+ if verbose and pixel_values is not None:
213
+ image_bs = pixel_values.shape[0]
214
+ print(f'dynamic ViT batch size: {image_bs}')
215
+
216
+ queries = []
217
+ for idx, num_patches in enumerate(num_patches_list):
218
+ question = questions[idx]
219
+ if pixel_values is not None and '<image>' not in question:
220
+ question = '<image>\n' + question
221
+ template = get_conv_template(self.template)
222
+ template.system_message = self.system_message
223
+ template.append_message(template.roles[0], question)
224
+ template.append_message(template.roles[1], None)
225
+ query = template.get_prompt()
226
+
227
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
228
+ query = query.replace('<image>', image_tokens, 1)
229
+ queries.append(query)
230
+
231
+ tokenizer.padding_side = 'left'
232
+ model_inputs = tokenizer(queries, return_tensors='pt', padding=True)
233
+ input_ids = model_inputs['input_ids'].cuda()
234
+ attention_mask = model_inputs['attention_mask'].cuda()
235
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
236
+ generation_config['eos_token_id'] = eos_token_id
237
+ generation_output = self.generate(
238
+ pixel_values=pixel_values,
239
+ input_ids=input_ids,
240
+ attention_mask=attention_mask,
241
+ **generation_config
242
+ )
243
+ responses = tokenizer.batch_decode(generation_output, skip_special_tokens=True)
244
+ responses = [response.split(template.sep)[0].strip() for response in responses]
245
+ return responses
246
+
247
+ def chat(self, tokenizer, pixel_values, question, generation_config, history=None, return_history=False,
248
+ num_patches_list=None, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>',
249
+ verbose=False):
250
+
251
+ if history is None and pixel_values is not None and '<image>' not in question:
252
+ question = '<image>\n' + question
253
+
254
+ if num_patches_list is None:
255
+ num_patches_list = [pixel_values.shape[0]] if pixel_values is not None else []
256
+ assert pixel_values is None or len(pixel_values) == sum(num_patches_list)
257
+
258
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
259
+ self.img_context_token_id = img_context_token_id
260
+
261
+ template = get_conv_template(self.template)
262
+ template.system_message = self.system_message
263
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
264
+
265
+ history = [] if history is None else history
266
+ for (old_question, old_answer) in history:
267
+ template.append_message(template.roles[0], old_question)
268
+ template.append_message(template.roles[1], old_answer)
269
+ template.append_message(template.roles[0], question)
270
+ template.append_message(template.roles[1], None)
271
+ query = template.get_prompt()
272
+
273
+ if verbose and pixel_values is not None:
274
+ image_bs = pixel_values.shape[0]
275
+ print(f'dynamic ViT batch size: {image_bs}')
276
+
277
+ for num_patches in num_patches_list:
278
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
279
+ query = query.replace('<image>', image_tokens, 1)
280
+
281
+ model_inputs = tokenizer(query, return_tensors='pt')
282
+ input_ids = model_inputs['input_ids'].cuda()
283
+ attention_mask = model_inputs['attention_mask'].cuda()
284
+ generation_config['eos_token_id'] = eos_token_id
285
+ generation_output = self.generate(
286
+ pixel_values=pixel_values,
287
+ input_ids=input_ids,
288
+ attention_mask=attention_mask,
289
+ **generation_config
290
+ )
291
+ response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
292
+ response = response.split(template.sep)[0].strip()
293
+ history.append((question, response))
294
+ if return_history:
295
+ return response, history
296
+ else:
297
+ query_to_print = query.replace(IMG_CONTEXT_TOKEN, '')
298
+ query_to_print = query_to_print.replace(f'{IMG_START_TOKEN}{IMG_END_TOKEN}', '<image>')
299
+ if verbose:
300
+ print(query_to_print, response)
301
+ return response
302
+
303
+ @torch.no_grad()
304
+ def generate(
305
+ self,
306
+ pixel_values: Optional[torch.FloatTensor] = None,
307
+ input_ids: Optional[torch.FloatTensor] = None,
308
+ attention_mask: Optional[torch.LongTensor] = None,
309
+ visual_features: Optional[torch.FloatTensor] = None,
310
+ generation_config: Optional[GenerationConfig] = None,
311
+ output_hidden_states: Optional[bool] = None,
312
+ return_dict: Optional[bool] = None,
313
+ **generate_kwargs,
314
+ ) -> torch.LongTensor:
315
+
316
+ assert self.img_context_token_id is not None
317
+ if pixel_values is not None:
318
+ if visual_features is not None:
319
+ vit_embeds = visual_features
320
+ else:
321
+ vit_embeds = self.extract_feature(pixel_values)
322
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
323
+ B, N, C = input_embeds.shape
324
+ input_embeds = input_embeds.reshape(B * N, C)
325
+
326
+ input_ids = input_ids.reshape(B * N)
327
+ selected = (input_ids == self.img_context_token_id)
328
+ assert selected.sum() != 0
329
+ input_embeds[selected] = vit_embeds.reshape(-1, C).to(input_embeds.device)
330
+
331
+ input_embeds = input_embeds.reshape(B, N, C)
332
+ else:
333
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
334
+
335
+ outputs = self.language_model.generate(
336
+ inputs_embeds=input_embeds,
337
+ attention_mask=attention_mask,
338
+ generation_config=generation_config,
339
+ output_hidden_states=output_hidden_states,
340
+ return_dict=return_dict,
341
+ use_cache=True,
342
+ **generate_kwargs,
343
+ )
344
+
345
+ return outputs
special_tokens_map.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<img>",
4
+ "</img>",
5
+ "<IMG_CONTEXT>",
6
+ "<quad>",
7
+ "</quad>",
8
+ "<ref>",
9
+ "</ref>",
10
+ "<box>",
11
+ "</box>"
12
+ ],
13
+ "bos_token": {
14
+ "content": "<|startoftext|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false
19
+ },
20
+ "eos_token": {
21
+ "content": "<|im_end|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false
26
+ },
27
+ "pad_token": {
28
+ "content": "<unk>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false
33
+ },
34
+ "unk_token": {
35
+ "content": "<unk>",
36
+ "lstrip": false,
37
+ "normalized": false,
38
+ "rstrip": false,
39
+ "single_word": false
40
+ }
41
+ }
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:386c49cf943d71aa110361135338c50e38beeff0a66593480421f37b319e1a39
3
+ size 1033105
tokenizer_config.json ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<unk>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<|startoftext|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "<|endoftext|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "6": {
30
+ "content": "<|im_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": false
36
+ },
37
+ "7": {
38
+ "content": "<|im_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "68": {
46
+ "content": "<img>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "70": {
54
+ "content": "</img>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "64000": {
62
+ "content": "<IMG_CONTEXT>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "64001": {
70
+ "content": "<quad>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "64002": {
78
+ "content": "</quad>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "64003": {
86
+ "content": "<ref>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "64004": {
94
+ "content": "</ref>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "64005": {
102
+ "content": "<box>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "64006": {
110
+ "content": "</box>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ }
117
+ },
118
+ "additional_special_tokens": [
119
+ "<img>",
120
+ "</img>",
121
+ "<IMG_CONTEXT>",
122
+ "<quad>",
123
+ "</quad>",
124
+ "<ref>",
125
+ "</ref>",
126
+ "<box>",
127
+ "</box>"
128
+ ],
129
+ "bos_token": "<|startoftext|>",
130
+ "chat_template": "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
131
+ "clean_up_tokenization_spaces": false,
132
+ "eos_token": "<|im_end|>",
133
+ "legacy": true,
134
+ "model_max_length": 8192,
135
+ "pad_token": "<unk>",
136
+ "sp_model_kwargs": {},
137
+ "spaces_between_special_tokens": false,
138
+ "tokenizer_class": "LlamaTokenizer",
139
+ "trust_remote_code": false,
140
+ "unk_token": "<unk>",
141
+ "use_default_system_prompt": false,
142
+ "use_fast": true
143
+ }